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 3 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
27 changes: 26 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,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 +211,7 @@ export class Clerk implements ClerkInterface {
public user: UserResource | null | undefined;
public __internal_country?: string | null;
public telemetry: TelemetryCollector | undefined;
public debugLogger?: any; // Will be typed properly after dynamic import

protected internal_last_error: ClerkAPIError | null = null;
// converted to protected environment to support `updateEnvironment` type assertion
Expand Down Expand Up @@ -1480,6 +1481,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 +2199,20 @@ 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');
this.debugLogger = await getDebugLogger({});
} catch (error) {
console.error('Failed to initialize debug module:', error);
}
}

__internal_setCountry = (country: string | null) => {
Expand Down Expand Up @@ -2838,4 +2854,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();
}
}
170 changes: 170 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,170 @@
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';

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
*/
class DebugLoggerManager {
private static instance: DebugLoggerManager;
private initialized = false;
private logger: any = 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
* @param options - Configuration options for the logger
* @returns The debug logger instance
*/
async initialize(options: LoggerOptions = {}): Promise<any> {
if (this.initialized && this.logger) {
return this.logger;
}

try {
const { endpoint, logLevel = 'info', filters } = options;

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, logLevel, filters);

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

/**
* Gets the current logger instance
*/
getLogger(): any {
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;
}
}

/**
* 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<any> {
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[] }) {
const { endpoint, logLevel = 'info', filters } = options;

return createCompositeLogger({
transports: [{ transport: new ConsoleTransport() }, { transport: new TelemetryTransport(endpoint) }],
logLevel,
filters,
});
}

/**
* 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) {
const { logLevel = 'info', filters } = options;
const transport = new ConsoleTransport();
const logger = new DebugLogger(transport, logLevel, filters);
return { logger, transport };
}

/**
* 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) {
const { endpoint, logLevel = 'info', filters } = options;
const transport = new TelemetryTransport(endpoint);
const logger = new DebugLogger(transport, logLevel, filters);
return { logger, transport };
}

/**
* 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) {
const { transports, logLevel = 'info', filters } = options;

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

const logger = new DebugLogger(compositeTransport, logLevel, filters);
return { logger, transport: compositeTransport };
}

/**
* @internal
* Resets the debug logger manager (for testing purposes)
*/
export function __internal_resetDebugLogger(): void {
DebugLoggerManager.getInstance().reset();
}
116 changes: 116 additions & 0 deletions packages/clerk-js/src/core/modules/debug/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import type { DebugLogEntry, DebugLogFilter, DebugLogLevel, DebugTransport } from './types';

/**
* Minimal debug logger interface for engineers
*/
export class DebugLogger {
private readonly transport: DebugTransport;
private readonly logLevel: DebugLogLevel;
private readonly filters?: DebugLogFilter[];

constructor(transport: DebugTransport, logLevel: DebugLogLevel = 'info', filters?: DebugLogFilter[]) {
this.transport = transport;
this.logLevel = logLevel;
this.filters = filters;
}

error(message: string, context?: Record<string, unknown>, source?: string): void {
this.log('error', message, context, source);
}

warn(message: string, context?: Record<string, unknown>, source?: string): void {
this.log('warn', message, context, source);
}

info(message: string, context?: Record<string, unknown>, source?: string): void {
this.log('info', message, context, source);
}

debug(message: string, context?: Record<string, unknown>, source?: string): void {
this.log('debug', message, context, source);
}

trace(message: string, context?: Record<string, unknown>, source?: string): void {
this.log('trace', message, context, source);
}

private log(level: DebugLogLevel, message: string, context?: Record<string, unknown>, source?: string): void {
if (!this.shouldLogLevel(level)) {
return;
}

if (!this.shouldLogFilters(level, message, source)) {
return;
}

const entry: DebugLogEntry = {
id: crypto.randomUUID(),
timestamp: Date.now(),
level,
message,
context,
source,
};

this.transport.send(entry).catch(err => {
console.error('Failed to send log entry:', err);
});
}

private shouldLogLevel(level: DebugLogLevel): boolean {
const levels: DebugLogLevel[] = ['error', 'warn', 'info', 'debug', 'trace'];
const currentLevelIndex = levels.indexOf(this.logLevel);
const messageLevelIndex = levels.indexOf(level);
return messageLevelIndex <= currentLevelIndex;
}

private shouldLogFilters(level: DebugLogLevel, message: string, source?: string): boolean {
if (!this.filters || this.filters.length === 0) {
return true;
}

return this.filters.every(filter => {
if (filter.level && filter.level !== level) {
return false;
}

if (filter.source) {
if (typeof filter.source === 'string') {
if (source !== filter.source) {
return false;
}
} else if (filter.source instanceof RegExp) {
if (!source || !filter.source.test(source)) {
return false;
}
}
}

if (filter.includePatterns && filter.includePatterns.length > 0) {
const matchesInclude = filter.includePatterns.some(pattern => {
if (typeof pattern === 'string') {
return message.includes(pattern);
}
return pattern.test(message);
});
if (!matchesInclude) {
return false;
}
}

if (filter.excludePatterns && filter.excludePatterns.length > 0) {
const matchesExclude = filter.excludePatterns.some(pattern => {
if (typeof pattern === 'string') {
return message.includes(pattern);
}
return pattern.test(message);
});
if (matchesExclude) {
return false;
}
}

return true;
});
}
}
27 changes: 27 additions & 0 deletions packages/clerk-js/src/core/modules/debug/transports/composite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { DebugLogEntry, DebugLogFilter, DebugTransport } from '../types';

export interface CompositeLoggerOptions {
transports: Array<{
transport: DebugTransport;
options?: Record<string, unknown>;
}>;
logLevel?: 'error' | 'warn' | 'info' | 'debug' | 'trace';
filters?: DebugLogFilter[];
}

export class CompositeTransport implements DebugTransport {
private readonly transports: DebugTransport[];

constructor(transports: DebugTransport[]) {
this.transports = transports;
}

async send(entry: DebugLogEntry): Promise<void> {
const promises = this.transports.map(transport =>
transport.send(entry).catch(err => {
console.error('Failed to send to transport:', err);
}),
);
await Promise.allSettled(promises);
}
}
Loading