@watchtowerobservability/node 0.6.0 → 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.
Files changed (67) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +53 -5
  3. package/dist/cjs/buffer.d.ts +3 -0
  4. package/dist/cjs/checkin.d.ts +7 -0
  5. package/dist/cjs/checkin.js +18 -0
  6. package/dist/cjs/filter.d.ts +3 -0
  7. package/dist/cjs/filter.js +16 -0
  8. package/dist/cjs/index.d.ts +25 -3
  9. package/dist/cjs/index.js +34 -6
  10. package/dist/cjs/instrument.d.ts +5 -2
  11. package/dist/cjs/instrument.js +26 -3
  12. package/dist/cjs/integrations/db.d.ts +3 -0
  13. package/dist/cjs/integrations/db.js +4 -1
  14. package/dist/cjs/integrations/next-build.d.ts +31 -0
  15. package/dist/cjs/integrations/next-build.js +95 -0
  16. package/dist/cjs/integrations/next-tunnel.d.ts +14 -0
  17. package/dist/cjs/integrations/next-tunnel.js +52 -0
  18. package/dist/cjs/integrations/next.d.ts +22 -1
  19. package/dist/cjs/integrations/next.js +28 -2
  20. package/dist/cjs/load.js +20 -35
  21. package/dist/cjs/metrics.d.ts +2 -0
  22. package/dist/cjs/next-sourcemaps-cli.d.ts +2 -0
  23. package/dist/cjs/next-sourcemaps-cli.js +9 -0
  24. package/dist/cjs/origin.d.ts +1 -0
  25. package/dist/cjs/redact.d.ts +1 -0
  26. package/dist/cjs/register.js +11 -0
  27. package/dist/cjs/sampling.d.ts +1 -0
  28. package/dist/cjs/scrub.d.ts +8 -0
  29. package/dist/cjs/scrub.js +39 -0
  30. package/dist/cjs/shutdown.d.ts +14 -0
  31. package/dist/cjs/shutdown.js +26 -0
  32. package/dist/cjs/sql.js +11 -1
  33. package/dist/cjs/version.d.ts +2 -0
  34. package/dist/cjs/version.js +5 -0
  35. package/dist/esm/buffer.d.ts +3 -0
  36. package/dist/esm/checkin.d.ts +7 -0
  37. package/dist/esm/checkin.js +15 -0
  38. package/dist/esm/filter.d.ts +3 -0
  39. package/dist/esm/filter.js +13 -0
  40. package/dist/esm/index.d.ts +25 -3
  41. package/dist/esm/index.js +32 -5
  42. package/dist/esm/instrument.d.ts +5 -2
  43. package/dist/esm/instrument.js +26 -3
  44. package/dist/esm/integrations/db.d.ts +3 -0
  45. package/dist/esm/integrations/db.js +5 -2
  46. package/dist/esm/integrations/next-build.d.ts +31 -0
  47. package/dist/esm/integrations/next-build.js +58 -0
  48. package/dist/esm/integrations/next-tunnel.d.ts +14 -0
  49. package/dist/esm/integrations/next-tunnel.js +49 -0
  50. package/dist/esm/integrations/next.d.ts +22 -1
  51. package/dist/esm/integrations/next.js +22 -1
  52. package/dist/esm/load.js +20 -60
  53. package/dist/esm/metrics.d.ts +2 -0
  54. package/dist/esm/next-sourcemaps-cli.d.ts +2 -0
  55. package/dist/esm/next-sourcemaps-cli.js +7 -0
  56. package/dist/esm/origin.d.ts +1 -0
  57. package/dist/esm/redact.d.ts +1 -0
  58. package/dist/esm/register.js +11 -0
  59. package/dist/esm/sampling.d.ts +1 -0
  60. package/dist/esm/scrub.d.ts +8 -0
  61. package/dist/esm/scrub.js +34 -0
  62. package/dist/esm/shutdown.d.ts +14 -0
  63. package/dist/esm/shutdown.js +23 -0
  64. package/dist/esm/sql.js +11 -1
  65. package/dist/esm/version.d.ts +2 -0
  66. package/dist/esm/version.js +2 -0
  67. package/package.json +10 -2
@@ -0,0 +1,14 @@
1
+ export interface TunnelOptions {
2
+ /** Edge base URL the requests are forwarded to. */
3
+ endpoint: string;
4
+ /** Route prefix to strip; default `/api/wt`. */
5
+ basePath?: string;
6
+ /** Request body cap in bytes; default 1 MiB (over it: 413). */
7
+ maxBodyBytes?: number;
8
+ fetch?: typeof fetch;
9
+ }
10
+ /** Next route handlers `{ GET, POST }` forwarding allow-listed RUM paths to the edge. Only the publishable key (`?k=` or a `wtp_` bearer) is forwarded as auth; cookies and other headers are not. */
11
+ export declare function tunnelHandler(o: TunnelOptions): {
12
+ GET: (r: Request) => Promise<Response>;
13
+ POST: (r: Request) => Promise<Response>;
14
+ };
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ // First-party tunnel for browser telemetry (ad blockers block third-party telemetry hosts).
3
+ // app/api/wt/[...path]/route.ts: export const { GET, POST } = tunnelHandler({ endpoint: process.env.WT_EDGE_URL! });
4
+ // Browser SDK: init({ endpoint: '/api/wt', publishableKey: 'wtp_...' }).
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.tunnelHandler = tunnelHandler;
7
+ // only what the browser SDK calls: /v1/rum/*, /v1/replay/<session>/chunks and /v1/logs
8
+ const ALLOWED = /^\/v1\/(rum\/[A-Za-z0-9/_-]+|replay\/[A-Za-z0-9_-]+\/chunks|logs)$/;
9
+ const FORWARD = ['content-type', 'content-encoding', 'user-agent'];
10
+ /** Next route handlers `{ GET, POST }` forwarding allow-listed RUM paths to the edge. Only the publishable key (`?k=` or a `wtp_` bearer) is forwarded as auth; cookies and other headers are not. */
11
+ function tunnelHandler(o) {
12
+ const base = (o.basePath ?? '/api/wt').replace(/\/+$/, '');
13
+ const max = o.maxBodyBytes ?? 1024 * 1024;
14
+ const edge = o.endpoint.replace(/\/+$/, '');
15
+ const send = o.fetch ?? fetch;
16
+ const handle = async (req) => {
17
+ const url = new URL(req.url);
18
+ const path = url.pathname.startsWith(base) ? url.pathname.slice(base.length) : url.pathname;
19
+ if (!ALLOWED.test(path) || path.includes('..'))
20
+ return new Response('not found', { status: 404 });
21
+ const headers = {};
22
+ for (const h of FORWARD) {
23
+ const v = req.headers.get(h);
24
+ if (v)
25
+ headers[h] = v;
26
+ }
27
+ const bearer = /^Bearer (wtp_\S+)$/.exec(req.headers.get('authorization') ?? '');
28
+ if (bearer)
29
+ headers.authorization = `Bearer ${bearer[1]}`;
30
+ const k = url.searchParams.get('k');
31
+ let body;
32
+ if (req.method === 'POST') {
33
+ if (Number(req.headers.get('content-length') ?? 0) > max)
34
+ return new Response('payload too large', { status: 413 });
35
+ body = await req.arrayBuffer();
36
+ if (body.byteLength > max)
37
+ return new Response('payload too large', { status: 413 });
38
+ }
39
+ try {
40
+ const res = await send(`${edge}${path}${k ? `?k=${encodeURIComponent(k)}` : ''}`, { method: req.method, headers, body });
41
+ const out = new Headers();
42
+ const ct = res.headers.get('content-type');
43
+ if (ct)
44
+ out.set('content-type', ct);
45
+ return new Response(res.status === 204 ? null : await res.arrayBuffer(), { status: res.status, headers: out });
46
+ }
47
+ catch {
48
+ return new Response('bad gateway', { status: 502 });
49
+ }
50
+ };
51
+ return { GET: handle, POST: handle };
52
+ }
@@ -1,6 +1,27 @@
1
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
+ import type { ReadableSpan } from '@opentelemetry/sdk-trace';
1
3
  import * as wt from '../index.js';
4
+ export { withWatchtower, uploadSourcemaps } from './next-build.js';
5
+ export type { SourcemapOptions } from './next-build.js';
6
+ export { tunnelHandler } from './next-tunnel.js';
7
+ export type { TunnelOptions } from './next-tunnel.js';
8
+ export interface NextOptions extends wt.InitOptions {
9
+ /**
10
+ * Next.js's own spans (`next.span_type` set: load route module, prepare route module, resolve page components, start
11
+ * response, middleware, generateMetadata ...). `"sample"` (default) keeps `nextInternalsRate` of them, `"drop"` none,
12
+ * `"keep"` all. Request (`BaseServer.handleRequest`), route handler, render, server action and fetch spans, every
13
+ * SERVER/CLIENT span and every errored span are always kept. A dropped span's children stay in the trace.
14
+ */
15
+ nextInternals?: 'drop' | 'sample' | 'keep';
16
+ /** Share of internal spans kept with `nextInternals: "sample"`; default 0.1. */
17
+ nextInternalsRate?: number;
18
+ }
19
+ /** Whether `span` is one of Next's internal spans (not a request, route handler, render, server action or fetch). */
20
+ export declare function isNextInternal(span: ReadableSpan): boolean;
21
+ /** The `spanFilter` for a `nextInternals` mode; `rand` is injectable for tests. */
22
+ export declare function nextInternalsFilter(mode?: 'drop' | 'sample' | 'keep', rate?: number, rand?: () => number): (s: ReadableSpan) => boolean;
2
23
  /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
3
- export declare function makeRegister(options?: wt.InitOptions): () => Promise<void>;
24
+ export declare function makeRegister(options?: NextOptions): () => Promise<void>;
4
25
  /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
5
26
  export declare const register: () => Promise<void>;
6
27
  /** Next.js onRequestError: server render, route handler and server action errors. */
@@ -33,19 +33,45 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.register = void 0;
36
+ exports.register = exports.tunnelHandler = exports.uploadSourcemaps = exports.withWatchtower = void 0;
37
+ exports.isNextInternal = isNextInternal;
38
+ exports.nextInternalsFilter = nextInternalsFilter;
37
39
  exports.makeRegister = makeRegister;
38
40
  exports.onRequestError = onRequestError;
39
41
  // instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
40
42
  // or, with options: export const register = makeRegister({ redact }); export { onRequestError } from '@watchtowerobservability/node/next';
43
+ const api_1 = require("@opentelemetry/api");
41
44
  const wt = __importStar(require("../index.js"));
45
+ var next_build_js_1 = require("./next-build.js");
46
+ Object.defineProperty(exports, "withWatchtower", { enumerable: true, get: function () { return next_build_js_1.withWatchtower; } });
47
+ Object.defineProperty(exports, "uploadSourcemaps", { enumerable: true, get: function () { return next_build_js_1.uploadSourcemaps; } });
48
+ var next_tunnel_js_1 = require("./next-tunnel.js");
49
+ Object.defineProperty(exports, "tunnelHandler", { enumerable: true, get: function () { return next_tunnel_js_1.tunnelHandler; } });
50
+ const KEEP_TYPES = new Set([
51
+ 'BaseServer.handleRequest', 'AppRouteRouteHandlers.runHandler', 'AppRender.fetch', 'AppRender.getBodyResult',
52
+ 'Render.getServerSideProps', 'Render.getStaticProps', 'NextNodeServer.runApi',
53
+ ]);
54
+ const KEEP_NAMES = /^(render route|executing api route|fetch |.*server action)/i;
55
+ /** Whether `span` is one of Next's internal spans (not a request, route handler, render, server action or fetch). */
56
+ function isNextInternal(span) {
57
+ const type = span.attributes['next.span_type'];
58
+ if (typeof type !== 'string')
59
+ return false;
60
+ return !KEEP_TYPES.has(type) && !KEEP_NAMES.test(span.name) && span.kind !== 1 && span.kind !== 2 && span.status.code !== api_1.SpanStatusCode.ERROR;
61
+ }
62
+ /** The `spanFilter` for a `nextInternals` mode; `rand` is injectable for tests. */
63
+ function nextInternalsFilter(mode = 'sample', rate = 0.1, rand = Math.random) {
64
+ return (s) => mode === 'keep' || !isNextInternal(s) || (mode === 'sample' && rand() < rate);
65
+ }
42
66
  /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
43
67
  function makeRegister(options = {}) {
44
68
  return async function register() {
45
69
  const rt = process.env.NEXT_RUNTIME;
46
70
  if ((rt && rt !== 'nodejs') || !(options.apiKey || process.env.WT_INGEST_KEY))
47
71
  return;
48
- wt.init(options);
72
+ const { nextInternals, nextInternalsRate, ...init } = options;
73
+ const own = nextInternalsFilter(nextInternals, nextInternalsRate);
74
+ wt.init({ ...init, spanFilter: init.spanFilter ? (s) => own(s) && init.spanFilter(s) : own });
49
75
  };
50
76
  }
51
77
  /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
package/dist/cjs/load.js CHANGED
@@ -2,44 +2,29 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.load = load;
4
4
  exports.need = need;
5
- // Optional-peer loader. Each peer is required by a LITERAL name inside a try block so bundlers (webpack, esbuild, Next's
6
- // file tracer) can follow it; a computed `require(name)` is invisible to them. This is the CommonJS form;
7
- // scripts/build.mjs prepends `const require = createRequire(import.meta.url)` for dist/esm (webpack follows that too).
8
- // The cwd fallback only matters when `require` does not exist (test runners running the TS source as ESM).
5
+ // Optional-peer loader (same source for the CommonJS and ESM builds).
9
6
  const node_module_1 = require("node:module");
10
- const NONE = Symbol('not a known peer');
11
- function known(id) {
12
- try { // bundlers only tolerate an optional require that is lexically inside try
13
- switch (id) {
14
- case '@opentelemetry/context-async-hooks': return require('@opentelemetry/context-async-hooks');
15
- case '@opentelemetry/core': return require('@opentelemetry/core');
16
- case '@opentelemetry/exporter-logs-otlp-http': return require('@opentelemetry/exporter-logs-otlp-http');
17
- case '@opentelemetry/exporter-metrics-otlp-http': return require('@opentelemetry/exporter-metrics-otlp-http');
18
- case '@opentelemetry/exporter-trace-otlp-http': return require('@opentelemetry/exporter-trace-otlp-http');
19
- case '@opentelemetry/otlp-transformer': return require('@opentelemetry/otlp-transformer');
20
- case '@opentelemetry/resources': return require('@opentelemetry/resources');
21
- case '@opentelemetry/sdk-logs': return require('@opentelemetry/sdk-logs');
22
- case '@opentelemetry/sdk-metrics': return require('@opentelemetry/sdk-metrics');
23
- case '@opentelemetry/sdk-trace': return require('@opentelemetry/sdk-trace');
24
- case '@opentelemetry/instrumentation-runtime-node': return require('@opentelemetry/instrumentation-runtime-node');
25
- case '@opentelemetry/instrumentation': return require('@opentelemetry/instrumentation');
26
- case '@opentelemetry/instrumentation-http': return require('@opentelemetry/instrumentation-http');
27
- case '@opentelemetry/instrumentation-undici': return require('@opentelemetry/instrumentation-undici');
28
- case '@opentelemetry/instrumentation-pg': return require('@opentelemetry/instrumentation-pg');
29
- case '@opentelemetry/instrumentation-ioredis': return require('@opentelemetry/instrumentation-ioredis');
30
- case 'winston-transport': return require('winston-transport');
31
- default: return NONE;
32
- }
33
- }
34
- catch (e) {
35
- throw e;
36
- }
7
+ // Bundlers must NOT follow this: an optional peer the app did not install would make webpack warn "Module not found",
8
+ // and a bare require call on a variable id is a "Critical dependency" warning. createRequire() is opaque to webpack/esbuild/Next's tracer,
9
+ // so peers resolve at run time from the SDK's own location, then from the app root (cwd). Install the peers in the app
10
+ // (pnpm: as direct dependencies); for a Next standalone build add them to outputFileTracingIncludes.
11
+ function resolvers() {
12
+ const from = [typeof __filename === 'string' ? __filename : '', `${process.cwd()}/`].filter(Boolean);
13
+ return from.map((f) => (0, node_module_1.createRequire)(f));
37
14
  }
38
15
  function load(id) {
39
- if (typeof require !== 'function')
40
- return (0, node_module_1.createRequire)(`${process.cwd()}/`)(id);
41
- const m = known(id);
42
- return m === NONE ? require(id) : m;
16
+ let err;
17
+ for (const r of resolvers()) {
18
+ try {
19
+ return r(id);
20
+ }
21
+ catch (e) {
22
+ if (e?.code !== 'MODULE_NOT_FOUND')
23
+ throw e;
24
+ err ??= e;
25
+ }
26
+ }
27
+ throw err;
43
28
  }
44
29
  const SDK_PEERS = [
45
30
  '@opentelemetry/context-async-hooks', '@opentelemetry/core', '@opentelemetry/exporter-logs-otlp-http',
@@ -1,4 +1,6 @@
1
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
1
2
  import type { Resource } from '@opentelemetry/resources';
3
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
4
  import type { MeterProvider, PushMetricExporter } from '@opentelemetry/sdk-metrics';
3
5
  /** Explicit flag, else `WATCHTOWER_LOGS` / `WATCHTOWER_METRICS` (default on); `OTEL_*_EXPORTER=none` turns it off. */
4
6
  export declare function switchOn(name: string, otelExporterEnv: string, flag?: boolean): boolean;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ // `wt-next-sourcemaps [dir]`: upload .next/static source maps after `next build` (env: WT_API_KEY, WT_PROJECT, WT_RELEASE, WT_API_URL), then delete them.
5
+ const next_build_js_1 = require("./integrations/next-build.js");
6
+ (0, next_build_js_1.uploadSourcemaps)({ dir: process.argv[2], log: (l) => console.log(`[watchtower] ${l}`) }).catch((e) => {
7
+ console.error(`[watchtower] source map upload failed: ${e.message}`);
8
+ process.exit(1);
9
+ });
@@ -1,3 +1,4 @@
1
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
1
2
  import type { SpanProcessor } from '@opentelemetry/sdk-trace';
2
3
  export interface Frame {
3
4
  file: string;
@@ -1,3 +1,4 @@
1
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
1
2
  import type { SpanProcessor } from '@opentelemetry/sdk-trace';
2
3
  export type RedactHook = (key: string, value: unknown) => unknown;
3
4
  /** Hook keys for the non-attribute fields. Event attributes (incl. exception.message / exception.stacktrace) use their own keys. */
@@ -14,12 +14,23 @@ if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
14
14
  const key = Symbol.for('watchtower.node.esm-hook');
15
15
  if (!g[key]) {
16
16
  g[key] = true;
17
+ // Node 26 prints DEP0205 for module.register(); import-in-the-middle's hook has no sync (registerHooks) form yet,
18
+ // so mute only that one warning for this call.
19
+ const emit = process.emitWarning;
20
+ process.emitWarning = ((w, ...a) => {
21
+ if (JSON.stringify(a).includes('DEP0205'))
22
+ return;
23
+ return emit.call(process, w, ...a);
24
+ });
17
25
  try {
18
26
  (0, node_module_1.register)('@opentelemetry/instrumentation/hook.mjs', (0, node_url_1.pathToFileURL)(`${process.cwd()}/`));
19
27
  }
20
28
  catch {
21
29
  // @opentelemetry/instrumentation not installed: CommonJS apps are still instrumented
22
30
  }
31
+ finally {
32
+ process.emitWarning = emit;
33
+ }
23
34
  }
24
35
  (0, index_js_1.init)({});
25
36
  }
@@ -1,4 +1,5 @@
1
1
  import type { Attributes, Context, Link, SpanKind } from '@opentelemetry/api';
2
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
3
  import type { Sampler, SamplingResult } from '@opentelemetry/sdk-trace';
3
4
  export interface SamplingRule {
4
5
  name?: string;
@@ -0,0 +1,8 @@
1
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
+ import type { SpanProcessor } from '@opentelemetry/sdk-trace';
3
+ /** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
4
+ export declare function looksSecret(seg: string): boolean;
5
+ /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. */
6
+ export declare function scrubUrl(value: string): string;
7
+ /** Span processor: scrubs URL attributes (query dropped, `url.query` removed, secret path segments redacted) and URLs inside the span name. `http.route` is kept. */
8
+ export declare function urlScrubber(): SpanProcessor;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.looksSecret = looksSecret;
4
+ exports.scrubUrl = scrubUrl;
5
+ exports.urlScrubber = urlScrubber;
6
+ const URL_KEYS = ['http.target', 'url.full', 'url.path', 'http.url', 'http.request.url'];
7
+ const QUERY_KEYS = ['url.query'];
8
+ /** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
9
+ function looksSecret(seg) {
10
+ return seg.length >= 24 || (seg.length >= 10 && /[A-Za-z]/.test(seg) && /\d/.test(seg));
11
+ }
12
+ /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. */
13
+ function scrubUrl(value) {
14
+ const m = /^(?:([a-z][a-z0-9+.-]*:\/\/)([^/?#]*))?([^?#]*)/i.exec(value);
15
+ const origin = m[1] ? m[1] + m[2].replace(/^[^@]*@/, '') : '';
16
+ return origin + m[3].split('/').map((s) => (looksSecret(s) ? ':redacted' : s)).join('/');
17
+ }
18
+ function scrubName(name) {
19
+ return name.split(' ').map((t) => (/^(https?:\/\/|\/)/i.test(t) ? scrubUrl(t) : t)).join(' ');
20
+ }
21
+ /** Span processor: scrubs URL attributes (query dropped, `url.query` removed, secret path segments redacted) and URLs inside the span name. `http.route` is kept. */
22
+ function urlScrubber() {
23
+ return {
24
+ onStart() { },
25
+ onEnd(span) {
26
+ const a = span.attributes;
27
+ for (const k of URL_KEYS)
28
+ if (typeof a[k] === 'string')
29
+ a[k] = scrubUrl(a[k]);
30
+ for (const k of QUERY_KEYS)
31
+ delete a[k];
32
+ const n = scrubName(span.name);
33
+ if (n !== span.name)
34
+ span.name = n;
35
+ },
36
+ shutdown: () => Promise.resolve(),
37
+ forceFlush: () => Promise.resolve(),
38
+ };
39
+ }
@@ -0,0 +1,14 @@
1
+ export interface SignalProc {
2
+ on(event: string, l: () => void): unknown;
3
+ off(event: string, l: () => void): unknown;
4
+ listenerCount(event: string): number;
5
+ kill(pid: number, signal: string): unknown;
6
+ readonly pid: number;
7
+ }
8
+ /**
9
+ * On SIGTERM and SIGINT: flush (at most `timeoutMs`). Adding a signal listener turns off Node's default exit, so when
10
+ * ours is the only listener it removes itself and re-sends the signal after the flush; when the app or a framework
11
+ * (`next start`) has its own handler, that handler decides how the process ends and ours only starts the flush.
12
+ * Returns the uninstall function.
13
+ */
14
+ export declare function installSignalFlush(flush: () => Promise<unknown>, timeoutMs?: number, proc?: SignalProc): () => void;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ // Flush on SIGTERM / SIGINT without changing how the process ends.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.installSignalFlush = installSignalFlush;
5
+ /**
6
+ * On SIGTERM and SIGINT: flush (at most `timeoutMs`). Adding a signal listener turns off Node's default exit, so when
7
+ * ours is the only listener it removes itself and re-sends the signal after the flush; when the app or a framework
8
+ * (`next start`) has its own handler, that handler decides how the process ends and ours only starts the flush.
9
+ * Returns the uninstall function.
10
+ */
11
+ function installSignalFlush(flush, timeoutMs = 2000, proc = process) {
12
+ const handlers = new Map();
13
+ for (const sig of ['SIGTERM', 'SIGINT']) {
14
+ const h = () => {
15
+ const alone = proc.listenerCount(sig) <= 1;
16
+ const done = Promise.race([flush().catch(() => undefined), new Promise((r) => setTimeout(r, timeoutMs).unref())]);
17
+ if (!alone)
18
+ return;
19
+ void done.finally(() => { proc.off(sig, h); proc.kill(proc.pid, sig); });
20
+ };
21
+ handlers.set(sig, h);
22
+ proc.on(sig, h);
23
+ }
24
+ return () => { for (const [sig, h] of handlers)
25
+ proc.off(sig, h); };
26
+ }
package/dist/cjs/sql.js CHANGED
@@ -212,9 +212,19 @@ function normalizeAndHash(stmt, pg = false) {
212
212
  const isPgDialect = (system) => system === 'postgresql' || system === 'cockroachdb' || system === 'redshift';
213
213
  exports.isPgDialect = isPgDialect;
214
214
  const OP = /^\s*(?:with\b[\s\S]*?\)\s*)?([a-z]+)/i;
215
- const TARGET = /\b(?:from|into|update|join|table)\s+((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)/i;
215
+ const NAME = '(?:"[^"]+"|[\\w$]+)(?:\\.(?:"[^"]+"|[\\w$]+))?';
216
+ const TARGET = new RegExp(`\\b(?:from|into|update|join|table)\\s+(?:if\\s+(?:not\\s+)?exists\\s+)?(${NAME})`, 'i');
217
+ // DDL: `CREATE [TEMP|VIRTUAL|UNIQUE...] TABLE|INDEX|VIEW [IF NOT EXISTS] name [ON table]`; an index is named after its table
218
+ const CREATE = new RegExp(`^\\s*create\\s+(?:(?:temp|temporary|virtual|unique|fulltext|spatial|clustered|nonclustered|materialized|or\\s+replace)\\s+)*(table|index|view)\\s+(?:if\\s+not\\s+exists\\s+)?(?:concurrently\\s+)?(${NAME})(?:\\s+on\\s+(?:only\\s+)?(${NAME}))?`, 'i');
216
219
  /** `SELECT users`-style summary: the operation and first table, never values or the statement text. */
217
220
  function querySummary(text, fallback = 'postgres') {
221
+ const ddl = text?.match(CREATE);
222
+ if (ddl) {
223
+ const kind = ddl[1].toLowerCase();
224
+ const operation = `CREATE ${kind.toUpperCase()}`;
225
+ const target = (kind === 'index' ? ddl[3] ?? ddl[2] : ddl[2]).replace(/"/g, '');
226
+ return { operation, target, summary: `${operation} ${target}` };
227
+ }
218
228
  const operation = text?.match(OP)?.[1]?.toUpperCase();
219
229
  const target = text?.match(TARGET)?.[1]?.replace(/"/g, '');
220
230
  return { operation, target, summary: [operation ?? fallback, target].filter(Boolean).join(' ') };
@@ -0,0 +1,2 @@
1
+ /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
2
+ export declare const VERSION = "0.7.1";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSION = void 0;
4
+ /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
5
+ exports.VERSION = '0.7.1';
@@ -1,5 +1,8 @@
1
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
1
2
  import type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace';
3
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
4
  import type { LogRecordExporter, ReadableLogRecord } from '@opentelemetry/sdk-logs';
5
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
3
6
  import type { AggregationTemporality, InstrumentType, PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics';
4
7
  type Done = Parameters<SpanExporter['export']>[1];
5
8
  /** What the spool wraps: a span, log record or metric exporter; `B` is one export batch. */
@@ -0,0 +1,7 @@
1
+ export interface CheckinTarget {
2
+ endpoint: string;
3
+ headers: Record<string, string>;
4
+ fetch: typeof fetch;
5
+ }
6
+ /** Send `in_progress`, run `fn`, then send `ok` or `error` with its duration. Check-in failures never affect `fn`; its result or error is passed through. */
7
+ export declare function checkin<T>(c: CheckinTarget, slug: string, fn: () => T | Promise<T>): Promise<T>;
@@ -0,0 +1,15 @@
1
+ /** Send `in_progress`, run `fn`, then send `ok` or `error` with its duration. Check-in failures never affect `fn`; its result or error is passed through. */
2
+ export async function checkin(c, slug, fn) {
3
+ const send = (status, ms) => c.fetch(`${c.endpoint}/v1/checkins/${encodeURIComponent(slug)}?status=${status}${ms === undefined ? '' : `&duration_ms=${Math.min(ms, 86_400_000)}`}`, { method: 'POST', headers: c.headers }).catch(() => undefined);
4
+ await send('in_progress');
5
+ const t = Date.now();
6
+ try {
7
+ const r = await fn();
8
+ await send('ok', Date.now() - t);
9
+ return r;
10
+ }
11
+ catch (e) {
12
+ await send('error', Date.now() - t);
13
+ throw e;
14
+ }
15
+ }
@@ -0,0 +1,3 @@
1
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
+ import type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace';
3
+ export declare function filterExporter(inner: SpanExporter, keep: (s: ReadableSpan) => boolean): SpanExporter;
@@ -0,0 +1,13 @@
1
+ export function filterExporter(inner, keep) {
2
+ return {
3
+ export(spans, done) {
4
+ const kept = spans.filter(keep);
5
+ if (kept.length)
6
+ inner.export(kept, done);
7
+ else
8
+ done({ code: 0 });
9
+ },
10
+ shutdown: () => inner.shutdown(),
11
+ forceFlush: () => inner.forceFlush?.() ?? Promise.resolve(),
12
+ };
13
+ }
@@ -1,9 +1,13 @@
1
1
  import { inspect } from 'node:util';
2
2
  import { metrics, trace } from '@opentelemetry/api';
3
3
  import type { Tracer } from '@opentelemetry/api';
4
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
4
5
  import type { Resource } from '@opentelemetry/resources';
5
- import type { TracerProvider } from '@opentelemetry/sdk-trace';
6
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
7
+ import type { ReadableSpan, TracerProvider } from '@opentelemetry/sdk-trace';
8
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
6
9
  import type { LoggerProvider } from '@opentelemetry/sdk-logs';
10
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
7
11
  import type { MeterProvider } from '@opentelemetry/sdk-metrics';
8
12
  import { captureException } from './errors.js';
9
13
  import type { CaptureContext } from './errors.js';
@@ -63,8 +67,23 @@ export interface InitOptions {
63
67
  captureRules?: boolean;
64
68
  /** Replace the span exporter (tests). */
65
69
  exporter?: unknown;
66
- /** Patch node:http, fetch (undici), pg and ioredis for those whose `@opentelemetry/instrumentation-*` peer is installed; defaults to on unless WT_INSTRUMENT=0. `init` only: use the `/register` preload so it runs before the app imports them. */
67
- instrument?: boolean;
70
+ /**
71
+ * Scrub URLs on every span, including spans other libraries create (Next.js, node:http, fetch): the query string is dropped
72
+ * (`url.query` removed) and path segments that look like secrets or ids (>= 24 chars, or >= 10 chars mixing letters and digits,
73
+ * UUIDs included) become `:redacted`, in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names.
74
+ * `http.route` is kept. Default true; `false` records URLs as the instrumentation produced them.
75
+ */
76
+ urlScrubbing?: boolean;
77
+ /** Return false to drop a finished span before export (the `/next` entry uses it for `nextInternals`). */
78
+ spanFilter?: (span: ReadableSpan) => boolean;
79
+ /**
80
+ * Patch node:http, fetch (undici), pg and ioredis for those whose `@opentelemetry/instrumentation-*` peer is installed; defaults to on unless WT_INSTRUMENT=0.
81
+ * `'auto'` (or WT_INSTRUMENT=auto) also instruments whichever of postgres.js, better-sqlite3 and mysql2 is installed and logs one line naming what it patched
82
+ * (`instrumentLog: false` or WT_INSTRUMENT_LOG=0 silences it). `init` only: use the `/register` preload so it runs before the app imports them.
83
+ */
84
+ instrument?: boolean | 'auto';
85
+ /** Print the one-line list of what `instrument: 'auto'` patched (default true). */
86
+ instrumentLog?: boolean;
68
87
  fetch?: typeof fetch;
69
88
  }
70
89
  export interface EvalRow {
@@ -114,6 +133,8 @@ export declare class Client {
114
133
  constructor(opts: InitOptions);
115
134
  /** Emit an OTLP log record; trace and span ids come from the active context. */
116
135
  log(level: LogLevel, body: string, attributes?: Record<string, unknown>): void;
136
+ /** Run `fn` as a cron / scheduler job with check-ins to the monitor `monitorSlug` (needs the `ingest:checkins` key scope): `in_progress`, then `ok` or `error` with the duration. */
137
+ checkin<T>(monitorSlug: string, fn: () => T | Promise<T>): Promise<T>;
117
138
  forceFlush(): Promise<unknown>;
118
139
  toJSON(): {
119
140
  endpoint: string;
@@ -135,6 +156,7 @@ export declare class Client {
135
156
  shutdown(): Promise<void>;
136
157
  }
137
158
  export declare function init(opts: InitOptions): Client;
159
+ export declare const checkin: <T>(slug: string, fn: () => T | Promise<T>) => Promise<T>;
138
160
  export declare const flush: () => Promise<unknown>;
139
161
  export declare const log: (l: LogLevel, b: string, a?: Record<string, unknown>) => void;
140
162
  export declare const getPrompt: (id: string) => Promise<unknown>;
package/dist/esm/index.js CHANGED
@@ -6,6 +6,11 @@ import { need as needPeer } from './load.js';
6
6
  import { otelEnv } from './env.js';
7
7
  import { instrumentAll } from './instrument.js';
8
8
  import { LOG_BODY_KEY, redactor } from './redact.js';
9
+ import { urlScrubber } from './scrub.js';
10
+ import { filterExporter } from './filter.js';
11
+ import { checkin as runCheckin } from './checkin.js';
12
+ import { installSignalFlush } from './shutdown.js';
13
+ import { VERSION } from './version.js';
9
14
  import { SpoolExporter, spoolLogs } from './buffer.js';
10
15
  import { startMetrics, switchOn } from './metrics.js';
11
16
  import * as nodePath from 'node:path';
@@ -64,8 +69,15 @@ export class Client {
64
69
  const environment = o.environment || env.WT_ENVIRONMENT || oe.resource['deployment.environment.name'];
65
70
  const release = o.release || env.WT_RELEASE || oe.resource['service.version'];
66
71
  // the OTel SDK packages are optional peers, loaded here (not at import time) with a clear error when missing
67
- const { resourceFromAttributes } = needPeer('@opentelemetry/resources');
72
+ const { resourceFromAttributes, defaultResource } = needPeer('@opentelemetry/resources');
73
+ // the SDK's own telemetry.sdk.* (name, language, version): a bare resourceFromAttributes does not add them
74
+ const sdk = (defaultResource().attributes ?? {});
68
75
  const resource = resourceFromAttributes({
76
+ 'telemetry.sdk.name': String(sdk['telemetry.sdk.name'] ?? 'opentelemetry'),
77
+ 'telemetry.sdk.language': String(sdk['telemetry.sdk.language'] ?? 'nodejs'),
78
+ 'telemetry.sdk.version': String(sdk['telemetry.sdk.version'] ?? 'unknown'),
79
+ 'telemetry.distro.name': 'watchtower',
80
+ 'telemetry.distro.version': VERSION,
69
81
  ...safeResource(oe.resource),
70
82
  'service.name': o.serviceName || env.WT_SERVICE || oe.serviceName || 'app',
71
83
  ...(environment ? { 'deployment.environment.name': environment } : {}),
@@ -84,7 +96,9 @@ export class Client {
84
96
  if (o.bufferDir)
85
97
  exporter = new SpoolExporter(exporter, nodePath.join(o.bufferDir, 'traces'), url, this.headers, this.fetch);
86
98
  }
87
- // the redactor runs first, so the batch processor exports redacted attributes
99
+ if (o.spanFilter)
100
+ exporter = filterExporter(exporter, o.spanFilter);
101
+ // the scrubber and redactor run first, so the batch processor exports scrubbed attributes (the user's `redact` sees scrubbed URLs)
88
102
  const { BatchSpanProcessor, TracerProvider: TP } = needPeer('@opentelemetry/sdk-trace');
89
103
  let sampler;
90
104
  if (o.remoteSampling ?? env.WT_REMOTE_SAMPLING === '1') {
@@ -100,6 +114,7 @@ export class Client {
100
114
  ...(sampler ? { sampler: sampler } : {}),
101
115
  spanProcessors: [
102
116
  ...(o.codeOrigin ?? env.WT_CODE_ORIGIN === '1' ? [codeOrigin()] : []),
117
+ ...(o.urlScrubbing ?? true ? [urlScrubber()] : []),
103
118
  ...(o.redact ? [redactor(o.redact)] : []),
104
119
  new BatchSpanProcessor({ exporter }),
105
120
  ],
@@ -147,6 +162,10 @@ export class Client {
147
162
  attributes: attrs,
148
163
  });
149
164
  }
165
+ /** Run `fn` as a cron / scheduler job with check-ins to the monitor `monitorSlug` (needs the `ingest:checkins` key scope): `in_progress`, then `ok` or `error` with the duration. */
166
+ checkin(monitorSlug, fn) {
167
+ return runCheckin(this, monitorSlug, fn);
168
+ }
150
169
  forceFlush() {
151
170
  return Promise.all([this.provider.forceFlush(), this.loggerProvider.forceFlush(), this.meterProvider?.forceFlush()]);
152
171
  }
@@ -285,8 +304,13 @@ export function init(opts) {
285
304
  const c = new Client(opts);
286
305
  state.current = c;
287
306
  registerGlobals(c);
288
- if (opts?.instrument ?? !['0', 'off', 'false', 'no'].includes((process.env.WT_INSTRUMENT || '').trim().toLowerCase())) {
289
- instrumentAll({ tracerProvider: c.provider, meterProvider: c.meterProvider }, [c.endpoint, c.apiUrl]);
307
+ const env = (process.env.WT_INSTRUMENT || '').trim().toLowerCase();
308
+ const mode = opts?.instrument ?? (env === 'auto' ? 'auto' : !['0', 'off', 'false', 'no'].includes(env));
309
+ if (mode) {
310
+ const names = instrumentAll({ tracerProvider: c.provider, meterProvider: c.meterProvider }, [c.endpoint, c.apiUrl], mode === 'auto');
311
+ if (mode === 'auto' && (opts?.instrumentLog ?? !['0', 'off', 'false', 'no'].includes((process.env.WT_INSTRUMENT_LOG || '').trim().toLowerCase()))) {
312
+ console.info(`[watchtower] instrumented: ${names.map((n) => n.replace('@opentelemetry/instrumentation-', '')).join(', ') || 'nothing (no supported package found)'}`);
313
+ }
290
314
  }
291
315
  if (process.env.WT_PROFILING === '1') {
292
316
  const attrs = c.resource.attributes;
@@ -298,7 +322,9 @@ export function init(opts) {
298
322
  }).catch(() => undefined); // best effort: never break init
299
323
  }
300
324
  if ((opts || {}).captureProcessErrors !== false) {
301
- c.uninstall = installProcessHandlers(() => c.forceFlush());
325
+ const offErrors = installProcessHandlers(() => c.forceFlush());
326
+ const offSignals = installSignalFlush(() => c.forceFlush());
327
+ c.uninstall = () => { offErrors(); offSignals(); };
302
328
  }
303
329
  return c;
304
330
  }
@@ -307,6 +333,7 @@ function need() {
307
333
  throw new Error('watchtower.init() has not been called');
308
334
  return state.current;
309
335
  }
336
+ export const checkin = (slug, fn) => need().checkin(slug, fn);
310
337
  export const flush = () => (state.current ? state.current.forceFlush() : Promise.resolve());
311
338
  export const log = (l, b, a) => need().log(l, b, a);
312
339
  export const getPrompt = (id) => need().getPrompt(id);
@@ -2,6 +2,9 @@ interface Providers {
2
2
  tracerProvider: unknown;
3
3
  meterProvider?: unknown;
4
4
  }
5
- /** Register whichever of the four instrumentations is installed. Returns the package names that were enabled. */
6
- export declare function instrumentAll(p: Providers, selfUrls: string[]): string[];
5
+ /**
6
+ * Register whichever of the OTel instrumentations is installed (http, undici, pg, ioredis; with `auto` also mysql2) and,
7
+ * with `auto`, patch postgres.js and better-sqlite3 when installed. Returns the names that were enabled.
8
+ */
9
+ export declare function instrumentAll(p: Providers, selfUrls: string[], auto?: boolean): string[];
7
10
  export {};