Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Aug 26, 2025

Description

Make sure we catch all errors from public methods of the Telemetry collector

Fixes: USER-3312

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • Bug Fixes

    • Prevent telemetry errors from surfacing, improving stability and avoiding crashes when telemetry operations fail.
  • Chores

    • Prepare a patch release for @clerk/shared reflecting the telemetry error handling improvement.
  • Tests

    • Add tests to verify telemetry operations no longer throw on bad input and continue functioning after internal errors.

@changeset-bot
Copy link

changeset-bot bot commented Aug 26, 2025

🦋 Changeset detected

Latest commit: bbedda4

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

This PR includes changesets to release 19 packages
Name Type
@clerk/shared Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/chrome-extension Patch
@clerk/clerk-js Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/clerk-expo Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/vue 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

@vercel
Copy link

vercel bot commented Aug 26, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Aug 26, 2025 3:14pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 26, 2025

Walkthrough

Wraps telemetry recording paths in try/catch to prevent exceptions from bubbling, adds tests verifying non-throwing behavior, and adds a changeset entry for a patch release of @clerk/shared.

Changes

Cohort / File(s) Summary
Release metadata
./.changeset/thirty-cars-beg.md
Adds a patch changeset for @clerk/shared noting telemetry errors should not bubble up.
Telemetry collector implementation
packages/shared/src/telemetry/collector.ts
Wraps record() and recordLog() internals in try/catch; logs specific error messages on failure; preserves existing validation/drop behavior while preventing uncaught exceptions.
Telemetry tests (error handling)
packages/shared/src/__tests__/telemetry.test.ts, packages/shared/src/__tests__/telemetry.logs.test.ts
Adds tests ensuring record and recordLog do not throw on non-serializable or circular payloads, assert console error logging, and verify continued operation (fetch called for subsequent valid events). Minor comment removals in existing tests.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App
  participant Collector as TelemetryCollector
  participant Buffer as Buffer/Queue
  participant Logger as Console

  rect rgba(200,235,255,0.25)
  note over App,Collector: record(event)
  App->>Collector: record(event)
  activate Collector
  Collector->>Collector: try { prepare payload, sample decision, buffer, maybe flush }
  alt success
    Collector->>Buffer: buffer(event)
    Collector-->>App: return
  else error
    Collector->>Logger: "[clerk/telemetry] Error recording telemetry event" + Error
    Collector-->>App: return
  end
  deactivate Collector
  end

  rect rgba(225,255,200,0.25)
  note over App,Collector: recordLog(entry)
  App->>Collector: recordLog(entry)
  activate Collector
  Collector->>Collector: try { validate, normalize ts, construct log, buffer, maybe flush }
  alt success
    Collector->>Buffer: buffer(log)
    Collector-->>App: return
  else error
    Collector->>Logger: "[clerk/telemetry] Error recording telemetry log entry" + Error
    Collector-->>App: return
  end
  deactivate Collector
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Prevent app error when recording telemetry data in @clerk/expo (USER-3312)

I nibble at tangled bytes with care,
Unwind the loops that gave a scare,
No crashing thumps, just gentle logs—
I buffer breaths for restful frogs. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch jr.feat/do-not-allow-telemetry-errors-to-bubble-up

🪧 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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@jacekradko jacekradko marked this pull request as ready for review August 26, 2025 15:09
@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 26, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6640

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6640

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6640

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6640

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6640

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6640

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6640

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6640

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6640

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6640

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6640

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6640

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6640

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6640

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6640

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6640

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6640

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6640

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6640

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6640

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6640

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6640

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6640

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6640

commit: bbedda4

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

🧹 Nitpick comments (6)
packages/shared/src/telemetry/collector.ts (6)

179-193: Good: wrap record in try/catch; minor logging refinements recommended

Catching all errors prevents propagation as intended. To reduce noise in consumer consoles and avoid leaking details in production, consider:

  • Logging only in debug mode.
  • Narrowing the caught error to unknown and printing a concise message.
  • Including the event name to aid triage.

Suggested change:

-    } catch (error) {
-      console.error('[clerk/telemetry] Error recording telemetry event', error);
-    }
+    } catch (err: unknown) {
+      if (this.isDebug && typeof console !== 'undefined') {
+        const e = err instanceof Error ? err : new Error(String(err));
+        console.warn('[clerk/telemetry] Error recording telemetry event', {
+          event: event?.event,
+          message: e.message,
+        });
+      }
+    }

203-206: #shouldRecordLog gate is a no-op; align behavior with JSDoc or remove the check

Right now #shouldRecordLog always returns true, so this early return never triggers. Either:

  • Gate logs (e.g., return this.isEnabled && !this.isDebug) if you truly want “logging is enabled and not in debug mode”, or
  • Update the JSDoc to remove that claim and drop the check for clarity.

If you decide to gate, consider:

// outside this hunk (method definition)
#shouldRecordLog(_entry: TelemetryLogEntry): boolean {
  // Always allow when telemetry is enabled; avoid logging during debug runs to keep consoles quiet.
  return this.isEnabled && !this.isDebug;
}

219-228: Validation now over-filters due to timestamp check; remove the timestamp predicate

With the fallback to new Date() (previous comment), the timestamp is always valid. Keep the validation focused on level and message to avoid silently dropping logs.

-      if (!levelIsValid || !messageIsValid || normalizedTimestamp === null) {
+      if (!levelIsValid || !messageIsValid) {
         if (this.isDebug && typeof console !== 'undefined') {
           console.warn('[clerk/telemetry] Dropping invalid telemetry log entry', {
             levelIsValid,
             messageIsValid,
-            timestampIsValid: normalizedTimestamp !== null,
+            timestampIsValid: true,
           });
         }
         return;
       }

233-241: Consider including a minimal correlation identifier and avoid leaking context keys

Two small improvements:

  • If you have an instance or request correlation ID available (e.g., iid), consider including it to aid debugging.
  • #sanitizeContext is good, but you might want to prune obviously sensitive keys (e.g., password, token) if they slip through. Even best-effort redaction helps.

No blocker; just considerations for operating telemetry at scale.

Happy to add a small redaction helper with a denylist and unit tests.


246-248: Narrow catch variable and gate logging behind debug to avoid noisy consoles

Same rationale as for record. Keep errors silent in production but visible when CLERK_TELEMETRY_DEBUG is on.

-    } catch (error) {
-      console.error('[clerk/telemetry] Error recording telemetry log entry', error);
-    }
+    } catch (err: unknown) {
+      if (this.isDebug && typeof console !== 'undefined') {
+        const e = err instanceof Error ? err : new Error(String(err));
+        console.warn('[clerk/telemetry] Error recording telemetry log entry', {
+          level: entry?.level,
+          message: e.message,
+        });
+      }
+    }

178-194: Add unit tests to lock in “errors never bubble up” behavior

To prevent regressions for USER-3312:

  • record: when #preparePayload or #scheduleFlush throws, no exception escapes and nothing is enqueued.
  • recordLog: invalid level, empty message, missing/invalid timestamp → entry is handled according to the new rules (default timestamp), and no exception escapes.

I can draft tests with stubs for #preparePayload, #scheduleFlush, and fetch.

Do you want me to open a follow-up PR with Jest tests covering these cases?

Also applies to: 201-248

📜 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 f49ec31 and bb4c3ee.

📒 Files selected for processing (2)
  • .changeset/thirty-cars-beg.md (1 hunks)
  • packages/shared/src/telemetry/collector.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/thirty-cars-beg.md
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/shared/src/telemetry/collector.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/telemetry/collector.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/telemetry/collector.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/telemetry/collector.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/shared/src/telemetry/collector.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/shared/src/telemetry/collector.ts
🧬 Code graph analysis (1)
packages/shared/src/telemetry/collector.ts (3)
packages/clerk-js/src/core/modules/debug/types.ts (1)
  • VALID_LOG_LEVELS (9-9)
packages/clerk-js/src/core/clerk.ts (2)
  • sdkMetadata (271-273)
  • sdkMetadata (275-277)
packages/react/src/isomorphicClerk.ts (1)
  • sdkMetadata (264-266)
🔇 Additional comments (3)
.changeset/thirty-cars-beg.md (1)

1-6: Changeset looks correct for a patch to @clerk/shared

The package name and bump type are valid; message is concise and matches the PR intent.

packages/shared/src/telemetry/collector.ts (2)

207-209: Telemetry collector’s log levels are correctly aligned with its own types

The TelemetryLogEntry interface (packages/types/src/telemetry.ts:49–51) explicitly includes 'trace', and the collector’s VALID_LOG_LEVELS set in packages/shared/src/telemetry/collector.ts mirrors that union (['error','warn','info','debug','trace']). The DebugLogLevel type in clerk-js is a separate, debug-specific enum (['error','warn','info','debug']) and is not the source of truth for telemetry log levels. No changes are necessary here; the original comment conflates two distinct domains.

Likely an incorrect or invalid review comment.


207-217: Suggestion to ignore – timestamp is always a required number

The TelemetryLogEntry interface (packages/types/src/telemetry.ts:56) declares

readonly timestamp: number;

so:

  • A missing timestamp cannot occur under the declared type.
  • The existing guard correctly handles the only valid runtime form (a number).
  • Accepting Date instances or defaulting to new Date() would be out of spec and unnecessary.

Please disregard the proposed changes around timestamp normalization.

Likely an incorrect or invalid review comment.

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

🧹 Nitpick comments (4)
packages/shared/src/__tests__/telemetry.logs.test.ts (3)

141-169: Stabilize network behavior in tests by mocking fetch and assert a single call

These tests currently rely on the real fetch polyfill. For deterministic, fast, and offline-safe tests, set a resolved mock and assert the exact call count.

Apply this diff:

   test('recordLog() method handles circular references in context gracefully', () => {
     const collector = new TelemetryCollector({ publishableKey: TEST_PK });
 
+    // Avoid real network and make the test deterministic
+    fetchSpy.mockResolvedValue({ ok: true } as any);
+
     const circularContext = (() => {
       const obj: any = { test: 'value' };
       obj.self = obj;
       return obj;
     })();
@@
 
     jest.runAllTimers();
-    expect(fetchSpy).toHaveBeenCalled();
+    expect(fetchSpy).toHaveBeenCalledTimes(1);
 
     const [url, init] = fetchSpy.mock.calls[0];
     expect(String(url)).toMatch('/v1/logs');

171-204: Make this test cover a truly “non-circular but non-serializable” context

As written, this case also includes a circular reference, overlapping with the previous test. Swap the circular part with a BigInt (JSON.stringify throws on BigInt), so we uniquely cover a different non-serializable shape.

Apply this diff:

   test('recordLog() method handles non-serializable context gracefully', () => {
     const collector = new TelemetryCollector({ publishableKey: TEST_PK });
 
-    const nonSerializableContext = {
-      function: () => 'test',
-      undefined: undefined,
-      symbol: Symbol('test'),
-      circular: (() => {
-        const obj: any = { test: 'value' };
-        obj.self = obj;
-        return obj;
-      })(),
-    };
+    const nonSerializableContext = {
+      function: () => 'test',
+      undefined: undefined,
+      symbol: Symbol('test'),
+      // BigInt cannot be serialized to JSON and will throw
+      bigint: 10n,
+    } as const;
 
     expect(() => {
       collector.recordLog({
         level: 'info',
         message: 'test message',
         timestamp: Date.now(),
         context: nonSerializableContext,
       });
     }).not.toThrow();
 
     jest.runAllTimers();
-    expect(fetchSpy).toHaveBeenCalled();
+    expect(fetchSpy).toHaveBeenCalledTimes(1);

205-221: Optionally verify debug warnings for invalid log entries

When debug is enabled, invalid entries should emit a console.warn. Consider adding a small companion test to assert this behavior so we don’t regress the developer-facing diagnostics.

Example (new test block):

test('logs a warning in debug mode for invalid timestamp', () => {
  const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
  const collector = new TelemetryCollector({ publishableKey: TEST_PK, debug: true });

  collector.recordLog({
    level: 'info',
    message: 'test message',
    // invalid timestamp
    timestamp: Number.NaN,
  });

  jest.runAllTimers();
  expect(consoleWarnSpy).toHaveBeenCalledWith(
    '[clerk/telemetry] Dropping invalid telemetry log entry',
    expect.objectContaining({
      levelIsValid: true,
      messageIsValid: true,
      timestampIsValid: false,
    }),
  );

  consoleWarnSpy.mockRestore();
});
packages/shared/src/__tests__/telemetry.test.ts (1)

422-452: Make the “continues operation” test deterministic and assert payload integrity

  • Mock fetch to avoid real network and to capture the posted body.
  • Strengthen the assertion to ensure only the healthy event is sent after the failure.

Apply this diff:

   test('record() method handles errors gracefully and continues operation', () => {
     const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
 
     const collector = new TelemetryCollector({
       publishableKey: TEST_PK,
     });
 
+    // Capture the posted event batches and avoid real network
+    const postedBodies: any[] = [];
+    fetchSpy.mockImplementation((_, options: RequestInit) => {
+      try {
+        postedBodies.push(JSON.parse(String(options.body)));
+      } catch {
+        // ignore parse errors in test harness
+      }
+      return Promise.resolve({ ok: true } as any);
+    });
+
     const problematicPayload = (() => {
       const obj: any = { test: 'value' };
       obj.self = obj;
       return obj;
     })();
@@
     expect(() => {
       collector.record({ event: 'TEST_EVENT', payload: { normal: 'data' } });
     }).not.toThrow();
 
     jest.runAllTimers();
-    expect(fetchSpy).toHaveBeenCalled();
+    expect(fetchSpy).toHaveBeenCalledTimes(1);
+    expect(postedBodies[0]).toEqual(
+      expect.objectContaining({
+        events: [
+          expect.objectContaining({
+            event: 'TEST_EVENT',
+            payload: { normal: 'data' },
+          }),
+        ],
+      }),
+    );
 
     consoleErrorSpy.mockRestore();
   });
📜 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 bb4c3ee and bbedda4.

📒 Files selected for processing (2)
  • packages/shared/src/__tests__/telemetry.logs.test.ts (1 hunks)
  • packages/shared/src/__tests__/telemetry.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/telemetry.logs.test.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/telemetry.logs.test.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/telemetry.logs.test.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/telemetry.logs.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/telemetry.logs.test.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/telemetry.logs.test.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/telemetry.logs.test.ts
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/telemetry.logs.test.ts
🧬 Code graph analysis (2)
packages/shared/src/__tests__/telemetry.test.ts (1)
packages/shared/src/telemetry/collector.ts (1)
  • TelemetryCollector (102-450)
packages/shared/src/__tests__/telemetry.logs.test.ts (2)
packages/shared/src/telemetry/collector.ts (1)
  • TelemetryCollector (102-450)
packages/types/src/telemetry.ts (1)
  • TelemetryCollector (60-65)
⏰ 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). (12)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Unit Tests (22, **)
🔇 Additional comments (1)
packages/shared/src/__tests__/telemetry.test.ts (1)

396-421: Good coverage to ensure exceptions don’t escape record()

Asserting a precise console.error signature with an Error instance directly validates the new try/catch path. Looks good.

@brkalow brkalow merged commit 05b6d65 into main Aug 26, 2025
63 of 64 checks passed
@brkalow brkalow deleted the jr.feat/do-not-allow-telemetry-errors-to-bubble-up branch August 26, 2025 16:51
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.

4 participants