Skip to content

feat(clerk-js,themes,shared): Add theme-usage telemetry #6529

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

alexcarpenter
Copy link
Member

@alexcarpenter alexcarpenter commented Aug 12, 2025

Description

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

  • New Features

    • No user-facing changes.
  • Chores

    • Telemetry now records the configured theme (when telemetry is enabled); no personal data collected.
    • Theme definitions and theme-creation parameters include optional names to improve telemetry and debugging.
  • Tests

    • Added unit tests validating theme-usage telemetry across various theme configurations and input shapes.

Copy link

changeset-bot bot commented Aug 12, 2025

⚠️ No Changeset found

Latest commit: e11a15a

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

vercel bot commented Aug 12, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Preview Comment Aug 13, 2025 8:22pm


if (typeof theme === 'object' && theme !== null) {
// Check for explicit theme name
if ('__themeName' in theme && typeof theme.__themeName === 'string') {
Copy link
Member

Choose a reason for hiding this comment

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

is this an ai hallucination?

Copy link
Member Author

Choose a reason for hiding this comment

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

👀 wdym? From my testing this is working
Screenshot 2025-08-12 at 2 16 22 PM

Copy link
Member

Choose a reason for hiding this comment

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

sorry, I wasn't understanding why we needed __themeName, but I think I get it now! I thought we supplied the shadcn theme via appearance.theme = 'shadcn', so I was confused why we needed __themeName.

Copy link

pkg-pr-new bot commented Aug 13, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: e11a15a

Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

📝 Walkthrough

Walkthrough

Adds theme-usage telemetry: introduces eventThemeUsage and unit tests in shared telemetry, and re-exports it. Emits the telemetry event from Clerk.load (packages/clerk-js) when telemetry is enabled and appearance is provided, and from the React Clerk context effect when options.appearance changes. Extends theme creation params with an optional name and adds name properties to built-in themes (dark, neobrutalism, shadcn, shadesOfPurple, simple). Adjusts a bundle size threshold. No other public function signatures were changed.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 065197a and e11a15a.

📒 Files selected for processing (1)
  • packages/clerk-js/bundlewatch.config.json (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{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/clerk-js/bundlewatch.config.json
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/bundlewatch.config.json
⏰ 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). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/clerk-js/bundlewatch.config.json (1)

3-3: Telemetry imports validated — bump justified

  • The ~0.1 KB size increase aligns exactly with adding two calls to eventThemeUsage in
    • packages/clerk-js/src/core/clerk.ts
    • packages/react/src/contexts/ClerkContextProvider.tsx
  • eventThemeUsage and its helper analyzeThemeUsage live entirely in one file and only import types from @clerk/types at compile time—no heavy runtime dependencies.
  • The telemetry module does not pull in any large theme or shared utilities beyond its own minimal logic.

Given the minimal, tree-shakeable footprint of the new telemetry code, the threshold bump is acceptable.


🪧 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.

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

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.

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

🔭 Outside diff range comments (1)
packages/themes/src/createTheme.ts (1)

20-28: Avoid leaking __themeName and ensure excess-property safety with satisfies

Two issues:

  • Adding __themeName directly in the returned object can (a) surface an internal field to consumers and (b) trigger excess property checks depending on how BaseTheme is defined.
  • Prefer making the internal field non-enumerable and using satisfies to validate shape without widening.

Refactor as below.

 export const experimental_createTheme = (appearance: Appearance<CreateClerkThemeParams>): BaseTheme => {
-  // Placeholder method that might hande more transformations in the future
-  return {
-    ...appearance,
-    __type: 'prebuilt_appearance',
-    // Include the name in the theme object for telemetry
-    ...(appearance.name && { __themeName: appearance.name }),
-  };
+  // Placeholder method that might handle more transformations in the future
+  const base = {
+    ...appearance,
+    __type: 'prebuilt_appearance',
+  } satisfies BaseTheme;
+
+  // Add internal-only metadata for telemetry without exposing it via enumeration
+  if (appearance.name) {
+    Object.defineProperty(base as object, '__themeName', {
+      value: appearance.name,
+      enumerable: false,
+      configurable: false,
+      writable: false,
+    });
+  }
+
+  return base;
 };
🧹 Nitpick comments (6)
packages/themes/src/createTheme.ts (2)

8-12: Make the theme name param immutable

Mark name as readonly to align with the repo’s immutability guidance and signal intent.

   /**
    * Optional name for the theme, used for telemetry and debugging.
    * @example 'shadcn', 'neobrutalism', 'custom-dark'
    */
-  name?: string;
+  readonly name?: string;

21-21: Typo: “hande” → “handle”

-  // Placeholder method that might hande more transformations in the future
+  // Placeholder method that might handle more transformations in the future
packages/shared/src/telemetry/events/theme-usage.ts (1)

35-63: Optional: Avoid sending undefined payload fields

Returning { themeName: undefined } increases payload size without information. Consider omitting the field entirely when not present.

-  return { themeName };
+  return themeName ? { themeName } : {};
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts (3)

15-19: Make assertions resilient to future event fields using objectContaining (or a helper)

Asserting deep equality on the entire event object is brittle; adding non-breaking fields (e.g., timestamp, sdkVersion) will cause test failures. Prefer objectContaining, and optionally DRY with a small helper.

Apply this diff to introduce a helper and replace the assertions:

 import { eventThemeUsage } from '../theme-usage';
 
+type ThemeUsageResult = ReturnType<typeof eventThemeUsage>;
+const expectThemeUsageEvent = (result: ThemeUsageResult, payload: Record<string, unknown>) => {
+  expect(result).toEqual(
+    expect.objectContaining({
+      event: 'THEME_USAGE',
+      eventSamplingRate: 0.1,
+      payload,
+    }),
+  );
+};
+
 describe('eventThemeUsage', () => {
   it('should create telemetry event with shadcn theme name', () => {
@@
-    expect(result).toEqual({
-      event: 'THEME_USAGE',
-      eventSamplingRate: 0.1,
-      payload: { themeName: 'shadcn' },
-    });
+    expectThemeUsageEvent(result, { themeName: 'shadcn' });
   });
@@
-    expect(result).toEqual({
-      event: 'THEME_USAGE',
-      eventSamplingRate: 0.1,
-      payload: { themeName: 'clerk' },
-    });
+    expectThemeUsageEvent(result, { themeName: 'clerk' });
   });
@@
-    expect(result).toEqual({
-      event: 'THEME_USAGE',
-      eventSamplingRate: 0.1,
-      payload: { themeName: 'clerk' },
-    });
+    expectThemeUsageEvent(result, { themeName: 'clerk' });
   });
@@
-    expect(result).toEqual({
-      event: 'THEME_USAGE',
-      eventSamplingRate: 0.1,
-      payload: { themeName: undefined },
-    });
+    expectThemeUsageEvent(result, { themeName: undefined });
   });
@@
-    expect(result).toEqual({
-      event: 'THEME_USAGE',
-      eventSamplingRate: 0.1,
-      payload: { themeName: 'clerk' },
-    });
+    expectThemeUsageEvent(result, { themeName: 'clerk' });
   });
@@
-    expect(result).toEqual({
-      event: 'THEME_USAGE',
-      eventSamplingRate: 0.1,
-      payload: { themeName: 'shadcn' },
-    });
+    expectThemeUsageEvent(result, { themeName: 'shadcn' });
   });
@@
-    expect(result).toEqual({
-      event: 'THEME_USAGE',
-      eventSamplingRate: 0.1,
-      payload: {},
-    });
+    expectThemeUsageEvent(result, {});
   });
@@
-    expect(result).toEqual({
-      event: 'THEME_USAGE',
-      eventSamplingRate: 0.1,
-      payload: {},
-    });
+    expectThemeUsageEvent(result, {});
   });

Also applies to: 29-33, 49-53, 66-70, 85-88, 101-105, 111-115, 121-125


23-26: Avoid explicit any in tests; safely cast via Parameters[0]

This keeps tests aligned with the “no any” guideline while still exercising runtime-only shapes.

   it('should handle string themes', () => {
-    const appearance = {
-      theme: 'clerk' as any, // String themes are valid at runtime
-    };
+    // String themes are valid at runtime
+    const appearance = {
+      theme: 'clerk',
+    } as unknown as Parameters<typeof eventThemeUsage>[0];
@@
   it('should handle array of themes', () => {
-    const appearance = {
-      theme: [
-        'clerk' as any, // String themes are valid at runtime
-        {
-          __type: 'prebuilt_appearance' as const,
-          __themeName: 'shadcn',
-        },
-      ] as any,
-    };
+    // String themes are valid at runtime
+    const appearance = {
+      theme: [
+        'clerk',
+        {
+          __type: 'prebuilt_appearance' as const,
+          __themeName: 'shadcn',
+        },
+      ],
+    } as unknown as Parameters<typeof eventThemeUsage>[0];
@@
   it('should prioritize theme over deprecated baseTheme', () => {
-    const appearance = {
-      theme: 'clerk' as any, // String themes are valid at runtime
-      baseTheme: {
-        __type: 'prebuilt_appearance' as const,
-        __themeName: 'shadcn',
-      },
-    };
+    // String themes are valid at runtime
+    const appearance = {
+      theme: 'clerk',
+      baseTheme: {
+        __type: 'prebuilt_appearance' as const,
+        __themeName: 'shadcn',
+      },
+    } as unknown as Parameters<typeof eventThemeUsage>[0];
@@
   it('should handle null appearance', () => {
-    const result = eventThemeUsage(null as any);
+    const result = eventThemeUsage(null as unknown as Parameters<typeof eventThemeUsage>[0]);

Also applies to: 36-45, 73-80, 119-119


127-127: Consider a couple more edge cases to harden behavior

Optional, but these catch edge shapes we’ve seen in the wild: empty theme arrays and non-object/non-string theme values.

   it('should handle null appearance', () => {
     const result = eventThemeUsage(null as unknown as Parameters<typeof eventThemeUsage>[0]);
 
     expectThemeUsageEvent(result, {});
   });
 });
+
+  it('should handle empty theme array by emitting without themeName', () => {
+    const appearance = {
+      theme: [],
+    } as unknown as Parameters<typeof eventThemeUsage>[0];
+
+    const result = eventThemeUsage(appearance);
+    expectThemeUsageEvent(result, {});
+  });
+
+  it('should tolerate invalid theme shapes (number) without throwing', () => {
+    const appearance = {
+      // @ts-expect-error runtime can be messy; ensure we don’t throw
+      theme: 123,
+    } as unknown as Parameters<typeof eventThemeUsage>[0];
+
+    const result = eventThemeUsage(appearance);
+    expectThemeUsageEvent(result, {});
+  });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 15fe106 and 2a6d113.

📒 Files selected for processing (11)
  • packages/clerk-js/src/core/clerk.ts (2 hunks)
  • packages/react/src/contexts/ClerkContextProvider.tsx (2 hunks)
  • packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts (1 hunks)
  • packages/shared/src/telemetry/events/index.ts (1 hunks)
  • packages/shared/src/telemetry/events/theme-usage.ts (1 hunks)
  • packages/themes/src/createTheme.ts (2 hunks)
  • packages/themes/src/themes/dark.ts (1 hunks)
  • packages/themes/src/themes/neobrutalism.ts (1 hunks)
  • packages/themes/src/themes/shadcn.ts (1 hunks)
  • packages/themes/src/themes/shadesOfPurple.ts (1 hunks)
  • packages/themes/src/themes/simple.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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/events/index.ts
  • packages/themes/src/themes/shadesOfPurple.ts
  • packages/react/src/contexts/ClerkContextProvider.tsx
  • packages/clerk-js/src/core/clerk.ts
  • packages/themes/src/themes/neobrutalism.ts
  • packages/shared/src/telemetry/events/theme-usage.ts
  • packages/themes/src/themes/shadcn.ts
  • packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
  • packages/themes/src/themes/dark.ts
  • packages/themes/src/themes/simple.ts
  • packages/themes/src/createTheme.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/events/index.ts
  • packages/themes/src/themes/shadesOfPurple.ts
  • packages/react/src/contexts/ClerkContextProvider.tsx
  • packages/clerk-js/src/core/clerk.ts
  • packages/themes/src/themes/neobrutalism.ts
  • packages/shared/src/telemetry/events/theme-usage.ts
  • packages/themes/src/themes/shadcn.ts
  • packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
  • packages/themes/src/themes/dark.ts
  • packages/themes/src/themes/simple.ts
  • packages/themes/src/createTheme.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/telemetry/events/index.ts
  • packages/themes/src/themes/shadesOfPurple.ts
  • packages/react/src/contexts/ClerkContextProvider.tsx
  • packages/clerk-js/src/core/clerk.ts
  • packages/themes/src/themes/neobrutalism.ts
  • packages/shared/src/telemetry/events/theme-usage.ts
  • packages/themes/src/themes/shadcn.ts
  • packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
  • packages/themes/src/themes/dark.ts
  • packages/themes/src/themes/simple.ts
  • packages/themes/src/createTheme.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/events/index.ts
  • packages/themes/src/themes/shadesOfPurple.ts
  • packages/react/src/contexts/ClerkContextProvider.tsx
  • packages/clerk-js/src/core/clerk.ts
  • packages/themes/src/themes/neobrutalism.ts
  • packages/shared/src/telemetry/events/theme-usage.ts
  • packages/themes/src/themes/shadcn.ts
  • packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
  • packages/themes/src/themes/dark.ts
  • packages/themes/src/themes/simple.ts
  • packages/themes/src/createTheme.ts
packages/**/index.{js,ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use tree-shaking friendly exports

Files:

  • packages/shared/src/telemetry/events/index.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/events/index.ts
  • packages/themes/src/themes/shadesOfPurple.ts
  • packages/react/src/contexts/ClerkContextProvider.tsx
  • packages/clerk-js/src/core/clerk.ts
  • packages/themes/src/themes/neobrutalism.ts
  • packages/shared/src/telemetry/events/theme-usage.ts
  • packages/themes/src/themes/shadcn.ts
  • packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
  • packages/themes/src/themes/dark.ts
  • packages/themes/src/themes/simple.ts
  • packages/themes/src/createTheme.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/events/index.ts
  • packages/themes/src/themes/shadesOfPurple.ts
  • packages/react/src/contexts/ClerkContextProvider.tsx
  • packages/clerk-js/src/core/clerk.ts
  • packages/themes/src/themes/neobrutalism.ts
  • packages/shared/src/telemetry/events/theme-usage.ts
  • packages/themes/src/themes/shadcn.ts
  • packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
  • packages/themes/src/themes/dark.ts
  • packages/themes/src/themes/simple.ts
  • packages/themes/src/createTheme.ts
**/index.ts

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/shared/src/telemetry/events/index.ts
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/shared/src/telemetry/events/index.ts
  • packages/themes/src/themes/shadesOfPurple.ts
  • packages/react/src/contexts/ClerkContextProvider.tsx
  • packages/clerk-js/src/core/clerk.ts
  • packages/themes/src/themes/neobrutalism.ts
  • packages/shared/src/telemetry/events/theme-usage.ts
  • packages/themes/src/themes/shadcn.ts
  • packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
  • packages/themes/src/themes/dark.ts
  • packages/themes/src/themes/simple.ts
  • packages/themes/src/createTheme.ts
**/*.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/react/src/contexts/ClerkContextProvider.tsx
**/*.tsx

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/react/src/contexts/ClerkContextProvider.tsx
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/telemetry/events/__tests__/theme-usage.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/telemetry/events/__tests__/theme-usage.test.ts
🧬 Code Graph Analysis (4)
packages/react/src/contexts/ClerkContextProvider.tsx (1)
packages/shared/src/telemetry/events/theme-usage.ts (1)
  • eventThemeUsage (20-28)
packages/clerk-js/src/core/clerk.ts (1)
packages/shared/src/telemetry/events/theme-usage.ts (1)
  • eventThemeUsage (20-28)
packages/shared/src/telemetry/events/theme-usage.ts (2)
packages/types/src/appearance.ts (2)
  • Appearance (991-1057)
  • BaseTheme (814-814)
packages/types/src/telemetry.ts (1)
  • TelemetryEventRaw (40-44)
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts (1)
packages/shared/src/telemetry/events/theme-usage.ts (1)
  • eventThemeUsage (20-28)
🔇 Additional comments (10)
packages/shared/src/telemetry/events/index.ts (1)

4-4: No circular dependency detected – barrel re-export is safe

I ran a scan against packages/shared/src/telemetry/events/theme-usage.ts and confirmed it does not import from the new index.ts barrel (neither directly via ./index nor via @clerk/shared/telemetry). All existing call sites import from the telemetry barrel but don’t create a cycle back into theme-usage.ts. You’re clear to merge.

packages/themes/src/themes/shadesOfPurple.ts (1)

5-5: LGTM: Theme name included for telemetry consistency

Name is aligned with file/export and supports the new telemetry flow.

packages/themes/src/themes/neobrutalism.ts (1)

23-23: LGTM: Added theme name matches export and file name

This keeps naming consistent across built-in themes for telemetry.

packages/themes/src/themes/shadcn.ts (1)

4-4: LGTM: Telemetry-friendly theme name added

Consistent with other themes and the new createTheme contract.

packages/themes/src/themes/dark.ts (1)

4-4: Adding a stable theme name is correct and aligned with telemetry usage

Including name: 'dark' ensures consistent theme identification for telemetry and debugging. No issues spotted.

packages/themes/src/themes/simple.ts (1)

4-7: Theme name addition looks good

Adding name: 'simple' is consistent with other themes and enables correct telemetry attribution.

packages/clerk-js/src/core/clerk.ts (1)

13-15: Importing eventThemeUsage is correct

The import is scoped to telemetry and maintains existing structure. No concerns here.

packages/react/src/contexts/ClerkContextProvider.tsx (1)

9-9: Telemetry import is appropriate

Re-using the shared event factory keeps event shape consistent across packages.

packages/shared/src/telemetry/events/theme-usage.ts (1)

20-28: Public telemetry event factory looks good

Clear event naming, sampling, and payload construction; type-only imports and explicit return type comply with guidelines.

packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts (1)

3-127: Solid coverage of theme-name derivation cases

Good breadth: prebuilt theme names, string themes, arrays, deprecated baseTheme precedence, and undefined/null appearance. This gives confidence the telemetry event wiring won’t regress.

Comment on lines +447 to +451

// Record theme usage telemetry when appearance is provided
if (this.#options.appearance) {
this.telemetry.record(eventThemeUsage(this.#options.appearance));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Potential duplicate THEME_USAGE events (core load vs React provider); add simple de-duplication

Clerk.load records theme usage when appearance is provided. The React Provider also records on appearance changes. On initial mount, both can fire for the same theme, producing duplicates. Add a simple guard to skip recording the same theme name twice in a row.

Proposed change:

-      // Record theme usage telemetry when appearance is provided
-      if (this.#options.appearance) {
-        this.telemetry.record(eventThemeUsage(this.#options.appearance));
-      }
+      // Record theme usage telemetry when appearance is provided (dedupe consecutive identical names)
+      if (this.#options.appearance) {
+        const evt = eventThemeUsage(this.#options.appearance);
+        const currentThemeName = evt.payload?.themeName;
+        if (currentThemeName !== this.#lastThemeUsageName) {
+          this.telemetry.record(evt);
+          this.#lastThemeUsageName = currentThemeName;
+        }
+      }

Add this private field to the class (near other private fields):

// Tracks last emitted theme usage to avoid duplicates
#lastThemeUsageName?: string;

Verification suggestion:

  • In a React app, initialize Clerk with appearance and mount ClerkProvider with the same appearance. Confirm only one THEME_USAGE event is emitted on boot, and another only when theme changes.

🏁 Script executed:

#!/bin/bash
set -e

# 1. Locate all occurrences of eventThemeUsage across the repo
rg "eventThemeUsage" -n

# 2. Identify where telemetry.record is called with eventThemeUsage (including in React provider)
rg "record.*eventThemeUsage" -n

Length of output: 2277


Add de-duplication for consecutive THEME_USAGE events

In packages/clerk-js/src/core/clerk.ts (around lines 447–451), wrap the existing call to telemetry.record(eventThemeUsage…) with a guard that skips recording if the theme name hasn’t changed since the last emission:

--- a/packages/clerk-js/src/core/clerk.ts
+++ b/packages/clerk-js/src/core/clerk.ts
@@ -447,7 +447,14 @@ export class Clerk {
       // Record theme usage telemetry when appearance is provided
       if (this.#options.appearance) {
-        this.telemetry.record(eventThemeUsage(this.#options.appearance));
+        const evt = eventThemeUsage(this.#options.appearance);
+        const currentTheme = evt.payload.themeName;
+        if (currentTheme !== this.#lastThemeUsageName) {
+          this.telemetry.record(evt);
+          this.#lastThemeUsageName = currentTheme;
+        }
       }

Add this private field alongside the other #-prefixed members of the class:

// Tracks the last emitted theme name to prevent back-to-back duplicates
#lastThemeUsageName?: string;

Why?

  • Both Clerk.load and the React <ClerkProvider> will fire a THEME_USAGE event on mount with the same appearance.
  • Without this guard you’ll see two identical events at boot; with it, you get exactly one per theme and still record on real theme changes.

How to verify:

  1. In a test app call Clerk.load({ appearance: { /*…*/ } }).
  2. Mount <ClerkProvider appearance={/* same */}>.
  3. Confirm only one THEME_USAGE is emitted on startup, and a second only after you change appearance.
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/clerk.ts around lines 447–451, add a private field
on the class (next to the other # members) to track the last emitted theme name
(e.g. #lastThemeUsageName?: string) and wrap the
telemetry.record(eventThemeUsage(...)) call with a guard that compares the
current appearance name to #lastThemeUsageName; if they are equal, skip
recording, otherwise call telemetry.record(...) and update #lastThemeUsageName
to the current theme name. This prevents back-to-back duplicate THEME_USAGE
events while still recording on real theme changes.

Comment on lines +123 to +129
// Record theme usage telemetry when appearance changes
React.useEffect(() => {
if (options.appearance && isomorphicClerkRef.current.telemetry) {
isomorphicClerkRef.current.telemetry.record(eventThemeUsage(options.appearance));
}
}, [options.appearance]);

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Guard against repeated emissions when appearance object identity changes without an actual theme change

The effect emits an event whenever options.appearance reference changes. In practice, this can emit duplicates on re-renders. Track the last emitted theme name and only record when it changes.

Note: This does not fully avoid a possible duplicate with the core Clerk.load emission; combine with the core-side dedupe proposed in clerk.ts for complete coverage.

   // Record theme usage telemetry when appearance changes
-  React.useEffect(() => {
-    if (options.appearance && isomorphicClerkRef.current.telemetry) {
-      isomorphicClerkRef.current.telemetry.record(eventThemeUsage(options.appearance));
-    }
-  }, [options.appearance]);
+  const lastThemeNameRef = React.useRef<string | undefined>(undefined);
+  React.useEffect(() => {
+    const telemetry = isomorphicClerkRef.current.telemetry;
+    if (!telemetry) {
+      return;
+    }
+    const evt = eventThemeUsage(options.appearance);
+    const nextName = evt.payload?.themeName;
+    if (nextName === lastThemeNameRef.current) {
+      return;
+    }
+    telemetry.record(evt);
+    lastThemeNameRef.current = nextName;
+  }, [options.appearance]);
🤖 Prompt for AI Agents
In packages/react/src/contexts/ClerkContextProvider.tsx around lines 123 to 129,
the effect records telemetry on every options.appearance reference change which
can emit duplicates; add a local ref (e.g., lastEmittedThemeRef) to store the
last emitted theme name, derive the current theme name from options.appearance
(handle strings and appearance objects), compare it to
lastEmittedThemeRef.current and only call
isomorphicClerkRef.current.telemetry.record(...) when they differ, then update
lastEmittedThemeRef.current to the new name; keep the same dependency on
options.appearance so it runs on changes but prevents repeated emissions for
identical theme names.

Comment on lines 70 to 83
function extractThemeName(theme: BaseTheme): string | undefined {
if (typeof theme === 'string') {
return theme;
}

if (typeof theme === 'object' && theme !== null) {
// Check for explicit theme name
if ('__themeName' in theme && typeof theme.__themeName === 'string') {
return theme.__themeName;
}
}

return undefined;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix TypeScript safety when reading __themeName from BaseTheme

BaseTheme does not declare a __themeName property. The current check uses '__themeName' in theme and then accesses theme.__themeName, which can fail type-checking under strict settings. Prefer narrowing with a type guard and accepting unknown input.

-function extractThemeName(theme: BaseTheme): string | undefined {
-  if (typeof theme === 'string') {
-    return theme;
-  }
-
-  if (typeof theme === 'object' && theme !== null) {
-    // Check for explicit theme name
-    if ('__themeName' in theme && typeof theme.__themeName === 'string') {
-      return theme.__themeName;
-    }
-  }
-
-  return undefined;
-}
+function hasThemeName(t: unknown): t is { __themeName: string } {
+  return typeof t === 'object' && t !== null && '__themeName' in t && typeof (t as any).__themeName === 'string';
+}
+
+function extractThemeName(theme: unknown): string | undefined {
+  if (typeof theme === 'string') {
+    return theme;
+  }
+  if (hasThemeName(theme)) {
+    return theme.__themeName;
+  }
+  return undefined;
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function extractThemeName(theme: BaseTheme): string | undefined {
if (typeof theme === 'string') {
return theme;
}
if (typeof theme === 'object' && theme !== null) {
// Check for explicit theme name
if ('__themeName' in theme && typeof theme.__themeName === 'string') {
return theme.__themeName;
}
}
return undefined;
}
function hasThemeName(t: unknown): t is { __themeName: string } {
return (
typeof t === 'object' &&
t !== null &&
'__themeName' in t &&
typeof (t as any).__themeName === 'string'
);
}
function extractThemeName(theme: unknown): string | undefined {
if (typeof theme === 'string') {
return theme;
}
if (hasThemeName(theme)) {
return theme.__themeName;
}
return undefined;
}
🤖 Prompt for AI Agents
packages/shared/src/telemetry/events/theme-usage.ts around lines 70 to 83: the
current code uses a raw "'__themeName' in theme" and then accesses
theme.__themeName which can fail TS strict checks because BaseTheme doesn't
declare that property; add a proper type guard or narrow to unknown before
reading the property. Implement a small type-guard like hasThemeName(x:
unknown): x is { __themeName: unknown } that checks x is non-null object and
'__themeName' in x, then inside that guarded branch check typeof x.__themeName
=== 'string' and return it; alternatively narrow theme to unknown and cast
safely (e.g. const maybe = theme as unknown as { __themeName?: unknown } and
then check typeof maybe.__themeName === 'string') before returning the string.

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

Successfully merging this pull request may close these issues.

3 participants