@watchtowerobservability/node 0.7.9 → 0.8.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 (57) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +31 -9
  3. package/dist/cjs/buffer.d.ts +0 -3
  4. package/dist/cjs/diagnostics.d.ts +37 -0
  5. package/dist/cjs/diagnostics.js +92 -0
  6. package/dist/cjs/filter.d.ts +0 -1
  7. package/dist/cjs/index.d.ts +1 -4
  8. package/dist/cjs/index.js +44 -9
  9. package/dist/cjs/integrations/db.js +4 -2
  10. package/dist/cjs/integrations/next-build.d.ts +3 -1
  11. package/dist/cjs/integrations/next-build.js +5 -2
  12. package/dist/cjs/integrations/next-edge.d.ts +13 -0
  13. package/dist/cjs/integrations/next-edge.js +14 -0
  14. package/dist/cjs/integrations/next.d.ts +11 -4
  15. package/dist/cjs/integrations/next.js +12 -6
  16. package/dist/cjs/late.d.ts +7 -0
  17. package/dist/cjs/late.js +28 -0
  18. package/dist/cjs/load.d.ts +6 -1
  19. package/dist/cjs/load.js +12 -2
  20. package/dist/cjs/metrics.d.ts +1 -3
  21. package/dist/cjs/metrics.js +3 -1
  22. package/dist/cjs/next-filter.d.ts +0 -1
  23. package/dist/cjs/origin.d.ts +0 -1
  24. package/dist/cjs/redact.d.ts +0 -1
  25. package/dist/cjs/register.js +2 -0
  26. package/dist/cjs/sampling.d.ts +0 -1
  27. package/dist/cjs/scrub.d.ts +0 -1
  28. package/dist/cjs/version.d.ts +1 -1
  29. package/dist/cjs/version.js +1 -1
  30. package/dist/esm/buffer.d.ts +0 -3
  31. package/dist/esm/diagnostics.d.ts +37 -0
  32. package/dist/esm/diagnostics.js +79 -0
  33. package/dist/esm/filter.d.ts +0 -1
  34. package/dist/esm/index.d.ts +1 -4
  35. package/dist/esm/index.js +45 -10
  36. package/dist/esm/integrations/db.js +5 -3
  37. package/dist/esm/integrations/next-build.d.ts +3 -1
  38. package/dist/esm/integrations/next-build.js +5 -2
  39. package/dist/esm/integrations/next-edge.d.ts +13 -0
  40. package/dist/esm/integrations/next-edge.js +8 -0
  41. package/dist/esm/integrations/next.d.ts +11 -4
  42. package/dist/esm/integrations/next.js +12 -4
  43. package/dist/esm/late.d.ts +7 -0
  44. package/dist/esm/late.js +22 -0
  45. package/dist/esm/load.d.ts +6 -1
  46. package/dist/esm/load.js +11 -2
  47. package/dist/esm/metrics.d.ts +1 -3
  48. package/dist/esm/metrics.js +3 -1
  49. package/dist/esm/next-filter.d.ts +0 -1
  50. package/dist/esm/origin.d.ts +0 -1
  51. package/dist/esm/redact.d.ts +0 -1
  52. package/dist/esm/register.js +2 -0
  53. package/dist/esm/sampling.d.ts +0 -1
  54. package/dist/esm/scrub.d.ts +0 -1
  55. package/dist/esm/version.d.ts +1 -1
  56. package/dist/esm/version.js +1 -1
  57. package/package.json +21 -49
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.1 (2026-11-18)
4
+
5
+ - New: a `[watchtower] loaded too late: http was already imported, so its requests are not traced. Start node with --import @watchtowerobservability/node/register` warning, once per process, when `register` or `init()` loads after `http`/`https` (an ES module app that imports `register` from app code links `http` first, and its requests are then silently untraced). The check reads `process.moduleLoadList` in the first module the SDK evaluates, before its own dependencies load. Silent under Next.js and test runners. Verified: a bare `node --import` process has neither module loaded (no false positive on correct use), and a unit test covers the warning and its once-only guard.
6
+ - New: after the first exports the SDK prints one line, `[watchtower] <service> → <host> traces:ok logs:ok metrics:ok release=<release>` (`pending` until a signal exported, `fail(<status or error>)` for a failed one, `off` for a disabled one; it prints when every signal has a result, at the first failure, or after 90 s). `WT_DEBUG=1` (or `WATCHTOWER_DEBUG=1`) also logs the exporter endpoints (the key as its first 8 characters only), each export result (signal, item count, status or error) and a per-minute count of dropped Next.js internal spans and parentless DB queries. The default OTLP exporters are wrapped, not replaced. Verified with unit tests on the wrappers, line states and the debug output.
7
+ - The startup line `requireParent on; queries outside a span are not recorded` is gone. The first query actually dropped for lack of a parent span prints `[watchtower] dropped a DB query outside any span (requireParent on; WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)` once (the count is in the `WT_DEBUG` summary). Verified by a test that drops two queries and sees one line.
8
+ - `@watchtowerobservability/node/next` and `/next-build` are marked `@deprecated`: use `@watchtowerobservability/next` (`withWatchtower()` in next.config, `register` in `instrumentation.ts`, `npx wt-next-doctor` after `next build`). They work unchanged. The README gains a "Docker builds and source maps" note: pass the `ci:write` key with `--mount=type=secret`, never as a build `ARG`.
9
+
10
+ ## 0.8.0 (2026-11-16)
11
+
12
+ - `init()` never throws. A missing OpenTelemetry package, a missing key or any startup error logs one `[watchtower] telemetry is OFF` warning (listing every missing package and the install command), leaves every helper a no-op and returns a no-op client, so the app boots. Under pnpm this fixes the crash at the first import of `main.ts`.
13
+ - The OpenTelemetry SDK packages (`context-async-hooks`, `core`, the three OTLP exporters, `otlp-transformer`, `resources`, `sdk-logs`, `sdk-metrics`, `sdk-trace`) are now `dependencies`, not optional peers: `pnpm add @watchtowerobservability/node` is enough. The `instrumentation-*` packages and `winston-transport` stay optional peers.
14
+ - `@watchtowerobservability/node/next` has `edge-light`, `worker` and `browser` conditions pointing at a no-op stub with no `node:*` imports, so `export { register } from '@watchtowerobservability/node/next'` in `instrumentation.ts` builds with no bundler config.
15
+ - Fix (ESM under pnpm): the SDK now looks for its OpenTelemetry packages from its own location in the ESM build too (it only did in CommonJS), which is where pnpm puts its dependencies.
16
+ - Next.js standalone: the SDK names its OpenTelemetry packages literally (`tracedPackages`, never called), so Next's file tracer copies them with their pnpm links. Verified with a pnpm workspace where the app depends only on `@watchtowerobservability/node`, an edge middleware, and `.next/standalone` copied out of the project: `next build` passes and `server.js` starts with no missing-package warning.
17
+
3
18
  ## 0.7.9 (2026-11-16)
4
19
 
5
20
  - Fix (Next.js standalone, pnpm and monorepos; B22, WT-13): `withWatchtower` listed `node_modules/@opentelemetry/**` globs in `outputFileTracingIncludes`. Under pnpm those copied each peer as a plain folder without its own dependencies, or matched nothing when the `.pnpm` store sits at the workspace root, so `init` failed with `missing @opentelemetry/resources`. It now walks the SDK's dependency closure from the app at config time and lists each package's real store folder plus the pnpm links to it, which Next recreates as links. Verified with a pnpm workspace (`apps/web`, `outputFileTracingRoot` at the root, `output: 'standalone'`, peers as direct deps of the app, no peer imports in `instrumentation`): `server.js` starts with no missing-package warning and `wt-next-doctor` exits 0. Your own `outputFileTracingIncludes` are kept. New export: `tracingIncludes(ids, cwd)`.
package/README.md CHANGED
@@ -7,12 +7,10 @@
7
7
  Published on npm:
8
8
 
9
9
  ```sh
10
- npm install @watchtowerobservability/node @opentelemetry/context-async-hooks @opentelemetry/core \
11
- @opentelemetry/exporter-logs-otlp-http @opentelemetry/exporter-metrics-otlp-http @opentelemetry/exporter-trace-otlp-http \
12
- @opentelemetry/otlp-transformer @opentelemetry/resources @opentelemetry/sdk-logs @opentelemetry/sdk-metrics @opentelemetry/sdk-trace
10
+ npm install @watchtowerobservability/node # or: pnpm add @watchtowerobservability/node
13
11
  ```
14
12
 
15
- `@opentelemetry/api` is the only hard dependency; the OpenTelemetry SDK packages above are optional peers (so your app controls their versions) and are loaded by `init`, which throws an error naming the missing ones.
13
+ The OpenTelemetry SDK packages are regular dependencies, so that is enough. `init()` never throws: if a package is missing or startup fails it logs one warning, leaves telemetry off and returns a no-op client. In Next.js, `export { register } from '@watchtowerobservability/node/next'` builds with no bundler config (edge and browser builds get a no-op stub).
16
14
 
17
15
  Optional auto-instrumentation peers (installed ones are used, see below):
18
16
  `npm install @opentelemetry/instrumentation @opentelemetry/instrumentation-http @opentelemetry/instrumentation-undici @opentelemetry/instrumentation-pg @opentelemetry/instrumentation-ioredis`.
@@ -46,13 +44,20 @@ Pass `urlScrubbing: false` to record URLs as the instrumentation produced them.
46
44
 
47
45
  ## Auto-instrumentation and preload
48
46
 
47
+ The SDK prints one line once the first exports have gone out: `[watchtower] <service> → <host> traces:ok logs:ok metrics:ok release=<release>`
48
+ (`pending` until a signal has exported, `fail(<status>)` when it failed, `off` when switched off). `WT_DEBUG=1` (or `WATCHTOWER_DEBUG=1`)
49
+ also logs the exporter endpoints (the key as its first 8 characters only), every export result (signal, item count, HTTP status or error)
50
+ and a per-minute count of what the SDK dropped (Next.js internal spans under `nextInternals`, DB queries without a parent span).
51
+ If `http` or `https` was already imported when the SDK loaded (an ES module graph that imports `register` from app code links `http` first), it prints
52
+ `[watchtower] loaded too late: http was already imported, so its requests are not traced` once; start with `--import` instead.
53
+
49
54
  `instrument: 'auto'` (or `WT_INSTRUMENT=auto`) also patches whichever of postgres.js, better-sqlite3 and mysql2
50
55
  (`@opentelemetry/instrumentation-mysql2`) is installed, and prints one line (`[watchtower] instrumented: http, undici, pg, better-sqlite3`);
51
56
  silence it with `instrumentLog: false` or `WT_INSTRUMENT_LOG=0`.
52
57
 
53
58
  Start the preload in the start command: `node --import @watchtowerobservability/node/register app.js` (or `node -r ...` for CommonJS).
54
59
  Do not use `NODE_OPTIONS=--import ...`: it leaks into healthchecks and `pnpm` itself, which cannot resolve the package from the image root.
55
- OpenTelemetry peers are looked up from the SDK's location, then the working directory, then the directory of the entry script, so in a pnpm
60
+ OpenTelemetry packages are looked up from the SDK's location, then the working directory, then the directory of the entry script, so in a pnpm
56
61
  monorepo the app that runs the script is enough.
57
62
 
58
63
  `wt.checkin('nightly-report', async () => { ... })` wraps a cron or scheduler job in check-ins to the monitor with that slug
@@ -84,6 +89,13 @@ node --import @watchtowerobservability/node/register app.mjs # ESM app
84
89
 
85
90
  ## Next.js
86
91
 
92
+ Use **`@watchtowerobservability/next`**: `register` / `onRequestError` in `instrumentation.ts`, `withWatchtower()` in `next.config.mjs`
93
+ (`import { withWatchtower } from '@watchtowerobservability/next/config'`; `output: 'standalone'` is handled with no other config), and after
94
+ `next build` run `npx wt-next-doctor` to check that `.next/standalone` can load the SDK and its OpenTelemetry packages. See that package's README.
95
+
96
+ `@watchtowerobservability/node/next` (`makeRegister`, `register`, `withWatchtower`) and `@watchtowerobservability/node/next-build` are
97
+ deprecated (`@deprecated use @watchtowerobservability/next`). They keep working unchanged; the examples below still use them.
98
+
87
99
  ```ts
88
100
  // instrumentation.ts
89
101
  import { makeRegister } from '@watchtowerobservability/node/next';
@@ -96,12 +108,22 @@ own spans (those with a `next.span_type` attribute: load route module, prepare r
96
108
  response, middleware, generateMetadata). Root (parentless) internals such as `LoadComponents.loadRouteModule` are sampled like the rest. Request, route handler, render, server action and fetch spans, all SERVER/CLIENT
97
109
  spans and errored spans are always kept; children of a dropped internal span stay in the trace.
98
110
 
111
+ **Docker builds and source maps.** Pass the `ci:write` key to the build with a BuildKit secret, never as a build `ARG` (an `ARG` lands in the image history):
112
+
113
+ ```dockerfile
114
+ RUN --mount=type=secret,id=wt_ci_key WT_API_KEY=$(cat /run/secrets/wt_ci_key) npx wt-next-sourcemaps
115
+ ```
116
+
117
+ ```sh
118
+ docker build --secret id=wt_ci_key,env=WT_CI_KEY .
119
+ ```
120
+
99
121
  **Source maps.** `next.config.js`: `module.exports = withWatchtower(nextConfig, { sourcemaps: true })` (from
100
122
  `@watchtowerobservability/node/next`) turns on `productionBrowserSourceMaps`. Build with
101
123
  `"build": "next build && wt-next-sourcemaps"`: the `wt-next-sourcemaps` bin (or `uploadSourcemaps()`) uploads every `.map` under
102
124
  `.next/static` as `_next/static/<path>` for release `$WT_RELEASE` (the upload creates the release when it does not exist; it must equal
103
125
  the browser SDK's `release`), with `$WT_API_KEY` and `$WT_PROJECT` (and `$WT_API_URL`, default `https://watchtowerops.net`; the old `$WT_API` still works with a warning), then deletes the `.map` files so they are
104
- never served. Maps go up in one `POST /artifacts/bundle` request (a tar.gz plus manifest; about 120 MB per request) and fall back to single uploads, 8 at a time, when the server has no bundle route. Requests retry 429/5xx with backoff (honoring `Retry-After`) and continue past failures; the run prints `{uploaded, skipped, failed}` (`skipped`: the server already had the same bytes, HTTP 200) and exits 1 when any failed, leaving the files. Each map is sent with `for=<chunk path>` read from the chunk's `//# sourceMappingURL=` comment or the map's `file` field. A wrong host fails at once with a message naming it. Bodies are sent gzipped. **Key scope: `ci:write`** (it covers releases and
126
+ never served. Maps go up in one `POST /artifacts/bundle` request (a tar.gz plus manifest; about 32 MB per request) and fall back to single uploads, 8 at a time, when the server has no bundle route. Requests retry 429/5xx with backoff (honoring `Retry-After`) and continue past failures; the run prints `{uploaded, skipped, failed}` (`skipped`: the server already had the same bytes, HTTP 200) and exits 1 when any failed, leaving the files. Each map is sent with `for=<chunk path>` read from the chunk's `//# sourceMappingURL=` comment or the map's `file` field. A wrong host fails at once with a message naming it. Bodies are sent gzipped. **Key scope: `ci:write`** (it covers releases and
105
127
  artifacts; `admin:write` also works). Ingest keys cannot upload. Turbopack and webpack both emit these maps; Next does not inject
106
128
  debug ids, so maps match by release and file name.
107
129
 
@@ -116,9 +138,9 @@ registered it re-sends the signal so the exit is unchanged. Under `next start`,
116
138
  the server and calls `process.exit`; our flush starts first (the `register` hook runs before) and gets the time the server takes
117
139
  to close, so a very slow export can still be cut.
118
140
 
119
- Install the OpenTelemetry peers above in the app itself (with pnpm, as direct dependencies). The SDK loads peers at run time through `createRequire`, which webpack does not follow, so a build prints no "Module not found" warning for peers you did not install. Next's standalone file tracer does not follow them either.
141
+ The SDK loads its OpenTelemetry packages at run time through `createRequire`, which webpack does not follow, so a build prints no "Module not found" warning for peers you did not install. Next's standalone file tracer does not follow them either.
120
142
 
121
- Standalone recipe: wrap the config, `module.exports = withWatchtower(nextConfig)` (from `@watchtowerobservability/node/next-build`, or `@watchtowerobservability/next`). It adds the SDK and its OpenTelemetry peers to `serverExternalPackages`, and to `outputFileTracingIncludes` each of them with its dependencies and pnpm links, resolved from the app (npm, pnpm, monorepos with `outputFileTracingRoot` at the workspace root). By hand, add the same packages to `serverExternalPackages` and import each peer literally in `instrumentation.ts`; plain `node_modules/@opentelemetry/**` include globs do not work under pnpm, since they copy each peer without its dependencies. If a peer is missing at run time, `init` logs one warning naming it; after `next build`, `npx wt-next-doctor` checks that `.next/standalone` holds the SDK and its peers and that each one loads from `server.js`, and exits 1 otherwise.
143
+ Standalone recipe: wrap the config, `module.exports = withWatchtower(nextConfig)` (from `@watchtowerobservability/node/next-build`, or `@watchtowerobservability/next`). It adds the SDK and its OpenTelemetry packages to `serverExternalPackages`, and to `outputFileTracingIncludes` each of them with its dependencies and pnpm links, resolved from the app (npm, pnpm, monorepos with `outputFileTracingRoot` at the workspace root). By hand, add the same packages to `serverExternalPackages` and import each peer literally in `instrumentation.ts`; plain `node_modules/@opentelemetry/**` include globs do not work under pnpm, since they copy each peer without its dependencies. If a peer is missing at run time, `init` logs one warning naming it; after `next build`, `npx wt-next-doctor` checks that `.next/standalone` holds the SDK and its peers and that each one loads from `server.js`, and exits 1 otherwise.
122
144
 
123
145
  Bundling with esbuild or webpack (ESM or CommonJS output) works without warnings; mark the peers you use as externals (or ship `node_modules`), because they are resolved at run time. Declarations name optional peers behind `// @ts-ignore`, so `skipLibCheck: false` builds compile without them installed.
124
146
 
@@ -453,7 +475,7 @@ Development: `npm install`, `npm run typecheck`, `npm test` (vitest), `npm run b
453
475
 
454
476
  ### Datastore spans without a parent
455
477
 
456
- With `requireParent` on, a query run outside any span is dropped. Each drop increments the counter `wt.sdk.db.dropped_spans` (exported with the SDK's metrics, readable in-process with `droppedDbSpans()`) and the first one logs a diag warning; a rising count means work (a cron, a worker) runs outside `observe`/a request span.
478
+ With `requireParent` on, a query run outside any span is dropped. Each drop increments the counter `wt.sdk.db.dropped_spans` (exported with the SDK's metrics, readable in-process with `droppedDbSpans()`) and the first one prints `[watchtower] dropped a DB query outside any span (requireParent on; WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)` (nothing is printed at startup; `WT_DEBUG=1` adds a per-minute count); a rising count means work (a cron, a worker) runs outside `observe`/a request span.
457
479
 
458
480
  ### Release detection order
459
481
 
@@ -1,8 +1,5 @@
1
- // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
1
  import type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace';
3
- // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
4
2
  import type { LogRecordExporter, ReadableLogRecord } from '@opentelemetry/sdk-logs';
5
- // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
6
3
  import type { AggregationTemporality, InstrumentType, PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics';
7
4
  type Done = Parameters<SpanExporter['export']>[1];
8
5
  /** What the spool wraps: a span, log record or metric exporter; `B` is one export batch. */
@@ -0,0 +1,37 @@
1
+ import type { SpanExporter } from '@opentelemetry/sdk-trace';
2
+ import type { LogRecordExporter } from '@opentelemetry/sdk-logs';
3
+ import type { PushMetricExporter } from '@opentelemetry/sdk-metrics';
4
+ export type Signal = 'traces' | 'logs' | 'metrics';
5
+ type Result = {
6
+ code: number;
7
+ error?: Error;
8
+ };
9
+ export declare const debugOn: () => boolean;
10
+ /** First 8 characters only. */
11
+ export declare const keyHint: (k: string) => string;
12
+ export declare const debug: (m: string) => void;
13
+ /** HTTP status or error text of a failed export (the OTLP exporters put the status in `code` or the message). */
14
+ export declare function failure(e: (Error & {
15
+ code?: unknown;
16
+ }) | undefined): string;
17
+ export declare class StatusLine {
18
+ private readonly o;
19
+ private readonly out;
20
+ private st;
21
+ private printed;
22
+ constructor(o: {
23
+ service: string;
24
+ endpoint: string;
25
+ release?: string;
26
+ off?: Signal[];
27
+ }, out?: (m: string) => void);
28
+ /** One result for `signal`: the first failure and the last pending signal turning ok both print the line. */
29
+ record(signal: Signal, items: number, r: Result): void;
30
+ print(): void;
31
+ }
32
+ export declare const watchSpans: (e: SpanExporter, l: StatusLine) => SpanExporter;
33
+ export declare const watchLogs: (e: LogRecordExporter, l: StatusLine) => LogRecordExporter;
34
+ export declare const watchMetrics: (e: PushMetricExporter, l: StatusLine) => PushMetricExporter;
35
+ export declare function noteDrop(kind: string): void;
36
+ export declare function flushDrops(): void;
37
+ export {};
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.watchMetrics = exports.watchLogs = exports.watchSpans = exports.StatusLine = exports.debug = exports.keyHint = exports.debugOn = void 0;
4
+ exports.failure = failure;
5
+ exports.noteDrop = noteDrop;
6
+ exports.flushDrops = flushDrops;
7
+ const debugOn = () => ['1', 'true', 'on', 'yes'].includes((process.env.WT_DEBUG ?? process.env.WATCHTOWER_DEBUG ?? '').trim().toLowerCase());
8
+ exports.debugOn = debugOn;
9
+ /** First 8 characters only. */
10
+ const keyHint = (k) => `${k.slice(0, 8)}…`;
11
+ exports.keyHint = keyHint;
12
+ const debug = (m) => { if ((0, exports.debugOn)())
13
+ console.info(`[watchtower:debug] ${m}`); };
14
+ exports.debug = debug;
15
+ /** HTTP status or error text of a failed export (the OTLP exporters put the status in `code` or the message). */
16
+ function failure(e) {
17
+ const m = /\bstatus(?: code)?:? (\d{3})\b/i.exec(e?.message ?? '');
18
+ return String((typeof e?.code === 'number' ? e.code : undefined) ?? m?.[1] ?? e?.message ?? 'error').split('\n')[0].slice(0, 80);
19
+ }
20
+ const quiet = () => process.env.NODE_ENV === 'test' && !(0, exports.debugOn)();
21
+ class StatusLine {
22
+ o;
23
+ out;
24
+ st;
25
+ printed = false;
26
+ constructor(o, out = (m) => { if (!quiet())
27
+ console.info(m); }) {
28
+ this.o = o;
29
+ this.out = out;
30
+ this.st = { traces: 'pending', logs: 'pending', metrics: 'pending' };
31
+ for (const s of o.off ?? [])
32
+ this.st[s] = 'off';
33
+ // a signal that never fires (no logs yet, metrics every 60 s) must not hide the line forever
34
+ const t = setTimeout(() => this.print(), 90_000);
35
+ t.unref?.();
36
+ }
37
+ /** One result for `signal`: the first failure and the last pending signal turning ok both print the line. */
38
+ record(signal, items, r) {
39
+ const fail = r.code !== 0;
40
+ const why = fail ? failure(r.error) : '';
41
+ (0, exports.debug)(`export ${signal} items=${items} ${fail ? `fail(${why})` : 'ok'}`);
42
+ if (fail) {
43
+ if (this.st[signal] !== 'ok')
44
+ this.st[signal] = `fail(${why})`;
45
+ this.print();
46
+ return;
47
+ }
48
+ this.st[signal] = 'ok';
49
+ if (Object.values(this.st).every((s) => s !== 'pending'))
50
+ this.print();
51
+ }
52
+ print() {
53
+ if (this.printed)
54
+ return;
55
+ this.printed = true;
56
+ let host = this.o.endpoint;
57
+ try {
58
+ host = new URL(this.o.endpoint).host;
59
+ }
60
+ catch { /* keep as given */ }
61
+ const s = this.st;
62
+ this.out(`[watchtower] ${this.o.service} → ${host} traces:${s.traces} logs:${s.logs} metrics:${s.metrics} release=${this.o.release ?? 'none'}`);
63
+ }
64
+ }
65
+ exports.StatusLine = StatusLine;
66
+ const countMetrics = (m) => (m?.scopeMetrics ?? []).reduce((n, s) => n + s.metrics.length, 0);
67
+ function watch(inner, signal, line, count) {
68
+ const wrapped = Object.create(inner); // keeps every other exporter method (selectAggregation etc.)
69
+ wrapped.export = (items, done) => inner.export(items, (r) => { line.record(signal, count(items), r); done(r); });
70
+ return wrapped;
71
+ }
72
+ const watchSpans = (e, l) => watch(e, 'traces', l, (i) => i.length);
73
+ exports.watchSpans = watchSpans;
74
+ const watchLogs = (e, l) => watch(e, 'logs', l, (i) => i.length);
75
+ exports.watchLogs = watchLogs;
76
+ const watchMetrics = (e, l) => watch(e, 'metrics', l, countMetrics);
77
+ exports.watchMetrics = watchMetrics;
78
+ // Drop counters: Next-internal spans (sampling) and DB queries without a parent span. Summarised per minute under WT_DEBUG.
79
+ const drops = new Map();
80
+ let timer;
81
+ function noteDrop(kind) {
82
+ drops.set(kind, (drops.get(kind) ?? 0) + 1);
83
+ if (!timer && (0, exports.debugOn)()) {
84
+ timer = setInterval(flushDrops, 60_000);
85
+ timer.unref?.();
86
+ }
87
+ }
88
+ function flushDrops() {
89
+ if (drops.size)
90
+ (0, exports.debug)(`dropped in the last minute: ${[...drops].map(([k, n]) => `${n} ${k}`).join(', ')}`);
91
+ drops.clear();
92
+ }
@@ -1,4 +1,3 @@
1
- // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
1
  import type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace';
3
2
  export declare function filterExporter(inner: SpanExporter, keep: (s: ReadableSpan) => boolean): SpanExporter;
4
3
  /**
@@ -1,13 +1,9 @@
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)
5
4
  import type { Resource } from '@opentelemetry/resources';
6
- // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
7
5
  import type { ReadableSpan, TracerProvider } from '@opentelemetry/sdk-trace';
8
- // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
9
6
  import type { LoggerProvider } from '@opentelemetry/sdk-logs';
10
- // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
11
7
  import type { MeterProvider } from '@opentelemetry/sdk-metrics';
12
8
  import type { RedactHook } from './redact.js';
13
9
  import type { RedactPreset } from './redact-presets.js';
@@ -208,6 +204,7 @@ export declare class Client implements InitStatus {
208
204
  observe<A extends unknown[], R>(name: string, fn: (...a: A) => R): (...a: A) => R;
209
205
  shutdown(): Promise<void>;
210
206
  }
207
+ /** Never throws: when a peer is missing, the key is absent or startup fails, it warns once, leaves telemetry off and returns a no-op client. */
211
208
  export declare function init(opts: InitOptions): Client;
212
209
  /** Why telemetry is off (set by the preload when it cannot start); shown on the first dropped helper call. */
213
210
  export declare const setOffReason: (r: string) => void;
package/dist/cjs/index.js CHANGED
@@ -39,6 +39,7 @@ exports.safeResource = safeResource;
39
39
  exports.init = init;
40
40
  // Thin Watchtower layer over the OpenTelemetry Node SDK: key header, endpoint default,
41
41
  // offline buffer, wt.*-safe resource attributes, redaction hook, getPrompt/score/evaluate/observe.
42
+ const late_js_1 = require("./late.js"); // first: snapshots which builtins were loaded before the SDK
42
43
  const node_util_1 = require("node:util");
43
44
  const api_1 = require("@opentelemetry/api");
44
45
  Object.defineProperty(exports, "metrics", { enumerable: true, get: function () { return api_1.metrics; } });
@@ -53,6 +54,7 @@ const attach_js_1 = require("./attach.js");
53
54
  const scrub_js_1 = require("./scrub.js");
54
55
  const filter_js_1 = require("./filter.js");
55
56
  const next_filter_js_1 = require("./next-filter.js");
57
+ const diagnostics_js_1 = require("./diagnostics.js");
56
58
  const checkin_js_1 = require("./checkin.js");
57
59
  const monitor_js_1 = require("./cron/monitor.js");
58
60
  const shutdown_js_1 = require("./shutdown.js");
@@ -154,6 +156,11 @@ class Client {
154
156
  this.redact = red.hook;
155
157
  this.scrubUrls = o.urlScrubbing ?? red.preset !== 'off';
156
158
  this.logCaller = o.logCaller ?? env.WATCHTOWER_LOG_CALLER === '1';
159
+ const logsOn = (0, metrics_js_1.switchOn)('WATCHTOWER_LOGS', 'OTEL_LOGS_EXPORTER', o.logs ?? (o.logExporter ? true : undefined));
160
+ const metricsOn = (0, metrics_js_1.switchOn)('WATCHTOWER_METRICS', 'OTEL_METRICS_EXPORTER', o.metrics ?? (o.metricExporter ? true : undefined));
161
+ // one status line per process, fed by the default OTLP exporters (explicit test exporters are left alone)
162
+ const line = new diagnostics_js_1.StatusLine({ service: String(resource.attributes['service.name']), endpoint: this.endpoint, release, off: [...(logsOn ? [] : ['logs']), ...(metricsOn ? [] : ['metrics'])] });
163
+ (0, diagnostics_js_1.debug)(`exporters: ${this.endpoint}/v1/traces, /v1/logs, /v1/metrics key=${(0, diagnostics_js_1.keyHint)(apiKey)}`);
157
164
  let exporter = o.exporter;
158
165
  if (!exporter) {
159
166
  const url = `${this.endpoint}/v1/traces`;
@@ -162,6 +169,7 @@ class Client {
162
169
  // spans and log records spool to their own subdirectories
163
170
  if (o.bufferDir)
164
171
  exporter = new buffer_js_1.SpoolExporter(exporter, nodePath.join(o.bufferDir, 'traces'), url, this.headers, this.fetch);
172
+ exporter = (0, diagnostics_js_1.watchSpans)(exporter, line);
165
173
  }
166
174
  const keepNoisy = o.noisySpans ?? env.WT_NOISY_SPANS === '1';
167
175
  const user = o.spanFilter;
@@ -199,7 +207,6 @@ class Client {
199
207
  }
200
208
  this.tracer = this.provider.getTracer('watchtower');
201
209
  // an explicit exporter never switches the other signals off: only `logs` / `metrics` / the env switches do
202
- const logsOn = (0, metrics_js_1.switchOn)('WATCHTOWER_LOGS', 'OTEL_LOGS_EXPORTER', o.logs ?? (o.logExporter ? true : undefined));
203
210
  this.logs = logsOn ? 'ok' : 'disabled';
204
211
  let logExporter = logsOn ? o.logExporter : undefined;
205
212
  if (logsOn && !logExporter) {
@@ -208,6 +215,7 @@ class Client {
208
215
  logExporter = new OTLPLogExporter({ url, headers: this.headers });
209
216
  if (o.bufferDir)
210
217
  logExporter = (0, buffer_js_1.spoolLogs)(logExporter, nodePath.join(o.bufferDir, 'logs'), url, this.headers, this.fetch);
218
+ logExporter = (0, diagnostics_js_1.watchLogs)(logExporter, line);
211
219
  }
212
220
  const { LoggerProvider: LP, BatchLogRecordProcessor } = (0, load_js_1.need)('@opentelemetry/sdk-logs');
213
221
  this.loggerProvider = new LP({
@@ -215,8 +223,8 @@ class Client {
215
223
  processors: !logExporter ? [] : [new BatchLogRecordProcessor({ exporter: logExporter })],
216
224
  });
217
225
  this.logger = this.loggerProvider.getLogger('watchtower');
218
- if ((0, metrics_js_1.switchOn)('WATCHTOWER_METRICS', 'OTEL_METRICS_EXPORTER', o.metrics ?? (o.metricExporter ? true : undefined))) {
219
- const m = (0, metrics_js_1.startMetrics)(this.endpoint, this.headers, resource, o.bufferDir, this.fetch, o.metricExporter);
226
+ if (metricsOn) {
227
+ const m = (0, metrics_js_1.startMetrics)(this.endpoint, this.headers, resource, o.bufferDir, this.fetch, o.metricExporter, (e) => (0, diagnostics_js_1.watchMetrics)(e, line));
220
228
  this.meterProvider = m.provider;
221
229
  this.stopRuntime = m.stop;
222
230
  }
@@ -404,14 +412,44 @@ function registerGlobals(c) {
404
412
  api_1.diag.warn(w);
405
413
  }
406
414
  }
415
+ /** A Client-shaped stand-in for when telemetry cannot start: every method does nothing, observe/checkin pass the function through. */
416
+ function offClient() {
417
+ const fns = {
418
+ observe: (_n, f) => f,
419
+ checkin: (_s, f) => Promise.resolve().then(f),
420
+ log: () => undefined,
421
+ toJSON: () => ({}),
422
+ evaluate: () => Promise.resolve([]),
423
+ evaluateResume: () => Promise.resolve([]),
424
+ };
425
+ const plain = { traces: 'disabled', metrics: 'disabled', logs: 'disabled', blocked: [], warnings: [], attached: false };
426
+ return new Proxy({}, { get: (_t, k) => (typeof k === 'symbol' || k === 'then' ? undefined : k in plain ? plain[k] : fns[k] ?? (() => Promise.resolve(undefined))) });
427
+ }
428
+ /** Never throws: when a peer is missing, the key is absent or startup fails, it warns once, leaves telemetry off and returns a no-op client. */
407
429
  function init(opts) {
408
- (0, env_js_1.defaultResourceDetectors)(); // before any NodeSDK reads OTEL_NODE_RESOURCE_DETECTORS
409
430
  const missing = (0, load_js_1.missingPeers)();
410
431
  if (missing.length)
411
- console.warn(`[watchtower] missing OpenTelemetry package(s): ${missing.join(', ')}. Next.js standalone: ${load_js_1.STANDALONE_HINT}. Otherwise: npm install ${missing.join(' ')}`);
432
+ return turnOff(`missing OpenTelemetry package(s): ${missing.join(', ')}. Next.js standalone: ${load_js_1.STANDALONE_HINT}. Otherwise: npm install ${missing.join(' ')}`);
433
+ try {
434
+ return start(opts);
435
+ }
436
+ catch (e) {
437
+ return turnOff(e?.message ?? String(e));
438
+ }
439
+ }
440
+ function turnOff(why) {
441
+ state.current = undefined;
442
+ (0, exports.setOffReason)(why);
443
+ console.warn(`[watchtower] telemetry is OFF: ${why}`);
444
+ return offClient();
445
+ }
446
+ function start(opts) {
447
+ (0, late_js_1.checkLate)();
448
+ (0, env_js_1.defaultResourceDetectors)(); // before any NodeSDK reads OTEL_NODE_RESOURCE_DETECTORS
412
449
  const nextMode = opts?.nextInternals ?? (process.env.NEXT_RUNTIME ? 'sample' : undefined);
413
450
  if (nextMode) {
414
- const own = (0, next_filter_js_1.nextInternalsFilter)(nextMode, opts?.nextInternalsRate);
451
+ const base = (0, next_filter_js_1.nextInternalsFilter)(nextMode, opts?.nextInternalsRate);
452
+ const own = (s) => base(s) || ((0, diagnostics_js_1.noteDrop)('Next.js internal spans (nextInternals sampling)'), false);
415
453
  const user = opts.spanFilter;
416
454
  opts = { ...opts, nextInternals: undefined, spanFilter: user ? (s) => own(s) && user(s) : own }; // cleared: a second init() never stacks the filter
417
455
  }
@@ -430,9 +468,6 @@ function init(opts) {
430
468
  if (mode === 'auto' && logOn) {
431
469
  console.info(`[watchtower] instrumented: ${names.map((n) => n.replace('@opentelemetry/instrumentation-', '')).join(', ') || 'nothing (no supported package found)'}`);
432
470
  }
433
- if (logOn && (0, db_js_1.dbRequireParent)(undefined)) {
434
- console.info('watchtower: requireParent on; queries outside a span are not recorded (WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)');
435
- }
436
471
  }
437
472
  if (process.env.WT_PROFILING === '1') {
438
473
  const attrs = c.resource.attributes;
@@ -51,6 +51,7 @@ exports.sizeOf = sizeOf;
51
51
  const fs = __importStar(require("node:fs"));
52
52
  const nodePath = __importStar(require("node:path"));
53
53
  const api_1 = require("@opentelemetry/api");
54
+ const diagnostics_js_1 = require("../diagnostics.js");
54
55
  const sql_js_1 = require("../sql.js");
55
56
  /** Set inside an instrumented call so a wrapper the library calls internally adds no second span. */
56
57
  const INSIDE = (0, api_1.createContextKey)('watchtower.db.inside');
@@ -95,10 +96,11 @@ let droppedCounter;
95
96
  /** Datastore spans dropped so far because `requireParent` found no active parent span. */
96
97
  const droppedDbSpans = () => droppedSpans;
97
98
  exports.droppedDbSpans = droppedDbSpans;
98
- /** Count a dropped span: the `wt.sdk.db.dropped_spans` counter (exported with the SDK's metrics) and one diag warning. */
99
+ /** Count a dropped span: the `wt.sdk.db.dropped_spans` counter (exported with the SDK's metrics) and one console line (the first drop). */
99
100
  function dropped() {
100
101
  if (droppedSpans++ === 0)
101
- api_1.diag.warn('watchtower: a datastore span was dropped because it has no parent span (requireParent); counted in wt.sdk.db.dropped_spans. Set WATCHTOWER_DB_REQUIRE_PARENT=0 to keep such queries as root spans');
102
+ console.info('[watchtower] dropped a DB query outside any span (requireParent on; WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)');
103
+ (0, diagnostics_js_1.noteDrop)('DB queries outside any span');
102
104
  droppedCounter ??= api_1.metrics.getMeter('watchtower').createCounter('wt.sdk.db.dropped_spans', { description: 'Datastore spans dropped for lack of a parent span (requireParent)' });
103
105
  droppedCounter.add(1);
104
106
  return api_1.trace.wrapSpanContext(api_1.INVALID_SPAN_CONTEXT);
@@ -51,16 +51,18 @@ export declare function tracingIncludes(ids: string[], cwd?: string): string[];
51
51
  * the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
52
52
  * `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
53
53
  * client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
54
+ * @deprecated use `withWatchtower` from `@watchtowerobservability/next`
54
55
  */
55
56
  export declare function withWatchtower(config?: ConfigOrFn, opts?: WatchtowerNextOptions): ConfigOrFn;
56
57
  /** A ustar archive of `[name, bytes]` (names up to 100 bytes). */
57
58
  export declare function makeTar(files: [string, Buffer][]): Buffer;
58
59
  /**
59
- * Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~120 MB
60
+ * Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~32 MB
60
61
  * batch (tar.gz plus manifest), falling back to single uploads (8 at a time) when the server has no bundle route.
61
62
  * 429/5xx are retried with backoff honoring Retry-After; a failed map does not stop the others. The maps are deleted when none failed. Returns
62
63
  * `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
63
64
  * gzipped (`Content-Encoding: gzip`).
65
+ * @deprecated use `@watchtowerobservability/next`
64
66
  */
65
67
  export declare function uploadSourcemaps(o?: SourcemapOptions): Promise<{
66
68
  uploaded: number;
@@ -39,6 +39,7 @@ exports.tracingIncludes = tracingIncludes;
39
39
  exports.withWatchtower = withWatchtower;
40
40
  exports.makeTar = makeTar;
41
41
  exports.uploadSourcemaps = uploadSourcemaps;
42
+ // Deprecated entry (`@watchtowerobservability/node/next-build`): use `@watchtowerobservability/next`. Still works unchanged.
42
43
  // Build-time helpers for Next.js: `withWatchtower` (next.config) and `uploadSourcemaps` (after `next build`).
43
44
  const fs = __importStar(require("node:fs"));
44
45
  const nodePath = __importStar(require("node:path"));
@@ -123,6 +124,7 @@ const SHA_ENV = ['WT_RELEASE', 'GITHUB_SHA', 'CI_COMMIT_SHA', 'VERCEL_GIT_COMMIT
123
124
  * the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
124
125
  * `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
125
126
  * client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
127
+ * @deprecated use `withWatchtower` from `@watchtowerobservability/next`
126
128
  */
127
129
  function withWatchtower(config = {}, opts = {}) {
128
130
  const sm = opts.sourcemaps === true ? {} : opts.sourcemaps || undefined;
@@ -218,11 +220,12 @@ function chunkFor(mapFile, name) {
218
220
  return undefined;
219
221
  }
220
222
  /**
221
- * Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~120 MB
223
+ * Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~32 MB
222
224
  * batch (tar.gz plus manifest), falling back to single uploads (8 at a time) when the server has no bundle route.
223
225
  * 429/5xx are retried with backoff honoring Retry-After; a failed map does not stop the others. The maps are deleted when none failed. Returns
224
226
  * `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
225
227
  * gzipped (`Content-Encoding: gzip`).
228
+ * @deprecated use `@watchtowerobservability/next`
226
229
  */
227
230
  async function uploadSourcemaps(o = {}) {
228
231
  const env = process.env;
@@ -306,7 +309,7 @@ async function uploadSourcemaps(o = {}) {
306
309
  };
307
310
  // One request per batch (tar.gz + manifest). A server without the bundle route (or a request that
308
311
  // never got through) falls back to concurrent single uploads for that batch.
309
- const BATCH_BYTES = 120 * 1024 * 1024;
312
+ const BATCH_BYTES = 32 * 1024 * 1024; // smaller requests keep the API's upload memory low
310
313
  const batches = [];
311
314
  let cur = [], curBytes = 0;
312
315
  for (const e of entries) {
@@ -0,0 +1,13 @@
1
+ type Opts = Record<string, unknown>;
2
+ export type NextOptions = Opts;
3
+ export type SourcemapOptions = Opts;
4
+ export type TunnelOptions = Opts;
5
+ /** @deprecated use `@watchtowerobservability/next` */
6
+ export declare const makeRegister: (_options?: NextOptions) => (() => Promise<void>);
7
+ /** @deprecated use `@watchtowerobservability/next` */
8
+ export declare const register: () => Promise<void>;
9
+ /** @deprecated use `@watchtowerobservability/next` */
10
+ export declare function onRequestError(_err?: unknown, _request?: unknown, _context?: unknown): Promise<void>;
11
+ /** @deprecated use `@watchtowerobservability/next` */
12
+ export declare const withWatchtower: <T>(config: T, _opts?: Opts) => T;
13
+ export {};
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withWatchtower = exports.register = exports.makeRegister = void 0;
4
+ exports.onRequestError = onRequestError;
5
+ /** @deprecated use `@watchtowerobservability/next` */
6
+ const makeRegister = (_options = {}) => async () => { };
7
+ exports.makeRegister = makeRegister;
8
+ /** @deprecated use `@watchtowerobservability/next` */
9
+ exports.register = (0, exports.makeRegister)();
10
+ /** @deprecated use `@watchtowerobservability/next` */
11
+ async function onRequestError(_err, _request, _context) { }
12
+ /** @deprecated use `@watchtowerobservability/next` */
13
+ const withWatchtower = (config, _opts) => config;
14
+ exports.withWatchtower = withWatchtower;
@@ -1,15 +1,22 @@
1
1
  import * as wt from '../index.js';
2
- export { withWatchtower, uploadSourcemaps } from './next-build.js';
2
+ import * as build from './next-build.js';
3
+ /** @deprecated use `withWatchtower` from `@watchtowerobservability/next` */
4
+ export declare const withWatchtower: typeof build.withWatchtower;
5
+ /** @deprecated use `uploadSourcemaps` from `@watchtowerobservability/next` */
6
+ export declare const uploadSourcemaps: typeof build.uploadSourcemaps;
3
7
  export type { SourcemapOptions } from './next-build.js';
4
8
  export { isNextInternal, nextInternalsFilter } from '../next-filter.js';
5
9
  export { tunnelHandler } from './next-tunnel.js';
6
10
  export type { TunnelOptions } from './next-tunnel.js';
7
11
  export type NextOptions = wt.InitOptions;
8
- /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
12
+ /** @deprecated use `register` from `@watchtowerobservability/next`.
13
+ * Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
9
14
  export declare function makeRegister(options?: NextOptions): () => Promise<void>;
10
- /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
15
+ /** @deprecated use `register` from `@watchtowerobservability/next`.
16
+ * Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
11
17
  export declare const register: () => Promise<void>;
12
- /** Next.js onRequestError: server render, route handler and server action errors. */
18
+ /** @deprecated use `onRequestError` from `@watchtowerobservability/next`.
19
+ * Next.js onRequestError: server render, route handler and server action errors. */
13
20
  export declare function onRequestError(err: unknown, request?: {
14
21
  path?: string;
15
22
  method?: string;
@@ -36,18 +36,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.register = exports.tunnelHandler = exports.nextInternalsFilter = exports.isNextInternal = exports.uploadSourcemaps = exports.withWatchtower = void 0;
37
37
  exports.makeRegister = makeRegister;
38
38
  exports.onRequestError = onRequestError;
39
+ // Deprecated entry: use `@watchtowerobservability/next` (register, onRequestError, withWatchtower). Still works unchanged.
39
40
  // instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
40
41
  // or, with options: export const register = makeRegister({ redact }); export { onRequestError } from '@watchtowerobservability/node/next';
41
42
  const wt = __importStar(require("../index.js"));
42
- var next_build_js_1 = require("./next-build.js");
43
- Object.defineProperty(exports, "withWatchtower", { enumerable: true, get: function () { return next_build_js_1.withWatchtower; } });
44
- Object.defineProperty(exports, "uploadSourcemaps", { enumerable: true, get: function () { return next_build_js_1.uploadSourcemaps; } });
43
+ const build = __importStar(require("./next-build.js"));
44
+ /** @deprecated use `withWatchtower` from `@watchtowerobservability/next` */
45
+ exports.withWatchtower = build.withWatchtower;
46
+ /** @deprecated use `uploadSourcemaps` from `@watchtowerobservability/next` */
47
+ exports.uploadSourcemaps = build.uploadSourcemaps;
45
48
  var next_filter_js_1 = require("../next-filter.js");
46
49
  Object.defineProperty(exports, "isNextInternal", { enumerable: true, get: function () { return next_filter_js_1.isNextInternal; } });
47
50
  Object.defineProperty(exports, "nextInternalsFilter", { enumerable: true, get: function () { return next_filter_js_1.nextInternalsFilter; } });
48
51
  var next_tunnel_js_1 = require("./next-tunnel.js");
49
52
  Object.defineProperty(exports, "tunnelHandler", { enumerable: true, get: function () { return next_tunnel_js_1.tunnelHandler; } });
50
- /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
53
+ /** @deprecated use `register` from `@watchtowerobservability/next`.
54
+ * Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
51
55
  function makeRegister(options = {}) {
52
56
  return async function register() {
53
57
  const rt = process.env.NEXT_RUNTIME;
@@ -56,9 +60,11 @@ function makeRegister(options = {}) {
56
60
  wt.init({ ...options, nextInternals: options.nextInternals ?? 'sample' }); // init() applies the filter (once)
57
61
  };
58
62
  }
59
- /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
63
+ /** @deprecated use `register` from `@watchtowerobservability/next`.
64
+ * Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
60
65
  exports.register = makeRegister();
61
- /** Next.js onRequestError: server render, route handler and server action errors. */
66
+ /** @deprecated use `onRequestError` from `@watchtowerobservability/next`.
67
+ * Next.js onRequestError: server render, route handler and server action errors. */
62
68
  async function onRequestError(err, request, context) {
63
69
  const c = context || {};
64
70
  wt.captureException(err, {
@@ -0,0 +1,7 @@
1
+ /** Which of http/https are in `list` (default: this process's loaded builtins). */
2
+ export declare const lateModules: (list?: readonly string[]) => string[];
3
+ export declare const LATE_HINT = "Start node with --import @watchtowerobservability/node/register";
4
+ /** Prints once per process (global flag, so the CJS and ESM copies share it). */
5
+ export declare function warnLate(mods: string[], out?: (m: string) => void): void;
6
+ /** The entry points call this: silent under Next (it loads http before instrumentation runs) and in test runners. */
7
+ export declare function checkLate(): void;