@macss/modular-api 0.6.1 → 0.7.1

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.
@@ -0,0 +1,65 @@
1
+ import { type Context, type TextMapPropagator } from '@opentelemetry/api';
2
+ /**
3
+ * The header carrying a caller-supplied correlation id.
4
+ *
5
+ * Read and preserved, **never** adopted as the trace id — see {@link PropagationPolicy}.
6
+ */
7
+ export declare const REQUEST_ID_HEADER = "x-request-id";
8
+ /** What resolving the incoming headers produced. */
9
+ export interface PropagationResult {
10
+ /**
11
+ * The context to continue with. Carries a remote parent when one was accepted,
12
+ * and otherwise carries none — trace and span id generation belongs to the
13
+ * tracer, not here.
14
+ */
15
+ readonly context: Context;
16
+ /**
17
+ * The caller's `X-Request-ID`, when it sent one. Preserved for log correlation
18
+ * and for forwarding on outbound calls; it is not identity.
19
+ */
20
+ readonly requestId?: string;
21
+ /** Whether a remote parent was accepted from the incoming headers. */
22
+ readonly hasRemoteParent: boolean;
23
+ }
24
+ export interface PropagationPolicyOptions {
25
+ /** The ordered chain. First valid span context wins. Defaults to W3C alone. */
26
+ readonly propagators?: readonly TextMapPropagator<unknown>[];
27
+ /** Whether an incoming trace context is honoured at all. Defaults to `true`. */
28
+ readonly trustIncomingTraceContext?: boolean;
29
+ }
30
+ /**
31
+ * Resolves incoming request headers into a tracing context.
32
+ *
33
+ * **Composable rather than hardcoded** (runbook D24). The chain is an ordered list
34
+ * of propagators and the first to yield a valid span context wins. The default is
35
+ * W3C Trace Context only: a service on Google Cloud appends a Cloud Trace
36
+ * propagator, which keeps anything vendor-specific out of the framework. A service
37
+ * behind a B3-speaking mesh appends a B3 propagator the same way, instead of forking.
38
+ *
39
+ * **`X-Request-ID` is never the trace id** (runbook D6). It is read and preserved
40
+ * beside the trace id, never promoted into it: callers reuse it deliberately on
41
+ * retries, so adopting it would merge unrelated retries into one trace; any client
42
+ * could then collide traces on purpose; and `trace_id` would have ambiguous
43
+ * provenance, sometimes caller-supplied and sometimes generated.
44
+ *
45
+ * **Nothing is generated here.** When no propagator matches, the returned context
46
+ * simply carries no span context and the tracer starts a fresh trace with ids of its
47
+ * own (runbook D7, gate G3).
48
+ *
49
+ * The Dart counterpart is `lib/src/core/tracing/propagation_policy.dart`.
50
+ */
51
+ export declare class PropagationPolicy {
52
+ /** The ordered chain. First valid span context wins. */
53
+ readonly propagators: readonly TextMapPropagator<unknown>[];
54
+ /**
55
+ * Whether an incoming trace context is honoured at all (D25).
56
+ *
57
+ * Defaults to `true`, matching every official OpenTelemetry SDK. Set it to
58
+ * `false` on a service that receives internet traffic directly, where a caller
59
+ * could otherwise choose its trace ids.
60
+ */
61
+ readonly trustIncomingTraceContext: boolean;
62
+ constructor(options?: PropagationPolicyOptions);
63
+ /** Resolves `headers` into a context plus the preserved request id. */
64
+ resolve(headers: Record<string, string>): PropagationResult;
65
+ }
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PropagationPolicy = exports.REQUEST_ID_HEADER = void 0;
4
+ const api_1 = require("@opentelemetry/api");
5
+ const w3cTraceContextPropagator_1 = require("./w3cTraceContextPropagator");
6
+ /**
7
+ * The header carrying a caller-supplied correlation id.
8
+ *
9
+ * Read and preserved, **never** adopted as the trace id — see {@link PropagationPolicy}.
10
+ */
11
+ exports.REQUEST_ID_HEADER = 'x-request-id';
12
+ /**
13
+ * Resolves incoming request headers into a tracing context.
14
+ *
15
+ * **Composable rather than hardcoded** (runbook D24). The chain is an ordered list
16
+ * of propagators and the first to yield a valid span context wins. The default is
17
+ * W3C Trace Context only: a service on Google Cloud appends a Cloud Trace
18
+ * propagator, which keeps anything vendor-specific out of the framework. A service
19
+ * behind a B3-speaking mesh appends a B3 propagator the same way, instead of forking.
20
+ *
21
+ * **`X-Request-ID` is never the trace id** (runbook D6). It is read and preserved
22
+ * beside the trace id, never promoted into it: callers reuse it deliberately on
23
+ * retries, so adopting it would merge unrelated retries into one trace; any client
24
+ * could then collide traces on purpose; and `trace_id` would have ambiguous
25
+ * provenance, sometimes caller-supplied and sometimes generated.
26
+ *
27
+ * **Nothing is generated here.** When no propagator matches, the returned context
28
+ * simply carries no span context and the tracer starts a fresh trace with ids of its
29
+ * own (runbook D7, gate G3).
30
+ *
31
+ * The Dart counterpart is `lib/src/core/tracing/propagation_policy.dart`.
32
+ */
33
+ class PropagationPolicy {
34
+ /** The ordered chain. First valid span context wins. */
35
+ propagators;
36
+ /**
37
+ * Whether an incoming trace context is honoured at all (D25).
38
+ *
39
+ * Defaults to `true`, matching every official OpenTelemetry SDK. Set it to
40
+ * `false` on a service that receives internet traffic directly, where a caller
41
+ * could otherwise choose its trace ids.
42
+ */
43
+ trustIncomingTraceContext;
44
+ constructor(options = {}) {
45
+ this.propagators = options.propagators ?? [new w3cTraceContextPropagator_1.W3CTraceContextPropagator()];
46
+ this.trustIncomingTraceContext = options.trustIncomingTraceContext ?? true;
47
+ }
48
+ /** Resolves `headers` into a context plus the preserved request id. */
49
+ resolve(headers) {
50
+ // Read first and unconditionally: the request id is preserved whether or not
51
+ // incoming trace context is trusted, because it was never trusted as identity.
52
+ const requestId = headerValue(headers, exports.REQUEST_ID_HEADER);
53
+ if (!this.trustIncomingTraceContext) {
54
+ return { context: api_1.ROOT_CONTEXT, requestId, hasRemoteParent: false };
55
+ }
56
+ const getter = caseInsensitiveGetter;
57
+ for (const propagator of this.propagators) {
58
+ try {
59
+ const resolved = propagator.extract(api_1.ROOT_CONTEXT, headers, getter);
60
+ if (isValid(api_1.trace.getSpanContext(resolved))) {
61
+ // First valid wins (D24).
62
+ return { context: resolved, requestId, hasRemoteParent: true };
63
+ }
64
+ }
65
+ catch {
66
+ // A third-party propagator is not our code, and one misbehaving entry must
67
+ // not fail a request. Move on to the next.
68
+ continue;
69
+ }
70
+ }
71
+ // No parent accepted. The tracer starts a fresh trace and generates its own
72
+ // ids — nothing is generated here, which is what keeps this allocation-free.
73
+ return { context: api_1.ROOT_CONTEXT, requestId, hasRemoteParent: false };
74
+ }
75
+ }
76
+ exports.PropagationPolicy = PropagationPolicy;
77
+ function isValid(spanContext) {
78
+ return spanContext !== undefined && api_1.trace.isSpanContextValid(spanContext);
79
+ }
80
+ /** Reads a header case-insensitively, as HTTP requires. */
81
+ function headerValue(headers, name) {
82
+ const wanted = name.toLowerCase();
83
+ return Object.entries(headers).find(([key]) => key.toLowerCase() === wanted)?.[1];
84
+ }
85
+ /**
86
+ * Carrier reader with HTTP semantics.
87
+ *
88
+ * Header casing belongs to the carrier rather than to any propagator, so it is
89
+ * handled once here instead of in each of them.
90
+ */
91
+ const caseInsensitiveGetter = {
92
+ keys: (carrier) => Object.keys(carrier),
93
+ get: (carrier, key) => headerValue(carrier, key),
94
+ };
@@ -0,0 +1,40 @@
1
+ import { type Span, type Tracer } from '@opentelemetry/api';
2
+ import { PropagationPolicy, type PropagationResult } from './propagationPolicy';
3
+ /** The server span for one inbound call, plus what propagation resolved. */
4
+ export interface ServerSpanStart {
5
+ readonly span: Span;
6
+ readonly propagation: PropagationResult;
7
+ }
8
+ export interface StartServerSpanOptions {
9
+ readonly tracer: Tracer;
10
+ readonly method: string;
11
+ readonly route: string;
12
+ readonly headers: Record<string, string>;
13
+ readonly policy?: PropagationPolicy;
14
+ }
15
+ /**
16
+ * Opens a server span for one inbound call.
17
+ *
18
+ * **Deliberately transport-neutral** (gate G4). Nothing in this file mentions HTTP, Express, or a
19
+ * request object: it takes a method, a route and a header map, which is all any transport can
20
+ * supply. `tracingMiddleware` is a thin adapter from Express to this, and the planned gRPC transport
21
+ * arrives the same way — as another adapter, not as a second copy of span construction.
22
+ *
23
+ * This was extracted when G4 was checked rather than assumed. The span had been built inline inside
24
+ * the middleware's Express closure, which satisfied every behavioural test and would have forced a
25
+ * gRPC transport to duplicate it.
26
+ */
27
+ export declare function startServerSpan(options: StartServerSpanOptions): ServerSpanStart;
28
+ export interface CompleteServerSpanOptions {
29
+ readonly statusCode?: number;
30
+ readonly error?: unknown;
31
+ /** A client that disconnected before the response completed. */
32
+ readonly aborted?: boolean;
33
+ }
34
+ /**
35
+ * Records the outcome on `span` and ends it.
36
+ *
37
+ * `statusCode` is undefined when the call produced no status — a transport that has no such concept,
38
+ * or a failure before one was determined.
39
+ */
40
+ export declare function completeServerSpan(span: Span, { statusCode, error, aborted }?: CompleteServerSpanOptions): void;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startServerSpan = startServerSpan;
4
+ exports.completeServerSpan = completeServerSpan;
5
+ const api_1 = require("@opentelemetry/api");
6
+ const propagationPolicy_1 = require("./propagationPolicy");
7
+ /**
8
+ * Opens a server span for one inbound call.
9
+ *
10
+ * **Deliberately transport-neutral** (gate G4). Nothing in this file mentions HTTP, Express, or a
11
+ * request object: it takes a method, a route and a header map, which is all any transport can
12
+ * supply. `tracingMiddleware` is a thin adapter from Express to this, and the planned gRPC transport
13
+ * arrives the same way — as another adapter, not as a second copy of span construction.
14
+ *
15
+ * This was extracted when G4 was checked rather than assumed. The span had been built inline inside
16
+ * the middleware's Express closure, which satisfied every behavioural test and would have forced a
17
+ * gRPC transport to duplicate it.
18
+ */
19
+ function startServerSpan(options) {
20
+ const method = options.method.toUpperCase();
21
+ const policy = options.policy ?? new propagationPolicy_1.PropagationPolicy();
22
+ const resolved = policy.resolve(options.headers);
23
+ const span = options.tracer.startSpan(
24
+ // Semantic convention for a server span: method then route.
25
+ `${method} ${options.route}`, {
26
+ kind: api_1.SpanKind.SERVER,
27
+ attributes: {
28
+ 'http.request.method': method,
29
+ 'url.path': options.route,
30
+ // The convention's name for a captured header rather than an invented one, so a reader of
31
+ // the trace recognises it (D6).
32
+ ...(resolved.requestId === undefined
33
+ ? {}
34
+ : { 'http.request.header.x-request-id': resolved.requestId }),
35
+ },
36
+ },
37
+ // The parent comes from the resolved context, never from whatever happened to be ambient.
38
+ resolved.context);
39
+ return { span, propagation: resolved };
40
+ }
41
+ /**
42
+ * Records the outcome on `span` and ends it.
43
+ *
44
+ * `statusCode` is undefined when the call produced no status — a transport that has no such concept,
45
+ * or a failure before one was determined.
46
+ */
47
+ function completeServerSpan(span, { statusCode, error, aborted = false } = {}) {
48
+ if (statusCode !== undefined) {
49
+ span.setAttribute('http.response.status_code', statusCode);
50
+ }
51
+ if (error !== undefined) {
52
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
53
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: 'request failed' });
54
+ }
55
+ else if (aborted) {
56
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: 'client disconnected' });
57
+ }
58
+ else if (statusCode !== undefined && statusCode >= 500) {
59
+ // 5xx is ours; 4xx is the caller's. Marking client mistakes as errors makes an error-rate panel
60
+ // useless.
61
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: `HTTP ${statusCode}` });
62
+ }
63
+ span.end();
64
+ }
@@ -0,0 +1,42 @@
1
+ import { type Tracer } from '@opentelemetry/api';
2
+ import type { RequestHandler } from 'express';
3
+ import { PropagationPolicy } from './propagationPolicy';
4
+ /** Property under which the server span is exposed on `res.locals`. */
5
+ export declare const TRACING_SPAN_LOCAL = "modularTracingSpan";
6
+ /** Property under which the resolved propagation result is exposed on `res.locals`. */
7
+ export declare const PROPAGATION_RESULT_LOCAL = "modularPropagationResult";
8
+ export interface TracingMiddlewareOptions {
9
+ readonly tracer: Tracer;
10
+ readonly policy?: PropagationPolicy;
11
+ readonly excludedRoutes?: readonly string[];
12
+ }
13
+ /**
14
+ * Creates the middleware that owns the server span.
15
+ *
16
+ * **Host-owned, not plugin-owned, and OUTERMOST** — `loggingMiddleware` runs inside it
17
+ * (runbook D12 as reversed), so the logger reads `trace_id` and `span_id` from the
18
+ * ambient span on every line. Being outside every plugin middleware is the other half of
19
+ * the point: a span created from inside a plugin slot would miss the plugin
20
+ * middleware registered before it, leaving a hole in the waterfall exactly where
21
+ * cold start and early middleware live (ADR-0005 decision 4).
22
+ *
23
+ * **Where this genuinely differs from the Dart version, rather than merely reading
24
+ * differently.** Shelf hands a middleware the `Response` its inner handler
25
+ * produced, so the Dart implementation reads the status code and ends the span in a
26
+ * `finally`. Express does not: a middleware calls `next()` and never sees the
27
+ * response. The status code and the end of the request are therefore observed
28
+ * through `res.on('finish')`, with `res.on('close')` covering a client that
29
+ * disconnects before the response completes. A guard makes sure the span ends
30
+ * exactly once whichever fires first.
31
+ *
32
+ * Ambient propagation also differs. Dart's context is zone-based and the API
33
+ * handles it alone; in JavaScript `context.with` needs a context manager, which the
34
+ * application's SDK registers. Without one it degrades to a passthrough: child
35
+ * spans created downstream become roots instead of children, rather than failing.
36
+ * The wiring recipe in the observability guide covers this.
37
+ *
38
+ * **This is an adapter, and only an adapter.** Span construction lives in `serverSpan.ts`, which
39
+ * knows nothing about HTTP or Express, so the planned gRPC transport arrives as a second adapter
40
+ * rather than a second copy (gate G4).
41
+ */
42
+ export declare function tracingMiddleware(options: TracingMiddlewareOptions): RequestHandler;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROPAGATION_RESULT_LOCAL = exports.TRACING_SPAN_LOCAL = void 0;
4
+ exports.tracingMiddleware = tracingMiddleware;
5
+ const api_1 = require("@opentelemetry/api");
6
+ const propagationPolicy_1 = require("./propagationPolicy");
7
+ const serverSpan_1 = require("./serverSpan");
8
+ /** Property under which the server span is exposed on `res.locals`. */
9
+ exports.TRACING_SPAN_LOCAL = 'modularTracingSpan';
10
+ /** Property under which the resolved propagation result is exposed on `res.locals`. */
11
+ exports.PROPAGATION_RESULT_LOCAL = 'modularPropagationResult';
12
+ /**
13
+ * Creates the middleware that owns the server span.
14
+ *
15
+ * **Host-owned, not plugin-owned, and OUTERMOST** — `loggingMiddleware` runs inside it
16
+ * (runbook D12 as reversed), so the logger reads `trace_id` and `span_id` from the
17
+ * ambient span on every line. Being outside every plugin middleware is the other half of
18
+ * the point: a span created from inside a plugin slot would miss the plugin
19
+ * middleware registered before it, leaving a hole in the waterfall exactly where
20
+ * cold start and early middleware live (ADR-0005 decision 4).
21
+ *
22
+ * **Where this genuinely differs from the Dart version, rather than merely reading
23
+ * differently.** Shelf hands a middleware the `Response` its inner handler
24
+ * produced, so the Dart implementation reads the status code and ends the span in a
25
+ * `finally`. Express does not: a middleware calls `next()` and never sees the
26
+ * response. The status code and the end of the request are therefore observed
27
+ * through `res.on('finish')`, with `res.on('close')` covering a client that
28
+ * disconnects before the response completes. A guard makes sure the span ends
29
+ * exactly once whichever fires first.
30
+ *
31
+ * Ambient propagation also differs. Dart's context is zone-based and the API
32
+ * handles it alone; in JavaScript `context.with` needs a context manager, which the
33
+ * application's SDK registers. Without one it degrades to a passthrough: child
34
+ * spans created downstream become roots instead of children, rather than failing.
35
+ * The wiring recipe in the observability guide covers this.
36
+ *
37
+ * **This is an adapter, and only an adapter.** Span construction lives in `serverSpan.ts`, which
38
+ * knows nothing about HTTP or Express, so the planned gRPC transport arrives as a second adapter
39
+ * rather than a second copy (gate G4).
40
+ */
41
+ function tracingMiddleware(options) {
42
+ const { tracer } = options;
43
+ const policy = options.policy ?? new propagationPolicy_1.PropagationPolicy();
44
+ const excluded = new Set(options.excludedRoutes ?? []);
45
+ return (req, res, next) => {
46
+ // Health, metrics and docs are noise in a trace store. The host derives this
47
+ // list from operationalPaths rather than hardcoding it.
48
+ if (excluded.has(req.path)) {
49
+ next();
50
+ return;
51
+ }
52
+ const { span, propagation: resolved } = (0, serverSpan_1.startServerSpan)({
53
+ tracer,
54
+ method: req.method,
55
+ route: req.path,
56
+ headers: req.headers,
57
+ policy,
58
+ });
59
+ res.locals[exports.TRACING_SPAN_LOCAL] = span;
60
+ res.locals[exports.PROPAGATION_RESULT_LOCAL] = resolved;
61
+ let ended = false;
62
+ const endSpan = (aborted) => {
63
+ if (ended)
64
+ return;
65
+ ended = true;
66
+ (0, serverSpan_1.completeServerSpan)(span, { statusCode: res.statusCode, aborted });
67
+ };
68
+ res.on('finish', () => endSpan(false));
69
+ res.on('close', () => endSpan(!res.writableEnded));
70
+ // Ambient for everything downstream, so a child span created in a use case, a
71
+ // database command or an outbound call attaches by itself.
72
+ api_1.context.with(api_1.trace.setSpan(resolved.context, span), () => {
73
+ next();
74
+ });
75
+ };
76
+ }
@@ -0,0 +1,76 @@
1
+ import type { TextMapPropagator, Tracer, TracerProvider } from '@opentelemetry/api';
2
+ import type { TraceFieldFormatter } from '../logger/logger';
3
+ import { PropagationPolicy } from './propagationPolicy';
4
+ export interface TracingOptionsInit {
5
+ /** The application's tracer provider, from its OpenTelemetry SDK. */
6
+ readonly tracerProvider: TracerProvider;
7
+ /**
8
+ * The ordered propagator chain. Defaults to W3C Trace Context alone.
9
+ *
10
+ * A service on Google Cloud appends a Cloud Trace propagator, which is how
11
+ * vendor-specific formats stay out of the framework (runbook D24, roadmap
12
+ * invariant 7).
13
+ */
14
+ readonly propagators?: readonly TextMapPropagator<unknown>[];
15
+ /**
16
+ * Whether an incoming trace context is honoured at all. Defaults to `true`.
17
+ *
18
+ * **Set it to `false` on a service that receives internet traffic directly**,
19
+ * where a caller could otherwise choose its own trace ids and collide traces
20
+ * (runbook D25).
21
+ */
22
+ readonly trustIncomingTraceContext?: boolean;
23
+ /** The instrumentation scope name reported to the backend. */
24
+ readonly instrumentationName?: string;
25
+ /**
26
+ * Builds platform-specific log correlation fields, or undefined for none.
27
+ *
28
+ * The framework emits open formats and nothing vendor-specific (roadmap invariant 7),
29
+ * so a field like Google's `logging.googleapis.com/trace` — which needs a project id
30
+ * the framework has no business knowing — is produced here by the application.
31
+ */
32
+ readonly traceFieldFormatter?: TraceFieldFormatter;
33
+ /**
34
+ * Runs when the server closes, before the process goes away.
35
+ *
36
+ * **The framework offers the timing; the application decides what it means.** On a
37
+ * scale-to-zero platform this is the only window to flush queued spans before the
38
+ * container dies — but the provider belongs to the application, which may share it with
39
+ * a worker or a scheduled job still running. Tearing down a resource the framework did
40
+ * not create would be presumptuous, and `TracerProvider` in `@opentelemetry/api`
41
+ * exposes no shutdown at all: only `getTracer` (runbook D8 as revised).
42
+ *
43
+ * ```ts
44
+ * onShutdown: () => provider.shutdown(),
45
+ * ```
46
+ *
47
+ * A callback that rejects is swallowed: losing telemetry is bad, failing to stop the
48
+ * server is worse.
49
+ */
50
+ readonly onShutdown?: () => Promise<void>;
51
+ }
52
+ /**
53
+ * Turns tracing on and says how.
54
+ *
55
+ * **Absent means off, and off is free.** Without this, no tracing middleware is
56
+ * installed, no span is ever created, and the log format is unchanged. A REST-only
57
+ * API that never asks for tracing behaves exactly as it did before (ADR-0005
58
+ * invariant 3, gate G3).
59
+ *
60
+ * **The application supplies the tracer, not the framework** (ADR-0005 A2). Core
61
+ * depends on `@opentelemetry/api`; the SDK, its exporters and any credentials belong
62
+ * to the application, which builds a provider and passes it here.
63
+ */
64
+ export declare class TracingOptions {
65
+ readonly tracerProvider: TracerProvider;
66
+ readonly trustIncomingTraceContext: boolean;
67
+ readonly instrumentationName: string;
68
+ readonly traceFieldFormatter?: TraceFieldFormatter;
69
+ readonly onShutdown?: () => Promise<void>;
70
+ private readonly propagators?;
71
+ constructor(init: TracingOptionsInit);
72
+ /** The propagation policy these options describe. */
73
+ get policy(): PropagationPolicy;
74
+ /** The tracer the host instruments with. */
75
+ get tracer(): Tracer;
76
+ }
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TracingOptions = void 0;
4
+ const propagationPolicy_1 = require("./propagationPolicy");
5
+ /**
6
+ * Turns tracing on and says how.
7
+ *
8
+ * **Absent means off, and off is free.** Without this, no tracing middleware is
9
+ * installed, no span is ever created, and the log format is unchanged. A REST-only
10
+ * API that never asks for tracing behaves exactly as it did before (ADR-0005
11
+ * invariant 3, gate G3).
12
+ *
13
+ * **The application supplies the tracer, not the framework** (ADR-0005 A2). Core
14
+ * depends on `@opentelemetry/api`; the SDK, its exporters and any credentials belong
15
+ * to the application, which builds a provider and passes it here.
16
+ */
17
+ class TracingOptions {
18
+ tracerProvider;
19
+ trustIncomingTraceContext;
20
+ instrumentationName;
21
+ traceFieldFormatter;
22
+ onShutdown;
23
+ propagators;
24
+ constructor(init) {
25
+ this.tracerProvider = init.tracerProvider;
26
+ this.propagators = init.propagators;
27
+ this.trustIncomingTraceContext = init.trustIncomingTraceContext ?? true;
28
+ this.instrumentationName = init.instrumentationName ?? 'modular_api';
29
+ this.traceFieldFormatter = init.traceFieldFormatter;
30
+ this.onShutdown = init.onShutdown;
31
+ }
32
+ /** The propagation policy these options describe. */
33
+ get policy() {
34
+ return new propagationPolicy_1.PropagationPolicy({
35
+ ...(this.propagators === undefined ? {} : { propagators: this.propagators }),
36
+ trustIncomingTraceContext: this.trustIncomingTraceContext,
37
+ });
38
+ }
39
+ /** The tracer the host instruments with. */
40
+ get tracer() {
41
+ return this.tracerProvider.getTracer(this.instrumentationName);
42
+ }
43
+ }
44
+ exports.TracingOptions = TracingOptions;
@@ -0,0 +1,31 @@
1
+ import { type Context, type TextMapGetter, type TextMapPropagator, type TextMapSetter } from '@opentelemetry/api';
2
+ /** The W3C `traceparent` carrier key. */
3
+ export declare const TRACEPARENT_HEADER = "traceparent";
4
+ /** The W3C `tracestate` carrier key. */
5
+ export declare const TRACESTATE_HEADER = "tracestate";
6
+ /**
7
+ * Propagates W3C Trace Context: `traceparent` and `tracestate`.
8
+ *
9
+ * This is ours because `@opentelemetry/api` does not ship a propagator — the W3C
10
+ * implementation lives in `@opentelemetry/core`, which is past the API boundary
11
+ * that ADR-0005 A2 draws and which the Stage 1b dependency guard forbids
12
+ * (runbook D26). Python's official API package includes an equivalent, and that
13
+ * implementation is the reference these cases are checked against.
14
+ *
15
+ * The format is exact: 55 characters, `00-<trace id>-<parent span id>-<flags>`,
16
+ * lowercase hex only, version `00` the only one defined. Anything else is
17
+ * rejected, and rejection means *return the context unchanged* — a broken header
18
+ * from an upstream caller must never fail a request.
19
+ *
20
+ * `tracestate` is carried verbatim and never interpreted (runbook D4). This
21
+ * implementation is more faithful to that than the Dart one can be: the
22
+ * JavaScript API's `createTraceState` accepts the raw header string, so ordering
23
+ * and formatting survive untouched, whereas the Dart API only accepts a map.
24
+ *
25
+ * The Dart counterpart is `lib/src/core/tracing/w3c_trace_context_propagator.dart`.
26
+ */
27
+ export declare class W3CTraceContextPropagator implements TextMapPropagator<unknown> {
28
+ fields(): string[];
29
+ inject(context: Context, carrier: unknown, setter: TextMapSetter<unknown>): void;
30
+ extract(context: Context, carrier: unknown, getter: TextMapGetter<unknown>): Context;
31
+ }
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.W3CTraceContextPropagator = exports.TRACESTATE_HEADER = exports.TRACEPARENT_HEADER = void 0;
4
+ const api_1 = require("@opentelemetry/api");
5
+ /** The W3C `traceparent` carrier key. */
6
+ exports.TRACEPARENT_HEADER = 'traceparent';
7
+ /** The W3C `tracestate` carrier key. */
8
+ exports.TRACESTATE_HEADER = 'tracestate';
9
+ /** The only version currently defined by the W3C Trace Context recommendation. */
10
+ const SUPPORTED_VERSION = '00';
11
+ /** Reserved by the specification and never valid. */
12
+ const FORBIDDEN_VERSION = 'ff';
13
+ /**
14
+ * The 55 characters every version must begin with:
15
+ * `<version>-<32 hex>-<16 hex>-<2 hex>`, lowercase only, fixed-width fields.
16
+ *
17
+ * Deliberately **not** anchored at the end. A future version may append fields, and
18
+ * the specification requires parsing the known prefix rather than rejecting the
19
+ * header — see `extract`.
20
+ */
21
+ const TRACEPARENT_PATTERN = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})/;
22
+ /**
23
+ * Propagates W3C Trace Context: `traceparent` and `tracestate`.
24
+ *
25
+ * This is ours because `@opentelemetry/api` does not ship a propagator — the W3C
26
+ * implementation lives in `@opentelemetry/core`, which is past the API boundary
27
+ * that ADR-0005 A2 draws and which the Stage 1b dependency guard forbids
28
+ * (runbook D26). Python's official API package includes an equivalent, and that
29
+ * implementation is the reference these cases are checked against.
30
+ *
31
+ * The format is exact: 55 characters, `00-<trace id>-<parent span id>-<flags>`,
32
+ * lowercase hex only, version `00` the only one defined. Anything else is
33
+ * rejected, and rejection means *return the context unchanged* — a broken header
34
+ * from an upstream caller must never fail a request.
35
+ *
36
+ * `tracestate` is carried verbatim and never interpreted (runbook D4). This
37
+ * implementation is more faithful to that than the Dart one can be: the
38
+ * JavaScript API's `createTraceState` accepts the raw header string, so ordering
39
+ * and formatting survive untouched, whereas the Dart API only accepts a map.
40
+ *
41
+ * The Dart counterpart is `lib/src/core/tracing/w3c_trace_context_propagator.dart`.
42
+ */
43
+ class W3CTraceContextPropagator {
44
+ fields() {
45
+ return [exports.TRACEPARENT_HEADER, exports.TRACESTATE_HEADER];
46
+ }
47
+ inject(context, carrier, setter) {
48
+ const spanContext = api_1.trace.getSpanContext(context);
49
+ if (spanContext === undefined)
50
+ return;
51
+ if (!(0, api_1.isValidTraceId)(spanContext.traceId) || !(0, api_1.isValidSpanId)(spanContext.spanId))
52
+ return;
53
+ const flags = (spanContext.traceFlags & api_1.TraceFlags.SAMPLED) === api_1.TraceFlags.SAMPLED ? '01' : '00';
54
+ setter.set(carrier, exports.TRACEPARENT_HEADER, `${SUPPORTED_VERSION}-${spanContext.traceId}-${spanContext.spanId}-${flags}`);
55
+ // Only when there is something to carry. An empty tracestate is a header that
56
+ // says nothing.
57
+ const serialized = spanContext.traceState?.serialize();
58
+ if (serialized !== undefined && serialized.length > 0) {
59
+ setter.set(carrier, exports.TRACESTATE_HEADER, serialized);
60
+ }
61
+ }
62
+ extract(context, carrier, getter) {
63
+ try {
64
+ const raw = first(getter.get(carrier, exports.TRACEPARENT_HEADER));
65
+ if (raw === undefined || raw.length === 0)
66
+ return context;
67
+ const match = TRACEPARENT_PATTERN.exec(raw);
68
+ if (match === null)
69
+ return context;
70
+ const [matched, version, traceId, spanId, flagsHex] = match;
71
+ // `ff` is reserved and never valid.
72
+ if (version === FORBIDDEN_VERSION)
73
+ return context;
74
+ // A *future* version must be parsed, not rejected: the specification says an
75
+ // implementation should read the known 55-character prefix and ignore what
76
+ // follows. Rejecting it would mean that the day W3C publishes version 01,
77
+ // every service running this code silently stops honouring incoming trace
78
+ // context — the failure would look like tracing simply not working.
79
+ //
80
+ // Verified against the official Python implementation, which accepts `01-…`
81
+ // and `01-…-extra` and rejects `00-…-extra`.
82
+ if (version === SUPPORTED_VERSION) {
83
+ // Version 00 is exactly 55 characters; trailing data is malformed.
84
+ if (raw.length !== matched.length)
85
+ return context;
86
+ }
87
+ else if (raw.length > matched.length && raw[matched.length] !== '-') {
88
+ // A newer version's extra fields must be delimited.
89
+ return context;
90
+ }
91
+ if (!(0, api_1.isValidTraceId)(traceId) || !(0, api_1.isValidSpanId)(spanId))
92
+ return context;
93
+ // Bit 0 is `sampled`. Unknown bits must not defeat the one we understand.
94
+ const flags = Number.parseInt(flagsHex, 16);
95
+ const sampled = (flags & api_1.TraceFlags.SAMPLED) === api_1.TraceFlags.SAMPLED;
96
+ const rawState = first(getter.get(carrier, exports.TRACESTATE_HEADER));
97
+ return api_1.trace.setSpanContext(context, {
98
+ traceId,
99
+ spanId,
100
+ traceFlags: sampled ? api_1.TraceFlags.SAMPLED : api_1.TraceFlags.NONE,
101
+ isRemote: true,
102
+ // Verbatim: the raw header goes in untouched (D4).
103
+ traceState: rawState !== undefined && rawState.trim().length > 0
104
+ ? (0, api_1.createTraceState)(rawState)
105
+ : undefined,
106
+ });
107
+ }
108
+ catch {
109
+ return context;
110
+ }
111
+ }
112
+ }
113
+ exports.W3CTraceContextPropagator = W3CTraceContextPropagator;
114
+ /** This API's getter may return a single value or a list. */
115
+ function first(value) {
116
+ return Array.isArray(value) ? value[0] : value;
117
+ }
@@ -37,7 +37,7 @@ export declare abstract class Input {
37
37
  * - `"Missing required field: {name}"`
38
38
  * - `"Field '{name}' must be of type {type}"`
39
39
  */
40
- static validateJson(json: Record<string, unknown>, targetClass: abstract new (...args: unknown[]) => unknown): void;
40
+ static validateJson(json: Record<string, unknown>, targetClass: abstract new (...args: never[]) => unknown): void;
41
41
  }
42
42
  /**
43
43
  * **Contract** — use `extends Output`.