@watchtowerobservability/node 0.6.0 → 0.7.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.
Files changed (54) hide show
  1. package/README.md +51 -3
  2. package/dist/cjs/checkin.d.ts +7 -0
  3. package/dist/cjs/checkin.js +18 -0
  4. package/dist/cjs/filter.d.ts +2 -0
  5. package/dist/cjs/filter.js +16 -0
  6. package/dist/cjs/index.d.ts +21 -3
  7. package/dist/cjs/index.js +34 -6
  8. package/dist/cjs/instrument.d.ts +5 -2
  9. package/dist/cjs/instrument.js +26 -3
  10. package/dist/cjs/integrations/db.d.ts +3 -0
  11. package/dist/cjs/integrations/db.js +4 -1
  12. package/dist/cjs/integrations/next-build.d.ts +31 -0
  13. package/dist/cjs/integrations/next-build.js +95 -0
  14. package/dist/cjs/integrations/next-tunnel.d.ts +14 -0
  15. package/dist/cjs/integrations/next-tunnel.js +52 -0
  16. package/dist/cjs/integrations/next.d.ts +21 -1
  17. package/dist/cjs/integrations/next.js +28 -2
  18. package/dist/cjs/load.js +1 -0
  19. package/dist/cjs/next-sourcemaps-cli.d.ts +2 -0
  20. package/dist/cjs/next-sourcemaps-cli.js +9 -0
  21. package/dist/cjs/scrub.d.ts +7 -0
  22. package/dist/cjs/scrub.js +39 -0
  23. package/dist/cjs/shutdown.d.ts +14 -0
  24. package/dist/cjs/shutdown.js +26 -0
  25. package/dist/cjs/sql.js +11 -1
  26. package/dist/cjs/version.d.ts +2 -0
  27. package/dist/cjs/version.js +5 -0
  28. package/dist/esm/checkin.d.ts +7 -0
  29. package/dist/esm/checkin.js +15 -0
  30. package/dist/esm/filter.d.ts +2 -0
  31. package/dist/esm/filter.js +13 -0
  32. package/dist/esm/index.d.ts +21 -3
  33. package/dist/esm/index.js +32 -5
  34. package/dist/esm/instrument.d.ts +5 -2
  35. package/dist/esm/instrument.js +26 -3
  36. package/dist/esm/integrations/db.d.ts +3 -0
  37. package/dist/esm/integrations/db.js +5 -2
  38. package/dist/esm/integrations/next-build.d.ts +31 -0
  39. package/dist/esm/integrations/next-build.js +58 -0
  40. package/dist/esm/integrations/next-tunnel.d.ts +14 -0
  41. package/dist/esm/integrations/next-tunnel.js +49 -0
  42. package/dist/esm/integrations/next.d.ts +21 -1
  43. package/dist/esm/integrations/next.js +22 -1
  44. package/dist/esm/load.js +2 -0
  45. package/dist/esm/next-sourcemaps-cli.d.ts +2 -0
  46. package/dist/esm/next-sourcemaps-cli.js +7 -0
  47. package/dist/esm/scrub.d.ts +7 -0
  48. package/dist/esm/scrub.js +34 -0
  49. package/dist/esm/shutdown.d.ts +14 -0
  50. package/dist/esm/shutdown.js +23 -0
  51. package/dist/esm/sql.js +11 -1
  52. package/dist/esm/version.d.ts +2 -0
  53. package/dist/esm/version.js +2 -0
  54. package/package.json +8 -1
@@ -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
@@ -27,6 +27,7 @@ function known(id) {
27
27
  case '@opentelemetry/instrumentation-undici': return require('@opentelemetry/instrumentation-undici');
28
28
  case '@opentelemetry/instrumentation-pg': return require('@opentelemetry/instrumentation-pg');
29
29
  case '@opentelemetry/instrumentation-ioredis': return require('@opentelemetry/instrumentation-ioredis');
30
+ case '@opentelemetry/instrumentation-mysql2': return require('@opentelemetry/instrumentation-mysql2');
30
31
  case 'winston-transport': return require('winston-transport');
31
32
  default: return NONE;
32
33
  }
@@ -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
+ });
@@ -0,0 +1,7 @@
1
+ import type { SpanProcessor } from '@opentelemetry/sdk-trace';
2
+ /** 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). */
3
+ export declare function looksSecret(seg: string): boolean;
4
+ /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. */
5
+ export declare function scrubUrl(value: string): string;
6
+ /** Span processor: scrubs URL attributes (query dropped, `url.query` removed, secret path segments redacted) and URLs inside the span name. `http.route` is kept. */
7
+ 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.0";
@@ -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.0';
@@ -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,2 @@
1
+ import type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace';
2
+ 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
+ }
@@ -2,7 +2,7 @@ import { inspect } from 'node:util';
2
2
  import { metrics, trace } from '@opentelemetry/api';
3
3
  import type { Tracer } from '@opentelemetry/api';
4
4
  import type { Resource } from '@opentelemetry/resources';
5
- import type { TracerProvider } from '@opentelemetry/sdk-trace';
5
+ import type { ReadableSpan, TracerProvider } from '@opentelemetry/sdk-trace';
6
6
  import type { LoggerProvider } from '@opentelemetry/sdk-logs';
7
7
  import type { MeterProvider } from '@opentelemetry/sdk-metrics';
8
8
  import { captureException } from './errors.js';
@@ -63,8 +63,23 @@ export interface InitOptions {
63
63
  captureRules?: boolean;
64
64
  /** Replace the span exporter (tests). */
65
65
  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;
66
+ /**
67
+ * Scrub URLs on every span, including spans other libraries create (Next.js, node:http, fetch): the query string is dropped
68
+ * (`url.query` removed) and path segments that look like secrets or ids (>= 24 chars, or >= 10 chars mixing letters and digits,
69
+ * UUIDs included) become `:redacted`, in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names.
70
+ * `http.route` is kept. Default true; `false` records URLs as the instrumentation produced them.
71
+ */
72
+ urlScrubbing?: boolean;
73
+ /** Return false to drop a finished span before export (the `/next` entry uses it for `nextInternals`). */
74
+ spanFilter?: (span: ReadableSpan) => boolean;
75
+ /**
76
+ * Patch node:http, fetch (undici), pg and ioredis for those whose `@opentelemetry/instrumentation-*` peer is installed; defaults to on unless WT_INSTRUMENT=0.
77
+ * `'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
78
+ * (`instrumentLog: false` or WT_INSTRUMENT_LOG=0 silences it). `init` only: use the `/register` preload so it runs before the app imports them.
79
+ */
80
+ instrument?: boolean | 'auto';
81
+ /** Print the one-line list of what `instrument: 'auto'` patched (default true). */
82
+ instrumentLog?: boolean;
68
83
  fetch?: typeof fetch;
69
84
  }
70
85
  export interface EvalRow {
@@ -114,6 +129,8 @@ export declare class Client {
114
129
  constructor(opts: InitOptions);
115
130
  /** Emit an OTLP log record; trace and span ids come from the active context. */
116
131
  log(level: LogLevel, body: string, attributes?: Record<string, unknown>): void;
132
+ /** 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. */
133
+ checkin<T>(monitorSlug: string, fn: () => T | Promise<T>): Promise<T>;
117
134
  forceFlush(): Promise<unknown>;
118
135
  toJSON(): {
119
136
  endpoint: string;
@@ -135,6 +152,7 @@ export declare class Client {
135
152
  shutdown(): Promise<void>;
136
153
  }
137
154
  export declare function init(opts: InitOptions): Client;
155
+ export declare const checkin: <T>(slug: string, fn: () => T | Promise<T>) => Promise<T>;
138
156
  export declare const flush: () => Promise<unknown>;
139
157
  export declare const log: (l: LogLevel, b: string, a?: Record<string, unknown>) => void;
140
158
  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 {};
@@ -1,5 +1,7 @@
1
1
  // Auto-instrumentation: node:http, fetch (undici), pg and ioredis, each only when its optional peer package is installed.
2
2
  import { load } from './load.js';
3
+ import { instrumentBetterSqlite3 } from './integrations/sqlite.js';
4
+ import { instrumentPostgres } from './integrations/postgres.js';
3
5
  const ENTRIES = [
4
6
  {
5
7
  pkg: '@opentelemetry/instrumentation-http', ctor: 'HttpInstrumentation',
@@ -12,15 +14,24 @@ const ENTRIES = [
12
14
  },
13
15
  { pkg: '@opentelemetry/instrumentation-pg', ctor: 'PgInstrumentation', opts: () => ({}) },
14
16
  { pkg: '@opentelemetry/instrumentation-ioredis', ctor: 'IORedisInstrumentation', opts: () => ({}) },
17
+ { pkg: '@opentelemetry/instrumentation-mysql2', ctor: 'MySQL2Instrumentation', opts: () => ({}), auto: true },
15
18
  ];
16
- /** Register whichever of the four instrumentations is installed. Returns the package names that were enabled. */
17
- export function instrumentAll(p, selfUrls) {
19
+ /** Drivers patched in place (no OTel package): `instrument: 'auto'` only. Each loads the app's installed copy or is skipped. */
20
+ const DRIVERS = [
21
+ { name: 'postgres.js', run: () => { load('postgres'); instrumentPostgres(); } }, // only when `postgres` is installed
22
+ { name: 'better-sqlite3', run: () => instrumentBetterSqlite3(load('better-sqlite3')) },
23
+ ];
24
+ /**
25
+ * Register whichever of the OTel instrumentations is installed (http, undici, pg, ioredis; with `auto` also mysql2) and,
26
+ * with `auto`, patch postgres.js and better-sqlite3 when installed. Returns the names that were enabled.
27
+ */
28
+ export function instrumentAll(p, selfUrls, auto = false) {
18
29
  let registerInstrumentations;
19
30
  try {
20
31
  ({ registerInstrumentations } = load('@opentelemetry/instrumentation'));
21
32
  }
22
33
  catch {
23
- return []; // optional peer not installed
34
+ return auto ? patchDrivers([]) : []; // optional peer not installed
24
35
  }
25
36
  const self = selfUrls.flatMap((u) => { try {
26
37
  return [new URL(u)];
@@ -31,6 +42,8 @@ export function instrumentAll(p, selfUrls) {
31
42
  const found = [];
32
43
  const names = [];
33
44
  for (const e of ENTRIES) {
45
+ if (e.auto && !auto)
46
+ continue;
34
47
  try {
35
48
  const Ctor = load(e.pkg)[e.ctor];
36
49
  if (Ctor) {
@@ -44,5 +57,15 @@ export function instrumentAll(p, selfUrls) {
44
57
  }
45
58
  if (found.length)
46
59
  registerInstrumentations({ instrumentations: found, tracerProvider: p.tracerProvider, meterProvider: p.meterProvider });
60
+ return auto ? patchDrivers(names) : names;
61
+ }
62
+ function patchDrivers(names) {
63
+ for (const d of DRIVERS) {
64
+ try {
65
+ d.run();
66
+ names.push(d.name);
67
+ }
68
+ catch { /* driver not installed */ }
69
+ }
47
70
  return names;
48
71
  }
@@ -5,6 +5,9 @@ export interface DbOptions {
5
5
  /** Flag a statement run more than this many times under one parent span. Default:
6
6
  * `WATCHTOWER_DB_N_PLUS_ONE` or 5; 0 turns it off. */
7
7
  nPlusOne?: number;
8
+ /** Record a query only when a span is active (a request, job or `observe` span). Default true (`WATCHTOWER_DB_REQUIRE_PARENT=0`
9
+ * turns it off): startup DDL, migrations and polling loops run outside any span and would otherwise each become a root trace. */
10
+ requireParent?: boolean;
8
11
  }
9
12
  export interface DbOp {
10
13
  /** `db.system.name`, e.g. `sqlite`. */
@@ -2,7 +2,7 @@
2
2
  // statement hash and N+1 hint, connection-pool metrics and embedded-store gauges.
3
3
  import * as fs from 'node:fs';
4
4
  import * as nodePath from 'node:path';
5
- import { context, createContextKey, metrics, trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
5
+ import { context, createContextKey, INVALID_SPAN_CONTEXT, metrics, trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
6
6
  import { isPgDialect, normalizeAndHash, querySummary } from '../sql.js';
7
7
  /** Set inside an instrumented call so a wrapper the library calls internally adds no second span. */
8
8
  const INSIDE = createContextKey('watchtower.db.inside');
@@ -27,6 +27,10 @@ function repeats(parent, key) {
27
27
  }
28
28
  /** A CLIENT span for `op` (not made active): summary, hash, N+1 hint. Prefer `traced`. */
29
29
  export function startDbSpan(op, opts, parent, startTime) {
30
+ const p = trace.getSpan(parent)?.spanContext();
31
+ const requireParent = opts?.requireParent ?? !['0', 'false', 'off', 'no'].includes((process.env.WATCHTOWER_DB_REQUIRE_PARENT || '').trim().toLowerCase());
32
+ if (requireParent && !(p && trace.isSpanContextValid(p)))
33
+ return trace.wrapSpanContext(INVALID_SPAN_CONTEXT); // non-recording: nothing is exported
30
34
  const attrs = { 'db.system.name': op.system, ...op.attributes };
31
35
  let { operation, collection } = op;
32
36
  let name = [operation, collection].filter(Boolean).join(' ') || op.system;
@@ -49,7 +53,6 @@ export function startDbSpan(op, opts, parent, startTime) {
49
53
  attrs['db.collection.name'] = collection;
50
54
  if (op.namespace)
51
55
  attrs['db.namespace'] = op.namespace;
52
- const p = trace.getSpan(parent)?.spanContext();
53
56
  const max = threshold(opts);
54
57
  if (p && max > 0) {
55
58
  const n = repeats(p.spanId, key);
@@ -0,0 +1,31 @@
1
+ export interface SourcemapOptions {
2
+ /** Directory holding the client build; default `.next/static`. */
3
+ dir?: string;
4
+ /** Default WT_API_URL, then https://api.watchtower.observer. */
5
+ apiUrl?: string;
6
+ /** A key with scope `ci:write` (it covers releases and artifacts; `admin:write` also works). Default WT_API_KEY. */
7
+ apiKey?: string;
8
+ /** Project id or slug the maps belong to. Default WT_PROJECT. */
9
+ project?: string;
10
+ /** Release version: must equal the `release` the browser SDK reports. Default WT_RELEASE. */
11
+ release?: string;
12
+ /** Keep the .map files after a successful upload (default: delete them so they are never served). */
13
+ keep?: boolean;
14
+ fetch?: typeof fetch;
15
+ log?: (line: string) => void;
16
+ }
17
+ type NextConfig = Record<string, unknown>;
18
+ type ConfigOrFn = NextConfig | ((...a: unknown[]) => NextConfig | Promise<NextConfig>);
19
+ /**
20
+ * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
21
+ * `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
22
+ * (`"build": "next build && wt-next-sourcemaps"`) to upload them and delete the .map files from `.next/static`.
23
+ */
24
+ export declare function withWatchtower(config?: ConfigOrFn, opts?: {
25
+ sourcemaps?: boolean;
26
+ }): ConfigOrFn;
27
+ /** Upload every `.map` under `dir` as `_next/static/<path>` for the release, then delete them. Throws (leaving the files) when an upload fails. */
28
+ export declare function uploadSourcemaps(o?: SourcemapOptions): Promise<{
29
+ uploaded: number;
30
+ }>;
31
+ export {};
@@ -0,0 +1,58 @@
1
+ // Build-time helpers for Next.js: `withWatchtower` (next.config) and `uploadSourcemaps` (after `next build`).
2
+ import * as fs from 'node:fs';
3
+ import * as nodePath from 'node:path';
4
+ /**
5
+ * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
6
+ * `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
7
+ * (`"build": "next build && wt-next-sourcemaps"`) to upload them and delete the .map files from `.next/static`.
8
+ */
9
+ export function withWatchtower(config = {}, opts = {}) {
10
+ const apply = (c) => (opts.sourcemaps ? { ...c, productionBrowserSourceMaps: true } : c);
11
+ if (typeof config !== 'function')
12
+ return apply(config);
13
+ return async (...a) => apply(await config(...a));
14
+ }
15
+ function* maps(dir) {
16
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
17
+ const p = nodePath.join(dir, e.name);
18
+ if (e.isDirectory())
19
+ yield* maps(p);
20
+ else if (e.name.endsWith('.map'))
21
+ yield p;
22
+ }
23
+ }
24
+ /** Upload every `.map` under `dir` as `_next/static/<path>` for the release, then delete them. Throws (leaving the files) when an upload fails. */
25
+ export async function uploadSourcemaps(o = {}) {
26
+ const env = process.env;
27
+ const key = o.apiKey || env.WT_API_KEY;
28
+ const project = o.project || env.WT_PROJECT;
29
+ const release = o.release || env.WT_RELEASE;
30
+ if (!key)
31
+ throw new Error('WT_API_KEY is required (a key with scope ci:write)');
32
+ if (!project)
33
+ throw new Error('WT_PROJECT (project id) is required');
34
+ if (!release)
35
+ throw new Error('WT_RELEASE is required');
36
+ const dir = nodePath.resolve(o.dir || '.next/static');
37
+ const f = o.fetch || fetch;
38
+ const log = o.log || (() => { });
39
+ const root = `${(o.apiUrl || env.WT_API_URL || 'https://api.watchtower.observer').replace(/\/+$/, '')}/v1/projects/${encodeURIComponent(project)}`;
40
+ const call = async (path, init, okStatus = []) => {
41
+ const res = await f(root + path, { ...init, headers: { authorization: `Bearer ${key}`, ...init.headers } });
42
+ if (!res.ok && !okStatus.includes(res.status))
43
+ throw new Error(`watchtower ${init.method} ${path.split('?')[0]} -> HTTP ${res.status}`);
44
+ };
45
+ const files = fs.existsSync(dir) ? [...maps(dir)] : [];
46
+ await call('/releases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ version: release }) }, [409]); // 409: exists
47
+ for (const file of files) {
48
+ const name = `_next/static/${nodePath.relative(dir, file).split(nodePath.sep).join('/')}`;
49
+ await call(`/artifacts?${new URLSearchParams({ kind: 'sourcemap', name, release })}`, {
50
+ method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: new Uint8Array(fs.readFileSync(file)),
51
+ });
52
+ }
53
+ if (!o.keep)
54
+ for (const file of files)
55
+ fs.rmSync(file);
56
+ log(`uploaded ${files.length} source maps for release ${release}${o.keep ? '' : ' and deleted them'}`);
57
+ return { uploaded: files.length };
58
+ }
@@ -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
+ };