@xovris/node 0.1.0 → 0.1.2

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,2 @@
1
+ /** The wizard's own variables from `<dir>/.env`, set where the process lacks them; returns the names it set. */
2
+ export declare function wizardEnv(dir?: string, env?: NodeJS.ProcessEnv): string[];
@@ -0,0 +1,26 @@
1
+ // D01.01.06.01 (the clean room's first Express run, 13 Nov 2026: the wizard wrote its address and key to the project's .env, the app was
2
+ // started as `npm start` starts it, and no event ever left it - nothing in a Node app reads a .env by itself): Xovris reads its OWN
3
+ // variables from the project's .env when the process was not given them, as the Go and Python setups read theirs. Only XOVRIS_
4
+ // variables are taken, never one the process already has, and nothing else of the file is loaded - the app's own environment is
5
+ // exactly as it was.
6
+ import { readFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { parseEnv } from 'node:util';
9
+ /** The wizard's own variables from `<dir>/.env`, set where the process lacks them; returns the names it set. */
10
+ export function wizardEnv(dir = process.cwd(), env = process.env) {
11
+ let text;
12
+ try {
13
+ text = readFileSync(join(dir, '.env'), 'utf8');
14
+ }
15
+ catch {
16
+ return [];
17
+ }
18
+ const set = [];
19
+ for (const [k, v] of Object.entries(parseEnv(text))) {
20
+ if (!k.startsWith('XOVRIS_') || env[k] !== undefined)
21
+ continue;
22
+ env[k] = v;
23
+ set.push(k);
24
+ }
25
+ return set;
26
+ }
package/dist/index.js CHANGED
@@ -2,8 +2,11 @@
2
2
  // writes. Process handlers keep Node's own behaviour: an uncaught error or rejection still ends the process (after the
3
3
  // event is flushed) unless the app has its own handler - Xovris observes, it never changes how the app fails.
4
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';
5
+ import { createClient, environmentFrom } from '@xovris/core';
6
+ import { wizardEnv } from './env-file.js';
7
+ import { releaseOf } from './release.js';
6
8
  import { activeTraceContext, flushTraces, withoutTracing } from './otel.js';
9
+ import { captureServerErrors } from './server-errors.js';
7
10
  const SHARED = Symbol.for('xovris.node.v1');
8
11
  function shared() {
9
12
  const g = globalThis;
@@ -13,19 +16,32 @@ const fetchSend = (url, init) => withoutTracing(() => fetch(url, init)).then((r)
13
16
  const ra = Number(r.headers.get('retry-after'));
14
17
  return { status: r.status, ...(Number.isFinite(ra) && ra > 0 ? { retryAfterSeconds: ra } : {}) };
15
18
  });
19
+ // the edge runtime's process has no working directory: its events carry only the release the host names
20
+ const cwdOf = (proc) => { try {
21
+ return typeof proc.cwd === 'function' ? proc.cwd() : undefined;
22
+ }
23
+ catch {
24
+ return undefined;
25
+ } };
16
26
  export function init(o = {}, proc = process) {
17
27
  const s = shared();
18
28
  if (s.client)
19
29
  return s.client;
30
+ // An app whose run reads no .env (SvelteKit 3's preview and built server, a built Nuxt server - the clean room, 14 Nov: the server half
31
+ // sent nothing) gets Xovris's own two variables from the .env the wizard wrote, never another line of it nor over one it was given.
32
+ if ((!(o.url || proc.env.XOVRIS_INGEST_URL) || !(o.key || proc.env.XOVRIS_INGEST_KEY)) && typeof proc.cwd === 'function')
33
+ wizardEnv(proc.cwd(), proc.env);
20
34
  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',
35
+ url: o.url || proc.env.XOVRIS_INGEST_URL, key: o.key || proc.env.XOVRIS_INGEST_KEY,
36
+ release: o.release ?? releaseOf(proc.env, cwdOf(proc)), environment: o.environment ?? environmentFrom(proc.env), platform: 'node',
23
37
  send: o.send ?? fetchSend, traceContext: activeTraceContext,
24
38
  });
25
39
  s.client = client;
26
40
  // 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')
41
+ if (client.enabled && typeof proc?.on === 'function') {
28
42
  installProcessHandlers(client, proc);
43
+ s.stopServerErrors = captureServerErrors(client);
44
+ }
29
45
  return client;
30
46
  }
31
47
  export function installProcessHandlers(c, proc = process) {
@@ -60,5 +76,5 @@ export async function flush(timeoutMs) {
60
76
  return ok;
61
77
  }
62
78
  /** Tests only: forget the process-wide client. */
63
- export function resetForTests() { const s = shared(); s.client = null; s.handlers = new WeakSet(); }
79
+ export function resetForTests() { const s = shared(); s.stopServerErrors?.(); s.stopServerErrors = undefined; s.client = null; s.handlers = new WeakSet(); }
64
80
  export { startTracing, tracingState, xovrisSpanProcessor } from './otel.js';
package/dist/otel.js CHANGED
@@ -8,7 +8,8 @@ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
8
8
  import { defaultResource, resourceFromAttributes } from '@opentelemetry/resources';
9
9
  import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
10
10
  import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
11
- import { ERRORS_VIA_ENVELOPE, environmentFrom, otlpTracesUrl, projectIdFrom, releaseFrom } from '@xovris/core';
11
+ import { ERRORS_VIA_ENVELOPE, environmentFrom, otlpTracesUrl, projectIdFrom } from '@xovris/core';
12
+ import { releaseOf } from './release.js';
12
13
  const REGISTRY = Symbol.for('xovris.otel.v1');
13
14
  function registry() {
14
15
  const g = globalThis;
@@ -145,7 +146,7 @@ export function sentrySpanToReadable(j, resource) {
145
146
  };
146
147
  }
147
148
  function resourceOf(env, url) {
148
- const release = releaseFrom(env);
149
+ const release = releaseOf(env, typeof process.cwd === 'function' ? process.cwd() : undefined);
149
150
  const environment = environmentFrom(env);
150
151
  const projectId = projectIdFrom(url);
151
152
  return defaultResource().merge(resourceFromAttributes({
@@ -204,7 +205,7 @@ export function decideTracing(o = {}) {
204
205
  warnOnce('stood-down', `${state.reason} ${state.next}`, o.warn);
205
206
  return set(state);
206
207
  }
207
- const release = releaseFrom(env);
208
+ const release = releaseOf(env, typeof process.cwd === 'function' ? process.cwd() : undefined);
208
209
  const environment = environmentFrom(env);
209
210
  const projectId = projectIdFrom(url);
210
211
  const provider = new NodeTracerProvider({
package/dist/register.js CHANGED
@@ -1,6 +1,9 @@
1
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.
2
+ // at once, traces after this start-up step so an OpenTelemetry setup registered next is joined, never replaced. The variables
3
+ // come from the process, else from the .env the wizard wrote (env-file.ts) - a Node app reads no .env by itself.
4
+ import { wizardEnv } from './env-file.js';
3
5
  import { init } from './index.js';
4
6
  import { startTracing } from './otel.js';
7
+ wizardEnv();
5
8
  init();
6
9
  void startTracing();
@@ -0,0 +1,5 @@
1
+ /** The commit the code at `dir` is checked out at, from the nearest .git above it (a worktree's or submodule's gitdir file, a loose or a
2
+ * packed ref, a detached head); undefined where there is none or it names no commit yet. */
3
+ export declare function gitCommitAt(dir: string): string | undefined;
4
+ /** The release a Node app's events carry: what it or its host says, else the commit of the code it runs from. */
5
+ export declare function releaseOf(env: Record<string, string | undefined>, cwd: string | undefined): string | undefined;
@@ -0,0 +1,72 @@
1
+ // D01.03 (the open setup race, 14 Nov: the wizard waited 15 minutes for a first real event that had already arrived, because it carried no
2
+ // release): a Node app's events name the code they came from on any host. The explicit XOVRIS_RELEASE first, then what the host already says
3
+ // (releaseFrom), then the code itself - the commit its own .git names - so an app run from a clone, a container built with its history or a
4
+ // person's own machine is never release-less. Read once, synchronously, never a process spawned and never a network call.
5
+ import { existsSync, readFileSync, statSync } from 'node:fs';
6
+ import { dirname, join, resolve } from 'node:path';
7
+ import { releaseFrom } from '@xovris/core';
8
+ const SHA = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i;
9
+ /** The commit the code at `dir` is checked out at, from the nearest .git above it (a worktree's or submodule's gitdir file, a loose or a
10
+ * packed ref, a detached head); undefined where there is none or it names no commit yet. */
11
+ export function gitCommitAt(dir) {
12
+ try {
13
+ for (let d = resolve(dir);;) {
14
+ const dot = join(d, '.git');
15
+ if (existsSync(dot))
16
+ return commitOf(dot, d);
17
+ const up = dirname(d);
18
+ if (up === d)
19
+ return undefined;
20
+ d = up;
21
+ }
22
+ }
23
+ catch {
24
+ // a runtime with no file system (the edge) names no release from git
25
+ return undefined;
26
+ }
27
+ }
28
+ function commitOf(dot, top) {
29
+ try {
30
+ let git = dot;
31
+ if (statSync(dot).isFile()) {
32
+ const to = /^gitdir:\s*(.+)$/m.exec(readFileSync(dot, 'utf8'))?.[1]?.trim();
33
+ if (!to)
34
+ return undefined;
35
+ git = resolve(top, to);
36
+ }
37
+ const head = readFileSync(join(git, 'HEAD'), 'utf8').trim();
38
+ if (SHA.test(head))
39
+ return head.toLowerCase();
40
+ const ref = /^ref:\s*(\S+)$/.exec(head)?.[1];
41
+ if (!ref)
42
+ return undefined;
43
+ // a linked worktree keeps its HEAD here and its branches in the common directory it names
44
+ const common = existsSync(join(git, 'commondir')) ? resolve(git, readFileSync(join(git, 'commondir'), 'utf8').trim()) : git;
45
+ for (const base of [git, common]) {
46
+ const loose = join(base, ref);
47
+ if (existsSync(loose)) {
48
+ const s = readFileSync(loose, 'utf8').trim();
49
+ if (SHA.test(s))
50
+ return s.toLowerCase();
51
+ }
52
+ }
53
+ for (const base of [git, common]) {
54
+ const packed = join(base, 'packed-refs');
55
+ if (!existsSync(packed))
56
+ continue;
57
+ for (const line of readFileSync(packed, 'utf8').split(/\r?\n/)) {
58
+ const [sha, name] = line.split(' ');
59
+ if (name === ref && sha && SHA.test(sha))
60
+ return sha.toLowerCase();
61
+ }
62
+ }
63
+ }
64
+ catch {
65
+ // an unreadable .git names no release; the event is still sent
66
+ }
67
+ return undefined;
68
+ }
69
+ /** The release a Node app's events carry: what it or its host says, else the commit of the code it runs from. */
70
+ export function releaseOf(env, cwd) {
71
+ return releaseFrom(env) ?? (cwd ? gitCommitAt(cwd) : undefined);
72
+ }
@@ -0,0 +1,34 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { Client } from '@xovris/core';
3
+ /** The event a 5xx answer becomes: the method, the path without its query, and the status - never the query, a header or a body. */
4
+ export declare function serverErrorOf(request: Pick<IncomingMessage, 'method' | 'url'>, status: number): {
5
+ error: Error;
6
+ request: {
7
+ method: string;
8
+ url: string;
9
+ };
10
+ };
11
+ /**
12
+ * Subscribes the client to every 5xx answer of every HTTP server in this process; returns how to stop. B311s's clean room (14 Nov): a route
13
+ * whose own exception was captured while its request ran (Next.js's onRequestError, a framework's error handler) was then reported a
14
+ * second time by this floor as "GET /x answered 500" - two events for one failure. Each request now runs in its own async context, an
15
+ * exception captured inside it marks the request reported, and the floor speaks only for a 5xx nothing else reported.
16
+ */
17
+ export declare function captureServerErrors(c: Client): () => void;
18
+ type BunHandler = (this: unknown, ...a: unknown[]) => unknown;
19
+ type BunServeOptions = {
20
+ fetch?: BunHandler;
21
+ routes?: Record<string, unknown>;
22
+ } & Record<string, unknown>;
23
+ type BunGlobal = {
24
+ serve: (this: unknown, o: BunServeOptions) => unknown;
25
+ };
26
+ /**
27
+ * D01.05.01 (the setup race's Bun probe, 14 Nov: a route's thrown error never reaches a Node channel): Bun's own server answers a thrown
28
+ * error with a 500 by itself, so each fetch and route handler Bun.serve is given is wrapped - the thrown error reaches Xovris with the
29
+ * method and the path (never the query) and is thrown on unchanged, to the app's and Bun's own error handling. Returns how to stop.
30
+ */
31
+ export declare function captureBunServe(c: Client, g?: {
32
+ Bun?: BunGlobal;
33
+ }): () => void;
34
+ export {};
@@ -0,0 +1,83 @@
1
+ // D01.01.06.01 (the clean room's Express run, 14 Nov 2026: the app answered 500 and nothing reached Xovris - Express, like Fastify, Koa,
2
+ // Hono and Nest, handles a route's error itself, so neither an uncaught exception nor an unhandled rejection ever fires): every request
3
+ // a Node server answers with a 5xx reaches Xovris, whatever framework answered it - read from Node's own HTTP diagnostics channel
4
+ // (http.server.response.finish), so nothing is patched, no dependency is added, and an ES module app is covered as a CommonJS one.
5
+ // The route's own exception, where a framework hands it over, is the next layer; this is the floor every server stands on.
6
+ import { AsyncLocalStorage } from 'node:async_hooks';
7
+ import { subscribe, unsubscribe } from 'node:diagnostics_channel';
8
+ const CHANNEL = 'http.server.response.finish'; // KEEP: machine format - Node's own HTTP server channel (nodejs.org/api/diagnostics_channel.html)
9
+ /** The event a 5xx answer becomes: the method, the path without its query, and the status - never the query, a header or a body. */
10
+ export function serverErrorOf(request, status) {
11
+ const method = request.method ?? 'GET';
12
+ const url = (request.url ?? '/').split('?')[0] ?? '/';
13
+ const error = new Error(`${method} ${url} answered ${status}`);
14
+ error.name = 'ServerError';
15
+ // no frames: the stack would be Xovris's own, never the app's
16
+ error.stack = `${error.name}: ${error.message}`;
17
+ return { error, request: { method, url } };
18
+ }
19
+ const START = 'http.server.request.start'; // KEEP: machine format - Node's own HTTP server channel
20
+ /**
21
+ * Subscribes the client to every 5xx answer of every HTTP server in this process; returns how to stop. B311s's clean room (14 Nov): a route
22
+ * whose own exception was captured while its request ran (Next.js's onRequestError, a framework's error handler) was then reported a
23
+ * second time by this floor as "GET /x answered 500" - two events for one failure. Each request now runs in its own async context, an
24
+ * exception captured inside it marks the request reported, and the floor speaks only for a 5xx nothing else reported.
25
+ */
26
+ export function captureServerErrors(c) {
27
+ const reported = new WeakSet();
28
+ const running = new AsyncLocalStorage();
29
+ // the request's own context from its first line of handling - the channel is published just before the server emits 'request'
30
+ const start = (m) => { const { request } = (m ?? {}); if (request)
31
+ running.enterWith(request); };
32
+ const capture = c.captureException.bind(c);
33
+ c.captureException = (err, o) => { const r = running.getStore(); if (r && o?.mechanism !== 'http.server')
34
+ reported.add(r); return capture(err, o); };
35
+ const on = (m) => {
36
+ const { request, response } = (m ?? {});
37
+ const status = response?.statusCode ?? 0;
38
+ if (!request || status < 500 || reported.has(request))
39
+ return;
40
+ const e = serverErrorOf(request, status);
41
+ c.captureException(e.error, { handled: true, mechanism: 'http.server', request: e.request, level: 'error' });
42
+ };
43
+ subscribe(START, start);
44
+ subscribe(CHANNEL, on);
45
+ const stopBun = captureBunServe(c);
46
+ return () => { unsubscribe(START, start); unsubscribe(CHANNEL, on); stopBun(); c.captureException = capture; };
47
+ }
48
+ /**
49
+ * D01.05.01 (the setup race's Bun probe, 14 Nov: a route's thrown error never reaches a Node channel): Bun's own server answers a thrown
50
+ * error with a 500 by itself, so each fetch and route handler Bun.serve is given is wrapped - the thrown error reaches Xovris with the
51
+ * method and the path (never the query) and is thrown on unchanged, to the app's and Bun's own error handling. Returns how to stop.
52
+ */
53
+ export function captureBunServe(c, g = globalThis) {
54
+ const bun = g.Bun;
55
+ if (!bun || typeof bun.serve !== 'function')
56
+ return () => { };
57
+ const serve = bun.serve;
58
+ const report = (e, r) => {
59
+ const req = r;
60
+ const ok = !!req && typeof req.method === 'string' && typeof req.url === 'string';
61
+ c.captureException(e, { handled: false, mechanism: 'bun.serve', level: 'error', ...(ok ? { request: { method: req.method, url: new URL(req.url).pathname } } : {}) });
62
+ };
63
+ const wrap = (f) => function (...a) {
64
+ try {
65
+ const out = f.apply(this, a);
66
+ return out instanceof Promise ? out.catch((e) => { report(e, a[0]); throw e; }) : out;
67
+ }
68
+ catch (e) {
69
+ report(e, a[0]);
70
+ throw e;
71
+ }
72
+ };
73
+ // a route is a handler, a plain object of one handler per method, or a value Bun serves as it is (a Response, an HTML import) - kept
74
+ const plain = (v) => !!v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype;
75
+ const routes = (r) => Object.fromEntries(Object.entries(r).map(([path, h]) => [path,
76
+ typeof h === 'function' ? wrap(h) : plain(h) ? Object.fromEntries(Object.entries(h).map(([m, f]) => [m, typeof f === 'function' ? wrap(f) : f])) : h]));
77
+ bun.serve = function (o) {
78
+ if (!plain(o))
79
+ return serve.call(this, o);
80
+ return serve.call(this, { ...o, ...(typeof o.fetch === 'function' ? { fetch: wrap(o.fetch) } : {}), ...(plain(o.routes) ? { routes: routes(o.routes) } : {}) });
81
+ };
82
+ return () => { bun.serve = serve; };
83
+ }
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@xovris/node",
3
+ "gitHead": "8c4ea16632dacbd3d42aa498287016ff8445a668",
3
4
  "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
+ "version": "0.1.2",
5
6
  "license": "Apache-2.0",
6
7
  "type": "module",
7
8
  "files": [
@@ -10,15 +11,18 @@
10
11
  "exports": {
11
12
  ".": {
12
13
  "types": "./dist/index.d.ts",
13
- "import": "./dist/index.js"
14
+ "import": "./dist/index.js",
15
+ "default": "./dist/index.js"
14
16
  },
15
17
  "./register": {
16
18
  "types": "./dist/register.d.ts",
17
- "import": "./dist/register.js"
19
+ "import": "./dist/register.js",
20
+ "default": "./dist/register.js"
18
21
  },
19
22
  "./otel": {
20
23
  "types": "./dist/otel.d.ts",
21
- "import": "./dist/otel.js"
24
+ "import": "./dist/otel.js",
25
+ "default": "./dist/otel.js"
22
26
  }
23
27
  },
24
28
  "publishConfig": {
@@ -31,7 +35,7 @@
31
35
  "@opentelemetry/resources": "^2.12.0",
32
36
  "@opentelemetry/sdk-trace-base": "^2.12.0",
33
37
  "@opentelemetry/sdk-trace-node": "^2.12.0",
34
- "@xovris/core": "0.1.0"
38
+ "@xovris/core": "0.1.2"
35
39
  },
36
40
  "devDependencies": {
37
41
  "@opentelemetry/sdk-node": "^0.222.0",