Skip to content

feat(clerk-js): Introduce debugLogger #6452

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 39 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
ab3cde4
feat(clerk-js): Introduce debugLogger
jacekradko Jul 31, 2025
4931533
small fixes
jacekradko Jul 31, 2025
f9a6a97
Merge branch 'main' into feat/debug-module
jacekradko Jul 31, 2025
d24c0e8
changeset
jacekradko Jul 31, 2025
0f1803d
coderabbit
jacekradko Jul 31, 2025
3ba5c80
Merge branch 'main' into feat/debug-module
jacekradko Aug 4, 2025
775fccb
fix build
jacekradko Aug 4, 2025
b6f886a
wip
jacekradko Aug 4, 2025
eaeacb8
safe initializations
jacekradko Aug 4, 2025
c3e6e52
wip
jacekradko Aug 4, 2025
bd86e19
pr feedback
jacekradko Aug 4, 2025
a7cfc1f
pr feedback
jacekradko Aug 4, 2025
806688a
Merge branch 'main' into feat/debug-module
jacekradko Aug 5, 2025
9c234a4
Merge branch 'main' into feat/debug-module
jacekradko Aug 6, 2025
496cd4c
Integrate telemetry collector
jacekradko Aug 6, 2025
aedc788
correct telemetry endpoint
jacekradko Aug 6, 2025
9828a80
tests
jacekradko Aug 6, 2025
32ce445
wip
jacekradko Aug 6, 2025
053efaf
Merge branch 'main' into feat/debug-module
jacekradko Aug 6, 2025
59b998e
fix lint and test
jacekradko Aug 6, 2025
7c311cc
wip
jacekradko Aug 6, 2025
4bcf294
Merge branch 'main' into feat/debug-module
jacekradko Aug 6, 2025
441061e
wip
jacekradko Aug 6, 2025
d79b5db
Merge branch 'main' into feat/debug-module
jacekradko Aug 7, 2025
2170de0
refactor flush methods to avoid stacking requests
jacekradko Aug 7, 2025
7604e58
remove redundant try/catch
jacekradko Aug 7, 2025
cfc5a05
consistent flush logic
jacekradko Aug 7, 2025
2f4b36b
Resolve merge conflicts: bundlewatch thresholds, TelemetryCollector l…
jacekradko Aug 8, 2025
5ff7b86
wip
jacekradko Aug 8, 2025
1562ebf
Merge branch 'main' into feat/debug-module
jacekradko Aug 11, 2025
f532cf0
wip
jacekradko Aug 11, 2025
55bda4e
Merge branch 'main' into feat/debug-module
jacekradko Aug 12, 2025
243f598
pr feedback
jacekradko Aug 12, 2025
b25d4d4
pr feedback
jacekradko Aug 12, 2025
a1994c4
wip
jacekradko Aug 12, 2025
fa0cffd
Merge branch 'main' into feat/debug-module
jacekradko Aug 12, 2025
e544597
fix lint
jacekradko Aug 12, 2025
c7798ff
Merge branch 'main' into feat/debug-module
jacekradko Aug 12, 2025
275ba94
wip
jacekradko Aug 12, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/all-cougars-hide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/types': patch
---

Introduce debugLogger for internal debugging support
2 changes: 1 addition & 1 deletion packages/clerk-js/bundlewatch.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
{ "path": "./dist/clerk.headless*.js", "maxSize": "55.2KB" },
{ "path": "./dist/ui-common*.js", "maxSize": "113KB" },
{ "path": "./dist/ui-common*.legacy.*.js", "maxSize": "118KB" },
{ "path": "./dist/vendors*.js", "maxSize": "40.2KB" },
{ "path": "./dist/vendors*.js", "maxSize": "41KB" },
{ "path": "./dist/coinbase*.js", "maxSize": "38KB" },
{ "path": "./dist/stripe-vendors*.js", "maxSize": "1KB" },
{ "path": "./dist/createorganization*.js", "maxSize": "5KB" },
Expand Down
56 changes: 55 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,32 @@ type SetActiveHook = (intent?: 'sign-out') => void | Promise<void>;

export type ClerkCoreBroadcastChannelEvent = { type: 'signout' };

/**
* Interface for the debug logger with all available logging methods
*/
interface DebugLoggerInterface {
debug(message: string, context?: Record<string, unknown>, source?: string): void;
error(message: string, context?: Record<string, unknown>, source?: string): void;
info(message: string, context?: Record<string, unknown>, source?: string): void;
trace(message: string, context?: Record<string, unknown>, source?: string): void;
warn(message: string, context?: Record<string, unknown>, source?: string): void;
}

/**
* Type guard to check if an object implements the DebugLoggerInterface
*/
function _isDebugLogger(obj: unknown): obj is DebugLoggerInterface {
return (
typeof obj === 'object' &&
obj !== null &&
typeof (obj as DebugLoggerInterface).debug === 'function' &&
typeof (obj as DebugLoggerInterface).error === 'function' &&
typeof (obj as DebugLoggerInterface).info === 'function' &&
typeof (obj as DebugLoggerInterface).trace === 'function' &&
typeof (obj as DebugLoggerInterface).warn === 'function'
);
}

declare global {
interface Window {
Clerk?: Clerk;
Expand Down Expand Up @@ -199,8 +225,8 @@ export class Clerk implements ClerkInterface {
public static sdkMetadata: SDKMetadata = {
name: __PKG_NAME__,
version: __PKG_VERSION__,
environment: process.env.NODE_ENV || 'production',
};

private static _billing: CommerceBillingNamespace;
private static _apiKeys: APIKeysNamespace;
private _checkout: ClerkInterface['__experimental_checkout'] | undefined;
Expand All @@ -211,6 +237,7 @@ export class Clerk implements ClerkInterface {
public user: UserResource | null | undefined;
public __internal_country?: string | null;
public telemetry: TelemetryCollector | undefined;
public debugLogger?: DebugLoggerInterface; // Properly typed debug logger interface

protected internal_last_error: ClerkAPIError | null = null;
// converted to protected environment to support `updateEnvironment` type assertion
Expand Down Expand Up @@ -1480,6 +1507,7 @@ export class Clerk implements ClerkInterface {
const customNavigate =
options?.replace && this.#options.routerReplace ? this.#options.routerReplace : this.#options.routerPush;

this.debugLogger?.info(`Clerk is navigating to: ${toURL}`);
if (this.#options.routerDebug) {
console.log(`Clerk is navigating to: ${toURL}`);
}
Expand Down Expand Up @@ -2197,6 +2225,23 @@ export class Clerk implements ClerkInterface {

public updateEnvironment(environment: EnvironmentResource): asserts this is { environment: EnvironmentResource } {
this.environment = environment;

// Initialize debug module if client_debug_mode is enabled
if (environment.clientDebugMode) {
this.#initializeDebugModule();
}
}

async #initializeDebugModule(): Promise<void> {
try {
const { getDebugLogger } = await import('./modules/debug');
const logger = await getDebugLogger({});
if (_isDebugLogger(logger)) {
this.debugLogger = logger;
}
} catch (error) {
console.error('Failed to initialize debug module:', error);
}
}

__internal_setCountry = (country: string | null) => {
Expand Down Expand Up @@ -2840,4 +2885,13 @@ export class Clerk implements ClerkInterface {

return allowedProtocols;
}

/**
* @internal
*/
public static async __internal_resetDebugLogger(): Promise<void> {
// This method is now handled by the debug module itself
const { __internal_resetDebugLogger } = await import('./modules/debug');
__internal_resetDebugLogger();
}
}
254 changes: 254 additions & 0 deletions packages/clerk-js/src/core/modules/debug/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
import { DebugLogger } from './logger';
import { type CompositeLoggerOptions, CompositeTransport } from './transports/composite';
import { ConsoleTransport } from './transports/console';
import { type TelemetryLoggerOptions, TelemetryTransport } from './transports/telemetry';
import type { DebugLogFilter, DebugLogLevel } from './types';
import { isValidLogLevel, VALID_LOG_LEVELS } from './types';

/**
* Default log level for debug logging
*/
export const DEFAULT_LOG_LEVEL: DebugLogLevel = 'debug';

/**
* Validates logger options and throws if invalid
* @param options - The options to validate
* @throws Error if invalid log level is provided
*/
function validateLoggerOptions<T extends { logLevel?: unknown }>(options: T): void {
const { logLevel } = options;

if (logLevel !== undefined && !isValidLogLevel(logLevel)) {
const levelString = typeof logLevel === 'string' ? logLevel : JSON.stringify(logLevel);
throw new Error(`Invalid log level: "${levelString}". Valid levels are: ${VALID_LOG_LEVELS.join(', ')}`);
}
}

export type * from './types';

export { ConsoleTransport, TelemetryTransport, CompositeTransport };
export type { TelemetryLoggerOptions, CompositeLoggerOptions };

/**
* Options for configuring a logger with endpoint, filters, and log level
*/
export interface LoggerOptions {
endpoint?: string;
filters?: DebugLogFilter[];
logLevel?: DebugLogLevel;
}

/**
* Options for configuring a console logger with filters and log level
*/
export interface ConsoleLoggerOptions {
filters?: DebugLogFilter[];
logLevel?: DebugLogLevel;
}

/**
* Singleton instance for managing debug logger initialization
*
* Race Condition Fix:
* - Uses a promise cache (initializationPromise) to prevent multiple concurrent initializations
* - If initialization is already in progress, subsequent calls wait for the same promise
* - If initialization fails, the promise cache is cleared to allow retries
* - This ensures only one initialization process runs at a time, even with concurrent calls
*/
class DebugLoggerManager {
private static instance: DebugLoggerManager;
private initialized = false;
private logger: DebugLogger | null = null;
private initializationPromise: Promise<DebugLogger | null> | null = null;

private constructor() {}

/**
* Gets the singleton instance
*/
static getInstance(): DebugLoggerManager {
if (!DebugLoggerManager.instance) {
DebugLoggerManager.instance = new DebugLoggerManager();
}
return DebugLoggerManager.instance;
}

/**
* Initializes the debug logger if not already initialized
* Uses a promise cache to prevent race conditions during concurrent initialization
* @param options - Configuration options for the logger
* @returns The debug logger instance
*/
async initialize(options: LoggerOptions = {}): Promise<DebugLogger | null> {
if (this.initialized && this.logger) {
return this.logger;
}

if (this.initializationPromise) {
return this.initializationPromise;
}

this.initializationPromise = this.performInitialization(options);
return this.initializationPromise;
}

/**
* Performs the actual initialization logic
* @param options - Configuration options for the logger
* @returns Promise resolving to the debug logger instance
*/
private async performInitialization(options: LoggerOptions): Promise<DebugLogger | null> {
try {
validateLoggerOptions(options);
const { endpoint, logLevel, filters } = options;
const finalLogLevel = logLevel ?? DEFAULT_LOG_LEVEL;

const transports = [{ transport: new ConsoleTransport() }, { transport: new TelemetryTransport(endpoint) }];

const transportInstances = transports.map(t => t.transport);
const compositeTransport = new CompositeTransport(transportInstances);
const logger = new DebugLogger(compositeTransport, finalLogLevel, filters);

this.logger = logger;
this.initialized = true;
return this.logger;
} catch (error) {
console.error('Failed to initialize debug module:', error);
this.initializationPromise = null;
return null;
}
}

/**
* Gets the current logger instance
*/
getLogger(): DebugLogger | null {
return this.logger;
}

/**
* Checks if the debug logger is initialized
*/
isInitialized(): boolean {
return this.initialized;
}

/**
* Resets the initialization state (for testing purposes)
*/
reset(): void {
this.initialized = false;
this.logger = null;
this.initializationPromise = null;
}
}

/**
* Gets or initializes the debug logger
* @param options - Configuration options for the logger
* @returns Promise resolving to the debug logger instance
*/
export async function getDebugLogger(options: LoggerOptions = {}): Promise<DebugLogger | null> {
const manager = DebugLoggerManager.getInstance();
return manager.initialize(options);
}

/**
* Creates a composite logger with both console and telemetry transports
* @param options - Configuration options for the logger
* @returns Object containing the logger and composite transport
*/
export function createLogger(options: {
endpoint?: string;
logLevel?: DebugLogLevel;
filters?: DebugLogFilter[];
}): { logger: DebugLogger; transport: CompositeTransport } | null {
try {
validateLoggerOptions(options);
const { endpoint, logLevel, filters } = options;
const finalLogLevel = logLevel ?? DEFAULT_LOG_LEVEL;

return createCompositeLogger({
transports: [{ transport: new ConsoleTransport() }, { transport: new TelemetryTransport(endpoint) }],
logLevel: finalLogLevel,
filters,
});
} catch (error) {
console.error('Failed to create logger:', error);
return null;
}
}

/**
* Creates a console-only logger
* @param options - Configuration options for the console logger
* @returns Object containing the logger and console transport
*/
export function createConsoleLogger(
options: ConsoleLoggerOptions,
): { logger: DebugLogger; transport: ConsoleTransport } | null {
try {
validateLoggerOptions(options);
const { logLevel, filters } = options;
const finalLogLevel = logLevel ?? DEFAULT_LOG_LEVEL;
const transport = new ConsoleTransport();
const logger = new DebugLogger(transport, finalLogLevel, filters);
return { logger, transport };
} catch (error) {
console.error('Failed to create console logger:', error);
return null;
}
}

/**
* Creates a telemetry-only logger
* @param options - Configuration options for the telemetry logger
* @returns Object containing the logger and telemetry transport
*/
export function createTelemetryLogger(
options: TelemetryLoggerOptions,
): { logger: DebugLogger; transport: TelemetryTransport } | null {
try {
validateLoggerOptions(options);
const { endpoint, logLevel, filters } = options;
const finalLogLevel = logLevel ?? DEFAULT_LOG_LEVEL;
const transport = new TelemetryTransport(endpoint);
const logger = new DebugLogger(transport, finalLogLevel, filters);
return { logger, transport };
} catch (error) {
console.error('Failed to create telemetry logger:', error);
return null;
}
}

/**
* Creates a composite logger with multiple transports
* @param options - Configuration options for the composite logger
* @returns Object containing the logger and composite transport
*/
export function createCompositeLogger(
options: CompositeLoggerOptions,
): { logger: DebugLogger; transport: CompositeTransport } | null {
try {
validateLoggerOptions(options);
const { transports, logLevel, filters } = options;
const finalLogLevel = logLevel ?? DEFAULT_LOG_LEVEL;

const transportInstances = transports.map((t: any) => t.transport);
const compositeTransport = new CompositeTransport(transportInstances);

const logger = new DebugLogger(compositeTransport, finalLogLevel, filters);
return { logger, transport: compositeTransport };
} catch (error) {
console.error('Failed to create composite logger:', error);
return null;
}
}

/**
* @internal
* Resets the debug logger manager (for testing purposes)
*/
export function __internal_resetDebugLogger(): void {
DebugLoggerManager.getInstance().reset();
}
Loading
Loading