@parsrun/core 0.1.28 → 0.1.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/decimal.d.ts +176 -46
- package/dist/decimal.js +123 -40
- package/dist/decimal.js.map +1 -1
- package/dist/errors.d.ts +39 -3
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +184 -15
- package/dist/index.js +155 -40
- package/dist/index.js.map +1 -1
- package/dist/{logger-3oVznpFY.d.ts → logger-DrxxwI7C.d.ts} +136 -11
- package/dist/logger.d.ts +1 -1
- package/dist/logger.js +32 -0
- package/dist/logger.js.map +1 -1
- package/dist/transports/index.d.ts +58 -7
- package/dist/transports/index.js.map +1 -1
- package/dist/types.d.ts +176 -0
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime.ts","../src/env.ts","../src/transports/console.ts","../src/logger.ts","../src/decimal.ts","../src/types.ts","../src/errors.ts","../src/error-codes.ts","../src/transports/axiom.ts","../src/transports/sentry.ts","../src/transports/logtape.ts","../src/index.ts"],"sourcesContent":["/**\n * @module\n * Runtime detection for Node.js, Deno, Bun, and Cloudflare Workers.\n * Detects the current JavaScript runtime and provides helper functions.\n *\n * @example\n * ```typescript\n * import { runtime, isNode, isDeno, isBun, isCloudflare, getRuntimeVersion } from '@parsrun/core';\n *\n * console.log(`Running on ${runtime}`); // \"node\", \"deno\", \"bun\", \"cloudflare\", etc.\n *\n * if (isNode()) {\n * // Node.js specific code\n * } else if (isCloudflare()) {\n * // Cloudflare Workers specific code\n * }\n *\n * console.log(getRuntimeVersion()); // \"Node.js 20.0.0\"\n * ```\n */\n\nexport type Runtime = \"node\" | \"deno\" | \"bun\" | \"cloudflare\" | \"edge\" | \"browser\" | \"unknown\";\n\n/**\n * Detect the current JavaScript runtime\n */\nexport function detectRuntime(): Runtime {\n // Bun check (must be before Node since Bun also has process)\n if (typeof globalThis !== \"undefined\" && \"Bun\" in globalThis) {\n return \"bun\";\n }\n\n // Deno check\n if (typeof globalThis !== \"undefined\" && \"Deno\" in globalThis) {\n return \"deno\";\n }\n\n // Cloudflare Workers check (has caches but no process)\n if (\n typeof globalThis !== \"undefined\" &&\n typeof (globalThis as any).caches !== \"undefined\" &&\n typeof (globalThis as any).process === \"undefined\"\n ) {\n return \"cloudflare\";\n }\n\n // Generic Edge runtime check (Vercel Edge, etc.)\n if (\n typeof globalThis !== \"undefined\" &&\n typeof (globalThis as any).EdgeRuntime !== \"undefined\"\n ) {\n return \"edge\";\n }\n\n // Browser check\n if (\n typeof globalThis !== \"undefined\" &&\n typeof (globalThis as any).window !== \"undefined\" &&\n typeof (globalThis as any).document !== \"undefined\"\n ) {\n return \"browser\";\n }\n\n // Node.js check\n if (\n typeof process !== \"undefined\" &&\n process.versions &&\n process.versions.node\n ) {\n return \"node\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Current runtime (cached)\n */\nexport const runtime = detectRuntime();\n\n/**\n * Runtime information helpers\n */\nexport const runtimeInfo = {\n runtime,\n isNode: runtime === \"node\",\n isDeno: runtime === \"deno\",\n isBun: runtime === \"bun\",\n isCloudflare: runtime === \"cloudflare\",\n isEdge: runtime === \"cloudflare\" || runtime === \"edge\" || runtime === \"deno\",\n isBrowser: runtime === \"browser\",\n isServer: runtime !== \"browser\",\n supportsWebCrypto: typeof globalThis.crypto?.subtle !== \"undefined\",\n supportsStreams: typeof globalThis.ReadableStream !== \"undefined\",\n} as const;\n\n/**\n * Check if running in Node.js\n */\nexport function isNode(): boolean {\n return runtime === \"node\";\n}\n\n/**\n * Check if running in Deno\n */\nexport function isDeno(): boolean {\n return runtime === \"deno\";\n}\n\n/**\n * Check if running in Bun\n */\nexport function isBun(): boolean {\n return runtime === \"bun\";\n}\n\n/**\n * Check if running in Cloudflare Workers\n */\nexport function isCloudflare(): boolean {\n return runtime === \"cloudflare\";\n}\n\n/**\n * Check if running in any edge environment\n */\nexport function isEdge(): boolean {\n return runtimeInfo.isEdge;\n}\n\n/**\n * Check if running in browser\n */\nexport function isBrowser(): boolean {\n return runtime === \"browser\";\n}\n\n/**\n * Check if running on server (not browser)\n */\nexport function isServer(): boolean {\n return runtimeInfo.isServer;\n}\n\n/**\n * Get runtime version string\n */\nexport function getRuntimeVersion(): string {\n switch (runtime) {\n case \"node\":\n return `Node.js ${process?.versions?.node ?? \"unknown\"}`;\n case \"bun\":\n return `Bun ${(globalThis as any).Bun.version}`;\n case \"deno\":\n return `Deno ${(globalThis as any).Deno.version.deno}`;\n case \"cloudflare\":\n return \"Cloudflare Workers\";\n case \"edge\":\n return \"Edge Runtime\";\n case \"browser\":\n return typeof navigator !== \"undefined\" ? navigator.userAgent : \"Browser\";\n default:\n return \"Unknown\";\n }\n}\n","/**\n * @module\n * Runtime-agnostic environment variable access.\n * Works in Node.js, Deno, Bun, and Cloudflare Workers.\n *\n * @example\n * ```typescript\n * import { getEnv, requireEnv, getEnvNumber, isDevelopment } from '@parsrun/core';\n *\n * // Get optional env var with default\n * const port = getEnvNumber('PORT', 3000);\n *\n * // Get required env var (throws if missing)\n * const apiKey = requireEnv('API_KEY');\n *\n * // Check environment\n * if (isDevelopment()) {\n * console.log('Running in development mode');\n * }\n * ```\n */\n\nimport { runtime } from \"./runtime.js\";\n\n/**\n * Environment variable store for edge runtimes\n * Must be set from the request handler's env parameter\n */\nlet edgeEnvStore: Record<string, string | undefined> = {};\n\n/**\n * Set environment variables for edge runtimes (Cloudflare Workers, etc.)\n * Call this from your worker's fetch handler with the env parameter\n *\n * @example\n * ```typescript\n * export default {\n * async fetch(request, env) {\n * setEdgeEnv(env);\n * // ... rest of handler\n * }\n * }\n * ```\n */\nexport function setEdgeEnv(env: Record<string, string | undefined>): void {\n edgeEnvStore = { ...edgeEnvStore, ...env };\n}\n\n/**\n * Clear edge environment store\n */\nexport function clearEdgeEnv(): void {\n edgeEnvStore = {};\n}\n\n/**\n * Get an environment variable value\n * Works across all runtimes\n */\nexport function getEnv(key: string, defaultValue?: string): string | undefined {\n // Edge runtimes (Cloudflare Workers, etc.)\n if (runtime === \"cloudflare\" || runtime === \"edge\") {\n return edgeEnvStore[key] ?? defaultValue;\n }\n\n // Deno\n if (runtime === \"deno\") {\n try {\n return (globalThis as any).Deno.env.get(key) ?? defaultValue;\n } catch {\n return defaultValue;\n }\n }\n\n // Node.js / Bun (both use process.env)\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[key] ?? defaultValue;\n }\n\n // Browser - check for injected env\n if (runtime === \"browser\" && typeof (globalThis as any).__ENV__ !== \"undefined\") {\n return (globalThis as any).__ENV__[key] ?? defaultValue;\n }\n\n return defaultValue;\n}\n\n/**\n * Get an environment variable, throwing if not found\n */\nexport function requireEnv(key: string): string {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n throw new Error(`Required environment variable \"${key}\" is not set`);\n }\n return value;\n}\n\n/**\n * Get an environment variable as a number\n */\nexport function getEnvNumber(key: string, defaultValue?: number): number | undefined {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n const parsed = parseInt(value, 10);\n return isNaN(parsed) ? defaultValue : parsed;\n}\n\n/**\n * Get an environment variable as a float\n */\nexport function getEnvFloat(key: string, defaultValue?: number): number | undefined {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n const parsed = parseFloat(value);\n return isNaN(parsed) ? defaultValue : parsed;\n}\n\n/**\n * Get an environment variable as a boolean\n */\nexport function getEnvBoolean(key: string, defaultValue: boolean = false): boolean {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n return value === \"true\" || value === \"1\" || value === \"yes\";\n}\n\n/**\n * Get an environment variable as an array (comma-separated)\n */\nexport function getEnvArray(key: string, defaultValue: string[] = []): string[] {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n return value.split(\",\").map((s) => s.trim()).filter(Boolean);\n}\n\n/**\n * Get an environment variable as JSON\n */\nexport function getEnvJson<T>(key: string, defaultValue?: T): T | undefined {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n try {\n return JSON.parse(value) as T;\n } catch {\n return defaultValue;\n }\n}\n\n/**\n * Check if running in development mode\n */\nexport function isDevelopment(): boolean {\n const env = getEnv(\"NODE_ENV\");\n return env === \"development\" || env === undefined;\n}\n\n/**\n * Check if running in production mode\n */\nexport function isProduction(): boolean {\n return getEnv(\"NODE_ENV\") === \"production\";\n}\n\n/**\n * Check if running in test mode\n */\nexport function isTest(): boolean {\n return getEnv(\"NODE_ENV\") === \"test\";\n}\n\n/**\n * Environment mode\n */\nexport type EnvMode = \"development\" | \"production\" | \"test\";\n\n/**\n * Get current environment mode\n */\nexport function getEnvMode(): EnvMode {\n const env = getEnv(\"NODE_ENV\");\n if (env === \"production\") return \"production\";\n if (env === \"test\") return \"test\";\n return \"development\";\n}\n\n/**\n * Create a typed environment configuration object\n *\n * @example\n * ```typescript\n * const env = createEnvConfig({\n * DATABASE_URL: { required: true },\n * PORT: { type: 'number', default: 3000 },\n * DEBUG: { type: 'boolean', default: false },\n * });\n *\n * env.DATABASE_URL // string\n * env.PORT // number\n * env.DEBUG // boolean\n * ```\n */\nexport function createEnvConfig<T extends EnvSchema>(schema: T): EnvResult<T> {\n const result: Record<string, unknown> = {};\n\n for (const [key, config] of Object.entries(schema)) {\n const envConfig = config as EnvConfigItem;\n let value: unknown;\n\n switch (envConfig.type) {\n case \"number\":\n value = getEnvNumber(key, envConfig.default as number | undefined);\n break;\n case \"boolean\":\n value = getEnvBoolean(key, envConfig.default as boolean | undefined);\n break;\n case \"array\":\n value = getEnvArray(key, envConfig.default as string[] | undefined);\n break;\n case \"json\":\n value = getEnvJson(key, envConfig.default);\n break;\n default:\n value = getEnv(key, envConfig.default as string | undefined);\n }\n\n if (envConfig.required && (value === undefined || value === \"\")) {\n throw new Error(`Required environment variable \"${key}\" is not set`);\n }\n\n result[key] = value;\n }\n\n return result as EnvResult<T>;\n}\n\n// Type helpers for createEnvConfig\ntype EnvConfigItem = {\n type?: \"string\" | \"number\" | \"boolean\" | \"array\" | \"json\";\n required?: boolean;\n default?: unknown;\n};\n\ntype EnvSchema = Record<string, EnvConfigItem>;\n\ntype EnvResult<T extends EnvSchema> = {\n [K in keyof T]: T[K][\"type\"] extends \"number\"\n ? number\n : T[K][\"type\"] extends \"boolean\"\n ? boolean\n : T[K][\"type\"] extends \"array\"\n ? string[]\n : T[K][\"type\"] extends \"json\"\n ? unknown\n : string;\n};\n","/**\n * @parsrun/core - Console Transport\n * Default transport that outputs to console\n */\n\nimport { runtime } from \"../runtime.js\";\nimport { isDevelopment } from \"../env.js\";\nimport type { LogEntry, LogLevelName } from \"../logger.js\";\nimport type { LogTransport } from \"./types.js\";\n\n/**\n * Console transport options\n */\nexport interface ConsoleTransportOptions {\n /** Enable pretty printing (default: true in development) */\n pretty?: boolean;\n /** Enable ANSI colors (default: true in Node/Bun) */\n colors?: boolean;\n}\n\n/**\n * Console transport\n * Outputs logs to console with optional pretty printing and colors\n */\nexport class ConsoleTransport implements LogTransport {\n readonly name = \"console\";\n\n private pretty: boolean;\n private colors: boolean;\n\n constructor(options: ConsoleTransportOptions = {}) {\n this.pretty = options.pretty ?? isDevelopment();\n this.colors = options.colors ?? (runtime === \"node\" || runtime === \"bun\");\n }\n\n log(entry: LogEntry): void {\n if (this.pretty) {\n this.logPretty(entry);\n } else {\n this.logJson(entry);\n }\n }\n\n private logJson(entry: LogEntry): void {\n const { level, message, timestamp, context, error } = entry;\n\n const output: Record<string, unknown> = {\n level,\n time: timestamp,\n msg: message,\n };\n\n if (context && Object.keys(context).length > 0) {\n Object.assign(output, context);\n }\n\n if (error) {\n output[\"err\"] = error;\n }\n\n console.log(JSON.stringify(output));\n }\n\n private logPretty(entry: LogEntry): void {\n const { level, message, timestamp, context, error } = entry;\n\n const levelColors: Record<LogLevelName, string> = {\n TRACE: \"\\x1b[90m\", // Gray\n DEBUG: \"\\x1b[36m\", // Cyan\n INFO: \"\\x1b[32m\", // Green\n WARN: \"\\x1b[33m\", // Yellow\n ERROR: \"\\x1b[31m\", // Red\n FATAL: \"\\x1b[35m\", // Magenta\n SILENT: \"\",\n };\n\n const reset = \"\\x1b[0m\";\n const color = this.colors ? levelColors[level] : \"\";\n const resetCode = this.colors ? reset : \"\";\n\n // Extract time part from ISO timestamp\n const timePart = timestamp.split(\"T\")[1];\n const time = timePart ? timePart.slice(0, 8) : timestamp;\n\n let output = `${color}[${time}] ${level.padEnd(5)}${resetCode} ${message}`;\n\n if (context && Object.keys(context).length > 0) {\n output += ` ${JSON.stringify(context)}`;\n }\n\n // Route to appropriate console method\n if (level === \"ERROR\" || level === \"FATAL\") {\n console.error(output);\n if (error?.stack) {\n console.error(error.stack);\n }\n } else if (level === \"WARN\") {\n console.warn(output);\n } else if (level === \"DEBUG\" || level === \"TRACE\") {\n console.debug(output);\n } else {\n console.log(output);\n }\n }\n}\n","/**\n * @module\n * Lightweight, edge-compatible structured logging.\n * Works standalone or as abstraction over pino/winston in Node.js.\n *\n * @example\n * ```typescript\n * import { createLogger, Logger, LogLevel } from '@parsrun/core';\n *\n * // Create a logger\n * const log = createLogger({\n * name: 'my-service',\n * level: 'DEBUG',\n * pretty: true\n * });\n *\n * log.info('Server started', { port: 3000 });\n * log.error('Request failed', error, { userId: '123' });\n *\n * // Create child logger with context\n * const requestLog = log.child({ requestId: 'abc123' });\n * ```\n */\n\nimport { getEnv } from \"./env.js\";\nimport { ConsoleTransport } from \"./transports/console.js\";\nimport type { LogTransport } from \"./transports/types.js\";\n\n// Re-export ConsoleTransport for backward compatibility\nexport { ConsoleTransport, type ConsoleTransportOptions } from \"./transports/console.js\";\n\n// Re-export transport types\nexport type { LogTransport } from \"./transports/types.js\";\n\n/**\n * Log levels\n */\nexport const LogLevel = {\n TRACE: 10,\n DEBUG: 20,\n INFO: 30,\n WARN: 40,\n ERROR: 50,\n FATAL: 60,\n SILENT: 100,\n} as const;\n\nexport type LogLevelName = keyof typeof LogLevel;\nexport type LogLevelValue = (typeof LogLevel)[LogLevelName];\n\n/**\n * Error info structure\n */\nexport interface ErrorInfo {\n name: string;\n message: string;\n stack: string | undefined;\n}\n\n/**\n * Log entry structure\n */\nexport interface LogEntry {\n level: LogLevelName;\n levelValue: LogLevelValue;\n message: string;\n timestamp: string;\n context: Record<string, unknown> | undefined;\n error: ErrorInfo | undefined;\n}\n\n\n/**\n * Logger configuration\n */\nexport interface LoggerConfig {\n /** Minimum log level */\n level: LogLevelName | undefined;\n /** Logger name/module */\n name: string | undefined;\n /** Base context added to all logs */\n context: Record<string, unknown> | undefined;\n /** Custom transports */\n transports: LogTransport[] | undefined;\n /** Pretty print in development */\n pretty: boolean | undefined;\n /** Redact sensitive fields */\n redact: string[] | undefined;\n /** Timestamp format */\n timestamp: boolean | (() => string) | undefined;\n}\n\n\n/**\n * Redact sensitive fields from context\n */\nfunction redactFields(\n obj: Record<string, unknown>,\n fields: string[]\n): Record<string, unknown> {\n const result = { ...obj };\n for (const field of fields) {\n if (field in result) {\n result[field] = \"[REDACTED]\";\n }\n // Handle nested fields like \"user.password\"\n const parts = field.split(\".\");\n if (parts.length > 1) {\n let current: Record<string, unknown> | undefined = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (part && current && typeof current === \"object\" && part in current) {\n const val = current[part];\n if (val && typeof val === \"object\") {\n current = val as Record<string, unknown>;\n } else {\n current = undefined;\n break;\n }\n } else {\n current = undefined;\n break;\n }\n }\n const lastPart = parts[parts.length - 1];\n if (lastPart && current && typeof current === \"object\" && lastPart in current) {\n current[lastPart] = \"[REDACTED]\";\n }\n }\n }\n return result;\n}\n\n/**\n * Default redact fields\n */\nconst DEFAULT_REDACT_FIELDS = [\n \"password\",\n \"secret\",\n \"token\",\n \"accessToken\",\n \"refreshToken\",\n \"apiKey\",\n \"authorization\",\n \"cookie\",\n \"creditCard\",\n \"ssn\",\n];\n\n/**\n * Logger class\n */\nexport class Logger {\n private level: LogLevelValue;\n private name: string | undefined;\n private context: Record<string, unknown>;\n private transports: LogTransport[];\n private redactFields: string[];\n private timestampFn: () => string;\n\n constructor(config: Partial<LoggerConfig> = {}) {\n const levelName = config.level ?? (getEnv(\"LOG_LEVEL\") as LogLevelName | undefined) ?? \"INFO\";\n this.level = LogLevel[levelName] ?? LogLevel.INFO;\n this.name = config.name;\n this.context = config.context ?? {};\n this.transports = config.transports ?? [\n new ConsoleTransport(\n config.pretty !== undefined ? { pretty: config.pretty } : {}\n ),\n ];\n this.redactFields = [...DEFAULT_REDACT_FIELDS, ...(config.redact ?? [])];\n\n if (config.timestamp === false) {\n this.timestampFn = () => \"\";\n } else if (typeof config.timestamp === \"function\") {\n this.timestampFn = config.timestamp;\n } else {\n this.timestampFn = () => new Date().toISOString();\n }\n }\n\n /**\n * Create a child logger with additional context\n */\n child(context: Record<string, unknown>): Logger {\n const levelEntry = Object.entries(LogLevel).find(([_, v]) => v === this.level);\n const levelName = levelEntry ? (levelEntry[0] as LogLevelName) : \"INFO\";\n\n const child = new Logger({\n level: levelName,\n name: this.name,\n context: { ...this.context, ...context },\n transports: this.transports,\n redact: this.redactFields,\n });\n return child;\n }\n\n /**\n * Log a message\n */\n private log(\n level: LogLevelName,\n message: string,\n context?: Record<string, unknown>,\n error?: Error\n ): void {\n const levelValue = LogLevel[level];\n if (levelValue < this.level) return;\n\n let finalContext = { ...this.context };\n if (this.name) {\n finalContext[\"module\"] = this.name;\n }\n if (context) {\n finalContext = { ...finalContext, ...context };\n }\n\n // Redact sensitive fields\n finalContext = redactFields(finalContext, this.redactFields);\n\n const entry: LogEntry = {\n level,\n levelValue,\n message,\n timestamp: this.timestampFn(),\n context: Object.keys(finalContext).length > 0 ? finalContext : undefined,\n error: error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : undefined,\n };\n\n for (const transport of this.transports) {\n transport.log(entry);\n }\n }\n\n trace(message: string, context?: Record<string, unknown>): void {\n this.log(\"TRACE\", message, context);\n }\n\n debug(message: string, context?: Record<string, unknown>): void {\n this.log(\"DEBUG\", message, context);\n }\n\n info(message: string, context?: Record<string, unknown>): void {\n this.log(\"INFO\", message, context);\n }\n\n warn(message: string, context?: Record<string, unknown>): void {\n this.log(\"WARN\", message, context);\n }\n\n error(message: string, error?: Error | unknown, context?: Record<string, unknown>): void {\n const err = error instanceof Error ? error : undefined;\n const ctx = error instanceof Error ? context : (error as Record<string, unknown> | undefined);\n this.log(\"ERROR\", message, ctx, err);\n }\n\n fatal(message: string, error?: Error | unknown, context?: Record<string, unknown>): void {\n const err = error instanceof Error ? error : undefined;\n const ctx = error instanceof Error ? context : (error as Record<string, unknown> | undefined);\n this.log(\"FATAL\", message, ctx, err);\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createLogger(config?: Partial<LoggerConfig>): Logger {\n return new Logger(config);\n}\n\n/**\n * Default logger instance\n */\nexport const logger = createLogger();\n\n/**\n * Utility: Log error with proper formatting\n */\nexport function logError(\n log: Logger,\n error: unknown,\n message: string,\n context?: Record<string, unknown>\n): void {\n if (error instanceof Error) {\n log.error(message, error, context);\n } else {\n log.error(message, { error: String(error), ...context });\n }\n}\n\n/**\n * Utility: Measure execution time\n */\nexport async function measureTime<T>(\n log: Logger,\n operation: string,\n fn: () => Promise<T>\n): Promise<T> {\n const start = Date.now();\n try {\n const result = await fn();\n const duration = Date.now() - start;\n log.info(`${operation} completed`, { operation, durationMs: duration });\n return result;\n } catch (error) {\n const duration = Date.now() - start;\n logError(log, error, `${operation} failed`, { operation, durationMs: duration });\n throw error;\n }\n}\n\n/**\n * Utility: Create request logger middleware context\n */\nexport function createRequestLogger(\n baseLogger: Logger,\n request: {\n method?: string;\n url?: string;\n requestId?: string;\n userId?: string;\n tenantId?: string;\n }\n): Logger {\n const pathname = request.url ? new URL(request.url).pathname : undefined;\n return baseLogger.child({\n requestId: request.requestId,\n method: request.method,\n path: pathname,\n userId: request.userId,\n tenantId: request.tenantId,\n });\n}\n","/**\n * @parsrun/core - Decimal Utilities\n * Precise decimal calculations for financial and quantity operations\n * Edge-compatible - no external dependencies\n */\n\n/**\n * Internal precision for calculations\n */\nconst PRECISION = 20;\n\n/**\n * Decimal class for precise arithmetic\n * Uses string-based arithmetic to avoid floating point issues\n */\nexport class Decimal {\n private value: string;\n\n constructor(value: number | string | Decimal) {\n if (value instanceof Decimal) {\n this.value = value.value;\n } else if (typeof value === \"number\") {\n this.value = this.normalizeNumber(value);\n } else {\n this.value = this.normalizeString(value);\n }\n }\n\n private normalizeNumber(n: number): string {\n if (!isFinite(n)) {\n throw new Error(`Invalid number: ${n}`);\n }\n return n.toFixed(PRECISION).replace(/\\.?0+$/, \"\") || \"0\";\n }\n\n private normalizeString(s: string): string {\n const trimmed = s.trim();\n if (!/^-?\\d*\\.?\\d+$/.test(trimmed)) {\n throw new Error(`Invalid decimal string: ${s}`);\n }\n return trimmed.replace(/^(-?)0+(?=\\d)/, \"$1\").replace(/\\.?0+$/, \"\") || \"0\";\n }\n\n /**\n * Add two decimals\n */\n add(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n return new Decimal(a + b);\n }\n\n /**\n * Subtract\n */\n sub(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n return new Decimal(a - b);\n }\n\n /**\n * Multiply\n */\n mul(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n return new Decimal(a * b);\n }\n\n /**\n * Divide\n */\n div(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n if (b === 0) {\n throw new Error(\"Division by zero\");\n }\n return new Decimal(a / b);\n }\n\n /**\n * Modulo\n */\n mod(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n return new Decimal(a % b);\n }\n\n /**\n * Power\n */\n pow(exp: number): Decimal {\n const a = parseFloat(this.value);\n return new Decimal(Math.pow(a, exp));\n }\n\n /**\n * Square root\n */\n sqrt(): Decimal {\n const a = parseFloat(this.value);\n if (a < 0) {\n throw new Error(\"Square root of negative number\");\n }\n return new Decimal(Math.sqrt(a));\n }\n\n /**\n * Absolute value\n */\n abs(): Decimal {\n const a = parseFloat(this.value);\n return new Decimal(Math.abs(a));\n }\n\n /**\n * Negate\n */\n neg(): Decimal {\n const a = parseFloat(this.value);\n return new Decimal(-a);\n }\n\n /**\n * Round to decimal places\n */\n round(decimals: number = 0): Decimal {\n const a = parseFloat(this.value);\n const factor = Math.pow(10, decimals);\n return new Decimal(Math.round(a * factor) / factor);\n }\n\n /**\n * Floor to decimal places\n */\n floor(decimals: number = 0): Decimal {\n const a = parseFloat(this.value);\n const factor = Math.pow(10, decimals);\n return new Decimal(Math.floor(a * factor) / factor);\n }\n\n /**\n * Ceiling to decimal places\n */\n ceil(decimals: number = 0): Decimal {\n const a = parseFloat(this.value);\n const factor = Math.pow(10, decimals);\n return new Decimal(Math.ceil(a * factor) / factor);\n }\n\n /**\n * Compare: returns -1, 0, or 1\n */\n cmp(other: number | string | Decimal): -1 | 0 | 1 {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n }\n\n /**\n * Equality check\n */\n eq(other: number | string | Decimal): boolean {\n return this.cmp(other) === 0;\n }\n\n /**\n * Greater than\n */\n gt(other: number | string | Decimal): boolean {\n return this.cmp(other) === 1;\n }\n\n /**\n * Greater than or equal\n */\n gte(other: number | string | Decimal): boolean {\n return this.cmp(other) >= 0;\n }\n\n /**\n * Less than\n */\n lt(other: number | string | Decimal): boolean {\n return this.cmp(other) === -1;\n }\n\n /**\n * Less than or equal\n */\n lte(other: number | string | Decimal): boolean {\n return this.cmp(other) <= 0;\n }\n\n /**\n * Check if zero\n */\n isZero(): boolean {\n return parseFloat(this.value) === 0;\n }\n\n /**\n * Check if positive\n */\n isPositive(): boolean {\n return parseFloat(this.value) > 0;\n }\n\n /**\n * Check if negative\n */\n isNegative(): boolean {\n return parseFloat(this.value) < 0;\n }\n\n /**\n * Convert to number\n */\n toNumber(): number {\n return parseFloat(this.value);\n }\n\n /**\n * Convert to string\n */\n toString(): string {\n return this.value;\n }\n\n /**\n * Format with fixed decimal places\n */\n toFixed(decimals: number = 2): string {\n return parseFloat(this.value).toFixed(decimals);\n }\n\n /**\n * Convert to JSON (string representation)\n */\n toJSON(): string {\n return this.value;\n }\n\n /**\n * Static: Create from value\n */\n static from(value: number | string | Decimal): Decimal {\n return new Decimal(value);\n }\n\n /**\n * Static: Sum array of values\n */\n static sum(values: (number | string | Decimal)[]): Decimal {\n return values.reduce<Decimal>(\n (acc, val) => acc.add(val),\n new Decimal(0)\n );\n }\n\n /**\n * Static: Average of array\n */\n static avg(values: (number | string | Decimal)[]): Decimal {\n if (values.length === 0) return new Decimal(0);\n return Decimal.sum(values).div(values.length);\n }\n\n /**\n * Static: Min of array\n */\n static min(...values: (number | string | Decimal)[]): Decimal {\n if (values.length === 0) throw new Error(\"No values provided\");\n return values.reduce<Decimal>((min, val) => {\n const d = new Decimal(val);\n return d.lt(min) ? d : min;\n }, new Decimal(values[0]!));\n }\n\n /**\n * Static: Max of array\n */\n static max(...values: (number | string | Decimal)[]): Decimal {\n if (values.length === 0) throw new Error(\"No values provided\");\n return values.reduce<Decimal>((max, val) => {\n const d = new Decimal(val);\n return d.gt(max) ? d : max;\n }, new Decimal(values[0]!));\n }\n}\n\n/**\n * Decimal utilities for database operations\n */\nexport const DecimalUtils = {\n /**\n * Convert number to database decimal string\n */\n toDecimalString(value: number | string | null | undefined): string | null {\n if (value === null || value === undefined) return null;\n return new Decimal(value).toString();\n },\n\n /**\n * Convert database decimal string to number\n */\n fromDecimalString(value: string | null | undefined): number {\n if (!value) return 0;\n return new Decimal(value).toNumber();\n },\n\n /**\n * Perform precise decimal multiplication\n */\n multiply(a: number | string, b: number | string): string {\n return new Decimal(a).mul(b).toString();\n },\n\n /**\n * Perform precise decimal addition\n */\n add(a: number | string, b: number | string): string {\n return new Decimal(a).add(b).toString();\n },\n\n /**\n * Perform precise decimal subtraction\n */\n subtract(a: number | string, b: number | string): string {\n return new Decimal(a).sub(b).toString();\n },\n\n /**\n * Perform precise decimal division\n */\n divide(a: number | string, b: number | string): string {\n return new Decimal(a).div(b).toString();\n },\n\n /**\n * Format decimal for display\n */\n format(value: string | number, decimalPlaces: number = 2): string {\n return new Decimal(value).toFixed(decimalPlaces);\n },\n\n /**\n * Format as currency\n */\n formatCurrency(\n value: string | number,\n options: {\n currency?: string;\n locale?: string;\n decimals?: number;\n } = {}\n ): string {\n const { currency = \"USD\", locale = \"en-US\", decimals = 2 } = options;\n const num = new Decimal(value).toNumber();\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n minimumFractionDigits: decimals,\n maximumFractionDigits: decimals,\n }).format(num);\n },\n\n /**\n * Convert object with decimal fields for database insert/update\n */\n prepareForDatabase<T extends Record<string, unknown>>(\n data: T,\n decimalFields: string[]\n ): T {\n const result = { ...data };\n for (const field of decimalFields) {\n if (field in result && result[field] !== undefined && result[field] !== null) {\n const value = result[field];\n if (typeof value === \"number\") {\n (result as Record<string, unknown>)[field] = DecimalUtils.toDecimalString(value);\n }\n }\n }\n return result;\n },\n\n /**\n * Convert object with decimal fields from database\n */\n parseFromDatabase<T extends Record<string, unknown>>(\n data: T,\n decimalFields: string[]\n ): T {\n const result = { ...data };\n for (const field of decimalFields) {\n if (field in result && result[field] !== undefined && result[field] !== null) {\n const value = result[field];\n if (typeof value === \"string\") {\n (result as Record<string, unknown>)[field] = DecimalUtils.fromDecimalString(value);\n }\n }\n }\n return result;\n },\n};\n\n/**\n * Shorthand for creating Decimal\n */\nexport function decimal(value: number | string): Decimal {\n return new Decimal(value);\n}\n","/**\n * @parsrun/core - Type Definitions\n */\n\n// ============================================\n// TENANT TYPES\n// ============================================\n\nexport interface Tenant {\n id: string;\n name: string;\n slug: string;\n status: TenantStatus;\n plan?: string;\n settings?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport type TenantStatus = \"active\" | \"suspended\" | \"pending\" | \"deleted\";\n\n// ============================================\n// USER TYPES\n// ============================================\n\nexport interface User {\n id: string;\n email: string;\n emailVerified: boolean;\n name?: string;\n avatarUrl?: string;\n twoFactorEnabled: boolean;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface Session {\n id: string;\n userId: string;\n tenantId: string;\n expiresAt: Date;\n ipAddress?: string;\n userAgent?: string;\n createdAt: Date;\n}\n\n// ============================================\n// MEMBERSHIP TYPES\n// ============================================\n\nexport interface TenantMembership {\n id: string;\n userId: string;\n tenantId: string;\n roleId?: string;\n permissions: MembershipPermissions;\n accessLevel: AccessLevel;\n resourceRestrictions: ResourceRestrictions;\n ipRestrictions?: IpRestrictions;\n timeRestrictions?: TimeRestrictions;\n status: MembershipStatus;\n expiresAt?: Date;\n invitedBy?: string;\n invitedAt?: Date;\n joinedAt?: Date;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport type MembershipStatus = \"pending\" | \"active\" | \"suspended\" | \"expired\" | \"revoked\";\n\nexport type AccessLevel = \"full\" | \"limited\" | \"readonly\" | \"custom\";\n\nexport interface MembershipPermissions {\n [resource: string]: string[];\n}\n\nexport interface ResourceRestrictions {\n locations?: string[];\n departments?: string[];\n projects?: string[];\n [key: string]: string[] | undefined;\n}\n\nexport interface IpRestrictions {\n allowedIps?: string[];\n allowedCidrs?: string[];\n deniedIps?: string[];\n}\n\nexport interface TimeRestrictions {\n timezone?: string;\n allowedDays?: number[]; // 0-6, Sunday = 0\n allowedHoursStart?: number; // 0-23\n allowedHoursEnd?: number; // 0-23\n}\n\n// ============================================\n// AUTH CONTEXT\n// ============================================\n\nexport interface AuthContext {\n user: User;\n session: Session;\n tenant: Tenant;\n membership: TenantMembership;\n}\n\n// ============================================\n// PAGINATION\n// ============================================\n\nexport interface PaginationParams {\n page?: number;\n limit?: number;\n cursor?: string;\n}\n\nexport interface PaginatedResult<T> {\n data: T[];\n pagination: {\n total: number;\n page: number;\n limit: number;\n totalPages: number;\n hasNext: boolean;\n hasPrev: boolean;\n nextCursor?: string;\n };\n}\n\n// ============================================\n// RESULT TYPES\n// ============================================\n\nexport type Result<T, E = Error> =\n | { success: true; data: T }\n | { success: false; error: E };\n\nexport function ok<T>(data: T): Result<T, never> {\n return { success: true, data };\n}\n\nexport function err<E>(error: E): Result<never, E> {\n return { success: false, error };\n}\n\n// ============================================\n// UTILITY TYPES\n// ============================================\n\nexport type Prettify<T> = {\n [K in keyof T]: T[K];\n} & {};\n\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\nexport type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<\n T,\n Exclude<keyof T, Keys>\n> &\n {\n [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;\n }[Keys];\n","/**\n * @module\n * Error classes for the Pars framework.\n * Provides typed errors for auth, validation, rate limiting, and more.\n *\n * @example\n * ```typescript\n * import { NotFoundError, ValidationError, UnauthorizedError } from '@parsrun/core';\n *\n * // Throw typed errors\n * throw new NotFoundError('User');\n * throw new ValidationError('Invalid input', [{ field: 'email', message: 'Invalid format' }]);\n * throw new UnauthorizedError('Token expired');\n * ```\n */\n\n/**\n * Base error class for all Pars framework errors.\n * Includes error code, HTTP status code, and optional details.\n *\n * @example\n * ```typescript\n * throw new ParsError('Something went wrong', 'CUSTOM_ERROR', 500, { extra: 'info' });\n * ```\n */\nexport class ParsError extends Error {\n public readonly code: string;\n public readonly statusCode: number;\n public readonly details: Record<string, unknown> | undefined;\n\n constructor(\n message: string,\n code: string,\n statusCode: number = 500,\n details?: Record<string, unknown>\n ) {\n super(message);\n this.name = \"ParsError\";\n this.code = code;\n this.statusCode = statusCode;\n this.details = details ?? undefined;\n Error.captureStackTrace?.(this, this.constructor);\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n statusCode: this.statusCode,\n details: this.details,\n };\n }\n}\n\n// ============================================\n// AUTH ERRORS\n// ============================================\n\n/** Base class for authentication-related errors (HTTP 401/403) */\nexport class AuthError extends ParsError {\n constructor(\n message: string,\n code: string = \"AUTH_ERROR\",\n statusCode: number = 401,\n details?: Record<string, unknown>\n ) {\n super(message, code, statusCode, details);\n this.name = \"AuthError\";\n }\n}\n\n/** User is not authenticated (HTTP 401) */\nexport class UnauthorizedError extends AuthError {\n constructor(message: string = \"Unauthorized\", details?: Record<string, unknown>) {\n super(message, \"UNAUTHORIZED\", 401, details);\n this.name = \"UnauthorizedError\";\n }\n}\n\n/** User lacks permission for the requested action (HTTP 403) */\nexport class ForbiddenError extends AuthError {\n constructor(message: string = \"Forbidden\", details?: Record<string, unknown>) {\n super(message, \"FORBIDDEN\", 403, details);\n this.name = \"ForbiddenError\";\n }\n}\n\nexport class InvalidCredentialsError extends AuthError {\n constructor(message: string = \"Invalid credentials\", details?: Record<string, unknown>) {\n super(message, \"INVALID_CREDENTIALS\", 401, details);\n this.name = \"InvalidCredentialsError\";\n }\n}\n\nexport class SessionExpiredError extends AuthError {\n constructor(message: string = \"Session expired\", details?: Record<string, unknown>) {\n super(message, \"SESSION_EXPIRED\", 401, details);\n this.name = \"SessionExpiredError\";\n }\n}\n\nexport class TwoFactorRequiredError extends AuthError {\n constructor(\n message: string = \"Two-factor authentication required\",\n public readonly challengeId: string,\n details?: Record<string, unknown>\n ) {\n super(message, \"TWO_FACTOR_REQUIRED\", 403, { ...details, challengeId });\n this.name = \"TwoFactorRequiredError\";\n }\n}\n\nexport class AccountLockedError extends AuthError {\n constructor(\n message: string = \"Account locked\",\n public readonly lockedUntil?: Date,\n details?: Record<string, unknown>\n ) {\n super(message, \"ACCOUNT_LOCKED\", 423, { ...details, lockedUntil });\n this.name = \"AccountLockedError\";\n }\n}\n\n// ============================================\n// TENANT ERRORS\n// ============================================\n\nexport class TenantError extends ParsError {\n constructor(\n message: string,\n code: string = \"TENANT_ERROR\",\n statusCode: number = 400,\n details?: Record<string, unknown>\n ) {\n super(message, code, statusCode, details);\n this.name = \"TenantError\";\n }\n}\n\nexport class TenantNotFoundError extends TenantError {\n constructor(message: string = \"Tenant not found\", details?: Record<string, unknown>) {\n super(message, \"TENANT_NOT_FOUND\", 404, details);\n this.name = \"TenantNotFoundError\";\n }\n}\n\nexport class TenantSuspendedError extends TenantError {\n constructor(message: string = \"Tenant suspended\", details?: Record<string, unknown>) {\n super(message, \"TENANT_SUSPENDED\", 403, details);\n this.name = \"TenantSuspendedError\";\n }\n}\n\nexport class MembershipError extends TenantError {\n constructor(\n message: string = \"Membership error\",\n code: string = \"MEMBERSHIP_ERROR\",\n statusCode: number = 400,\n details?: Record<string, unknown>\n ) {\n super(message, code, statusCode, details);\n this.name = \"MembershipError\";\n }\n}\n\nexport class MembershipNotFoundError extends MembershipError {\n constructor(message: string = \"Membership not found\", details?: Record<string, unknown>) {\n super(message, \"MEMBERSHIP_NOT_FOUND\", 404, details);\n this.name = \"MembershipNotFoundError\";\n }\n}\n\nexport class MembershipExpiredError extends MembershipError {\n constructor(message: string = \"Membership expired\", details?: Record<string, unknown>) {\n super(message, \"MEMBERSHIP_EXPIRED\", 403, details);\n this.name = \"MembershipExpiredError\";\n }\n}\n\n// ============================================\n// VALIDATION ERRORS\n// ============================================\n\n/** Request validation failed with one or more field errors (HTTP 400) */\nexport class ValidationError extends ParsError {\n constructor(\n message: string = \"Validation failed\",\n public readonly errors: ValidationErrorDetail[],\n details?: Record<string, unknown>\n ) {\n super(message, \"VALIDATION_ERROR\", 400, { ...details, errors });\n this.name = \"ValidationError\";\n }\n}\n\n/** Details about a single validation error */\nexport interface ValidationErrorDetail {\n /** Field path that failed validation */\n field: string;\n /** Human-readable error message */\n message: string;\n /** Optional error code for programmatic handling */\n code?: string;\n}\n\n// ============================================\n// RATE LIMIT ERRORS\n// ============================================\n\n/** Too many requests - rate limit exceeded (HTTP 429) */\nexport class RateLimitError extends ParsError {\n constructor(\n message: string = \"Rate limit exceeded\",\n public readonly retryAfter?: number,\n details?: Record<string, unknown>\n ) {\n super(message, \"RATE_LIMIT_EXCEEDED\", 429, { ...details, retryAfter });\n this.name = \"RateLimitError\";\n }\n}\n\n// ============================================\n// NOT FOUND ERRORS\n// ============================================\n\n/** Requested resource was not found (HTTP 404) */\nexport class NotFoundError extends ParsError {\n constructor(\n resource: string = \"Resource\",\n message?: string,\n details?: Record<string, unknown>\n ) {\n super(message ?? `${resource} not found`, \"NOT_FOUND\", 404, { ...details, resource });\n this.name = \"NotFoundError\";\n }\n}\n\n// ============================================\n// CONFLICT ERRORS\n// ============================================\n\n/** Resource conflict, such as duplicate entry (HTTP 409) */\nexport class ConflictError extends ParsError {\n constructor(message: string = \"Conflict\", details?: Record<string, unknown>) {\n super(message, \"CONFLICT\", 409, details);\n this.name = \"ConflictError\";\n }\n}\n\nexport class DuplicateError extends ConflictError {\n constructor(\n resource: string = \"Resource\",\n field?: string,\n details?: Record<string, unknown>\n ) {\n super(`${resource} already exists${field ? ` with this ${field}` : \"\"}`, {\n ...details,\n resource,\n field,\n });\n this.name = \"DuplicateError\";\n }\n}\n","/**\n * @parsrun/core - Error Code Catalog\n * Centralized error code definitions for the entire framework\n */\n\n/**\n * Error category for grouping and filtering\n */\nexport type ErrorCategory =\n | \"auth\"\n | \"tenant\"\n | \"validation\"\n | \"resource\"\n | \"rate_limit\"\n | \"server\"\n | \"database\"\n | \"external\";\n\n/**\n * Error code definition\n */\nexport interface ErrorCodeDefinition {\n readonly code: string;\n readonly status: number;\n readonly category: ErrorCategory;\n readonly retryable?: boolean;\n}\n\n/**\n * Centralized error code catalog\n * All error codes used throughout the framework are defined here\n */\nexport const ErrorCodes = {\n // ============================================================================\n // Authentication Errors (401, 403, 423)\n // ============================================================================\n AUTH_ERROR: {\n code: \"AUTH_ERROR\",\n status: 401,\n category: \"auth\",\n },\n UNAUTHORIZED: {\n code: \"UNAUTHORIZED\",\n status: 401,\n category: \"auth\",\n },\n FORBIDDEN: {\n code: \"FORBIDDEN\",\n status: 403,\n category: \"auth\",\n },\n INVALID_CREDENTIALS: {\n code: \"INVALID_CREDENTIALS\",\n status: 401,\n category: \"auth\",\n },\n SESSION_EXPIRED: {\n code: \"SESSION_EXPIRED\",\n status: 401,\n category: \"auth\",\n },\n TOKEN_EXPIRED: {\n code: \"TOKEN_EXPIRED\",\n status: 401,\n category: \"auth\",\n },\n TOKEN_INVALID: {\n code: \"TOKEN_INVALID\",\n status: 401,\n category: \"auth\",\n },\n TWO_FACTOR_REQUIRED: {\n code: \"TWO_FACTOR_REQUIRED\",\n status: 403,\n category: \"auth\",\n },\n TWO_FACTOR_INVALID: {\n code: \"TWO_FACTOR_INVALID\",\n status: 401,\n category: \"auth\",\n },\n ACCOUNT_LOCKED: {\n code: \"ACCOUNT_LOCKED\",\n status: 423,\n category: \"auth\",\n },\n ACCOUNT_DISABLED: {\n code: \"ACCOUNT_DISABLED\",\n status: 403,\n category: \"auth\",\n },\n PASSWORD_RESET_REQUIRED: {\n code: \"PASSWORD_RESET_REQUIRED\",\n status: 403,\n category: \"auth\",\n },\n\n // ============================================================================\n // Tenant Errors (400, 403, 404)\n // ============================================================================\n TENANT_ERROR: {\n code: \"TENANT_ERROR\",\n status: 400,\n category: \"tenant\",\n },\n TENANT_NOT_FOUND: {\n code: \"TENANT_NOT_FOUND\",\n status: 404,\n category: \"tenant\",\n },\n TENANT_SUSPENDED: {\n code: \"TENANT_SUSPENDED\",\n status: 403,\n category: \"tenant\",\n },\n TENANT_LIMIT_EXCEEDED: {\n code: \"TENANT_LIMIT_EXCEEDED\",\n status: 403,\n category: \"tenant\",\n },\n MEMBERSHIP_ERROR: {\n code: \"MEMBERSHIP_ERROR\",\n status: 400,\n category: \"tenant\",\n },\n MEMBERSHIP_NOT_FOUND: {\n code: \"MEMBERSHIP_NOT_FOUND\",\n status: 404,\n category: \"tenant\",\n },\n MEMBERSHIP_EXPIRED: {\n code: \"MEMBERSHIP_EXPIRED\",\n status: 403,\n category: \"tenant\",\n },\n\n // ============================================================================\n // Validation Errors (400, 422)\n // ============================================================================\n VALIDATION_ERROR: {\n code: \"VALIDATION_ERROR\",\n status: 400,\n category: \"validation\",\n },\n BAD_REQUEST: {\n code: \"BAD_REQUEST\",\n status: 400,\n category: \"validation\",\n },\n INVALID_INPUT: {\n code: \"INVALID_INPUT\",\n status: 422,\n category: \"validation\",\n },\n MISSING_REQUIRED_FIELD: {\n code: \"MISSING_REQUIRED_FIELD\",\n status: 400,\n category: \"validation\",\n },\n INVALID_FORMAT: {\n code: \"INVALID_FORMAT\",\n status: 400,\n category: \"validation\",\n },\n\n // ============================================================================\n // Resource Errors (404, 409, 410)\n // ============================================================================\n NOT_FOUND: {\n code: \"NOT_FOUND\",\n status: 404,\n category: \"resource\",\n },\n CONFLICT: {\n code: \"CONFLICT\",\n status: 409,\n category: \"resource\",\n },\n DUPLICATE: {\n code: \"DUPLICATE\",\n status: 409,\n category: \"resource\",\n },\n GONE: {\n code: \"GONE\",\n status: 410,\n category: \"resource\",\n },\n RESOURCE_LOCKED: {\n code: \"RESOURCE_LOCKED\",\n status: 423,\n category: \"resource\",\n },\n\n // ============================================================================\n // Rate Limiting (429)\n // ============================================================================\n RATE_LIMIT_EXCEEDED: {\n code: \"RATE_LIMIT_EXCEEDED\",\n status: 429,\n category: \"rate_limit\",\n retryable: true,\n },\n QUOTA_EXCEEDED: {\n code: \"QUOTA_EXCEEDED\",\n status: 429,\n category: \"rate_limit\",\n },\n\n // ============================================================================\n // Server Errors (500, 502, 503, 504)\n // ============================================================================\n INTERNAL_ERROR: {\n code: \"INTERNAL_ERROR\",\n status: 500,\n category: \"server\",\n },\n BAD_GATEWAY: {\n code: \"BAD_GATEWAY\",\n status: 502,\n category: \"server\",\n retryable: true,\n },\n SERVICE_UNAVAILABLE: {\n code: \"SERVICE_UNAVAILABLE\",\n status: 503,\n category: \"server\",\n retryable: true,\n },\n GATEWAY_TIMEOUT: {\n code: \"GATEWAY_TIMEOUT\",\n status: 504,\n category: \"server\",\n retryable: true,\n },\n\n // ============================================================================\n // Database Errors (500)\n // ============================================================================\n DATABASE_ERROR: {\n code: \"DATABASE_ERROR\",\n status: 500,\n category: \"database\",\n },\n CONNECTION_ERROR: {\n code: \"CONNECTION_ERROR\",\n status: 503,\n category: \"database\",\n retryable: true,\n },\n TRANSACTION_ERROR: {\n code: \"TRANSACTION_ERROR\",\n status: 500,\n category: \"database\",\n },\n RLS_ERROR: {\n code: \"RLS_ERROR\",\n status: 500,\n category: \"database\",\n },\n\n // ============================================================================\n // External Service Errors (502, 503)\n // ============================================================================\n EXTERNAL_SERVICE_ERROR: {\n code: \"EXTERNAL_SERVICE_ERROR\",\n status: 502,\n category: \"external\",\n retryable: true,\n },\n EXTERNAL_TIMEOUT: {\n code: \"EXTERNAL_TIMEOUT\",\n status: 504,\n category: \"external\",\n retryable: true,\n },\n} as const;\n\n/**\n * Error code type (union of all error code keys)\n */\nexport type ErrorCode = keyof typeof ErrorCodes;\n\n/**\n * Get error code definition by code string\n */\nexport function getErrorCode(code: string): ErrorCodeDefinition | undefined {\n return (ErrorCodes as Record<string, ErrorCodeDefinition>)[code];\n}\n\n/**\n * Get all error codes by category\n */\nexport function getErrorCodesByCategory(\n category: ErrorCategory\n): ErrorCodeDefinition[] {\n return Object.values(ErrorCodes).filter((e) => e.category === category);\n}\n\n/**\n * Check if an error code is retryable\n */\nexport function isRetryableError(code: string): boolean {\n const errorCode = getErrorCode(code);\n return errorCode?.retryable === true;\n}\n\n/**\n * Get HTTP status for an error code\n */\nexport function getStatusForCode(code: string): number {\n const errorCode = getErrorCode(code);\n return errorCode?.status ?? 500;\n}\n","/**\n * @parsrun/core - Axiom Transport\n * Log ingestion transport for Axiom (axiom.co)\n * Uses native fetch - works on all runtimes (Node, Deno, Bun, Workers)\n */\n\nimport type { LogEntry } from \"../logger.js\";\nimport type { LogTransport, BatchTransportOptions } from \"./types.js\";\n\n/**\n * Axiom transport options\n */\nexport interface AxiomTransportOptions extends BatchTransportOptions {\n /** Axiom API token */\n token: string;\n /** Dataset name to ingest logs into */\n dataset: string;\n /** Organization ID (optional, for personal tokens) */\n orgId?: string;\n /** Custom Axiom API URL (default: https://api.axiom.co) */\n apiUrl?: string;\n /** Callback for errors during ingestion */\n onError?: (error: Error, droppedCount: number) => void;\n}\n\n/**\n * Axiom log event structure\n */\ninterface AxiomEvent {\n _time: string;\n level: string;\n message: string;\n [key: string]: unknown;\n}\n\n/**\n * Axiom Transport\n * Batches logs and sends them to Axiom's ingest API\n */\nexport class AxiomTransport implements LogTransport {\n readonly name = \"axiom\";\n\n private buffer: AxiomEvent[] = [];\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private isFlushing = false;\n private readonly options: Required<\n Pick<AxiomTransportOptions, \"batchSize\" | \"flushInterval\" | \"apiUrl\">\n > &\n AxiomTransportOptions;\n\n constructor(options: AxiomTransportOptions) {\n this.options = {\n batchSize: 100,\n flushInterval: 5000,\n apiUrl: \"https://api.axiom.co\",\n ...options,\n };\n\n // Start flush interval if enabled\n if (this.options.flushInterval > 0) {\n this.flushTimer = setInterval(\n () => this.flush(),\n this.options.flushInterval\n );\n }\n }\n\n log(entry: LogEntry): void {\n if (this.options.enabled === false) return;\n\n const event: AxiomEvent = {\n _time: entry.timestamp,\n level: entry.level,\n message: entry.message,\n };\n\n // Add context fields\n if (entry.context) {\n Object.assign(event, entry.context);\n }\n\n // Add error fields\n if (entry.error) {\n event[\"error.name\"] = entry.error.name;\n event[\"error.message\"] = entry.error.message;\n event[\"error.stack\"] = entry.error.stack;\n }\n\n this.buffer.push(event);\n\n // Flush if buffer is full\n if (this.buffer.length >= this.options.batchSize) {\n this.flush();\n }\n }\n\n async flush(): Promise<void> {\n // Prevent concurrent flushes\n if (this.isFlushing || this.buffer.length === 0) return;\n\n this.isFlushing = true;\n const events = this.buffer;\n this.buffer = [];\n\n try {\n const response = await fetch(\n `${this.options.apiUrl}/v1/datasets/${this.options.dataset}/ingest`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.options.token}`,\n \"Content-Type\": \"application/json\",\n ...(this.options.orgId && {\n \"X-Axiom-Org-Id\": this.options.orgId,\n }),\n },\n body: JSON.stringify(events),\n }\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Axiom ingest failed: ${response.status} ${errorText}`);\n }\n } catch (error) {\n // Call error handler if provided\n if (this.options.onError) {\n this.options.onError(\n error instanceof Error ? error : new Error(String(error)),\n events.length\n );\n } else {\n // Silent fail by default - don't crash the app for logging failures\n console.error(\"[Axiom] Failed to send logs:\", error);\n }\n } finally {\n this.isFlushing = false;\n }\n }\n\n async close(): Promise<void> {\n // Stop flush timer\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n\n // Final flush\n await this.flush();\n }\n}\n\n/**\n * Create Axiom transport\n */\nexport function createAxiomTransport(\n options: AxiomTransportOptions\n): AxiomTransport {\n return new AxiomTransport(options);\n}\n","/**\n * @parsrun/core - Sentry Transport\n * Error tracking transport for Sentry\n *\n * Supports two modes:\n * 1. HTTP API mode (default) - Zero dependency, works on all runtimes\n * 2. SDK mode (BYOS) - Full features with user-provided Sentry SDK\n *\n * @example HTTP API mode (simple, universal)\n * ```typescript\n * const sentry = new SentryTransport({\n * dsn: 'https://xxx@sentry.io/123',\n * environment: 'production',\n * });\n * ```\n *\n * @example SDK mode (full features)\n * ```typescript\n * import * as Sentry from '@sentry/cloudflare'; // or @sentry/node\n *\n * Sentry.init({ dsn: '...' });\n *\n * const sentry = new SentryTransport({\n * client: Sentry,\n * });\n * ```\n */\n\nimport type { LogEntry } from \"../logger.js\";\nimport type {\n LogTransport,\n ErrorTransport,\n ErrorContext,\n ErrorUser,\n Breadcrumb,\n BaseTransportOptions,\n} from \"./types.js\";\n\n/**\n * Sentry SDK interface (minimal interface for BYOS)\n * Compatible with @sentry/node, @sentry/cloudflare, @sentry/browser, etc.\n */\nexport interface SentryClient {\n captureException(error: Error, hint?: unknown): string;\n captureMessage(message: string, level?: string): string;\n withScope(callback: (scope: SentryScope) => void): void;\n flush?(timeout?: number): Promise<boolean>;\n}\n\nexport interface SentryScope {\n setTag(key: string, value: string): void;\n setUser(user: { id: string; email?: string; [key: string]: unknown } | null): void;\n setExtra(key: string, value: unknown): void;\n setExtras(extras: Record<string, unknown>): void;\n setLevel(level: string): void;\n addBreadcrumb(breadcrumb: unknown): void;\n}\n\n/**\n * Parsed DSN components\n */\ninterface ParsedDSN {\n protocol: string;\n publicKey: string;\n host: string;\n projectId: string;\n}\n\n/**\n * Sentry transport options\n */\nexport interface SentryTransportOptions extends BaseTransportOptions {\n /**\n * Sentry DSN (required for HTTP mode)\n * Format: https://{publicKey}@{host}/{projectId}\n */\n dsn?: string;\n\n /**\n * Sentry SDK client (for BYOS mode)\n * Pass your initialized Sentry client for full SDK features\n */\n client?: SentryClient;\n\n /** Environment name (e.g., 'production', 'staging') */\n environment?: string;\n\n /** Release version */\n release?: string;\n\n /** Server name */\n serverName?: string;\n\n /** Sample rate for error events (0.0 to 1.0) */\n sampleRate?: number;\n\n /** Additional tags to add to all events */\n tags?: Record<string, string>;\n\n /** Callback before sending (return null to drop event) */\n beforeSend?: (event: SentryEvent) => SentryEvent | null;\n\n /** Callback for transport errors */\n onError?: (error: Error) => void;\n}\n\n/**\n * Sentry event structure (simplified)\n */\nexport interface SentryEvent {\n event_id: string;\n timestamp: string;\n platform: string;\n level: \"fatal\" | \"error\" | \"warning\" | \"info\" | \"debug\";\n logger?: string;\n transaction?: string;\n server_name?: string;\n release?: string;\n environment?: string;\n message?: { formatted: string };\n exception?: {\n values: Array<{\n type: string;\n value: string;\n stacktrace?: {\n frames: Array<{\n filename?: string;\n function?: string;\n lineno?: number;\n colno?: number;\n in_app?: boolean;\n }>;\n };\n }>;\n };\n tags?: Record<string, string>;\n extra?: Record<string, unknown>;\n user?: {\n id?: string;\n email?: string;\n username?: string;\n [key: string]: unknown;\n };\n breadcrumbs?: Array<{\n type?: string;\n category?: string;\n message?: string;\n data?: Record<string, unknown>;\n level?: string;\n timestamp?: number;\n }>;\n contexts?: Record<string, Record<string, unknown>>;\n}\n\n/**\n * Sentry Transport\n * Implements both LogTransport and ErrorTransport\n */\nexport class SentryTransport implements LogTransport, ErrorTransport {\n readonly name = \"sentry\";\n\n private readonly client?: SentryClient;\n private readonly dsn?: ParsedDSN;\n private readonly options: SentryTransportOptions;\n private user: ErrorUser | null = null;\n private contexts: Map<string, Record<string, unknown>> = new Map();\n private breadcrumbs: Breadcrumb[] = [];\n private readonly maxBreadcrumbs = 100;\n\n constructor(options: SentryTransportOptions) {\n this.options = {\n sampleRate: 1.0,\n ...options,\n };\n\n if (options.client) {\n this.client = options.client;\n } else if (options.dsn) {\n this.dsn = this.parseDSN(options.dsn);\n } else {\n throw new Error(\"SentryTransport requires either 'dsn' or 'client' option\");\n }\n }\n\n /**\n * Parse Sentry DSN\n */\n private parseDSN(dsn: string): ParsedDSN {\n const match = dsn.match(/^(https?):\\/\\/([^@]+)@([^/]+)\\/(.+)$/);\n if (!match || !match[1] || !match[2] || !match[3] || !match[4]) {\n throw new Error(`Invalid Sentry DSN: ${dsn}`);\n }\n return {\n protocol: match[1],\n publicKey: match[2],\n host: match[3],\n projectId: match[4],\n };\n }\n\n /**\n * LogTransport implementation\n * Only sends ERROR and FATAL level logs\n */\n log(entry: LogEntry): void {\n if (this.options.enabled === false) return;\n\n // Only capture errors\n if (entry.levelValue < 50) return; // ERROR = 50, FATAL = 60\n\n if (entry.error) {\n const error = new Error(entry.error.message);\n error.name = entry.error.name;\n if (entry.error.stack) {\n error.stack = entry.error.stack;\n }\n\n this.captureException(\n error,\n entry.context ? { extra: entry.context } : undefined\n );\n } else {\n this.captureMessage(\n entry.message,\n entry.level === \"FATAL\" ? \"error\" : \"warning\",\n entry.context ? { extra: entry.context } : undefined\n );\n }\n }\n\n /**\n * Capture an exception\n */\n captureException(error: Error, context?: ErrorContext): void {\n if (this.options.enabled === false) return;\n if (!this.shouldSample()) return;\n\n if (this.client) {\n this.captureWithSdk(error, context);\n } else {\n this.captureWithHttp(error, context);\n }\n }\n\n /**\n * Capture a message\n */\n captureMessage(\n message: string,\n level: \"info\" | \"warning\" | \"error\",\n context?: ErrorContext\n ): void {\n if (this.options.enabled === false) return;\n if (!this.shouldSample()) return;\n\n if (this.client) {\n this.client.withScope((scope) => {\n this.applyContext(scope, context);\n scope.setLevel(level);\n this.client!.captureMessage(message, level);\n });\n } else {\n this.sendHttpEvent({\n level: level === \"warning\" ? \"warning\" : level === \"info\" ? \"info\" : \"error\",\n message: { formatted: message },\n ...this.buildEventContext(context),\n });\n }\n }\n\n /**\n * Set user context\n */\n setUser(user: ErrorUser | null): void {\n this.user = user;\n }\n\n /**\n * Set custom context\n */\n setContext(name: string, context: Record<string, unknown>): void {\n this.contexts.set(name, context);\n }\n\n /**\n * Add breadcrumb\n */\n addBreadcrumb(breadcrumb: Breadcrumb): void {\n this.breadcrumbs.push({\n ...breadcrumb,\n timestamp: breadcrumb.timestamp ?? Date.now() / 1000,\n });\n\n // Keep only last N breadcrumbs\n if (this.breadcrumbs.length > this.maxBreadcrumbs) {\n this.breadcrumbs = this.breadcrumbs.slice(-this.maxBreadcrumbs);\n }\n }\n\n /**\n * Flush pending events\n */\n async flush(): Promise<void> {\n if (this.client?.flush) {\n await this.client.flush(2000);\n }\n }\n\n // ============================================================================\n // Private Methods\n // ============================================================================\n\n private shouldSample(): boolean {\n const rate = this.options.sampleRate ?? 1.0;\n return Math.random() < rate;\n }\n\n /**\n * Capture with SDK (BYOS mode)\n */\n private captureWithSdk(error: Error, context?: ErrorContext): void {\n this.client!.withScope((scope) => {\n this.applyContext(scope, context);\n this.client!.captureException(error);\n });\n }\n\n /**\n * Apply context to SDK scope\n */\n private applyContext(scope: SentryScope, context?: ErrorContext): void {\n // User\n if (this.user) {\n scope.setUser(this.user);\n } else if (context?.userId) {\n scope.setUser({ id: context.userId });\n }\n\n // Tags\n if (this.options.tags) {\n for (const [key, value] of Object.entries(this.options.tags)) {\n scope.setTag(key, value);\n }\n }\n if (context?.tags) {\n for (const [key, value] of Object.entries(context.tags)) {\n scope.setTag(key, value);\n }\n }\n if (context?.requestId) {\n scope.setTag(\"requestId\", context.requestId);\n }\n if (context?.tenantId) {\n scope.setTag(\"tenantId\", context.tenantId);\n }\n\n // Extra\n if (context?.extra) {\n scope.setExtras(context.extra);\n }\n\n // Breadcrumbs\n for (const bc of this.breadcrumbs) {\n scope.addBreadcrumb(bc);\n }\n }\n\n /**\n * Capture with HTTP API (default mode)\n */\n private captureWithHttp(error: Error, context?: ErrorContext): void {\n const stacktrace = this.parseStackTrace(error.stack);\n const exceptionValue: {\n type: string;\n value: string;\n stacktrace?: { frames: Array<{ filename?: string; function?: string; lineno?: number; colno?: number }> };\n } = {\n type: error.name,\n value: error.message,\n };\n\n if (stacktrace) {\n exceptionValue.stacktrace = stacktrace;\n }\n\n const event: Partial<SentryEvent> = {\n level: \"error\",\n exception: {\n values: [exceptionValue],\n },\n ...this.buildEventContext(context),\n };\n\n this.sendHttpEvent(event);\n }\n\n /**\n * Build event context for HTTP API\n */\n private buildEventContext(context?: ErrorContext): Partial<SentryEvent> {\n const event: Partial<SentryEvent> = {};\n\n // Environment & Release\n if (this.options.environment) {\n event.environment = this.options.environment;\n }\n if (this.options.release) {\n event.release = this.options.release;\n }\n if (this.options.serverName) {\n event.server_name = this.options.serverName;\n }\n\n // Tags\n const tags: Record<string, string> = { ...this.options.tags };\n if (context?.tags) {\n Object.assign(tags, context.tags);\n }\n if (context?.requestId) {\n tags[\"requestId\"] = context.requestId;\n }\n if (context?.tenantId) {\n tags[\"tenantId\"] = context.tenantId;\n }\n if (Object.keys(tags).length > 0) {\n event.tags = tags;\n }\n\n // Extra\n if (context?.extra) {\n event.extra = context.extra;\n }\n\n // User\n if (this.user) {\n event.user = this.user;\n } else if (context?.userId) {\n event.user = { id: context.userId };\n }\n\n // Breadcrumbs\n if (this.breadcrumbs.length > 0) {\n event.breadcrumbs = this.breadcrumbs.map((bc) => {\n const crumb: {\n type?: string;\n category?: string;\n message?: string;\n data?: Record<string, unknown>;\n level?: string;\n timestamp?: number;\n } = {};\n if (bc.type) crumb.type = bc.type;\n if (bc.category) crumb.category = bc.category;\n if (bc.message) crumb.message = bc.message;\n if (bc.data) crumb.data = bc.data;\n if (bc.level) crumb.level = bc.level;\n if (bc.timestamp !== undefined) crumb.timestamp = bc.timestamp;\n return crumb;\n });\n }\n\n // Contexts\n if (this.contexts.size > 0) {\n event.contexts = Object.fromEntries(this.contexts);\n }\n\n return event;\n }\n\n /**\n * Parse error stack trace into Sentry format\n */\n private parseStackTrace(\n stack?: string\n ): { frames: Array<{ filename?: string; function?: string; lineno?: number; colno?: number }> } | undefined {\n if (!stack) return undefined;\n\n const lines = stack.split(\"\\n\").slice(1); // Skip first line (error message)\n const frames: Array<{ filename?: string; function?: string; lineno?: number; colno?: number }> = [];\n\n for (const line of lines) {\n // Parse V8 stack trace format\n const match = line.match(/^\\s*at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/);\n if (match && match[3] && match[4]) {\n const frame: { filename?: string; function?: string; lineno?: number; colno?: number } = {\n function: match[1] || \"<anonymous>\",\n lineno: parseInt(match[3], 10),\n colno: parseInt(match[4], 10),\n };\n if (match[2]) {\n frame.filename = match[2];\n }\n frames.push(frame);\n }\n }\n\n // Sentry expects oldest frame first\n frames.reverse();\n\n return frames.length > 0 ? { frames } : undefined;\n }\n\n /**\n * Generate event ID\n */\n private generateEventId(): string {\n // 32 character hex string\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n }\n\n /**\n * Send event via HTTP API\n */\n private async sendHttpEvent(eventData: Partial<SentryEvent>): Promise<void> {\n if (!this.dsn) return;\n\n const event: SentryEvent = {\n event_id: this.generateEventId(),\n timestamp: new Date().toISOString(),\n platform: \"javascript\",\n level: \"error\",\n ...eventData,\n };\n\n // Apply beforeSend hook\n if (this.options.beforeSend) {\n const result = this.options.beforeSend(event);\n if (result === null) return;\n }\n\n const url = `${this.dsn.protocol}://${this.dsn.host}/api/${this.dsn.projectId}/store/`;\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Sentry-Auth\": [\n \"Sentry sentry_version=7\",\n `sentry_client=pars-sentry/1.0.0`,\n `sentry_key=${this.dsn.publicKey}`,\n ].join(\", \"),\n },\n body: JSON.stringify(event),\n });\n\n if (!response.ok) {\n throw new Error(`Sentry API error: ${response.status}`);\n }\n } catch (error) {\n if (this.options.onError) {\n this.options.onError(error instanceof Error ? error : new Error(String(error)));\n }\n // Silent fail - don't crash the app for logging failures\n }\n }\n}\n\n/**\n * Create Sentry transport\n */\nexport function createSentryTransport(options: SentryTransportOptions): SentryTransport {\n return new SentryTransport(options);\n}\n","/**\n * @parsrun/core - Logtape Transport\n * Structured logging transport for Logtape (@logtape/logtape)\n *\n * Logtape is a TypeScript-first structured logging library.\n * This transport bridges Pars Logger to Logtape for advanced logging scenarios.\n *\n * @example BYOS (Bring Your Own SDK)\n * ```typescript\n * import { getLogger, configure } from '@logtape/logtape';\n *\n * // Configure Logtape\n * await configure({\n * sinks: { console: consoleSink() },\n * loggers: [{ category: 'pars', sinks: ['console'], level: 'info' }],\n * });\n *\n * const logtapeLogger = getLogger('pars');\n * const transport = new LogtapeTransport({ logger: logtapeLogger });\n * ```\n *\n * @example Simple mode (creates internal logger)\n * ```typescript\n * const transport = new LogtapeTransport({\n * category: 'my-app',\n * });\n * ```\n */\n\nimport type { LogEntry, LogLevelName } from \"../logger.js\";\nimport type { LogTransport, BaseTransportOptions } from \"./types.js\";\n\n/**\n * Logtape Logger interface (minimal interface for BYOS)\n * Compatible with @logtape/logtape getLogger() return type\n */\nexport interface LogtapeLogger {\n debug(message: string, properties?: Record<string, unknown>): void;\n info(message: string, properties?: Record<string, unknown>): void;\n warn(message: string, properties?: Record<string, unknown>): void;\n warning(message: string, properties?: Record<string, unknown>): void;\n error(message: string, properties?: Record<string, unknown>): void;\n fatal(message: string, properties?: Record<string, unknown>): void;\n}\n\n/**\n * Level mapping from Pars to Logtape\n */\ntype LogtapeLevel = \"debug\" | \"info\" | \"warning\" | \"error\" | \"fatal\";\n\n/**\n * Logtape transport options\n */\nexport interface LogtapeTransportOptions extends BaseTransportOptions {\n /**\n * Logtape logger instance (for BYOS mode)\n * Get this from @logtape/logtape's getLogger()\n */\n logger?: LogtapeLogger;\n\n /**\n * Category name for the logger\n * Only used if logger is not provided (creates a simple fallback logger)\n */\n category?: string;\n\n /**\n * Include timestamp in properties\n * @default true\n */\n includeTimestamp?: boolean;\n\n /**\n * Include level value in properties\n * @default false\n */\n includeLevelValue?: boolean;\n}\n\n/**\n * Simple fallback logger when no Logtape instance is provided\n * Just outputs structured JSON - users should use BYOS for full features\n */\nclass FallbackLogger implements LogtapeLogger {\n constructor(private category: string) {}\n\n private log(level: string, message: string, properties?: Record<string, unknown>): void {\n const entry = {\n level,\n category: this.category,\n msg: message,\n time: new Date().toISOString(),\n ...properties,\n };\n console.log(JSON.stringify(entry));\n }\n\n debug(message: string, properties?: Record<string, unknown>): void {\n this.log(\"debug\", message, properties);\n }\n\n info(message: string, properties?: Record<string, unknown>): void {\n this.log(\"info\", message, properties);\n }\n\n warn(message: string, properties?: Record<string, unknown>): void {\n this.log(\"warn\", message, properties);\n }\n\n warning(message: string, properties?: Record<string, unknown>): void {\n this.log(\"warning\", message, properties);\n }\n\n error(message: string, properties?: Record<string, unknown>): void {\n this.log(\"error\", message, properties);\n }\n\n fatal(message: string, properties?: Record<string, unknown>): void {\n this.log(\"fatal\", message, properties);\n }\n}\n\n/**\n * Logtape Transport\n * Bridges Pars Logger to Logtape\n */\nexport class LogtapeTransport implements LogTransport {\n readonly name = \"logtape\";\n\n private readonly logger: LogtapeLogger;\n private readonly includeTimestamp: boolean;\n private readonly includeLevelValue: boolean;\n private readonly enabled: boolean;\n\n constructor(options: LogtapeTransportOptions = {}) {\n this.enabled = options.enabled !== false;\n this.includeTimestamp = options.includeTimestamp !== false;\n this.includeLevelValue = options.includeLevelValue ?? false;\n\n if (options.logger) {\n this.logger = options.logger;\n } else {\n // Create fallback logger\n this.logger = new FallbackLogger(options.category ?? \"pars\");\n }\n }\n\n log(entry: LogEntry): void {\n if (!this.enabled) return;\n\n const level = this.mapLevel(entry.level);\n const properties = this.buildProperties(entry);\n\n // Call the appropriate log method\n this.logger[level](entry.message, properties);\n }\n\n /**\n * Map Pars log level to Logtape level\n */\n private mapLevel(level: LogLevelName): LogtapeLevel {\n const mapping: Record<LogLevelName, LogtapeLevel> = {\n TRACE: \"debug\",\n DEBUG: \"debug\",\n INFO: \"info\",\n WARN: \"warning\",\n ERROR: \"error\",\n FATAL: \"fatal\",\n SILENT: \"debug\", // Should never be logged\n };\n return mapping[level];\n }\n\n /**\n * Build properties object for Logtape\n */\n private buildProperties(entry: LogEntry): Record<string, unknown> {\n const properties: Record<string, unknown> = {};\n\n // Add timestamp if enabled\n if (this.includeTimestamp) {\n properties[\"timestamp\"] = entry.timestamp;\n }\n\n // Add level value if enabled\n if (this.includeLevelValue) {\n properties[\"levelValue\"] = entry.levelValue;\n }\n\n // Add context\n if (entry.context) {\n Object.assign(properties, entry.context);\n }\n\n // Add error info\n if (entry.error) {\n properties[\"error\"] = {\n name: entry.error.name,\n message: entry.error.message,\n stack: entry.error.stack,\n };\n }\n\n return properties;\n }\n}\n\n/**\n * Create Logtape transport\n */\nexport function createLogtapeTransport(\n options?: LogtapeTransportOptions\n): LogtapeTransport {\n return new LogtapeTransport(options);\n}\n","/**\n * @module\n * Core utilities and types for the Pars framework.\n * Edge-compatible with zero dependencies - works in Node.js, Deno, Bun, and Cloudflare Workers.\n *\n * @example\n * ```typescript\n * import {\n * // Runtime detection\n * runtime, isNode, isDeno, isBun, isCloudflare,\n * // Environment\n * getEnv, requireEnv, isDevelopment,\n * // Logging\n * createLogger, logger,\n * // Errors\n * ParsError, ValidationError, NotFoundError,\n * // Utilities\n * generateId, sha256, retry, sleep\n * } from '@parsrun/core';\n *\n * // Create a logger\n * const log = createLogger({ name: 'my-service' });\n * log.info('Service started', { port: 3000 });\n *\n * // Use runtime detection\n * if (isCloudflare()) {\n * // Cloudflare-specific code\n * }\n * ```\n */\n\n// ============================================\n// RUNTIME & ENVIRONMENT\n// ============================================\n\nexport {\n detectRuntime,\n runtime,\n runtimeInfo,\n isNode,\n isDeno,\n isBun,\n isCloudflare,\n isEdge,\n isBrowser,\n isServer,\n getRuntimeVersion,\n type Runtime,\n} from \"./runtime.js\";\n\nexport {\n getEnv,\n requireEnv,\n getEnvNumber,\n getEnvFloat,\n getEnvBoolean,\n getEnvArray,\n getEnvJson,\n setEdgeEnv,\n clearEdgeEnv,\n isDevelopment,\n isProduction,\n isTest,\n getEnvMode,\n createEnvConfig,\n type EnvMode,\n} from \"./env.js\";\n\n// ============================================\n// LOGGING\n// ============================================\n\nexport {\n Logger,\n ConsoleTransport,\n LogLevel,\n createLogger,\n logger,\n logError,\n measureTime,\n createRequestLogger,\n type LogLevelName,\n type LogLevelValue,\n type LogEntry,\n type LogTransport,\n type LoggerConfig,\n} from \"./logger.js\";\n\n// ============================================\n// DECIMAL / MATH\n// ============================================\n\nexport {\n Decimal,\n DecimalUtils,\n decimal,\n} from \"./decimal.js\";\n\n// ============================================\n// TYPES\n// ============================================\n\nexport * from \"./types.js\";\n\n// ============================================\n// ERRORS\n// ============================================\n\nexport * from \"./errors.js\";\n\n// ============================================\n// ERROR CODES\n// ============================================\n\nexport {\n ErrorCodes,\n getErrorCode,\n getErrorCodesByCategory,\n isRetryableError,\n getStatusForCode,\n type ErrorCode,\n type ErrorCategory,\n type ErrorCodeDefinition,\n} from \"./error-codes.js\";\n\n// ============================================\n// TRANSPORTS (additional - ConsoleTransport already in logger.js)\n// ============================================\n\nexport {\n // Error transport types (LogTransport is in logger.js)\n type ErrorTransport,\n type CombinedTransport,\n type ErrorContext,\n type ErrorUser,\n type Breadcrumb,\n type BaseTransportOptions,\n type BatchTransportOptions,\n // Axiom\n AxiomTransport,\n createAxiomTransport,\n type AxiomTransportOptions,\n // Sentry\n SentryTransport,\n createSentryTransport,\n type SentryTransportOptions,\n type SentryClient,\n type SentryEvent,\n // Logtape\n LogtapeTransport,\n createLogtapeTransport,\n type LogtapeTransportOptions,\n type LogtapeLogger,\n} from \"./transports/index.js\";\n\n// ============================================\n// UTILITY FUNCTIONS\n// ============================================\n\n/**\n * Generate a cryptographically secure random string (hex).\n *\n * @param length - Number of random bytes (output will be 2x this length in hex)\n * @returns Promise resolving to a hex string\n *\n * @example\n * ```typescript\n * const token = await generateRandomString(32); // 64 character hex string\n * ```\n */\nexport async function generateRandomString(length: number): Promise<string> {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Generate a UUID v4 using the Web Crypto API.\n *\n * @returns A new UUID v4 string\n *\n * @example\n * ```typescript\n * const id = generateId(); // \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\nexport function generateId(): string {\n return crypto.randomUUID();\n}\n\n/**\n * Hash a string using SHA-256 and return as hex string.\n *\n * @param input - The string to hash\n * @returns Promise resolving to the hex-encoded hash\n *\n * @example\n * ```typescript\n * const hash = await sha256('password123');\n * ```\n */\nexport async function sha256(input: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(input);\n const hash = await crypto.subtle.digest(\"SHA-256\", data);\n return Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Hash a string using SHA-256 and return as ArrayBuffer\n */\nexport async function sha256Bytes(input: string): Promise<ArrayBuffer> {\n const encoder = new TextEncoder();\n const data = encoder.encode(input);\n return crypto.subtle.digest(\"SHA-256\", data);\n}\n\n/**\n * Constant-time string comparison (timing-safe).\n * Use this for comparing secrets to prevent timing attacks.\n *\n * @param a - First string to compare\n * @param b - Second string to compare\n * @returns True if strings are equal\n *\n * @example\n * ```typescript\n * if (constantTimeEquals(providedToken, storedToken)) {\n * // Token is valid\n * }\n * ```\n */\nexport function constantTimeEquals(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n const aBytes = new TextEncoder().encode(a);\n const bBytes = new TextEncoder().encode(b);\n\n let result = 0;\n for (let i = 0; i < aBytes.length; i++) {\n result |= aBytes[i]! ^ bBytes[i]!;\n }\n\n return result === 0;\n}\n\n/**\n * Sleep for a given number of milliseconds.\n *\n * @param ms - Milliseconds to sleep\n * @returns Promise that resolves after the delay\n *\n * @example\n * ```typescript\n * await sleep(1000); // Wait 1 second\n * ```\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry a function with exponential backoff.\n *\n * @param fn - The async function to retry\n * @param options - Retry configuration options\n * @returns Promise resolving to the function result\n * @throws The last error if all retries fail\n *\n * @example\n * ```typescript\n * const data = await retry(\n * () => fetchFromAPI('/users'),\n * {\n * maxRetries: 3,\n * initialDelayMs: 1000,\n * shouldRetry: (err) => err.status >= 500\n * }\n * );\n * ```\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n options: {\n maxRetries?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n backoffMultiplier?: number;\n shouldRetry?: (error: unknown) => boolean;\n onRetry?: (error: unknown, attempt: number) => void;\n } = {}\n): Promise<T> {\n const {\n maxRetries = 3,\n initialDelayMs = 1000,\n maxDelayMs = 30000,\n backoffMultiplier = 2,\n shouldRetry = () => true,\n onRetry,\n } = options;\n\n let lastError: unknown;\n let delay = initialDelayMs;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n\n if (attempt === maxRetries || !shouldRetry(error)) {\n throw error;\n }\n\n onRetry?.(error, attempt + 1);\n await sleep(delay);\n delay = Math.min(delay * backoffMultiplier, maxDelayMs);\n }\n }\n\n throw lastError;\n}\n\n/**\n * Omit keys from an object\n */\nexport function omit<T extends object, K extends keyof T>(\n obj: T,\n keys: K[]\n): Omit<T, K> {\n const result = { ...obj };\n for (const key of keys) {\n delete result[key];\n }\n return result;\n}\n\n/**\n * Pick keys from an object\n */\nexport function pick<T extends object, K extends keyof T>(\n obj: T,\n keys: K[]\n): Pick<T, K> {\n const result = {} as Pick<T, K>;\n for (const key of keys) {\n if (key in obj) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n\n/**\n * Deep merge two objects recursively.\n *\n * @param target - The target object\n * @param source - The source object to merge from\n * @returns A new merged object\n *\n * @example\n * ```typescript\n * const config = deepMerge(defaults, userConfig);\n * ```\n */\nexport function deepMerge<T extends object>(target: T, source: Partial<T>): T {\n const result = { ...target };\n\n for (const key of Object.keys(source) as (keyof T)[]) {\n const sourceValue = source[key];\n const targetValue = target[key];\n\n if (\n sourceValue !== undefined &&\n typeof sourceValue === \"object\" &&\n sourceValue !== null &&\n !Array.isArray(sourceValue) &&\n typeof targetValue === \"object\" &&\n targetValue !== null &&\n !Array.isArray(targetValue)\n ) {\n result[key] = deepMerge(\n targetValue as object,\n sourceValue as object\n ) as T[keyof T];\n } else if (sourceValue !== undefined) {\n result[key] = sourceValue as T[keyof T];\n }\n }\n\n return result;\n}\n\n/**\n * Deep clone an object\n */\nexport function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(deepClone) as T;\n }\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as T;\n }\n const cloned = {} as T;\n for (const key of Object.keys(obj) as (keyof T)[]) {\n cloned[key] = deepClone(obj[key]);\n }\n return cloned;\n}\n\n/**\n * Check if a value is a plain object\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\n/**\n * Check if value is null or undefined\n */\nexport function isNil(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * Check if value is empty (null, undefined, empty string, empty array, empty object)\n */\nexport function isEmpty(value: unknown): boolean {\n if (isNil(value)) return true;\n if (typeof value === \"string\") return value.trim() === \"\";\n if (Array.isArray(value)) return value.length === 0;\n if (isPlainObject(value)) return Object.keys(value).length === 0;\n return false;\n}\n\n/**\n * Normalize email address\n */\nexport function normalizeEmail(email: string): string {\n return email.toLowerCase().trim();\n}\n\n/**\n * Validate email format\n */\nexport function isValidEmail(email: string): boolean {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n\n/**\n * Generate a URL-friendly slug from a string\n */\nexport function slugify(str: string): string {\n return str\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\n/**\n * Truncate string to a maximum length\n */\nexport function truncate(str: string, maxLength: number, suffix: string = \"...\"): string {\n if (str.length <= maxLength) return str;\n return str.slice(0, maxLength - suffix.length) + suffix;\n}\n\n/**\n * Debounce a function\n */\nexport function debounce<T extends (...args: unknown[]) => unknown>(\n fn: T,\n wait: number\n): (...args: Parameters<T>) => void {\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n return (...args: Parameters<T>) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n fn(...args);\n timeoutId = null;\n }, wait);\n };\n}\n\n/**\n * Throttle a function\n */\nexport function throttle<T extends (...args: unknown[]) => unknown>(\n fn: T,\n wait: number\n): (...args: Parameters<T>) => void {\n let lastTime = 0;\n\n return (...args: Parameters<T>) => {\n const now = Date.now();\n if (now - lastTime >= wait) {\n lastTime = now;\n fn(...args);\n }\n };\n}\n\n/**\n * Create a deferred promise\n */\nexport function createDeferred<T>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (reason?: unknown) => void;\n} {\n let resolve!: (value: T) => void;\n let reject!: (reason?: unknown) => void;\n\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return { promise, resolve, reject };\n}\n\n/**\n * Run promises with concurrency limit.\n *\n * @param tasks - Array of async functions to execute\n * @param concurrency - Maximum concurrent tasks\n * @returns Promise resolving to array of results in order\n *\n * @example\n * ```typescript\n * const results = await pLimit(\n * urls.map(url => () => fetch(url)),\n * 5 // Max 5 concurrent requests\n * );\n * ```\n */\nexport async function pLimit<T>(\n tasks: (() => Promise<T>)[],\n concurrency: number\n): Promise<T[]> {\n const results: T[] = [];\n const executing: Promise<void>[] = [];\n\n for (const [index, task] of tasks.entries()) {\n const p = Promise.resolve().then(async () => {\n results[index] = await task();\n });\n\n executing.push(p);\n\n if (executing.length >= concurrency) {\n await Promise.race(executing);\n executing.splice(\n executing.findIndex((e) => e === p),\n 1\n );\n }\n }\n\n await Promise.all(executing);\n return results;\n}\n"],"mappings":";AA0BO,SAAS,gBAAyB;AAEvC,MAAI,OAAO,eAAe,eAAe,SAAS,YAAY;AAC5D,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,eAAe,eAAe,UAAU,YAAY;AAC7D,WAAO;AAAA,EACT;AAGA,MACE,OAAO,eAAe,eACtB,OAAQ,WAAmB,WAAW,eACtC,OAAQ,WAAmB,YAAY,aACvC;AACA,WAAO;AAAA,EACT;AAGA,MACE,OAAO,eAAe,eACtB,OAAQ,WAAmB,gBAAgB,aAC3C;AACA,WAAO;AAAA,EACT;AAGA,MACE,OAAO,eAAe,eACtB,OAAQ,WAAmB,WAAW,eACtC,OAAQ,WAAmB,aAAa,aACxC;AACA,WAAO;AAAA,EACT;AAGA,MACE,OAAO,YAAY,eACnB,QAAQ,YACR,QAAQ,SAAS,MACjB;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKO,IAAM,UAAU,cAAc;AAK9B,IAAM,cAAc;AAAA,EACzB;AAAA,EACA,QAAQ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IACZ;AAAA,EACF;AACF;AAKO,SAAS,iBAId;AACA,MAAI;AACJ,MAAI;AAEJ,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AAED,SAAO,EAAE,SAAS,SAAS,OAAO;AACpC;AAiBA,eAAsB,OACpB,OACA,aACc;AACd,QAAM,UAAe,CAAC;AACtB,QAAM,YAA6B,CAAC;AAEpC,aAAW,CAAC,OAAO,IAAI,KAAK,MAAM,QAAQ,GAAG;AAC3C,UAAM,IAAI,QAAQ,QAAQ,EAAE,KAAK,YAAY;AAC3C,cAAQ,KAAK,IAAI,MAAM,KAAK;AAAA,IAC9B,CAAC;AAED,cAAU,KAAK,CAAC;AAEhB,QAAI,UAAU,UAAU,aAAa;AACnC,YAAM,QAAQ,KAAK,SAAS;AAC5B,gBAAU;AAAA,QACR,UAAU,UAAU,CAAC,MAAM,MAAM,CAAC;AAAA,QAClC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,QAAM,QAAQ,IAAI,SAAS;AAC3B,SAAO;AACT;","names":["err"]}
|
|
1
|
+
{"version":3,"sources":["../src/runtime.ts","../src/env.ts","../src/transports/console.ts","../src/logger.ts","../src/decimal.ts","../src/types.ts","../src/errors.ts","../src/error-codes.ts","../src/transports/axiom.ts","../src/transports/sentry.ts","../src/transports/logtape.ts","../src/index.ts"],"sourcesContent":["/**\n * @module\n * Runtime detection for Node.js, Deno, Bun, and Cloudflare Workers.\n * Detects the current JavaScript runtime and provides helper functions.\n *\n * @example\n * ```typescript\n * import { runtime, isNode, isDeno, isBun, isCloudflare, getRuntimeVersion } from '@parsrun/core';\n *\n * console.log(`Running on ${runtime}`); // \"node\", \"deno\", \"bun\", \"cloudflare\", etc.\n *\n * if (isNode()) {\n * // Node.js specific code\n * } else if (isCloudflare()) {\n * // Cloudflare Workers specific code\n * }\n *\n * console.log(getRuntimeVersion()); // \"Node.js 20.0.0\"\n * ```\n */\n\nexport type Runtime = \"node\" | \"deno\" | \"bun\" | \"cloudflare\" | \"edge\" | \"browser\" | \"unknown\";\n\n/**\n * Detect the current JavaScript runtime\n */\nexport function detectRuntime(): Runtime {\n // Bun check (must be before Node since Bun also has process)\n if (typeof globalThis !== \"undefined\" && \"Bun\" in globalThis) {\n return \"bun\";\n }\n\n // Deno check\n if (typeof globalThis !== \"undefined\" && \"Deno\" in globalThis) {\n return \"deno\";\n }\n\n // Cloudflare Workers check (has caches but no process)\n if (\n typeof globalThis !== \"undefined\" &&\n typeof (globalThis as any).caches !== \"undefined\" &&\n typeof (globalThis as any).process === \"undefined\"\n ) {\n return \"cloudflare\";\n }\n\n // Generic Edge runtime check (Vercel Edge, etc.)\n if (\n typeof globalThis !== \"undefined\" &&\n typeof (globalThis as any).EdgeRuntime !== \"undefined\"\n ) {\n return \"edge\";\n }\n\n // Browser check\n if (\n typeof globalThis !== \"undefined\" &&\n typeof (globalThis as any).window !== \"undefined\" &&\n typeof (globalThis as any).document !== \"undefined\"\n ) {\n return \"browser\";\n }\n\n // Node.js check\n if (\n typeof process !== \"undefined\" &&\n process.versions &&\n process.versions.node\n ) {\n return \"node\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Current runtime (cached)\n */\nexport const runtime = detectRuntime();\n\n/**\n * Runtime information helpers\n */\nexport const runtimeInfo = {\n runtime,\n isNode: runtime === \"node\",\n isDeno: runtime === \"deno\",\n isBun: runtime === \"bun\",\n isCloudflare: runtime === \"cloudflare\",\n isEdge: runtime === \"cloudflare\" || runtime === \"edge\" || runtime === \"deno\",\n isBrowser: runtime === \"browser\",\n isServer: runtime !== \"browser\",\n supportsWebCrypto: typeof globalThis.crypto?.subtle !== \"undefined\",\n supportsStreams: typeof globalThis.ReadableStream !== \"undefined\",\n} as const;\n\n/**\n * Check if running in Node.js\n */\nexport function isNode(): boolean {\n return runtime === \"node\";\n}\n\n/**\n * Check if running in Deno\n */\nexport function isDeno(): boolean {\n return runtime === \"deno\";\n}\n\n/**\n * Check if running in Bun\n */\nexport function isBun(): boolean {\n return runtime === \"bun\";\n}\n\n/**\n * Check if running in Cloudflare Workers\n */\nexport function isCloudflare(): boolean {\n return runtime === \"cloudflare\";\n}\n\n/**\n * Check if running in any edge environment\n */\nexport function isEdge(): boolean {\n return runtimeInfo.isEdge;\n}\n\n/**\n * Check if running in browser\n */\nexport function isBrowser(): boolean {\n return runtime === \"browser\";\n}\n\n/**\n * Check if running on server (not browser)\n */\nexport function isServer(): boolean {\n return runtimeInfo.isServer;\n}\n\n/**\n * Get runtime version string\n */\nexport function getRuntimeVersion(): string {\n switch (runtime) {\n case \"node\":\n return `Node.js ${process?.versions?.node ?? \"unknown\"}`;\n case \"bun\":\n return `Bun ${(globalThis as any).Bun.version}`;\n case \"deno\":\n return `Deno ${(globalThis as any).Deno.version.deno}`;\n case \"cloudflare\":\n return \"Cloudflare Workers\";\n case \"edge\":\n return \"Edge Runtime\";\n case \"browser\":\n return typeof navigator !== \"undefined\" ? navigator.userAgent : \"Browser\";\n default:\n return \"Unknown\";\n }\n}\n","/**\n * @module\n * Runtime-agnostic environment variable access.\n * Works in Node.js, Deno, Bun, and Cloudflare Workers.\n *\n * @example\n * ```typescript\n * import { getEnv, requireEnv, getEnvNumber, isDevelopment } from '@parsrun/core';\n *\n * // Get optional env var with default\n * const port = getEnvNumber('PORT', 3000);\n *\n * // Get required env var (throws if missing)\n * const apiKey = requireEnv('API_KEY');\n *\n * // Check environment\n * if (isDevelopment()) {\n * console.log('Running in development mode');\n * }\n * ```\n */\n\nimport { runtime } from \"./runtime.js\";\n\n/**\n * Environment variable store for edge runtimes\n * Must be set from the request handler's env parameter\n */\nlet edgeEnvStore: Record<string, string | undefined> = {};\n\n/**\n * Set environment variables for edge runtimes (Cloudflare Workers, etc.)\n * Call this from your worker's fetch handler with the env parameter\n *\n * @example\n * ```typescript\n * export default {\n * async fetch(request, env) {\n * setEdgeEnv(env);\n * // ... rest of handler\n * }\n * }\n * ```\n */\nexport function setEdgeEnv(env: Record<string, string | undefined>): void {\n edgeEnvStore = { ...edgeEnvStore, ...env };\n}\n\n/**\n * Clear edge environment store\n */\nexport function clearEdgeEnv(): void {\n edgeEnvStore = {};\n}\n\n/**\n * Get an environment variable value\n * Works across all runtimes\n */\nexport function getEnv(key: string, defaultValue?: string): string | undefined {\n // Edge runtimes (Cloudflare Workers, etc.)\n if (runtime === \"cloudflare\" || runtime === \"edge\") {\n return edgeEnvStore[key] ?? defaultValue;\n }\n\n // Deno\n if (runtime === \"deno\") {\n try {\n return (globalThis as any).Deno.env.get(key) ?? defaultValue;\n } catch {\n return defaultValue;\n }\n }\n\n // Node.js / Bun (both use process.env)\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[key] ?? defaultValue;\n }\n\n // Browser - check for injected env\n if (runtime === \"browser\" && typeof (globalThis as any).__ENV__ !== \"undefined\") {\n return (globalThis as any).__ENV__[key] ?? defaultValue;\n }\n\n return defaultValue;\n}\n\n/**\n * Get an environment variable, throwing if not found\n */\nexport function requireEnv(key: string): string {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n throw new Error(`Required environment variable \"${key}\" is not set`);\n }\n return value;\n}\n\n/**\n * Get an environment variable as a number\n */\nexport function getEnvNumber(key: string, defaultValue?: number): number | undefined {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n const parsed = parseInt(value, 10);\n return isNaN(parsed) ? defaultValue : parsed;\n}\n\n/**\n * Get an environment variable as a float\n */\nexport function getEnvFloat(key: string, defaultValue?: number): number | undefined {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n const parsed = parseFloat(value);\n return isNaN(parsed) ? defaultValue : parsed;\n}\n\n/**\n * Get an environment variable as a boolean\n */\nexport function getEnvBoolean(key: string, defaultValue: boolean = false): boolean {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n return value === \"true\" || value === \"1\" || value === \"yes\";\n}\n\n/**\n * Get an environment variable as an array (comma-separated)\n */\nexport function getEnvArray(key: string, defaultValue: string[] = []): string[] {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n return value.split(\",\").map((s) => s.trim()).filter(Boolean);\n}\n\n/**\n * Get an environment variable as JSON\n */\nexport function getEnvJson<T>(key: string, defaultValue?: T): T | undefined {\n const value = getEnv(key);\n if (value === undefined || value === \"\") {\n return defaultValue;\n }\n try {\n return JSON.parse(value) as T;\n } catch {\n return defaultValue;\n }\n}\n\n/**\n * Check if running in development mode\n */\nexport function isDevelopment(): boolean {\n const env = getEnv(\"NODE_ENV\");\n return env === \"development\" || env === undefined;\n}\n\n/**\n * Check if running in production mode\n */\nexport function isProduction(): boolean {\n return getEnv(\"NODE_ENV\") === \"production\";\n}\n\n/**\n * Check if running in test mode\n */\nexport function isTest(): boolean {\n return getEnv(\"NODE_ENV\") === \"test\";\n}\n\n/**\n * Environment mode\n */\nexport type EnvMode = \"development\" | \"production\" | \"test\";\n\n/**\n * Get current environment mode\n */\nexport function getEnvMode(): EnvMode {\n const env = getEnv(\"NODE_ENV\");\n if (env === \"production\") return \"production\";\n if (env === \"test\") return \"test\";\n return \"development\";\n}\n\n/**\n * Create a typed environment configuration object\n *\n * @example\n * ```typescript\n * const env = createEnvConfig({\n * DATABASE_URL: { required: true },\n * PORT: { type: 'number', default: 3000 },\n * DEBUG: { type: 'boolean', default: false },\n * });\n *\n * env.DATABASE_URL // string\n * env.PORT // number\n * env.DEBUG // boolean\n * ```\n */\nexport function createEnvConfig<T extends EnvSchema>(schema: T): EnvResult<T> {\n const result: Record<string, unknown> = {};\n\n for (const [key, config] of Object.entries(schema)) {\n const envConfig = config as EnvConfigItem;\n let value: unknown;\n\n switch (envConfig.type) {\n case \"number\":\n value = getEnvNumber(key, envConfig.default as number | undefined);\n break;\n case \"boolean\":\n value = getEnvBoolean(key, envConfig.default as boolean | undefined);\n break;\n case \"array\":\n value = getEnvArray(key, envConfig.default as string[] | undefined);\n break;\n case \"json\":\n value = getEnvJson(key, envConfig.default);\n break;\n default:\n value = getEnv(key, envConfig.default as string | undefined);\n }\n\n if (envConfig.required && (value === undefined || value === \"\")) {\n throw new Error(`Required environment variable \"${key}\" is not set`);\n }\n\n result[key] = value;\n }\n\n return result as EnvResult<T>;\n}\n\n// Type helpers for createEnvConfig\ntype EnvConfigItem = {\n type?: \"string\" | \"number\" | \"boolean\" | \"array\" | \"json\";\n required?: boolean;\n default?: unknown;\n};\n\ntype EnvSchema = Record<string, EnvConfigItem>;\n\ntype EnvResult<T extends EnvSchema> = {\n [K in keyof T]: T[K][\"type\"] extends \"number\"\n ? number\n : T[K][\"type\"] extends \"boolean\"\n ? boolean\n : T[K][\"type\"] extends \"array\"\n ? string[]\n : T[K][\"type\"] extends \"json\"\n ? unknown\n : string;\n};\n","/**\n * @parsrun/core - Console Transport\n *\n * Default log transport that outputs to the console.\n * Supports pretty printing with colors for development and JSON output for production.\n *\n * @example\n * ```typescript\n * import { ConsoleTransport } from '@parsrun/core';\n *\n * const transport = new ConsoleTransport({\n * pretty: true, // Enable colored, human-readable output\n * colors: true // Enable ANSI colors\n * });\n * ```\n */\n\nimport { runtime } from \"../runtime.js\";\nimport { isDevelopment } from \"../env.js\";\nimport type { LogEntry, LogLevelName } from \"../logger.js\";\nimport type { LogTransport } from \"./types.js\";\n\n/**\n * Console transport options\n */\nexport interface ConsoleTransportOptions {\n /** Enable pretty printing (default: true in development) */\n pretty?: boolean;\n /** Enable ANSI colors (default: true in Node/Bun) */\n colors?: boolean;\n}\n\n/**\n * Console transport\n * Outputs logs to console with optional pretty printing and colors\n */\nexport class ConsoleTransport implements LogTransport {\n readonly name = \"console\";\n\n private pretty: boolean;\n private colors: boolean;\n\n constructor(options: ConsoleTransportOptions = {}) {\n this.pretty = options.pretty ?? isDevelopment();\n this.colors = options.colors ?? (runtime === \"node\" || runtime === \"bun\");\n }\n\n log(entry: LogEntry): void {\n if (this.pretty) {\n this.logPretty(entry);\n } else {\n this.logJson(entry);\n }\n }\n\n private logJson(entry: LogEntry): void {\n const { level, message, timestamp, context, error } = entry;\n\n const output: Record<string, unknown> = {\n level,\n time: timestamp,\n msg: message,\n };\n\n if (context && Object.keys(context).length > 0) {\n Object.assign(output, context);\n }\n\n if (error) {\n output[\"err\"] = error;\n }\n\n console.log(JSON.stringify(output));\n }\n\n private logPretty(entry: LogEntry): void {\n const { level, message, timestamp, context, error } = entry;\n\n const levelColors: Record<LogLevelName, string> = {\n TRACE: \"\\x1b[90m\", // Gray\n DEBUG: \"\\x1b[36m\", // Cyan\n INFO: \"\\x1b[32m\", // Green\n WARN: \"\\x1b[33m\", // Yellow\n ERROR: \"\\x1b[31m\", // Red\n FATAL: \"\\x1b[35m\", // Magenta\n SILENT: \"\",\n };\n\n const reset = \"\\x1b[0m\";\n const color = this.colors ? levelColors[level] : \"\";\n const resetCode = this.colors ? reset : \"\";\n\n // Extract time part from ISO timestamp\n const timePart = timestamp.split(\"T\")[1];\n const time = timePart ? timePart.slice(0, 8) : timestamp;\n\n let output = `${color}[${time}] ${level.padEnd(5)}${resetCode} ${message}`;\n\n if (context && Object.keys(context).length > 0) {\n output += ` ${JSON.stringify(context)}`;\n }\n\n // Route to appropriate console method\n if (level === \"ERROR\" || level === \"FATAL\") {\n console.error(output);\n if (error?.stack) {\n console.error(error.stack);\n }\n } else if (level === \"WARN\") {\n console.warn(output);\n } else if (level === \"DEBUG\" || level === \"TRACE\") {\n console.debug(output);\n } else {\n console.log(output);\n }\n }\n}\n","/**\n * @module\n * Lightweight, edge-compatible structured logging.\n * Works standalone or as abstraction over pino/winston in Node.js.\n *\n * @example\n * ```typescript\n * import { createLogger, Logger, LogLevel } from '@parsrun/core';\n *\n * // Create a logger\n * const log = createLogger({\n * name: 'my-service',\n * level: 'DEBUG',\n * pretty: true\n * });\n *\n * log.info('Server started', { port: 3000 });\n * log.error('Request failed', error, { userId: '123' });\n *\n * // Create child logger with context\n * const requestLog = log.child({ requestId: 'abc123' });\n * ```\n */\n\nimport { getEnv } from \"./env.js\";\nimport { ConsoleTransport } from \"./transports/console.js\";\nimport type { LogTransport } from \"./transports/types.js\";\n\n// Re-export ConsoleTransport for backward compatibility\nexport { ConsoleTransport, type ConsoleTransportOptions } from \"./transports/console.js\";\n\n// Re-export transport types\nexport type { LogTransport } from \"./transports/types.js\";\n\n/**\n * Log level constants mapping level names to numeric values.\n * Lower values are more verbose; higher values are more severe.\n */\nexport const LogLevel = {\n TRACE: 10,\n DEBUG: 20,\n INFO: 30,\n WARN: 40,\n ERROR: 50,\n FATAL: 60,\n SILENT: 100,\n} as const;\n\n/** Log level name string literal type (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, SILENT) */\nexport type LogLevelName = keyof typeof LogLevel;\n\n/** Numeric log level value type */\nexport type LogLevelValue = (typeof LogLevel)[LogLevelName];\n\n/**\n * Structured error information included in log entries.\n * Extracted from Error objects for serialization.\n */\nexport interface ErrorInfo {\n /** Error class name (e.g., \"TypeError\", \"ValidationError\") */\n name: string;\n /** Error message */\n message: string;\n /** Stack trace if available */\n stack: string | undefined;\n}\n\n/**\n * Structured log entry passed to transports.\n * Contains all information about a single log event.\n */\nexport interface LogEntry {\n /** Log level name */\n level: LogLevelName;\n /** Numeric log level value */\n levelValue: LogLevelValue;\n /** Log message */\n message: string;\n /** ISO 8601 timestamp */\n timestamp: string;\n /** Additional context data */\n context: Record<string, unknown> | undefined;\n /** Error information if an error was logged */\n error: ErrorInfo | undefined;\n}\n\n\n/**\n * Configuration options for creating a Logger instance.\n */\nexport interface LoggerConfig {\n /** Minimum log level */\n level: LogLevelName | undefined;\n /** Logger name/module */\n name: string | undefined;\n /** Base context added to all logs */\n context: Record<string, unknown> | undefined;\n /** Custom transports */\n transports: LogTransport[] | undefined;\n /** Pretty print in development */\n pretty: boolean | undefined;\n /** Redact sensitive fields */\n redact: string[] | undefined;\n /** Timestamp format */\n timestamp: boolean | (() => string) | undefined;\n}\n\n\n/**\n * Redact sensitive fields from context\n */\nfunction redactFields(\n obj: Record<string, unknown>,\n fields: string[]\n): Record<string, unknown> {\n const result = { ...obj };\n for (const field of fields) {\n if (field in result) {\n result[field] = \"[REDACTED]\";\n }\n // Handle nested fields like \"user.password\"\n const parts = field.split(\".\");\n if (parts.length > 1) {\n let current: Record<string, unknown> | undefined = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (part && current && typeof current === \"object\" && part in current) {\n const val = current[part];\n if (val && typeof val === \"object\") {\n current = val as Record<string, unknown>;\n } else {\n current = undefined;\n break;\n }\n } else {\n current = undefined;\n break;\n }\n }\n const lastPart = parts[parts.length - 1];\n if (lastPart && current && typeof current === \"object\" && lastPart in current) {\n current[lastPart] = \"[REDACTED]\";\n }\n }\n }\n return result;\n}\n\n/**\n * Default redact fields\n */\nconst DEFAULT_REDACT_FIELDS = [\n \"password\",\n \"secret\",\n \"token\",\n \"accessToken\",\n \"refreshToken\",\n \"apiKey\",\n \"authorization\",\n \"cookie\",\n \"creditCard\",\n \"ssn\",\n];\n\n/**\n * Structured logger with support for multiple transports and redaction.\n * Thread-safe and edge-compatible.\n *\n * @example\n * ```typescript\n * const logger = new Logger({ name: 'api', level: 'DEBUG' });\n * logger.info('Request received', { path: '/users' });\n * logger.error('Request failed', new Error('Not found'), { userId: '123' });\n * ```\n */\nexport class Logger {\n private level: LogLevelValue;\n private name: string | undefined;\n private context: Record<string, unknown>;\n private transports: LogTransport[];\n private redactFields: string[];\n private timestampFn: () => string;\n\n constructor(config: Partial<LoggerConfig> = {}) {\n const levelName = config.level ?? (getEnv(\"LOG_LEVEL\") as LogLevelName | undefined) ?? \"INFO\";\n this.level = LogLevel[levelName] ?? LogLevel.INFO;\n this.name = config.name;\n this.context = config.context ?? {};\n this.transports = config.transports ?? [\n new ConsoleTransport(\n config.pretty !== undefined ? { pretty: config.pretty } : {}\n ),\n ];\n this.redactFields = [...DEFAULT_REDACT_FIELDS, ...(config.redact ?? [])];\n\n if (config.timestamp === false) {\n this.timestampFn = () => \"\";\n } else if (typeof config.timestamp === \"function\") {\n this.timestampFn = config.timestamp;\n } else {\n this.timestampFn = () => new Date().toISOString();\n }\n }\n\n /**\n * Create a child logger with additional context\n */\n child(context: Record<string, unknown>): Logger {\n const levelEntry = Object.entries(LogLevel).find(([_, v]) => v === this.level);\n const levelName = levelEntry ? (levelEntry[0] as LogLevelName) : \"INFO\";\n\n const child = new Logger({\n level: levelName,\n name: this.name,\n context: { ...this.context, ...context },\n transports: this.transports,\n redact: this.redactFields,\n });\n return child;\n }\n\n /**\n * Log a message\n */\n private log(\n level: LogLevelName,\n message: string,\n context?: Record<string, unknown>,\n error?: Error\n ): void {\n const levelValue = LogLevel[level];\n if (levelValue < this.level) return;\n\n let finalContext = { ...this.context };\n if (this.name) {\n finalContext[\"module\"] = this.name;\n }\n if (context) {\n finalContext = { ...finalContext, ...context };\n }\n\n // Redact sensitive fields\n finalContext = redactFields(finalContext, this.redactFields);\n\n const entry: LogEntry = {\n level,\n levelValue,\n message,\n timestamp: this.timestampFn(),\n context: Object.keys(finalContext).length > 0 ? finalContext : undefined,\n error: error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : undefined,\n };\n\n for (const transport of this.transports) {\n transport.log(entry);\n }\n }\n\n /**\n * Log a trace message (most verbose level).\n * @param message - Log message\n * @param context - Optional context data\n */\n trace(message: string, context?: Record<string, unknown>): void {\n this.log(\"TRACE\", message, context);\n }\n\n /**\n * Log a debug message.\n * @param message - Log message\n * @param context - Optional context data\n */\n debug(message: string, context?: Record<string, unknown>): void {\n this.log(\"DEBUG\", message, context);\n }\n\n /**\n * Log an informational message.\n * @param message - Log message\n * @param context - Optional context data\n */\n info(message: string, context?: Record<string, unknown>): void {\n this.log(\"INFO\", message, context);\n }\n\n /**\n * Log a warning message.\n * @param message - Log message\n * @param context - Optional context data\n */\n warn(message: string, context?: Record<string, unknown>): void {\n this.log(\"WARN\", message, context);\n }\n\n /**\n * Log an error message with optional Error object.\n * @param message - Log message\n * @param error - Optional Error object or context\n * @param context - Optional additional context\n */\n error(message: string, error?: Error | unknown, context?: Record<string, unknown>): void {\n const err = error instanceof Error ? error : undefined;\n const ctx = error instanceof Error ? context : (error as Record<string, unknown> | undefined);\n this.log(\"ERROR\", message, ctx, err);\n }\n\n /**\n * Log a fatal error message (most severe level).\n * @param message - Log message\n * @param error - Optional Error object or context\n * @param context - Optional additional context\n */\n fatal(message: string, error?: Error | unknown, context?: Record<string, unknown>): void {\n const err = error instanceof Error ? error : undefined;\n const ctx = error instanceof Error ? context : (error as Record<string, unknown> | undefined);\n this.log(\"FATAL\", message, ctx, err);\n }\n}\n\n/**\n * Create a new Logger instance with the specified configuration.\n *\n * @param config - Logger configuration options\n * @returns A new Logger instance\n *\n * @example\n * ```typescript\n * const log = createLogger({\n * name: 'my-service',\n * level: 'DEBUG',\n * pretty: true\n * });\n * ```\n */\nexport function createLogger(config?: Partial<LoggerConfig>): Logger {\n return new Logger(config);\n}\n\n/**\n * Default logger instance using default configuration.\n * Level can be controlled via LOG_LEVEL environment variable.\n */\nexport const logger = createLogger();\n\n/**\n * Utility function to log an error with proper formatting.\n * Handles both Error objects and unknown error types.\n *\n * @param log - The logger instance to use\n * @param error - The error to log\n * @param message - Human-readable error message\n * @param context - Optional additional context\n *\n * @example\n * ```typescript\n * try {\n * await doSomething();\n * } catch (error) {\n * logError(logger, error, 'Operation failed', { userId });\n * }\n * ```\n */\nexport function logError(\n log: Logger,\n error: unknown,\n message: string,\n context?: Record<string, unknown>\n): void {\n if (error instanceof Error) {\n log.error(message, error, context);\n } else {\n log.error(message, { error: String(error), ...context });\n }\n}\n\n/**\n * Measure and log the execution time of an async operation.\n * Logs completion time on success, or error details on failure.\n *\n * @param log - The logger instance to use\n * @param operation - Name of the operation being measured\n * @param fn - Async function to execute and measure\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * const users = await measureTime(logger, 'fetchUsers', async () => {\n * return await db.users.findMany();\n * });\n * // Logs: \"fetchUsers completed\" { operation: 'fetchUsers', durationMs: 45 }\n * ```\n */\nexport async function measureTime<T>(\n log: Logger,\n operation: string,\n fn: () => Promise<T>\n): Promise<T> {\n const start = Date.now();\n try {\n const result = await fn();\n const duration = Date.now() - start;\n log.info(`${operation} completed`, { operation, durationMs: duration });\n return result;\n } catch (error) {\n const duration = Date.now() - start;\n logError(log, error, `${operation} failed`, { operation, durationMs: duration });\n throw error;\n }\n}\n\n/**\n * Create a child logger with request context for HTTP request logging.\n * Automatically extracts the pathname from the URL.\n *\n * @param baseLogger - The parent logger instance\n * @param request - Request information to include in all logs\n * @returns A child Logger with request context\n *\n * @example\n * ```typescript\n * const requestLog = createRequestLogger(logger, {\n * requestId: 'abc-123',\n * method: 'GET',\n * url: 'https://api.example.com/users',\n * userId: 'user-456'\n * });\n * requestLog.info('Processing request');\n * // Includes: requestId, method, path, userId in all logs\n * ```\n */\nexport function createRequestLogger(\n baseLogger: Logger,\n request: {\n method?: string;\n url?: string;\n requestId?: string;\n userId?: string;\n tenantId?: string;\n }\n): Logger {\n const pathname = request.url ? new URL(request.url).pathname : undefined;\n return baseLogger.child({\n requestId: request.requestId,\n method: request.method,\n path: pathname,\n userId: request.userId,\n tenantId: request.tenantId,\n });\n}\n","/**\n * @parsrun/core - Decimal Utilities\n * Precise decimal calculations for financial and quantity operations.\n * Edge-compatible - no external dependencies.\n *\n * @example\n * ```typescript\n * import { Decimal, decimal } from '@parsrun/core';\n *\n * // Create decimals\n * const price = new Decimal('19.99');\n * const quantity = decimal(3);\n *\n * // Arithmetic operations (chainable)\n * const total = price.mul(quantity).round(2);\n * console.log(total.toString()); // '59.97'\n *\n * // Static helpers\n * const sum = Decimal.sum(['10.50', '20.25', '15.75']);\n * const avg = Decimal.avg([100, 200, 300]);\n * ```\n */\n\n/**\n * Internal precision for calculations (number of decimal places)\n */\nconst PRECISION = 20;\n\n/**\n * Decimal class for precise arithmetic operations.\n * Uses string-based representation internally to avoid floating point issues.\n *\n * @example\n * ```typescript\n * const a = new Decimal('0.1');\n * const b = new Decimal('0.2');\n * const c = a.add(b);\n * console.log(c.toString()); // '0.3' (not 0.30000000000000004)\n * ```\n */\nexport class Decimal {\n private value: string;\n\n constructor(value: number | string | Decimal) {\n if (value instanceof Decimal) {\n this.value = value.value;\n } else if (typeof value === \"number\") {\n this.value = this.normalizeNumber(value);\n } else {\n this.value = this.normalizeString(value);\n }\n }\n\n private normalizeNumber(n: number): string {\n if (!isFinite(n)) {\n throw new Error(`Invalid number: ${n}`);\n }\n return n.toFixed(PRECISION).replace(/\\.?0+$/, \"\") || \"0\";\n }\n\n private normalizeString(s: string): string {\n const trimmed = s.trim();\n if (!/^-?\\d*\\.?\\d+$/.test(trimmed)) {\n throw new Error(`Invalid decimal string: ${s}`);\n }\n return trimmed.replace(/^(-?)0+(?=\\d)/, \"$1\").replace(/\\.?0+$/, \"\") || \"0\";\n }\n\n /**\n * Add another value to this decimal.\n * @param other - Value to add\n * @returns A new Decimal with the result\n */\n add(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n return new Decimal(a + b);\n }\n\n /**\n * Subtract a value from this decimal.\n * @param other - Value to subtract\n * @returns A new Decimal with the result\n */\n sub(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n return new Decimal(a - b);\n }\n\n /**\n * Multiply this decimal by another value.\n * @param other - Value to multiply by\n * @returns A new Decimal with the result\n */\n mul(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n return new Decimal(a * b);\n }\n\n /**\n * Divide this decimal by another value.\n * @param other - Value to divide by\n * @returns A new Decimal with the result\n * @throws Error if dividing by zero\n */\n div(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n if (b === 0) {\n throw new Error(\"Division by zero\");\n }\n return new Decimal(a / b);\n }\n\n /**\n * Get the modulo (remainder) of dividing this decimal by another value.\n * @param other - Value to divide by\n * @returns A new Decimal with the remainder\n */\n mod(other: number | string | Decimal): Decimal {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n return new Decimal(a % b);\n }\n\n /**\n * Raise this decimal to a power.\n * @param exp - The exponent\n * @returns A new Decimal with the result\n */\n pow(exp: number): Decimal {\n const a = parseFloat(this.value);\n return new Decimal(Math.pow(a, exp));\n }\n\n /**\n * Calculate the square root of this decimal.\n * @returns A new Decimal with the square root\n * @throws Error if the value is negative\n */\n sqrt(): Decimal {\n const a = parseFloat(this.value);\n if (a < 0) {\n throw new Error(\"Square root of negative number\");\n }\n return new Decimal(Math.sqrt(a));\n }\n\n /**\n * Get the absolute value of this decimal.\n * @returns A new Decimal with the absolute value\n */\n abs(): Decimal {\n const a = parseFloat(this.value);\n return new Decimal(Math.abs(a));\n }\n\n /**\n * Negate this decimal (multiply by -1).\n * @returns A new Decimal with the negated value\n */\n neg(): Decimal {\n const a = parseFloat(this.value);\n return new Decimal(-a);\n }\n\n /**\n * Round to the specified number of decimal places using standard rounding.\n * @param decimals - Number of decimal places (default: 0)\n * @returns A new Decimal with the rounded value\n */\n round(decimals: number = 0): Decimal {\n const a = parseFloat(this.value);\n const factor = Math.pow(10, decimals);\n return new Decimal(Math.round(a * factor) / factor);\n }\n\n /**\n * Round down to the specified number of decimal places.\n * @param decimals - Number of decimal places (default: 0)\n * @returns A new Decimal with the floored value\n */\n floor(decimals: number = 0): Decimal {\n const a = parseFloat(this.value);\n const factor = Math.pow(10, decimals);\n return new Decimal(Math.floor(a * factor) / factor);\n }\n\n /**\n * Round up to the specified number of decimal places.\n * @param decimals - Number of decimal places (default: 0)\n * @returns A new Decimal with the ceiled value\n */\n ceil(decimals: number = 0): Decimal {\n const a = parseFloat(this.value);\n const factor = Math.pow(10, decimals);\n return new Decimal(Math.ceil(a * factor) / factor);\n }\n\n /**\n * Compare this decimal to another value.\n * @param other - Value to compare against\n * @returns -1 if less, 0 if equal, 1 if greater\n */\n cmp(other: number | string | Decimal): -1 | 0 | 1 {\n const a = parseFloat(this.value);\n const b = parseFloat(other instanceof Decimal ? other.value : String(other));\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n }\n\n /**\n * Check if this decimal equals another value.\n * @param other - Value to compare against\n * @returns True if values are equal\n */\n eq(other: number | string | Decimal): boolean {\n return this.cmp(other) === 0;\n }\n\n /**\n * Check if this decimal is greater than another value.\n * @param other - Value to compare against\n * @returns True if this is greater\n */\n gt(other: number | string | Decimal): boolean {\n return this.cmp(other) === 1;\n }\n\n /**\n * Check if this decimal is greater than or equal to another value.\n * @param other - Value to compare against\n * @returns True if this is greater or equal\n */\n gte(other: number | string | Decimal): boolean {\n return this.cmp(other) >= 0;\n }\n\n /**\n * Check if this decimal is less than another value.\n * @param other - Value to compare against\n * @returns True if this is less\n */\n lt(other: number | string | Decimal): boolean {\n return this.cmp(other) === -1;\n }\n\n /**\n * Check if this decimal is less than or equal to another value.\n * @param other - Value to compare against\n * @returns True if this is less or equal\n */\n lte(other: number | string | Decimal): boolean {\n return this.cmp(other) <= 0;\n }\n\n /**\n * Check if this decimal is exactly zero.\n * @returns True if value is zero\n */\n isZero(): boolean {\n return parseFloat(this.value) === 0;\n }\n\n /**\n * Check if this decimal is positive (greater than zero).\n * @returns True if value is positive\n */\n isPositive(): boolean {\n return parseFloat(this.value) > 0;\n }\n\n /**\n * Check if this decimal is negative (less than zero).\n * @returns True if value is negative\n */\n isNegative(): boolean {\n return parseFloat(this.value) < 0;\n }\n\n /**\n * Convert this decimal to a JavaScript number.\n * @returns The numeric value\n */\n toNumber(): number {\n return parseFloat(this.value);\n }\n\n /**\n * Convert this decimal to its string representation.\n * @returns The string value\n */\n toString(): string {\n return this.value;\n }\n\n /**\n * Format this decimal with a fixed number of decimal places.\n * @param decimals - Number of decimal places (default: 2)\n * @returns Formatted string\n */\n toFixed(decimals: number = 2): string {\n return parseFloat(this.value).toFixed(decimals);\n }\n\n /**\n * Convert to JSON (returns string representation for serialization).\n * @returns The string value for JSON serialization\n */\n toJSON(): string {\n return this.value;\n }\n\n /**\n * Create a Decimal from a value (alias for constructor).\n * @param value - The value to convert\n * @returns A new Decimal instance\n */\n static from(value: number | string | Decimal): Decimal {\n return new Decimal(value);\n }\n\n /**\n * Calculate the sum of an array of values.\n * @param values - Array of values to sum\n * @returns A new Decimal with the sum\n */\n static sum(values: (number | string | Decimal)[]): Decimal {\n return values.reduce<Decimal>(\n (acc, val) => acc.add(val),\n new Decimal(0)\n );\n }\n\n /**\n * Calculate the average of an array of values.\n * @param values - Array of values to average\n * @returns A new Decimal with the average (0 if empty array)\n */\n static avg(values: (number | string | Decimal)[]): Decimal {\n if (values.length === 0) return new Decimal(0);\n return Decimal.sum(values).div(values.length);\n }\n\n /**\n * Find the minimum value from the provided values.\n * @param values - Values to compare\n * @returns A new Decimal with the minimum value\n * @throws Error if no values provided\n */\n static min(...values: (number | string | Decimal)[]): Decimal {\n if (values.length === 0) throw new Error(\"No values provided\");\n return values.reduce<Decimal>((min, val) => {\n const d = new Decimal(val);\n return d.lt(min) ? d : min;\n }, new Decimal(values[0]!));\n }\n\n /**\n * Find the maximum value from the provided values.\n * @param values - Values to compare\n * @returns A new Decimal with the maximum value\n * @throws Error if no values provided\n */\n static max(...values: (number | string | Decimal)[]): Decimal {\n if (values.length === 0) throw new Error(\"No values provided\");\n return values.reduce<Decimal>((max, val) => {\n const d = new Decimal(val);\n return d.gt(max) ? d : max;\n }, new Decimal(values[0]!));\n }\n}\n\n/**\n * Utility functions for working with decimals in database operations.\n * Provides helpers for converting between JavaScript numbers and database decimal strings.\n *\n * @example\n * ```typescript\n * // Convert numeric fields before database insert\n * const data = DecimalUtils.prepareForDatabase(\n * { price: 19.99, quantity: 5 },\n * ['price']\n * );\n *\n * // Format for display\n * DecimalUtils.formatCurrency('19.99', { currency: 'USD' }); // '$19.99'\n * ```\n */\nexport const DecimalUtils = {\n /**\n * Convert a number to a database-safe decimal string.\n * @param value - The value to convert\n * @returns The decimal string or null if value is null/undefined\n */\n toDecimalString(value: number | string | null | undefined): string | null {\n if (value === null || value === undefined) return null;\n return new Decimal(value).toString();\n },\n\n /**\n * Convert a database decimal string to a JavaScript number.\n * @param value - The decimal string from database\n * @returns The numeric value (0 if null/undefined/empty)\n */\n fromDecimalString(value: string | null | undefined): number {\n if (!value) return 0;\n return new Decimal(value).toNumber();\n },\n\n /**\n * Multiply two values with precise decimal arithmetic.\n * @param a - First value\n * @param b - Second value\n * @returns The product as a string\n */\n multiply(a: number | string, b: number | string): string {\n return new Decimal(a).mul(b).toString();\n },\n\n /**\n * Add two values with precise decimal arithmetic.\n * @param a - First value\n * @param b - Second value\n * @returns The sum as a string\n */\n add(a: number | string, b: number | string): string {\n return new Decimal(a).add(b).toString();\n },\n\n /**\n * Subtract two values with precise decimal arithmetic.\n * @param a - Value to subtract from\n * @param b - Value to subtract\n * @returns The difference as a string\n */\n subtract(a: number | string, b: number | string): string {\n return new Decimal(a).sub(b).toString();\n },\n\n /**\n * Divide two values with precise decimal arithmetic.\n * @param a - Dividend\n * @param b - Divisor\n * @returns The quotient as a string\n */\n divide(a: number | string, b: number | string): string {\n return new Decimal(a).div(b).toString();\n },\n\n /**\n * Format a decimal value for display with fixed decimal places.\n * @param value - The value to format\n * @param decimalPlaces - Number of decimal places (default: 2)\n * @returns Formatted string\n */\n format(value: string | number, decimalPlaces: number = 2): string {\n return new Decimal(value).toFixed(decimalPlaces);\n },\n\n /**\n * Format a value as currency using Intl.NumberFormat.\n * @param value - The value to format\n * @param options - Currency formatting options\n * @returns Formatted currency string\n */\n formatCurrency(\n value: string | number,\n options: {\n currency?: string;\n locale?: string;\n decimals?: number;\n } = {}\n ): string {\n const { currency = \"USD\", locale = \"en-US\", decimals = 2 } = options;\n const num = new Decimal(value).toNumber();\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n minimumFractionDigits: decimals,\n maximumFractionDigits: decimals,\n }).format(num);\n },\n\n /**\n * Prepare an object for database insert/update by converting numeric fields to decimal strings.\n * @param data - The object to prepare\n * @param decimalFields - Array of field names that should be converted to decimal strings\n * @returns A new object with specified fields converted to decimal strings\n */\n prepareForDatabase<T extends Record<string, unknown>>(\n data: T,\n decimalFields: string[]\n ): T {\n const result = { ...data };\n for (const field of decimalFields) {\n if (field in result && result[field] !== undefined && result[field] !== null) {\n const value = result[field];\n if (typeof value === \"number\") {\n (result as Record<string, unknown>)[field] = DecimalUtils.toDecimalString(value);\n }\n }\n }\n return result;\n },\n\n /**\n * Parse an object from database by converting decimal string fields to JavaScript numbers.\n * @param data - The object from database\n * @param decimalFields - Array of field names that should be converted from decimal strings\n * @returns A new object with specified fields converted to numbers\n */\n parseFromDatabase<T extends Record<string, unknown>>(\n data: T,\n decimalFields: string[]\n ): T {\n const result = { ...data };\n for (const field of decimalFields) {\n if (field in result && result[field] !== undefined && result[field] !== null) {\n const value = result[field];\n if (typeof value === \"string\") {\n (result as Record<string, unknown>)[field] = DecimalUtils.fromDecimalString(value);\n }\n }\n }\n return result;\n },\n};\n\n/**\n * Shorthand function for creating a Decimal instance.\n *\n * @param value - The value to convert to a Decimal\n * @returns A new Decimal instance\n *\n * @example\n * ```typescript\n * const price = decimal('19.99');\n * const total = decimal(100).mul(price);\n * ```\n */\nexport function decimal(value: number | string): Decimal {\n return new Decimal(value);\n}\n","/**\n * @parsrun/core - Type Definitions\n *\n * Core type definitions for multi-tenant applications including users,\n * sessions, tenants, memberships, and common utility types.\n */\n\n// ============================================\n// TENANT TYPES\n// ============================================\n\n/**\n * Represents a tenant (organization/workspace) in a multi-tenant application.\n * Each tenant has its own isolated data and can have multiple users.\n */\nexport interface Tenant {\n id: string;\n name: string;\n slug: string;\n status: TenantStatus;\n plan?: string;\n settings?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Possible states for a tenant.\n * - `active`: Tenant is fully operational\n * - `suspended`: Tenant access is temporarily disabled\n * - `pending`: Tenant is awaiting activation or verification\n * - `deleted`: Tenant has been soft-deleted\n */\nexport type TenantStatus = \"active\" | \"suspended\" | \"pending\" | \"deleted\";\n\n// ============================================\n// USER TYPES\n// ============================================\n\n/**\n * Represents a user in the system.\n * Users can belong to multiple tenants through memberships.\n */\nexport interface User {\n id: string;\n email: string;\n emailVerified: boolean;\n name?: string;\n avatarUrl?: string;\n twoFactorEnabled: boolean;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Represents an authenticated user session.\n * Sessions are scoped to a specific user and tenant.\n */\nexport interface Session {\n id: string;\n userId: string;\n tenantId: string;\n expiresAt: Date;\n ipAddress?: string;\n userAgent?: string;\n createdAt: Date;\n}\n\n// ============================================\n// MEMBERSHIP TYPES\n// ============================================\n\n/**\n * Represents a user's membership in a tenant.\n * Contains role, permissions, and access restrictions.\n */\nexport interface TenantMembership {\n id: string;\n userId: string;\n tenantId: string;\n roleId?: string;\n permissions: MembershipPermissions;\n accessLevel: AccessLevel;\n resourceRestrictions: ResourceRestrictions;\n ipRestrictions?: IpRestrictions;\n timeRestrictions?: TimeRestrictions;\n status: MembershipStatus;\n expiresAt?: Date;\n invitedBy?: string;\n invitedAt?: Date;\n joinedAt?: Date;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Possible states for a tenant membership.\n * - `pending`: Invitation sent, awaiting acceptance\n * - `active`: Membership is active and user has access\n * - `suspended`: Membership temporarily disabled\n * - `expired`: Membership has passed its expiration date\n * - `revoked`: Membership has been permanently revoked\n */\nexport type MembershipStatus = \"pending\" | \"active\" | \"suspended\" | \"expired\" | \"revoked\";\n\n/**\n * Access level for a membership.\n * - `full`: Complete access to all resources\n * - `limited`: Restricted access based on permissions\n * - `readonly`: Can view but not modify resources\n * - `custom`: Custom permission set defined by permissions field\n */\nexport type AccessLevel = \"full\" | \"limited\" | \"readonly\" | \"custom\";\n\n/**\n * Maps resources to allowed actions.\n * Keys are resource names, values are arrays of permitted actions.\n *\n * @example\n * ```typescript\n * const permissions: MembershipPermissions = {\n * users: ['read', 'create'],\n * settings: ['read']\n * };\n * ```\n */\nexport interface MembershipPermissions {\n [resource: string]: string[];\n}\n\n/**\n * Restricts access to specific resources within a tenant.\n * Can limit access by location, department, project, or custom dimensions.\n */\nexport interface ResourceRestrictions {\n /** Allowed location IDs */\n locations?: string[];\n /** Allowed department IDs */\n departments?: string[];\n /** Allowed project IDs */\n projects?: string[];\n /** Custom resource restrictions */\n [key: string]: string[] | undefined;\n}\n\n/**\n * IP-based access restrictions for a membership.\n * Can whitelist or blacklist specific IPs or CIDR ranges.\n */\nexport interface IpRestrictions {\n /** Specific IP addresses that are allowed */\n allowedIps?: string[];\n /** CIDR ranges that are allowed (e.g., \"192.168.1.0/24\") */\n allowedCidrs?: string[];\n /** Specific IP addresses that are denied */\n deniedIps?: string[];\n}\n\n/**\n * Time-based access restrictions for a membership.\n * Can limit access to specific days and hours.\n */\nexport interface TimeRestrictions {\n /** Timezone for time calculations (e.g., \"America/New_York\") */\n timezone?: string;\n /** Days of the week when access is allowed (0-6, Sunday = 0) */\n allowedDays?: number[];\n /** Hour when access begins (0-23) */\n allowedHoursStart?: number;\n /** Hour when access ends (0-23) */\n allowedHoursEnd?: number;\n}\n\n// ============================================\n// AUTH CONTEXT\n// ============================================\n\n/**\n * Complete authentication context for a request.\n * Contains the authenticated user, their session, tenant, and membership.\n */\nexport interface AuthContext {\n user: User;\n session: Session;\n tenant: Tenant;\n membership: TenantMembership;\n}\n\n// ============================================\n// PAGINATION\n// ============================================\n\n/**\n * Parameters for paginated queries.\n * Supports both offset-based and cursor-based pagination.\n */\nexport interface PaginationParams {\n /** Page number (1-indexed) for offset pagination */\n page?: number;\n /** Number of items per page */\n limit?: number;\n /** Cursor for cursor-based pagination */\n cursor?: string;\n}\n\n/**\n * Result of a paginated query.\n * Contains the data array and pagination metadata.\n *\n * @typeParam T - The type of items in the result\n */\nexport interface PaginatedResult<T> {\n data: T[];\n pagination: {\n total: number;\n page: number;\n limit: number;\n totalPages: number;\n hasNext: boolean;\n hasPrev: boolean;\n nextCursor?: string;\n };\n}\n\n// ============================================\n// RESULT TYPES\n// ============================================\n\n/**\n * A discriminated union type representing either success or failure.\n * Use pattern matching to safely handle both cases.\n *\n * @typeParam T - The success value type\n * @typeParam E - The error type (defaults to Error)\n *\n * @example\n * ```typescript\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return err('Division by zero');\n * return ok(a / b);\n * }\n *\n * const result = divide(10, 2);\n * if (result.success) {\n * console.log(result.data); // 5\n * } else {\n * console.error(result.error);\n * }\n * ```\n */\nexport type Result<T, E = Error> =\n | { success: true; data: T }\n | { success: false; error: E };\n\n/**\n * Create a successful Result.\n *\n * @param data - The success value\n * @returns A Result indicating success with the provided data\n *\n * @example\n * ```typescript\n * return ok({ id: 1, name: 'John' });\n * ```\n */\nexport function ok<T>(data: T): Result<T, never> {\n return { success: true, data };\n}\n\n/**\n * Create a failed Result.\n *\n * @param error - The error value\n * @returns A Result indicating failure with the provided error\n *\n * @example\n * ```typescript\n * return err(new Error('User not found'));\n * ```\n */\nexport function err<E>(error: E): Result<never, E> {\n return { success: false, error };\n}\n\n// ============================================\n// UTILITY TYPES\n// ============================================\n\n/**\n * Flattens complex intersection types for better IDE display.\n * Use this to make hover information more readable.\n *\n * @typeParam T - The type to prettify\n *\n * @example\n * ```typescript\n * type Ugly = { a: string } & { b: number };\n * type Pretty = Prettify<Ugly>; // { a: string; b: number }\n * ```\n */\nexport type Prettify<T> = {\n [K in keyof T]: T[K];\n} & {};\n\n/**\n * Makes all properties in T optional recursively.\n * Useful for partial updates or patch operations.\n *\n * @typeParam T - The type to make deeply partial\n *\n * @example\n * ```typescript\n * interface User { name: string; address: { city: string } }\n * type PartialUser = DeepPartial<User>;\n * // { name?: string; address?: { city?: string } }\n * ```\n */\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\n/**\n * Requires at least one of the specified keys to be present.\n * Useful for APIs that need at least one identifier.\n *\n * @typeParam T - The base type\n * @typeParam Keys - The keys of which at least one must be present\n *\n * @example\n * ```typescript\n * interface Query { id?: string; email?: string; name?: string }\n * type UserQuery = RequireAtLeastOne<Query, 'id' | 'email'>;\n * // Must have either id or email (or both)\n * ```\n */\nexport type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<\n T,\n Exclude<keyof T, Keys>\n> &\n {\n [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;\n }[Keys];\n","/**\n * @module\n * Error classes for the Pars framework.\n * Provides typed errors for auth, validation, rate limiting, and more.\n *\n * @example\n * ```typescript\n * import { NotFoundError, ValidationError, UnauthorizedError } from '@parsrun/core';\n *\n * // Throw typed errors\n * throw new NotFoundError('User');\n * throw new ValidationError('Invalid input', [{ field: 'email', message: 'Invalid format' }]);\n * throw new UnauthorizedError('Token expired');\n * ```\n */\n\n/**\n * Base error class for all Pars framework errors.\n * Includes error code, HTTP status code, and optional details.\n *\n * @example\n * ```typescript\n * throw new ParsError('Something went wrong', 'CUSTOM_ERROR', 500, { extra: 'info' });\n * ```\n */\nexport class ParsError extends Error {\n public readonly code: string;\n public readonly statusCode: number;\n public readonly details: Record<string, unknown> | undefined;\n\n constructor(\n message: string,\n code: string,\n statusCode: number = 500,\n details?: Record<string, unknown>\n ) {\n super(message);\n this.name = \"ParsError\";\n this.code = code;\n this.statusCode = statusCode;\n this.details = details ?? undefined;\n Error.captureStackTrace?.(this, this.constructor);\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n statusCode: this.statusCode,\n details: this.details,\n };\n }\n}\n\n// ============================================\n// AUTH ERRORS\n// ============================================\n\n/** Base class for authentication-related errors (HTTP 401/403) */\nexport class AuthError extends ParsError {\n constructor(\n message: string,\n code: string = \"AUTH_ERROR\",\n statusCode: number = 401,\n details?: Record<string, unknown>\n ) {\n super(message, code, statusCode, details);\n this.name = \"AuthError\";\n }\n}\n\n/** User is not authenticated (HTTP 401) */\nexport class UnauthorizedError extends AuthError {\n constructor(message: string = \"Unauthorized\", details?: Record<string, unknown>) {\n super(message, \"UNAUTHORIZED\", 401, details);\n this.name = \"UnauthorizedError\";\n }\n}\n\n/** User lacks permission for the requested action (HTTP 403) */\nexport class ForbiddenError extends AuthError {\n constructor(message: string = \"Forbidden\", details?: Record<string, unknown>) {\n super(message, \"FORBIDDEN\", 403, details);\n this.name = \"ForbiddenError\";\n }\n}\n\n/**\n * Credentials (username/password, API key, etc.) are invalid (HTTP 401).\n * Thrown during authentication when credentials don't match.\n */\nexport class InvalidCredentialsError extends AuthError {\n constructor(message: string = \"Invalid credentials\", details?: Record<string, unknown>) {\n super(message, \"INVALID_CREDENTIALS\", 401, details);\n this.name = \"InvalidCredentialsError\";\n }\n}\n\n/**\n * User session has expired (HTTP 401).\n * User needs to re-authenticate to continue.\n */\nexport class SessionExpiredError extends AuthError {\n constructor(message: string = \"Session expired\", details?: Record<string, unknown>) {\n super(message, \"SESSION_EXPIRED\", 401, details);\n this.name = \"SessionExpiredError\";\n }\n}\n\n/**\n * Two-factor authentication is required to complete login (HTTP 403).\n * Contains a challengeId that should be used to submit the 2FA code.\n */\nexport class TwoFactorRequiredError extends AuthError {\n constructor(\n message: string = \"Two-factor authentication required\",\n /** Unique identifier for the 2FA challenge */\n public readonly challengeId: string,\n details?: Record<string, unknown>\n ) {\n super(message, \"TWO_FACTOR_REQUIRED\", 403, { ...details, challengeId });\n this.name = \"TwoFactorRequiredError\";\n }\n}\n\n/**\n * Account has been locked due to too many failed attempts or admin action (HTTP 423).\n * May include a lockedUntil timestamp indicating when the account will be unlocked.\n */\nexport class AccountLockedError extends AuthError {\n constructor(\n message: string = \"Account locked\",\n /** When the account will be automatically unlocked (if applicable) */\n public readonly lockedUntil?: Date,\n details?: Record<string, unknown>\n ) {\n super(message, \"ACCOUNT_LOCKED\", 423, { ...details, lockedUntil });\n this.name = \"AccountLockedError\";\n }\n}\n\n// ============================================\n// TENANT ERRORS\n// ============================================\n\n/** Base class for tenant-related errors */\nexport class TenantError extends ParsError {\n constructor(\n message: string,\n code: string = \"TENANT_ERROR\",\n statusCode: number = 400,\n details?: Record<string, unknown>\n ) {\n super(message, code, statusCode, details);\n this.name = \"TenantError\";\n }\n}\n\n/** Tenant does not exist or user does not have access to it (HTTP 404) */\nexport class TenantNotFoundError extends TenantError {\n constructor(message: string = \"Tenant not found\", details?: Record<string, unknown>) {\n super(message, \"TENANT_NOT_FOUND\", 404, details);\n this.name = \"TenantNotFoundError\";\n }\n}\n\n/** Tenant has been suspended and access is denied (HTTP 403) */\nexport class TenantSuspendedError extends TenantError {\n constructor(message: string = \"Tenant suspended\", details?: Record<string, unknown>) {\n super(message, \"TENANT_SUSPENDED\", 403, details);\n this.name = \"TenantSuspendedError\";\n }\n}\n\n/** Base class for membership-related errors */\nexport class MembershipError extends TenantError {\n constructor(\n message: string = \"Membership error\",\n code: string = \"MEMBERSHIP_ERROR\",\n statusCode: number = 400,\n details?: Record<string, unknown>\n ) {\n super(message, code, statusCode, details);\n this.name = \"MembershipError\";\n }\n}\n\n/** User is not a member of the specified tenant (HTTP 404) */\nexport class MembershipNotFoundError extends MembershipError {\n constructor(message: string = \"Membership not found\", details?: Record<string, unknown>) {\n super(message, \"MEMBERSHIP_NOT_FOUND\", 404, details);\n this.name = \"MembershipNotFoundError\";\n }\n}\n\n/** User's membership in the tenant has expired (HTTP 403) */\nexport class MembershipExpiredError extends MembershipError {\n constructor(message: string = \"Membership expired\", details?: Record<string, unknown>) {\n super(message, \"MEMBERSHIP_EXPIRED\", 403, details);\n this.name = \"MembershipExpiredError\";\n }\n}\n\n// ============================================\n// VALIDATION ERRORS\n// ============================================\n\n/** Request validation failed with one or more field errors (HTTP 400) */\nexport class ValidationError extends ParsError {\n constructor(\n message: string = \"Validation failed\",\n public readonly errors: ValidationErrorDetail[],\n details?: Record<string, unknown>\n ) {\n super(message, \"VALIDATION_ERROR\", 400, { ...details, errors });\n this.name = \"ValidationError\";\n }\n}\n\n/** Details about a single validation error */\nexport interface ValidationErrorDetail {\n /** Field path that failed validation */\n field: string;\n /** Human-readable error message */\n message: string;\n /** Optional error code for programmatic handling */\n code?: string;\n}\n\n// ============================================\n// RATE LIMIT ERRORS\n// ============================================\n\n/** Too many requests - rate limit exceeded (HTTP 429) */\nexport class RateLimitError extends ParsError {\n constructor(\n message: string = \"Rate limit exceeded\",\n public readonly retryAfter?: number,\n details?: Record<string, unknown>\n ) {\n super(message, \"RATE_LIMIT_EXCEEDED\", 429, { ...details, retryAfter });\n this.name = \"RateLimitError\";\n }\n}\n\n// ============================================\n// NOT FOUND ERRORS\n// ============================================\n\n/** Requested resource was not found (HTTP 404) */\nexport class NotFoundError extends ParsError {\n constructor(\n resource: string = \"Resource\",\n message?: string,\n details?: Record<string, unknown>\n ) {\n super(message ?? `${resource} not found`, \"NOT_FOUND\", 404, { ...details, resource });\n this.name = \"NotFoundError\";\n }\n}\n\n// ============================================\n// CONFLICT ERRORS\n// ============================================\n\n/** Resource conflict, such as duplicate entry (HTTP 409) */\nexport class ConflictError extends ParsError {\n constructor(message: string = \"Conflict\", details?: Record<string, unknown>) {\n super(message, \"CONFLICT\", 409, details);\n this.name = \"ConflictError\";\n }\n}\n\n/**\n * A duplicate resource already exists (HTTP 409).\n * Used when attempting to create a resource that violates a uniqueness constraint.\n */\nexport class DuplicateError extends ConflictError {\n constructor(\n /** The type of resource that already exists */\n resource: string = \"Resource\",\n /** The field that caused the conflict (e.g., 'email', 'slug') */\n field?: string,\n details?: Record<string, unknown>\n ) {\n super(`${resource} already exists${field ? ` with this ${field}` : \"\"}`, {\n ...details,\n resource,\n field,\n });\n this.name = \"DuplicateError\";\n }\n}\n","/**\n * @parsrun/core - Error Code Catalog\n * Centralized error code definitions for the entire framework\n */\n\n/**\n * Error category for grouping and filtering\n */\nexport type ErrorCategory =\n | \"auth\"\n | \"tenant\"\n | \"validation\"\n | \"resource\"\n | \"rate_limit\"\n | \"server\"\n | \"database\"\n | \"external\";\n\n/**\n * Error code definition\n */\nexport interface ErrorCodeDefinition {\n readonly code: string;\n readonly status: number;\n readonly category: ErrorCategory;\n readonly retryable?: boolean;\n}\n\n/**\n * Centralized error code catalog\n * All error codes used throughout the framework are defined here\n */\nexport const ErrorCodes = {\n // ============================================================================\n // Authentication Errors (401, 403, 423)\n // ============================================================================\n AUTH_ERROR: {\n code: \"AUTH_ERROR\",\n status: 401,\n category: \"auth\",\n },\n UNAUTHORIZED: {\n code: \"UNAUTHORIZED\",\n status: 401,\n category: \"auth\",\n },\n FORBIDDEN: {\n code: \"FORBIDDEN\",\n status: 403,\n category: \"auth\",\n },\n INVALID_CREDENTIALS: {\n code: \"INVALID_CREDENTIALS\",\n status: 401,\n category: \"auth\",\n },\n SESSION_EXPIRED: {\n code: \"SESSION_EXPIRED\",\n status: 401,\n category: \"auth\",\n },\n TOKEN_EXPIRED: {\n code: \"TOKEN_EXPIRED\",\n status: 401,\n category: \"auth\",\n },\n TOKEN_INVALID: {\n code: \"TOKEN_INVALID\",\n status: 401,\n category: \"auth\",\n },\n TWO_FACTOR_REQUIRED: {\n code: \"TWO_FACTOR_REQUIRED\",\n status: 403,\n category: \"auth\",\n },\n TWO_FACTOR_INVALID: {\n code: \"TWO_FACTOR_INVALID\",\n status: 401,\n category: \"auth\",\n },\n ACCOUNT_LOCKED: {\n code: \"ACCOUNT_LOCKED\",\n status: 423,\n category: \"auth\",\n },\n ACCOUNT_DISABLED: {\n code: \"ACCOUNT_DISABLED\",\n status: 403,\n category: \"auth\",\n },\n PASSWORD_RESET_REQUIRED: {\n code: \"PASSWORD_RESET_REQUIRED\",\n status: 403,\n category: \"auth\",\n },\n\n // ============================================================================\n // Tenant Errors (400, 403, 404)\n // ============================================================================\n TENANT_ERROR: {\n code: \"TENANT_ERROR\",\n status: 400,\n category: \"tenant\",\n },\n TENANT_NOT_FOUND: {\n code: \"TENANT_NOT_FOUND\",\n status: 404,\n category: \"tenant\",\n },\n TENANT_SUSPENDED: {\n code: \"TENANT_SUSPENDED\",\n status: 403,\n category: \"tenant\",\n },\n TENANT_LIMIT_EXCEEDED: {\n code: \"TENANT_LIMIT_EXCEEDED\",\n status: 403,\n category: \"tenant\",\n },\n MEMBERSHIP_ERROR: {\n code: \"MEMBERSHIP_ERROR\",\n status: 400,\n category: \"tenant\",\n },\n MEMBERSHIP_NOT_FOUND: {\n code: \"MEMBERSHIP_NOT_FOUND\",\n status: 404,\n category: \"tenant\",\n },\n MEMBERSHIP_EXPIRED: {\n code: \"MEMBERSHIP_EXPIRED\",\n status: 403,\n category: \"tenant\",\n },\n\n // ============================================================================\n // Validation Errors (400, 422)\n // ============================================================================\n VALIDATION_ERROR: {\n code: \"VALIDATION_ERROR\",\n status: 400,\n category: \"validation\",\n },\n BAD_REQUEST: {\n code: \"BAD_REQUEST\",\n status: 400,\n category: \"validation\",\n },\n INVALID_INPUT: {\n code: \"INVALID_INPUT\",\n status: 422,\n category: \"validation\",\n },\n MISSING_REQUIRED_FIELD: {\n code: \"MISSING_REQUIRED_FIELD\",\n status: 400,\n category: \"validation\",\n },\n INVALID_FORMAT: {\n code: \"INVALID_FORMAT\",\n status: 400,\n category: \"validation\",\n },\n\n // ============================================================================\n // Resource Errors (404, 409, 410)\n // ============================================================================\n NOT_FOUND: {\n code: \"NOT_FOUND\",\n status: 404,\n category: \"resource\",\n },\n CONFLICT: {\n code: \"CONFLICT\",\n status: 409,\n category: \"resource\",\n },\n DUPLICATE: {\n code: \"DUPLICATE\",\n status: 409,\n category: \"resource\",\n },\n GONE: {\n code: \"GONE\",\n status: 410,\n category: \"resource\",\n },\n RESOURCE_LOCKED: {\n code: \"RESOURCE_LOCKED\",\n status: 423,\n category: \"resource\",\n },\n\n // ============================================================================\n // Rate Limiting (429)\n // ============================================================================\n RATE_LIMIT_EXCEEDED: {\n code: \"RATE_LIMIT_EXCEEDED\",\n status: 429,\n category: \"rate_limit\",\n retryable: true,\n },\n QUOTA_EXCEEDED: {\n code: \"QUOTA_EXCEEDED\",\n status: 429,\n category: \"rate_limit\",\n },\n\n // ============================================================================\n // Server Errors (500, 502, 503, 504)\n // ============================================================================\n INTERNAL_ERROR: {\n code: \"INTERNAL_ERROR\",\n status: 500,\n category: \"server\",\n },\n BAD_GATEWAY: {\n code: \"BAD_GATEWAY\",\n status: 502,\n category: \"server\",\n retryable: true,\n },\n SERVICE_UNAVAILABLE: {\n code: \"SERVICE_UNAVAILABLE\",\n status: 503,\n category: \"server\",\n retryable: true,\n },\n GATEWAY_TIMEOUT: {\n code: \"GATEWAY_TIMEOUT\",\n status: 504,\n category: \"server\",\n retryable: true,\n },\n\n // ============================================================================\n // Database Errors (500)\n // ============================================================================\n DATABASE_ERROR: {\n code: \"DATABASE_ERROR\",\n status: 500,\n category: \"database\",\n },\n CONNECTION_ERROR: {\n code: \"CONNECTION_ERROR\",\n status: 503,\n category: \"database\",\n retryable: true,\n },\n TRANSACTION_ERROR: {\n code: \"TRANSACTION_ERROR\",\n status: 500,\n category: \"database\",\n },\n RLS_ERROR: {\n code: \"RLS_ERROR\",\n status: 500,\n category: \"database\",\n },\n\n // ============================================================================\n // External Service Errors (502, 503)\n // ============================================================================\n EXTERNAL_SERVICE_ERROR: {\n code: \"EXTERNAL_SERVICE_ERROR\",\n status: 502,\n category: \"external\",\n retryable: true,\n },\n EXTERNAL_TIMEOUT: {\n code: \"EXTERNAL_TIMEOUT\",\n status: 504,\n category: \"external\",\n retryable: true,\n },\n} as const;\n\n/**\n * Error code type (union of all error code keys)\n */\nexport type ErrorCode = keyof typeof ErrorCodes;\n\n/**\n * Get error code definition by code string\n */\nexport function getErrorCode(code: string): ErrorCodeDefinition | undefined {\n return (ErrorCodes as Record<string, ErrorCodeDefinition>)[code];\n}\n\n/**\n * Get all error codes by category\n */\nexport function getErrorCodesByCategory(\n category: ErrorCategory\n): ErrorCodeDefinition[] {\n return Object.values(ErrorCodes).filter((e) => e.category === category);\n}\n\n/**\n * Check if an error code is retryable\n */\nexport function isRetryableError(code: string): boolean {\n const errorCode = getErrorCode(code);\n return errorCode?.retryable === true;\n}\n\n/**\n * Get HTTP status for an error code\n */\nexport function getStatusForCode(code: string): number {\n const errorCode = getErrorCode(code);\n return errorCode?.status ?? 500;\n}\n","/**\n * @parsrun/core - Axiom Transport\n *\n * Log ingestion transport for Axiom (axiom.co).\n * Uses native fetch - works on all runtimes (Node, Deno, Bun, Workers).\n *\n * @example\n * ```typescript\n * import { createLogger, AxiomTransport } from '@parsrun/core';\n *\n * const axiom = new AxiomTransport({\n * token: process.env.AXIOM_TOKEN!,\n * dataset: 'my-app-logs',\n * batchSize: 100, // Send every 100 logs\n * flushInterval: 5000, // Or every 5 seconds\n * });\n *\n * const logger = createLogger({\n * transports: [axiom]\n * });\n * ```\n */\n\nimport type { LogEntry } from \"../logger.js\";\nimport type { LogTransport, BatchTransportOptions } from \"./types.js\";\n\n/**\n * Axiom transport options\n */\nexport interface AxiomTransportOptions extends BatchTransportOptions {\n /** Axiom API token */\n token: string;\n /** Dataset name to ingest logs into */\n dataset: string;\n /** Organization ID (optional, for personal tokens) */\n orgId?: string;\n /** Custom Axiom API URL (default: https://api.axiom.co) */\n apiUrl?: string;\n /** Callback for errors during ingestion */\n onError?: (error: Error, droppedCount: number) => void;\n}\n\n/**\n * Axiom log event structure\n */\ninterface AxiomEvent {\n _time: string;\n level: string;\n message: string;\n [key: string]: unknown;\n}\n\n/**\n * Axiom Transport\n * Batches logs and sends them to Axiom's ingest API\n */\nexport class AxiomTransport implements LogTransport {\n readonly name = \"axiom\";\n\n private buffer: AxiomEvent[] = [];\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private isFlushing = false;\n private readonly options: Required<\n Pick<AxiomTransportOptions, \"batchSize\" | \"flushInterval\" | \"apiUrl\">\n > &\n AxiomTransportOptions;\n\n constructor(options: AxiomTransportOptions) {\n this.options = {\n batchSize: 100,\n flushInterval: 5000,\n apiUrl: \"https://api.axiom.co\",\n ...options,\n };\n\n // Start flush interval if enabled\n if (this.options.flushInterval > 0) {\n this.flushTimer = setInterval(\n () => this.flush(),\n this.options.flushInterval\n );\n }\n }\n\n log(entry: LogEntry): void {\n if (this.options.enabled === false) return;\n\n const event: AxiomEvent = {\n _time: entry.timestamp,\n level: entry.level,\n message: entry.message,\n };\n\n // Add context fields\n if (entry.context) {\n Object.assign(event, entry.context);\n }\n\n // Add error fields\n if (entry.error) {\n event[\"error.name\"] = entry.error.name;\n event[\"error.message\"] = entry.error.message;\n event[\"error.stack\"] = entry.error.stack;\n }\n\n this.buffer.push(event);\n\n // Flush if buffer is full\n if (this.buffer.length >= this.options.batchSize) {\n this.flush();\n }\n }\n\n async flush(): Promise<void> {\n // Prevent concurrent flushes\n if (this.isFlushing || this.buffer.length === 0) return;\n\n this.isFlushing = true;\n const events = this.buffer;\n this.buffer = [];\n\n try {\n const response = await fetch(\n `${this.options.apiUrl}/v1/datasets/${this.options.dataset}/ingest`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.options.token}`,\n \"Content-Type\": \"application/json\",\n ...(this.options.orgId && {\n \"X-Axiom-Org-Id\": this.options.orgId,\n }),\n },\n body: JSON.stringify(events),\n }\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Axiom ingest failed: ${response.status} ${errorText}`);\n }\n } catch (error) {\n // Call error handler if provided\n if (this.options.onError) {\n this.options.onError(\n error instanceof Error ? error : new Error(String(error)),\n events.length\n );\n } else {\n // Silent fail by default - don't crash the app for logging failures\n console.error(\"[Axiom] Failed to send logs:\", error);\n }\n } finally {\n this.isFlushing = false;\n }\n }\n\n async close(): Promise<void> {\n // Stop flush timer\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n\n // Final flush\n await this.flush();\n }\n}\n\n/**\n * Create an Axiom transport instance.\n *\n * @param options - Axiom transport configuration\n * @returns A new AxiomTransport instance\n *\n * @example\n * ```typescript\n * const axiom = createAxiomTransport({\n * token: 'xaat-xxx',\n * dataset: 'logs'\n * });\n * ```\n */\nexport function createAxiomTransport(\n options: AxiomTransportOptions\n): AxiomTransport {\n return new AxiomTransport(options);\n}\n","/**\n * @parsrun/core - Sentry Transport\n * Error tracking transport for Sentry\n *\n * Supports two modes:\n * 1. HTTP API mode (default) - Zero dependency, works on all runtimes\n * 2. SDK mode (BYOS) - Full features with user-provided Sentry SDK\n *\n * @example HTTP API mode (simple, universal)\n * ```typescript\n * const sentry = new SentryTransport({\n * dsn: 'https://xxx@sentry.io/123',\n * environment: 'production',\n * });\n * ```\n *\n * @example SDK mode (full features)\n * ```typescript\n * import * as Sentry from '@sentry/cloudflare'; // or @sentry/node\n *\n * Sentry.init({ dsn: '...' });\n *\n * const sentry = new SentryTransport({\n * client: Sentry,\n * });\n * ```\n */\n\nimport type { LogEntry } from \"../logger.js\";\nimport type {\n LogTransport,\n ErrorTransport,\n ErrorContext,\n ErrorUser,\n Breadcrumb,\n BaseTransportOptions,\n} from \"./types.js\";\n\n/**\n * Sentry SDK interface (minimal interface for BYOS)\n * Compatible with @sentry/node, @sentry/cloudflare, @sentry/browser, etc.\n */\nexport interface SentryClient {\n captureException(error: Error, hint?: unknown): string;\n captureMessage(message: string, level?: string): string;\n withScope(callback: (scope: SentryScope) => void): void;\n flush?(timeout?: number): Promise<boolean>;\n}\n\nexport interface SentryScope {\n setTag(key: string, value: string): void;\n setUser(user: { id: string; email?: string; [key: string]: unknown } | null): void;\n setExtra(key: string, value: unknown): void;\n setExtras(extras: Record<string, unknown>): void;\n setLevel(level: string): void;\n addBreadcrumb(breadcrumb: unknown): void;\n}\n\n/**\n * Parsed DSN components\n */\ninterface ParsedDSN {\n protocol: string;\n publicKey: string;\n host: string;\n projectId: string;\n}\n\n/**\n * Sentry transport options\n */\nexport interface SentryTransportOptions extends BaseTransportOptions {\n /**\n * Sentry DSN (required for HTTP mode)\n * Format: https://{publicKey}@{host}/{projectId}\n */\n dsn?: string;\n\n /**\n * Sentry SDK client (for BYOS mode)\n * Pass your initialized Sentry client for full SDK features\n */\n client?: SentryClient;\n\n /** Environment name (e.g., 'production', 'staging') */\n environment?: string;\n\n /** Release version */\n release?: string;\n\n /** Server name */\n serverName?: string;\n\n /** Sample rate for error events (0.0 to 1.0) */\n sampleRate?: number;\n\n /** Additional tags to add to all events */\n tags?: Record<string, string>;\n\n /** Callback before sending (return null to drop event) */\n beforeSend?: (event: SentryEvent) => SentryEvent | null;\n\n /** Callback for transport errors */\n onError?: (error: Error) => void;\n}\n\n/**\n * Sentry event structure (simplified)\n */\nexport interface SentryEvent {\n event_id: string;\n timestamp: string;\n platform: string;\n level: \"fatal\" | \"error\" | \"warning\" | \"info\" | \"debug\";\n logger?: string;\n transaction?: string;\n server_name?: string;\n release?: string;\n environment?: string;\n message?: { formatted: string };\n exception?: {\n values: Array<{\n type: string;\n value: string;\n stacktrace?: {\n frames: Array<{\n filename?: string;\n function?: string;\n lineno?: number;\n colno?: number;\n in_app?: boolean;\n }>;\n };\n }>;\n };\n tags?: Record<string, string>;\n extra?: Record<string, unknown>;\n user?: {\n id?: string;\n email?: string;\n username?: string;\n [key: string]: unknown;\n };\n breadcrumbs?: Array<{\n type?: string;\n category?: string;\n message?: string;\n data?: Record<string, unknown>;\n level?: string;\n timestamp?: number;\n }>;\n contexts?: Record<string, Record<string, unknown>>;\n}\n\n/**\n * Sentry Transport\n * Implements both LogTransport and ErrorTransport\n */\nexport class SentryTransport implements LogTransport, ErrorTransport {\n readonly name = \"sentry\";\n\n private readonly client?: SentryClient;\n private readonly dsn?: ParsedDSN;\n private readonly options: SentryTransportOptions;\n private user: ErrorUser | null = null;\n private contexts: Map<string, Record<string, unknown>> = new Map();\n private breadcrumbs: Breadcrumb[] = [];\n private readonly maxBreadcrumbs = 100;\n\n constructor(options: SentryTransportOptions) {\n this.options = {\n sampleRate: 1.0,\n ...options,\n };\n\n if (options.client) {\n this.client = options.client;\n } else if (options.dsn) {\n this.dsn = this.parseDSN(options.dsn);\n } else {\n throw new Error(\"SentryTransport requires either 'dsn' or 'client' option\");\n }\n }\n\n /**\n * Parse Sentry DSN\n */\n private parseDSN(dsn: string): ParsedDSN {\n const match = dsn.match(/^(https?):\\/\\/([^@]+)@([^/]+)\\/(.+)$/);\n if (!match || !match[1] || !match[2] || !match[3] || !match[4]) {\n throw new Error(`Invalid Sentry DSN: ${dsn}`);\n }\n return {\n protocol: match[1],\n publicKey: match[2],\n host: match[3],\n projectId: match[4],\n };\n }\n\n /**\n * LogTransport implementation\n * Only sends ERROR and FATAL level logs\n */\n log(entry: LogEntry): void {\n if (this.options.enabled === false) return;\n\n // Only capture errors\n if (entry.levelValue < 50) return; // ERROR = 50, FATAL = 60\n\n if (entry.error) {\n const error = new Error(entry.error.message);\n error.name = entry.error.name;\n if (entry.error.stack) {\n error.stack = entry.error.stack;\n }\n\n this.captureException(\n error,\n entry.context ? { extra: entry.context } : undefined\n );\n } else {\n this.captureMessage(\n entry.message,\n entry.level === \"FATAL\" ? \"error\" : \"warning\",\n entry.context ? { extra: entry.context } : undefined\n );\n }\n }\n\n /**\n * Capture an exception\n */\n captureException(error: Error, context?: ErrorContext): void {\n if (this.options.enabled === false) return;\n if (!this.shouldSample()) return;\n\n if (this.client) {\n this.captureWithSdk(error, context);\n } else {\n this.captureWithHttp(error, context);\n }\n }\n\n /**\n * Capture a message\n */\n captureMessage(\n message: string,\n level: \"info\" | \"warning\" | \"error\",\n context?: ErrorContext\n ): void {\n if (this.options.enabled === false) return;\n if (!this.shouldSample()) return;\n\n if (this.client) {\n this.client.withScope((scope) => {\n this.applyContext(scope, context);\n scope.setLevel(level);\n this.client!.captureMessage(message, level);\n });\n } else {\n this.sendHttpEvent({\n level: level === \"warning\" ? \"warning\" : level === \"info\" ? \"info\" : \"error\",\n message: { formatted: message },\n ...this.buildEventContext(context),\n });\n }\n }\n\n /**\n * Set user context\n */\n setUser(user: ErrorUser | null): void {\n this.user = user;\n }\n\n /**\n * Set custom context\n */\n setContext(name: string, context: Record<string, unknown>): void {\n this.contexts.set(name, context);\n }\n\n /**\n * Add breadcrumb\n */\n addBreadcrumb(breadcrumb: Breadcrumb): void {\n this.breadcrumbs.push({\n ...breadcrumb,\n timestamp: breadcrumb.timestamp ?? Date.now() / 1000,\n });\n\n // Keep only last N breadcrumbs\n if (this.breadcrumbs.length > this.maxBreadcrumbs) {\n this.breadcrumbs = this.breadcrumbs.slice(-this.maxBreadcrumbs);\n }\n }\n\n /**\n * Flush pending events\n */\n async flush(): Promise<void> {\n if (this.client?.flush) {\n await this.client.flush(2000);\n }\n }\n\n // ============================================================================\n // Private Methods\n // ============================================================================\n\n private shouldSample(): boolean {\n const rate = this.options.sampleRate ?? 1.0;\n return Math.random() < rate;\n }\n\n /**\n * Capture with SDK (BYOS mode)\n */\n private captureWithSdk(error: Error, context?: ErrorContext): void {\n this.client!.withScope((scope) => {\n this.applyContext(scope, context);\n this.client!.captureException(error);\n });\n }\n\n /**\n * Apply context to SDK scope\n */\n private applyContext(scope: SentryScope, context?: ErrorContext): void {\n // User\n if (this.user) {\n scope.setUser(this.user);\n } else if (context?.userId) {\n scope.setUser({ id: context.userId });\n }\n\n // Tags\n if (this.options.tags) {\n for (const [key, value] of Object.entries(this.options.tags)) {\n scope.setTag(key, value);\n }\n }\n if (context?.tags) {\n for (const [key, value] of Object.entries(context.tags)) {\n scope.setTag(key, value);\n }\n }\n if (context?.requestId) {\n scope.setTag(\"requestId\", context.requestId);\n }\n if (context?.tenantId) {\n scope.setTag(\"tenantId\", context.tenantId);\n }\n\n // Extra\n if (context?.extra) {\n scope.setExtras(context.extra);\n }\n\n // Breadcrumbs\n for (const bc of this.breadcrumbs) {\n scope.addBreadcrumb(bc);\n }\n }\n\n /**\n * Capture with HTTP API (default mode)\n */\n private captureWithHttp(error: Error, context?: ErrorContext): void {\n const stacktrace = this.parseStackTrace(error.stack);\n const exceptionValue: {\n type: string;\n value: string;\n stacktrace?: { frames: Array<{ filename?: string; function?: string; lineno?: number; colno?: number }> };\n } = {\n type: error.name,\n value: error.message,\n };\n\n if (stacktrace) {\n exceptionValue.stacktrace = stacktrace;\n }\n\n const event: Partial<SentryEvent> = {\n level: \"error\",\n exception: {\n values: [exceptionValue],\n },\n ...this.buildEventContext(context),\n };\n\n this.sendHttpEvent(event);\n }\n\n /**\n * Build event context for HTTP API\n */\n private buildEventContext(context?: ErrorContext): Partial<SentryEvent> {\n const event: Partial<SentryEvent> = {};\n\n // Environment & Release\n if (this.options.environment) {\n event.environment = this.options.environment;\n }\n if (this.options.release) {\n event.release = this.options.release;\n }\n if (this.options.serverName) {\n event.server_name = this.options.serverName;\n }\n\n // Tags\n const tags: Record<string, string> = { ...this.options.tags };\n if (context?.tags) {\n Object.assign(tags, context.tags);\n }\n if (context?.requestId) {\n tags[\"requestId\"] = context.requestId;\n }\n if (context?.tenantId) {\n tags[\"tenantId\"] = context.tenantId;\n }\n if (Object.keys(tags).length > 0) {\n event.tags = tags;\n }\n\n // Extra\n if (context?.extra) {\n event.extra = context.extra;\n }\n\n // User\n if (this.user) {\n event.user = this.user;\n } else if (context?.userId) {\n event.user = { id: context.userId };\n }\n\n // Breadcrumbs\n if (this.breadcrumbs.length > 0) {\n event.breadcrumbs = this.breadcrumbs.map((bc) => {\n const crumb: {\n type?: string;\n category?: string;\n message?: string;\n data?: Record<string, unknown>;\n level?: string;\n timestamp?: number;\n } = {};\n if (bc.type) crumb.type = bc.type;\n if (bc.category) crumb.category = bc.category;\n if (bc.message) crumb.message = bc.message;\n if (bc.data) crumb.data = bc.data;\n if (bc.level) crumb.level = bc.level;\n if (bc.timestamp !== undefined) crumb.timestamp = bc.timestamp;\n return crumb;\n });\n }\n\n // Contexts\n if (this.contexts.size > 0) {\n event.contexts = Object.fromEntries(this.contexts);\n }\n\n return event;\n }\n\n /**\n * Parse error stack trace into Sentry format\n */\n private parseStackTrace(\n stack?: string\n ): { frames: Array<{ filename?: string; function?: string; lineno?: number; colno?: number }> } | undefined {\n if (!stack) return undefined;\n\n const lines = stack.split(\"\\n\").slice(1); // Skip first line (error message)\n const frames: Array<{ filename?: string; function?: string; lineno?: number; colno?: number }> = [];\n\n for (const line of lines) {\n // Parse V8 stack trace format\n const match = line.match(/^\\s*at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/);\n if (match && match[3] && match[4]) {\n const frame: { filename?: string; function?: string; lineno?: number; colno?: number } = {\n function: match[1] || \"<anonymous>\",\n lineno: parseInt(match[3], 10),\n colno: parseInt(match[4], 10),\n };\n if (match[2]) {\n frame.filename = match[2];\n }\n frames.push(frame);\n }\n }\n\n // Sentry expects oldest frame first\n frames.reverse();\n\n return frames.length > 0 ? { frames } : undefined;\n }\n\n /**\n * Generate event ID\n */\n private generateEventId(): string {\n // 32 character hex string\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n }\n\n /**\n * Send event via HTTP API\n */\n private async sendHttpEvent(eventData: Partial<SentryEvent>): Promise<void> {\n if (!this.dsn) return;\n\n const event: SentryEvent = {\n event_id: this.generateEventId(),\n timestamp: new Date().toISOString(),\n platform: \"javascript\",\n level: \"error\",\n ...eventData,\n };\n\n // Apply beforeSend hook\n if (this.options.beforeSend) {\n const result = this.options.beforeSend(event);\n if (result === null) return;\n }\n\n const url = `${this.dsn.protocol}://${this.dsn.host}/api/${this.dsn.projectId}/store/`;\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Sentry-Auth\": [\n \"Sentry sentry_version=7\",\n `sentry_client=pars-sentry/1.0.0`,\n `sentry_key=${this.dsn.publicKey}`,\n ].join(\", \"),\n },\n body: JSON.stringify(event),\n });\n\n if (!response.ok) {\n throw new Error(`Sentry API error: ${response.status}`);\n }\n } catch (error) {\n if (this.options.onError) {\n this.options.onError(error instanceof Error ? error : new Error(String(error)));\n }\n // Silent fail - don't crash the app for logging failures\n }\n }\n}\n\n/**\n * Create a Sentry transport instance.\n *\n * @param options - Sentry transport configuration\n * @returns A new SentryTransport instance\n *\n * @example\n * ```typescript\n * const sentry = createSentryTransport({\n * dsn: 'https://xxx@sentry.io/123',\n * environment: 'production'\n * });\n * ```\n */\nexport function createSentryTransport(options: SentryTransportOptions): SentryTransport {\n return new SentryTransport(options);\n}\n","/**\n * @parsrun/core - Logtape Transport\n * Structured logging transport for Logtape (@logtape/logtape)\n *\n * Logtape is a TypeScript-first structured logging library.\n * This transport bridges Pars Logger to Logtape for advanced logging scenarios.\n *\n * @example BYOS (Bring Your Own SDK)\n * ```typescript\n * import { getLogger, configure } from '@logtape/logtape';\n *\n * // Configure Logtape\n * await configure({\n * sinks: { console: consoleSink() },\n * loggers: [{ category: 'pars', sinks: ['console'], level: 'info' }],\n * });\n *\n * const logtapeLogger = getLogger('pars');\n * const transport = new LogtapeTransport({ logger: logtapeLogger });\n * ```\n *\n * @example Simple mode (creates internal logger)\n * ```typescript\n * const transport = new LogtapeTransport({\n * category: 'my-app',\n * });\n * ```\n */\n\nimport type { LogEntry, LogLevelName } from \"../logger.js\";\nimport type { LogTransport, BaseTransportOptions } from \"./types.js\";\n\n/**\n * Logtape Logger interface (minimal interface for BYOS)\n * Compatible with @logtape/logtape getLogger() return type\n */\nexport interface LogtapeLogger {\n debug(message: string, properties?: Record<string, unknown>): void;\n info(message: string, properties?: Record<string, unknown>): void;\n warn(message: string, properties?: Record<string, unknown>): void;\n warning(message: string, properties?: Record<string, unknown>): void;\n error(message: string, properties?: Record<string, unknown>): void;\n fatal(message: string, properties?: Record<string, unknown>): void;\n}\n\n/**\n * Level mapping from Pars to Logtape\n */\ntype LogtapeLevel = \"debug\" | \"info\" | \"warning\" | \"error\" | \"fatal\";\n\n/**\n * Logtape transport options\n */\nexport interface LogtapeTransportOptions extends BaseTransportOptions {\n /**\n * Logtape logger instance (for BYOS mode)\n * Get this from @logtape/logtape's getLogger()\n */\n logger?: LogtapeLogger;\n\n /**\n * Category name for the logger\n * Only used if logger is not provided (creates a simple fallback logger)\n */\n category?: string;\n\n /**\n * Include timestamp in properties\n * @default true\n */\n includeTimestamp?: boolean;\n\n /**\n * Include level value in properties\n * @default false\n */\n includeLevelValue?: boolean;\n}\n\n/**\n * Simple fallback logger when no Logtape instance is provided\n * Just outputs structured JSON - users should use BYOS for full features\n */\nclass FallbackLogger implements LogtapeLogger {\n constructor(private category: string) {}\n\n private log(level: string, message: string, properties?: Record<string, unknown>): void {\n const entry = {\n level,\n category: this.category,\n msg: message,\n time: new Date().toISOString(),\n ...properties,\n };\n console.log(JSON.stringify(entry));\n }\n\n debug(message: string, properties?: Record<string, unknown>): void {\n this.log(\"debug\", message, properties);\n }\n\n info(message: string, properties?: Record<string, unknown>): void {\n this.log(\"info\", message, properties);\n }\n\n warn(message: string, properties?: Record<string, unknown>): void {\n this.log(\"warn\", message, properties);\n }\n\n warning(message: string, properties?: Record<string, unknown>): void {\n this.log(\"warning\", message, properties);\n }\n\n error(message: string, properties?: Record<string, unknown>): void {\n this.log(\"error\", message, properties);\n }\n\n fatal(message: string, properties?: Record<string, unknown>): void {\n this.log(\"fatal\", message, properties);\n }\n}\n\n/**\n * Logtape Transport\n * Bridges Pars Logger to Logtape\n */\nexport class LogtapeTransport implements LogTransport {\n readonly name = \"logtape\";\n\n private readonly logger: LogtapeLogger;\n private readonly includeTimestamp: boolean;\n private readonly includeLevelValue: boolean;\n private readonly enabled: boolean;\n\n constructor(options: LogtapeTransportOptions = {}) {\n this.enabled = options.enabled !== false;\n this.includeTimestamp = options.includeTimestamp !== false;\n this.includeLevelValue = options.includeLevelValue ?? false;\n\n if (options.logger) {\n this.logger = options.logger;\n } else {\n // Create fallback logger\n this.logger = new FallbackLogger(options.category ?? \"pars\");\n }\n }\n\n log(entry: LogEntry): void {\n if (!this.enabled) return;\n\n const level = this.mapLevel(entry.level);\n const properties = this.buildProperties(entry);\n\n // Call the appropriate log method\n this.logger[level](entry.message, properties);\n }\n\n /**\n * Map Pars log level to Logtape level\n */\n private mapLevel(level: LogLevelName): LogtapeLevel {\n const mapping: Record<LogLevelName, LogtapeLevel> = {\n TRACE: \"debug\",\n DEBUG: \"debug\",\n INFO: \"info\",\n WARN: \"warning\",\n ERROR: \"error\",\n FATAL: \"fatal\",\n SILENT: \"debug\", // Should never be logged\n };\n return mapping[level];\n }\n\n /**\n * Build properties object for Logtape\n */\n private buildProperties(entry: LogEntry): Record<string, unknown> {\n const properties: Record<string, unknown> = {};\n\n // Add timestamp if enabled\n if (this.includeTimestamp) {\n properties[\"timestamp\"] = entry.timestamp;\n }\n\n // Add level value if enabled\n if (this.includeLevelValue) {\n properties[\"levelValue\"] = entry.levelValue;\n }\n\n // Add context\n if (entry.context) {\n Object.assign(properties, entry.context);\n }\n\n // Add error info\n if (entry.error) {\n properties[\"error\"] = {\n name: entry.error.name,\n message: entry.error.message,\n stack: entry.error.stack,\n };\n }\n\n return properties;\n }\n}\n\n/**\n * Create a Logtape transport instance.\n *\n * @param options - Logtape transport configuration\n * @returns A new LogtapeTransport instance\n *\n * @example\n * ```typescript\n * import { getLogger } from '@logtape/logtape';\n *\n * const transport = createLogtapeTransport({\n * logger: getLogger('my-app')\n * });\n * ```\n */\nexport function createLogtapeTransport(\n options?: LogtapeTransportOptions\n): LogtapeTransport {\n return new LogtapeTransport(options);\n}\n","/**\n * @module\n * Core utilities and types for the Pars framework.\n * Edge-compatible with zero dependencies - works in Node.js, Deno, Bun, and Cloudflare Workers.\n *\n * @example\n * ```typescript\n * import {\n * // Runtime detection\n * runtime, isNode, isDeno, isBun, isCloudflare,\n * // Environment\n * getEnv, requireEnv, isDevelopment,\n * // Logging\n * createLogger, logger,\n * // Errors\n * ParsError, ValidationError, NotFoundError,\n * // Utilities\n * generateId, sha256, retry, sleep\n * } from '@parsrun/core';\n *\n * // Create a logger\n * const log = createLogger({ name: 'my-service' });\n * log.info('Service started', { port: 3000 });\n *\n * // Use runtime detection\n * if (isCloudflare()) {\n * // Cloudflare-specific code\n * }\n * ```\n */\n\n// ============================================\n// RUNTIME & ENVIRONMENT\n// ============================================\n\nexport {\n detectRuntime,\n runtime,\n runtimeInfo,\n isNode,\n isDeno,\n isBun,\n isCloudflare,\n isEdge,\n isBrowser,\n isServer,\n getRuntimeVersion,\n type Runtime,\n} from \"./runtime.js\";\n\nexport {\n getEnv,\n requireEnv,\n getEnvNumber,\n getEnvFloat,\n getEnvBoolean,\n getEnvArray,\n getEnvJson,\n setEdgeEnv,\n clearEdgeEnv,\n isDevelopment,\n isProduction,\n isTest,\n getEnvMode,\n createEnvConfig,\n type EnvMode,\n} from \"./env.js\";\n\n// ============================================\n// LOGGING\n// ============================================\n\nexport {\n Logger,\n ConsoleTransport,\n LogLevel,\n createLogger,\n logger,\n logError,\n measureTime,\n createRequestLogger,\n type LogLevelName,\n type LogLevelValue,\n type LogEntry,\n type LogTransport,\n type LoggerConfig,\n} from \"./logger.js\";\n\n// ============================================\n// DECIMAL / MATH\n// ============================================\n\nexport {\n Decimal,\n DecimalUtils,\n decimal,\n} from \"./decimal.js\";\n\n// ============================================\n// TYPES\n// ============================================\n\nexport * from \"./types.js\";\n\n// ============================================\n// ERRORS\n// ============================================\n\nexport * from \"./errors.js\";\n\n// ============================================\n// ERROR CODES\n// ============================================\n\nexport {\n ErrorCodes,\n getErrorCode,\n getErrorCodesByCategory,\n isRetryableError,\n getStatusForCode,\n type ErrorCode,\n type ErrorCategory,\n type ErrorCodeDefinition,\n} from \"./error-codes.js\";\n\n// ============================================\n// TRANSPORTS (additional - ConsoleTransport already in logger.js)\n// ============================================\n\nexport {\n // Error transport types (LogTransport is in logger.js)\n type ErrorTransport,\n type CombinedTransport,\n type ErrorContext,\n type ErrorUser,\n type Breadcrumb,\n type BaseTransportOptions,\n type BatchTransportOptions,\n // Axiom\n AxiomTransport,\n createAxiomTransport,\n type AxiomTransportOptions,\n // Sentry\n SentryTransport,\n createSentryTransport,\n type SentryTransportOptions,\n type SentryClient,\n type SentryEvent,\n // Logtape\n LogtapeTransport,\n createLogtapeTransport,\n type LogtapeTransportOptions,\n type LogtapeLogger,\n} from \"./transports/index.js\";\n\n// ============================================\n// UTILITY FUNCTIONS\n// ============================================\n\n/**\n * Generate a cryptographically secure random string (hex).\n *\n * @param length - Number of random bytes (output will be 2x this length in hex)\n * @returns Promise resolving to a hex string\n *\n * @example\n * ```typescript\n * const token = await generateRandomString(32); // 64 character hex string\n * ```\n */\nexport async function generateRandomString(length: number): Promise<string> {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Generate a UUID v4 using the Web Crypto API.\n *\n * @returns A new UUID v4 string\n *\n * @example\n * ```typescript\n * const id = generateId(); // \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\nexport function generateId(): string {\n return crypto.randomUUID();\n}\n\n/**\n * Hash a string using SHA-256 and return as hex string.\n *\n * @param input - The string to hash\n * @returns Promise resolving to the hex-encoded hash\n *\n * @example\n * ```typescript\n * const hash = await sha256('password123');\n * ```\n */\nexport async function sha256(input: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(input);\n const hash = await crypto.subtle.digest(\"SHA-256\", data);\n return Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Hash a string using SHA-256 and return as ArrayBuffer.\n * Useful when you need the raw bytes for further cryptographic operations.\n *\n * @param input - The string to hash\n * @returns Promise resolving to the raw hash bytes\n *\n * @example\n * ```typescript\n * const hashBytes = await sha256Bytes('data');\n * const key = await crypto.subtle.importKey('raw', hashBytes, 'AES-GCM', false, ['encrypt']);\n * ```\n */\nexport async function sha256Bytes(input: string): Promise<ArrayBuffer> {\n const encoder = new TextEncoder();\n const data = encoder.encode(input);\n return crypto.subtle.digest(\"SHA-256\", data);\n}\n\n/**\n * Constant-time string comparison (timing-safe).\n * Use this for comparing secrets to prevent timing attacks.\n *\n * @param a - First string to compare\n * @param b - Second string to compare\n * @returns True if strings are equal\n *\n * @example\n * ```typescript\n * if (constantTimeEquals(providedToken, storedToken)) {\n * // Token is valid\n * }\n * ```\n */\nexport function constantTimeEquals(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n const aBytes = new TextEncoder().encode(a);\n const bBytes = new TextEncoder().encode(b);\n\n let result = 0;\n for (let i = 0; i < aBytes.length; i++) {\n result |= aBytes[i]! ^ bBytes[i]!;\n }\n\n return result === 0;\n}\n\n/**\n * Sleep for a given number of milliseconds.\n *\n * @param ms - Milliseconds to sleep\n * @returns Promise that resolves after the delay\n *\n * @example\n * ```typescript\n * await sleep(1000); // Wait 1 second\n * ```\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry a function with exponential backoff.\n *\n * @param fn - The async function to retry\n * @param options - Retry configuration options\n * @returns Promise resolving to the function result\n * @throws The last error if all retries fail\n *\n * @example\n * ```typescript\n * const data = await retry(\n * () => fetchFromAPI('/users'),\n * {\n * maxRetries: 3,\n * initialDelayMs: 1000,\n * shouldRetry: (err) => err.status >= 500\n * }\n * );\n * ```\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n options: {\n maxRetries?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n backoffMultiplier?: number;\n shouldRetry?: (error: unknown) => boolean;\n onRetry?: (error: unknown, attempt: number) => void;\n } = {}\n): Promise<T> {\n const {\n maxRetries = 3,\n initialDelayMs = 1000,\n maxDelayMs = 30000,\n backoffMultiplier = 2,\n shouldRetry = () => true,\n onRetry,\n } = options;\n\n let lastError: unknown;\n let delay = initialDelayMs;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n\n if (attempt === maxRetries || !shouldRetry(error)) {\n throw error;\n }\n\n onRetry?.(error, attempt + 1);\n await sleep(delay);\n delay = Math.min(delay * backoffMultiplier, maxDelayMs);\n }\n }\n\n throw lastError;\n}\n\n/**\n * Create a new object with specified keys omitted.\n *\n * @param obj - The source object\n * @param keys - Array of keys to omit\n * @returns A new object without the specified keys\n *\n * @example\n * ```typescript\n * const user = { id: 1, name: 'John', password: 'secret' };\n * const safe = omit(user, ['password']); // { id: 1, name: 'John' }\n * ```\n */\nexport function omit<T extends object, K extends keyof T>(\n obj: T,\n keys: K[]\n): Omit<T, K> {\n const result = { ...obj };\n for (const key of keys) {\n delete result[key];\n }\n return result;\n}\n\n/**\n * Create a new object with only the specified keys.\n *\n * @param obj - The source object\n * @param keys - Array of keys to include\n * @returns A new object with only the specified keys\n *\n * @example\n * ```typescript\n * const user = { id: 1, name: 'John', email: 'john@example.com' };\n * const subset = pick(user, ['id', 'name']); // { id: 1, name: 'John' }\n * ```\n */\nexport function pick<T extends object, K extends keyof T>(\n obj: T,\n keys: K[]\n): Pick<T, K> {\n const result = {} as Pick<T, K>;\n for (const key of keys) {\n if (key in obj) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n\n/**\n * Deep merge two objects recursively.\n *\n * @param target - The target object\n * @param source - The source object to merge from\n * @returns A new merged object\n *\n * @example\n * ```typescript\n * const config = deepMerge(defaults, userConfig);\n * ```\n */\nexport function deepMerge<T extends object>(target: T, source: Partial<T>): T {\n const result = { ...target };\n\n for (const key of Object.keys(source) as (keyof T)[]) {\n const sourceValue = source[key];\n const targetValue = target[key];\n\n if (\n sourceValue !== undefined &&\n typeof sourceValue === \"object\" &&\n sourceValue !== null &&\n !Array.isArray(sourceValue) &&\n typeof targetValue === \"object\" &&\n targetValue !== null &&\n !Array.isArray(targetValue)\n ) {\n result[key] = deepMerge(\n targetValue as object,\n sourceValue as object\n ) as T[keyof T];\n } else if (sourceValue !== undefined) {\n result[key] = sourceValue as T[keyof T];\n }\n }\n\n return result;\n}\n\n/**\n * Create a deep clone of an object.\n * Handles nested objects, arrays, and Date instances.\n *\n * @param obj - The object to clone\n * @returns A deep copy of the object\n *\n * @example\n * ```typescript\n * const original = { nested: { value: 1 }, date: new Date() };\n * const cloned = deepClone(original);\n * cloned.nested.value = 2; // original.nested.value is still 1\n * ```\n */\nexport function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(deepClone) as T;\n }\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as T;\n }\n const cloned = {} as T;\n for (const key of Object.keys(obj) as (keyof T)[]) {\n cloned[key] = deepClone(obj[key]);\n }\n return cloned;\n}\n\n/**\n * Check if a value is a plain object (not an array, Date, etc.).\n * Useful for type guards and deep merge operations.\n *\n * @param value - The value to check\n * @returns True if the value is a plain object\n *\n * @example\n * ```typescript\n * isPlainObject({}); // true\n * isPlainObject({ a: 1 }); // true\n * isPlainObject([]); // false\n * isPlainObject(new Date()); // false\n * isPlainObject(null); // false\n * ```\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\n/**\n * Check if a value is null or undefined.\n * Provides a type guard for narrowing types.\n *\n * @param value - The value to check\n * @returns True if the value is null or undefined\n *\n * @example\n * ```typescript\n * if (!isNil(user)) {\n * console.log(user.name); // TypeScript knows user is not null/undefined\n * }\n * ```\n */\nexport function isNil(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * Check if a value is empty.\n * Considers null, undefined, empty strings (including whitespace-only),\n * empty arrays, and empty objects as empty.\n *\n * @param value - The value to check\n * @returns True if the value is considered empty\n *\n * @example\n * ```typescript\n * isEmpty(null); // true\n * isEmpty(''); // true\n * isEmpty(' '); // true\n * isEmpty([]); // true\n * isEmpty({}); // true\n * isEmpty('hello'); // false\n * isEmpty([1]); // false\n * ```\n */\nexport function isEmpty(value: unknown): boolean {\n if (isNil(value)) return true;\n if (typeof value === \"string\") return value.trim() === \"\";\n if (Array.isArray(value)) return value.length === 0;\n if (isPlainObject(value)) return Object.keys(value).length === 0;\n return false;\n}\n\n/**\n * Normalize an email address by converting to lowercase and trimming whitespace.\n * Use this before storing or comparing email addresses.\n *\n * @param email - The email address to normalize\n * @returns The normalized email address\n *\n * @example\n * ```typescript\n * normalizeEmail(' John.Doe@Example.COM '); // 'john.doe@example.com'\n * ```\n */\nexport function normalizeEmail(email: string): string {\n return email.toLowerCase().trim();\n}\n\n/**\n * Validate that a string is a valid email format.\n * Uses a simple regex that covers most common email formats.\n *\n * @param email - The string to validate\n * @returns True if the string is a valid email format\n *\n * @example\n * ```typescript\n * isValidEmail('user@example.com'); // true\n * isValidEmail('user@sub.example.com'); // true\n * isValidEmail('invalid'); // false\n * isValidEmail('user@'); // false\n * ```\n */\nexport function isValidEmail(email: string): boolean {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n\n/**\n * Generate a URL-friendly slug from a string.\n * Converts to lowercase, replaces non-alphanumeric characters with hyphens,\n * and removes leading/trailing hyphens.\n *\n * @param str - The string to convert\n * @returns A URL-friendly slug\n *\n * @example\n * ```typescript\n * slugify('Hello World!'); // 'hello-world'\n * slugify('My Blog Post Title'); // 'my-blog-post-title'\n * slugify(' Multiple Spaces '); // 'multiple-spaces'\n * ```\n */\nexport function slugify(str: string): string {\n return str\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\n/**\n * Truncate a string to a maximum length, adding a suffix if truncated.\n *\n * @param str - The string to truncate\n * @param maxLength - Maximum length including the suffix\n * @param suffix - String to append when truncated (default: \"...\")\n * @returns The truncated string or original if within maxLength\n *\n * @example\n * ```typescript\n * truncate('Hello World', 8); // 'Hello...'\n * truncate('Hello', 10); // 'Hello'\n * truncate('Long text here', 10, '>>'); // 'Long tex>>'\n * ```\n */\nexport function truncate(str: string, maxLength: number, suffix: string = \"...\"): string {\n if (str.length <= maxLength) return str;\n return str.slice(0, maxLength - suffix.length) + suffix;\n}\n\n/**\n * Create a debounced version of a function.\n * The function will only be called after it stops being called for the specified wait period.\n *\n * @param fn - The function to debounce\n * @param wait - Milliseconds to wait before calling the function\n * @returns A debounced version of the function\n *\n * @example\n * ```typescript\n * const debouncedSearch = debounce((query: string) => {\n * // API call\n * }, 300);\n *\n * // Rapid calls will only trigger one API call after 300ms of inactivity\n * input.addEventListener('input', (e) => debouncedSearch(e.target.value));\n * ```\n */\nexport function debounce<T extends (...args: unknown[]) => unknown>(\n fn: T,\n wait: number\n): (...args: Parameters<T>) => void {\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n return (...args: Parameters<T>) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n fn(...args);\n timeoutId = null;\n }, wait);\n };\n}\n\n/**\n * Create a throttled version of a function.\n * The function will be called at most once per wait period.\n *\n * @param fn - The function to throttle\n * @param wait - Minimum milliseconds between function calls\n * @returns A throttled version of the function\n *\n * @example\n * ```typescript\n * const throttledScroll = throttle(() => {\n * // Handle scroll event\n * }, 100);\n *\n * // Called at most every 100ms during scrolling\n * window.addEventListener('scroll', throttledScroll);\n * ```\n */\nexport function throttle<T extends (...args: unknown[]) => unknown>(\n fn: T,\n wait: number\n): (...args: Parameters<T>) => void {\n let lastTime = 0;\n\n return (...args: Parameters<T>) => {\n const now = Date.now();\n if (now - lastTime >= wait) {\n lastTime = now;\n fn(...args);\n }\n };\n}\n\n/**\n * Create a deferred promise with externally accessible resolve/reject functions.\n * Useful when you need to resolve a promise from outside its executor.\n *\n * @returns An object containing the promise and its resolve/reject functions\n *\n * @example\n * ```typescript\n * const { promise, resolve, reject } = createDeferred<string>();\n *\n * // Later, resolve from elsewhere\n * setTimeout(() => resolve('done!'), 1000);\n *\n * const result = await promise; // 'done!'\n * ```\n */\nexport function createDeferred<T>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (reason?: unknown) => void;\n} {\n let resolve!: (value: T) => void;\n let reject!: (reason?: unknown) => void;\n\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return { promise, resolve, reject };\n}\n\n/**\n * Run promises with concurrency limit.\n *\n * @param tasks - Array of async functions to execute\n * @param concurrency - Maximum concurrent tasks\n * @returns Promise resolving to array of results in order\n *\n * @example\n * ```typescript\n * const results = await pLimit(\n * urls.map(url => () => fetch(url)),\n * 5 // Max 5 concurrent requests\n * );\n * ```\n */\nexport async function pLimit<T>(\n tasks: (() => Promise<T>)[],\n concurrency: number\n): Promise<T[]> {\n const results: T[] = [];\n const executing: Promise<void>[] = [];\n\n for (const [index, task] of tasks.entries()) {\n const p = Promise.resolve().then(async () => {\n results[index] = await task();\n });\n\n executing.push(p);\n\n if (executing.length >= concurrency) {\n await Promise.race(executing);\n executing.splice(\n executing.findIndex((e) => e === p),\n 1\n );\n }\n }\n\n await Promise.all(executing);\n return results;\n}\n"],"mappings":";AA0BO,SAAS,gBAAyB;AAEvC,MAAI,OAAO,eAAe,eAAe,SAAS,YAAY;AAC5D,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,eAAe,eAAe,UAAU,YAAY;AAC7D,WAAO;AAAA,EACT;AAGA,MACE,OAAO,eAAe,eACtB,OAAQ,WAAmB,WAAW,eACtC,OAAQ,WAAmB,YAAY,aACvC;AACA,WAAO;AAAA,EACT;AAGA,MACE,OAAO,eAAe,eACtB,OAAQ,WAAmB,gBAAgB,aAC3C;AACA,WAAO;AAAA,EACT;AAGA,MACE,OAAO,eAAe,eACtB,OAAQ,WAAmB,WAAW,eACtC,OAAQ,WAAmB,aAAa,aACxC;AACA,WAAO;AAAA,EACT;AAGA,MACE,OAAO,YAAY,eACnB,QAAQ,YACR,QAAQ,SAAS,MACjB;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKO,IAAM,UAAU,cAAc;AAK9B,IAAM,cAAc;AAAA,EACzB;AAAA,EACA,QAAQ,YAAY;AAAA,EACpB,QAAQ,YAAY;AAAA,EACpB,OAAO,YAAY;AAAA,EACnB,cAAc,YAAY;AAAA,EAC1B,QAAQ,YAAY,gBAAgB,YAAY,UAAU,YAAY;AAAA,EACtE,WAAW,YAAY;AAAA,EACvB,UAAU,YAAY;AAAA,EACtB,mBAAmB,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