Skip to content

Conversation

Adi-204
Copy link
Member

@Adi-204 Adi-204 commented Sep 2, 2025

Description
Add new component HandleMessage and refactor existing codebase.

Related issue(s)
Fixes #1711

Summary by CodeRabbit

  • New Features

    • Added a language-aware message handler generator with configurable method name, parameters, and optional pre/post execution code for JavaScript, Python, and Dart; now available from the shared components package.
  • Refactor

    • WebSocket client templates updated to use the centralized message handler, replacing local implementations for consistent generation.
  • Tests

    • Added snapshot tests validating rendering across supported languages.

Copy link

changeset-bot bot commented Sep 2, 2025

⚠️ No Changeset found

Latest commit: 3ec0b59

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

Copy link

coderabbitai bot commented Sep 2, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • packages/templates/clients/websocket/test/integration-test/__snapshots__/integration.test.js.snap is excluded by !**/*.snap

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Adds a new language-aware HandleMessage component in generator-components, re-exports it publicly, adds snapshot tests, removes per-template HandleMessage implementations, and updates Dart/JavaScript/Python WebSocket client templates to import and use the shared component with explicit props.

Changes

Cohort / File(s) Summary
New shared component
packages/components/src/components/HandleMessage.js
Adds HandleMessage component that selects per-language methodDocs and methodLogic (python, javascript, dart) and renders MethodGenerator with configurable props (language, methodName, methodParams, preExecutionCode, postExecutionCode).
Public export
packages/components/src/index.js
Re-exports HandleMessage from the components package.
Unit tests
packages/components/test/components/HandleMessage.test.js
Adds snapshot tests rendering HandleMessage for javascript, python, and dart variants.
Templates — ClientClass updates
packages/templates/clients/websocket/dart/components/ClientClass.js
packages/templates/clients/websocket/javascript/components/ClientClass.js
packages/templates/clients/websocket/python/components/ClientClass.js
Replaces local imports with HandleMessage from @asyncapi/generator-components and invokes it with explicit props (language, methodName, methodParams, optional preExecutionCode).
Remove per-template HandleMessage implementations
packages/templates/clients/websocket/dart/components/HandleMessage.js
packages/templates/clients/websocket/javascript/components/HandleMessage.js
packages/templates/clients/websocket/python/components/HandleMessage.js
Deletes the template-local HandleMessage components that previously rendered language-specific code snippets.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Add reusable HandleMessage component in @asyncapi/generator-components (#1711)
Expose HandleMessage via public export in @asyncapi/generator-components (#1711)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Replaced local template imports and usages to consume shared component (e.g. packages/templates/clients/websocket/python/components/ClientClass.js) Template updates and behavior changes to client templates are not required by issue #1711, which only requested adding the reusable component and export.
Deleted per-template HandleMessage implementations (e.g. packages/templates/clients/websocket/javascript/components/HandleMessage.js) Removing template-local components is not explicitly part of #1711; this is a template refactor beyond the stated objective.

Possibly related PRs

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@asyncapi-bot
Copy link
Contributor

What reviewer looks at during PR review

The following are ideal points maintainers look for during review. Reviewing these points yourself beforehand can help streamline the review process and reduce time to merge.

  1. PR Title: Use a concise title that follows our Conventional Commits guidelines and clearly summarizes the change using imperative mood (it means spoken or written as if giving a command or instruction, like "add new helper for listing operations")

    Note - In Generator, prepend feat: or fix: in PR title only when PATCH/MINOR release must be triggered.

  2. PR Description: Clearly explain the issue being solved, summarize the changes made, and mention the related issue.

    Note - In Generator, we use Maintainers Work board to track progress. Ensure the PR Description includes Resolves #<issue-number> or Fixes #<issue-number> this will automatically close the linked issue when the PR is merged and helps automate the maintainers workflow.

  3. Documentation: Update the relevant Generator documentation to accurately reflect the changes introduced in the PR, ensuring users and contributors have up-to-date guidance.

  4. Comments and JSDoc: Write clear and consistent JSDoc comments for functions, including parameter types, return values, and error conditions, so others can easily understand and use the code.

  5. DRY Code: Ensure the code follows the Don't Repeat Yourself principle. Look out for duplicate logic that can be reused.

  6. Test Coverage: Ensure the new code is well-tested with meaningful test cases that pass consistently and cover all relevant edge cases.

  7. Commit History: Contributors should avoid force-pushing as much as possible. It makes it harder to track incremental changes and review the latest updates.

  8. Template Design Principles Alignment: While reviewing template-related changes in the packages/ directory, ensure they align with the Assumptions and Principles. If any principle feels outdated or no longer applicable, start a discussion these principles are meant to evolve with the project.

  9. Reduce Scope When Needed: If an issue or PR feels too large or complex, consider splitting it and creating follow-up issues. Smaller, focused PRs are easier to review and merge.

  10. Bot Comments: As reviewers, check that contributors have appropriately addressed comments or suggestions made by automated bots. If there are bot comments the reviewer disagrees with, react to them or mark them as resolved, so the review history remains clear and accurate.

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: 4

🧹 Nitpick comments (8)
packages/components/src/index.js (1)

6-7: Document the new public surface.
Please add HandleMessage (and MethodGenerator if new) to the package README/CHANGELOG to avoid silent API drift.

packages/templates/clients/websocket/javascript/components/ClientClass.js (1)

22-25: Verify cb is wired at call sites; align semantics with RegisterMessageHandler.
HandleMessage expects (message, cb) while RegisterMessageHandler registers a handler. Ensure the websocket onmessage path passes a dispatcher cb that invokes all registered handlers; otherwise messages will be dropped.

If no cb is provided, consider a safe fallback (log raw message) to mirror Python.

packages/components/test/components/HandleMessage.test.js (2)

13-23: Minor: keep docstring tidy.
Drop the trailing space inside the triple-quoted string to reduce snapshot churn.

-        preExecutionCode='"""Pass the incoming message to all registered message handlers. """'
+        preExecutionCode='"""Pass the incoming message to all registered message handlers."""'

25-35: Add negative test for unsupported language (after adding guard).
Covers error path and improves robustness.

   test('render dart websocket message handler method', () => {
@@
   });
+
+  test('throws on unsupported language', () => {
+    expect(() => render(<HandleMessage language="go" />)).toThrow(/Unsupported language/i);
+  });
packages/templates/clients/websocket/dart/components/ClientClass.js (1)

23-27: Confirm dispatcher cb is provided on message receive; consider null-safe fallback.
_handleMessage expects a non-null cb. Verify Connect/onMessage provides it; otherwise add a guard to log the raw message.

packages/components/src/components/HandleMessage.js (2)

47-58: Expose formatting knobs via props for consistency with MethodGenerator.
Let callers override indent/newLines/customMethodConfig when needed.

     <MethodGenerator
       language={language}
       methodName={methodName}
       methodParams={methodParams}
       methodDocs={methodDocs}
       methodLogic={methodLogic}
       preExecutionCode={preExecutionCode}
       postExecutionCode={postExecutionCode}
-      indent={2}
-      newLines={2}
+      indent={indent}
+      newLines={newLines}
+      customMethodConfig={customMethodConfig}
     />

13-19: Nit: normalize Python indentation for readability.
Two-space indent under if is unconventional; align to 4 spaces for consistency with the else/for block.

   python: {
-    methodLogic: `if len(self.message_handlers) == 0:
-  print("\\033[94mReceived raw message:\\033[0m", message)
-else:
-    for handler in self.message_handlers:
-      handler(message)`
+    methodLogic: `if len(self.message_handlers) == 0:
+    print("\\033[94mReceived raw message:\\033[0m", message)
+else:
+    for handler in self.message_handlers:
+        handler(message)`
   },
packages/templates/clients/websocket/python/components/ClientClass.js (1)

35-40: Trim trailing space in Python docstring.

Minor PEP 257 polish.

Apply:

-        preExecutionCode='"""Pass the incoming message to all registered message handlers. """'
+        preExecutionCode='"""Pass the incoming message to all registered message handlers."""'

Confirm MethodGenerator emits preExecutionCode as the first statement in the method body so it becomes the function’s __doc__ (and that methodDocs isn’t inserted before it).

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e5e13d5 and 7071ac6.

⛔ Files ignored due to path filters (2)
  • packages/components/test/components/__snapshots__/HandleMessage.test.js.snap is excluded by !**/*.snap
  • packages/templates/clients/websocket/test/integration-test/__snapshots__/integration.test.js.snap is excluded by !**/*.snap
📒 Files selected for processing (9)
  • packages/components/src/components/HandleMessage.js (1 hunks)
  • packages/components/src/index.js (1 hunks)
  • packages/components/test/components/HandleMessage.test.js (1 hunks)
  • packages/templates/clients/websocket/dart/components/ClientClass.js (2 hunks)
  • packages/templates/clients/websocket/dart/components/HandleMessage.js (0 hunks)
  • packages/templates/clients/websocket/javascript/components/ClientClass.js (2 hunks)
  • packages/templates/clients/websocket/javascript/components/HandleMessage.js (0 hunks)
  • packages/templates/clients/websocket/python/components/ClientClass.js (2 hunks)
  • packages/templates/clients/websocket/python/components/HandleMessage.js (0 hunks)
💤 Files with no reviewable changes (3)
  • packages/templates/clients/websocket/javascript/components/HandleMessage.js
  • packages/templates/clients/websocket/dart/components/HandleMessage.js
  • packages/templates/clients/websocket/python/components/HandleMessage.js
🧰 Additional context used
🧬 Code graph analysis (5)
packages/components/test/components/HandleMessage.test.js (2)
apps/react-sdk/src/renderer/renderer.ts (1)
  • render (63-77)
packages/components/src/components/HandleMessage.js (1)
  • HandleMessage (41-60)
packages/components/src/components/HandleMessage.js (1)
packages/components/src/components/MethodGenerator.js (1)
  • MethodGenerator (34-82)
packages/templates/clients/websocket/dart/components/ClientClass.js (1)
packages/components/src/components/HandleMessage.js (1)
  • HandleMessage (41-60)
packages/templates/clients/websocket/javascript/components/ClientClass.js (1)
packages/components/src/components/HandleMessage.js (1)
  • HandleMessage (41-60)
packages/templates/clients/websocket/python/components/ClientClass.js (1)
packages/components/src/components/HandleMessage.js (1)
  • HandleMessage (41-60)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Test generator as dependency with Node 18
  • GitHub Check: Acceptance tests for generated templates
  • GitHub Check: Test NodeJS PR - windows-latest
  • GitHub Check: Test NodeJS PR - macos-13
  • GitHub Check: Test NodeJS PR - ubuntu-latest
🔇 Additional comments (5)
packages/components/src/index.js (1)

6-7: LGTM: public re-exports added correctly.

packages/templates/clients/websocket/javascript/components/ClientClass.js (1)

6-6: LGTM: switched to central components import.

packages/components/test/components/HandleMessage.test.js (2)

1-3: LGTM: tests target the public export and renderer.


5-35: Ensure snapshots are committed or switch to inline snapshots.
These tests use toMatchSnapshot; please commit the generated snapshots or convert to inline snapshots to avoid CI failures.

packages/templates/clients/websocket/dart/components/ClientClass.js (1)

6-6: LGTM: centralized imports.

import { SendOperation } from './SendOperation';
import { Send } from './Send';
import { CloseConnection, RegisterMessageHandler } from '@asyncapi/generator-components';
import { CloseConnection, RegisterMessageHandler, HandleMessage } from '@asyncapi/generator-components';
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Switch to shared HandleMessage import looks good—verify export and dependency.

Ensure @asyncapi/generator-components re-exports HandleMessage and that the repo depends on a version including it. Also confirm old template-local HandleMessage.js files are gone to avoid dead code.

Run:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "1) Check HandleMessage export in components index:"
rg -nP 'export\s+\{[^}]*HandleMessage' packages/components/src/index.js || rg -n 'export \* from .*/HandleMessage' packages/components/src/index.js || true

echo -e "\n2) Ensure no leftover template-local HandleMessage.js files:"
fd -a -t f --exclude node_modules 'HandleMessage.js' packages/templates || true

echo -e "\n3) Check dependency declarations for generator-components:"
rg -n '"@asyncapi/generator-components"' package.json packages/**/package.json || true

echo -e "\n4) Verify imports now point to @asyncapi/generator-components:"
rg -nP "from\\s+'@asyncapi/generator-components'.*HandleMessage" packages/templates || true

Length of output: 1045


Add missing @asyncapi/generator-components dependency
The export of HandleMessage is confirmed and no stale template-local files remain, but the templates that import it don’t declare @asyncapi/generator-components. Add it (with a version including HandleMessage) to the relevant package.json (e.g. packages/templates/clients/websocket/python/package.json) so the import resolves.

🤖 Prompt for AI Agents
In packages/templates/clients/websocket/python/components/ClientClass.js around
line 8, the file imports HandleMessage (and other symbols) from
'@asyncapi/generator-components' but the template package does not declare this
dependency; update packages/templates/clients/websocket/python/package.json to
add '@asyncapi/generator-components' with a version range that includes the
release containing HandleMessage (e.g. bump to the minimum semver that
introduced HandleMessage or use a caret range like ^X.Y.Z), then run npm/yarn
install and verify the import resolves and the build/tests for the template
pass.

Copy link

sonarqubecloud bot commented Sep 7, 2025

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.

Introduce new component for HandleMessage in @asyncapi/generator-components
2 participants