@open-mercato/telemetry 0.10.1-develop.8259.1.382cb7589a → 0.10.1-develop.8271.1.346e524319

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.
@@ -1,2 +1,2 @@
1
- [build:telemetry] found 31 entry points
1
+ [build:telemetry] found 32 entry points
2
2
  [build:telemetry] built successfully
package/README.md CHANGED
@@ -399,6 +399,13 @@ consumer.
399
399
  fields, span attributes, and metric labels.
400
400
  - Postgres parameter-value capture is locked off with
401
401
  `enhancedDatabaseReporting: false`.
402
+ - Postgres statement text (`db.query.text` / `db.statement`) keeps the query
403
+ shape only. MikroORM inlines parameter values into the SQL before it reaches
404
+ `pg`, so a pg `requestHook` replaces every string, numeric and boolean
405
+ literal with `?` and drops comments. A statement that cannot be tokenized is
406
+ exported as `[redacted]` rather than as-is.
407
+ - Not yet covered: the error message of a failed query (span status and
408
+ exception event) can still quote a value, e.g. a duplicate-key detail.
402
409
  - Metric labels must remain low-cardinality and must never contain tenant,
403
410
  organization, or user IDs.
404
411
 
@@ -26,6 +26,7 @@ import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";
26
26
  import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
27
27
  import { PgInstrumentation } from "@opentelemetry/instrumentation-pg";
28
28
  import { UndiciInstrumentation } from "@opentelemetry/instrumentation-undici";
29
+ import { REDACTED_SQL_STATEMENT, sanitizeSqlStatement } from "./sanitize-sql.js";
29
30
  import { readTelemetryEnv } from "../env.js";
30
31
  import { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from "../trace-headers.js";
31
32
  import { redactAttributes, redactPii } from "../facade/redact.js";
@@ -124,7 +125,15 @@ class OtelSpan {
124
125
  this.span.end();
125
126
  }
126
127
  }
127
- const PG_INSTRUMENTATION_OPTIONS = { enhancedDatabaseReporting: false };
128
+ const PG_STATEMENT_ATTRIBUTE_KEYS = ["db.query.text", "db.statement"];
129
+ const PG_INSTRUMENTATION_OPTIONS = {
130
+ enhancedDatabaseReporting: false,
131
+ requestHook: (span, { query }) => {
132
+ if (typeof query.text !== "string" || query.text.length === 0) return;
133
+ const statement = sanitizeSqlStatement(query.text) ?? REDACTED_SQL_STATEMENT;
134
+ for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) span.setAttribute(key, statement);
135
+ }
136
+ };
128
137
  const SECONDS_HISTOGRAM_BUCKETS = [
129
138
  1e-3,
130
139
  5e-3,
@@ -251,6 +260,7 @@ class OtlpProvider {
251
260
  export {
252
261
  OtlpProvider,
253
262
  PG_INSTRUMENTATION_OPTIONS,
263
+ PG_STATEMENT_ATTRIBUTE_KEYS,
254
264
  SECONDS_HISTOGRAM_BUCKETS
255
265
  };
256
266
  //# sourceMappingURL=otlp-provider.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/provider/otlp-provider.ts"],
4
- "sourcesContent": ["/**\n * The ONLY file in this package that imports `@opentelemetry/*`. Loaded via\n * dynamic `import()` from `init.ts` (so the heavy SDK never loads when telemetry\n * is off), and the OTEL packages live in `optionalDependencies`.\n *\n * Serves any OTLP backend \u2014 the endpoint + headers come from the standard\n * `OTEL_EXPORTER_OTLP_*` env vars, read by the exporters directly.\n */\nimport {\n trace,\n metrics,\n context,\n isSpanContextValid,\n defaultTextMapGetter,\n defaultTextMapSetter,\n ROOT_CONTEXT,\n SpanStatusCode,\n SpanKind as OtelSpanKind,\n type Link,\n type Span as OtelApiSpan,\n type SpanOptions as OtelSpanOptions,\n type TextMapPropagator,\n type Counter,\n type Histogram,\n type Gauge,\n type MetricOptions,\n} from '@opentelemetry/api'\nimport { W3CTraceContextPropagator } from '@opentelemetry/core'\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs'\nimport { NodeSDK } from '@opentelemetry/sdk-node'\nimport type { Instrumentation } from '@opentelemetry/instrumentation'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'\nimport {\n BatchSpanProcessor,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n type SpanProcessor,\n} from '@opentelemetry/sdk-trace-node'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'\nimport { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { PeriodicExportingMetricReader, type IMetricReader } from '@opentelemetry/sdk-metrics'\nimport { PgInstrumentation } from '@opentelemetry/instrumentation-pg'\nimport { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici'\n\nimport type {\n Attributes,\n AttributeValue,\n LogLevel,\n LogRecord,\n MetricPoint,\n Span,\n SpanKind,\n SpanOptions,\n TelemetryProvider,\n TelemetrySignal,\n TraceCarrier,\n TraceContext,\n} from '../types'\nimport { readTelemetryEnv } from '../env'\nimport { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from '../trace-headers'\nimport { redactAttributes, redactPii } from '../facade/redact'\nimport { serializeError } from '../facade/serialize'\nimport { runSpan } from './run-span'\n\nconst TRACER_NAME = 'open-mercato'\n\n/**\n * Queue/event trace propagation rides a dedicated W3C propagator on the payload\n * `_trace` carrier \u2014 deliberately NOT the global propagator below.\n */\nconst queuePropagator = new W3CTraceContextPropagator()\n\nconst W3C_TRACEPARENT = 'traceparent'\nconst W3C_TRACESTATE = 'tracestate'\n// Backup headers that mirror the W3C context but a proxy/LB won't rewrite.\nconst BACKUP_TRACEPARENT = BACKUP_TRACEPARENT_HEADER\nconst BACKUP_TRACESTATE = BACKUP_TRACESTATE_HEADER\n\n/**\n * Global propagator: standard W3C plus a backup copy\n * (`x-original-traceparent`), with explicit inbound trust.\n *\n * The problem: a load balancer (e.g. GCP's) reads the inbound `traceparent`,\n * creates its own span, and **rewrites** `traceparent` to point at that span \u2014\n * which our backend never sees. With plain W3C extraction every request becomes a\n * child of that unexported span: no request is a root, and root-span / trace-group\n * views come up empty.\n *\n * The fix (the industry \"backup header\" pattern): on inject we also write\n * `x-original-traceparent`, which the LB leaves untouched. A backup header is\n * still caller-controlled at an HTTP boundary, so its mere\n * presence is not proof that one of our services created it. Extraction ignores\n * both standard and backup headers by default.\n *\n * `TELEMETRY_TRUST_INBOUND_TRACE=true` enables both extraction paths for a\n * deployment behind a trusted upstream. Our dedicated queue/event carrier is\n * unaffected \u2014 it uses `queuePropagator` directly, not this global one.\n */\nconst backupHeaderPropagator: TextMapPropagator = {\n inject(ctx, carrier, setter) {\n // Inject into a plain temp carrier so we can mirror the values regardless of\n // the real carrier's setter shape, then copy both standard + backup headers.\n const tmp: Record<string, string> = {}\n queuePropagator.inject(ctx, tmp, defaultTextMapSetter)\n for (const [key, value] of Object.entries(tmp)) setter.set(carrier, key, value)\n if (tmp[W3C_TRACEPARENT]) setter.set(carrier, BACKUP_TRACEPARENT, tmp[W3C_TRACEPARENT])\n if (tmp[W3C_TRACESTATE]) setter.set(carrier, BACKUP_TRACESTATE, tmp[W3C_TRACESTATE])\n },\n extract(ctx, carrier, getter) {\n // Both the standard and backup headers are caller-controlled at an HTTP\n // boundary. Trust neither unless the deployment explicitly opts in.\n if (!readTelemetryEnv().trustInboundTrace) return ctx\n const first = (value: string | string[] | undefined): string | undefined =>\n Array.isArray(value) ? value[0] : value\n const backupTraceparent = first(getter.get(carrier, BACKUP_TRACEPARENT))\n if (backupTraceparent) {\n const backupCarrier: Record<string, string> = { [W3C_TRACEPARENT]: backupTraceparent }\n const backupTracestate = first(getter.get(carrier, BACKUP_TRACESTATE))\n if (backupTracestate) backupCarrier[W3C_TRACESTATE] = backupTracestate\n return queuePropagator.extract(ctx, backupCarrier, defaultTextMapGetter)\n }\n return queuePropagator.extract(ctx, carrier, getter)\n },\n fields: () => [...queuePropagator.fields(), BACKUP_TRACEPARENT, BACKUP_TRACESTATE],\n}\n\nfunction cleanAttributes(attributes?: Attributes): Record<string, AttributeValue> {\n const out: Record<string, AttributeValue> = {}\n if (!attributes) return out\n for (const [key, value] of Object.entries(redactAttributes(attributes))) {\n if (value !== undefined) out[key] = value\n }\n return out\n}\n\nconst SPAN_KIND: Record<SpanKind, OtelSpanKind> = {\n internal: OtelSpanKind.INTERNAL,\n server: OtelSpanKind.SERVER,\n client: OtelSpanKind.CLIENT,\n producer: OtelSpanKind.PRODUCER,\n consumer: OtelSpanKind.CONSUMER,\n}\n\n/**\n * Resolve `links` carriers to span contexts. Extraction runs against\n * `ROOT_CONTEXT`, never the active one \u2014 otherwise an empty carrier would\n * silently link a span to its own ambient parent instead of yielding no link.\n */\nfunction spanLinks(carriers?: TraceCarrier[]): Link[] | undefined {\n if (!carriers?.length) return undefined\n const links: Link[] = []\n for (const carrier of carriers) {\n const linked = trace.getSpanContext(queuePropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter))\n if (linked && isSpanContextValid(linked)) links.push({ context: linked })\n }\n return links.length ? links : undefined\n}\n\n/**\n * Translate the vendor-neutral options to OTEL's. `root: true` makes OTEL drop\n * the parent from the context it samples against, so the span starts a new trace\n * and the `ParentBasedSampler` falls through to its ratio-based root sampler.\n */\nfunction toOtelSpanOptions(options: SpanOptions): OtelSpanOptions {\n return {\n kind: options.kind ? SPAN_KIND[options.kind] : undefined,\n attributes: cleanAttributes(options.attributes),\n root: options.root,\n links: spanLinks(options.links),\n }\n}\n\nconst SEVERITY: Record<LogLevel, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n}\n\n/** Adapts an OTEL span to the vendor-neutral `Span` interface. */\nclass OtelSpan implements Span {\n constructor(private readonly span: OtelApiSpan) {}\n setAttribute(key: string, value: AttributeValue): void {\n const redacted = cleanAttributes({ [key]: value })[key]\n if (redacted !== undefined) this.span.setAttribute(key, redacted)\n }\n setAttributes(attributes: Attributes): void {\n this.span.setAttributes(cleanAttributes(attributes))\n }\n updateName(name: string): void {\n this.span.updateName(name)\n }\n recordException(error: unknown): void {\n // Redact message + stack before they leave the process (Privacy): the auto\n // record-on-throw path (run-span) and reportError both pass raw errors here.\n this.span.recordException(serializeError(error))\n }\n setStatus(status: 'ok' | 'error', message?: string): void {\n this.span.setStatus({\n code: status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n message: message ? redactPii(message) : undefined,\n })\n }\n end(): void {\n this.span.end()\n }\n}\n\n/**\n * Test seam: override the SDK's exporters/instrumentations so tests can use\n * in-memory exporters (deterministic, no network) instead of the OTLP defaults.\n * Production passes nothing \u2014 the OTLP defaults apply.\n */\nexport type OtlpProviderOptions = {\n spanProcessors?: SpanProcessor[]\n logRecordProcessors?: LogRecordProcessor[]\n metricReaders?: IMetricReader[]\n instrumentations?: Instrumentation[]\n}\n\n/**\n * PII guard (telemetry spec Privacy / R12). The single source of truth for pg\n * instrumentation config: `enhancedDatabaseReporting: false` means bound SQL\n * parameter VALUES are NOT captured \u2014 only the statement shape ($1, $2). User\n * data lives in those params, so this must never be flipped on. Asserted by a\n * regression test.\n */\nexport const PG_INSTRUMENTATION_OPTIONS = { enhancedDatabaseReporting: false } as const\n\n/**\n * Bucket boundaries for every histogram recorded in seconds. Without explicit\n * advice the SDK falls back to millisecond-scaled defaults (0, 5, 10 \u2026 10000),\n * which puts every realistic latency in the first bucket and leaves percentiles\n * uncomputable. A superset of the semconv HTTP-duration advice, plus a 1 ms\n * bucket for sub-millisecond pool acquisitions.\n */\nexport const SECONDS_HISTOGRAM_BUCKETS: readonly number[] = [\n 0.001, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10,\n]\n\nfunction histogramOptions(unit: string | undefined): MetricOptions | undefined {\n if (unit !== 's') return unit ? { unit } : undefined\n return { unit, advice: { explicitBucketBoundaries: [...SECONDS_HISTOGRAM_BUCKETS] } }\n}\n\nexport class OtlpProvider implements TelemetryProvider {\n /** The configured backend name (signoz | newrelic | otlp) \u2014 all OTLP, vendor differs only by endpoint. */\n readonly name: string\n readonly supports: readonly TelemetrySignal[] = ['traces', 'metrics', 'logs', 'errors']\n\n private sdk: NodeSDK | undefined\n private readonly instruments = new Map<string, Counter | Histogram | Gauge>()\n\n constructor(private readonly options: OtlpProviderOptions = {}, name = 'otlp') {\n this.name = name\n }\n\n async start(): Promise<void> {\n if (this.sdk) return\n const env = readTelemetryEnv()\n\n this.sdk = new NodeSDK({\n resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: env.serviceName }),\n // Global propagation roots requests by default. Both standard and backup\n // inbound headers are honored only when TELEMETRY_TRUST_INBOUND_TRACE is\n // explicitly enabled behind trusted infrastructure.\n textMapPropagator: backupHeaderPropagator,\n // Parent-based so child spans follow the trace's sampling decision; root\n // spans sample at the configured ratio.\n sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(env.samplingRatio) }),\n spanProcessors: this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())],\n logRecordProcessors: this.options.logRecordProcessors ?? [\n new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() }),\n ],\n metricReaders: this.options.metricReaders ?? [\n new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }),\n ],\n instrumentations: this.options.instrumentations ?? [\n new PgInstrumentation(PG_INSTRUMENTATION_OPTIONS),\n new UndiciInstrumentation(),\n ],\n })\n this.sdk.start()\n }\n\n async shutdown(): Promise<void> {\n if (!this.sdk) return\n await this.sdk.shutdown()\n this.sdk = undefined\n }\n\n runInSpan<T>(name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const tracer = trace.getTracer(TRACER_NAME)\n return tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n )\n }\n\n activeSpan(): Span | undefined {\n const active = trace.getActiveSpan()\n return active ? new OtelSpan(active) : undefined\n }\n\n activeTraceContext(): TraceContext | undefined {\n const ctx = trace.getActiveSpan()?.spanContext()\n if (!ctx || !isSpanContextValid(ctx)) return undefined\n return { traceId: ctx.traceId, spanId: ctx.spanId }\n }\n\n inject(carrier: TraceCarrier): void {\n queuePropagator.inject(context.active(), carrier, defaultTextMapSetter)\n }\n\n runInRemoteSpan<T>(carrier: TraceCarrier, name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const parent = queuePropagator.extract(context.active(), carrier, defaultTextMapGetter)\n const tracer = trace.getTracer(TRACER_NAME)\n return context.with(parent, () =>\n tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n ),\n )\n }\n\n emitLog(record: LogRecord): void {\n const attributes: Record<string, AttributeValue> = cleanAttributes(record.attributes)\n if (record.error) {\n attributes['exception.type'] = redactPii(record.error.name)\n attributes['exception.message'] = redactPii(record.error.message)\n if (record.error.stack) attributes['exception.stacktrace'] = redactPii(record.error.stack)\n }\n logs.getLogger(TRACER_NAME).emit({\n severityNumber: SEVERITY[record.level],\n severityText: record.level,\n body: redactPii(record.message),\n attributes,\n })\n }\n\n recordMetric(point: MetricPoint): void {\n const labels = cleanAttributes(point.labels)\n const instrument = this.getInstrument(point)\n if (point.kind === 'counter') (instrument as Counter).add(point.value, labels)\n else (instrument as Histogram | Gauge).record(point.value, labels)\n }\n\n private getInstrument(point: MetricPoint): Counter | Histogram | Gauge {\n const key = `${point.kind}:${point.name}`\n let instrument = this.instruments.get(key)\n if (!instrument) {\n const meter = metrics.getMeter(TRACER_NAME)\n const opts = point.unit ? { unit: point.unit } : undefined\n instrument =\n point.kind === 'counter'\n ? meter.createCounter(point.name, opts)\n : point.kind === 'histogram'\n ? meter.createHistogram(point.name, histogramOptions(point.unit))\n : meter.createGauge(point.name, opts)\n this.instruments.set(key, instrument)\n }\n return instrument\n }\n}\n"],
5
- "mappings": "AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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AA,MACrC,cAAc,OAAO;AAAA,MACrB,MAAM,UAAU,OAAO,OAAO;AAAA,MAC9B;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,aAAa,OAA0B;AACrC,UAAM,SAAS,gBAAgB,MAAM,MAAM;AAC3C,UAAM,aAAa,KAAK,cAAc,KAAK;AAC3C,QAAI,MAAM,SAAS,UAAW,CAAC,WAAuB,IAAI,MAAM,OAAO,MAAM;AAAA,QACxE,CAAC,WAAiC,OAAO,MAAM,OAAO,MAAM;AAAA,EACnE;AAAA,EAEQ,cAAc,OAAiD;AACrE,UAAM,MAAM,GAAG,MAAM,IAAI,IAAI,MAAM,IAAI;AACvC,QAAI,aAAa,KAAK,YAAY,IAAI,GAAG;AACzC,QAAI,CAAC,YAAY;AACf,YAAM,QAAQ,QAAQ,SAAS,WAAW;AAC1C,YAAM,OAAO,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI;AACjD,mBACE,MAAM,SAAS,YACX,MAAM,cAAc,MAAM,MAAM,IAAI,IACpC,MAAM,SAAS,cACb,MAAM,gBAAgB,MAAM,MAAM,iBAAiB,MAAM,IAAI,CAAC,IAC9D,MAAM,YAAY,MAAM,MAAM,IAAI;AAC1C,WAAK,YAAY,IAAI,KAAK,UAAU;AAAA,IACtC;AACA,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["/**\n * The ONLY file in this package that imports `@opentelemetry/*`. Loaded via\n * dynamic `import()` from `init.ts` (so the heavy SDK never loads when telemetry\n * is off), and the OTEL packages live in `optionalDependencies`.\n *\n * Serves any OTLP backend \u2014 the endpoint + headers come from the standard\n * `OTEL_EXPORTER_OTLP_*` env vars, read by the exporters directly.\n */\nimport {\n trace,\n metrics,\n context,\n isSpanContextValid,\n defaultTextMapGetter,\n defaultTextMapSetter,\n ROOT_CONTEXT,\n SpanStatusCode,\n SpanKind as OtelSpanKind,\n type Link,\n type Span as OtelApiSpan,\n type SpanOptions as OtelSpanOptions,\n type TextMapPropagator,\n type Counter,\n type Histogram,\n type Gauge,\n type MetricOptions,\n} from '@opentelemetry/api'\nimport { W3CTraceContextPropagator } from '@opentelemetry/core'\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs'\nimport { NodeSDK } from '@opentelemetry/sdk-node'\nimport type { Instrumentation } from '@opentelemetry/instrumentation'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'\nimport {\n BatchSpanProcessor,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n type SpanProcessor,\n} from '@opentelemetry/sdk-trace-node'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'\nimport { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { PeriodicExportingMetricReader, type IMetricReader } from '@opentelemetry/sdk-metrics'\nimport { PgInstrumentation, type PgInstrumentationConfig } from '@opentelemetry/instrumentation-pg'\nimport { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici'\n\nimport { REDACTED_SQL_STATEMENT, sanitizeSqlStatement } from './sanitize-sql'\nimport type {\n Attributes,\n AttributeValue,\n LogLevel,\n LogRecord,\n MetricPoint,\n Span,\n SpanKind,\n SpanOptions,\n TelemetryProvider,\n TelemetrySignal,\n TraceCarrier,\n TraceContext,\n} from '../types'\nimport { readTelemetryEnv } from '../env'\nimport { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from '../trace-headers'\nimport { redactAttributes, redactPii } from '../facade/redact'\nimport { serializeError } from '../facade/serialize'\nimport { runSpan } from './run-span'\n\nconst TRACER_NAME = 'open-mercato'\n\n/**\n * Queue/event trace propagation rides a dedicated W3C propagator on the payload\n * `_trace` carrier \u2014 deliberately NOT the global propagator below.\n */\nconst queuePropagator = new W3CTraceContextPropagator()\n\nconst W3C_TRACEPARENT = 'traceparent'\nconst W3C_TRACESTATE = 'tracestate'\n// Backup headers that mirror the W3C context but a proxy/LB won't rewrite.\nconst BACKUP_TRACEPARENT = BACKUP_TRACEPARENT_HEADER\nconst BACKUP_TRACESTATE = BACKUP_TRACESTATE_HEADER\n\n/**\n * Global propagator: standard W3C plus a backup copy\n * (`x-original-traceparent`), with explicit inbound trust.\n *\n * The problem: a load balancer (e.g. GCP's) reads the inbound `traceparent`,\n * creates its own span, and **rewrites** `traceparent` to point at that span \u2014\n * which our backend never sees. With plain W3C extraction every request becomes a\n * child of that unexported span: no request is a root, and root-span / trace-group\n * views come up empty.\n *\n * The fix (the industry \"backup header\" pattern): on inject we also write\n * `x-original-traceparent`, which the LB leaves untouched. A backup header is\n * still caller-controlled at an HTTP boundary, so its mere\n * presence is not proof that one of our services created it. Extraction ignores\n * both standard and backup headers by default.\n *\n * `TELEMETRY_TRUST_INBOUND_TRACE=true` enables both extraction paths for a\n * deployment behind a trusted upstream. Our dedicated queue/event carrier is\n * unaffected \u2014 it uses `queuePropagator` directly, not this global one.\n */\nconst backupHeaderPropagator: TextMapPropagator = {\n inject(ctx, carrier, setter) {\n // Inject into a plain temp carrier so we can mirror the values regardless of\n // the real carrier's setter shape, then copy both standard + backup headers.\n const tmp: Record<string, string> = {}\n queuePropagator.inject(ctx, tmp, defaultTextMapSetter)\n for (const [key, value] of Object.entries(tmp)) setter.set(carrier, key, value)\n if (tmp[W3C_TRACEPARENT]) setter.set(carrier, BACKUP_TRACEPARENT, tmp[W3C_TRACEPARENT])\n if (tmp[W3C_TRACESTATE]) setter.set(carrier, BACKUP_TRACESTATE, tmp[W3C_TRACESTATE])\n },\n extract(ctx, carrier, getter) {\n // Both the standard and backup headers are caller-controlled at an HTTP\n // boundary. Trust neither unless the deployment explicitly opts in.\n if (!readTelemetryEnv().trustInboundTrace) return ctx\n const first = (value: string | string[] | undefined): string | undefined =>\n Array.isArray(value) ? value[0] : value\n const backupTraceparent = first(getter.get(carrier, BACKUP_TRACEPARENT))\n if (backupTraceparent) {\n const backupCarrier: Record<string, string> = { [W3C_TRACEPARENT]: backupTraceparent }\n const backupTracestate = first(getter.get(carrier, BACKUP_TRACESTATE))\n if (backupTracestate) backupCarrier[W3C_TRACESTATE] = backupTracestate\n return queuePropagator.extract(ctx, backupCarrier, defaultTextMapGetter)\n }\n return queuePropagator.extract(ctx, carrier, getter)\n },\n fields: () => [...queuePropagator.fields(), BACKUP_TRACEPARENT, BACKUP_TRACESTATE],\n}\n\nfunction cleanAttributes(attributes?: Attributes): Record<string, AttributeValue> {\n const out: Record<string, AttributeValue> = {}\n if (!attributes) return out\n for (const [key, value] of Object.entries(redactAttributes(attributes))) {\n if (value !== undefined) out[key] = value\n }\n return out\n}\n\nconst SPAN_KIND: Record<SpanKind, OtelSpanKind> = {\n internal: OtelSpanKind.INTERNAL,\n server: OtelSpanKind.SERVER,\n client: OtelSpanKind.CLIENT,\n producer: OtelSpanKind.PRODUCER,\n consumer: OtelSpanKind.CONSUMER,\n}\n\n/**\n * Resolve `links` carriers to span contexts. Extraction runs against\n * `ROOT_CONTEXT`, never the active one \u2014 otherwise an empty carrier would\n * silently link a span to its own ambient parent instead of yielding no link.\n */\nfunction spanLinks(carriers?: TraceCarrier[]): Link[] | undefined {\n if (!carriers?.length) return undefined\n const links: Link[] = []\n for (const carrier of carriers) {\n const linked = trace.getSpanContext(queuePropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter))\n if (linked && isSpanContextValid(linked)) links.push({ context: linked })\n }\n return links.length ? links : undefined\n}\n\n/**\n * Translate the vendor-neutral options to OTEL's. `root: true` makes OTEL drop\n * the parent from the context it samples against, so the span starts a new trace\n * and the `ParentBasedSampler` falls through to its ratio-based root sampler.\n */\nfunction toOtelSpanOptions(options: SpanOptions): OtelSpanOptions {\n return {\n kind: options.kind ? SPAN_KIND[options.kind] : undefined,\n attributes: cleanAttributes(options.attributes),\n root: options.root,\n links: spanLinks(options.links),\n }\n}\n\nconst SEVERITY: Record<LogLevel, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n}\n\n/** Adapts an OTEL span to the vendor-neutral `Span` interface. */\nclass OtelSpan implements Span {\n constructor(private readonly span: OtelApiSpan) {}\n setAttribute(key: string, value: AttributeValue): void {\n const redacted = cleanAttributes({ [key]: value })[key]\n if (redacted !== undefined) this.span.setAttribute(key, redacted)\n }\n setAttributes(attributes: Attributes): void {\n this.span.setAttributes(cleanAttributes(attributes))\n }\n updateName(name: string): void {\n this.span.updateName(name)\n }\n recordException(error: unknown): void {\n // Redact message + stack before they leave the process (Privacy): the auto\n // record-on-throw path (run-span) and reportError both pass raw errors here.\n this.span.recordException(serializeError(error))\n }\n setStatus(status: 'ok' | 'error', message?: string): void {\n this.span.setStatus({\n code: status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n message: message ? redactPii(message) : undefined,\n })\n }\n end(): void {\n this.span.end()\n }\n}\n\n/**\n * Test seam: override the SDK's exporters/instrumentations so tests can use\n * in-memory exporters (deterministic, no network) instead of the OTLP defaults.\n * Production passes nothing \u2014 the OTLP defaults apply.\n */\nexport type OtlpProviderOptions = {\n spanProcessors?: SpanProcessor[]\n logRecordProcessors?: LogRecordProcessor[]\n metricReaders?: IMetricReader[]\n instrumentations?: Instrumentation[]\n}\n\n/**\n * Statement attribute keys written by `@opentelemetry/instrumentation-pg`:\n * `db.query.text` (stable semconv, 0.73+) and `db.statement` (older releases).\n */\nexport const PG_STATEMENT_ATTRIBUTE_KEYS = ['db.query.text', 'db.statement'] as const\n\n/**\n * PII guard (telemetry spec Privacy / R12). The single source of truth for pg\n * instrumentation config. Two layers, both asserted by regression tests:\n *\n * - `enhancedDatabaseReporting: false` keeps the bound parameter VALUES array\n * off the span. This must never be flipped on.\n * - `requestHook` rewrites the statement text with every literal replaced by\n * `?`. MikroORM inlines parameters into the SQL before it reaches `pg`, so\n * without this the statement itself carries record content and ids. When the\n * text cannot be tokenized the hook fails closed with a fixed marker.\n */\nexport const PG_INSTRUMENTATION_OPTIONS = {\n enhancedDatabaseReporting: false,\n requestHook: (span, { query }) => {\n if (typeof query.text !== 'string' || query.text.length === 0) return\n const statement = sanitizeSqlStatement(query.text) ?? REDACTED_SQL_STATEMENT\n for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) span.setAttribute(key, statement)\n },\n} as const satisfies PgInstrumentationConfig\n\n/**\n * Bucket boundaries for every histogram recorded in seconds. Without explicit\n * advice the SDK falls back to millisecond-scaled defaults (0, 5, 10 \u2026 10000),\n * which puts every realistic latency in the first bucket and leaves percentiles\n * uncomputable. A superset of the semconv HTTP-duration advice, plus a 1 ms\n * bucket for sub-millisecond pool acquisitions.\n */\nexport const SECONDS_HISTOGRAM_BUCKETS: readonly number[] = [\n 0.001, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10,\n]\n\nfunction histogramOptions(unit: string | undefined): MetricOptions | undefined {\n if (unit !== 's') return unit ? { unit } : undefined\n return { unit, advice: { explicitBucketBoundaries: [...SECONDS_HISTOGRAM_BUCKETS] } }\n}\n\nexport class OtlpProvider implements TelemetryProvider {\n /** The configured backend name (signoz | newrelic | otlp) \u2014 all OTLP, vendor differs only by endpoint. */\n readonly name: string\n readonly supports: readonly TelemetrySignal[] = ['traces', 'metrics', 'logs', 'errors']\n\n private sdk: NodeSDK | undefined\n private readonly instruments = new Map<string, Counter | Histogram | Gauge>()\n\n constructor(private readonly options: OtlpProviderOptions = {}, name = 'otlp') {\n this.name = name\n }\n\n async start(): Promise<void> {\n if (this.sdk) return\n const env = readTelemetryEnv()\n\n this.sdk = new NodeSDK({\n resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: env.serviceName }),\n // Global propagation roots requests by default. Both standard and backup\n // inbound headers are honored only when TELEMETRY_TRUST_INBOUND_TRACE is\n // explicitly enabled behind trusted infrastructure.\n textMapPropagator: backupHeaderPropagator,\n // Parent-based so child spans follow the trace's sampling decision; root\n // spans sample at the configured ratio.\n sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(env.samplingRatio) }),\n spanProcessors: this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())],\n logRecordProcessors: this.options.logRecordProcessors ?? [\n new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() }),\n ],\n metricReaders: this.options.metricReaders ?? [\n new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }),\n ],\n instrumentations: this.options.instrumentations ?? [\n new PgInstrumentation(PG_INSTRUMENTATION_OPTIONS),\n new UndiciInstrumentation(),\n ],\n })\n this.sdk.start()\n }\n\n async shutdown(): Promise<void> {\n if (!this.sdk) return\n await this.sdk.shutdown()\n this.sdk = undefined\n }\n\n runInSpan<T>(name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const tracer = trace.getTracer(TRACER_NAME)\n return tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n )\n }\n\n activeSpan(): Span | undefined {\n const active = trace.getActiveSpan()\n return active ? new OtelSpan(active) : undefined\n }\n\n activeTraceContext(): TraceContext | undefined {\n const ctx = trace.getActiveSpan()?.spanContext()\n if (!ctx || !isSpanContextValid(ctx)) return undefined\n return { traceId: ctx.traceId, spanId: ctx.spanId }\n }\n\n inject(carrier: TraceCarrier): void {\n queuePropagator.inject(context.active(), carrier, defaultTextMapSetter)\n }\n\n runInRemoteSpan<T>(carrier: TraceCarrier, name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const parent = queuePropagator.extract(context.active(), carrier, defaultTextMapGetter)\n const tracer = trace.getTracer(TRACER_NAME)\n return context.with(parent, () =>\n tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n ),\n )\n }\n\n emitLog(record: LogRecord): void {\n const attributes: Record<string, AttributeValue> = cleanAttributes(record.attributes)\n if (record.error) {\n attributes['exception.type'] = redactPii(record.error.name)\n attributes['exception.message'] = redactPii(record.error.message)\n if (record.error.stack) attributes['exception.stacktrace'] = redactPii(record.error.stack)\n }\n logs.getLogger(TRACER_NAME).emit({\n severityNumber: SEVERITY[record.level],\n severityText: record.level,\n body: redactPii(record.message),\n attributes,\n })\n }\n\n recordMetric(point: MetricPoint): void {\n const labels = cleanAttributes(point.labels)\n const instrument = this.getInstrument(point)\n if (point.kind === 'counter') (instrument as Counter).add(point.value, labels)\n else (instrument as Histogram | Gauge).record(point.value, labels)\n }\n\n private getInstrument(point: MetricPoint): Counter | Histogram | Gauge {\n const key = `${point.kind}:${point.name}`\n let instrument = this.instruments.get(key)\n if (!instrument) {\n const meter = metrics.getMeter(TRACER_NAME)\n const opts = point.unit ? { unit: point.unit } : undefined\n instrument =\n point.kind === 'counter'\n ? meter.createCounter(point.name, opts)\n : point.kind === 'histogram'\n ? meter.createHistogram(point.name, histogramOptions(point.unit))\n : meter.createGauge(point.name, opts)\n this.instruments.set(key, instrument)\n }\n return instrument\n }\n}\n"],
5
+ "mappings": "AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,OASP;AACP,SAAS,iCAAiC;AAC1C,SAAS,MAAM,sBAAsB;AACrC,SAAS,eAAe;AAExB,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,+BAAwD;AACjE,SAAS,qCAAyD;AAClE,SAAS,yBAAuD;AAChE,SAAS,6BAA6B;AAEtC,SAAS,wBAAwB,4BAA4B;AAe7D,SAAS,wBAAwB;AACjC,SAAS,2BAA2B,gCAAgC;AACpE,SAAS,kBAAkB,iBAAiB;AAC5C,SAAS,sBAA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KAAK,cAAc,KAAK;AAC3C,QAAI,MAAM,SAAS,UAAW,CAAC,WAAuB,IAAI,MAAM,OAAO,MAAM;AAAA,QACxE,CAAC,WAAiC,OAAO,MAAM,OAAO,MAAM;AAAA,EACnE;AAAA,EAEQ,cAAc,OAAiD;AACrE,UAAM,MAAM,GAAG,MAAM,IAAI,IAAI,MAAM,IAAI;AACvC,QAAI,aAAa,KAAK,YAAY,IAAI,GAAG;AACzC,QAAI,CAAC,YAAY;AACf,YAAM,QAAQ,QAAQ,SAAS,WAAW;AAC1C,YAAM,OAAO,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI;AACjD,mBACE,MAAM,SAAS,YACX,MAAM,cAAc,MAAM,MAAM,IAAI,IACpC,MAAM,SAAS,cACb,MAAM,gBAAgB,MAAM,MAAM,iBAAiB,MAAM,IAAI,CAAC,IAC9D,MAAM,YAAY,MAAM,MAAM,IAAI;AAC1C,WAAK,YAAY,IAAI,KAAK,UAAU;AAAA,IACtC;AACA,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,145 @@
1
+ const REDACTED_SQL_STATEMENT = "[redacted]";
2
+ const LITERAL_PLACEHOLDER = "?";
3
+ const STRING_PREFIXES = /* @__PURE__ */ new Set(["e", "b", "x", "n"]);
4
+ const BOOLEAN_LITERALS = /* @__PURE__ */ new Set(["true", "false"]);
5
+ const NUMBER_PATTERN = /^(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?[A-Za-z0-9_\u0080-\uFFFF]*/;
6
+ const DOLLAR_TAG_PATTERN = /^\$(?:[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_\u0080-\uFFFF]*)?\$/;
7
+ const WORD_PATTERN = /^[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_$\u0080-\uFFFF]*/;
8
+ const WORD_START_PATTERN = /[A-Za-z_\u0080-\uFFFF]/;
9
+ const IDENTIFIER_CHAR_PATTERN = /[A-Za-z0-9_$\u0080-\uFFFF]/;
10
+ function isIdentifierChar(char) {
11
+ return char !== void 0 && IDENTIFIER_CHAR_PATTERN.test(char);
12
+ }
13
+ function skipBlockComment(text, start) {
14
+ let depth = 0;
15
+ let index = start;
16
+ while (index < text.length) {
17
+ if (text[index] === "/" && text[index + 1] === "*") {
18
+ depth += 1;
19
+ index += 2;
20
+ continue;
21
+ }
22
+ if (text[index] === "*" && text[index + 1] === "/") {
23
+ depth -= 1;
24
+ index += 2;
25
+ if (depth === 0) return index;
26
+ continue;
27
+ }
28
+ index += 1;
29
+ }
30
+ return void 0;
31
+ }
32
+ function skipQuotedString(text, start, backslashEscapes) {
33
+ let index = start + 1;
34
+ while (index < text.length) {
35
+ const char = text[index];
36
+ if (backslashEscapes && char === "\\") {
37
+ index += 2;
38
+ continue;
39
+ }
40
+ if (char === "'") {
41
+ if (text[index + 1] === "'") {
42
+ index += 2;
43
+ continue;
44
+ }
45
+ return index + 1;
46
+ }
47
+ index += 1;
48
+ }
49
+ return void 0;
50
+ }
51
+ function skipQuotedIdentifier(text, start) {
52
+ let index = start + 1;
53
+ while (index < text.length) {
54
+ if (text[index] === '"') {
55
+ if (text[index + 1] === '"') {
56
+ index += 2;
57
+ continue;
58
+ }
59
+ return index + 1;
60
+ }
61
+ index += 1;
62
+ }
63
+ return void 0;
64
+ }
65
+ function sanitizeSqlStatement(text) {
66
+ let output = "";
67
+ let index = 0;
68
+ while (index < text.length) {
69
+ const char = text[index];
70
+ const previous = index > 0 ? text[index - 1] : void 0;
71
+ if (char === "'") {
72
+ const end = skipQuotedString(text, index, false);
73
+ if (end === void 0) return void 0;
74
+ output += LITERAL_PLACEHOLDER;
75
+ index = end;
76
+ continue;
77
+ }
78
+ if (char === '"') {
79
+ const end = skipQuotedIdentifier(text, index);
80
+ if (end === void 0) return void 0;
81
+ output += text.slice(index, end);
82
+ index = end;
83
+ continue;
84
+ }
85
+ if (char === "-" && text[index + 1] === "-") {
86
+ const newline = text.indexOf("\n", index);
87
+ index = newline === -1 ? text.length : newline;
88
+ continue;
89
+ }
90
+ if (char === "/" && text[index + 1] === "*") {
91
+ const end = skipBlockComment(text, index);
92
+ if (end === void 0) return void 0;
93
+ output += " ";
94
+ index = end;
95
+ continue;
96
+ }
97
+ if (char === "$" && !isIdentifierChar(previous)) {
98
+ const placeholder = /^\$\d+/.exec(text.slice(index));
99
+ if (placeholder) {
100
+ output += placeholder[0];
101
+ index += placeholder[0].length;
102
+ continue;
103
+ }
104
+ const tag = DOLLAR_TAG_PATTERN.exec(text.slice(index));
105
+ if (tag) {
106
+ const end = text.indexOf(tag[0], index + tag[0].length);
107
+ if (end === -1) return void 0;
108
+ output += LITERAL_PLACEHOLDER;
109
+ index = end + tag[0].length;
110
+ continue;
111
+ }
112
+ }
113
+ if (!isIdentifierChar(previous) && /[0-9.]/.test(char)) {
114
+ const number = NUMBER_PATTERN.exec(text.slice(index));
115
+ if (number) {
116
+ output += LITERAL_PLACEHOLDER;
117
+ index += number[0].length;
118
+ continue;
119
+ }
120
+ }
121
+ if (!isIdentifierChar(previous) && WORD_START_PATTERN.test(char)) {
122
+ const word = WORD_PATTERN.exec(text.slice(index))?.[0] ?? char;
123
+ const lowered = word.toLowerCase();
124
+ const afterWord = index + word.length;
125
+ if (STRING_PREFIXES.has(lowered) && text[afterWord] === "'") {
126
+ const end = skipQuotedString(text, afterWord, lowered === "e");
127
+ if (end === void 0) return void 0;
128
+ output += LITERAL_PLACEHOLDER;
129
+ index = end;
130
+ continue;
131
+ }
132
+ output += BOOLEAN_LITERALS.has(lowered) ? LITERAL_PLACEHOLDER : word;
133
+ index = afterWord;
134
+ continue;
135
+ }
136
+ output += char;
137
+ index += 1;
138
+ }
139
+ return output;
140
+ }
141
+ export {
142
+ REDACTED_SQL_STATEMENT,
143
+ sanitizeSqlStatement
144
+ };
145
+ //# sourceMappingURL=sanitize-sql.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/provider/sanitize-sql.ts"],
4
+ "sourcesContent": ["/**\n * Replaces every literal in a Postgres statement with `?` so span attributes\n * keep the query shape but never the values. MikroORM inlines bound parameters\n * into the SQL text before it reaches `pg`, so `enhancedDatabaseReporting: false`\n * alone cannot keep record content, user ids or session ids out of spans.\n *\n * Kept: keywords, `\"quoted identifiers\"`, `$1` placeholders, operators.\n * Replaced: quoted strings (including `E'\u2026'`, `B'\u2026'`, `X'\u2026'`, `N'\u2026'`),\n * dollar-quoted strings, numeric literals and `true` / `false`.\n * Dropped: comments, since they can carry arbitrary text.\n *\n * Returns `undefined` when the text cannot be tokenized (an unterminated\n * quote or comment) so the caller can fail closed instead of exporting it.\n */\nexport const REDACTED_SQL_STATEMENT = '[redacted]'\n\nconst LITERAL_PLACEHOLDER = '?'\nconst STRING_PREFIXES = new Set(['e', 'b', 'x', 'n'])\nconst BOOLEAN_LITERALS = new Set(['true', 'false'])\nconst NUMBER_PATTERN = /^(?:\\d[\\d_]*(?:\\.[\\d_]*)?|\\.\\d[\\d_]*)(?:[eE][+-]?\\d+)?[A-Za-z0-9_\\u0080-\\uFFFF]*/\nconst DOLLAR_TAG_PATTERN = /^\\$(?:[A-Za-z_\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*)?\\$/\nconst WORD_PATTERN = /^[A-Za-z_\\u0080-\\uFFFF][A-Za-z0-9_$\\u0080-\\uFFFF]*/\nconst WORD_START_PATTERN = /[A-Za-z_\\u0080-\\uFFFF]/\nconst IDENTIFIER_CHAR_PATTERN = /[A-Za-z0-9_$\\u0080-\\uFFFF]/\n\nfunction isIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && IDENTIFIER_CHAR_PATTERN.test(char)\n}\n\nfunction skipBlockComment(text: string, start: number): number | undefined {\n let depth = 0\n let index = start\n while (index < text.length) {\n if (text[index] === '/' && text[index + 1] === '*') {\n depth += 1\n index += 2\n continue\n }\n if (text[index] === '*' && text[index + 1] === '/') {\n depth -= 1\n index += 2\n if (depth === 0) return index\n continue\n }\n index += 1\n }\n return undefined\n}\n\nfunction skipQuotedString(text: string, start: number, backslashEscapes: boolean): number | undefined {\n let index = start + 1\n while (index < text.length) {\n const char = text[index]\n if (backslashEscapes && char === '\\\\') {\n index += 2\n continue\n }\n if (char === \"'\") {\n if (text[index + 1] === \"'\") {\n index += 2\n continue\n }\n return index + 1\n }\n index += 1\n }\n return undefined\n}\n\nfunction skipQuotedIdentifier(text: string, start: number): number | undefined {\n let index = start + 1\n while (index < text.length) {\n if (text[index] === '\"') {\n if (text[index + 1] === '\"') {\n index += 2\n continue\n }\n return index + 1\n }\n index += 1\n }\n return undefined\n}\n\nexport function sanitizeSqlStatement(text: string): string | undefined {\n let output = ''\n let index = 0\n while (index < text.length) {\n const char = text[index]\n const previous = index > 0 ? text[index - 1] : undefined\n\n if (char === \"'\") {\n const end = skipQuotedString(text, index, false)\n if (end === undefined) return undefined\n output += LITERAL_PLACEHOLDER\n index = end\n continue\n }\n\n if (char === '\"') {\n const end = skipQuotedIdentifier(text, index)\n if (end === undefined) return undefined\n output += text.slice(index, end)\n index = end\n continue\n }\n\n if (char === '-' && text[index + 1] === '-') {\n const newline = text.indexOf('\\n', index)\n index = newline === -1 ? text.length : newline\n continue\n }\n\n if (char === '/' && text[index + 1] === '*') {\n const end = skipBlockComment(text, index)\n if (end === undefined) return undefined\n output += ' '\n index = end\n continue\n }\n\n if (char === '$' && !isIdentifierChar(previous)) {\n const placeholder = /^\\$\\d+/.exec(text.slice(index))\n if (placeholder) {\n output += placeholder[0]\n index += placeholder[0].length\n continue\n }\n const tag = DOLLAR_TAG_PATTERN.exec(text.slice(index))\n if (tag) {\n const end = text.indexOf(tag[0], index + tag[0].length)\n if (end === -1) return undefined\n output += LITERAL_PLACEHOLDER\n index = end + tag[0].length\n continue\n }\n }\n\n if (!isIdentifierChar(previous) && /[0-9.]/.test(char)) {\n const number = NUMBER_PATTERN.exec(text.slice(index))\n if (number) {\n output += LITERAL_PLACEHOLDER\n index += number[0].length\n continue\n }\n }\n\n if (!isIdentifierChar(previous) && WORD_START_PATTERN.test(char)) {\n const word = WORD_PATTERN.exec(text.slice(index))?.[0] ?? char\n const lowered = word.toLowerCase()\n const afterWord = index + word.length\n if (STRING_PREFIXES.has(lowered) && text[afterWord] === \"'\") {\n const end = skipQuotedString(text, afterWord, lowered === 'e')\n if (end === undefined) return undefined\n output += LITERAL_PLACEHOLDER\n index = end\n continue\n }\n output += BOOLEAN_LITERALS.has(lowered) ? LITERAL_PLACEHOLDER : word\n index = afterWord\n continue\n }\n\n output += char\n index += 1\n }\n return output\n}\n"],
5
+ "mappings": "AAcO,MAAM,yBAAyB;AAEtC,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,GAAG,CAAC;AACpD,MAAM,mBAAmB,oBAAI,IAAI,CAAC,QAAQ,OAAO,CAAC;AAClD,MAAM,iBAAiB;AACvB,MAAM,qBAAqB;AAC3B,MAAM,eAAe;AACrB,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;AAEhC,SAAS,iBAAiB,MAAmC;AAC3D,SAAO,SAAS,UAAa,wBAAwB,KAAK,IAAI;AAChE;AAEA,SAAS,iBAAiB,MAAc,OAAmC;AACzE,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,SAAO,QAAQ,KAAK,QAAQ;AAC1B,QAAI,KAAK,KAAK,MAAM,OAAO,KAAK,QAAQ,CAAC,MAAM,KAAK;AAClD,eAAS;AACT,eAAS;AACT;AAAA,IACF;AACA,QAAI,KAAK,KAAK,MAAM,OAAO,KAAK,QAAQ,CAAC,MAAM,KAAK;AAClD,eAAS;AACT,eAAS;AACT,UAAI,UAAU,EAAG,QAAO;AACxB;AAAA,IACF;AACA,aAAS;AAAA,EACX;AACA,SAAO;AACT;AAEA,SAAS,iBAAiB,MAAc,OAAe,kBAA+C;AACpG,MAAI,QAAQ,QAAQ;AACpB,SAAO,QAAQ,KAAK,QAAQ;AAC1B,UAAM,OAAO,KAAK,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ACV,aAAS;AAAA,EACX;AACA,SAAO;AACT;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/telemetry",
3
- "version": "0.10.1-develop.8259.1.382cb7589a",
3
+ "version": "0.10.1-develop.8271.1.346e524319",
4
4
  "license": "MIT",
5
5
  "description": "Vendor-neutral spans, metrics, and error reporting backed by a pluggable OTLP provider. Off by default; the telemetry runtime is loaded only when explicitly enabled.",
6
6
  "type": "module",
@@ -38,7 +38,7 @@
38
38
  }
39
39
  },
40
40
  "dependencies": {
41
- "@open-mercato/shared": "0.10.1-develop.8259.1.382cb7589a"
41
+ "@open-mercato/shared": "0.10.1-develop.8271.1.346e524319"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "react": ">=18.0.0"
@@ -70,6 +70,7 @@
70
70
  "@opentelemetry/semantic-conventions": "^1.41.1"
71
71
  },
72
72
  "devDependencies": {
73
+ "@mikro-orm/postgresql": "^7.1.14",
73
74
  "@testing-library/dom": "^10.4.1",
74
75
  "@testing-library/react": "^16.3.1",
75
76
  "@types/jest": "^30.0.0",
@@ -60,6 +60,8 @@ try {
60
60
  await client.end()
61
61
  stage('query')
62
62
  await assert.rejects(client.query('SELECT $1::text', ['pii-sentinel-value']))
63
+ stage('inlined-query')
64
+ await assert.rejects(client.query('select "s0".* from "sessions" as "s0" where "s0"."id" = \\'pii-sentinel-value\\' limit 1'))
63
65
  stage('flush-spans')
64
66
  await processor.forceFlush()
65
67
  const spans = exporter.getFinishedSpans().map((span) => ({ name: span.name, attributes: span.attributes }))
@@ -109,9 +111,12 @@ describe('OTLP provider pg instrumentation', () => {
109
111
  (order) => {
110
112
  const spans = runChild(order)
111
113
  expect(spans.some((span) => span.name.startsWith('pg.query'))).toBe(true)
112
- // enhancedDatabaseReporting must stay off in the provider's default wiring:
113
- // the statement text may appear, bound values must not.
114
+ // enhancedDatabaseReporting must stay off in the provider's default wiring,
115
+ // and values inlined into the SQL text (as MikroORM sends every query) must
116
+ // be sanitized out: the statement shape may appear, the values must not.
114
117
  expect(JSON.stringify(spans)).not.toContain('pii-sentinel-value')
118
+ const statements = spans.flatMap((span) => [span.attributes['db.query.text'], span.attributes['db.statement']])
119
+ expect(statements).toContain('select "s0".* from "sessions" as "s0" where "s0"."id" = ? limit ?')
115
120
  },
116
121
  35_000,
117
122
  )
@@ -0,0 +1,121 @@
1
+ import { PostgreSqlPlatform } from '@mikro-orm/postgresql'
2
+ import { sanitizeSqlStatement } from '../provider/sanitize-sql'
3
+ import { PG_INSTRUMENTATION_OPTIONS, PG_STATEMENT_ATTRIBUTE_KEYS } from '../provider/otlp-provider'
4
+
5
+ const SENTINEL = 'pii-sentinel-value'
6
+ const platform = new PostgreSqlPlatform()
7
+
8
+ describe('sanitizeSqlStatement', () => {
9
+ it('strips values MikroORM inlines into an insert, keeping the shape', () => {
10
+ const formatted = platform.formatQuery(
11
+ 'insert into "comments" ("tenant_id", "body", "attempts", "is_public", "created_at") values (?, ?, ?, ?, ?) returning "id"',
12
+ ['c68d875e-b431-48c4-85ef-a8ce6d1c5540', SENTINEL, 42, true, new Date('2026-11-18T08:04:43.385Z')],
13
+ )
14
+ expect(formatted).toContain(SENTINEL)
15
+ expect(sanitizeSqlStatement(formatted)).toBe(
16
+ 'insert into "comments" ("tenant_id", "body", "attempts", "is_public", "created_at") values (?, ?, ?, ?, ?) returning "id"',
17
+ )
18
+ })
19
+
20
+ it('strips an id literal from a MikroORM findOne-style select', () => {
21
+ const formatted = platform.formatQuery(
22
+ 'select "s0".* from "sessions" as "s0" where "s0"."id" = ? and "s0"."user_id" = ? limit ?',
23
+ [SENTINEL, '405da1c6-ddf1-4c4b-9f1e-a7cdead1749c', 1],
24
+ )
25
+ const sanitized = sanitizeSqlStatement(formatted)
26
+ expect(sanitized).toBe('select "s0".* from "sessions" as "s0" where "s0"."id" = ? and "s0"."user_id" = ? limit ?')
27
+ expect(sanitized).not.toContain(SENTINEL)
28
+ })
29
+
30
+ it('strips escape strings that MikroORM emits for values with quotes and backslashes', () => {
31
+ const formatted = platform.formatQuery('update "notes" set "body" = ? where "id" = ?', [`O'Brien \\ ${SENTINEL} '`, 7])
32
+ expect(formatted).toContain(" E'")
33
+ expect(sanitizeSqlStatement(formatted)).toBe('update "notes" set "body" = ? where "id" = ?')
34
+ })
35
+
36
+ it('strips JSON and array literals', () => {
37
+ const formatted = platform.formatQuery('select * from "t" where "data" @> ? and "id" in (?)', [
38
+ JSON.stringify({ email: SENTINEL }),
39
+ [SENTINEL, 'other'],
40
+ ])
41
+ const sanitized = sanitizeSqlStatement(formatted)
42
+ expect(sanitized).toBe('select * from "t" where "data" @> ? and "id" in (?, ?)')
43
+ })
44
+
45
+ it('keeps placeholders, quoted identifiers, and numbers inside identifiers', () => {
46
+ const statement = `select "u1"."id", t0.x$1 from "it's ""odd"""."x" as t0 where id = $1 and n = $12`
47
+ expect(sanitizeSqlStatement(statement)).toBe(statement)
48
+ })
49
+
50
+ it('strips numeric, boolean, prefixed and dollar-quoted literals', () => {
51
+ expect(sanitizeSqlStatement("select 1, -2.5, .5e3, TRUE, false, B'0101', X'ff', N'abc', $$x$$, $tag$y$tag$")).toBe(
52
+ 'select ?, -?, ?, ?, ?, ?, ?, ?, ?, ?',
53
+ )
54
+ })
55
+
56
+ it('strips non-decimal, underscored and suffixed numbers whole', () => {
57
+ expect(sanitizeSqlStatement('select 0x1F, 0o17, 0b101, 1_000_000, 123abc, 1.5e3')).toBe('select ?, ?, ?, ?, ?, ?')
58
+ })
59
+
60
+ it('strips dollar-quoted strings with non-ASCII tags and keeps non-ASCII identifiers whole', () => {
61
+ expect(sanitizeSqlStatement(`select $é$ ${SENTINEL} $é$ from zamówienia1`)).toBe('select ? from zamówienia1')
62
+ })
63
+
64
+ it.each(['$🔐$', '$e\u0301$', '$€$'])('strips Postgres high-bit dollar tags: %s', (tag) => {
65
+ expect(sanitizeSqlStatement(`select ${tag}${SENTINEL}${tag}`)).toBe('select ?')
66
+ expect(sanitizeSqlStatement(`select ${tag}${SENTINEL}`)).toBeUndefined()
67
+ })
68
+
69
+ it('keeps non-ASCII identifier characters adjacent to dollar signs whole', () => {
70
+ const statement = 'select 🔐$1, e\u0301$2 from t'
71
+ expect(sanitizeSqlStatement(statement)).toBe(statement)
72
+ })
73
+
74
+ it('drops nested block comments in full', () => {
75
+ expect(sanitizeSqlStatement(`select 1 /* outer /* inner */ ${SENTINEL} */ from t`)).toBe('select ? from t')
76
+ })
77
+
78
+ it('drops comments, which can carry arbitrary text', () => {
79
+ expect(sanitizeSqlStatement(`select 1 -- ${SENTINEL}\nfrom t /* ${SENTINEL} */ where a = b`)).toBe(
80
+ 'select ? \nfrom t where a = b',
81
+ )
82
+ })
83
+
84
+ it.each([
85
+ `select '${SENTINEL}`,
86
+ `select E'${SENTINEL}\\'`,
87
+ 'select "unterminated',
88
+ `select $$${SENTINEL}`,
89
+ `select 1 /* ${SENTINEL}`,
90
+ `select 1 /* a /* b */ ${SENTINEL}`,
91
+ ])('fails closed on %s', (text) => {
92
+ expect(sanitizeSqlStatement(text)).toBeUndefined()
93
+ })
94
+ })
95
+
96
+ describe('PG_INSTRUMENTATION_OPTIONS.requestHook', () => {
97
+ function runHook(text: unknown) {
98
+ const attributes: Record<string, unknown> = {}
99
+ const span = { setAttribute: (key: string, value: unknown) => { attributes[key] = value } }
100
+ const hook = PG_INSTRUMENTATION_OPTIONS.requestHook as (span: unknown, info: unknown) => void
101
+ hook(span, { connection: {}, query: { text } })
102
+ return attributes
103
+ }
104
+
105
+ it('overwrites every statement attribute key with the sanitized text', () => {
106
+ const attributes = runHook(`select * from "users" where "id" = '${SENTINEL}'`)
107
+ for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) {
108
+ expect(attributes[key]).toBe('select * from "users" where "id" = ?')
109
+ }
110
+ })
111
+
112
+ it('writes a fixed marker when the text cannot be tokenized', () => {
113
+ const attributes = runHook(`select '${SENTINEL}`)
114
+ expect(JSON.stringify(attributes)).not.toContain(SENTINEL)
115
+ expect(attributes['db.query.text']).toBe('[redacted]')
116
+ })
117
+
118
+ it('leaves the span alone when there is no statement text', () => {
119
+ expect(runHook(undefined)).toEqual({})
120
+ })
121
+ })
@@ -42,9 +42,10 @@ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'
42
42
  import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
43
43
  import { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs'
44
44
  import { PeriodicExportingMetricReader, type IMetricReader } from '@opentelemetry/sdk-metrics'
45
- import { PgInstrumentation } from '@opentelemetry/instrumentation-pg'
45
+ import { PgInstrumentation, type PgInstrumentationConfig } from '@opentelemetry/instrumentation-pg'
46
46
  import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici'
47
47
 
48
+ import { REDACTED_SQL_STATEMENT, sanitizeSqlStatement } from './sanitize-sql'
48
49
  import type {
49
50
  Attributes,
50
51
  AttributeValue,
@@ -221,14 +222,31 @@ export type OtlpProviderOptions = {
221
222
  instrumentations?: Instrumentation[]
222
223
  }
223
224
 
225
+ /**
226
+ * Statement attribute keys written by `@opentelemetry/instrumentation-pg`:
227
+ * `db.query.text` (stable semconv, 0.73+) and `db.statement` (older releases).
228
+ */
229
+ export const PG_STATEMENT_ATTRIBUTE_KEYS = ['db.query.text', 'db.statement'] as const
230
+
224
231
  /**
225
232
  * PII guard (telemetry spec Privacy / R12). The single source of truth for pg
226
- * instrumentation config: `enhancedDatabaseReporting: false` means bound SQL
227
- * parameter VALUES are NOT captured — only the statement shape ($1, $2). User
228
- * data lives in those params, so this must never be flipped on. Asserted by a
229
- * regression test.
233
+ * instrumentation config. Two layers, both asserted by regression tests:
234
+ *
235
+ * - `enhancedDatabaseReporting: false` keeps the bound parameter VALUES array
236
+ * off the span. This must never be flipped on.
237
+ * - `requestHook` rewrites the statement text with every literal replaced by
238
+ * `?`. MikroORM inlines parameters into the SQL before it reaches `pg`, so
239
+ * without this the statement itself carries record content and ids. When the
240
+ * text cannot be tokenized the hook fails closed with a fixed marker.
230
241
  */
231
- export const PG_INSTRUMENTATION_OPTIONS = { enhancedDatabaseReporting: false } as const
242
+ export const PG_INSTRUMENTATION_OPTIONS = {
243
+ enhancedDatabaseReporting: false,
244
+ requestHook: (span, { query }) => {
245
+ if (typeof query.text !== 'string' || query.text.length === 0) return
246
+ const statement = sanitizeSqlStatement(query.text) ?? REDACTED_SQL_STATEMENT
247
+ for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) span.setAttribute(key, statement)
248
+ },
249
+ } as const satisfies PgInstrumentationConfig
232
250
 
233
251
  /**
234
252
  * Bucket boundaries for every histogram recorded in seconds. Without explicit
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Replaces every literal in a Postgres statement with `?` so span attributes
3
+ * keep the query shape but never the values. MikroORM inlines bound parameters
4
+ * into the SQL text before it reaches `pg`, so `enhancedDatabaseReporting: false`
5
+ * alone cannot keep record content, user ids or session ids out of spans.
6
+ *
7
+ * Kept: keywords, `"quoted identifiers"`, `$1` placeholders, operators.
8
+ * Replaced: quoted strings (including `E'…'`, `B'…'`, `X'…'`, `N'…'`),
9
+ * dollar-quoted strings, numeric literals and `true` / `false`.
10
+ * Dropped: comments, since they can carry arbitrary text.
11
+ *
12
+ * Returns `undefined` when the text cannot be tokenized (an unterminated
13
+ * quote or comment) so the caller can fail closed instead of exporting it.
14
+ */
15
+ export const REDACTED_SQL_STATEMENT = '[redacted]'
16
+
17
+ const LITERAL_PLACEHOLDER = '?'
18
+ const STRING_PREFIXES = new Set(['e', 'b', 'x', 'n'])
19
+ const BOOLEAN_LITERALS = new Set(['true', 'false'])
20
+ const NUMBER_PATTERN = /^(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?[A-Za-z0-9_\u0080-\uFFFF]*/
21
+ const DOLLAR_TAG_PATTERN = /^\$(?:[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_\u0080-\uFFFF]*)?\$/
22
+ const WORD_PATTERN = /^[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_$\u0080-\uFFFF]*/
23
+ const WORD_START_PATTERN = /[A-Za-z_\u0080-\uFFFF]/
24
+ const IDENTIFIER_CHAR_PATTERN = /[A-Za-z0-9_$\u0080-\uFFFF]/
25
+
26
+ function isIdentifierChar(char: string | undefined): boolean {
27
+ return char !== undefined && IDENTIFIER_CHAR_PATTERN.test(char)
28
+ }
29
+
30
+ function skipBlockComment(text: string, start: number): number | undefined {
31
+ let depth = 0
32
+ let index = start
33
+ while (index < text.length) {
34
+ if (text[index] === '/' && text[index + 1] === '*') {
35
+ depth += 1
36
+ index += 2
37
+ continue
38
+ }
39
+ if (text[index] === '*' && text[index + 1] === '/') {
40
+ depth -= 1
41
+ index += 2
42
+ if (depth === 0) return index
43
+ continue
44
+ }
45
+ index += 1
46
+ }
47
+ return undefined
48
+ }
49
+
50
+ function skipQuotedString(text: string, start: number, backslashEscapes: boolean): number | undefined {
51
+ let index = start + 1
52
+ while (index < text.length) {
53
+ const char = text[index]
54
+ if (backslashEscapes && char === '\\') {
55
+ index += 2
56
+ continue
57
+ }
58
+ if (char === "'") {
59
+ if (text[index + 1] === "'") {
60
+ index += 2
61
+ continue
62
+ }
63
+ return index + 1
64
+ }
65
+ index += 1
66
+ }
67
+ return undefined
68
+ }
69
+
70
+ function skipQuotedIdentifier(text: string, start: number): number | undefined {
71
+ let index = start + 1
72
+ while (index < text.length) {
73
+ if (text[index] === '"') {
74
+ if (text[index + 1] === '"') {
75
+ index += 2
76
+ continue
77
+ }
78
+ return index + 1
79
+ }
80
+ index += 1
81
+ }
82
+ return undefined
83
+ }
84
+
85
+ export function sanitizeSqlStatement(text: string): string | undefined {
86
+ let output = ''
87
+ let index = 0
88
+ while (index < text.length) {
89
+ const char = text[index]
90
+ const previous = index > 0 ? text[index - 1] : undefined
91
+
92
+ if (char === "'") {
93
+ const end = skipQuotedString(text, index, false)
94
+ if (end === undefined) return undefined
95
+ output += LITERAL_PLACEHOLDER
96
+ index = end
97
+ continue
98
+ }
99
+
100
+ if (char === '"') {
101
+ const end = skipQuotedIdentifier(text, index)
102
+ if (end === undefined) return undefined
103
+ output += text.slice(index, end)
104
+ index = end
105
+ continue
106
+ }
107
+
108
+ if (char === '-' && text[index + 1] === '-') {
109
+ const newline = text.indexOf('\n', index)
110
+ index = newline === -1 ? text.length : newline
111
+ continue
112
+ }
113
+
114
+ if (char === '/' && text[index + 1] === '*') {
115
+ const end = skipBlockComment(text, index)
116
+ if (end === undefined) return undefined
117
+ output += ' '
118
+ index = end
119
+ continue
120
+ }
121
+
122
+ if (char === '$' && !isIdentifierChar(previous)) {
123
+ const placeholder = /^\$\d+/.exec(text.slice(index))
124
+ if (placeholder) {
125
+ output += placeholder[0]
126
+ index += placeholder[0].length
127
+ continue
128
+ }
129
+ const tag = DOLLAR_TAG_PATTERN.exec(text.slice(index))
130
+ if (tag) {
131
+ const end = text.indexOf(tag[0], index + tag[0].length)
132
+ if (end === -1) return undefined
133
+ output += LITERAL_PLACEHOLDER
134
+ index = end + tag[0].length
135
+ continue
136
+ }
137
+ }
138
+
139
+ if (!isIdentifierChar(previous) && /[0-9.]/.test(char)) {
140
+ const number = NUMBER_PATTERN.exec(text.slice(index))
141
+ if (number) {
142
+ output += LITERAL_PLACEHOLDER
143
+ index += number[0].length
144
+ continue
145
+ }
146
+ }
147
+
148
+ if (!isIdentifierChar(previous) && WORD_START_PATTERN.test(char)) {
149
+ const word = WORD_PATTERN.exec(text.slice(index))?.[0] ?? char
150
+ const lowered = word.toLowerCase()
151
+ const afterWord = index + word.length
152
+ if (STRING_PREFIXES.has(lowered) && text[afterWord] === "'") {
153
+ const end = skipQuotedString(text, afterWord, lowered === 'e')
154
+ if (end === undefined) return undefined
155
+ output += LITERAL_PLACEHOLDER
156
+ index = end
157
+ continue
158
+ }
159
+ output += BOOLEAN_LITERALS.has(lowered) ? LITERAL_PLACEHOLDER : word
160
+ index = afterWord
161
+ continue
162
+ }
163
+
164
+ output += char
165
+ index += 1
166
+ }
167
+ return output
168
+ }