@xovris/node 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ import { type Client, type Send } from '@xovris/core';
2
+ export interface NodeOptions {
3
+ url?: string | undefined;
4
+ key?: string | undefined;
5
+ release?: string | undefined;
6
+ environment?: string | undefined;
7
+ send?: Send;
8
+ }
9
+ export declare function init(o?: NodeOptions, proc?: NodeJS.Process): Client;
10
+ export declare function installProcessHandlers(c: Client, proc?: NodeJS.Process): void;
11
+ export declare function captureException(err: unknown, o?: Parameters<Client['captureException']>[1]): string | null;
12
+ /** Sends every pending error and finished span; resolves false if errors were still in flight at the timeout. */
13
+ export declare function flush(timeoutMs?: number): Promise<boolean>;
14
+ /** Tests only: forget the process-wide client. */
15
+ export declare function resetForTests(): void;
16
+ export { startTracing, tracingState, xovrisSpanProcessor, type TracingState } from './otel.ts';
package/dist/index.js ADDED
@@ -0,0 +1,64 @@
1
+ // @xovris/node (ADR 0011): errors from a Node.js server sent to Xovris, configured from the two variables the wizard
2
+ // writes. Process handlers keep Node's own behaviour: an uncaught error or rejection still ends the process (after the
3
+ // event is flushed) unless the app has its own handler - Xovris observes, it never changes how the app fails.
4
+ // The client is process-wide, shared by every copy of this package, so loading Xovris twice never sends twice.
5
+ import { createClient, environmentFrom, releaseFrom } from '@xovris/core';
6
+ import { activeTraceContext, flushTraces, withoutTracing } from './otel.js';
7
+ const SHARED = Symbol.for('xovris.node.v1');
8
+ function shared() {
9
+ const g = globalThis;
10
+ return (g[SHARED] ??= { client: null, handlers: new WeakSet() });
11
+ }
12
+ const fetchSend = (url, init) => withoutTracing(() => fetch(url, init)).then((r) => {
13
+ const ra = Number(r.headers.get('retry-after'));
14
+ return { status: r.status, ...(Number.isFinite(ra) && ra > 0 ? { retryAfterSeconds: ra } : {}) };
15
+ });
16
+ export function init(o = {}, proc = process) {
17
+ const s = shared();
18
+ if (s.client)
19
+ return s.client;
20
+ const client = createClient({
21
+ url: o.url ?? proc.env.XOVRIS_INGEST_URL, key: o.key ?? proc.env.XOVRIS_INGEST_KEY,
22
+ release: o.release ?? releaseFrom(proc.env), environment: o.environment ?? environmentFrom(proc.env), platform: 'node',
23
+ send: o.send ?? fetchSend, traceContext: activeTraceContext,
24
+ });
25
+ s.client = client;
26
+ // The edge runtime has no process events; there the client reports what it is handed and nothing more.
27
+ if (client.enabled && typeof proc?.on === 'function')
28
+ installProcessHandlers(client, proc);
29
+ return client;
30
+ }
31
+ export function installProcessHandlers(c, proc = process) {
32
+ // One set of handlers per process object, whoever calls this.
33
+ const s = shared();
34
+ if (s.handlers.has(proc))
35
+ return;
36
+ s.handlers.add(proc);
37
+ proc.on('uncaughtException', (err) => {
38
+ c.captureException(err, { handled: false, mechanism: 'onuncaughtexception', level: 'fatal' });
39
+ if (proc.listenerCount('uncaughtException') <= 1) {
40
+ console.error(err);
41
+ void Promise.all([c.flush(2000), flushTraces()]).finally(() => proc.exit(1));
42
+ }
43
+ });
44
+ proc.on('unhandledRejection', (reason) => {
45
+ c.captureException(reason, { handled: false, mechanism: 'onunhandledrejection' });
46
+ // Node's default for an unhandled rejection is to crash; adding a listener would silently stop that, so keep it.
47
+ if (proc.listenerCount('unhandledRejection') <= 1) {
48
+ console.error(reason);
49
+ void Promise.all([c.flush(2000), flushTraces()]).finally(() => proc.exit(1));
50
+ }
51
+ });
52
+ }
53
+ export function captureException(err, o) {
54
+ return init().captureException(err, o);
55
+ }
56
+ /** Sends every pending error and finished span; resolves false if errors were still in flight at the timeout. */
57
+ export async function flush(timeoutMs) {
58
+ const c = shared().client;
59
+ const [ok] = await Promise.all([c ? c.flush(timeoutMs) : Promise.resolve(true), flushTraces()]);
60
+ return ok;
61
+ }
62
+ /** Tests only: forget the process-wide client. */
63
+ export function resetForTests() { const s = shared(); s.client = null; s.handlers = new WeakSet(); }
64
+ export { startTracing, tracingState, xovrisSpanProcessor } from './otel.js';
package/dist/otel.d.ts ADDED
@@ -0,0 +1,109 @@
1
+ import { type Context } from '@opentelemetry/api';
2
+ import { defaultResource } from '@opentelemetry/resources';
3
+ import { type ReadableSpan, type Span, type SpanExporter, type SpanProcessor } from '@opentelemetry/sdk-trace-base';
4
+ type Env = Record<string, string | undefined>;
5
+ export interface TraceOptions {
6
+ url?: string | undefined;
7
+ key?: string | undefined;
8
+ /** Where this processor was added, named in the duplicate warning ("registerOTel in instrumentation.ts"). */
9
+ source?: string;
10
+ env?: Env;
11
+ /** Tests and custom pipelines: export somewhere other than Xovris's OTLP endpoint. */
12
+ exporter?: SpanExporter;
13
+ warn?: (message: string) => void;
14
+ }
15
+ export type TracingState = {
16
+ mode: 'own';
17
+ source: string;
18
+ } | {
19
+ mode: 'adopted';
20
+ via: 'configuration' | 'runtime' | 'environment' | 'sentry';
21
+ source: string;
22
+ } | {
23
+ mode: 'stood_down';
24
+ reason: string;
25
+ next: string;
26
+ } | {
27
+ mode: 'off';
28
+ reason: string;
29
+ };
30
+ /** True when the app's own OTLP exporter variables already point at the Xovris ingest host - adding Xovris again
31
+ * would send every span twice. */
32
+ export declare function envExportsToXovris(env: Env, ingestUrl: string | undefined): boolean;
33
+ /** One more span processor for an existing OpenTelemetry setup: batches spans to Xovris's OTLP endpoint with the
34
+ * ingestion key in a header (never the URL). Two of them on one provider send each span once, and say so. */
35
+ export declare class XovrisSpanProcessor implements SpanProcessor {
36
+ readonly source: string;
37
+ readonly enabled: boolean;
38
+ readonly reason: string | null;
39
+ private readonly inner;
40
+ private readonly warn;
41
+ constructor(o?: TraceOptions);
42
+ onStart(span: Span, parentContext: Context): void;
43
+ onEnd(span: ReadableSpan): void;
44
+ forceFlush(): Promise<void>;
45
+ shutdown(): Promise<void>;
46
+ }
47
+ /** The processor the wizard writes into an existing setup: `spanProcessors: ['auto', xovrisSpanProcessor()]`. */
48
+ export declare function xovrisSpanProcessor(o?: TraceOptions): XovrisSpanProcessor;
49
+ /** NodeSDK configured with a `traceExporter` only: the wizard keeps that exporter exactly and adds Xovris beside it. */
50
+ export declare function batchFor(exporter: SpanExporter): SpanProcessor;
51
+ interface LiveProvider {
52
+ constructor?: {
53
+ name?: string;
54
+ };
55
+ addSpanProcessor?: (p: SpanProcessor) => void;
56
+ _activeSpanProcessor?: {
57
+ _spanProcessors?: SpanProcessor[];
58
+ };
59
+ }
60
+ export declare function liveTracerProvider(): LiveProvider | null;
61
+ /** Joins a provider that is already running: the SDK 1.x public method, or the SDK 2.x processor list (the 2.x
62
+ * provider takes processors only in its constructor). Returns false when the provider has neither - it is not an
63
+ * OpenTelemetry SDK provider (Sentry's own, for one), so Xovris stands down rather than start a rival. */
64
+ export declare function joinLiveProvider(provider: LiveProvider, p: SpanProcessor): boolean;
65
+ /** Sentry's client as the app runs it, read from Sentry's own global carrier (version 8 and later) - Xovris never imports Sentry. */
66
+ export interface SentryClientLike {
67
+ on: (hook: 'spanEnd', cb: (span: unknown) => void) => unknown;
68
+ }
69
+ export declare function liveSentryClient(): SentryClientLike | null;
70
+ /** A finished Sentry span as Sentry itself writes it (spanToJSON / getSpanJSON). */
71
+ export interface SentrySpanJson {
72
+ name?: string;
73
+ description?: string;
74
+ op?: string;
75
+ span_id: string;
76
+ trace_id: string;
77
+ parent_span_id?: string;
78
+ start_timestamp: number;
79
+ timestamp?: number;
80
+ end_timestamp?: number;
81
+ status?: string;
82
+ data?: Record<string, unknown>;
83
+ attributes?: Record<string, unknown>;
84
+ }
85
+ /** One Sentry span as the OpenTelemetry span the OTLP exporter sends: the same trace and span ids, parent, times, status and attributes. */
86
+ export declare function sentrySpanToReadable(j: SentrySpanJson, resource: ReturnType<typeof defaultResource>): ReadableSpan;
87
+ /** G105.01.C191 (#248): Sentry stays the app's tracer and keeps its spans; Xovris reads each one as it ends (the client's own spanEnd
88
+ * hook, Sentry 8 and later) and sends it over OTLP - nothing to change in the app, no second SDK. Once per process. */
89
+ export declare function rideSentry(client: SentryClientLike, o: TraceOptions, resource: ReturnType<typeof defaultResource>): boolean;
90
+ /** Decides, once per process, how this app's traces reach Xovris. Never registers a provider when one is live. */
91
+ export declare function decideTracing(o?: TraceOptions): TracingState;
92
+ /** Starts tracing after the code that loaded Xovris has finished its own start-up, so a setup registered on the same
93
+ * start-up path (registerOTel after this import, a NodeSDK started next) always wins and Xovris joins it. */
94
+ export declare function startTracing(o?: TraceOptions & {
95
+ defer?: boolean;
96
+ }): Promise<TracingState>;
97
+ export declare function tracingState(): TracingState | null;
98
+ /** Sends every finished span now (before a serverless function freezes, or at shutdown). */
99
+ export declare function flushTraces(): Promise<void>;
100
+ /** The active span, so an error event names the trace it happened in. */
101
+ export declare function activeTraceContext(): {
102
+ trace_id: string;
103
+ span_id: string;
104
+ } | undefined;
105
+ /** Runs Xovris's own network calls with tracing suppressed, so sending an error never creates a span to send. */
106
+ export declare function withoutTracing<T>(work: () => T): T;
107
+ /** Tests only: forget the process-wide decision and any provider Xovris registered. */
108
+ export declare function resetTracingForTests(): Promise<void>;
109
+ export {};
package/dist/otel.js ADDED
@@ -0,0 +1,262 @@
1
+ // @xovris/node/otel (D01.02.01): traces reach Xovris over OTLP without ever starting a second tracing SDK. If the app
2
+ // already runs OpenTelemetry (@vercel/otel, NodeSDK, its own provider), Xovris joins it as one more span processor -
3
+ // written into that setup by the wizard as a reviewable change, or joined at start-up - and only when nothing is
4
+ // running does Xovris register a provider of its own. Every span is sent once, however many times Xovris is added.
5
+ import { SpanKind, SpanStatusCode, TraceFlags, context, diag, trace } from '@opentelemetry/api';
6
+ import { suppressTracing } from '@opentelemetry/core';
7
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
8
+ import { defaultResource, resourceFromAttributes } from '@opentelemetry/resources';
9
+ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
10
+ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
11
+ import { ERRORS_VIA_ENVELOPE, environmentFrom, otlpTracesUrl, projectIdFrom, releaseFrom } from '@xovris/core';
12
+ const REGISTRY = Symbol.for('xovris.otel.v1');
13
+ function registry() {
14
+ const g = globalThis;
15
+ return (g[REGISTRY] ??= { processors: [], claimed: new WeakSet(), state: null, warned: new Set(), own: null });
16
+ }
17
+ const defaultWarn = (m) => console.warn(`[xovris] ${m}`);
18
+ function warnOnce(key, message, warn = defaultWarn) {
19
+ const r = registry();
20
+ if (r.warned.has(key))
21
+ return;
22
+ r.warned.add(key);
23
+ warn(message);
24
+ }
25
+ /** True when the app's own OTLP exporter variables already point at the Xovris ingest host - adding Xovris again
26
+ * would send every span twice. */
27
+ export function envExportsToXovris(env, ingestUrl) {
28
+ if (!ingestUrl)
29
+ return false;
30
+ const target = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? env.OTEL_EXPORTER_OTLP_ENDPOINT;
31
+ if (!target)
32
+ return false;
33
+ try {
34
+ return new URL(target).host === new URL(ingestUrl).host;
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ /** One more span processor for an existing OpenTelemetry setup: batches spans to Xovris's OTLP endpoint with the
41
+ * ingestion key in a header (never the URL). Two of them on one provider send each span once, and say so. */
42
+ export class XovrisSpanProcessor {
43
+ source;
44
+ enabled;
45
+ reason;
46
+ inner;
47
+ warn;
48
+ constructor(o = {}) {
49
+ const env = o.env ?? process.env;
50
+ const url = o.url ?? env.XOVRIS_INGEST_URL;
51
+ const key = o.key ?? env.XOVRIS_INGEST_KEY;
52
+ const endpoint = url ? otlpTracesUrl(url) : null;
53
+ this.source = o.source ?? 'your OpenTelemetry setup';
54
+ this.warn = o.warn ?? defaultWarn;
55
+ if (!endpoint || !key) {
56
+ this.inner = null;
57
+ this.reason = 'No ingest address or key is set, so traces are not sent. Run the wizard: it writes both.';
58
+ }
59
+ else if (envExportsToXovris(env, url)) {
60
+ this.inner = null;
61
+ this.reason = 'Your OpenTelemetry exporter variables already send traces to Xovris, so this processor stays idle and each span arrives once.';
62
+ warnOnce('env-duplicate', this.reason, this.warn);
63
+ }
64
+ else {
65
+ this.reason = null;
66
+ this.inner = new BatchSpanProcessor(o.exporter ?? new OTLPTraceExporter({ url: endpoint, headers: { 'x-xovris-key': key, ...ERRORS_VIA_ENVELOPE }, timeoutMillis: 10_000 }));
67
+ }
68
+ this.enabled = this.inner !== null;
69
+ registry().processors.push(this);
70
+ }
71
+ onStart(span, parentContext) { this.inner?.onStart(span, parentContext); }
72
+ onEnd(span) {
73
+ if (!this.inner)
74
+ return;
75
+ const r = registry();
76
+ if (r.claimed.has(span)) {
77
+ const first = r.processors.find((p) => p.enabled && p !== this);
78
+ warnOnce('processor-duplicate', `Xovris is added to this app's OpenTelemetry setup twice (${first?.source ?? 'another place'} and ${this.source}). Each span is sent once; remove one of them - npx xovris remove undoes the one the wizard added.`, this.warn);
79
+ return;
80
+ }
81
+ r.claimed.add(span);
82
+ this.inner.onEnd(span);
83
+ }
84
+ forceFlush() { return this.inner?.forceFlush() ?? Promise.resolve(); }
85
+ shutdown() { return this.inner?.shutdown() ?? Promise.resolve(); }
86
+ }
87
+ /** The processor the wizard writes into an existing setup: `spanProcessors: ['auto', xovrisSpanProcessor()]`. */
88
+ export function xovrisSpanProcessor(o = {}) {
89
+ return new XovrisSpanProcessor(o);
90
+ }
91
+ /** NodeSDK configured with a `traceExporter` only: the wizard keeps that exporter exactly and adds Xovris beside it. */
92
+ export function batchFor(exporter) {
93
+ return new BatchSpanProcessor(exporter);
94
+ }
95
+ // The API keeps one registry per major version on the global object, shared by every copy of @opentelemetry/api in the
96
+ // process - the only reliable way to ask "is a tracer provider already registered?" across bundled copies.
97
+ const OTEL_API_GLOBAL = Symbol.for('opentelemetry.js.api.1');
98
+ export function liveTracerProvider() {
99
+ const api = globalThis[OTEL_API_GLOBAL];
100
+ if (!api?.trace)
101
+ return null;
102
+ const p = api.trace;
103
+ return (typeof p.getDelegate === 'function' ? p.getDelegate() : p);
104
+ }
105
+ /** Joins a provider that is already running: the SDK 1.x public method, or the SDK 2.x processor list (the 2.x
106
+ * provider takes processors only in its constructor). Returns false when the provider has neither - it is not an
107
+ * OpenTelemetry SDK provider (Sentry's own, for one), so Xovris stands down rather than start a rival. */
108
+ export function joinLiveProvider(provider, p) {
109
+ if (typeof provider.addSpanProcessor === 'function') {
110
+ provider.addSpanProcessor(p);
111
+ return true;
112
+ }
113
+ const list = provider._activeSpanProcessor?._spanProcessors;
114
+ if (Array.isArray(list)) {
115
+ list.push(p);
116
+ return true;
117
+ }
118
+ return false;
119
+ }
120
+ export function liveSentryClient() {
121
+ const carrier = globalThis.__SENTRY__;
122
+ if (!carrier)
123
+ return null;
124
+ const box = (typeof carrier.version === 'string' ? carrier[carrier.version] : carrier);
125
+ const scope = (box?.defaultCurrentScope ?? box?.stack?.getStackTop?.()?.scope);
126
+ const client = scope?.getClient?.();
127
+ return client && typeof client.on === 'function' ? client : null;
128
+ }
129
+ const SENTRY_KIND = { 'http.server': SpanKind.SERVER, 'http.client': SpanKind.CLIENT, 'queue.publish': SpanKind.PRODUCER, 'queue.process': SpanKind.CONSUMER };
130
+ const hrOf = (sec) => { const whole = Math.floor(sec); return [whole, Math.round((sec - whole) * 1e9)]; };
131
+ const plainAttrs = (o) => Object.fromEntries(Object.entries(o ?? {}).filter(([, v]) => ['string', 'number', 'boolean'].includes(typeof v) || (Array.isArray(v) && v.every((x) => ['string', 'number', 'boolean'].includes(typeof x)))));
132
+ /** One Sentry span as the OpenTelemetry span the OTLP exporter sends: the same trace and span ids, parent, times, status and attributes. */
133
+ export function sentrySpanToReadable(j, resource) {
134
+ const end = j.end_timestamp ?? j.timestamp ?? j.start_timestamp;
135
+ const ctx = { traceId: j.trace_id, spanId: j.span_id, traceFlags: TraceFlags.SAMPLED };
136
+ const parent = j.parent_span_id ? { traceId: j.trace_id, spanId: j.parent_span_id, traceFlags: TraceFlags.SAMPLED } : undefined;
137
+ const op = j.op ?? (typeof j.attributes?.['sentry.op'] === 'string' ? j.attributes['sentry.op'] : undefined);
138
+ const ms = Math.max(0, end - j.start_timestamp);
139
+ return {
140
+ name: j.description ?? j.name ?? op ?? 'span', kind: (op && SENTRY_KIND[op]) ?? SpanKind.INTERNAL, spanContext: () => ctx, parentSpanContext: parent, parentSpanId: parent?.spanId,
141
+ startTime: hrOf(j.start_timestamp), endTime: hrOf(end), duration: hrOf(ms), ended: true,
142
+ status: { code: !j.status || j.status === 'ok' ? SpanStatusCode.UNSET : SpanStatusCode.ERROR, ...(j.status && j.status !== 'ok' ? { message: j.status } : {}) },
143
+ attributes: { ...plainAttrs(j.data), ...plainAttrs(j.attributes), ...(op ? { 'sentry.op': op } : {}) }, links: [], events: [], resource,
144
+ instrumentationScope: { name: '@xovris/node (Sentry spans)' }, instrumentationLibrary: { name: '@xovris/node (Sentry spans)' }, droppedAttributesCount: 0, droppedEventsCount: 0, droppedLinksCount: 0,
145
+ };
146
+ }
147
+ function resourceOf(env, url) {
148
+ const release = releaseFrom(env);
149
+ const environment = environmentFrom(env);
150
+ const projectId = projectIdFrom(url);
151
+ return defaultResource().merge(resourceFromAttributes({
152
+ 'service.name': env.OTEL_SERVICE_NAME ?? env.npm_package_name ?? 'app',
153
+ ...(release ? { 'service.version': release } : {}),
154
+ ...(environment ? { 'deployment.environment.name': environment } : {}),
155
+ ...(projectId ? { 'xovris.project_id': projectId } : {}),
156
+ }));
157
+ }
158
+ /** G105.01.C191 (#248): Sentry stays the app's tracer and keeps its spans; Xovris reads each one as it ends (the client's own spanEnd
159
+ * hook, Sentry 8 and later) and sends it over OTLP - nothing to change in the app, no second SDK. Once per process. */
160
+ export function rideSentry(client, o, resource) {
161
+ const r = registry();
162
+ if (r.sentry)
163
+ return true;
164
+ const p = new XovrisSpanProcessor({ ...o, source: "Sentry's own spans" });
165
+ if (!p.enabled)
166
+ return false;
167
+ client.on('spanEnd', (span) => {
168
+ const j = span.getSpanJSON?.();
169
+ if (j?.trace_id && j.span_id && typeof j.start_timestamp === 'number')
170
+ p.onEnd(sentrySpanToReadable(j, resource));
171
+ });
172
+ r.sentry = true;
173
+ return true;
174
+ }
175
+ /** Decides, once per process, how this app's traces reach Xovris. Never registers a provider when one is live. */
176
+ export function decideTracing(o = {}) {
177
+ const r = registry();
178
+ if (r.state)
179
+ return r.state;
180
+ const env = o.env ?? process.env;
181
+ const url = o.url ?? env.XOVRIS_INGEST_URL;
182
+ const key = o.key ?? env.XOVRIS_INGEST_KEY;
183
+ const set = (s) => (r.state = s);
184
+ if ((env.XOVRIS_TRACES ?? '').toLowerCase() === 'off')
185
+ return set({ mode: 'off', reason: 'XOVRIS_TRACES=off is set, so only errors are sent.' }); // own setting: the customer's SDK variable
186
+ if (!url || !key || !otlpTracesUrl(url))
187
+ return set({ mode: 'off', reason: 'No ingest address or key is set, so traces are not sent. Run the wizard: it writes both.' });
188
+ if (envExportsToXovris(env, url))
189
+ return set({ mode: 'adopted', via: 'environment', source: 'OTEL_EXPORTER_OTLP_ENDPOINT' });
190
+ const live = liveTracerProvider();
191
+ if (live) {
192
+ const configured = r.processors.find((p) => p.enabled);
193
+ if (configured)
194
+ return set({ mode: 'adopted', via: 'configuration', source: configured.source });
195
+ if (joinLiveProvider(live, new XovrisSpanProcessor({ ...o, source: 'joined at start-up' })))
196
+ return set({ mode: 'adopted', via: 'runtime', source: 'joined at start-up' });
197
+ const sentry = /sentry/i.test(live.constructor?.name ?? '');
198
+ const client = liveSentryClient();
199
+ if (client && rideSentry(client, o, resourceOf(env, url)))
200
+ return set({ mode: 'adopted', via: 'sentry', source: "Sentry's own spans, read as each one ends" });
201
+ const state = sentry
202
+ ? { mode: 'stood_down', reason: "Sentry's SDK is this app's tracer, and this version (before 8) lets nothing else read its spans.", next: 'Errors still reach Xovris. npx xovris init brings the traces too - Xovris writes the change to point your Sentry DSN at Xovris, and no second SDK is installed. Do it yourself instead: upgrade Sentry to version 8 or later and Xovris reads its spans by itself.' }
203
+ : { mode: 'stood_down', reason: `Another tracer (${live.constructor?.name ?? 'unknown'}) is already running and does not accept another processor.`, next: 'Errors still reach Xovris. Run npx xovris init in this project to add Xovris to that tracer as a reviewable change.' };
204
+ warnOnce('stood-down', `${state.reason} ${state.next}`, o.warn);
205
+ return set(state);
206
+ }
207
+ const release = releaseFrom(env);
208
+ const environment = environmentFrom(env);
209
+ const projectId = projectIdFrom(url);
210
+ const provider = new NodeTracerProvider({
211
+ resource: defaultResource().merge(resourceFromAttributes({
212
+ 'service.name': env.OTEL_SERVICE_NAME ?? env.npm_package_name ?? 'app',
213
+ ...(release ? { 'service.version': release } : {}),
214
+ ...(environment ? { 'deployment.environment.name': environment } : {}),
215
+ ...(projectId ? { 'xovris.project_id': projectId } : {}),
216
+ })),
217
+ spanProcessors: [new XovrisSpanProcessor({ ...o, source: 'Xovris (no other tracer was running)' })],
218
+ });
219
+ provider.register();
220
+ r.own = provider;
221
+ // Sentry 10+ traces without OpenTelemetry: its spans are read too, so the app's own instrumentation reaches Xovris as well
222
+ const sentryClient = liveSentryClient();
223
+ if (sentryClient && rideSentry(sentryClient, o, resourceOf(env, url)))
224
+ return set({ mode: 'own', source: "Xovris (no other tracer was running), with Sentry's own spans read as each one ends" });
225
+ return set({ mode: 'own', source: 'Xovris (no other tracer was running)' });
226
+ }
227
+ /** Starts tracing after the code that loaded Xovris has finished its own start-up, so a setup registered on the same
228
+ * start-up path (registerOTel after this import, a NodeSDK started next) always wins and Xovris joins it. */
229
+ export function startTracing(o = {}) {
230
+ if (o.defer === false)
231
+ return Promise.resolve(decideTracing(o));
232
+ return new Promise((resolve) => setImmediate(() => resolve(decideTracing(o))));
233
+ }
234
+ export function tracingState() { return registry().state; }
235
+ /** Sends every finished span now (before a serverless function freezes, or at shutdown). */
236
+ export async function flushTraces() {
237
+ await Promise.all(registry().processors.map((p) => p.forceFlush().catch(() => undefined)));
238
+ }
239
+ /** The active span, so an error event names the trace it happened in. */
240
+ export function activeTraceContext() {
241
+ const c = trace.getActiveSpan()?.spanContext();
242
+ return c && /^[0-9a-f]{32}$/.test(c.traceId) && !/^0+$/.test(c.traceId) ? { trace_id: c.traceId, span_id: c.spanId } : undefined;
243
+ }
244
+ /** Runs Xovris's own network calls with tracing suppressed, so sending an error never creates a span to send. */
245
+ export function withoutTracing(work) {
246
+ return context.with(suppressTracing(context.active()), work);
247
+ }
248
+ /** Tests only: forget the process-wide decision and any provider Xovris registered. */
249
+ export async function resetTracingForTests() {
250
+ const r = registry();
251
+ const own = r.own;
252
+ r.processors.length = 0;
253
+ r.claimed = new WeakSet();
254
+ r.state = null;
255
+ r.warned.clear();
256
+ r.own = null;
257
+ if (own)
258
+ await own.shutdown().catch(() => undefined);
259
+ trace.disable();
260
+ context.disable();
261
+ diag.disable();
262
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ // Loaded first (node --import / --require, or Next.js's register()): starts Xovris from the wizard's variables - errors
2
+ // at once, traces after this start-up step so an OpenTelemetry setup registered next is joined, never replaced.
3
+ import { init } from './index.js';
4
+ import { startTracing } from './otel.js';
5
+ init();
6
+ void startTracing();
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@xovris/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Xovris for Node.js servers: errors from the wizard-written variables, process handlers that keep Node's own failure behaviour, and OTLP traces that join an existing OpenTelemetry setup instead of starting a second one (ADR 0011, D01.02.01).",
4
+ "version": "0.1.0",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ },
15
+ "./register": {
16
+ "types": "./dist/register.d.ts",
17
+ "import": "./dist/register.js"
18
+ },
19
+ "./otel": {
20
+ "types": "./dist/otel.d.ts",
21
+ "import": "./dist/otel.js"
22
+ }
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "dependencies": {
28
+ "@opentelemetry/api": "^1.9.1",
29
+ "@opentelemetry/core": "^2.12.0",
30
+ "@opentelemetry/exporter-trace-otlp-http": "^0.222.0",
31
+ "@opentelemetry/resources": "^2.12.0",
32
+ "@opentelemetry/sdk-trace-base": "^2.12.0",
33
+ "@opentelemetry/sdk-trace-node": "^2.12.0",
34
+ "@xovris/core": "0.1.0"
35
+ },
36
+ "devDependencies": {
37
+ "@opentelemetry/sdk-node": "^0.222.0",
38
+ "@sentry/node": "^11.6.0",
39
+ "@vercel/otel": "^2.1.3"
40
+ },
41
+ "homepage": "https://xovris.ai/developers/",
42
+ "engines": {
43
+ "node": ">=20"
44
+ },
45
+ "scripts": {
46
+ "build": "tsc -p tsconfig.build.json",
47
+ "typecheck": "tsc --noEmit -p .",
48
+ "test": "vitest run"
49
+ }
6
50
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.