@zharp/node 0.2.0 → 0.3.0
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/README.md +8 -6
- package/dist/index.d.mts +27 -2
- package/dist/index.d.ts +27 -2
- package/dist/index.js +288 -19
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +285 -16
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.26_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/cjs_shims.js","../src/zharp.ts","../../../internal/src/builtins.ts","../../../internal/src/env.ts","../../../internal/src/bodies.ts","../src/bodies.ts","../src/urls.ts","../src/context.ts","../src/console.ts","../../../internal/src/debug-ids.ts","../src/debug-ids.ts","../src/errors.ts","../src/version.ts"],"sourcesContent":["import { ZharpNode } from './zharp';\r\n\r\nexport { ZharpNode } from './zharp';\r\nexport { VERSION } from './version';\r\nexport type { NodeOptions, ZharpUser, Attributes, AttributeValue, CaptureBodies, CaptureBodiesOptions } from './types';\r\n\r\n// One instance per process, kept on globalThis: `instrument.mjs` imports the ES build and the\r\n// application may `require` the CommonJS one, and both must reach the SDK that was started.\r\nconst g = globalThis as any;\r\nexport const Zharp: ZharpNode = g.__ZHARP_NODE__ ?? (g.__ZHARP_NODE__ = new ZharpNode());\r\nexport default Zharp;\r\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","/**\r\n * @zharp/node: the OpenTelemetry Node SDK, configured for Zharp.\r\n *\r\n * Everything that makes spans is OpenTelemetry's — the Node SDK, the auto-instrumentations for\r\n * http, express, fastify, pg, redis, prisma's driver and the rest, the W3C propagators, the\r\n * pino/winston/bunyan log bridges. What is here is the configuration (where to send, with what\r\n * key, under which service), the two processors that put user and session on everything, a\r\n * console bridge, error capture, and a small API in the same shape as every other Zharp SDK.\r\n */\r\nimport { register as registerLoader } from 'node:module';\r\nimport {\r\n type Context,\r\n type DiagLogger,\r\n DiagLogLevel,\r\n diag,\r\n INVALID_SPAN_CONTEXT,\r\n logs,\r\n SeverityNumber,\r\n SpanStatusCode,\r\n trace,\r\n type Logger,\r\n type TextMapGetter,\r\n type TextMapPropagator,\r\n type Span,\r\n type SpanOptions,\r\n} from '@opentelemetry/api';\r\nimport { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from '@opentelemetry/core';\r\nimport { envDetector, hostDetector, resourceFromAttributes } from '@opentelemetry/resources';\r\nimport { NodeSDK } from '@opentelemetry/sdk-node';\r\nimport {\r\n BatchSpanProcessor,\r\n ParentBasedSampler,\r\n SamplingDecision,\r\n TraceIdRatioBasedSampler,\r\n type Sampler,\r\n type SamplingResult,\r\n type SpanProcessor,\r\n} from '@opentelemetry/sdk-trace';\r\nimport { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs';\r\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';\r\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto';\r\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\r\nimport { announce, describeTarget, disabledByEnv, nodeEnv, packageName, pick, warn } from '@zharp/internal/env';\r\nimport { bodySettings } from '@zharp/internal/bodies';\r\nimport { withBodyCapture } from './bodies';\r\nimport { UrlRedactionSpanProcessor } from './urls';\r\nimport { ContextLogProcessor, ContextSpanProcessor, ContextStore, userAttributes } from './context';\r\nimport { captureConsole } from './console';\r\nimport { DebugIdLogProcessor, DebugIdSpanProcessor } from './debug-ids';\r\nimport { asError, exceptionAttributes, SEVERITY, type Level } from './errors';\r\nimport type { Attributes, NodeOptions, ZharpUser } from './types';\r\nimport { VERSION } from './version';\r\n\r\nexport const DEFAULT_ENDPOINT = 'https://api.zharp.io/api/v1/otlp';\r\n\r\n/** How long a flush on the way out may hold the process up. */\r\nconst EXIT_FLUSH_MS = 2_000;\r\n\r\ntype LogFn = (message: unknown, attributes?: Attributes) => void;\r\n\r\nexport class ZharpNode {\r\n private sdk: NodeSDK | null = null;\r\n private spanProcessors: SpanProcessor[] = [];\r\n private logProcessors: LogRecordProcessor[] = [];\r\n private logger: Logger | null = null;\r\n private readonly store = new ContextStore();\r\n private teardowns: Array<() => void> = [];\r\n /** False in logs-only mode (`tracing: false` / `ZHARP_TRACING=false`). */\r\n private tracing = true;\r\n /** Errors already sent, so one that is both rejected and then thrown is reported once. */\r\n private readonly reported = new WeakSet<object>();\r\n\r\n /** `Zharp.log.info(\"Order placed\", { orderId })` — and debug, warn, error, fatal, trace. */\r\n readonly log: Record<Level, LogFn> = {\r\n trace: (m, a) => this.emit('trace', m, a),\r\n debug: (m, a) => this.emit('debug', m, a),\r\n info: (m, a) => this.emit('info', m, a),\r\n warn: (m, a) => this.emit('warn', m, a),\r\n error: (m, a) => this.emit('error', m, a),\r\n fatal: (m, a) => this.emit('fatal', m, a),\r\n };\r\n\r\n /** Whether `init()` started the SDK. */\r\n get isActive(): boolean {\r\n return this.sdk !== null;\r\n }\r\n\r\n /**\r\n * Start sending traces, logs and errors. Call it once, before the application's own modules\r\n * load — from a file preloaded with `node --import` (see the README) — so that http, the\r\n * database drivers and the frameworks are instrumented when they are first imported.\r\n */\r\n init(options: NodeOptions = {}): void {\r\n try {\r\n this.start(options);\r\n } catch (error) {\r\n warn(`Could not start: ${(error as Error)?.message ?? error}`);\r\n }\r\n }\r\n\r\n private start(options: NodeOptions): void {\r\n if (this.sdk) {\r\n warn('Zharp.init() was called again — the first call\\'s settings stay in effect.');\r\n return;\r\n }\r\n if (disabledByEnv()) {\r\n announce('Disabled by ZHARP_DISABLED — nothing will be sent');\r\n return;\r\n }\r\n const key = pick(options.key, nodeEnv('ZHARP_API_KEY'), nodeEnv('ZHARP_KEY'));\r\n if (!key) {\r\n warn('No key found — pass Zharp.init({ key }) or set ZHARP_API_KEY. Nothing will be sent.');\r\n return;\r\n }\r\n const service = pick(options.service, nodeEnv('ZHARP_SERVICE'), nodeEnv('OTEL_SERVICE_NAME'), packageName()) ?? 'node-app';\r\n const environment = pick(options.environment, nodeEnv('ZHARP_ENV'), nodeEnv('NODE_ENV'));\r\n const release = pick(options.release, nodeEnv('ZHARP_RELEASE'), nodeEnv('ZHARP_VERSION'));\r\n const endpoint = (pick(options.endpoint, nodeEnv('ZHARP_ENDPOINT')) ?? DEFAULT_ENDPOINT).replace(/\\/+$/, '');\r\n const tracing = tracingEnabled(options.tracing);\r\n this.tracing = tracing;\r\n\r\n if (options.debug) {\r\n // Bound to the console as it is now, before the bridge patches it: OpenTelemetry's own\r\n // messages about a failed export must not become log records that fail to export.\r\n const out = { error: console.error, warn: console.warn, info: console.info, debug: console.debug, verbose: console.debug };\r\n const prefixed = Object.fromEntries(\r\n Object.entries(out).map(([level, fn]) => [level, (message: string, ...args: unknown[]) => fn.call(console, `[Zharp][otel] ${message}`, ...args)]),\r\n ) as unknown as DiagLogger;\r\n diag.setLogger(prefixed, DiagLogLevel.DEBUG);\r\n }\r\n\r\n // ES modules can only be instrumented through a loader hook, and it has to be in place\r\n // before the application's first import — which is why init() belongs in a preloaded file.\r\n registerEsmHook();\r\n\r\n const headers = { Authorization: `Bearer ${key}` };\r\n const exporterOptions = { headers, compression: 'gzip' as any };\r\n // Logs only: no span exporter at all. The context processor stays, because it is what keeps\r\n // a user set with setUser() to its own request (see RecordOnlySampler).\r\n this.spanProcessors = tracing\r\n ? [\r\n new ContextSpanProcessor(this.store),\r\n new UrlRedactionSpanProcessor(),\r\n new DebugIdSpanProcessor(),\r\n new BatchSpanProcessor({ exporter: new OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) }),\r\n ]\r\n : [new ContextSpanProcessor(this.store)];\r\n this.logProcessors = [\r\n new ContextLogProcessor(this.store),\r\n new DebugIdLogProcessor(),\r\n new BatchLogRecordProcessor({ exporter: new OTLPLogExporter({ ...exporterOptions, url: `${endpoint}/v1/logs` }) }),\r\n ];\r\n\r\n const resource = resourceFromAttributes({\r\n 'service.name': service,\r\n ...(release ? { 'service.version': release } : {}),\r\n ...(environment ? { 'deployment.environment.name': environment } : {}),\r\n 'telemetry.sdk.name': 'zharp',\r\n 'telemetry.sdk.language': 'nodejs',\r\n 'telemetry.sdk.version': VERSION,\r\n 'process.runtime.name': 'nodejs',\r\n 'process.runtime.version': process.versions.node,\r\n });\r\n\r\n const propagator = new CompositePropagator({\r\n propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()],\r\n });\r\n const bodies = bodySettings(options.captureBodies, nodeEnv('ZHARP_CAPTURE_BODIES'));\r\n const rate = typeof options.sampleRate === 'number' ? Math.min(1, Math.max(0, options.sampleRate)) : 1;\r\n\r\n this.sdk = new NodeSDK({\r\n resource,\r\n // Host and OTEL_RESOURCE_ATTRIBUTES only. The process detector would send the command line,\r\n // which is where secrets passed as arguments live.\r\n resourceDetectors: [envDetector, hostDetector],\r\n sampler: tracing ? new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(rate) }) : new RecordOnlySampler(),\r\n textMapPropagator: tracing ? propagator : new ExtractOnlyPropagator(propagator),\r\n spanProcessors: this.spanProcessors,\r\n logRecordProcessors: this.logProcessors,\r\n // Without this the SDK would start an OTLP metrics exporter pointed at localhost:4318.\r\n metricReaders: [],\r\n instrumentations: [\r\n ...(tracing\r\n ? getNodeAutoInstrumentations({\r\n // A span per DNS lookup, socket and file read buries the requests that matter.\r\n '@opentelemetry/instrumentation-dns': { enabled: false },\r\n '@opentelemetry/instrumentation-net': { enabled: false },\r\n '@opentelemetry/instrumentation-fs': { enabled: false },\r\n ...options.instrumentations,\r\n ...(bodies && {\r\n '@opentelemetry/instrumentation-http': withBodyCapture(bodies, options.instrumentations?.['@opentelemetry/instrumentation-http'] as any) as any,\r\n }),\r\n })\r\n : logsOnlyInstrumentations(options)),\r\n ...(options.extraInstrumentations ?? []),\r\n ],\r\n });\r\n this.sdk.start();\r\n this.logger = logs.getLogger('@zharp/node', VERSION);\r\n\r\n if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));\r\n if (options.captureUncaught !== false) this.teardowns.push(this.captureProcessErrors());\r\n this.teardowns.push(this.flushOnExit());\r\n\r\n announce(`Application monitoring active${tracing ? '' : ' (logs only)'} — ${describeTarget(service, environment)}`);\r\n }\r\n\r\n /**\r\n * The user the current request is for: `enduser.id` (and `enduser.email`, `enduser.name`) on\r\n * every span and log of the request from here on, and on the request's own span. Outside a\r\n * request it applies to everything the process sends — for a script or a worker that runs as\r\n * one user.\r\n *\r\n * Requests from a page running @zharp/browser already carry the user in their baggage; this\r\n * is for servers that know the user themselves.\r\n */\r\n setUser(user: ZharpUser | null): void {\r\n try {\r\n this.store.setUser(user && user.id != null && user.id !== '' ? userAttributes(user) : null);\r\n } catch {\r\n // Never throw into the application.\r\n }\r\n }\r\n\r\n /** Forget the user — for the current request, or the process's when called outside one. */\r\n clearUser(): void {\r\n this.setUser(null);\r\n }\r\n\r\n /** An attribute on every span and log sent from now on, e.g. `setTag(\"region\", \"eu-west-1\")`. */\r\n setTag(key: string, value: string | number | boolean | null | undefined): void {\r\n if (value === null || value === undefined) delete this.store.tags[key];\r\n else this.store.tags[key] = value;\r\n }\r\n\r\n /**\r\n * Report an error you caught. It is sent as handled, in the trace of the request it happened\r\n * in, and grouped into an issue with every other occurrence.\r\n */\r\n captureError(error: unknown, attributes?: Attributes): void {\r\n this.report(error, true, 'error', attributes);\r\n }\r\n\r\n /**\r\n * Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A\r\n * throw or rejection marks the span as failed and is passed on unchanged.\r\n */\r\n startSpan<T>(name: string, fn: (span: Span) => T, options: SpanOptions = {}): T {\r\n // Logs only: no span — the callback runs as it is, handed a non-recording stand-in with the\r\n // current trace's ids (so ending or annotating it touches nothing).\r\n if (!this.tracing) return fn(trace.wrapSpanContext(trace.getActiveSpan()?.spanContext() ?? INVALID_SPAN_CONTEXT));\r\n const tracer = trace.getTracer('@zharp/node', VERSION);\r\n return tracer.startActiveSpan(name, options, (span) => {\r\n const fail = (error: unknown) => {\r\n span.setStatus({ code: SpanStatusCode.ERROR, message: asError(error).message });\r\n span.end();\r\n };\r\n let result: T;\r\n try {\r\n result = fn(span);\r\n } catch (error) {\r\n fail(error);\r\n throw error;\r\n }\r\n if (result && typeof (result as any).then === 'function') {\r\n return (result as any).then(\r\n (value: unknown) => {\r\n span.end();\r\n return value;\r\n },\r\n (error: unknown) => {\r\n fail(error);\r\n throw error;\r\n },\r\n ) as T;\r\n }\r\n span.end();\r\n return result;\r\n });\r\n }\r\n\r\n /** Send everything waiting now. Await it before a serverless function returns. */\r\n async flush(timeoutMs = 5_000): Promise<void> {\r\n const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {})));\r\n await Promise.race([all, new Promise((resolve) => setTimeout(resolve, timeoutMs).unref())]);\r\n }\r\n\r\n /** Flush, stop, and put back everything that was patched. */\r\n async shutdown(): Promise<void> {\r\n const sdk = this.sdk;\r\n if (!sdk) return;\r\n this.sdk = null;\r\n for (const undo of this.teardowns.splice(0)) undo();\r\n await sdk.shutdown().catch(() => {});\r\n }\r\n\r\n // ── internals ─────────────────────────────────────────────────────────\r\n\r\n private emit(level: Level, message: unknown, attributes?: Attributes): void {\r\n try {\r\n if (!this.logger) return;\r\n const extra: Record<string, unknown> = {};\r\n // An Error among the attributes is the reason for the log: it is sent as the exception,\r\n // so `Zharp.log.error(\"Payment failed\", { error })` becomes an issue with its stack.\r\n for (const [key, value] of Object.entries(attributes ?? {})) {\r\n if (value instanceof Error && (level === 'error' || level === 'fatal') && !extra['exception.type']) {\r\n Object.assign(extra, exceptionAttributes(value, true));\r\n } else {\r\n extra[key] = value instanceof Error ? `${value.name}: ${value.message}` : value;\r\n }\r\n }\r\n this.logger.emit({\r\n severityNumber: SEVERITY[level] as SeverityNumber,\r\n severityText: level.toUpperCase(),\r\n body: typeof message === 'string' ? message : message instanceof Error ? message.message : safeJson(message),\r\n attributes: extra as any,\r\n });\r\n } catch {\r\n // Never throw into the application.\r\n }\r\n }\r\n\r\n private report(value: unknown, handled: boolean, level: Level, attributes?: Attributes): void {\r\n try {\r\n if (!this.logger) return;\r\n const error = asError(value);\r\n if (value && typeof value === 'object') {\r\n if (this.reported.has(value)) return;\r\n this.reported.add(value);\r\n }\r\n const exception = exceptionAttributes(error, handled);\r\n this.logger.emit({\r\n severityNumber: SEVERITY[level] as SeverityNumber,\r\n severityText: level.toUpperCase(),\r\n body: `${exception['exception.type']}: ${exception['exception.message']}`,\r\n attributes: { ...(attributes as any), ...exception },\r\n });\r\n // An error in a request fails that request's span, so the trace shows where it broke.\r\n if (!handled) trace.getActiveSpan()?.setStatus({ code: SpanStatusCode.ERROR, message: error.message });\r\n } catch {\r\n // As above.\r\n }\r\n }\r\n\r\n /**\r\n * Uncaught exceptions and unhandled rejections, reported as unhandled.\r\n *\r\n * Listening for either changes what Node does — it no longer exits — so when Zharp's listener\r\n * is the only one, it finishes the job the way Node would have: print the error, then exit\r\n * with code 1, after the error has been sent. When the application has listeners of its own,\r\n * they decide, and Zharp only reports.\r\n */\r\n private captureProcessErrors(): () => void {\r\n const onException = (error: unknown, origin?: string) => {\r\n this.report(error, false, 'fatal', origin ? { 'zharp.mechanism': origin } : undefined);\r\n if (process.listenerCount('uncaughtException') > 1) return;\r\n this.crash(error);\r\n };\r\n const onRejection = (reason: unknown) => {\r\n this.report(reason, false, 'error', { 'zharp.mechanism': 'unhandledRejection' });\r\n if (process.listenerCount('unhandledRejection') > 1) return;\r\n const mode = unhandledRejectionsMode();\r\n if (mode === 'warn' || mode === 'none') return;\r\n if (mode === 'warn-with-error-code') {\r\n process.exitCode = 1;\r\n return;\r\n }\r\n this.crash(reason);\r\n };\r\n process.on('uncaughtException', onException);\r\n process.on('unhandledRejection', onRejection);\r\n return () => {\r\n process.off('uncaughtException', onException);\r\n process.off('unhandledRejection', onRejection);\r\n };\r\n }\r\n\r\n private crashing = false;\r\n\r\n private crash(error: unknown): void {\r\n if (this.crashing) return;\r\n this.crashing = true;\r\n try {\r\n // Straight to stderr, not console.error: the console is captured, and this is already sent.\r\n const text = error instanceof Error ? error.stack || String(error) : `Uncaught ${safeJson(error)}`;\r\n process.stderr.write(`${text}\\n\\nNode.js ${process.version}\\n`);\r\n } catch {\r\n // Exit regardless.\r\n }\r\n this.flush(EXIT_FLUSH_MS).finally(() => process.exit(1));\r\n }\r\n\r\n /**\r\n * Send what is waiting when the process ends on its own (the event loop drains) or is told to\r\n * stop. A signal listener also replaces Node's default of exiting, so once the flush is done,\r\n * if no one else is listening, the signal is raised again with Zharp's listener gone.\r\n */\r\n private flushOnExit(): () => void {\r\n let flushing = false;\r\n const onBeforeExit = () => {\r\n if (flushing) return;\r\n flushing = true;\r\n this.flush(EXIT_FLUSH_MS).finally(() => (flushing = false));\r\n };\r\n process.on('beforeExit', onBeforeExit);\r\n\r\n const signals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];\r\n const handlers = signals.map((signal) => {\r\n const handler = () => {\r\n this.flush(EXIT_FLUSH_MS).finally(() => {\r\n process.off(signal, handler);\r\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\r\n });\r\n };\r\n process.on(signal, handler);\r\n return [signal, handler] as const;\r\n });\r\n\r\n return () => {\r\n process.off('beforeExit', onBeforeExit);\r\n for (const [signal, handler] of handlers) process.off(signal, handler);\r\n };\r\n }\r\n}\r\n\r\n/** `--unhandled-rejections=…` from the command line or NODE_OPTIONS; `throw` when unset. */\r\nfunction unhandledRejectionsMode(): string {\r\n const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? '').split(/\\s+/)];\r\n for (const flag of flags) {\r\n const match = /^--unhandled-rejections=(.+)$/.exec(flag);\r\n if (match) return match[1];\r\n }\r\n return 'throw';\r\n}\r\n\r\nfunction safeJson(value: unknown): string {\r\n try {\r\n return typeof value === 'string' ? value : JSON.stringify(value) ?? String(value);\r\n } catch {\r\n return String(value);\r\n }\r\n}\r\n\r\n/** Register OpenTelemetry's ES module loader hook, once per process. */\r\nfunction registerEsmHook(): void {\r\n const g = globalThis as any;\r\n if (g.__ZHARP_ESM_HOOK__) return;\r\n g.__ZHARP_ESM_HOOK__ = true;\r\n try {\r\n // Resolved from this package, which depends on @opentelemetry/instrumentation directly.\r\n registerLoader?.('@opentelemetry/instrumentation/hook.mjs', import.meta.url);\r\n } catch {\r\n // Older Node without module.register: CommonJS is still instrumented.\r\n }\r\n}\r\n\r\n/**\r\n * `tracing` from the option, else `ZHARP_TRACING` (`false`, `0`, `no`, `off` turn it off).\r\n * On unless one of them says otherwise.\r\n */\r\nfunction tracingEnabled(option: boolean | undefined): boolean {\r\n if (typeof option === 'boolean') return option;\r\n const value = nodeEnv('ZHARP_TRACING');\r\n return !(value && /^(false|0|no|off)$/i.test(value));\r\n}\r\n\r\n/**\r\n * Logs only: the log bridges (pino, winston, bunyan) and the http *server* instrumentation —\r\n * nothing else. The http server side is there only to give each incoming request a context: it\r\n * reads the caller's `traceparent` and `baggage`, so the request's logs carry the caller's trace\r\n * id, session and user (and a fresh trace id of their own when the caller sent none). Its one\r\n * span per request is never exported. Outgoing requests are not patched at all, and nothing is\r\n * injected into them.\r\n */\r\nfunction logsOnlyInstrumentations(options: NodeOptions) {\r\n // getNodeAutoInstrumentations has no \"only these\" option, but it honours this variable — set\r\n // for the duration of the call alone.\r\n const previous = process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;\r\n process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = 'http,pino,winston,bunyan';\r\n try {\r\n return getNodeAutoInstrumentations({\r\n ...options.instrumentations,\r\n '@opentelemetry/instrumentation-http': {\r\n ...options.instrumentations?.['@opentelemetry/instrumentation-http'],\r\n disableOutgoingRequestInstrumentation: true,\r\n },\r\n });\r\n } finally {\r\n if (previous === undefined) delete process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;\r\n else process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = previous;\r\n }\r\n}\r\n\r\n/**\r\n * Logs only: every span is recorded (so the context processor sees it start and end, which is\r\n * what scopes setUser() to a request) and none is sampled (so nothing could export it, and the\r\n * flags say so). Spans live in memory for the length of the request and are then dropped.\r\n */\r\nclass RecordOnlySampler implements Sampler {\r\n shouldSample(): SamplingResult {\r\n return { decision: SamplingDecision.RECORD };\r\n }\r\n\r\n toString(): string {\r\n return 'ZharpRecordOnlySampler';\r\n }\r\n}\r\n\r\n/** Reads `traceparent` and `baggage` from incoming requests; never writes them anywhere. */\r\nclass ExtractOnlyPropagator implements TextMapPropagator {\r\n constructor(private readonly inner: TextMapPropagator) {}\r\n\r\n inject(): void {}\r\n\r\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\r\n return this.inner.extract(context, carrier, getter);\r\n }\r\n\r\n fields(): string[] {\r\n return [];\r\n }\r\n}\r\n","/**\n * Load a Node built-in module, or nothing at all outside Node.\n *\n * `process.getBuiltinModule` (Node 20.16+, 22.3+) is tried first because it is the only way in\n * that works from the ESM build: an ES module has no `require`, and the shim the bundler leaves\n * in its place throws. Without it, native-ESM applications silently lost HTTP tracing and kept\n * the active span in a single variable that every concurrent request overwrote.\n *\n * `require` remains the fallback for the CommonJS build on older Node. It is reached\n * indirectly so a bundler building for the browser does not try to resolve a Node built-in and\n * either fail or pull in a shim.\n *\n * @param name - Built-in name without the `node:` prefix, e.g. `http`\n */\nexport function loadBuiltin(name: string): any | null {\n try {\n const proc: any = typeof process !== 'undefined' ? process : undefined;\n if (proc && typeof proc.getBuiltinModule === 'function') {\n return proc.getBuiltinModule(`node:${name}`) ?? null;\n }\n const req = typeof module !== 'undefined' && typeof require === 'function' ? require : null;\n return req ? req(name) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Make a patch to a built-in visible to ES-module named imports.\n *\n * `import { request } from 'node:http'` is a snapshot of the module's exports, so replacing\n * `http.request` is not seen there until Node is told to resynchronise. A no-op where the\n * function does not exist.\n */\nexport function syncBuiltinExports(): void {\n try {\n loadBuiltin('module')?.syncBuiltinESMExports?.();\n } catch {\n // Older Node; named imports keep the unpatched function, default imports still see it.\n }\n}\n","/**\n * Configuration from the environment, and the lines printed at startup.\n *\n * Both packages start the way dd-trace does: `init()` with no arguments reads the environment,\n * explicit options override it, and the result is announced in one line so it is obvious from\n * the first few lines of output whether — and as what — the application is reporting.\n */\n\nimport { loadBuiltin } from './builtins';\n\n/**\n * An environment variable, in Node only.\n *\n * Browser bundles often carry a `process` shim whose `env` was baked in at build time — reading\n * it there would tag a page with the build machine's NODE_ENV — so a browser reads nothing.\n */\nexport function nodeEnv(name: string): string | undefined {\n if (typeof window !== 'undefined' || typeof process === 'undefined' || !process.env) return undefined;\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\n/** What a deployment can set without touching code. Every field may be absent. */\nexport interface EnvConfig {\n apiKey?: string;\n service?: string;\n environment?: string;\n version?: string;\n source?: string;\n endpoint?: string;\n /** Raw `ZHARP_CAPTURE_CONSOLE`: `all`, or a list such as `warn,error`. */\n captureConsole?: string;\n}\n\n/**\n * Everything the environment says, in Node. Empty in a browser.\n *\n * | Setting | Variables |\n * |---------------|---------------------------------------------|\n * | `apiKey` | `ZHARP_API_KEY` |\n * | `service` | `ZHARP_SERVICE`, then `OTEL_SERVICE_NAME` |\n * | `environment` | `ZHARP_ENV`, then `NODE_ENV` |\n * | `version` | `ZHARP_VERSION` |\n * | `source` | `ZHARP_SOURCE` |\n * | `endpoint` | `ZHARP_ENDPOINT` |\n * | `captureConsole` | `ZHARP_CAPTURE_CONSOLE` (logs only) |\n */\nexport function readEnv(): EnvConfig {\n return {\n apiKey: nodeEnv('ZHARP_API_KEY'),\n service: nodeEnv('ZHARP_SERVICE') || nodeEnv('OTEL_SERVICE_NAME'),\n environment: nodeEnv('ZHARP_ENV') || nodeEnv('NODE_ENV'),\n version: nodeEnv('ZHARP_VERSION'),\n source: nodeEnv('ZHARP_SOURCE'),\n endpoint: nodeEnv('ZHARP_ENDPOINT'),\n captureConsole: nodeEnv('ZHARP_CAPTURE_CONSOLE'),\n };\n}\n\n/**\n * The app's own name, from the nearest package.json above the script Node was started with (or\n * the working directory) — the name a service gets when none is configured, as dd-trace does.\n * A scope is dropped: \"@acme/checkout-api\" is \"checkout-api\". Nothing in a browser.\n */\nexport function packageName(): string | undefined {\n if (typeof window !== 'undefined' || typeof process === 'undefined') return undefined;\n const fs = loadBuiltin('fs');\n const path = loadBuiltin('path');\n if (!fs || !path) return undefined;\n const starts = [process.argv?.[1] ? path.dirname(path.resolve(process.argv[1])) : '', process.cwd?.() ?? ''];\n for (const start of starts.filter(Boolean)) {\n let dir = start;\n for (let i = 0; i < 12; i++) {\n // A dependency's own package.json is not the app's.\n if (path.basename(dir) !== 'node_modules') {\n try {\n const name = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))?.name;\n if (typeof name === 'string' && name.trim()) return name.trim().replace(/^@[^/]+\\//, '');\n } catch {\n // No package.json here, or not one we can read: keep looking further up.\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n }\n return undefined;\n}\n\n/** `ZHARP_DISABLED=true` (or `1`, `yes`): start nothing, whatever the code asks for. */\nexport function disabledByEnv(): boolean {\n const value = nodeEnv('ZHARP_DISABLED');\n return !!value && /^(true|1|yes|on)$/i.test(value);\n}\n\n/** The first argument that is a non-empty string — explicit option, then the next fallback. */\nexport function pick(...values: Array<string | undefined | null>): string | undefined {\n for (const value of values) {\n if (typeof value === 'string' && value.trim()) return value.trim();\n }\n return undefined;\n}\n\n/** `service \"checkout-api\", environment \"production\"` — the part both activation lines share. */\nexport function describeTarget(service: string, environment?: string): string {\n return `service \"${service}\", ${environment ? `environment \"${environment}\"` : 'no environment set'}`;\n}\n\n/** Startup output. One prefix, so it can be grepped for. */\nexport function announce(message: string): void {\n console.info(`[Zharp] ${message}`);\n}\n\nexport function warn(message: string): void {\n console.warn(`[Zharp] ${message}`);\n}\n","/**\r\n * Request and response bodies on HTTP spans (`captureBodies`), shared by @zharp/browser and\r\n * @zharp/node, and secrets in URLs.\r\n *\r\n * Off unless the application turns it on. When it is on, bodies are:\r\n * - redacted before they leave the process: field names stay, values under keys that look secret\r\n * (`password`, `token`, `authorization`, `card`, …) become `[Filtered]`, plus any keys the app adds\r\n * - kept readable: an inline image or other long base64 value becomes `[image/png · 24 KB]`, a\r\n * file in a form upload `[file photo.png · image/png · 240 KB]`, and a body that is not text\r\n * at all (an image, a PDF, an event stream) a one-line description of it\r\n * - capped (32 KB by default), with `http.*.body.truncated` set when they were cut\r\n *\r\n * They travel as the span attributes `http.request.body` and `http.response.body`, which the\r\n * trace view shows as a formatted payload.\r\n */\r\n\r\nexport type BodyMode = 'errors' | 'all';\r\n\r\nexport interface CaptureBodiesOptions {\r\n /** `errors` (default): only requests that failed (status 400 and above, or no response). `all`: every request. */\r\n mode?: BodyMode;\r\n /** Characters kept per body. Default 32768 (32 KB), at most 131072 (128 KB). */\r\n maxSize?: number;\r\n /**\r\n * More keys whose values are replaced with `[Filtered]`, on top of the built-in ones. A string\r\n * matches a key ignoring case, `-` and `_` (`\"accountNumber\"` also covers `account_number`); a\r\n * RegExp is tested against the key as it is.\r\n */\r\n redactKeys?: Array<string | RegExp>;\r\n /**\r\n * Which requests have their bodies captured. A bare host (`api.example.com`) matches that\r\n * host; a string with a scheme matches URLs starting with it; a RegExp is tested against the\r\n * full URL. Browser default: same-origin requests and `tracingOrigins` — your own APIs, never\r\n * third parties. Node default: every request.\r\n */\r\n urls?: Array<string | RegExp>;\r\n}\r\n\r\n/** `true` is `'errors'`. */\r\nexport type CaptureBodies = boolean | BodyMode | CaptureBodiesOptions;\r\n\r\nexport interface BodySettings {\r\n mode: BodyMode;\r\n maxSize: number;\r\n extraKeys: Array<string | RegExp>;\r\n urls?: Array<string | RegExp>;\r\n}\r\n\r\nexport const DEFAULT_MAX_BODY = 32 * 1024;\r\nexport const MAX_BODY = 128 * 1024;\r\nexport const FILTERED = '[Filtered]';\r\n\r\n/** Raw text read before shortening and capping: inline images shrink to a few words, so more is read than is kept. */\r\nexport function rawLimit(settings: BodySettings): number {\r\n return Math.max(64 * 1024, settings.maxSize * 2);\r\n}\r\n\r\nexport const BODY_ATTRIBUTES = {\r\n request: 'http.request.body',\r\n requestTruncated: 'http.request.body.truncated',\r\n requestType: 'http.request.header.content-type',\r\n response: 'http.response.body',\r\n responseTruncated: 'http.response.body.truncated',\r\n responseType: 'http.response.header.content-type',\r\n} as const;\r\n\r\n/** The setting as one shape, or null when bodies are off. `env` is `ZHARP_CAPTURE_BODIES` (`errors`, `all`, `off`). */\r\nexport function bodySettings(option: CaptureBodies | undefined, env?: string): BodySettings | null {\r\n let value: CaptureBodies | undefined = option;\r\n if (value === undefined && env) {\r\n const e = env.trim().toLowerCase();\r\n if (e === 'errors' || e === 'all') value = e;\r\n else if (/^(true|1|yes|on)$/.test(e)) value = true;\r\n }\r\n if (!value) return null;\r\n const o: CaptureBodiesOptions = value === true ? {} : typeof value === 'string' ? { mode: value } : value;\r\n const size = typeof o.maxSize === 'number' && o.maxSize > 0 ? Math.min(Math.floor(o.maxSize), MAX_BODY) : DEFAULT_MAX_BODY;\r\n return { mode: o.mode === 'all' ? 'all' : 'errors', maxSize: size, extraKeys: o.redactKeys ?? [], urls: o.urls };\r\n}\r\n\r\n/** Whether a request with this outcome has its bodies kept. `status` 0 means no response. */\r\nexport function wanted(settings: BodySettings, status: number): boolean {\r\n return settings.mode === 'all' || !status || status >= 400;\r\n}\r\n\r\n// ── content types ─────────────────────────────────────────────────────────────\r\n\r\nconst mime = (contentType: string | null | undefined) => (contentType ?? '').split(';')[0].trim().toLowerCase();\r\n\r\nexport function isEventStream(contentType: string | null | undefined): boolean {\r\n return mime(contentType) === 'text/event-stream';\r\n}\r\n\r\nexport function isMultipart(contentType: string | null | undefined): boolean {\r\n return mime(contentType) === 'multipart/form-data';\r\n}\r\n\r\n/** Whether a body of this type is text worth showing. An unknown type is given the benefit of the doubt. */\r\nexport function isTextual(contentType: string | null | undefined): boolean {\r\n const type = mime(contentType);\r\n if (!type) return true;\r\n if (type === 'text/event-stream') return false;\r\n return (\r\n type.startsWith('text/') ||\r\n type.endsWith('+json') ||\r\n type.endsWith('+xml') ||\r\n /^application\\/(json|xml|x-www-form-urlencoded|graphql|javascript|x-ndjson|ld\\+json)$/.test(type)\r\n );\r\n}\r\n\r\nfunction isForm(contentType: string | null | undefined): boolean {\r\n return mime(contentType) === 'application/x-www-form-urlencoded';\r\n}\r\n\r\n/** `240 KB`, `1.4 MB`. */\r\nexport function formatSize(bytes: number): string {\r\n if (bytes < 1024) return `${bytes} B`;\r\n if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;\r\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\r\n}\r\n\r\n/** How a file in a form upload is shown: `[file photo.png · image/png · 240 KB]`. */\r\nexport function fileLabel(name: string | undefined, type: string | undefined, size: number | undefined, partial = false): string {\r\n const parts = [`file ${name || 'blob'}`];\r\n if (type) parts.push(type);\r\n if (size !== undefined) parts.push(formatSize(size) + (partial ? '+' : ''));\r\n return `[${parts.join(' · ')}]`;\r\n}\r\n\r\n/** What a body that is not text says instead: `[binary · image/png · 24 KB]`, `[event stream]`. */\r\nexport function describeBody(contentType: string | null | undefined, size?: number, partial = false): string {\r\n if (isEventStream(contentType)) return '[event stream]';\r\n const parts = ['binary'];\r\n const type = mime(contentType);\r\n if (type) parts.push(type);\r\n if (size !== undefined && size > 0) parts.push(formatSize(size) + (partial ? '+' : ''));\r\n return `[${parts.join(' · ')}]`;\r\n}\r\n\r\n// ── redaction ─────────────────────────────────────────────────────────────────\r\n\r\n/** Built-in keys whose values never leave the process, compared without case, `-` or `_`. */\r\nconst CONTAINS = [\r\n 'password', 'passwd', 'passphrase', 'secret', 'token', 'apikey', 'accesskey', 'privatekey',\r\n 'authorization', 'cookie', 'creditcard', 'cardnumber', 'cvv', 'cvc', 'ssn', 'iban', 'sessionid',\r\n 'signature', 'credential',\r\n];\r\nconst EXACT = ['auth', 'pin', 'pwd', 'otp', 'card', 'pan', 'jwt', 'sid', 'codeverifier'];\r\n/** Also secret in a query string, where they are API keys and signed-URL signatures. */\r\nconst URL_EXACT = ['key', 'sig', 'code', 'state', 'session'];\r\n\r\nconst normalize = (key: string) => key.toLowerCase().replace(/[^a-z0-9]/g, '');\r\n\r\nexport function isSecretKey(key: string, extra: Array<string | RegExp> = []): boolean {\r\n const k = normalize(key);\r\n if (!k) return false;\r\n if (EXACT.includes(k) || CONTAINS.some((c) => k.includes(c))) return true;\r\n return extra.some((p) => (p instanceof RegExp ? p.test(key) : normalize(p) === k));\r\n}\r\n\r\nconst DATA_URI = /^data:([\\w.+-]+\\/[\\w.+-]+)?(?:;[\\w=.+-]+)*;base64,([A-Za-z0-9+/=\\s]*)$/;\r\nconst BASE64 = /^[A-Za-z0-9+/_-]{256,}={0,2}$/;\r\n\r\n/** A long base64 value as a short description; other strings as they are. */\r\nfunction shorten(value: string): string {\r\n if (value.length < 256) return value;\r\n const uri = DATA_URI.exec(value);\r\n if (uri) return `[${uri[1] || 'data'} · ${formatSize(Math.floor((uri[2].length * 3) / 4))}]`;\r\n if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 · ${formatSize(Math.floor((value.length * 3) / 4))}]`;\r\n return value;\r\n}\r\n\r\n/** Every value under `value` filtered, its keys kept: `{ brand: \"[Filtered]\", last4: \"[Filtered]\" }`. */\r\nfunction filterAll(value: unknown, depth: number): unknown {\r\n if (depth > 20) return FILTERED;\r\n if (value === null || value === '') return value;\r\n if (Array.isArray(value)) return value.map((v) => filterAll(v, depth + 1));\r\n if (typeof value === 'object') {\r\n const out: Record<string, unknown> = {};\r\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = filterAll(v, depth + 1);\r\n return out;\r\n }\r\n return FILTERED;\r\n}\r\n\r\nexport function redactValue(value: unknown, extra: Array<string | RegExp>, depth = 0): unknown {\r\n if (typeof value === 'string') return shorten(value);\r\n if (depth > 20 || value === null || typeof value !== 'object') return value;\r\n if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth + 1));\r\n const out: Record<string, unknown> = {};\r\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\r\n out[k] = isSecretKey(k, extra) ? filterAll(v, depth + 1) : redactValue(v, extra, depth + 1);\r\n }\r\n return out;\r\n}\r\n\r\n/**\r\n * Text that did not parse (cut-off JSON, a body that only looks like JSON): `\"key\": value`\r\n * pairs under secret keys are filtered where they appear, and long base64 runs shortened.\r\n */\r\nfunction redactLoose(text: string, extra: Array<string | RegExp>): string {\r\n // A quoted run of base64 (an inline image), possibly cut off before its closing quote.\r\n const runs = /\"((?:data:[\\w.+-]+\\/[\\w.+-]+(?:;[\\w=.+-]+)*;base64,)?[A-Za-z0-9+/_=-]{256,})(\"?)/g;\r\n return text\r\n .replace(runs, (match, run: string, close: string) => {\r\n const short = shorten(run);\r\n if (short === run) return match;\r\n return close ? `\"${short}\"` : `\"${short.slice(0, -1)}+]\"`;\r\n })\r\n .replace(\r\n /(\"([^\"\\\\]{1,100})\"\\s*:\\s*)(\"(?:[^\"\\\\]|\\\\.)*\"?|-?\\d[\\d.eE+-]*|true|false)/g,\r\n (match, prefix: string, key: string) => (isSecretKey(key, extra) ? `${prefix}\"${FILTERED}\"` : match),\r\n );\r\n}\r\n\r\nfunction redactForm(text: string, extra: Array<string | RegExp>): string {\r\n return text\r\n .split('&')\r\n .map((pair) => {\r\n const eq = pair.indexOf('=');\r\n if (eq < 0) return pair;\r\n let key = pair.slice(0, eq);\r\n try {\r\n key = decodeURIComponent(key.replace(/\\+/g, ' '));\r\n } catch {}\r\n if (isSecretKey(key, extra)) return `${pair.slice(0, eq)}=${FILTERED}`;\r\n const value = pair.slice(eq + 1);\r\n return value.length >= 256 ? `${pair.slice(0, eq)}=${shortenEncoded(value)}` : pair;\r\n })\r\n .join('&');\r\n}\r\n\r\nfunction shortenEncoded(value: string): string {\r\n try {\r\n const decoded = decodeURIComponent(value.replace(/\\+/g, ' '));\r\n const short = shorten(decoded);\r\n return short === decoded ? value : short;\r\n } catch {\r\n return value;\r\n }\r\n}\r\n\r\n// ── the attribute value ───────────────────────────────────────────────────────\r\n\r\n/**\r\n * A body as it is sent: redacted, then cut to `maxSize`. `cut` says the text was already cut\r\n * short where it was read. Null for an empty body. A `multipart/form-data` body is passed as the\r\n * JSON of its fields (files already described).\r\n */\r\nexport function formatBody(\r\n text: string | null | undefined,\r\n contentType: string | null | undefined,\r\n settings: BodySettings,\r\n cut = false,\r\n): { value: string; truncated: boolean } | null {\r\n if (text == null) return null;\r\n let body = String(text);\r\n if (!body.trim()) return null;\r\n\r\n if (isForm(contentType)) body = redactForm(body, settings.extraKeys);\r\n else {\r\n let parsed: unknown;\r\n let ok = false;\r\n const trimmed = body.trim();\r\n if (!cut && (trimmed[0] === '{' || trimmed[0] === '[')) {\r\n try {\r\n parsed = JSON.parse(trimmed);\r\n ok = true;\r\n } catch {}\r\n }\r\n body = ok ? JSON.stringify(redactValue(parsed, settings.extraKeys)) : redactLoose(body, settings.extraKeys);\r\n }\r\n\r\n const truncated = cut || body.length > settings.maxSize;\r\n return { value: body.length > settings.maxSize ? body.slice(0, settings.maxSize) : body, truncated };\r\n}\r\n\r\nfunction typeKey(side: 'request' | 'response') {\r\n return side === 'request' ? BODY_ATTRIBUTES.requestType : BODY_ATTRIBUTES.responseType;\r\n}\r\n\r\n/**\r\n * The span attributes for one side of a request (`request` or `response`). A body that is not\r\n * text is described (`size` in bytes when known) instead of left out.\r\n */\r\nexport function bodyAttributes(\r\n side: 'request' | 'response',\r\n text: string | null | undefined,\r\n contentType: string | null | undefined,\r\n settings: BodySettings,\r\n cut = false,\r\n): Record<string, unknown> {\r\n if (!isTextual(contentType) && !isMultipart(contentType)) return {};\r\n const formatted = formatBody(text, contentType, settings, cut);\r\n if (!formatted) return {};\r\n const attributes: Record<string, unknown> = { [BODY_ATTRIBUTES[side]]: formatted.value };\r\n if (formatted.truncated) attributes[side === 'request' ? BODY_ATTRIBUTES.requestTruncated : BODY_ATTRIBUTES.responseTruncated] = true;\r\n if (contentType) attributes[typeKey(side)] = contentType;\r\n return attributes;\r\n}\r\n\r\n/** The attributes for a body that is not text: what it was, not what it said. */\r\nexport function describedAttributes(side: 'request' | 'response', contentType: string | null | undefined, size?: number, partial = false): Record<string, unknown> {\r\n const attributes: Record<string, unknown> = { [BODY_ATTRIBUTES[side]]: describeBody(contentType, size, partial) };\r\n if (contentType) attributes[typeKey(side)] = contentType;\r\n return attributes;\r\n}\r\n\r\n// ── URLs ──────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * A URL as it is recorded: query values under secret-looking keys (`token`, `key`, `sig`,\r\n * `password`, …) become `[Filtered]`, and `user:password@` is dropped. Anything that is not\r\n * a URL is returned as it is.\r\n */\r\nexport function redactUrl(url: string, extra: Array<string | RegExp> = []): string {\r\n if (!url) return url;\r\n let out = url.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/?#@]*@/i, '$1');\r\n const q = out.indexOf('?');\r\n if (q < 0) return out;\r\n const hash = out.indexOf('#', q);\r\n const query = out.slice(q + 1, hash < 0 ? undefined : hash);\r\n const redacted = redactQuery(query, extra);\r\n if (redacted !== query) out = out.slice(0, q + 1) + redacted + (hash < 0 ? '' : out.slice(hash));\r\n return out;\r\n}\r\n\r\n/** A query string (without `?`) with secret-looking values filtered. */\r\nexport function redactQuery(query: string, extra: Array<string | RegExp> = []): string {\r\n if (!query) return query;\r\n return query\r\n .split('&')\r\n .map((pair) => {\r\n const eq = pair.indexOf('=');\r\n if (eq < 0) return pair;\r\n let key = pair.slice(0, eq);\r\n try {\r\n key = decodeURIComponent(key.replace(/\\+/g, ' '));\r\n } catch {}\r\n const secret = isSecretKey(key, extra) || URL_EXACT.includes(normalize(key));\r\n return secret && eq < pair.length - 1 ? `${pair.slice(0, eq)}=${FILTERED}` : pair;\r\n })\r\n .join('&');\r\n}\r\n\r\n/**\r\n * Whether `url` matches one of `patterns`: a bare host (with or without a port) matches that\r\n * host; a string with a scheme matches as a prefix; a RegExp is tested against the URL.\r\n */\r\nexport function urlMatches(url: string, patterns: Array<string | RegExp>): boolean {\r\n let host = '';\r\n let hostname = '';\r\n try {\r\n const parsed = new URL(url);\r\n host = parsed.host;\r\n hostname = parsed.hostname;\r\n } catch {}\r\n return patterns.some((p) => {\r\n if (p instanceof RegExp) return p.test(url);\r\n if (!p) return false;\r\n if (p.includes('://')) return url.startsWith(p);\r\n return host === p || hostname === p;\r\n });\r\n}\r\n","/**\r\n * `captureBodies` for Node: request and response bodies on the http instrumentation's spans,\r\n * for incoming requests (SERVER) and outgoing ones (CLIENT, http/https — axios, got, node-fetch).\r\n *\r\n * Nothing changes how the application reads or writes its streams. Readable sides (an incoming\r\n * request, an outgoing request's response) are seen through their own `emit('data')`, which\r\n * fires whichever way the app consumes them — listeners, pipe, async iteration — without\r\n * switching them into flowing mode. Writable sides (a server response, an outgoing request)\r\n * are seen through `write`/`end`. What is kept depends on the body:\r\n * - text: the first bytes, up to the raw limit\r\n * - a form upload (`multipart/form-data`): each text field, and each file as its name, type and\r\n * size — file bytes are counted as they pass, never kept\r\n * - anything else (an image, a PDF, an event stream): only its size\r\n * Attributes are made in `applyCustomAttributesOnSpan`, which runs just before the span ends.\r\n */\r\nimport { ClientRequest, IncomingMessage, ServerResponse } from 'node:http';\r\nimport { brotliDecompressSync, constants, gunzipSync, inflateSync } from 'node:zlib';\r\nimport type { Span } from '@opentelemetry/api';\r\nimport {\r\n bodyAttributes,\r\n describedAttributes,\r\n fileLabel,\r\n isMultipart,\r\n isTextual,\r\n rawLimit,\r\n urlMatches,\r\n wanted,\r\n type BodySettings,\r\n} from '@zharp/internal/bodies';\r\n\r\nconst TAP = Symbol.for('zharp.body');\r\n/** Fields kept from one form upload. */\r\nconst MAX_FIELDS = 200;\r\n\r\n// ── multipart/form-data ───────────────────────────────────────────────────────\r\n\r\ninterface Part {\r\n name: string;\r\n filename?: string;\r\n type?: string;\r\n size: number;\r\n text: Buffer[];\r\n kept: number;\r\n}\r\n\r\n/** Reads a form upload as it streams past: text fields kept (up to `maxText` each), files counted. */\r\nclass Multipart {\r\n private buf: Buffer = Buffer.alloc(0);\r\n private state: 'start' | 'after' | 'headers' | 'body' | 'done' = 'start';\r\n private readonly first: Buffer;\r\n private readonly delimiter: Buffer;\r\n private part: Part | null = null;\r\n private count = 0;\r\n readonly fields: Record<string, unknown> = {};\r\n cut = false;\r\n\r\n constructor(boundary: string, private readonly maxText: number) {\r\n this.first = Buffer.from(`--${boundary}`);\r\n this.delimiter = Buffer.from(`\\r\\n--${boundary}`);\r\n }\r\n\r\n push(chunk: Buffer): void {\r\n if (this.state === 'done') return;\r\n this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : chunk;\r\n for (;;) {\r\n if (this.state === 'start') {\r\n const i = this.buf.indexOf(this.first);\r\n if (i < 0) {\r\n if (this.buf.length > 64 * 1024) this.state = 'done';\r\n return;\r\n }\r\n this.buf = this.buf.subarray(i + this.first.length);\r\n this.state = 'after';\r\n }\r\n if (this.state === 'after') {\r\n if (this.buf.length < 2) return;\r\n if (this.buf[0] === 45 && this.buf[1] === 45) {\r\n this.state = 'done';\r\n this.buf = Buffer.alloc(0);\r\n return;\r\n }\r\n if (this.buf[0] === 13 && this.buf[1] === 10) this.buf = this.buf.subarray(2);\r\n this.state = 'headers';\r\n }\r\n if (this.state === 'headers') {\r\n const i = this.buf.indexOf('\\r\\n\\r\\n');\r\n if (i < 0) {\r\n if (this.buf.length > 16 * 1024) this.state = 'done';\r\n return;\r\n }\r\n this.part = parsePartHeaders(this.buf.subarray(0, i).toString('utf8'));\r\n this.buf = this.buf.subarray(i + 4);\r\n this.state = 'body';\r\n }\r\n if (this.state === 'body') {\r\n const i = this.buf.indexOf(this.delimiter);\r\n if (i >= 0) {\r\n this.consume(this.buf.subarray(0, i));\r\n this.finish(false);\r\n this.buf = this.buf.subarray(i + this.delimiter.length);\r\n this.state = 'after';\r\n if (this.count >= MAX_FIELDS) {\r\n this.state = 'done';\r\n this.cut = true;\r\n return;\r\n }\r\n continue;\r\n }\r\n // Keep what could be the start of the delimiter; the rest belongs to this part.\r\n const keep = this.delimiter.length - 1;\r\n if (this.buf.length > keep) {\r\n this.consume(this.buf.subarray(0, this.buf.length - keep));\r\n this.buf = Buffer.from(this.buf.subarray(this.buf.length - keep));\r\n }\r\n return;\r\n }\r\n return;\r\n }\r\n }\r\n\r\n private consume(bytes: Buffer): void {\r\n const part = this.part;\r\n if (!part || !bytes.length) return;\r\n part.size += bytes.length;\r\n if (part.filename !== undefined) return; // a file: counted, never kept\r\n const room = this.maxText - part.kept;\r\n if (room > 0) {\r\n const slice = bytes.subarray(0, room);\r\n part.text.push(Buffer.from(slice));\r\n part.kept += slice.length;\r\n }\r\n }\r\n\r\n private finish(partial: boolean): void {\r\n const part = this.part;\r\n this.part = null;\r\n if (!part) return;\r\n let value: unknown;\r\n if (part.filename !== undefined) value = fileLabel(part.filename, part.type, part.size, partial);\r\n else {\r\n value = Buffer.concat(part.text).toString('utf8').replace(/�$/, '');\r\n if (part.size > part.kept || partial) this.cut = true;\r\n }\r\n const existing = this.fields[part.name];\r\n this.fields[part.name] = existing === undefined ? value : Array.isArray(existing) ? [...existing, value] : [existing, value];\r\n this.count++;\r\n }\r\n\r\n /** The fields so far, including a part the stream stopped inside. */\r\n result(): { json: string; cut: boolean } {\r\n if (this.part) {\r\n this.consume(this.state === 'body' ? this.buf : Buffer.alloc(0));\r\n this.buf = Buffer.alloc(0);\r\n this.finish(true);\r\n this.cut = true;\r\n }\r\n return { json: JSON.stringify(this.fields), cut: this.cut };\r\n }\r\n}\r\n\r\nfunction parsePartHeaders(head: string): Part {\r\n const disposition = /^content-disposition:(.*)$/im.exec(head)?.[1] ?? '';\r\n const name = /\\bname=\"([^\"]*)\"/i.exec(disposition)?.[1] ?? /\\bname=([^;\\s]+)/i.exec(disposition)?.[1] ?? '';\r\n const filenameStar = /\\bfilename\\*=(?:UTF-8'')?([^;\\s]+)/i.exec(disposition)?.[1];\r\n let filename = /\\bfilename=\"([^\"]*)\"/i.exec(disposition)?.[1];\r\n if (filenameStar) {\r\n try {\r\n filename = decodeURIComponent(filenameStar);\r\n } catch {\r\n filename = filenameStar;\r\n }\r\n }\r\n const type = /^content-type:\\s*(.*)$/im.exec(head)?.[1]?.trim();\r\n return { name, filename, type: filename !== undefined ? type : undefined, size: 0, text: [], kept: 0 };\r\n}\r\n\r\nfunction boundaryOf(contentType: string | undefined): string | undefined {\r\n const m = /boundary=(?:\"([^\"]+)\"|([^;\\s]+))/i.exec(contentType ?? '');\r\n return m ? m[1] ?? m[2] : undefined;\r\n}\r\n\r\n// ── taps ──────────────────────────────────────────────────────────────────────\r\n\r\nclass Tap {\r\n private chunks: Buffer[] = [];\r\n private kept = 0;\r\n /** Every byte seen, kept or not. */\r\n total = 0;\r\n cut = false;\r\n private mode: 'text' | 'count' | 'multipart' | undefined;\r\n multipart?: Multipart;\r\n\r\n /** `typeOf` is asked once, at the first byte, when the content type is surely set. */\r\n constructor(\r\n private readonly settings: BodySettings,\r\n private readonly typeOf: () => string | undefined,\r\n ) {}\r\n\r\n add(chunk: unknown, encoding?: unknown): void {\r\n if (chunk == null || typeof chunk === 'function') return;\r\n let buf: Buffer;\r\n if (typeof chunk === 'string') buf = Buffer.from(chunk, typeof encoding === 'string' && Buffer.isEncoding(encoding) ? encoding : 'utf8');\r\n else if (chunk instanceof Uint8Array) buf = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\r\n else return;\r\n if (!buf.length) return;\r\n this.total += buf.length;\r\n\r\n if (this.mode === undefined) {\r\n const type = this.typeOf();\r\n const boundary = isMultipart(type) ? boundaryOf(type) : undefined;\r\n if (boundary) {\r\n this.mode = 'multipart';\r\n this.multipart = new Multipart(boundary, this.settings.maxSize);\r\n } else this.mode = isTextual(type) ? 'text' : 'count';\r\n }\r\n if (this.mode === 'multipart') return this.multipart!.push(Buffer.from(buf));\r\n if (this.mode === 'count' || this.cut) return;\r\n\r\n const room = rawLimit(this.settings) - this.kept;\r\n if (buf.length > room) {\r\n this.cut = true;\r\n buf = buf.subarray(0, Math.max(0, room));\r\n }\r\n if (buf.length) {\r\n this.chunks.push(Buffer.from(buf));\r\n this.kept += buf.length;\r\n }\r\n }\r\n\r\n /** The text, inflated if it was compressed; null when it cannot be read as text. */\r\n text(encoding: string | undefined): string | null {\r\n let raw = Buffer.concat(this.chunks);\r\n const enc = (encoding ?? '').toLowerCase().trim();\r\n try {\r\n // A cut-off stream still inflates up to where it stops.\r\n const flush = { finishFlush: constants.Z_SYNC_FLUSH };\r\n if (enc === 'gzip' || enc === 'x-gzip') raw = gunzipSync(raw, flush);\r\n else if (enc === 'deflate') raw = inflateSync(raw, flush);\r\n else if (enc === 'br') raw = brotliDecompressSync(raw, { finishFlush: constants.BROTLI_OPERATION_FLUSH });\r\n else if (enc && enc !== 'identity') return null;\r\n } catch {\r\n return null;\r\n }\r\n // A multi-byte character split at the cap decodes as U+FFFD; drop it.\r\n return raw.toString('utf8').replace(/�$/, '');\r\n }\r\n}\r\n\r\n/** The attributes for one side, whatever kind of body it was. */\r\nfunction sideAttributes(\r\n side: 'request' | 'response',\r\n tap: Tap | undefined,\r\n type: string | undefined,\r\n encoding: string | undefined,\r\n settings: BodySettings,\r\n): Record<string, unknown> {\r\n if (!tap || !tap.total) return {};\r\n if (tap.multipart) {\r\n const { json, cut } = tap.multipart.result();\r\n return bodyAttributes(side, json, type, settings, cut);\r\n }\r\n if (!isTextual(type)) return describedAttributes(side, type, tap.total);\r\n const text = tap.text(encoding);\r\n if (text == null) return describedAttributes(side, type, tap.total);\r\n return bodyAttributes(side, text, type, settings, tap.cut);\r\n}\r\n\r\n/** Keeps what a readable stream emits. */\r\nfunction tapReadable(stream: IncomingMessage, tap: Tap): void {\r\n const emit = stream.emit;\r\n stream.emit = function (this: IncomingMessage, event: string | symbol, ...args: any[]) {\r\n if (event === 'data') {\r\n try {\r\n tap.add(args[0]);\r\n } catch {}\r\n }\r\n return emit.call(this, event, ...args);\r\n } as typeof stream.emit;\r\n (stream as any)[TAP] = tap;\r\n}\r\n\r\n/** Keeps what is written to a writable stream. */\r\nfunction tapWritable(stream: ServerResponse | ClientRequest, tap: Tap): void {\r\n const target = stream as any;\r\n const write = target.write;\r\n const end = target.end;\r\n target.write = function (this: unknown, ...args: any[]) {\r\n try {\r\n tap.add(args[0], args[1]);\r\n } catch {}\r\n return write.apply(this, args);\r\n };\r\n target.end = function (this: unknown, ...args: any[]) {\r\n try {\r\n tap.add(args[0], args[1]);\r\n } catch {}\r\n return end.apply(this, args);\r\n };\r\n (stream as any)[TAP] = tap;\r\n}\r\n\r\nconst tapOf = (stream: unknown): Tap | undefined => (stream as any)?.[TAP];\r\n\r\nfunction header(value: unknown): string | undefined {\r\n if (value == null) return undefined;\r\n return Array.isArray(value) ? String(value[0]) : String(value);\r\n}\r\n\r\nfunction incomingUrl(req: IncomingMessage): string {\r\n const proto = (req.socket as any)?.encrypted ? 'https' : 'http';\r\n return `${proto}://${req.headers.host ?? 'localhost'}${req.url ?? '/'}`;\r\n}\r\n\r\n/**\r\n * A header the server sent. Headers given to `writeHead()` alone never reach `getHeader()`, so\r\n * the head as written is read as well.\r\n */\r\nfunction sentHeader(res: ServerResponse, name: string): string | undefined {\r\n const set = header(res.getHeader(name));\r\n if (set) return set;\r\n const head = (res as any)._header;\r\n if (typeof head !== 'string') return undefined;\r\n const match = head.match(new RegExp(`^${name}:[ \\\\t]*(.*)$`, 'im'));\r\n return match ? match[1].trim() : undefined;\r\n}\r\n\r\nfunction outgoingUrl(req: ClientRequest): string {\r\n const r = req as any;\r\n return `${r.protocol ?? 'http:'}//${r.host ?? 'localhost'}${r.path ?? '/'}`;\r\n}\r\n\r\ntype HttpConfig = {\r\n requestHook?: (span: Span, request: any) => void;\r\n responseHook?: (span: Span, response: any) => void;\r\n applyCustomAttributesOnSpan?: (span: Span, request: any, response: any) => void;\r\n [key: string]: unknown;\r\n};\r\n\r\n/**\r\n * The http instrumentation's config with body capture added. Hooks the application set itself\r\n * still run, first.\r\n */\r\nexport function withBodyCapture(settings: BodySettings, config: HttpConfig = {}): HttpConfig {\r\n const allowed = (url: string) => !settings.urls || urlMatches(url, settings.urls);\r\n\r\n return {\r\n ...config,\r\n requestHook(span, request) {\r\n config.requestHook?.(span, request);\r\n try {\r\n if (request instanceof IncomingMessage) {\r\n if (allowed(incomingUrl(request))) tapReadable(request, new Tap(settings, () => header(request.headers['content-type'])));\r\n } else if (request instanceof ClientRequest) {\r\n if (allowed(outgoingUrl(request))) tapWritable(request, new Tap(settings, () => header(request.getHeader('content-type'))));\r\n }\r\n } catch {}\r\n },\r\n responseHook(span, response) {\r\n config.responseHook?.(span, response);\r\n try {\r\n if (response instanceof ServerResponse) {\r\n if (tapOf(response.req) || allowed(incomingUrl(response.req))) tapWritable(response, new Tap(settings, () => sentHeader(response, 'content-type')));\r\n } else if (response instanceof IncomingMessage) {\r\n const req = (response as any).req as ClientRequest | undefined;\r\n if (!req || tapOf(req) || allowed(outgoingUrl(req))) tapReadable(response, new Tap(settings, () => header(response.headers['content-type'])));\r\n }\r\n } catch {}\r\n },\r\n applyCustomAttributesOnSpan(span, request, response) {\r\n config.applyCustomAttributesOnSpan?.(span, request, response);\r\n try {\r\n const status = Number(response?.statusCode) || 0;\r\n if (!wanted(settings, status)) return;\r\n const attributes: Record<string, unknown> = {};\r\n\r\n if (request instanceof ClientRequest) {\r\n Object.assign(\r\n attributes,\r\n sideAttributes('request', tapOf(request), header(request.getHeader('content-type')), header(request.getHeader('content-encoding')), settings),\r\n );\r\n const res = response as IncomingMessage;\r\n Object.assign(\r\n attributes,\r\n sideAttributes('response', tapOf(res), header(res?.headers?.['content-type']), header(res?.headers?.['content-encoding']), settings),\r\n );\r\n } else if (request instanceof IncomingMessage) {\r\n const sentType = header(request.headers['content-type']);\r\n const sent = tapOf(request);\r\n if (sent && sent.total) {\r\n Object.assign(attributes, sideAttributes('request', sent, sentType, header(request.headers['content-encoding']), settings));\r\n } else {\r\n // Read before the hooks were in place (rare): a framework's parsed body will do.\r\n const parsed = (request as any).body;\r\n if (parsed != null && (typeof parsed === 'string' || (typeof parsed === 'object' && !Buffer.isBuffer(parsed)))) {\r\n const text = typeof parsed === 'string' ? parsed : JSON.stringify(parsed);\r\n Object.assign(attributes, bodyAttributes('request', text, isTextual(sentType) ? sentType : 'application/json', settings));\r\n }\r\n }\r\n const res = response as ServerResponse;\r\n Object.assign(attributes, sideAttributes('response', tapOf(res), sentHeader(res, 'content-type'), sentHeader(res, 'content-encoding'), settings));\r\n }\r\n if (Object.keys(attributes).length) span.setAttributes(attributes as any);\r\n } catch {}\r\n },\r\n };\r\n}\r\n","/**\r\n * Secrets in URLs never leave the process: before any span ends, query values under\r\n * secret-looking keys (`token`, `key`, `sig`, `password`, …) in its URL attributes become\r\n * `[Filtered]`, and `user:password@` is dropped. Every span, whatever made it — http, fetch,\r\n * a framework — and whether or not `captureBodies` is on.\r\n */\r\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace';\r\nimport { redactQuery, redactUrl } from '@zharp/internal/bodies';\r\n\r\nconst URL_KEYS = ['url.full', 'http.url', 'http.target'];\r\n\r\nexport class UrlRedactionSpanProcessor implements SpanProcessor {\r\n onStart(): void {}\r\n\r\n onEnding(span: Span): void {\r\n try {\r\n const attributes = (span as unknown as ReadableSpan).attributes ?? {};\r\n for (const key of URL_KEYS) {\r\n const value = attributes[key];\r\n if (typeof value === 'string') {\r\n const redacted = redactUrl(value);\r\n if (redacted !== value) span.setAttribute(key, redacted);\r\n }\r\n }\r\n const query = attributes['url.query'];\r\n if (typeof query === 'string') {\r\n const bare = query.startsWith('?') ? query.slice(1) : query;\r\n const redacted = redactQuery(bare);\r\n if (redacted !== bare) span.setAttribute('url.query', (query.startsWith('?') ? '?' : '') + redacted);\r\n }\r\n } catch {\r\n // Never let telemetry break a request.\r\n }\r\n }\r\n\r\n onEnd(_span: ReadableSpan): void {}\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n","/**\r\n * Who a request is for, and the tags set on everything.\r\n *\r\n * Zharp joins a back end's spans and logs to the user and browser session that caused them\r\n * through two attributes, `enduser.id` and `session.id`. The browser SDK sends both in the W3C\r\n * `baggage` header next to `traceparent`; the processors here copy them from the baggage onto\r\n * every span and log written while handling that request, so nothing in the application has to\r\n * know about them.\r\n *\r\n * `Zharp.setUser()` covers the other case — a back end that knows the user itself (a session\r\n * cookie, an API token). OpenTelemetry's context is immutable, so the user cannot be put into\r\n * the request's context from inside a handler; it is kept per trace instead, and every span and\r\n * log in that trace picks it up from then on.\r\n */\r\nimport { context as otelContext, propagation, trace, type Context } from '@opentelemetry/api';\r\nimport type { ReadWriteLogRecord, LogRecordProcessor } from '@opentelemetry/sdk-logs';\r\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace';\r\nimport type { ZharpUser } from './types';\r\n\r\n/** Baggage entries copied onto spans and logs, unchanged in name. */\r\nconst BAGGAGE_KEYS = ['enduser.id', 'session.id'] as const;\r\n\r\n/** The user as attributes, ready to set. */\r\nexport type UserAttributes = Record<string, string>;\r\n\r\nexport function userAttributes(user: ZharpUser): UserAttributes {\r\n const out: UserAttributes = { 'enduser.id': String(user.id) };\r\n if (user.email) out['enduser.email'] = String(user.email);\r\n if (user.name) out['enduser.name'] = String(user.name);\r\n return out;\r\n}\r\n\r\n/**\r\n * Users and tags, and which trace each user belongs to.\r\n *\r\n * A trace's user is dropped when the span that began the trace in this process ends — its\r\n * SERVER span, for a request — so the map holds only requests in flight.\r\n */\r\nexport class ContextStore {\r\n /** Set outside any request: a script or worker that is one user's work throughout. */\r\n globalUser: UserAttributes | null = null;\r\n readonly tags: Record<string, string | number | boolean> = {};\r\n private readonly byTrace = new Map<string, UserAttributes>();\r\n /** The first span of each trace in this process, which the user is also written onto. */\r\n private readonly localRoots = new Map<string, { spanId: string; span: Span }>();\r\n\r\n /** Set the user for the request in progress, or for the whole process outside one. */\r\n setUser(user: UserAttributes | null): void {\r\n const span = trace.getActiveSpan();\r\n const traceId = span?.spanContext().traceId;\r\n if (!span || !traceId) {\r\n this.globalUser = user;\r\n return;\r\n }\r\n if (user) {\r\n this.byTrace.set(traceId, user);\r\n // The spans already open learn it too: the request's own span is the one the dashboard\r\n // lists, and it is still open while the handler runs.\r\n span.setAttributes(user);\r\n this.localRoots.get(traceId)?.span.setAttributes(user);\r\n } else {\r\n this.byTrace.delete(traceId);\r\n }\r\n }\r\n\r\n /** What every span and log in `traceId` should carry, before baggage. */\r\n attributesFor(traceId: string | undefined): Record<string, string | number | boolean> {\r\n const user = (traceId && this.byTrace.get(traceId)) || this.globalUser;\r\n return user ? { ...this.tags, ...user } : { ...this.tags };\r\n }\r\n\r\n noteStart(span: Span, parent: Context): void {\r\n const parentSpan = trace.getSpanContext(parent);\r\n // No parent, or one from another process: this span starts the trace here.\r\n if (!parentSpan || parentSpan.isRemote) {\r\n const { traceId, spanId } = span.spanContext();\r\n if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });\r\n }\r\n }\r\n\r\n noteEnd(span: ReadableSpan): void {\r\n const { traceId, spanId } = span.spanContext();\r\n if (this.localRoots.get(traceId)?.spanId !== spanId) return;\r\n this.localRoots.delete(traceId);\r\n this.byTrace.delete(traceId);\r\n }\r\n}\r\n\r\n/** `enduser.id` and `session.id` from the baggage in `ctx`, when the caller sent them. */\r\nfunction fromBaggage(ctx: Context): Record<string, string> {\r\n const out: Record<string, string> = {};\r\n const baggage = propagation.getBaggage(ctx);\r\n if (!baggage) return out;\r\n for (const key of BAGGAGE_KEYS) {\r\n const value = baggage.getEntry(key)?.value;\r\n if (value) out[key] = value;\r\n }\r\n return out;\r\n}\r\n\r\n/** Puts the user, session and tags on every span as it starts. Exports nothing itself. */\r\nexport class ContextSpanProcessor implements SpanProcessor {\r\n constructor(private readonly store: ContextStore) {}\r\n\r\n onStart(span: Span, parentContext: Context): void {\r\n try {\r\n this.store.noteStart(span, parentContext);\r\n // The store first, baggage over it: the browser's word on its own session is final, and\r\n // a user the server set itself is already in the store's entry for this trace.\r\n span.setAttributes({ ...this.store.attributesFor(span.spanContext().traceId), ...fromBaggage(parentContext) });\r\n } catch {\r\n // Never let telemetry break a request.\r\n }\r\n }\r\n\r\n onEnd(span: ReadableSpan): void {\r\n this.store.noteEnd(span);\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n\r\n/** The same for log records — those written through Zharp.log, the console, pino and winston alike. */\r\nexport class ContextLogProcessor implements LogRecordProcessor {\r\n constructor(private readonly store: ContextStore) {}\r\n\r\n onEmit(record: ReadWriteLogRecord, ctx?: Context): void {\r\n try {\r\n const active = ctx ?? otelContext.active();\r\n const traceId = record.spanContext?.traceId ?? trace.getSpanContext(active)?.traceId;\r\n const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };\r\n // An attribute the call itself set (a log naming a different user, say) is kept.\r\n for (const [key, value] of Object.entries(add)) {\r\n if (record.attributes[key] === undefined) record.setAttribute(key, value);\r\n }\r\n } catch {\r\n // As above.\r\n }\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n","/**\r\n * `console.*` as OpenTelemetry log records.\r\n *\r\n * OpenTelemetry bridges pino, winston and bunyan but not the console, which is where most Node\r\n * code logs. Each call still prints exactly as before; a copy is emitted as a record in the\r\n * active context, so it carries the trace and span it was written in.\r\n */\r\nimport { format } from 'node:util';\r\nimport { SeverityNumber, type Logger } from '@opentelemetry/api';\r\n\r\nconst LEVELS: Array<[method: 'log' | 'info' | 'warn' | 'error' | 'debug' | 'trace', severity: SeverityNumber, text: string]> = [\r\n ['debug', SeverityNumber.DEBUG, 'DEBUG'],\r\n ['trace', SeverityNumber.TRACE, 'TRACE'],\r\n ['log', SeverityNumber.INFO, 'INFO'],\r\n ['info', SeverityNumber.INFO, 'INFO'],\r\n ['warn', SeverityNumber.WARN, 'WARN'],\r\n ['error', SeverityNumber.ERROR, 'ERROR'],\r\n];\r\n\r\n/** Set while a record is being emitted, so a console call made by the exporter is not sent too. */\r\nlet emitting = false;\r\n\r\n/**\r\n * Patch the console. Returns the undo.\r\n *\r\n * Lines the SDK prints about itself (`[Zharp] …`) are left out: they describe the reporting,\r\n * not the application.\r\n */\r\nexport function captureConsole(logger: Logger): () => void {\r\n const originals = new Map<string, (...args: unknown[]) => void>();\r\n for (const [method, severityNumber, severityText] of LEVELS) {\r\n const original = console[method];\r\n if (typeof original !== 'function' || (original as any).__zharp) continue;\r\n originals.set(method, original);\r\n const patched = function (this: unknown, ...args: unknown[]) {\r\n original.apply(this ?? console, args);\r\n if (emitting) return;\r\n emitting = true;\r\n try {\r\n const body = format(...args);\r\n if (!body.startsWith('[Zharp]')) {\r\n logger.emit({ severityNumber, severityText, body, attributes: { 'log.source': 'console' } });\r\n }\r\n } catch {\r\n // A log line that could not be copied is not worth an exception in the caller.\r\n } finally {\r\n emitting = false;\r\n }\r\n };\r\n (patched as any).__zharp = true;\r\n console[method] = patched;\r\n }\r\n return () => {\r\n for (const [method, original] of originals) (console as any)[method] = original;\r\n };\r\n}\r\n","/**\r\n * Debug IDs: which build of a file a stack frame came from, so Zharp can find its source map.\r\n *\r\n * `zharp sourcemaps inject` (and the bundler plugins) add a line to every emitted JS file that\r\n * registers it at load time:\r\n *\r\n * (globalThis.__zharpDebugIds ||= {})[new Error().stack] = \"<uuid>\"\r\n *\r\n * The key is a stack captured inside the file, so its top frame names the file exactly as this\r\n * runtime sees it — whatever the CDN, URL or path. Parsing those stacks gives file → debug ID;\r\n * an error then carries the IDs of the files in its own stack as `zharp.debug_ids`, a JSON\r\n * object `{ \"<file as it appears in the stack>\": \"<uuid>\" }`.\r\n */\r\n\r\n/** The attribute an error carries its files' debug IDs in. */\r\nexport const DEBUG_IDS_ATTRIBUTE = 'zharp.debug_ids';\r\n\r\n/** File → debug ID, from the registry entries parsed so far. */\r\nconst files = new Map<string, string>();\r\n/** Registry keys already parsed. The registry only grows, so each stack is parsed once. */\r\nconst parsed = new Set<string>();\r\n\r\nfunction registry(): Record<string, unknown> | undefined {\r\n const g = typeof globalThis !== 'undefined' ? (globalThis as any) : undefined;\r\n const value = g && g.__zharpDebugIds;\r\n return value && typeof value === 'object' ? value : undefined;\r\n}\r\n\r\n/**\r\n * The file a stack frame line points at, as written in the line: V8 (`at fn (file:1:2)`,\r\n * `at file:1:2`), and Gecko/WebKit (`fn@file:1:2`, `@file:1:2`). Undefined for anything else.\r\n */\r\nexport function frameFile(line: string): string | undefined {\r\n const text = line.trim();\r\n if (!text) return undefined;\r\n let match = /^at (?:async )?(?:.*? \\()?(.+?):\\d+:\\d+\\)?$/.exec(text);\r\n if (match) return clean(match[1]);\r\n if (text.startsWith('at ')) return undefined;\r\n match = /^(?:[^@]*@)?(.+?):\\d+:\\d+$/.exec(text);\r\n return match ? clean(match[1]) : undefined;\r\n}\r\n\r\nfunction clean(file: string): string | undefined {\r\n // `eval at fn (file:1:2), <anonymous>` and friends name no file of their own.\r\n if (!file || file.includes('eval at ') || file === '<anonymous>' || file === 'native') return undefined;\r\n return file;\r\n}\r\n\r\n/** Every file in a stack, in order, each once. */\r\nexport function stackFiles(stack: string): string[] {\r\n const out: string[] = [];\r\n for (const line of stack.split('\\n')) {\r\n const file = frameFile(line);\r\n if (file && !out.includes(file)) out.push(file);\r\n }\r\n return out;\r\n}\r\n\r\n/** Parse the registry entries not seen yet: each one's top frame is the file that registered it. */\r\nfunction refresh(): void {\r\n const entries = registry();\r\n if (!entries) return;\r\n for (const stack in entries) {\r\n if (parsed.has(stack)) continue;\r\n parsed.add(stack);\r\n const id = entries[stack];\r\n if (typeof id !== 'string') continue;\r\n for (const line of stack.split('\\n')) {\r\n const file = frameFile(line);\r\n if (file) {\r\n files.set(file, id);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * The debug IDs of the files in `stack` that registered one, or undefined when none did (no\r\n * injected build, or only third-party frames).\r\n */\r\nexport function debugIdsFor(stack: string | undefined): Record<string, string> | undefined {\r\n if (!stack) return undefined;\r\n try {\r\n refresh();\r\n if (files.size === 0) return undefined;\r\n let out: Record<string, string> | undefined;\r\n for (const file of stackFiles(stack)) {\r\n const id = files.get(file);\r\n if (id) (out ??= {})[file] = id;\r\n }\r\n return out;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/** `{ 'zharp.debug_ids': '<json>' }` for `stack`, or an empty object. Spread it into an error's attributes. */\r\nexport function debugIdAttributes(stack: string | undefined): Record<string, string> {\r\n const ids = debugIdsFor(stack);\r\n return ids ? { [DEBUG_IDS_ATTRIBUTE]: JSON.stringify(ids) } : {};\r\n}\r\n\r\n/** For tests: forget everything parsed. */\r\nexport function resetDebugIdCache(): void {\r\n files.clear();\r\n parsed.clear();\r\n}\r\n","/**\r\n * `zharp.debug_ids` on errors that do not come through Zharp's own API: exceptions recorded on\r\n * spans by the instrumentations (`span.recordException`), and error logs from the pino and\r\n * winston bridges. Zharp's own error logs already have it (see errors.ts); these processors only\r\n * fill it in where a stack is present and the attribute is not.\r\n */\r\nimport type { Context } from '@opentelemetry/api';\r\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace';\r\nimport type { LogRecordProcessor, ReadWriteLogRecord } from '@opentelemetry/sdk-logs';\r\nimport { DEBUG_IDS_ATTRIBUTE, debugIdsFor } from '@zharp/internal/debug-ids';\r\n\r\nconst STACK = 'exception.stacktrace';\r\n\r\nexport class DebugIdSpanProcessor implements SpanProcessor {\r\n onStart(_span: Span, _parentContext: Context): void {}\r\n\r\n /** Exception events are added while the span runs; by its end they are all there. */\r\n onEnd(span: ReadableSpan): void {\r\n try {\r\n for (const event of span.events) {\r\n const attributes = event.attributes as Record<string, unknown> | undefined;\r\n if (event.name !== 'exception' || !attributes || attributes[DEBUG_IDS_ATTRIBUTE] !== undefined) continue;\r\n const stack = attributes[STACK];\r\n const ids = typeof stack === 'string' ? debugIdsFor(stack) : undefined;\r\n if (ids) attributes[DEBUG_IDS_ATTRIBUTE] = JSON.stringify(ids);\r\n }\r\n } catch {\r\n // Never let telemetry break a request.\r\n }\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n\r\nexport class DebugIdLogProcessor implements LogRecordProcessor {\r\n onEmit(record: ReadWriteLogRecord, _ctx?: Context): void {\r\n try {\r\n const attributes = record.attributes as Record<string, unknown>;\r\n const stack = attributes[STACK];\r\n if (typeof stack !== 'string' || attributes[DEBUG_IDS_ATTRIBUTE] !== undefined) return;\r\n const ids = debugIdsFor(stack);\r\n if (ids) record.setAttribute(DEBUG_IDS_ATTRIBUTE, JSON.stringify(ids));\r\n } catch {\r\n // As above.\r\n }\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n","/**\r\n * Errors as Zharp reads them: a log record of severity ERROR or FATAL carrying\r\n * `exception.type`, `exception.message` and `exception.stacktrace`, plus `zharp.handled`.\r\n *\r\n * A log rather than a span event because an error does not always happen inside a span (a\r\n * crash at startup, a timer callback), and one shape for both keeps the count honest: the server\r\n * makes an error event from either, so sending both would count every error twice.\r\n */\r\nimport { inspect } from 'node:util';\r\nimport { debugIdAttributes } from '@zharp/internal/debug-ids';\r\n\r\n/** OTLP severity numbers. */\r\nexport const SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 } as const;\r\nexport type Level = keyof typeof SEVERITY;\r\n\r\n/** Whatever was thrown, as an Error — a rejection with a string or an object is still worth a stack. */\r\nexport function asError(value: unknown): Error {\r\n if (value instanceof Error) return value;\r\n if (value && typeof value === 'object' && typeof (value as any).message === 'string') {\r\n const error = new Error((value as any).message);\r\n error.name = typeof (value as any).name === 'string' ? (value as any).name : 'Error';\r\n if (typeof (value as any).stack === 'string') error.stack = (value as any).stack;\r\n return error;\r\n }\r\n const text = typeof value === 'string' ? value : inspect(value, { depth: 3, breakLength: Infinity });\r\n const error = new Error(`Non-Error thrown: ${text}`);\r\n // The stack points here, not at the throw — but it is the only one there is.\r\n return error;\r\n}\r\n\r\n/** The name an error is grouped under: `TypeError`, or a custom class's own name. */\r\nfunction typeOf(error: Error): string {\r\n const name = error.name && error.name !== 'Error' ? error.name : error.constructor?.name;\r\n return name || 'Error';\r\n}\r\n\r\n/** The `exception.*` attributes for `error`. The stack keeps its first `Type: message` line. */\r\nexport function exceptionAttributes(error: Error, handled: boolean): Record<string, string> {\r\n const type = typeOf(error);\r\n const message = error.message || '';\r\n let stack = typeof error.stack === 'string' && error.stack ? error.stack : `${type}: ${message}`;\r\n // A cause is part of what went wrong; Node prints it, so the stack shown in Zharp does too.\r\n const cause = (error as { cause?: unknown }).cause;\r\n if (cause instanceof Error && cause.stack) stack += `\\nCaused by: ${cause.stack}`;\r\n return {\r\n 'exception.type': type,\r\n 'exception.message': message,\r\n 'exception.stacktrace': stack,\r\n 'zharp.handled': handled ? 'true' : 'false',\r\n ...debugIdAttributes(stack),\r\n };\r\n}\r\n","/** Sent as `telemetry.sdk.version`. Bumped with package.json. */\r\nexport const VERSION = '0.2.0';\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IA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EACpD;AAAA,EAEA,SAAmB;AACjB,WAAO,CAAC;AAAA,EACV;AACF;;;AFjgBA,IAAM,IAAI;AACH,IAAM,QAAmB,EAAE,mBAAmB,EAAE,iBAAiB,IAAI,UAAU;AACtF,IAAO,gBAAQ;","names":["import_api","parsed","typeOf","parsed","otelContext","import_api","g","import_node_util","error","g","registerLoader"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.26_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/cjs_shims.js","../src/zharp.ts","../../../internal/src/builtins.ts","../../../internal/src/env.ts","../../../internal/src/bodies.ts","../src/bodies.ts","../src/urls.ts","../src/context.ts","../src/console.ts","../src/capture-state.ts","../src/stdout.ts","../../../internal/src/debug-ids.ts","../src/debug-ids.ts","../src/errors.ts","../src/version.ts"],"sourcesContent":["import { ZharpNode } from './zharp';\r\n\r\nexport { ZharpNode } from './zharp';\r\nexport { VERSION } from './version';\r\nexport type { NodeOptions, ZharpUser, Attributes, AttributeValue, CaptureBodies, CaptureBodiesOptions } from './types';\r\n\r\n// One instance per process, kept on globalThis: `instrument.mjs` imports the ES build and the\r\n// application may `require` the CommonJS one, and both must reach the SDK that was started.\r\nconst g = globalThis as any;\r\nexport const Zharp: ZharpNode = g.__ZHARP_NODE__ ?? (g.__ZHARP_NODE__ = new ZharpNode());\r\nexport default Zharp;\r\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","/**\r\n * @zharp/node: the OpenTelemetry Node SDK, configured for Zharp.\r\n *\r\n * Everything that makes spans is OpenTelemetry's — the Node SDK, the auto-instrumentations for\r\n * http, express, fastify, pg, redis, prisma's driver and the rest, the W3C propagators, the\r\n * pino/winston/bunyan log bridges. What is here is the configuration (where to send, with what\r\n * key, under which service), the two processors that put user and session on everything, a\r\n * console bridge, error capture, and a small API in the same shape as every other Zharp SDK.\r\n */\r\nimport { register as registerLoader } from 'node:module';\r\nimport {\r\n type Context,\r\n type DiagLogger,\r\n DiagLogLevel,\r\n diag,\r\n INVALID_SPAN_CONTEXT,\r\n logs,\r\n SeverityNumber,\r\n SpanStatusCode,\r\n trace,\r\n type Logger,\r\n type TextMapGetter,\r\n type TextMapPropagator,\r\n type Span,\r\n type SpanOptions,\r\n} from '@opentelemetry/api';\r\nimport { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from '@opentelemetry/core';\r\nimport { envDetector, hostDetector, resourceFromAttributes } from '@opentelemetry/resources';\r\nimport { NodeSDK } from '@opentelemetry/sdk-node';\r\nimport {\r\n BatchSpanProcessor,\r\n ParentBasedSampler,\r\n SamplingDecision,\r\n TraceIdRatioBasedSampler,\r\n type Sampler,\r\n type SamplingResult,\r\n type SpanProcessor,\r\n} from '@opentelemetry/sdk-trace';\r\nimport { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs';\r\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';\r\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto';\r\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\r\nimport { announce, describeTarget, disabledByEnv, nodeEnv, packageName, pick, warn } from '@zharp/internal/env';\r\nimport { bodySettings } from '@zharp/internal/bodies';\r\nimport { withBodyCapture } from './bodies';\r\nimport { UrlRedactionSpanProcessor } from './urls';\r\nimport { ContextLogProcessor, ContextSpanProcessor, ContextStore, userAttributes } from './context';\r\nimport { captureConsole } from './console';\r\nimport { captureOutput, SentLineProcessor, stampOutput } from './stdout';\r\nimport { DebugIdLogProcessor, DebugIdSpanProcessor } from './debug-ids';\r\nimport { asError, exceptionAttributes, SEVERITY, type Level } from './errors';\r\nimport type { Attributes, NodeOptions, ZharpUser } from './types';\r\nimport { VERSION } from './version';\r\n\r\nexport const DEFAULT_ENDPOINT = 'https://api.zharp.io/api/v1/otlp';\r\n\r\n/** How long a flush on the way out may hold the process up. */\r\nconst EXIT_FLUSH_MS = 2_000;\r\n\r\ntype LogFn = (message: unknown, attributes?: Attributes) => void;\r\n\r\nexport class ZharpNode {\r\n private sdk: NodeSDK | null = null;\r\n private spanProcessors: SpanProcessor[] = [];\r\n private logProcessors: LogRecordProcessor[] = [];\r\n private logger: Logger | null = null;\r\n private readonly store = new ContextStore();\r\n private teardowns: Array<() => void> = [];\r\n /** False in logs-only mode (`tracing: false` / `ZHARP_TRACING=false`). */\r\n private tracing = true;\r\n /** Errors already sent, so one that is both rejected and then thrown is reported once. */\r\n private readonly reported = new WeakSet<object>();\r\n\r\n /** `Zharp.log.info(\"Order placed\", { orderId })` — and debug, warn, error, fatal, trace. */\r\n readonly log: Record<Level, LogFn> = {\r\n trace: (m, a) => this.emit('trace', m, a),\r\n debug: (m, a) => this.emit('debug', m, a),\r\n info: (m, a) => this.emit('info', m, a),\r\n warn: (m, a) => this.emit('warn', m, a),\r\n error: (m, a) => this.emit('error', m, a),\r\n fatal: (m, a) => this.emit('fatal', m, a),\r\n };\r\n\r\n /** Whether `init()` started the SDK. */\r\n get isActive(): boolean {\r\n return this.sdk !== null;\r\n }\r\n\r\n /**\r\n * Start sending traces, logs and errors. Call it once, before the application's own modules\r\n * load — from a file preloaded with `node --import` (see the README) — so that http, the\r\n * database drivers and the frameworks are instrumented when they are first imported.\r\n */\r\n init(options: NodeOptions = {}): void {\r\n try {\r\n this.start(options);\r\n } catch (error) {\r\n warn(`Could not start: ${(error as Error)?.message ?? error}`);\r\n }\r\n }\r\n\r\n private start(options: NodeOptions): void {\r\n if (this.sdk) {\r\n warn('Zharp.init() was called again — the first call\\'s settings stay in effect.');\r\n return;\r\n }\r\n if (disabledByEnv()) {\r\n announce('Disabled by ZHARP_DISABLED — nothing will be sent');\r\n return;\r\n }\r\n const key = pick(options.key, nodeEnv('ZHARP_API_KEY'), nodeEnv('ZHARP_KEY'));\r\n if (!key) {\r\n warn('No key found — pass Zharp.init({ key }) or set ZHARP_API_KEY. Nothing will be sent.');\r\n return;\r\n }\r\n const service = pick(options.service, nodeEnv('ZHARP_SERVICE'), nodeEnv('OTEL_SERVICE_NAME'), packageName()) ?? 'node-app';\r\n const environment = pick(options.environment, nodeEnv('ZHARP_ENV'), nodeEnv('NODE_ENV'));\r\n const release = pick(options.release, nodeEnv('ZHARP_RELEASE'), nodeEnv('ZHARP_VERSION'));\r\n const endpoint = (pick(options.endpoint, nodeEnv('ZHARP_ENDPOINT')) ?? DEFAULT_ENDPOINT).replace(/\\/+$/, '');\r\n const tracing = tracingEnabled(options.tracing);\r\n this.tracing = tracing;\r\n // What the app prints is sent only when asked for: where the Zharp agent reads the\r\n // container's output it already brings those lines in, linked by the stamp below.\r\n const sendLogs = switchOn(options.logs, 'ZHARP_LOGS', false);\r\n const correlation = switchOn(options.logCorrelation, 'ZHARP_LOG_CORRELATION', true);\r\n const bridges = logBridges(sendLogs, correlation, options.instrumentations);\r\n\r\n if (options.debug) {\r\n // Bound to the console as it is now, before the bridge patches it: OpenTelemetry's own\r\n // messages about a failed export must not become log records that fail to export.\r\n const out = { error: console.error, warn: console.warn, info: console.info, debug: console.debug, verbose: console.debug };\r\n const prefixed = Object.fromEntries(\r\n Object.entries(out).map(([level, fn]) => [level, (message: string, ...args: unknown[]) => fn.call(console, `[Zharp][otel] ${message}`, ...args)]),\r\n ) as unknown as DiagLogger;\r\n diag.setLogger(prefixed, DiagLogLevel.DEBUG);\r\n }\r\n\r\n // ES modules can only be instrumented through a loader hook, and it has to be in place\r\n // before the application's first import — which is why init() belongs in a preloaded file.\r\n registerEsmHook();\r\n\r\n const headers = { Authorization: `Bearer ${key}` };\r\n const exporterOptions = { headers, compression: 'gzip' as any };\r\n // Logs only: no span exporter at all. The context processor stays, because it is what keeps\r\n // a user set with setUser() to its own request (see RecordOnlySampler).\r\n this.spanProcessors = tracing\r\n ? [\r\n new ContextSpanProcessor(this.store),\r\n new UrlRedactionSpanProcessor(),\r\n new DebugIdSpanProcessor(),\r\n new BatchSpanProcessor({ exporter: new OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) }),\r\n ]\r\n : [new ContextSpanProcessor(this.store)];\r\n this.logProcessors = [\r\n new SentLineProcessor(),\r\n new ContextLogProcessor(this.store),\r\n new DebugIdLogProcessor(),\r\n new BatchLogRecordProcessor({ exporter: new OTLPLogExporter({ ...exporterOptions, url: `${endpoint}/v1/logs` }) }),\r\n ];\r\n\r\n const resource = resourceFromAttributes({\r\n 'service.name': service,\r\n ...(release ? { 'service.version': release } : {}),\r\n ...(environment ? { 'deployment.environment.name': environment } : {}),\r\n 'telemetry.sdk.name': 'zharp',\r\n 'telemetry.sdk.language': 'nodejs',\r\n 'telemetry.sdk.version': VERSION,\r\n 'process.runtime.name': 'nodejs',\r\n 'process.runtime.version': process.versions.node,\r\n });\r\n\r\n const propagator = new CompositePropagator({\r\n propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()],\r\n });\r\n const bodies = bodySettings(options.captureBodies, nodeEnv('ZHARP_CAPTURE_BODIES'));\r\n const rate = typeof options.sampleRate === 'number' ? Math.min(1, Math.max(0, options.sampleRate)) : 1;\r\n\r\n this.sdk = new NodeSDK({\r\n resource,\r\n // Host and OTEL_RESOURCE_ATTRIBUTES only. The process detector would send the command line,\r\n // which is where secrets passed as arguments live.\r\n resourceDetectors: [envDetector, hostDetector],\r\n sampler: tracing ? new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(rate) }) : new RecordOnlySampler(),\r\n textMapPropagator: tracing ? propagator : new ExtractOnlyPropagator(propagator),\r\n spanProcessors: this.spanProcessors,\r\n logRecordProcessors: this.logProcessors,\r\n // Without this the SDK would start an OTLP metrics exporter pointed at localhost:4318.\r\n metricReaders: [],\r\n instrumentations: [\r\n ...(tracing\r\n ? getNodeAutoInstrumentations({\r\n // A span per DNS lookup, socket and file read buries the requests that matter.\r\n '@opentelemetry/instrumentation-dns': { enabled: false },\r\n '@opentelemetry/instrumentation-net': { enabled: false },\r\n '@opentelemetry/instrumentation-fs': { enabled: false },\r\n ...options.instrumentations,\r\n ...bridges,\r\n ...(bodies && {\r\n '@opentelemetry/instrumentation-http': withBodyCapture(bodies, options.instrumentations?.['@opentelemetry/instrumentation-http'] as any) as any,\r\n }),\r\n })\r\n : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges } })),\r\n ...(options.extraInstrumentations ?? []),\r\n ],\r\n });\r\n this.sdk.start();\r\n this.logger = logs.getLogger('@zharp/node', VERSION);\r\n\r\n if (correlation) this.teardowns.push(stampOutput());\r\n if (sendLogs) {\r\n if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));\r\n // Last, so it wraps whatever the console capture and the bridges print — and sees each\r\n // line before it is stamped.\r\n if (options.captureOutput !== false && nodeEnv('ZHARP_CAPTURE_OUTPUT') !== 'false') {\r\n this.teardowns.push(captureOutput(this.logger));\r\n }\r\n }\r\n if (options.captureUncaught !== false) this.teardowns.push(this.captureProcessErrors());\r\n this.teardowns.push(this.flushOnExit());\r\n\r\n announce(`Application monitoring active${tracing ? '' : ' (logs only)'} — ${describeTarget(service, environment)}`);\r\n }\r\n\r\n /**\r\n * The user the current request is for: `enduser.id` (and `enduser.email`, `enduser.name`) on\r\n * every span and log of the request from here on, and on the request's own span. Outside a\r\n * request it applies to everything the process sends — for a script or a worker that runs as\r\n * one user.\r\n *\r\n * Requests from a page running @zharp/browser already carry the user in their baggage; this\r\n * is for servers that know the user themselves.\r\n */\r\n setUser(user: ZharpUser | null): void {\r\n try {\r\n this.store.setUser(user && user.id != null && user.id !== '' ? userAttributes(user) : null);\r\n } catch {\r\n // Never throw into the application.\r\n }\r\n }\r\n\r\n /** Forget the user — for the current request, or the process's when called outside one. */\r\n clearUser(): void {\r\n this.setUser(null);\r\n }\r\n\r\n /** An attribute on every span and log sent from now on, e.g. `setTag(\"region\", \"eu-west-1\")`. */\r\n setTag(key: string, value: string | number | boolean | null | undefined): void {\r\n if (value === null || value === undefined) delete this.store.tags[key];\r\n else this.store.tags[key] = value;\r\n }\r\n\r\n /**\r\n * Report an error you caught. It is sent as handled, in the trace of the request it happened\r\n * in, and grouped into an issue with every other occurrence.\r\n */\r\n captureError(error: unknown, attributes?: Attributes): void {\r\n this.report(error, true, 'error', attributes);\r\n }\r\n\r\n /**\r\n * Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A\r\n * throw or rejection marks the span as failed and is passed on unchanged.\r\n */\r\n startSpan<T>(name: string, fn: (span: Span) => T, options: SpanOptions = {}): T {\r\n // Logs only: no span — the callback runs as it is, handed a non-recording stand-in with the\r\n // current trace's ids (so ending or annotating it touches nothing).\r\n if (!this.tracing) return fn(trace.wrapSpanContext(trace.getActiveSpan()?.spanContext() ?? INVALID_SPAN_CONTEXT));\r\n const tracer = trace.getTracer('@zharp/node', VERSION);\r\n return tracer.startActiveSpan(name, options, (span) => {\r\n const fail = (error: unknown) => {\r\n span.setStatus({ code: SpanStatusCode.ERROR, message: asError(error).message });\r\n span.end();\r\n };\r\n let result: T;\r\n try {\r\n result = fn(span);\r\n } catch (error) {\r\n fail(error);\r\n throw error;\r\n }\r\n if (result && typeof (result as any).then === 'function') {\r\n return (result as any).then(\r\n (value: unknown) => {\r\n span.end();\r\n return value;\r\n },\r\n (error: unknown) => {\r\n fail(error);\r\n throw error;\r\n },\r\n ) as T;\r\n }\r\n span.end();\r\n return result;\r\n });\r\n }\r\n\r\n /** Send everything waiting now. Await it before a serverless function returns. */\r\n async flush(timeoutMs = 5_000): Promise<void> {\r\n const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {})));\r\n await Promise.race([all, new Promise((resolve) => setTimeout(resolve, timeoutMs).unref())]);\r\n }\r\n\r\n /** Flush, stop, and put back everything that was patched. */\r\n async shutdown(): Promise<void> {\r\n const sdk = this.sdk;\r\n if (!sdk) return;\r\n this.sdk = null;\r\n for (const undo of this.teardowns.splice(0)) undo();\r\n await sdk.shutdown().catch(() => {});\r\n }\r\n\r\n // ── internals ─────────────────────────────────────────────────────────\r\n\r\n private emit(level: Level, message: unknown, attributes?: Attributes): void {\r\n try {\r\n if (!this.logger) return;\r\n const extra: Record<string, unknown> = {};\r\n // An Error among the attributes is the reason for the log: it is sent as the exception,\r\n // so `Zharp.log.error(\"Payment failed\", { error })` becomes an issue with its stack.\r\n for (const [key, value] of Object.entries(attributes ?? {})) {\r\n if (value instanceof Error && (level === 'error' || level === 'fatal') && !extra['exception.type']) {\r\n Object.assign(extra, exceptionAttributes(value, true));\r\n } else {\r\n extra[key] = value instanceof Error ? `${value.name}: ${value.message}` : value;\r\n }\r\n }\r\n this.logger.emit({\r\n severityNumber: SEVERITY[level] as SeverityNumber,\r\n severityText: level.toUpperCase(),\r\n body: typeof message === 'string' ? message : message instanceof Error ? message.message : safeJson(message),\r\n attributes: extra as any,\r\n });\r\n } catch {\r\n // Never throw into the application.\r\n }\r\n }\r\n\r\n private report(value: unknown, handled: boolean, level: Level, attributes?: Attributes): void {\r\n try {\r\n if (!this.logger) return;\r\n const error = asError(value);\r\n if (value && typeof value === 'object') {\r\n if (this.reported.has(value)) return;\r\n this.reported.add(value);\r\n }\r\n const exception = exceptionAttributes(error, handled);\r\n this.logger.emit({\r\n severityNumber: SEVERITY[level] as SeverityNumber,\r\n severityText: level.toUpperCase(),\r\n body: `${exception['exception.type']}: ${exception['exception.message']}`,\r\n attributes: { ...(attributes as any), ...exception },\r\n });\r\n // An error in a request fails that request's span, so the trace shows where it broke.\r\n if (!handled) trace.getActiveSpan()?.setStatus({ code: SpanStatusCode.ERROR, message: error.message });\r\n } catch {\r\n // As above.\r\n }\r\n }\r\n\r\n /**\r\n * Uncaught exceptions and unhandled rejections, reported as unhandled.\r\n *\r\n * Listening for either changes what Node does — it no longer exits — so when Zharp's listener\r\n * is the only one, it finishes the job the way Node would have: print the error, then exit\r\n * with code 1, after the error has been sent. When the application has listeners of its own,\r\n * they decide, and Zharp only reports.\r\n */\r\n private captureProcessErrors(): () => void {\r\n const onException = (error: unknown, origin?: string) => {\r\n this.report(error, false, 'fatal', origin ? { 'zharp.mechanism': origin } : undefined);\r\n if (process.listenerCount('uncaughtException') > 1) return;\r\n this.crash(error);\r\n };\r\n const onRejection = (reason: unknown) => {\r\n this.report(reason, false, 'error', { 'zharp.mechanism': 'unhandledRejection' });\r\n if (process.listenerCount('unhandledRejection') > 1) return;\r\n const mode = unhandledRejectionsMode();\r\n if (mode === 'warn' || mode === 'none') return;\r\n if (mode === 'warn-with-error-code') {\r\n process.exitCode = 1;\r\n return;\r\n }\r\n this.crash(reason);\r\n };\r\n process.on('uncaughtException', onException);\r\n process.on('unhandledRejection', onRejection);\r\n return () => {\r\n process.off('uncaughtException', onException);\r\n process.off('unhandledRejection', onRejection);\r\n };\r\n }\r\n\r\n private crashing = false;\r\n\r\n private crash(error: unknown): void {\r\n if (this.crashing) return;\r\n this.crashing = true;\r\n try {\r\n // Straight to stderr, not console.error: the console is captured, and this is already sent.\r\n const text = error instanceof Error ? error.stack || String(error) : `Uncaught ${safeJson(error)}`;\r\n process.stderr.write(`${text}\\n\\nNode.js ${process.version}\\n`);\r\n } catch {\r\n // Exit regardless.\r\n }\r\n this.flush(EXIT_FLUSH_MS).finally(() => process.exit(1));\r\n }\r\n\r\n /**\r\n * Send what is waiting when the process ends on its own (the event loop drains) or is told to\r\n * stop. A signal listener also replaces Node's default of exiting, so once the flush is done,\r\n * if no one else is listening, the signal is raised again with Zharp's listener gone.\r\n */\r\n private flushOnExit(): () => void {\r\n let flushing = false;\r\n const onBeforeExit = () => {\r\n if (flushing) return;\r\n flushing = true;\r\n this.flush(EXIT_FLUSH_MS).finally(() => (flushing = false));\r\n };\r\n process.on('beforeExit', onBeforeExit);\r\n\r\n const signals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];\r\n const handlers = signals.map((signal) => {\r\n const handler = () => {\r\n this.flush(EXIT_FLUSH_MS).finally(() => {\r\n process.off(signal, handler);\r\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\r\n });\r\n };\r\n process.on(signal, handler);\r\n return [signal, handler] as const;\r\n });\r\n\r\n return () => {\r\n process.off('beforeExit', onBeforeExit);\r\n for (const [signal, handler] of handlers) process.off(signal, handler);\r\n };\r\n }\r\n}\r\n\r\n/** `--unhandled-rejections=…` from the command line or NODE_OPTIONS; `throw` when unset. */\r\nfunction unhandledRejectionsMode(): string {\r\n const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? '').split(/\\s+/)];\r\n for (const flag of flags) {\r\n const match = /^--unhandled-rejections=(.+)$/.exec(flag);\r\n if (match) return match[1];\r\n }\r\n return 'throw';\r\n}\r\n\r\nfunction safeJson(value: unknown): string {\r\n try {\r\n return typeof value === 'string' ? value : JSON.stringify(value) ?? String(value);\r\n } catch {\r\n return String(value);\r\n }\r\n}\r\n\r\n/** Register OpenTelemetry's ES module loader hook, once per process. */\r\nfunction registerEsmHook(): void {\r\n const g = globalThis as any;\r\n if (g.__ZHARP_ESM_HOOK__) return;\r\n g.__ZHARP_ESM_HOOK__ = true;\r\n try {\r\n // Resolved from this package, which depends on @opentelemetry/instrumentation directly.\r\n registerLoader?.('@opentelemetry/instrumentation/hook.mjs', import.meta.url);\r\n } catch {\r\n // Older Node without module.register: CommonJS is still instrumented.\r\n }\r\n}\r\n\r\n/**\r\n * `tracing` from the option, else `ZHARP_TRACING` (`false`, `0`, `no`, `off` turn it off).\r\n * On unless one of them says otherwise.\r\n */\r\n/** An on/off setting: the option if given, else the environment variable, else the default. */\r\nfunction switchOn(option: boolean | undefined, variable: string, fallback: boolean): boolean {\r\n if (typeof option === 'boolean') return option;\r\n const value = nodeEnv(variable);\r\n if (value && /^(true|1|yes|on)$/i.test(value)) return true;\r\n if (value && /^(false|0|no|off)$/i.test(value)) return false;\r\n return fallback;\r\n}\r\n\r\n/**\r\n * pino, winston and bunyan: their records are sent only when logs are on; either way each record\r\n * carries trace_id and span_id (unless correlation is off), so a line collected from the output\r\n * is still linked to its request. The application's own settings for them win.\r\n */\r\nfunction logBridges(sendLogs: boolean, correlation: boolean, own: NodeOptions['instrumentations'] = {}) {\r\n const config = (name: string) => ({\r\n disableLogSending: !sendLogs,\r\n disableLogCorrelation: !correlation,\r\n ...(own as Record<string, object>)[name],\r\n });\r\n return {\r\n '@opentelemetry/instrumentation-pino': config('@opentelemetry/instrumentation-pino'),\r\n '@opentelemetry/instrumentation-winston': config('@opentelemetry/instrumentation-winston'),\r\n '@opentelemetry/instrumentation-bunyan': config('@opentelemetry/instrumentation-bunyan'),\r\n } as Record<string, any>;\r\n}\r\n\r\nfunction tracingEnabled(option: boolean | undefined): boolean {\r\n if (typeof option === 'boolean') return option;\r\n const value = nodeEnv('ZHARP_TRACING');\r\n return !(value && /^(false|0|no|off)$/i.test(value));\r\n}\r\n\r\n/**\r\n * Logs only: the log bridges (pino, winston, bunyan) and the http *server* instrumentation —\r\n * nothing else. The http server side is there only to give each incoming request a context: it\r\n * reads the caller's `traceparent` and `baggage`, so the request's logs carry the caller's trace\r\n * id, session and user (and a fresh trace id of their own when the caller sent none). Its one\r\n * span per request is never exported. Outgoing requests are not patched at all, and nothing is\r\n * injected into them.\r\n */\r\nfunction logsOnlyInstrumentations(options: NodeOptions) {\r\n // getNodeAutoInstrumentations has no \"only these\" option, but it honours this variable — set\r\n // for the duration of the call alone.\r\n const previous = process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;\r\n process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = 'http,pino,winston,bunyan';\r\n try {\r\n return getNodeAutoInstrumentations({\r\n ...options.instrumentations,\r\n '@opentelemetry/instrumentation-http': {\r\n ...options.instrumentations?.['@opentelemetry/instrumentation-http'],\r\n disableOutgoingRequestInstrumentation: true,\r\n },\r\n });\r\n } finally {\r\n if (previous === undefined) delete process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;\r\n else process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = previous;\r\n }\r\n}\r\n\r\n/**\r\n * Logs only: every span is recorded (so the context processor sees it start and end, which is\r\n * what scopes setUser() to a request) and none is sampled (so nothing could export it, and the\r\n * flags say so). Spans live in memory for the length of the request and are then dropped.\r\n */\r\nclass RecordOnlySampler implements Sampler {\r\n shouldSample(): SamplingResult {\r\n return { decision: SamplingDecision.RECORD };\r\n }\r\n\r\n toString(): string {\r\n return 'ZharpRecordOnlySampler';\r\n }\r\n}\r\n\r\n/** Reads `traceparent` and `baggage` from incoming requests; never writes them anywhere. */\r\nclass ExtractOnlyPropagator implements TextMapPropagator {\r\n constructor(private readonly inner: TextMapPropagator) {}\r\n\r\n inject(): void {}\r\n\r\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\r\n return this.inner.extract(context, carrier, getter);\r\n }\r\n\r\n fields(): string[] {\r\n return [];\r\n }\r\n}\r\n","/**\n * Load a Node built-in module, or nothing at all outside Node.\n *\n * `process.getBuiltinModule` (Node 20.16+, 22.3+) is tried first because it is the only way in\n * that works from the ESM build: an ES module has no `require`, and the shim the bundler leaves\n * in its place throws. Without it, native-ESM applications silently lost HTTP tracing and kept\n * the active span in a single variable that every concurrent request overwrote.\n *\n * `require` remains the fallback for the CommonJS build on older Node. It is reached\n * indirectly so a bundler building for the browser does not try to resolve a Node built-in and\n * either fail or pull in a shim.\n *\n * @param name - Built-in name without the `node:` prefix, e.g. `http`\n */\nexport function loadBuiltin(name: string): any | null {\n try {\n const proc: any = typeof process !== 'undefined' ? process : undefined;\n if (proc && typeof proc.getBuiltinModule === 'function') {\n return proc.getBuiltinModule(`node:${name}`) ?? null;\n }\n const req = typeof module !== 'undefined' && typeof require === 'function' ? require : null;\n return req ? req(name) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Make a patch to a built-in visible to ES-module named imports.\n *\n * `import { request } from 'node:http'` is a snapshot of the module's exports, so replacing\n * `http.request` is not seen there until Node is told to resynchronise. A no-op where the\n * function does not exist.\n */\nexport function syncBuiltinExports(): void {\n try {\n loadBuiltin('module')?.syncBuiltinESMExports?.();\n } catch {\n // Older Node; named imports keep the unpatched function, default imports still see it.\n }\n}\n","/**\n * Configuration from the environment, and the lines printed at startup.\n *\n * Both packages start the way dd-trace does: `init()` with no arguments reads the environment,\n * explicit options override it, and the result is announced in one line so it is obvious from\n * the first few lines of output whether — and as what — the application is reporting.\n */\n\nimport { loadBuiltin } from './builtins';\n\n/**\n * An environment variable, in Node only.\n *\n * Browser bundles often carry a `process` shim whose `env` was baked in at build time — reading\n * it there would tag a page with the build machine's NODE_ENV — so a browser reads nothing.\n */\nexport function nodeEnv(name: string): string | undefined {\n if (typeof window !== 'undefined' || typeof process === 'undefined' || !process.env) return undefined;\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\n/** What a deployment can set without touching code. Every field may be absent. */\nexport interface EnvConfig {\n apiKey?: string;\n service?: string;\n environment?: string;\n version?: string;\n source?: string;\n endpoint?: string;\n /** Raw `ZHARP_CAPTURE_CONSOLE`: `all`, or a list such as `warn,error`. */\n captureConsole?: string;\n}\n\n/**\n * Everything the environment says, in Node. Empty in a browser.\n *\n * | Setting | Variables |\n * |---------------|---------------------------------------------|\n * | `apiKey` | `ZHARP_API_KEY` |\n * | `service` | `ZHARP_SERVICE`, then `OTEL_SERVICE_NAME` |\n * | `environment` | `ZHARP_ENV`, then `NODE_ENV` |\n * | `version` | `ZHARP_VERSION` |\n * | `source` | `ZHARP_SOURCE` |\n * | `endpoint` | `ZHARP_ENDPOINT` |\n * | `captureConsole` | `ZHARP_CAPTURE_CONSOLE` (logs only) |\n */\nexport function readEnv(): EnvConfig {\n return {\n apiKey: nodeEnv('ZHARP_API_KEY'),\n service: nodeEnv('ZHARP_SERVICE') || nodeEnv('OTEL_SERVICE_NAME'),\n environment: nodeEnv('ZHARP_ENV') || nodeEnv('NODE_ENV'),\n version: nodeEnv('ZHARP_VERSION'),\n source: nodeEnv('ZHARP_SOURCE'),\n endpoint: nodeEnv('ZHARP_ENDPOINT'),\n captureConsole: nodeEnv('ZHARP_CAPTURE_CONSOLE'),\n };\n}\n\n/**\n * The app's own name, from the nearest package.json above the script Node was started with (or\n * the working directory) — the name a service gets when none is configured, as dd-trace does.\n * A scope is dropped: \"@acme/checkout-api\" is \"checkout-api\". Nothing in a browser.\n */\nexport function packageName(): string | undefined {\n if (typeof window !== 'undefined' || typeof process === 'undefined') return undefined;\n const fs = loadBuiltin('fs');\n const path = loadBuiltin('path');\n if (!fs || !path) return undefined;\n const starts = [process.argv?.[1] ? path.dirname(path.resolve(process.argv[1])) : '', process.cwd?.() ?? ''];\n for (const start of starts.filter(Boolean)) {\n let dir = start;\n for (let i = 0; i < 12; i++) {\n // A dependency's own package.json is not the app's.\n if (path.basename(dir) !== 'node_modules') {\n try {\n const name = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))?.name;\n if (typeof name === 'string' && name.trim()) return name.trim().replace(/^@[^/]+\\//, '');\n } catch {\n // No package.json here, or not one we can read: keep looking further up.\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n }\n return undefined;\n}\n\n/** `ZHARP_DISABLED=true` (or `1`, `yes`): start nothing, whatever the code asks for. */\nexport function disabledByEnv(): boolean {\n const value = nodeEnv('ZHARP_DISABLED');\n return !!value && /^(true|1|yes|on)$/i.test(value);\n}\n\n/** The first argument that is a non-empty string — explicit option, then the next fallback. */\nexport function pick(...values: Array<string | undefined | null>): string | undefined {\n for (const value of values) {\n if (typeof value === 'string' && value.trim()) return value.trim();\n }\n return undefined;\n}\n\n/** `service \"checkout-api\", environment \"production\"` — the part both activation lines share. */\nexport function describeTarget(service: string, environment?: string): string {\n return `service \"${service}\", ${environment ? `environment \"${environment}\"` : 'no environment set'}`;\n}\n\n/** Startup output. One prefix, so it can be grepped for. */\nexport function announce(message: string): void {\n console.info(`[Zharp] ${message}`);\n}\n\nexport function warn(message: string): void {\n console.warn(`[Zharp] ${message}`);\n}\n","/**\r\n * Request and response bodies on HTTP spans (`captureBodies`), shared by @zharp/browser and\r\n * @zharp/node, and secrets in URLs.\r\n *\r\n * Off unless the application turns it on. When it is on, bodies are:\r\n * - redacted before they leave the process: field names stay, values under keys that look secret\r\n * (`password`, `token`, `authorization`, `card`, …) become `[Filtered]`, plus any keys the app adds\r\n * - kept readable: an inline image or other long base64 value becomes `[image/png · 24 KB]`, a\r\n * file in a form upload `[file photo.png · image/png · 240 KB]`, and a body that is not text\r\n * at all (an image, a PDF, an event stream) a one-line description of it\r\n * - capped (32 KB by default), with `http.*.body.truncated` set when they were cut\r\n *\r\n * They travel as the span attributes `http.request.body` and `http.response.body`, which the\r\n * trace view shows as a formatted payload.\r\n */\r\n\r\nexport type BodyMode = 'errors' | 'all';\r\n\r\nexport interface CaptureBodiesOptions {\r\n /** `errors` (default): only requests that failed (status 400 and above, or no response). `all`: every request. */\r\n mode?: BodyMode;\r\n /** Characters kept per body. Default 32768 (32 KB), at most 131072 (128 KB). */\r\n maxSize?: number;\r\n /**\r\n * More keys whose values are replaced with `[Filtered]`, on top of the built-in ones. A string\r\n * matches a key ignoring case, `-` and `_` (`\"accountNumber\"` also covers `account_number`); a\r\n * RegExp is tested against the key as it is.\r\n */\r\n redactKeys?: Array<string | RegExp>;\r\n /**\r\n * Which requests have their bodies captured. A bare host (`api.example.com`) matches that\r\n * host; a string with a scheme matches URLs starting with it; a RegExp is tested against the\r\n * full URL. Browser default: same-origin requests and `tracingOrigins` — your own APIs, never\r\n * third parties. Node default: every request.\r\n */\r\n urls?: Array<string | RegExp>;\r\n}\r\n\r\n/** `true` is `'errors'`. */\r\nexport type CaptureBodies = boolean | BodyMode | CaptureBodiesOptions;\r\n\r\nexport interface BodySettings {\r\n mode: BodyMode;\r\n maxSize: number;\r\n extraKeys: Array<string | RegExp>;\r\n urls?: Array<string | RegExp>;\r\n}\r\n\r\nexport const DEFAULT_MAX_BODY = 32 * 1024;\r\nexport const MAX_BODY = 128 * 1024;\r\nexport const FILTERED = '[Filtered]';\r\n\r\n/** Raw text read before shortening and capping: inline images shrink to a few words, so more is read than is kept. */\r\nexport function rawLimit(settings: BodySettings): number {\r\n return Math.max(64 * 1024, settings.maxSize * 2);\r\n}\r\n\r\nexport const BODY_ATTRIBUTES = {\r\n request: 'http.request.body',\r\n requestTruncated: 'http.request.body.truncated',\r\n requestType: 'http.request.header.content-type',\r\n response: 'http.response.body',\r\n responseTruncated: 'http.response.body.truncated',\r\n responseType: 'http.response.header.content-type',\r\n} as const;\r\n\r\n/** The setting as one shape, or null when bodies are off. `env` is `ZHARP_CAPTURE_BODIES` (`errors`, `all`, `off`). */\r\nexport function bodySettings(option: CaptureBodies | undefined, env?: string): BodySettings | null {\r\n let value: CaptureBodies | undefined = option;\r\n if (value === undefined && env) {\r\n const e = env.trim().toLowerCase();\r\n if (e === 'errors' || e === 'all') value = e;\r\n else if (/^(true|1|yes|on)$/.test(e)) value = true;\r\n }\r\n if (!value) return null;\r\n const o: CaptureBodiesOptions = value === true ? {} : typeof value === 'string' ? { mode: value } : value;\r\n const size = typeof o.maxSize === 'number' && o.maxSize > 0 ? Math.min(Math.floor(o.maxSize), MAX_BODY) : DEFAULT_MAX_BODY;\r\n return { mode: o.mode === 'all' ? 'all' : 'errors', maxSize: size, extraKeys: o.redactKeys ?? [], urls: o.urls };\r\n}\r\n\r\n/** Whether a request with this outcome has its bodies kept. `status` 0 means no response. */\r\nexport function wanted(settings: BodySettings, status: number): boolean {\r\n return settings.mode === 'all' || !status || status >= 400;\r\n}\r\n\r\n// ── content types ─────────────────────────────────────────────────────────────\r\n\r\nconst mime = (contentType: string | null | undefined) => (contentType ?? '').split(';')[0].trim().toLowerCase();\r\n\r\nexport function isEventStream(contentType: string | null | undefined): boolean {\r\n return mime(contentType) === 'text/event-stream';\r\n}\r\n\r\nexport function isMultipart(contentType: string | null | undefined): boolean {\r\n return mime(contentType) === 'multipart/form-data';\r\n}\r\n\r\n/** Whether a body of this type is text worth showing. An unknown type is given the benefit of the doubt. */\r\nexport function isTextual(contentType: string | null | undefined): boolean {\r\n const type = mime(contentType);\r\n if (!type) return true;\r\n if (type === 'text/event-stream') return false;\r\n return (\r\n type.startsWith('text/') ||\r\n type.endsWith('+json') ||\r\n type.endsWith('+xml') ||\r\n /^application\\/(json|xml|x-www-form-urlencoded|graphql|javascript|x-ndjson|ld\\+json)$/.test(type)\r\n );\r\n}\r\n\r\nfunction isForm(contentType: string | null | undefined): boolean {\r\n return mime(contentType) === 'application/x-www-form-urlencoded';\r\n}\r\n\r\n/** `240 KB`, `1.4 MB`. */\r\nexport function formatSize(bytes: number): string {\r\n if (bytes < 1024) return `${bytes} B`;\r\n if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;\r\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\r\n}\r\n\r\n/** How a file in a form upload is shown: `[file photo.png · image/png · 240 KB]`. */\r\nexport function fileLabel(name: string | undefined, type: string | undefined, size: number | undefined, partial = false): string {\r\n const parts = [`file ${name || 'blob'}`];\r\n if (type) parts.push(type);\r\n if (size !== undefined) parts.push(formatSize(size) + (partial ? '+' : ''));\r\n return `[${parts.join(' · ')}]`;\r\n}\r\n\r\n/** What a body that is not text says instead: `[binary · image/png · 24 KB]`, `[event stream]`. */\r\nexport function describeBody(contentType: string | null | undefined, size?: number, partial = false): string {\r\n if (isEventStream(contentType)) return '[event stream]';\r\n const parts = ['binary'];\r\n const type = mime(contentType);\r\n if (type) parts.push(type);\r\n if (size !== undefined && size > 0) parts.push(formatSize(size) + (partial ? '+' : ''));\r\n return `[${parts.join(' · ')}]`;\r\n}\r\n\r\n// ── redaction ─────────────────────────────────────────────────────────────────\r\n\r\n/** Built-in keys whose values never leave the process, compared without case, `-` or `_`. */\r\nconst CONTAINS = [\r\n 'password', 'passwd', 'passphrase', 'secret', 'token', 'apikey', 'accesskey', 'privatekey',\r\n 'authorization', 'cookie', 'creditcard', 'cardnumber', 'cvv', 'cvc', 'ssn', 'iban', 'sessionid',\r\n 'signature', 'credential',\r\n];\r\nconst EXACT = ['auth', 'pin', 'pwd', 'otp', 'card', 'pan', 'jwt', 'sid', 'codeverifier'];\r\n/** Also secret in a query string, where they are API keys and signed-URL signatures. */\r\nconst URL_EXACT = ['key', 'sig', 'code', 'state', 'session'];\r\n\r\nconst normalize = (key: string) => key.toLowerCase().replace(/[^a-z0-9]/g, '');\r\n\r\nexport function isSecretKey(key: string, extra: Array<string | RegExp> = []): boolean {\r\n const k = normalize(key);\r\n if (!k) return false;\r\n if (EXACT.includes(k) || CONTAINS.some((c) => k.includes(c))) return true;\r\n return extra.some((p) => (p instanceof RegExp ? p.test(key) : normalize(p) === k));\r\n}\r\n\r\nconst DATA_URI = /^data:([\\w.+-]+\\/[\\w.+-]+)?(?:;[\\w=.+-]+)*;base64,([A-Za-z0-9+/=\\s]*)$/;\r\nconst BASE64 = /^[A-Za-z0-9+/_-]{256,}={0,2}$/;\r\n\r\n/** A long base64 value as a short description; other strings as they are. */\r\nfunction shorten(value: string): string {\r\n if (value.length < 256) return value;\r\n const uri = DATA_URI.exec(value);\r\n if (uri) return `[${uri[1] || 'data'} · ${formatSize(Math.floor((uri[2].length * 3) / 4))}]`;\r\n if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 · ${formatSize(Math.floor((value.length * 3) / 4))}]`;\r\n return value;\r\n}\r\n\r\n/** Every value under `value` filtered, its keys kept: `{ brand: \"[Filtered]\", last4: \"[Filtered]\" }`. */\r\nfunction filterAll(value: unknown, depth: number): unknown {\r\n if (depth > 20) return FILTERED;\r\n if (value === null || value === '') return value;\r\n if (Array.isArray(value)) return value.map((v) => filterAll(v, depth + 1));\r\n if (typeof value === 'object') {\r\n const out: Record<string, unknown> = {};\r\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = filterAll(v, depth + 1);\r\n return out;\r\n }\r\n return FILTERED;\r\n}\r\n\r\nexport function redactValue(value: unknown, extra: Array<string | RegExp>, depth = 0): unknown {\r\n if (typeof value === 'string') return shorten(value);\r\n if (depth > 20 || value === null || typeof value !== 'object') return value;\r\n if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth + 1));\r\n const out: Record<string, unknown> = {};\r\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\r\n out[k] = isSecretKey(k, extra) ? filterAll(v, depth + 1) : redactValue(v, extra, depth + 1);\r\n }\r\n return out;\r\n}\r\n\r\n/**\r\n * Text that did not parse (cut-off JSON, a body that only looks like JSON): `\"key\": value`\r\n * pairs under secret keys are filtered where they appear, and long base64 runs shortened.\r\n */\r\nfunction redactLoose(text: string, extra: Array<string | RegExp>): string {\r\n // A quoted run of base64 (an inline image), possibly cut off before its closing quote.\r\n const runs = /\"((?:data:[\\w.+-]+\\/[\\w.+-]+(?:;[\\w=.+-]+)*;base64,)?[A-Za-z0-9+/_=-]{256,})(\"?)/g;\r\n return text\r\n .replace(runs, (match, run: string, close: string) => {\r\n const short = shorten(run);\r\n if (short === run) return match;\r\n return close ? `\"${short}\"` : `\"${short.slice(0, -1)}+]\"`;\r\n })\r\n .replace(\r\n /(\"([^\"\\\\]{1,100})\"\\s*:\\s*)(\"(?:[^\"\\\\]|\\\\.)*\"?|-?\\d[\\d.eE+-]*|true|false)/g,\r\n (match, prefix: string, key: string) => (isSecretKey(key, extra) ? `${prefix}\"${FILTERED}\"` : match),\r\n );\r\n}\r\n\r\nfunction redactForm(text: string, extra: Array<string | RegExp>): string {\r\n return text\r\n .split('&')\r\n .map((pair) => {\r\n const eq = pair.indexOf('=');\r\n if (eq < 0) return pair;\r\n let key = pair.slice(0, eq);\r\n try {\r\n key = decodeURIComponent(key.replace(/\\+/g, ' '));\r\n } catch {}\r\n if (isSecretKey(key, extra)) return `${pair.slice(0, eq)}=${FILTERED}`;\r\n const value = pair.slice(eq + 1);\r\n return value.length >= 256 ? `${pair.slice(0, eq)}=${shortenEncoded(value)}` : pair;\r\n })\r\n .join('&');\r\n}\r\n\r\nfunction shortenEncoded(value: string): string {\r\n try {\r\n const decoded = decodeURIComponent(value.replace(/\\+/g, ' '));\r\n const short = shorten(decoded);\r\n return short === decoded ? value : short;\r\n } catch {\r\n return value;\r\n }\r\n}\r\n\r\n// ── the attribute value ───────────────────────────────────────────────────────\r\n\r\n/**\r\n * A body as it is sent: redacted, then cut to `maxSize`. `cut` says the text was already cut\r\n * short where it was read. Null for an empty body. A `multipart/form-data` body is passed as the\r\n * JSON of its fields (files already described).\r\n */\r\nexport function formatBody(\r\n text: string | null | undefined,\r\n contentType: string | null | undefined,\r\n settings: BodySettings,\r\n cut = false,\r\n): { value: string; truncated: boolean } | null {\r\n if (text == null) return null;\r\n let body = String(text);\r\n if (!body.trim()) return null;\r\n\r\n if (isForm(contentType)) body = redactForm(body, settings.extraKeys);\r\n else {\r\n let parsed: unknown;\r\n let ok = false;\r\n const trimmed = body.trim();\r\n if (!cut && (trimmed[0] === '{' || trimmed[0] === '[')) {\r\n try {\r\n parsed = JSON.parse(trimmed);\r\n ok = true;\r\n } catch {}\r\n }\r\n body = ok ? JSON.stringify(redactValue(parsed, settings.extraKeys)) : redactLoose(body, settings.extraKeys);\r\n }\r\n\r\n const truncated = cut || body.length > settings.maxSize;\r\n return { value: body.length > settings.maxSize ? body.slice(0, settings.maxSize) : body, truncated };\r\n}\r\n\r\nfunction typeKey(side: 'request' | 'response') {\r\n return side === 'request' ? BODY_ATTRIBUTES.requestType : BODY_ATTRIBUTES.responseType;\r\n}\r\n\r\n/**\r\n * The span attributes for one side of a request (`request` or `response`). A body that is not\r\n * text is described (`size` in bytes when known) instead of left out.\r\n */\r\nexport function bodyAttributes(\r\n side: 'request' | 'response',\r\n text: string | null | undefined,\r\n contentType: string | null | undefined,\r\n settings: BodySettings,\r\n cut = false,\r\n): Record<string, unknown> {\r\n if (!isTextual(contentType) && !isMultipart(contentType)) return {};\r\n const formatted = formatBody(text, contentType, settings, cut);\r\n if (!formatted) return {};\r\n const attributes: Record<string, unknown> = { [BODY_ATTRIBUTES[side]]: formatted.value };\r\n if (formatted.truncated) attributes[side === 'request' ? BODY_ATTRIBUTES.requestTruncated : BODY_ATTRIBUTES.responseTruncated] = true;\r\n if (contentType) attributes[typeKey(side)] = contentType;\r\n return attributes;\r\n}\r\n\r\n/** The attributes for a body that is not text: what it was, not what it said. */\r\nexport function describedAttributes(side: 'request' | 'response', contentType: string | null | undefined, size?: number, partial = false): Record<string, unknown> {\r\n const attributes: Record<string, unknown> = { [BODY_ATTRIBUTES[side]]: describeBody(contentType, size, partial) };\r\n if (contentType) attributes[typeKey(side)] = contentType;\r\n return attributes;\r\n}\r\n\r\n// ── URLs ──────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * A URL as it is recorded: query values under secret-looking keys (`token`, `key`, `sig`,\r\n * `password`, …) become `[Filtered]`, and `user:password@` is dropped. Anything that is not\r\n * a URL is returned as it is.\r\n */\r\nexport function redactUrl(url: string, extra: Array<string | RegExp> = []): string {\r\n if (!url) return url;\r\n let out = url.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/?#@]*@/i, '$1');\r\n const q = out.indexOf('?');\r\n if (q < 0) return out;\r\n const hash = out.indexOf('#', q);\r\n const query = out.slice(q + 1, hash < 0 ? undefined : hash);\r\n const redacted = redactQuery(query, extra);\r\n if (redacted !== query) out = out.slice(0, q + 1) + redacted + (hash < 0 ? '' : out.slice(hash));\r\n return out;\r\n}\r\n\r\n/** A query string (without `?`) with secret-looking values filtered. */\r\nexport function redactQuery(query: string, extra: Array<string | RegExp> = []): string {\r\n if (!query) return query;\r\n return query\r\n .split('&')\r\n .map((pair) => {\r\n const eq = pair.indexOf('=');\r\n if (eq < 0) return pair;\r\n let key = pair.slice(0, eq);\r\n try {\r\n key = decodeURIComponent(key.replace(/\\+/g, ' '));\r\n } catch {}\r\n const secret = isSecretKey(key, extra) || URL_EXACT.includes(normalize(key));\r\n return secret && eq < pair.length - 1 ? `${pair.slice(0, eq)}=${FILTERED}` : pair;\r\n })\r\n .join('&');\r\n}\r\n\r\n/**\r\n * Whether `url` matches one of `patterns`: a bare host (with or without a port) matches that\r\n * host; a string with a scheme matches as a prefix; a RegExp is tested against the URL.\r\n */\r\nexport function urlMatches(url: string, patterns: Array<string | RegExp>): boolean {\r\n let host = '';\r\n let hostname = '';\r\n try {\r\n const parsed = new URL(url);\r\n host = parsed.host;\r\n hostname = parsed.hostname;\r\n } catch {}\r\n return patterns.some((p) => {\r\n if (p instanceof RegExp) return p.test(url);\r\n if (!p) return false;\r\n if (p.includes('://')) return url.startsWith(p);\r\n return host === p || hostname === p;\r\n });\r\n}\r\n","/**\r\n * `captureBodies` for Node: request and response bodies on the http instrumentation's spans,\r\n * for incoming requests (SERVER) and outgoing ones (CLIENT, http/https — axios, got, node-fetch).\r\n *\r\n * Nothing changes how the application reads or writes its streams. Readable sides (an incoming\r\n * request, an outgoing request's response) are seen through their own `emit('data')`, which\r\n * fires whichever way the app consumes them — listeners, pipe, async iteration — without\r\n * switching them into flowing mode. Writable sides (a server response, an outgoing request)\r\n * are seen through `write`/`end`. What is kept depends on the body:\r\n * - text: the first bytes, up to the raw limit\r\n * - a form upload (`multipart/form-data`): each text field, and each file as its name, type and\r\n * size — file bytes are counted as they pass, never kept\r\n * - anything else (an image, a PDF, an event stream): only its size\r\n * Attributes are made in `applyCustomAttributesOnSpan`, which runs just before the span ends.\r\n */\r\nimport { ClientRequest, IncomingMessage, ServerResponse } from 'node:http';\r\nimport { brotliDecompressSync, constants, gunzipSync, inflateSync } from 'node:zlib';\r\nimport type { Span } from '@opentelemetry/api';\r\nimport {\r\n bodyAttributes,\r\n describedAttributes,\r\n fileLabel,\r\n isMultipart,\r\n isTextual,\r\n rawLimit,\r\n urlMatches,\r\n wanted,\r\n type BodySettings,\r\n} from '@zharp/internal/bodies';\r\n\r\nconst TAP = Symbol.for('zharp.body');\r\n/** Fields kept from one form upload. */\r\nconst MAX_FIELDS = 200;\r\n\r\n// ── multipart/form-data ───────────────────────────────────────────────────────\r\n\r\ninterface Part {\r\n name: string;\r\n filename?: string;\r\n type?: string;\r\n size: number;\r\n text: Buffer[];\r\n kept: number;\r\n}\r\n\r\n/** Reads a form upload as it streams past: text fields kept (up to `maxText` each), files counted. */\r\nclass Multipart {\r\n private buf: Buffer = Buffer.alloc(0);\r\n private state: 'start' | 'after' | 'headers' | 'body' | 'done' = 'start';\r\n private readonly first: Buffer;\r\n private readonly delimiter: Buffer;\r\n private part: Part | null = null;\r\n private count = 0;\r\n readonly fields: Record<string, unknown> = {};\r\n cut = false;\r\n\r\n constructor(boundary: string, private readonly maxText: number) {\r\n this.first = Buffer.from(`--${boundary}`);\r\n this.delimiter = Buffer.from(`\\r\\n--${boundary}`);\r\n }\r\n\r\n push(chunk: Buffer): void {\r\n if (this.state === 'done') return;\r\n this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : chunk;\r\n for (;;) {\r\n if (this.state === 'start') {\r\n const i = this.buf.indexOf(this.first);\r\n if (i < 0) {\r\n if (this.buf.length > 64 * 1024) this.state = 'done';\r\n return;\r\n }\r\n this.buf = this.buf.subarray(i + this.first.length);\r\n this.state = 'after';\r\n }\r\n if (this.state === 'after') {\r\n if (this.buf.length < 2) return;\r\n if (this.buf[0] === 45 && this.buf[1] === 45) {\r\n this.state = 'done';\r\n this.buf = Buffer.alloc(0);\r\n return;\r\n }\r\n if (this.buf[0] === 13 && this.buf[1] === 10) this.buf = this.buf.subarray(2);\r\n this.state = 'headers';\r\n }\r\n if (this.state === 'headers') {\r\n const i = this.buf.indexOf('\\r\\n\\r\\n');\r\n if (i < 0) {\r\n if (this.buf.length > 16 * 1024) this.state = 'done';\r\n return;\r\n }\r\n this.part = parsePartHeaders(this.buf.subarray(0, i).toString('utf8'));\r\n this.buf = this.buf.subarray(i + 4);\r\n this.state = 'body';\r\n }\r\n if (this.state === 'body') {\r\n const i = this.buf.indexOf(this.delimiter);\r\n if (i >= 0) {\r\n this.consume(this.buf.subarray(0, i));\r\n this.finish(false);\r\n this.buf = this.buf.subarray(i + this.delimiter.length);\r\n this.state = 'after';\r\n if (this.count >= MAX_FIELDS) {\r\n this.state = 'done';\r\n this.cut = true;\r\n return;\r\n }\r\n continue;\r\n }\r\n // Keep what could be the start of the delimiter; the rest belongs to this part.\r\n const keep = this.delimiter.length - 1;\r\n if (this.buf.length > keep) {\r\n this.consume(this.buf.subarray(0, this.buf.length - keep));\r\n this.buf = Buffer.from(this.buf.subarray(this.buf.length - keep));\r\n }\r\n return;\r\n }\r\n return;\r\n }\r\n }\r\n\r\n private consume(bytes: Buffer): void {\r\n const part = this.part;\r\n if (!part || !bytes.length) return;\r\n part.size += bytes.length;\r\n if (part.filename !== undefined) return; // a file: counted, never kept\r\n const room = this.maxText - part.kept;\r\n if (room > 0) {\r\n const slice = bytes.subarray(0, room);\r\n part.text.push(Buffer.from(slice));\r\n part.kept += slice.length;\r\n }\r\n }\r\n\r\n private finish(partial: boolean): void {\r\n const part = this.part;\r\n this.part = null;\r\n if (!part) return;\r\n let value: unknown;\r\n if (part.filename !== undefined) value = fileLabel(part.filename, part.type, part.size, partial);\r\n else {\r\n value = Buffer.concat(part.text).toString('utf8').replace(/�$/, '');\r\n if (part.size > part.kept || partial) this.cut = true;\r\n }\r\n const existing = this.fields[part.name];\r\n this.fields[part.name] = existing === undefined ? value : Array.isArray(existing) ? [...existing, value] : [existing, value];\r\n this.count++;\r\n }\r\n\r\n /** The fields so far, including a part the stream stopped inside. */\r\n result(): { json: string; cut: boolean } {\r\n if (this.part) {\r\n this.consume(this.state === 'body' ? this.buf : Buffer.alloc(0));\r\n this.buf = Buffer.alloc(0);\r\n this.finish(true);\r\n this.cut = true;\r\n }\r\n return { json: JSON.stringify(this.fields), cut: this.cut };\r\n }\r\n}\r\n\r\nfunction parsePartHeaders(head: string): Part {\r\n const disposition = /^content-disposition:(.*)$/im.exec(head)?.[1] ?? '';\r\n const name = /\\bname=\"([^\"]*)\"/i.exec(disposition)?.[1] ?? /\\bname=([^;\\s]+)/i.exec(disposition)?.[1] ?? '';\r\n const filenameStar = /\\bfilename\\*=(?:UTF-8'')?([^;\\s]+)/i.exec(disposition)?.[1];\r\n let filename = /\\bfilename=\"([^\"]*)\"/i.exec(disposition)?.[1];\r\n if (filenameStar) {\r\n try {\r\n filename = decodeURIComponent(filenameStar);\r\n } catch {\r\n filename = filenameStar;\r\n }\r\n }\r\n const type = /^content-type:\\s*(.*)$/im.exec(head)?.[1]?.trim();\r\n return { name, filename, type: filename !== undefined ? type : undefined, size: 0, text: [], kept: 0 };\r\n}\r\n\r\nfunction boundaryOf(contentType: string | undefined): string | undefined {\r\n const m = /boundary=(?:\"([^\"]+)\"|([^;\\s]+))/i.exec(contentType ?? '');\r\n return m ? m[1] ?? m[2] : undefined;\r\n}\r\n\r\n// ── taps ──────────────────────────────────────────────────────────────────────\r\n\r\nclass Tap {\r\n private chunks: Buffer[] = [];\r\n private kept = 0;\r\n /** Every byte seen, kept or not. */\r\n total = 0;\r\n cut = false;\r\n private mode: 'text' | 'count' | 'multipart' | undefined;\r\n multipart?: Multipart;\r\n\r\n /** `typeOf` is asked once, at the first byte, when the content type is surely set. */\r\n constructor(\r\n private readonly settings: BodySettings,\r\n private readonly typeOf: () => string | undefined,\r\n ) {}\r\n\r\n add(chunk: unknown, encoding?: unknown): void {\r\n if (chunk == null || typeof chunk === 'function') return;\r\n let buf: Buffer;\r\n if (typeof chunk === 'string') buf = Buffer.from(chunk, typeof encoding === 'string' && Buffer.isEncoding(encoding) ? encoding : 'utf8');\r\n else if (chunk instanceof Uint8Array) buf = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\r\n else return;\r\n if (!buf.length) return;\r\n this.total += buf.length;\r\n\r\n if (this.mode === undefined) {\r\n const type = this.typeOf();\r\n const boundary = isMultipart(type) ? boundaryOf(type) : undefined;\r\n if (boundary) {\r\n this.mode = 'multipart';\r\n this.multipart = new Multipart(boundary, this.settings.maxSize);\r\n } else this.mode = isTextual(type) ? 'text' : 'count';\r\n }\r\n if (this.mode === 'multipart') return this.multipart!.push(Buffer.from(buf));\r\n if (this.mode === 'count' || this.cut) return;\r\n\r\n const room = rawLimit(this.settings) - this.kept;\r\n if (buf.length > room) {\r\n this.cut = true;\r\n buf = buf.subarray(0, Math.max(0, room));\r\n }\r\n if (buf.length) {\r\n this.chunks.push(Buffer.from(buf));\r\n this.kept += buf.length;\r\n }\r\n }\r\n\r\n /** The text, inflated if it was compressed; null when it cannot be read as text. */\r\n text(encoding: string | undefined): string | null {\r\n let raw = Buffer.concat(this.chunks);\r\n const enc = (encoding ?? '').toLowerCase().trim();\r\n try {\r\n // A cut-off stream still inflates up to where it stops.\r\n const flush = { finishFlush: constants.Z_SYNC_FLUSH };\r\n if (enc === 'gzip' || enc === 'x-gzip') raw = gunzipSync(raw, flush);\r\n else if (enc === 'deflate') raw = inflateSync(raw, flush);\r\n else if (enc === 'br') raw = brotliDecompressSync(raw, { finishFlush: constants.BROTLI_OPERATION_FLUSH });\r\n else if (enc && enc !== 'identity') return null;\r\n } catch {\r\n return null;\r\n }\r\n // A multi-byte character split at the cap decodes as U+FFFD; drop it.\r\n return raw.toString('utf8').replace(/�$/, '');\r\n }\r\n}\r\n\r\n/** The attributes for one side, whatever kind of body it was. */\r\nfunction sideAttributes(\r\n side: 'request' | 'response',\r\n tap: Tap | undefined,\r\n type: string | undefined,\r\n encoding: string | undefined,\r\n settings: BodySettings,\r\n): Record<string, unknown> {\r\n if (!tap || !tap.total) return {};\r\n if (tap.multipart) {\r\n const { json, cut } = tap.multipart.result();\r\n return bodyAttributes(side, json, type, settings, cut);\r\n }\r\n if (!isTextual(type)) return describedAttributes(side, type, tap.total);\r\n const text = tap.text(encoding);\r\n if (text == null) return describedAttributes(side, type, tap.total);\r\n return bodyAttributes(side, text, type, settings, tap.cut);\r\n}\r\n\r\n/** Keeps what a readable stream emits. */\r\nfunction tapReadable(stream: IncomingMessage, tap: Tap): void {\r\n const emit = stream.emit;\r\n stream.emit = function (this: IncomingMessage, event: string | symbol, ...args: any[]) {\r\n if (event === 'data') {\r\n try {\r\n tap.add(args[0]);\r\n } catch {}\r\n }\r\n return emit.call(this, event, ...args);\r\n } as typeof stream.emit;\r\n (stream as any)[TAP] = tap;\r\n}\r\n\r\n/** Keeps what is written to a writable stream. */\r\nfunction tapWritable(stream: ServerResponse | ClientRequest, tap: Tap): void {\r\n const target = stream as any;\r\n const write = target.write;\r\n const end = target.end;\r\n target.write = function (this: unknown, ...args: any[]) {\r\n try {\r\n tap.add(args[0], args[1]);\r\n } catch {}\r\n return write.apply(this, args);\r\n };\r\n target.end = function (this: unknown, ...args: any[]) {\r\n try {\r\n tap.add(args[0], args[1]);\r\n } catch {}\r\n return end.apply(this, args);\r\n };\r\n (stream as any)[TAP] = tap;\r\n}\r\n\r\nconst tapOf = (stream: unknown): Tap | undefined => (stream as any)?.[TAP];\r\n\r\nfunction header(value: unknown): string | undefined {\r\n if (value == null) return undefined;\r\n return Array.isArray(value) ? String(value[0]) : String(value);\r\n}\r\n\r\nfunction incomingUrl(req: IncomingMessage): string {\r\n const proto = (req.socket as any)?.encrypted ? 'https' : 'http';\r\n return `${proto}://${req.headers.host ?? 'localhost'}${req.url ?? '/'}`;\r\n}\r\n\r\n/**\r\n * A header the server sent. Headers given to `writeHead()` alone never reach `getHeader()`, so\r\n * the head as written is read as well.\r\n */\r\nfunction sentHeader(res: ServerResponse, name: string): string | undefined {\r\n const set = header(res.getHeader(name));\r\n if (set) return set;\r\n const head = (res as any)._header;\r\n if (typeof head !== 'string') return undefined;\r\n const match = head.match(new RegExp(`^${name}:[ \\\\t]*(.*)$`, 'im'));\r\n return match ? match[1].trim() : undefined;\r\n}\r\n\r\nfunction outgoingUrl(req: ClientRequest): string {\r\n const r = req as any;\r\n return `${r.protocol ?? 'http:'}//${r.host ?? 'localhost'}${r.path ?? '/'}`;\r\n}\r\n\r\ntype HttpConfig = {\r\n requestHook?: (span: Span, request: any) => void;\r\n responseHook?: (span: Span, response: any) => void;\r\n applyCustomAttributesOnSpan?: (span: Span, request: any, response: any) => void;\r\n [key: string]: unknown;\r\n};\r\n\r\n/**\r\n * The http instrumentation's config with body capture added. Hooks the application set itself\r\n * still run, first.\r\n */\r\nexport function withBodyCapture(settings: BodySettings, config: HttpConfig = {}): HttpConfig {\r\n const allowed = (url: string) => !settings.urls || urlMatches(url, settings.urls);\r\n\r\n return {\r\n ...config,\r\n requestHook(span, request) {\r\n config.requestHook?.(span, request);\r\n try {\r\n if (request instanceof IncomingMessage) {\r\n if (allowed(incomingUrl(request))) tapReadable(request, new Tap(settings, () => header(request.headers['content-type'])));\r\n } else if (request instanceof ClientRequest) {\r\n if (allowed(outgoingUrl(request))) tapWritable(request, new Tap(settings, () => header(request.getHeader('content-type'))));\r\n }\r\n } catch {}\r\n },\r\n responseHook(span, response) {\r\n config.responseHook?.(span, response);\r\n try {\r\n if (response instanceof ServerResponse) {\r\n if (tapOf(response.req) || allowed(incomingUrl(response.req))) tapWritable(response, new Tap(settings, () => sentHeader(response, 'content-type')));\r\n } else if (response instanceof IncomingMessage) {\r\n const req = (response as any).req as ClientRequest | undefined;\r\n if (!req || tapOf(req) || allowed(outgoingUrl(req))) tapReadable(response, new Tap(settings, () => header(response.headers['content-type'])));\r\n }\r\n } catch {}\r\n },\r\n applyCustomAttributesOnSpan(span, request, response) {\r\n config.applyCustomAttributesOnSpan?.(span, request, response);\r\n try {\r\n const status = Number(response?.statusCode) || 0;\r\n if (!wanted(settings, status)) return;\r\n const attributes: Record<string, unknown> = {};\r\n\r\n if (request instanceof ClientRequest) {\r\n Object.assign(\r\n attributes,\r\n sideAttributes('request', tapOf(request), header(request.getHeader('content-type')), header(request.getHeader('content-encoding')), settings),\r\n );\r\n const res = response as IncomingMessage;\r\n Object.assign(\r\n attributes,\r\n sideAttributes('response', tapOf(res), header(res?.headers?.['content-type']), header(res?.headers?.['content-encoding']), settings),\r\n );\r\n } else if (request instanceof IncomingMessage) {\r\n const sentType = header(request.headers['content-type']);\r\n const sent = tapOf(request);\r\n if (sent && sent.total) {\r\n Object.assign(attributes, sideAttributes('request', sent, sentType, header(request.headers['content-encoding']), settings));\r\n } else {\r\n // Read before the hooks were in place (rare): a framework's parsed body will do.\r\n const parsed = (request as any).body;\r\n if (parsed != null && (typeof parsed === 'string' || (typeof parsed === 'object' && !Buffer.isBuffer(parsed)))) {\r\n const text = typeof parsed === 'string' ? parsed : JSON.stringify(parsed);\r\n Object.assign(attributes, bodyAttributes('request', text, isTextual(sentType) ? sentType : 'application/json', settings));\r\n }\r\n }\r\n const res = response as ServerResponse;\r\n Object.assign(attributes, sideAttributes('response', tapOf(res), sentHeader(res, 'content-type'), sentHeader(res, 'content-encoding'), settings));\r\n }\r\n if (Object.keys(attributes).length) span.setAttributes(attributes as any);\r\n } catch {}\r\n },\r\n };\r\n}\r\n","/**\r\n * Secrets in URLs never leave the process: before any span ends, query values under\r\n * secret-looking keys (`token`, `key`, `sig`, `password`, …) in its URL attributes become\r\n * `[Filtered]`, and `user:password@` is dropped. Every span, whatever made it — http, fetch,\r\n * a framework — and whether or not `captureBodies` is on.\r\n */\r\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace';\r\nimport { redactQuery, redactUrl } from '@zharp/internal/bodies';\r\n\r\nconst URL_KEYS = ['url.full', 'http.url', 'http.target'];\r\n\r\nexport class UrlRedactionSpanProcessor implements SpanProcessor {\r\n onStart(): void {}\r\n\r\n onEnding(span: Span): void {\r\n try {\r\n const attributes = (span as unknown as ReadableSpan).attributes ?? {};\r\n for (const key of URL_KEYS) {\r\n const value = attributes[key];\r\n if (typeof value === 'string') {\r\n const redacted = redactUrl(value);\r\n if (redacted !== value) span.setAttribute(key, redacted);\r\n }\r\n }\r\n const query = attributes['url.query'];\r\n if (typeof query === 'string') {\r\n const bare = query.startsWith('?') ? query.slice(1) : query;\r\n const redacted = redactQuery(bare);\r\n if (redacted !== bare) span.setAttribute('url.query', (query.startsWith('?') ? '?' : '') + redacted);\r\n }\r\n } catch {\r\n // Never let telemetry break a request.\r\n }\r\n }\r\n\r\n onEnd(_span: ReadableSpan): void {}\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n","/**\r\n * Who a request is for, and the tags set on everything.\r\n *\r\n * Zharp joins a back end's spans and logs to the user and browser session that caused them\r\n * through two attributes, `enduser.id` and `session.id`. The browser SDK sends both in the W3C\r\n * `baggage` header next to `traceparent`; the processors here copy them from the baggage onto\r\n * every span and log written while handling that request, so nothing in the application has to\r\n * know about them.\r\n *\r\n * `Zharp.setUser()` covers the other case — a back end that knows the user itself (a session\r\n * cookie, an API token). OpenTelemetry's context is immutable, so the user cannot be put into\r\n * the request's context from inside a handler; it is kept per trace instead, and every span and\r\n * log in that trace picks it up from then on.\r\n */\r\nimport { context as otelContext, propagation, trace, type Context } from '@opentelemetry/api';\r\nimport type { ReadWriteLogRecord, LogRecordProcessor } from '@opentelemetry/sdk-logs';\r\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace';\r\nimport type { ZharpUser } from './types';\r\n\r\n/** Baggage entries copied onto spans and logs, unchanged in name. */\r\nconst BAGGAGE_KEYS = ['enduser.id', 'session.id'] as const;\r\n\r\n/** The user as attributes, ready to set. */\r\nexport type UserAttributes = Record<string, string>;\r\n\r\nexport function userAttributes(user: ZharpUser): UserAttributes {\r\n const out: UserAttributes = { 'enduser.id': String(user.id) };\r\n if (user.email) out['enduser.email'] = String(user.email);\r\n if (user.name) out['enduser.name'] = String(user.name);\r\n return out;\r\n}\r\n\r\n/**\r\n * Users and tags, and which trace each user belongs to.\r\n *\r\n * A trace's user is dropped when the span that began the trace in this process ends — its\r\n * SERVER span, for a request — so the map holds only requests in flight.\r\n */\r\nexport class ContextStore {\r\n /** Set outside any request: a script or worker that is one user's work throughout. */\r\n globalUser: UserAttributes | null = null;\r\n readonly tags: Record<string, string | number | boolean> = {};\r\n private readonly byTrace = new Map<string, UserAttributes>();\r\n /** The first span of each trace in this process, which the user is also written onto. */\r\n private readonly localRoots = new Map<string, { spanId: string; span: Span }>();\r\n\r\n /** Set the user for the request in progress, or for the whole process outside one. */\r\n setUser(user: UserAttributes | null): void {\r\n const span = trace.getActiveSpan();\r\n const traceId = span?.spanContext().traceId;\r\n if (!span || !traceId) {\r\n this.globalUser = user;\r\n return;\r\n }\r\n if (user) {\r\n this.byTrace.set(traceId, user);\r\n // The spans already open learn it too: the request's own span is the one the dashboard\r\n // lists, and it is still open while the handler runs.\r\n span.setAttributes(user);\r\n this.localRoots.get(traceId)?.span.setAttributes(user);\r\n } else {\r\n this.byTrace.delete(traceId);\r\n }\r\n }\r\n\r\n /** What every span and log in `traceId` should carry, before baggage. */\r\n attributesFor(traceId: string | undefined): Record<string, string | number | boolean> {\r\n const user = (traceId && this.byTrace.get(traceId)) || this.globalUser;\r\n return user ? { ...this.tags, ...user } : { ...this.tags };\r\n }\r\n\r\n noteStart(span: Span, parent: Context): void {\r\n const parentSpan = trace.getSpanContext(parent);\r\n // No parent, or one from another process: this span starts the trace here.\r\n if (!parentSpan || parentSpan.isRemote) {\r\n const { traceId, spanId } = span.spanContext();\r\n if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });\r\n }\r\n }\r\n\r\n noteEnd(span: ReadableSpan): void {\r\n const { traceId, spanId } = span.spanContext();\r\n if (this.localRoots.get(traceId)?.spanId !== spanId) return;\r\n this.localRoots.delete(traceId);\r\n this.byTrace.delete(traceId);\r\n }\r\n}\r\n\r\n/** `enduser.id` and `session.id` from the baggage in `ctx`, when the caller sent them. */\r\nfunction fromBaggage(ctx: Context): Record<string, string> {\r\n const out: Record<string, string> = {};\r\n const baggage = propagation.getBaggage(ctx);\r\n if (!baggage) return out;\r\n for (const key of BAGGAGE_KEYS) {\r\n const value = baggage.getEntry(key)?.value;\r\n if (value) out[key] = value;\r\n }\r\n return out;\r\n}\r\n\r\n/** Puts the user, session and tags on every span as it starts. Exports nothing itself. */\r\nexport class ContextSpanProcessor implements SpanProcessor {\r\n constructor(private readonly store: ContextStore) {}\r\n\r\n onStart(span: Span, parentContext: Context): void {\r\n try {\r\n this.store.noteStart(span, parentContext);\r\n // The store first, baggage over it: the browser's word on its own session is final, and\r\n // a user the server set itself is already in the store's entry for this trace.\r\n span.setAttributes({ ...this.store.attributesFor(span.spanContext().traceId), ...fromBaggage(parentContext) });\r\n } catch {\r\n // Never let telemetry break a request.\r\n }\r\n }\r\n\r\n onEnd(span: ReadableSpan): void {\r\n this.store.noteEnd(span);\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n\r\n/** The same for log records — those written through Zharp.log, the console, pino and winston alike. */\r\nexport class ContextLogProcessor implements LogRecordProcessor {\r\n constructor(private readonly store: ContextStore) {}\r\n\r\n onEmit(record: ReadWriteLogRecord, ctx?: Context): void {\r\n try {\r\n const active = ctx ?? otelContext.active();\r\n const traceId = record.spanContext?.traceId ?? trace.getSpanContext(active)?.traceId;\r\n const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };\r\n // An attribute the call itself set (a log naming a different user, say) is kept.\r\n for (const [key, value] of Object.entries(add)) {\r\n if (record.attributes[key] === undefined) record.setAttribute(key, value);\r\n }\r\n } catch {\r\n // As above.\r\n }\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n","/**\r\n * `console.*` as OpenTelemetry log records.\r\n *\r\n * OpenTelemetry bridges pino, winston and bunyan but not the console, which is where most Node\r\n * code logs. Each call still prints exactly as before; a copy is emitted as a record in the\r\n * active context, so it carries the trace and span it was written in.\r\n */\r\nimport { format } from 'node:util';\r\nimport { SeverityNumber, type Logger } from '@opentelemetry/api';\r\nimport { quiet } from './capture-state';\r\n\r\nconst LEVELS: Array<[method: 'log' | 'info' | 'warn' | 'error' | 'debug' | 'trace', severity: SeverityNumber, text: string]> = [\r\n ['debug', SeverityNumber.DEBUG, 'DEBUG'],\r\n ['trace', SeverityNumber.TRACE, 'TRACE'],\r\n ['log', SeverityNumber.INFO, 'INFO'],\r\n ['info', SeverityNumber.INFO, 'INFO'],\r\n ['warn', SeverityNumber.WARN, 'WARN'],\r\n ['error', SeverityNumber.ERROR, 'ERROR'],\r\n];\r\n\r\n/** Set while a record is being emitted, so a console call made by the exporter is not sent too. */\r\nlet emitting = false;\r\n\r\n/**\r\n * Patch the console. Returns the undo.\r\n *\r\n * Lines the SDK prints about itself (`[Zharp] …`) are left out: they describe the reporting,\r\n * not the application.\r\n */\r\nexport function captureConsole(logger: Logger): () => void {\r\n const originals = new Map<string, (...args: unknown[]) => void>();\r\n for (const [method, severityNumber, severityText] of LEVELS) {\r\n const original = console[method];\r\n if (typeof original !== 'function' || (original as any).__zharp) continue;\r\n originals.set(method, original);\r\n const patched = function (this: unknown, ...args: unknown[]) {\r\n // Printed under quiet: the output capture would otherwise send the same line again.\r\n quiet(() => original.apply(this ?? console, args));\r\n if (emitting) return;\r\n emitting = true;\r\n try {\r\n const body = format(...args);\r\n if (!body.startsWith('[Zharp]')) {\r\n logger.emit({ severityNumber, severityText, body, attributes: { 'log.source': 'console' } });\r\n }\r\n } catch {\r\n // A log line that could not be copied is not worth an exception in the caller.\r\n } finally {\r\n emitting = false;\r\n }\r\n };\r\n (patched as any).__zharp = true;\r\n console[method] = patched;\r\n }\r\n return () => {\r\n for (const [method, original] of originals) (console as any)[method] = original;\r\n };\r\n}\r\n","/**\r\n * What the log captures share, so a line is sent once however many of them see it.\r\n *\r\n * The console capture and the logging-library bridges send a line with its exact level; the\r\n * output capture (stdout.ts) is the net under them, for whatever writes to the process's output\r\n * some other way. While a captured call is printing, the output capture stands aside; and a line\r\n * a bridge sent a moment ago is recognised when it then reaches the output (winston's console\r\n * transport, for one, prints after its bridge has already sent the record).\r\n */\r\n\r\n/** Above zero while a capture is printing a line it has already sent, or the SDK is exporting. */\r\nlet depth = 0;\r\n\r\nexport function quiet<T>(fn: () => T): T {\r\n depth++;\r\n try {\r\n return fn();\r\n } finally {\r\n depth--;\r\n }\r\n}\r\n\r\nexport const isQuiet = () => depth > 0;\r\n\r\n/** Bodies sent in the last few seconds, by a capture other than the output's. */\r\nconst RECENT_MS = 3000;\r\nconst RECENT_MAX = 500;\r\nconst recent: Array<{ at: number; text: string }> = [];\r\n\r\nconst normalise = (text: string) => text.replace(/\\s+/g, ' ').trim();\r\n\r\nexport function rememberSent(body: unknown): void {\r\n if (typeof body !== 'string') return;\r\n const text = normalise(body);\r\n if (text.length < 4) return;\r\n recent.push({ at: Date.now(), text });\r\n if (recent.length > RECENT_MAX) recent.splice(0, recent.length - RECENT_MAX);\r\n}\r\n\r\n/** Whether a printed line is one a capture already sent: its text contains a recent body. */\r\nexport function alreadySent(line: string): boolean {\r\n const now = Date.now();\r\n while (recent.length && now - recent[0].at > RECENT_MS) recent.shift();\r\n if (!recent.length) return false;\r\n const text = normalise(line);\r\n for (let i = recent.length - 1; i >= 0; i--) {\r\n if (text.includes(recent[i].text)) {\r\n recent.splice(i, 1);\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\n","/**\r\n * The process's output as logs: everything written to stdout and stderr that the console\r\n * capture and the logging-library bridges didn't already send.\r\n *\r\n * Plenty of Node logging never touches `console`: NestJS's Logger, debug, log4js, signale,\r\n * hand-rolled loggers and libraries all write to `process.stdout` directly. This is the net\r\n * under the exact captures, so a line printed any way at all still arrives, in the request it\r\n * was written in. Each line still prints exactly as before.\r\n *\r\n * A line's level is read from the line itself: a JSON record's own level, NestJS's\r\n * `LOG`/`WARN`/`ERROR`, or a level word such as `ERROR` or `[warn]`; failing that, stdout is\r\n * info and stderr is a warning.\r\n */\r\nimport { context as otelContext, isSpanContextValid, SeverityNumber, trace, type Context, type Logger } from '@opentelemetry/api';\r\nimport type { LogRecordProcessor, ReadWriteLogRecord } from '@opentelemetry/sdk-logs';\r\nimport { alreadySent, isQuiet, quiet, rememberSent } from './capture-state';\r\n\r\ntype Level = [SeverityNumber, string];\r\nconst LEVELS: Record<string, Level> = {\r\n trace: [SeverityNumber.TRACE, 'TRACE'],\r\n verbose: [SeverityNumber.DEBUG, 'DEBUG'],\r\n debug: [SeverityNumber.DEBUG, 'DEBUG'],\r\n log: [SeverityNumber.INFO, 'INFO'],\r\n info: [SeverityNumber.INFO, 'INFO'],\r\n notice: [SeverityNumber.INFO, 'INFO'],\r\n warn: [SeverityNumber.WARN, 'WARN'],\r\n warning: [SeverityNumber.WARN, 'WARN'],\r\n error: [SeverityNumber.ERROR, 'ERROR'],\r\n err: [SeverityNumber.ERROR, 'ERROR'],\r\n crit: [SeverityNumber.FATAL, 'FATAL'],\r\n critical: [SeverityNumber.FATAL, 'FATAL'],\r\n fatal: [SeverityNumber.FATAL, 'FATAL'],\r\n emerg: [SeverityNumber.FATAL, 'FATAL'],\r\n alert: [SeverityNumber.FATAL, 'FATAL'],\r\n};\r\n/** pino and bunyan write their level as a number. */\r\nconst NUMERIC: Array<[number, string]> = [[60, 'fatal'], [50, 'error'], [40, 'warn'], [30, 'info'], [20, 'debug'], [0, 'trace']];\r\n\r\n// eslint-disable-next-line no-control-regex\r\nconst ANSI = /\\u001b\\[[0-9;?]*[ -/]*[@-~]/g;\r\n/** `[Nest] 61 - 11/17/2026, 8:33:00 AM LOG [Context] message` */\r\nconst NEST = /^\\[Nest\\]\\s+\\d+\\s+-\\s+.*?\\s+(LOG|ERROR|WARN|DEBUG|VERBOSE|FATAL)\\s+(?:\\[([^\\]]+)\\]\\s+)?([\\s\\S]*)$/;\r\n/** The first level word in the opening of a line: `ERROR`, `[warn]`, `level=error`, `W/`. */\r\nconst WORD = /(?:^|[\\s[(|:=])(trace|verbose|debug|info|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|emerg|alert)(?=$|[\\s\\]):|,])/i;\r\n\r\nconst MAX_LINE = 32 * 1024;\r\nconst FLUSH_MS = 200;\r\n\r\ninterface Parsed {\r\n level: Level | null;\r\n body: string;\r\n attributes: Record<string, string>;\r\n}\r\n\r\nfunction levelOf(value: unknown): Level | null {\r\n if (typeof value === 'number') {\r\n const found = NUMERIC.find(([n]) => value >= n);\r\n return found ? LEVELS[found[1]] : null;\r\n }\r\n return typeof value === 'string' ? LEVELS[value.toLowerCase()] ?? null : null;\r\n}\r\n\r\n/** A line, read for its level and, for the formats worth knowing, its own message. */\r\nexport function parseLine(raw: string): Parsed {\r\n const line = raw.replace(ANSI, '').replace(/\\s+$/, '');\r\n if (line.startsWith('{') && line.endsWith('}')) {\r\n try {\r\n const record = JSON.parse(line);\r\n const message = record.msg ?? record.message ?? record.event;\r\n return {\r\n level: levelOf(record.level ?? record.severity ?? record.lvl),\r\n body: typeof message === 'string' ? message : line,\r\n attributes: {},\r\n };\r\n } catch {\r\n // Not JSON after all; read it as text.\r\n }\r\n }\r\n const nest = NEST.exec(line);\r\n if (nest) {\r\n return {\r\n level: LEVELS[nest[1].toLowerCase()],\r\n body: nest[3],\r\n attributes: nest[2] ? { 'log.logger': nest[2] } : {},\r\n };\r\n }\r\n const word = WORD.exec(line.slice(0, 120));\r\n return { level: word ? LEVELS[word[1].toLowerCase()] ?? null : null, body: line, attributes: {} };\r\n}\r\n\r\n/**\r\n * Remembers what every other capture sent (the logging-library bridges, Zharp.log, the\r\n * console), so the same line reaching the output a moment later isn't sent twice.\r\n */\r\nexport class SentLineProcessor implements LogRecordProcessor {\r\n onEmit(record: ReadWriteLogRecord): void {\r\n const source = record.attributes?.['log.source'];\r\n if (source !== 'stdout' && source !== 'stderr') rememberSent(record.body);\r\n }\r\n forceFlush(): Promise<void> { return Promise.resolve(); }\r\n shutdown(): Promise<void> { return Promise.resolve(); }\r\n}\r\n\r\n/**\r\n * Tap stdout and stderr. Returns the undo.\r\n */\r\nexport function captureOutput(logger: Logger): () => void {\r\n const undo: Array<() => void> = [];\r\n\r\n for (const [stream, name, fallback] of [\r\n [process.stdout, 'stdout', LEVELS.info],\r\n [process.stderr, 'stderr', LEVELS.warn],\r\n ] as const) {\r\n if (!stream || typeof stream.write !== 'function' || (stream.write as any).__zharp) continue;\r\n const original = stream.write;\r\n let pending = '';\r\n let pendingContext: Context | undefined;\r\n let timer: NodeJS.Timeout | undefined;\r\n\r\n const emitLine = (line: string, ctx: Context | undefined) => {\r\n if (!line.trim() || line.includes('[Zharp]') || alreadySent(line)) return;\r\n const parsed = parseLine(line.length > MAX_LINE ? line.slice(0, MAX_LINE) : line);\r\n if (!parsed.body.trim()) return;\r\n const [severityNumber, severityText] = parsed.level ?? fallback;\r\n quiet(() => logger.emit({\r\n severityNumber,\r\n severityText,\r\n body: parsed.body,\r\n attributes: { 'log.source': name, 'log.iostream': name, ...parsed.attributes },\r\n ...(ctx ? { context: ctx } : {}),\r\n }));\r\n };\r\n\r\n const flush = () => {\r\n timer = undefined;\r\n const line = pending;\r\n const ctx = pendingContext;\r\n pending = '';\r\n pendingContext = undefined;\r\n emitLine(line, ctx);\r\n };\r\n\r\n const take = (chunk: unknown, encoding: unknown) => {\r\n if (isQuiet()) return;\r\n const text = typeof chunk === 'string'\r\n ? chunk\r\n : chunk instanceof Uint8Array\r\n ? Buffer.from(chunk).toString(typeof encoding === 'string' ? (encoding as BufferEncoding) : 'utf8')\r\n : '';\r\n if (!text) return;\r\n // A line belongs to the request it started in.\r\n if (!pending) pendingContext = otelContext.active();\r\n pending += text;\r\n const lines = pending.split('\\n');\r\n pending = lines.pop() ?? '';\r\n const ctx = pendingContext;\r\n if (pending) pendingContext = otelContext.active();\r\n for (const line of lines) emitLine(line, ctx);\r\n if (pending.length > MAX_LINE) flush();\r\n else if (pending && !timer) {\r\n timer = setTimeout(flush, FLUSH_MS);\r\n timer.unref?.();\r\n }\r\n };\r\n\r\n const patched = function (this: unknown, chunk: unknown, encoding?: unknown, callback?: unknown) {\r\n try {\r\n take(chunk, encoding);\r\n } catch {\r\n // A line that could not be copied is not worth an exception in the caller.\r\n }\r\n return (original as any).call(this ?? stream, chunk, encoding, callback);\r\n };\r\n (patched as any).__zharp = true;\r\n stream.write = patched as typeof stream.write;\r\n undo.push(() => {\r\n if (timer) clearTimeout(timer);\r\n if (pending) flush();\r\n stream.write = original;\r\n });\r\n }\r\n\r\n return () => undo.forEach((fn) => fn());\r\n}\r\n\r\n/**\r\n * The request's ids on every line printed during it: `… trace_id=<32 hex> span_id=<16 hex>` at\r\n * the end of a text line, two fields in a JSON one. This is how a line someone else collects —\r\n * the Zharp agent reading the container's output — is linked to its request without the SDK\r\n * sending it. Lines printed outside a request, and lines that already carry a trace_id (pino and\r\n * winston add theirs), are left alone. Returns the undo.\r\n */\r\nexport function stampOutput(): () => void {\r\n const undo: Array<() => void> = [];\r\n for (const stream of [process.stdout, process.stderr]) {\r\n if (!stream || typeof stream.write !== 'function' || (stream.write as any).__zharpStamp) continue;\r\n const original = stream.write;\r\n const patched = function (this: unknown, chunk: unknown, encoding?: unknown, callback?: unknown) {\r\n let out = chunk;\r\n try {\r\n out = stamped(chunk, encoding);\r\n } catch {\r\n // An unstamped line is better than a lost one.\r\n }\r\n return (original as any).call(this ?? stream, out, encoding, callback);\r\n };\r\n (patched as any).__zharpStamp = true;\r\n stream.write = patched as typeof stream.write;\r\n undo.push(() => { stream.write = original; });\r\n }\r\n return () => undo.forEach((fn) => fn());\r\n}\r\n\r\nfunction stamped(chunk: unknown, encoding: unknown): unknown {\r\n const span = trace.getActiveSpan()?.spanContext();\r\n if (!span || !isSpanContextValid(span)) return chunk;\r\n const isBytes = chunk instanceof Uint8Array;\r\n if (typeof chunk !== 'string' && !isBytes) return chunk;\r\n const enc = typeof encoding === 'string' && Buffer.isEncoding(encoding) ? (encoding as BufferEncoding) : 'utf8';\r\n if (isBytes && enc !== 'utf8') return chunk;\r\n const text = isBytes ? Buffer.from(chunk as Uint8Array).toString('utf8') : (chunk as string);\r\n if (!text.includes('\\n')) return chunk;\r\n\r\n const parts = text.split('\\n');\r\n // One write is one record: a stack trace printed by console.log(error) or NestJS's Logger\r\n // spans many lines, and the agent joins it into one entry read for the stamp at its end. So\r\n // text gets one stamp, on its last line; JSON lines are records of their own and each gets\r\n // its fields.\r\n let last = -1;\r\n for (let i = parts.length - 2; i >= 0; i--) {\r\n if (parts[i].trim()) { last = i; break; }\r\n }\r\n let changed = false;\r\n for (let i = 0; i < parts.length - 1; i++) {\r\n if (i !== last && !parts[i].trimStart().startsWith('{')) continue;\r\n const next = stampLine(parts[i], span.traceId, span.spanId);\r\n if (next !== parts[i]) {\r\n parts[i] = next;\r\n changed = true;\r\n }\r\n }\r\n if (!changed) return chunk;\r\n const joined = parts.join('\\n');\r\n return isBytes ? Buffer.from(joined, 'utf8') : joined;\r\n}\r\n\r\nexport function stampLine(line: string, traceId: string, spanId: string): string {\r\n const cr = line.endsWith('\\r') ? '\\r' : '';\r\n const body = cr ? line.slice(0, -1) : line;\r\n const trimmed = body.trimEnd();\r\n if (!trimmed.trim() || body.includes('trace_id') || body.includes('[Zharp]')) return line;\r\n if (trimmed.endsWith('}')) {\r\n // A JSON record gets fields; the tail of a record written in pieces is left as it is.\r\n if (!trimmed.trimStart().startsWith('{')) return line;\r\n const close = trimmed.lastIndexOf('}');\r\n const inner = trimmed.slice(trimmed.indexOf('{') + 1, close).trim();\r\n const fields = `\"trace_id\":\"${traceId}\",\"span_id\":\"${spanId}\"`;\r\n return `${trimmed.slice(0, close)}${inner ? ',' : ''}${fields}}${body.slice(trimmed.length)}${cr}`;\r\n }\r\n return `${trimmed} trace_id=${traceId} span_id=${spanId}${body.slice(trimmed.length)}${cr}`;\r\n}\r\n","/**\r\n * Debug IDs: which build of a file a stack frame came from, so Zharp can find its source map.\r\n *\r\n * `zharp sourcemaps inject` (and the bundler plugins) add a line to every emitted JS file that\r\n * registers it at load time:\r\n *\r\n * (globalThis.__zharpDebugIds ||= {})[new Error().stack] = \"<uuid>\"\r\n *\r\n * The key is a stack captured inside the file, so its top frame names the file exactly as this\r\n * runtime sees it — whatever the CDN, URL or path. Parsing those stacks gives file → debug ID;\r\n * an error then carries the IDs of the files in its own stack as `zharp.debug_ids`, a JSON\r\n * object `{ \"<file as it appears in the stack>\": \"<uuid>\" }`.\r\n */\r\n\r\n/** The attribute an error carries its files' debug IDs in. */\r\nexport const DEBUG_IDS_ATTRIBUTE = 'zharp.debug_ids';\r\n\r\n/** File → debug ID, from the registry entries parsed so far. */\r\nconst files = new Map<string, string>();\r\n/** Registry keys already parsed. The registry only grows, so each stack is parsed once. */\r\nconst parsed = new Set<string>();\r\n\r\nfunction registry(): Record<string, unknown> | undefined {\r\n const g = typeof globalThis !== 'undefined' ? (globalThis as any) : undefined;\r\n const value = g && g.__zharpDebugIds;\r\n return value && typeof value === 'object' ? value : undefined;\r\n}\r\n\r\n/**\r\n * The file a stack frame line points at, as written in the line: V8 (`at fn (file:1:2)`,\r\n * `at file:1:2`), and Gecko/WebKit (`fn@file:1:2`, `@file:1:2`). Undefined for anything else.\r\n */\r\nexport function frameFile(line: string): string | undefined {\r\n const text = line.trim();\r\n if (!text) return undefined;\r\n let match = /^at (?:async )?(?:.*? \\()?(.+?):\\d+:\\d+\\)?$/.exec(text);\r\n if (match) return clean(match[1]);\r\n if (text.startsWith('at ')) return undefined;\r\n match = /^(?:[^@]*@)?(.+?):\\d+:\\d+$/.exec(text);\r\n return match ? clean(match[1]) : undefined;\r\n}\r\n\r\nfunction clean(file: string): string | undefined {\r\n // `eval at fn (file:1:2), <anonymous>` and friends name no file of their own.\r\n if (!file || file.includes('eval at ') || file === '<anonymous>' || file === 'native') return undefined;\r\n return file;\r\n}\r\n\r\n/** Every file in a stack, in order, each once. */\r\nexport function stackFiles(stack: string): string[] {\r\n const out: string[] = [];\r\n for (const line of stack.split('\\n')) {\r\n const file = frameFile(line);\r\n if (file && !out.includes(file)) out.push(file);\r\n }\r\n return out;\r\n}\r\n\r\n/** Parse the registry entries not seen yet: each one's top frame is the file that registered it. */\r\nfunction refresh(): void {\r\n const entries = registry();\r\n if (!entries) return;\r\n for (const stack in entries) {\r\n if (parsed.has(stack)) continue;\r\n parsed.add(stack);\r\n const id = entries[stack];\r\n if (typeof id !== 'string') continue;\r\n for (const line of stack.split('\\n')) {\r\n const file = frameFile(line);\r\n if (file) {\r\n files.set(file, id);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * The debug IDs of the files in `stack` that registered one, or undefined when none did (no\r\n * injected build, or only third-party frames).\r\n */\r\nexport function debugIdsFor(stack: string | undefined): Record<string, string> | undefined {\r\n if (!stack) return undefined;\r\n try {\r\n refresh();\r\n if (files.size === 0) return undefined;\r\n let out: Record<string, string> | undefined;\r\n for (const file of stackFiles(stack)) {\r\n const id = files.get(file);\r\n if (id) (out ??= {})[file] = id;\r\n }\r\n return out;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/** `{ 'zharp.debug_ids': '<json>' }` for `stack`, or an empty object. Spread it into an error's attributes. */\r\nexport function debugIdAttributes(stack: string | undefined): Record<string, string> {\r\n const ids = debugIdsFor(stack);\r\n return ids ? { [DEBUG_IDS_ATTRIBUTE]: JSON.stringify(ids) } : {};\r\n}\r\n\r\n/** For tests: forget everything parsed. */\r\nexport function resetDebugIdCache(): void {\r\n files.clear();\r\n parsed.clear();\r\n}\r\n","/**\r\n * `zharp.debug_ids` on errors that do not come through Zharp's own API: exceptions recorded on\r\n * spans by the instrumentations (`span.recordException`), and error logs from the pino and\r\n * winston bridges. Zharp's own error logs already have it (see errors.ts); these processors only\r\n * fill it in where a stack is present and the attribute is not.\r\n */\r\nimport type { Context } from '@opentelemetry/api';\r\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace';\r\nimport type { LogRecordProcessor, ReadWriteLogRecord } from '@opentelemetry/sdk-logs';\r\nimport { DEBUG_IDS_ATTRIBUTE, debugIdsFor } from '@zharp/internal/debug-ids';\r\n\r\nconst STACK = 'exception.stacktrace';\r\n\r\nexport class DebugIdSpanProcessor implements SpanProcessor {\r\n onStart(_span: Span, _parentContext: Context): void {}\r\n\r\n /** Exception events are added while the span runs; by its end they are all there. */\r\n onEnd(span: ReadableSpan): void {\r\n try {\r\n for (const event of span.events) {\r\n const attributes = event.attributes as Record<string, unknown> | undefined;\r\n if (event.name !== 'exception' || !attributes || attributes[DEBUG_IDS_ATTRIBUTE] !== undefined) continue;\r\n const stack = attributes[STACK];\r\n const ids = typeof stack === 'string' ? debugIdsFor(stack) : undefined;\r\n if (ids) attributes[DEBUG_IDS_ATTRIBUTE] = JSON.stringify(ids);\r\n }\r\n } catch {\r\n // Never let telemetry break a request.\r\n }\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n\r\nexport class DebugIdLogProcessor implements LogRecordProcessor {\r\n onEmit(record: ReadWriteLogRecord, _ctx?: Context): void {\r\n try {\r\n const attributes = record.attributes as Record<string, unknown>;\r\n const stack = attributes[STACK];\r\n if (typeof stack !== 'string' || attributes[DEBUG_IDS_ATTRIBUTE] !== undefined) return;\r\n const ids = debugIdsFor(stack);\r\n if (ids) record.setAttribute(DEBUG_IDS_ATTRIBUTE, JSON.stringify(ids));\r\n } catch {\r\n // As above.\r\n }\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n","/**\r\n * Errors as Zharp reads them: a log record of severity ERROR or FATAL carrying\r\n * `exception.type`, `exception.message` and `exception.stacktrace`, plus `zharp.handled`.\r\n *\r\n * A log rather than a span event because an error does not always happen inside a span (a\r\n * crash at startup, a timer callback), and one shape for both keeps the count honest: the server\r\n * makes an error event from either, so sending both would count every error twice.\r\n */\r\nimport { inspect } from 'node:util';\r\nimport { debugIdAttributes } from '@zharp/internal/debug-ids';\r\n\r\n/** OTLP severity numbers. */\r\nexport const SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 } as const;\r\nexport type Level = keyof typeof SEVERITY;\r\n\r\n/** Whatever was thrown, as an Error — a rejection with a string or an object is still worth a stack. */\r\nexport function asError(value: unknown): Error {\r\n if (value instanceof Error) return value;\r\n if (value && typeof value === 'object' && typeof (value as any).message === 'string') {\r\n const error = new Error((value as any).message);\r\n error.name = typeof (value as any).name === 'string' ? (value as any).name : 'Error';\r\n if (typeof (value as any).stack === 'string') error.stack = (value as any).stack;\r\n return error;\r\n }\r\n const text = typeof value === 'string' ? value : inspect(value, { depth: 3, breakLength: Infinity });\r\n const error = new Error(`Non-Error thrown: ${text}`);\r\n // The stack points here, not at the throw — but it is the only one there is.\r\n return error;\r\n}\r\n\r\n/** The name an error is grouped under: `TypeError`, or a custom class's own name. */\r\nfunction typeOf(error: Error): string {\r\n const name = error.name && error.name !== 'Error' ? error.name : error.constructor?.name;\r\n return name || 'Error';\r\n}\r\n\r\n/** The `exception.*` attributes for `error`. The stack keeps its first `Type: message` line. */\r\nexport function exceptionAttributes(error: Error, handled: boolean): Record<string, string> {\r\n const type = typeOf(error);\r\n const message = error.message || '';\r\n let stack = typeof error.stack === 'string' && error.stack ? error.stack : `${type}: ${message}`;\r\n // A cause is part of what went wrong; Node prints it, so the stack shown in Zharp does too.\r\n const cause = (error as { cause?: unknown }).cause;\r\n if (cause instanceof Error && cause.stack) stack += `\\nCaused by: ${cause.stack}`;\r\n return {\r\n 'exception.type': type,\r\n 'exception.message': message,\r\n 'exception.stacktrace': stack,\r\n 'zharp.handled': handled ? 'true' : 'false',\r\n ...debugIdAttributes(stack),\r\n };\r\n}\r\n","/** Sent as `telemetry.sdk.version`. Bumped with package.json. */\nexport const VERSION = '0.3.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cA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AA,EAA2B;AAAA,EAA3B;AAAA,EAE7B,SAAe;AAAA,EAAC;AAAA,EAEhB,QAAQ,SAAkB,SAAkB,QAAgC;AAC1E,WAAO,KAAK,MAAM,QAAQ,SAAS,SAAS,MAAM;AAAA,EACpD;AAAA,EAEA,SAAmB;AACjB,WAAO,CAAC;AAAA,EACV;AACF;;;AF5iBA,IAAM,IAAI;AACH,IAAM,QAAmB,EAAE,mBAAmB,EAAE,iBAAiB,IAAI,UAAU;AACtF,IAAO,gBAAQ;","names":["import_api","depth","parsed","typeOf","parsed","otelContext","import_api","import_api","LEVELS","parsed","otelContext","g","import_node_util","error","g","registerLoader"]}
|