Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Node SDK #694

Merged
merged 5 commits into from
Oct 28, 2024
Merged

Update Node SDK #694

merged 5 commits into from
Oct 28, 2024

Conversation

rygine
Copy link
Collaborator

@rygine rygine commented Oct 28, 2024

Summary

  • Allowed for undefined content type and content in messages
  • Filtered out messages without content when calling Conversation.messages
  • Added generic typing for message content to DecodedMessage class and Conversations.findMessageById
  • Replaced temporary group updated codec with official content type

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced message handling capabilities, including support for undefined as a valid content type.
    • Filtering mechanism added to exclude messages without content in conversations.
  • Improvements

    • Updated message classes and methods for better type safety and error handling.
    • Introduced generic typing for message content in key methods.
  • Chores

    • Added a new dependency to improve content type handling.
    • Updated external dependencies for improved module resolution.

@rygine rygine requested a review from a team as a code owner October 28, 2024 21:00
Copy link

changeset-bot bot commented Oct 28, 2024

🦋 Changeset detected

Latest commit: 87457d6

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@xmtp/node-sdk Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

coderabbitai bot commented Oct 28, 2024

Walkthrough

The changes enhance the message handling capabilities of the @xmtp/node-sdk. Key updates include allowing undefined as a valid content type, implementing a filtering mechanism for messages in the Conversation.messages method, and introducing generic typing for the DecodedMessage class and Conversations.findMessageById method. Additionally, the codec for group updates has been replaced with a new dependency, and the Rollup configuration has been updated to reflect these changes. Overall, these modifications aim to improve type safety, error handling, and the overall robustness of the messaging features.

Changes

File Path Change Summary
.changeset/chatty-snails-roll.md Introduced enhancements to message handling, allowing undefined content, filtering messages without content, and updating typing for DecodedMessage and findMessageById.
sdks/node-sdk/package.json Added dependency @xmtp/content-type-group-updated with version ^1.0.0.
sdks/node-sdk/rollup.config.js Updated external dependencies: replaced @xmtp/content-type-text with @xmtp/content-type-group-updated and added @xmtp/content-type-text back.
sdks/node-sdk/src/Client.ts Modified imports for codecs, updated create method to use new codec, and enhanced error handling in decodeContent method.
sdks/node-sdk/src/Conversation.ts Updated messages method to filter out messages without content.
sdks/node-sdk/src/Conversations.ts Changed getMessageById method to include a generic type parameter.
sdks/node-sdk/src/DecodedMessage.ts Introduced generic type parameter for content, updated contentType to allow undefined, and enhanced error handling.
sdks/node-sdk/src/codecs/GroupUpdatedCodec.ts Removed the GroupUpdatedCodec class and ContentTypeGroupUpdated constant.
sdks/node-sdk/src/index.ts Removed exports for ContentTypeGroupUpdated and GroupUpdatedCodec.

Poem

In the meadow where messages play,
A new codec hops in, bright as day.
With types so clear, and content so fine,
Our messages dance, they truly shine!
Undefined now has a place to be,
In this chatty world, so wild and free! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@rygine rygine force-pushed the rygine/node-sdk-updates branch from 4edc845 to 6c1ae40 Compare October 28, 2024 21:00
Copy link

cloudflare-workers-and-pages bot commented Oct 28, 2024

Deploying xmtp-js-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 87457d6
Status: ✅  Deploy successful!
Preview URL: https://8e2cec21.xmtp-js.pages.dev
Branch Preview URL: https://rygine-node-sdk-updates.xmtp-js.pages.dev

View logs

@rygine rygine force-pushed the rygine/node-sdk-updates branch from 6c1ae40 to f3d57da Compare October 28, 2024 21:03
@rygine rygine requested a review from a team as a code owner October 28, 2024 21:03
@rygine rygine merged commit b7d535d into main Oct 28, 2024
20 checks passed
@rygine rygine deleted the rygine/node-sdk-updates branch October 28, 2024 21:07
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (4)
.changeset/chatty-snails-roll.md (1)

7-7: Minor grammar improvement suggested.

Consider adding the article "the" before "DecodedMessage" for better readability.

-Added generic typing for message content to `DecodedMessage` class and `Conversations.findMessageById`
+Added generic typing for message content to the `DecodedMessage` class and `Conversations.findMessageById`
🧰 Tools
🪛 LanguageTool

[uncategorized] ~7-~7: You might be missing the article “the” here.
Context: ...d generic typing for message content to DecodedMessage class and `Conversations...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

sdks/node-sdk/src/DecodedMessage.ts (1)

13-13: LGTM! Consider adding JSDoc for type parameter.

The addition of generic typing improves type safety while maintaining backward compatibility with the any default.

Add TypeScript documentation for the type parameter:

+/**
+ * @template T The type of the message content
+ */
export class DecodedMessage<T = any> {
sdks/node-sdk/src/Conversations.ts (1)

Line range hint 82-94: Consider adding generic type support to streamAllMessages

For consistency with the updated getMessageById<T> method, consider adding generic type support to the streamAllMessages method as well.

- async streamAllMessages(callback?: StreamCallback<DecodedMessage>) {
+ async streamAllMessages<T = any>(callback?: StreamCallback<DecodedMessage<T>>) {
    await this.sync();
    const asyncStream = new AsyncStream<DecodedMessage>();
    const stream = this.#conversations.streamAllMessages((err, message) => {
-     const decodedMessage = new DecodedMessage(this.#client, message);
+     const decodedMessage = new DecodedMessage<T>(this.#client, message);
      asyncStream.callback(err, decodedMessage);
      callback?.(err, decodedMessage);
    });
    asyncStream.stopCallback = stream.end.bind(stream);
    return asyncStream;
  }
sdks/node-sdk/src/Client.ts (1)

Line range hint 208-213: Enhance error message for group membership validation.

While the validation is good, the error message could be more descriptive to help with debugging.

Consider this improvement:

   if (
     contentType.sameAs(ContentTypeGroupUpdated) &&
     message.kind !== NapiGroupMessageKind.MembershipChange
   ) {
-    throw new Error("Error decoding group membership change");
+    throw new Error(`Invalid message kind for group update: expected ${NapiGroupMessageKind.MembershipChange}, got ${message.kind}`);
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 850f061 and 87457d6.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (9)
  • .changeset/chatty-snails-roll.md (1 hunks)
  • sdks/node-sdk/package.json (1 hunks)
  • sdks/node-sdk/rollup.config.js (1 hunks)
  • sdks/node-sdk/src/Client.ts (1 hunks)
  • sdks/node-sdk/src/Conversation.ts (1 hunks)
  • sdks/node-sdk/src/Conversations.ts (1 hunks)
  • sdks/node-sdk/src/DecodedMessage.ts (2 hunks)
  • sdks/node-sdk/src/codecs/GroupUpdatedCodec.ts (0 hunks)
  • sdks/node-sdk/src/index.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • sdks/node-sdk/src/codecs/GroupUpdatedCodec.ts
  • sdks/node-sdk/src/index.ts
🧰 Additional context used
🪛 LanguageTool
.changeset/chatty-snails-roll.md

[uncategorized] ~7-~7: You might be missing the article “the” here.
Context: ...d generic typing for message content to DecodedMessage class and `Conversations...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

🔇 Additional comments (10)
.changeset/chatty-snails-roll.md (1)

1-3: LGTM: Appropriate version bump.

The patch version bump is correct as these changes are backwards-compatible improvements and bug fixes.

sdks/node-sdk/rollup.config.js (1)

11-11: LGTM! External dependencies properly configured.

The addition of @xmtp/content-type-group-updated and @xmtp/content-type-text as external dependencies aligns with the SDK's architectural changes, ensuring proper dependency handling during bundling.

Let's verify these dependencies are properly declared in package.json:

Also applies to: 13-13

✅ Verification successful

Dependencies are correctly declared in package.json

The verification confirms that both @xmtp/content-type-group-updated and @xmtp/content-type-text are properly declared in the package.json dependencies with appropriate version constraints:

  • @xmtp/content-type-group-updated: "^1.0.0"
  • @xmtp/content-type-text: "^1.0.0"

This aligns perfectly with their external configuration in rollup.config.js.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify dependencies are properly declared in package.json
# Expected: Both dependencies should be listed in package.json

# Test: Check package.json for the dependencies
jq '.dependencies | select(."@xmtp/content-type-group-updated" != null and ."@xmtp/content-type-text" != null)' sdks/node-sdk/package.json

Length of output: 339

sdks/node-sdk/src/DecodedMessage.ts (2)

15-16: LGTM! Type changes align with PR objectives.

The property type changes correctly implement:

  1. Generic typing for content
  2. Optional content type support

59-68: Verify error handling and add documentation for undefined cases.

While the implementation correctly handles undefined content types, consider:

  1. Adding type guards around decodeContent call
  2. Documenting the undefined behavior in class/method JSDoc
  3. Consider logging when content type is undefined for debugging

Let's verify the error handling in the codebase:

✅ Verification successful

Based on the shell script results, I can now provide a final response as we have sufficient information about the error handling and content type handling in the codebase:

Error handling for undefined content type is properly implemented

The current implementation is correct and follows the established patterns in the codebase:

  1. The decodeContent method in Client.ts already has proper error handling:

    • Throws an error when no codec is found for the content type
    • Has specific error handling for group membership changes
    • Uses type assertions appropriately with ESLint comments
  2. The undefined case is intentionally handled as part of the API design:

    • Content type is optional by design (type can be undefined)
    • The conditional assignment pattern is consistent with the codebase
    • Silent undefined for content is appropriate as it represents an optional field

No changes are needed as the current implementation aligns with the codebase's error handling patterns and type safety measures.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if undefined content types are documented and handled consistently
rg -A 2 "undefined.*content.*type" --type ts
# Check for existing error handling patterns
rg "decodeContent.*error" --type ts

Length of output: 84


Script:

#!/bin/bash
# Let's check the implementation of decodeContent and its error handling
ast-grep --pattern 'decodeContent($$$) { $$$ }'

# Check for any error handling patterns in the class
rg -B 2 -A 4 "throw.*Error" sdks/node-sdk/src/DecodedMessage.ts

# Look for documentation about content type handling
rg -B 2 "contentType" sdks/node-sdk/src/DecodedMessage.ts

# Check interface or type definitions related to message content
fd "\.d\.ts$" --exec rg -l "content.*type"

Length of output: 572


Script:

#!/bin/bash
# Let's check the Client class implementation for decodeContent
ast-grep --pattern 'class Client {
  $$$
  decodeContent($$$) {
    $$$
  }
  $$$
}'

# Check for any type definitions or interfaces for the message parameter
rg -B 2 "interface.*Message" --type ts
rg -B 2 "type.*Message" --type ts

# Look for any existing documentation about content handling
rg -B 2 "content:" --type ts sdks/node-sdk/src/

Length of output: 19679

sdks/node-sdk/package.json (1)

51-51: LGTM! Verify compatibility with existing content type packages.

The addition of @xmtp/content-type-group-updated aligns with the PR objective of replacing the temporary group updated codec with the official content type. The version constraint and scoping are consistent with other content type dependencies.

Let's verify the compatibility of content type packages:

✅ Verification successful

LGTM! Content type package versions are compatible

The version analysis shows:

  • @xmtp/content-type-group-updated@^1.0.0 is consistently used in both node-sdk and browser-sdk
  • All content type packages use compatible semver ranges (^1.0.x)
  • The primitives package shows minor variations (^1.0.1 and ^1.0.2) which are backward compatible
  • No conflicting version requirements were found
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential version conflicts or inconsistencies between content type packages

# Test: List all @xmtp/content-type-* dependencies and their versions across the monorepo
echo "Checking content type package versions across the monorepo:"
rg -A 1 '"@xmtp/content-type-[^"]+": "[^"]+"' --type json

Length of output: 2332

sdks/node-sdk/src/Conversations.ts (1)

30-37: LGTM! Generic type parameter enhances type safety

The addition of the generic type parameter <T = any> improves type safety while maintaining backward compatibility through the default type. This change aligns well with the PR objectives and the updates to the DecodedMessage class.

sdks/node-sdk/src/Conversation.ts (1)

192-198: Implementation looks good, but verify impact on consumers.

The changes align well with the PR objectives by filtering out messages with undefined content. However, there are a few considerations:

  1. Consider filtering before mapping to DecodedMessage for better performance
  2. The strict undefined check might want to include null values

Consider this performance optimization:

  messages(options?: NapiListMessagesOptions): DecodedMessage[] {
    return (
      this.#group
        .findMessages(options)
-       .map((message) => new DecodedMessage(this.#client, message))
-       // filter out messages without content
-       .filter((message) => message.content !== undefined)
+       .filter((message) => {
+         const decoded = new DecodedMessage(this.#client, message);
+         return decoded.content !== undefined;
+       })
    );
  }

Let's verify the impact on existing consumers:

✅ Verification successful

Based on the search results, I can see extensive usage of the messages() method across the codebase, particularly in tests. The key observations are:

  1. All tests expect and handle messages with undefined content correctly
  2. The filtering is already part of expected behavior in tests
  3. The performance concern about creating DecodedMessage instances before filtering is not critical since:
    • Tests show small message sets
    • The operation is not in a tight loop
    • The mapping provides type safety benefits

The review comment's concerns have been addressed by the codebase evidence

The implementation is correct and aligns with existing usage patterns. The filtering of undefined content messages is an expected behavior as demonstrated by numerous test cases. The performance suggestion is not necessary given the typical usage patterns shown in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct usage of the messages method to identify potential impacts
rg -l "\.messages\(" | xargs rg -B 5 -A 5 "\.messages\("

Length of output: 53138

sdks/node-sdk/src/Client.ts (3)

Line range hint 1-270: Overall implementation looks solid.

The changes successfully implement the intended updates:

  • Migration to official group update content type
  • Improved error handling for group messages
  • Proper type safety checks

The code is well-structured and maintains good practices.


Line range hint 142-142: Consider documenting codec order significance.

The addition of GroupUpdatedCodec before other codecs might affect message handling priority. Consider documenting if the order of codecs is significant for message processing.

#!/bin/bash
# Check if codec order is mentioned in documentation
rg -i "codec.*order|priority" docs/

3-6: Verify dependency on @xmtp/content-type-group-updated package.

The change from local codec to an external package looks good, but let's ensure the dependency is properly added.

✅ Verification successful

Dependency verification successful

The @xmtp/content-type-group-updated package is properly listed in the dependencies section of package.json with version ^1.0.0. The import change is valid and properly supported.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the package is listed in package.json
jq '.dependencies["@xmtp/content-type-group-updated"]' sdks/node-sdk/package.json

Length of output: 177


Script:

#!/bin/bash
# Check package.json content
cat sdks/node-sdk/package.json

Length of output: 2258

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants