Skip to content

Conversation

@transphorm
Copy link
Member

@transphorm transphorm commented Aug 10, 2025

Summary

  • clean up unused config merging and timeout scaffolding
  • add typed SDK event map and emit helper
  • export event types for browser and node builds

Testing

  • yarn workspace @selfxyz/mobile-sdk-alpha nice
  • yarn workspace @selfxyz/common nice (fails: Require statement not part of import statement)
  • yarn workspace @selfxyz/app nice (fails: Workspace '@selfxyz/app' not found)
  • yarn lint
  • yarn build
  • yarn workspace @selfxyz/contracts build (fails: Hardhat config error)
  • yarn types
  • yarn workspace @selfxyz/common test
  • yarn workspace @selfxyz/circuits test (fails: Unsupported signature algorithm: undefined)
  • yarn workspace @selfxyz/mobile-app test
  • yarn workspace @selfxyz/mobile-sdk-alpha test

https://chatgpt.com/codex/tasks/task_b_6898c5c2ebe0832db1332f91ff4f4e14

Summary by CodeRabbit

  • New Features

    • Introduced a strongly-typed event system, ensuring event listeners and emitters receive and send payloads with the correct types.
    • Added an event emission method to the client, allowing external code to trigger events with type-safe payloads.
  • Refactor

    • Updated event-related type definitions for improved type safety and consistency across the SDK.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 10, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review (2)
  • main
  • dev

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

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

Walkthrough

The changes introduce a strongly-typed event system to the mobile SDK alpha package. Event names and payloads are now mapped via a new SDKEventMap interface, ensuring type safety for event listeners and emitters. The SelfClient interface and implementation are updated to use these types, and event emission is now exposed in the client API.

Changes

Cohort / File(s) Change Summary
Export Type Updates
packages/mobile-sdk-alpha/src/browser.ts, packages/mobile-sdk-alpha/src/index.ts
Added SDKEventMap to exported types, extending the set of public types available from the SDK. No logic or control flow changes.
Event Typing and Emission Implementation
packages/mobile-sdk-alpha/src/client.ts
Enhanced event listener (on) and emitter (emit) functions with strong typing based on SDKEventMap. The on method now enforces correct payload types for each event. Introduced a new emit function, exposed it in the returned client, and improved timeout handling in generateProof to emit typed errors. Removed an unused config variable.
Event Type System Redesign
packages/mobile-sdk-alpha/src/types/public.ts
Replaced the union type SDKEvent with a mapped interface SDKEventMap for event names and payloads. Updated the SelfClient interface: the on method is now generic and type-safe, and a new emit method is defined, both using SDKEventMap for payload typing.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Listener
  participant SDK

  Note over Client,SDK: Registering an event listener
  Client->>SDK: on('progress', callback)
  SDK-->>Client: Unsubscribe function

  Note over SDK: Emitting an event
  SDK->>Listener: callback(payload) (typed via SDKEventMap)

  Note over Client,SDK: Emitting an event externally
  Client->>SDK: emit('error', errorPayload)
  SDK->>Listener: callback(errorPayload)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

Typed events now sing in tune,
With payloads matched from sun to moon.
Errors, progress, state—each one
Is safely typed, the work well done.
Emit and listen, clear and bright,
SDK events now feel just right!
🎉

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/review-code-logic-and-optimize-aliases

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

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.

@transphorm
Copy link
Member Author

@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 10, 2025

✅ Actions performed

Full review triggered.

Copy link
Contributor

@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: 1

🔭 Outside diff range comments (1)
packages/mobile-sdk-alpha/src/client.ts (1)

76-94: Timeout emission can fire after success or cancellation; also risk of unhandled rejections

  • The timeout task is never cancelled, so it may emit 'error' even if the proof completes or is cancelled.
  • If clock.sleep rejects on abort in some adapter, the voided promise may trigger an unhandled rejection.

Guard emission and catch rejections; also wire cancelation:

   async function generateProof(
@@
-    const timeoutMs = opts.timeoutMs ?? cfg.timeouts?.proofMs ?? defaultConfig.timeouts.proofMs;
-    void _adapters.clock.sleep(timeoutMs!, opts.signal).then(() => emit('error', new Error('timeout')));
+    const timeoutMs = opts.timeoutMs ?? cfg.timeouts?.proofMs ?? defaultConfig.timeouts.proofMs;
+    let cancelled = false;
+    void _adapters.clock.sleep(timeoutMs, opts.signal)
+      .then(() => {
+        if (!cancelled) emit('error', new Error('timeout'));
+      })
+      .catch(() => {
+        // aborted: ignore
+      });
     return {
       id: 'stub',
       status: 'pending',
       result: async () => ({ ok: false, reason: 'SELF_ERR_PROOF_STUB' }),
-      cancel: () => {},
+      cancel: () => {
+        cancelled = true;
+      },
     };

Optionally, consider using a domain error (e.g., sdkError('SELF_ERR_TIMEOUT', ...)) for consistency.

🧹 Nitpick comments (4)
packages/mobile-sdk-alpha/src/types/public.ts (2)

91-96: SDKEventMap is a solid foundation; consider tightening payload types

Current mapping is clear. Two suggestions:

  • Consider narrowing state: string to a string literal union of valid states to prevent accidental misuse.
  • If you have an SDK-specific error type (e.g., from ./errors), prefer that over the broad Error to carry codes/categories consistently.

129-131: Reassess exposing emit on the public client API

Exposing emit publicly allows external code to spoof internal events (including 'error'). If events are intended as output-only signals, consider:

  • Keeping emit internal (not part of SelfClient) and exposing only on/off/once to consumers, or
  • Documenting that emit is for testing only, or prefixing it with an “internal” marker in docs.
    If you keep it public, adding once and off would round out the emitter API ergonomics.
packages/mobile-sdk-alpha/src/client.ts (2)

49-55: Listener registry works; minor type-safety nit

The implementation is fine. If you want to avoid (cb as any), you can model listeners as a keyed record to preserve per-event payload typing:

type Listener<K extends SDKEvent> = (payload: SDKEventMap[K]) => void;
type Listeners = { [K in SDKEvent]?: Set<Listener<K>> };

const listeners: Listeners = {};

function on<E extends SDKEvent>(event: E, cb: Listener<E>): Unsubscribe {
  const set = (listeners[event] ??= new Set()) as Set<Listener<E>>;
  set.add(cb);
  return () => set.delete(cb);
}

Not mandatory, but it removes casts and improves maintainability.


101-103: Public emit exposure in returned object

Mirrors the interface change. See earlier comment on considering keeping emit internal to avoid consumer-triggered synthetic errors.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f85e298 and ef7162c.

📒 Files selected for processing (4)
  • packages/mobile-sdk-alpha/src/browser.ts (1 hunks)
  • packages/mobile-sdk-alpha/src/client.ts (4 hunks)
  • packages/mobile-sdk-alpha/src/index.ts (1 hunks)
  • packages/mobile-sdk-alpha/src/types/public.ts (2 hunks)
🔇 Additional comments (2)
packages/mobile-sdk-alpha/src/browser.ts (1)

20-22: Type-only re-export of SDKEventMap is correct and tree-shakeable

Exporting via export type { ... } ensures no runtime impact and keeps browser bundles lean. Looks good.

packages/mobile-sdk-alpha/src/index.ts (1)

18-20: Consistent public export of SDKEventMap

Good to see the event map exposed at the package entrypoint as a type-only export. This keeps external consumers aligned with the new typed event system without bundling overhead.

@transphorm transphorm merged commit 2fb33a0 into codex/simplify-and-fix-alias-import-system Aug 10, 2025
9 checks passed
@transphorm transphorm deleted the codex/review-code-logic-and-optimize-aliases branch August 10, 2025 20:35
transphorm added a commit that referenced this pull request Aug 10, 2025
* Simplify alias config

* Restore export sorting overrides

* save migration pattern

* alias last minute updates

* fix tests

* improved import sorting

* Implement typed event emitter (#869)

* Implement typed event emitter

* cr suggestion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants