@watchtowerobservability/node 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +13 -7
  3. package/dist/cjs/buffer.d.ts +3 -0
  4. package/dist/cjs/filter.d.ts +1 -0
  5. package/dist/cjs/index.d.ts +13 -0
  6. package/dist/cjs/index.js +12 -1
  7. package/dist/cjs/integrations/next-build.d.ts +9 -2
  8. package/dist/cjs/integrations/next-build.js +81 -17
  9. package/dist/cjs/integrations/next-tunnel.js +2 -2
  10. package/dist/cjs/integrations/next.d.ts +2 -16
  11. package/dist/cjs/integrations/next.js +5 -23
  12. package/dist/cjs/load.js +20 -36
  13. package/dist/cjs/metrics.d.ts +2 -0
  14. package/dist/cjs/next-filter.d.ts +6 -0
  15. package/dist/cjs/next-filter.js +22 -0
  16. package/dist/cjs/next-sourcemaps-cli.js +2 -1
  17. package/dist/cjs/origin.d.ts +1 -0
  18. package/dist/cjs/redact.d.ts +1 -0
  19. package/dist/cjs/register.js +11 -0
  20. package/dist/cjs/sampling.d.ts +1 -0
  21. package/dist/cjs/scrub.d.ts +1 -0
  22. package/dist/cjs/version.d.ts +1 -1
  23. package/dist/cjs/version.js +1 -1
  24. package/dist/esm/buffer.d.ts +3 -0
  25. package/dist/esm/filter.d.ts +1 -0
  26. package/dist/esm/index.d.ts +13 -0
  27. package/dist/esm/index.js +12 -1
  28. package/dist/esm/integrations/next-build.d.ts +9 -2
  29. package/dist/esm/integrations/next-build.js +81 -17
  30. package/dist/esm/integrations/next-tunnel.js +2 -2
  31. package/dist/esm/integrations/next.d.ts +2 -16
  32. package/dist/esm/integrations/next.js +2 -20
  33. package/dist/esm/load.js +20 -62
  34. package/dist/esm/metrics.d.ts +2 -0
  35. package/dist/esm/next-filter.d.ts +6 -0
  36. package/dist/esm/next-filter.js +18 -0
  37. package/dist/esm/next-sourcemaps-cli.js +2 -1
  38. package/dist/esm/origin.d.ts +1 -0
  39. package/dist/esm/redact.d.ts +1 -0
  40. package/dist/esm/register.js +11 -0
  41. package/dist/esm/sampling.d.ts +1 -0
  42. package/dist/esm/scrub.d.ts +1 -0
  43. package/dist/esm/version.d.ts +1 -1
  44. package/dist/esm/version.js +1 -1
  45. package/package.json +13 -2
package/CHANGELOG.md ADDED
@@ -0,0 +1,70 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.7.2
6
+
7
+ - `wt-next-sourcemaps` / `uploadSourcemaps()`: default API is `https://watchtowerops.net` (the old default did not resolve); one env name `WT_API_URL` (`WT_API` still works with a warning); a bad host fails fast naming it. Uploads run 8 at a time, retry 429/5xx honoring `Retry-After`, continue past failures, print `{uploaded, skipped, failed}` and exit 1 when any failed. Each map is sent with `for=<chunk path>`. Bodies are sent gzipped. `uploadSourcemaps()` now resolves `{uploaded, skipped, failed}` instead of throwing on a failed map.
8
+ - `init()` applies `nextInternals` itself when `NEXT_RUNTIME` is set (new `InitOptions.nextInternals` / `nextInternalsRate`), so the documented `init()` in `register()` filters Next's internal spans; never installed twice. Root `next.span_type` INTERNAL spans are sampled too (test with a parentless span).
9
+ - Next tunnel forwards `/v1/traces`.
10
+ - New export `@watchtowerobservability/node/messaging` (`produce`, `consume`) and a custom-queue recipe in the README.
11
+ - Start log line when datastore `requireParent` is on (`watchtower: requireParent on; queries outside a span are not recorded (WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)`); silenced by `instrumentLog: false` / `WT_INSTRUMENT_LOG=0`.
12
+
13
+ ## 0.7.1
14
+
15
+ - Fix (bundlers): optional OpenTelemetry peers are no longer named by a literal `require` / `import()`; `load()` uses `createRequire` (from the SDK's location, then the app root), so webpack and Next no longer print "Module not found" for peers you did not install or a "Critical dependency" warning. Install the peers you use as direct dependencies of the app (for a Next standalone build add them to `outputFileTracingIncludes` if the tracer misses one).
16
+ - Fix (types): emitted `.d.ts` files mark every optional-peer import with `// @ts-ignore`, so `tsc` with `skipLibCheck: false` no longer fails with TS2307 when a peer is not installed (the type is `any` then, the real type when installed). `scripts/dts-peers.mjs` does it at build time; `test/dts-peers.test.ts` checks it.
17
+ - Fix: the `register` preload no longer prints Node 26's `DEP0205` (`module.register()`) deprecation warning.
18
+
19
+ ## 0.7.0
20
+
21
+ - URL scrubbing on by default (`urlScrubbing: false` to opt out): a span processor drops the query string, removes `url.query` and replaces secret-looking path segments (>= 24 chars, or >= 10 chars with a letter and a digit; UUIDs too) with `:redacted` in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names, on every span including Next.js, http and fetch spans. `http.route` is kept. README no longer claims query strings are "never recorded" without saying how. Behaviour change: URLs that carried long ids now show `:redacted`.
22
+ - SQL summaries: `CREATE TABLE IF NOT EXISTS forms` is `CREATE TABLE forms`, `CREATE [UNIQUE] INDEX x ON forms` is `CREATE INDEX forms` (TEMP and VIRTUAL too); `DROP TABLE IF EXISTS` no longer reports `IF`. `db.operation.name` is `CREATE TABLE` / `CREATE INDEX` for these.
23
+ - `DbOptions.requireParent` (default true, `WATCHTOWER_DB_REQUIRE_PARENT=0` to turn off): datastore spans are recorded only under an active span, which keeps startup DDL, migrations and polling loops out. **Behaviour change** for every datastore integration and postgres.js: queries run outside any span used to become root traces and no longer do; pass `requireParent: false` to restore that.
24
+ - Resource attributes `telemetry.sdk.name/language/version` (from the OTel SDK) and `telemetry.distro.name=watchtower`, `telemetry.distro.version`. They were never set before (a bare resource was built; nothing stripped them), so the coverage report showed no SDK.
25
+ - `/next`: `nextInternals: 'drop' | 'sample' | 'keep'` (default `'sample'` at `nextInternalsRate` 0.1) for Next's internal spans (`next.span_type`); request, route-handler, render, server-action, fetch, SERVER/CLIENT and errored spans are kept. New `spanFilter` init option.
26
+ - `/next`: `withWatchtower(nextConfig, { sourcemaps })` (turns on `productionBrowserSourceMaps`), `uploadSourcemaps()` and the `wt-next-sourcemaps` bin (uploads `.next/static` maps with `WT_API_KEY` (scope `ci:write`), `WT_PROJECT`, `WT_RELEASE`, then deletes them), and `tunnelHandler({ endpoint })` for a first-party `app/api/wt/[...path]/route.ts` that forwards only the browser RUM paths.
27
+ - `instrument: 'auto'` (or `WT_INSTRUMENT=auto`): also patches postgres.js, better-sqlite3 and mysql2 (new optional peer `@opentelemetry/instrumentation-mysql2`) when installed and logs one line naming what was patched (`instrumentLog: false` / `WT_INSTRUMENT_LOG=0`).
28
+ - `wt.checkin(monitorSlug, fn)` cron helper over `POST /v1/checkins/{slug}` (key scope `ingest:checkins`).
29
+ - `init` now flushes on SIGTERM and SIGINT (2 s cap) and re-sends the signal when no other handler is registered. Not done before: a SIGTERM exited without flushing. Under `next start` Next's own handler still decides the exit.
30
+
31
+ ## 0.6.0
32
+
33
+ - Fix: the ESM build was unimportable (`dist/esm/load.js` lacked `need`). The ESM loader is now the compiled `load.ts` with a `createRequire`; `npm run smoke` packs, installs and imports both builds.
34
+ - Bundling: OpenTelemetry peers are required by literal name inside try blocks, so webpack, esbuild and Next's file tracer can follow them. README has a Next.js recipe.
35
+ - `redact` now also runs on span names (`span.name`), status messages (`status.message`), every span event's and link's attributes (including `exception.message` / `exception.stacktrace`) and log bodies (`log.body`). `@watchtowerobservability/node/next` exports `makeRegister(options)`; `register` is unchanged.
36
+ - `init` no longer disables the OpenTelemetry globals: it registers only those not yet set (a warning says when one was kept) and tears down only what an earlier `init` installed.
37
+ - Passing `exporter` no longer turns off the default log and metric exporters (use `logs: false` / `metrics: false`); an explicit `logExporter` / `metricExporter` turns its signal on and logs always go through a batch processor.
38
+ - Auto-instrumentation: `instrument` option (default on) for installed `@opentelemetry/instrumentation-{http,undici,pg,ioredis}` optional peers, and a `@watchtowerobservability/node/register` preload entry.
39
+ - `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` are read after the `WT_*` variables; `service.version` from `OTEL_RESOURCE_ATTRIBUTES` is the release.
40
+ - README: npm install instructions (no token, no tarball).
41
+
42
+ ## 0.5.0
43
+
44
+ - `@opentelemetry/api` is now the only hard dependency. The SDK packages (`sdk-trace`, `sdk-logs`, `sdk-metrics`, `resources`, `core`, `context-async-hooks`, `otlp-transformer` and the three OTLP/HTTP exporters) are optional peer dependencies, loaded when `init` runs; if one is missing, `init` throws an error that lists what to `npm install`. Install them next to the SDK (see the README). Same ranges as before (SDK 3.1, exporters 0.301).
45
+
46
+ - OpenTelemetry moves to the current majors: API 1.10, SDK packages 3.1 (`sdk-trace`, `sdk-metrics`, `sdk-logs`, `resources`, `core`) and the 0.301 exporters, replacing the 1.30 / 0.57 stack. Node 22.15 or newer is required (the OTel 3.x packages need it). `NodeTracerProvider` is gone upstream, so `init` registers the async-hooks context manager, the W3C propagators and the tracer provider itself; `Client.provider` is now an SDK `TracerProvider` and `Client.resource` is new. A span's parent is `parentSpanContext?.spanId` (was `parentSpanId`). The optional peer `@opentelemetry/instrumentation-runtime-node` is `>=0.38`.
47
+
48
+ - Datastores and queues: new subpaths `sql` (shared SQL normalizer and `db.query.hash`, same as the server), `sqlite` (node:sqlite, better-sqlite3, sqlite3, libSQL), `duckdb`, `lmdb`, `level` (LevelDB/RocksDB), `cache` (node-cache, lru-cache, Keyv hit/miss), `pools` (MongoDB, mysql2, any pool), `orm` (Drizzle, Kysely, TypeORM, Sequelize, MikroORM), `amqp` (amqplib, rabbitmq-client), `nats`, `mqtt`, `pg-boss`, `graphile-worker`. SQL spans carry an N+1 hint (`db.n_plus_one`, `db.query.repeat_count`); statement text is opt-in (`queryText` / `WATCHTOWER_DB_QUERY_TEXT=1`) and literal-free. postgres.js spans gain `db.query.hash`; `querySummary` also returns `target`.
49
+ - Metrics: the OTel metrics SDK with a periodic OTLP reader (delta temporality by default), set as the global meter provider by `init`; runtime metrics through the optional peer `@opentelemetry/instrumentation-runtime-node`; spooled to `bufferDir/metrics`. `WATCHTOWER_LOGS` / `WATCHTOWER_METRICS` (or `logs` / `metrics` options) switch the two signals, default on.
50
+
51
+ - GenAI: `instrumentMistral`, `instrumentOllama`, `instrumentLlamaIndex(Settings)` and `instrumentOpenAIAgents(addTraceProcessor)`. Streams (`stream: true`, Mistral `chat.stream`) keep the span open until the stream ends and record time to first chunk, usage and finish reasons; tool calls become `gen_ai.tool.call` span events (name and id only) for every wrapper.
52
+ - Offline buffer: log records are spooled too. `bufferDir` now holds `traces/` and `logs/` subdirectories (at most 500 batches each, oldest dropped, replayed oldest first before the next export); batches spooled by older versions in the root of `bufferDir` are not replayed.
53
+ - GenAI: `instrumentBedrock` (Converse/InvokeModel via `send`), `instrumentGoogleGenAI` (`models.generateContent`, Gemini or Vertex AI) and a gateway name for `instrumentOpenAI(client, 'litellm')`.
54
+
55
+ ## 0.2.0
56
+
57
+ - TypeScript source with generated type declarations; dual ESM and CommonJS build (`dist/esm`, `dist/cjs`).
58
+ - No API change: same exports, subpaths, options, environment variables and behavior.
59
+ - New: the `jest` and `vitest` reporter subpaths now ship types.
60
+
61
+ ## 0.1.0
62
+
63
+ - Init over the OpenTelemetry Node SDK: key header, `WT_OTLP_ENDPOINT`, offline buffer, redaction hook.
64
+ - Configuration from `WT_INGEST_KEY`, `WT_SERVICE`, `WT_ENVIRONMENT`, `WT_RELEASE`.
65
+ - Error capture: `captureException`, `uncaughtException` and `unhandledRejection` hooks, trace ids returned.
66
+ - OTLP logs (`log`) with pino and winston bridges.
67
+ - Integrations: express, fastify, koa, nestjs, next.js (instrumentation hook), prisma, AWS Lambda wrapper,
68
+ openai, anthropic and Vercel AI SDK GenAI spans.
69
+ - Jest and Vitest reporters, prompts, scores, evals.
70
+ - The key is masked in `console.log` and `JSON.stringify` output of the client.
package/README.md CHANGED
@@ -74,23 +74,23 @@ export const register = makeRegister({ redact: (k, v) => v }); // any InitOpti
74
74
  export { onRequestError } from '@watchtowerobservability/node/next';
75
75
  ```
76
76
 
77
- `makeRegister` also takes `nextInternals: 'drop' | 'sample' | 'keep'` (default `'sample'`, `nextInternalsRate` 0.1) for Next's
77
+ `init()` applies `nextInternals` itself when `NEXT_RUNTIME` is set, so a plain `init()` in `register()` is filtered too (no double install). `nextInternals: 'drop' | 'sample' | 'keep'` (default `'sample'`, `nextInternalsRate` 0.1) for Next's
78
78
  own spans (those with a `next.span_type` attribute: load route module, prepare route module, resolve page components, start
79
- response, middleware, generateMetadata). Request, route handler, render, server action and fetch spans, all SERVER/CLIENT
79
+ 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
80
80
  spans and errored spans are always kept; children of a dropped internal span stay in the trace.
81
81
 
82
82
  **Source maps.** `next.config.js`: `module.exports = withWatchtower(nextConfig, { sourcemaps: true })` (from
83
83
  `@watchtowerobservability/node/next`) turns on `productionBrowserSourceMaps`. Build with
84
84
  `"build": "next build && wt-next-sourcemaps"`: the `wt-next-sourcemaps` bin (or `uploadSourcemaps()`) uploads every `.map` under
85
85
  `.next/static` as `_next/static/<path>` for release `$WT_RELEASE` (create it first or let the upload create it; it must equal
86
- the browser SDK's `release`), with `$WT_API_KEY` and `$WT_PROJECT` (and `$WT_API_URL`), then deletes the `.map` files so they are
87
- never served. If an upload fails the command exits 1 and leaves the files. **Key scope: `ci:write`** (it covers releases and
86
+ 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
87
+ never served. Uploads run 8 at a time, 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
88
88
  artifacts; `admin:write` also works). Ingest keys cannot upload. Turbopack and webpack both emit these maps; Next does not inject
89
89
  debug ids, so maps match by release and file name.
90
90
 
91
91
  **First-party tunnel** (ad blockers block third-party telemetry hosts): `app/api/wt/[...path]/route.ts`:
92
92
  `export const { GET, POST } = tunnelHandler({ endpoint: process.env.WT_EDGE_URL! });`, then `init({ endpoint: '/api/wt', publishableKey })`
93
- in the browser SDK. Only `/v1/rum/*`, `/v1/replay/<session>/chunks` and `/v1/logs` are forwarded; the only credential passed on
93
+ in the browser SDK. Only `/v1/rum/*`, `/v1/replay/<session>/chunks`, `/v1/logs` and `/v1/traces` are forwarded; the only credential passed on
94
94
  is the publishable key (`?k=` or a `wtp_` bearer), cookies and other headers are dropped, bodies over 1 MiB get 413
95
95
  (`maxBodyBytes`). The visitor's IP is the server's, so geo comes from the Next host unless the edge is told otherwise.
96
96
 
@@ -99,9 +99,9 @@ registered it re-sends the signal so the exit is unchanged. Under `next start`,
99
99
  the server and calls `process.exit`; our flush starts first (the `register` hook runs before) and gets the time the server takes
100
100
  to close, so a very slow export can still be cut.
101
101
 
102
- Install the OpenTelemetry peers above in the app itself (with pnpm, as direct dependencies, so Next's standalone tracer copies them). The SDK requires each peer by its literal name, so webpack and Next's file tracer can follow them; if the SDK arrives through a transpiled workspace package, add it to `transpilePackages`. Add `outputFileTracingIncludes` for the peers only if the standalone build still reports a missing `@opentelemetry/*` package.
102
+ 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: add the peers you use to `outputFileTracingIncludes` (for example `{ '/*': ['./node_modules/@opentelemetry/**'] }`).
103
103
 
104
- Bundling with esbuild or webpack (ESM or CommonJS output) works: both the CommonJS and ESM builds name every optional peer with a literal `require`/`import()` inside try, so the bundler follows the peers you have installed and skips the rest.
104
+ 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.
105
105
 
106
106
  ## Integrations
107
107
 
@@ -294,6 +294,12 @@ with `error.type`; the error message is not recorded.
294
294
  - **Graphile Worker**: `instrumentAddJob(utils)` (or the runner from `run`) adds `_wt` to the payload.
295
295
  `wrapTaskList` runs each task in a consumer span, strips `_wt`, and instruments `helpers.addJob` so
296
296
  follow-up jobs stay in the trace. `quickAddJob` cannot be patched under ESM; use `utils.addJob`.
297
+ - **Custom queue** (a table, Redis list, anything without an integration): `import { produce, consume } from '@watchtowerobservability/node/messaging'`.
298
+ `produce('orders send', { 'messaging.system': 'my-queue', 'messaging.destination.name': 'orders' }, (headers) => insertJob(data, headers))`
299
+ runs a PRODUCER span and hands you the `traceparent` headers to store in the job row (a `headers jsonb` column).
300
+ The worker does `consume('orders process', { ...same attrs }, [row.headers], () => handle(row))`: a CONSUMER span
301
+ linked to (and, with one carrier, a child of) the producer, so the trace runs from request to job.
302
+
297
303
  - **kafkajs**: upstream `@opentelemetry/instrumentation-kafkajs` already covers it.
298
304
 
299
305
  ## Profiling
@@ -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. */
@@ -1,2 +1,3 @@
1
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
1
2
  import type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace';
2
3
  export declare function filterExporter(inner: SpanExporter, keep: (s: ReadableSpan) => boolean): SpanExporter;
@@ -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';
6
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
5
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';
@@ -72,6 +76,15 @@ export interface InitOptions {
72
76
  urlScrubbing?: boolean;
73
77
  /** Return false to drop a finished span before export (the `/next` entry uses it for `nextInternals`). */
74
78
  spanFilter?: (span: ReadableSpan) => boolean;
79
+ /**
80
+ * Next.js's own spans (`next.span_type` set: load route module, prepare route module, resolve page components, start
81
+ * response, middleware, generateMetadata ...), root ones included. `"sample"` keeps `nextInternalsRate` of them, `"drop"`
82
+ * none, `"keep"` all. Request, route handler, render, server action and fetch spans, every SERVER/CLIENT span and every
83
+ * errored span are always kept. Default: `"sample"` when `NEXT_RUNTIME` is set (Next.js), off otherwise.
84
+ */
85
+ nextInternals?: 'drop' | 'sample' | 'keep';
86
+ /** Share of internal spans kept with `nextInternals: "sample"`; default 0.1. */
87
+ nextInternalsRate?: number;
75
88
  /**
76
89
  * Patch node:http, fetch (undici), pg and ioredis for those whose `@opentelemetry/instrumentation-*` peer is installed; defaults to on unless WT_INSTRUMENT=0.
77
90
  * `'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
package/dist/cjs/index.js CHANGED
@@ -49,6 +49,7 @@ const instrument_js_1 = require("./instrument.js");
49
49
  const redact_js_1 = require("./redact.js");
50
50
  const scrub_js_1 = require("./scrub.js");
51
51
  const filter_js_1 = require("./filter.js");
52
+ const next_filter_js_1 = require("./next-filter.js");
52
53
  const checkin_js_1 = require("./checkin.js");
53
54
  const shutdown_js_1 = require("./shutdown.js");
54
55
  const version_js_1 = require("./version.js");
@@ -342,6 +343,12 @@ function registerGlobals(c) {
342
343
  api_1.diag.warn('watchtower: an OpenTelemetry global (tracer provider, context manager, propagator or meter provider) was already registered and was kept; call init() before other OTel setup to own them');
343
344
  }
344
345
  function init(opts) {
346
+ const nextMode = opts?.nextInternals ?? (process.env.NEXT_RUNTIME ? 'sample' : undefined);
347
+ if (nextMode) {
348
+ const own = (0, next_filter_js_1.nextInternalsFilter)(nextMode, opts?.nextInternalsRate);
349
+ const user = opts.spanFilter;
350
+ opts = { ...opts, nextInternals: undefined, spanFilter: user ? (s) => own(s) && user(s) : own }; // cleared: a second init() never stacks the filter
351
+ }
345
352
  if (state.current && state.current.uninstall)
346
353
  state.current.uninstall();
347
354
  void state.current?.profiler?.then((p) => p?.stop());
@@ -352,9 +359,13 @@ function init(opts) {
352
359
  const mode = opts?.instrument ?? (env === 'auto' ? 'auto' : !['0', 'off', 'false', 'no'].includes(env));
353
360
  if (mode) {
354
361
  const names = (0, instrument_js_1.instrumentAll)({ tracerProvider: c.provider, meterProvider: c.meterProvider }, [c.endpoint, c.apiUrl], mode === 'auto');
355
- if (mode === 'auto' && (opts?.instrumentLog ?? !['0', 'off', 'false', 'no'].includes((process.env.WT_INSTRUMENT_LOG || '').trim().toLowerCase()))) {
362
+ const logOn = opts?.instrumentLog ?? !['0', 'off', 'false', 'no'].includes((process.env.WT_INSTRUMENT_LOG || '').trim().toLowerCase());
363
+ if (mode === 'auto' && logOn) {
356
364
  console.info(`[watchtower] instrumented: ${names.map((n) => n.replace('@opentelemetry/instrumentation-', '')).join(', ') || 'nothing (no supported package found)'}`);
357
365
  }
366
+ if (logOn && !['0', 'false', 'off', 'no'].includes((process.env.WATCHTOWER_DB_REQUIRE_PARENT || '').trim().toLowerCase())) {
367
+ console.info('watchtower: requireParent on; queries outside a span are not recorded (WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)');
368
+ }
358
369
  }
359
370
  if (process.env.WT_PROFILING === '1') {
360
371
  const attrs = c.resource.attributes;
@@ -1,7 +1,7 @@
1
1
  export interface SourcemapOptions {
2
2
  /** Directory holding the client build; default `.next/static`. */
3
3
  dir?: string;
4
- /** Default WT_API_URL, then https://api.watchtower.observer. */
4
+ /** Default WT_API_URL (old name WT_API still works, with a warning), then https://watchtowerops.net. */
5
5
  apiUrl?: string;
6
6
  /** A key with scope `ci:write` (it covers releases and artifacts; `admin:write` also works). Default WT_API_KEY. */
7
7
  apiKey?: string;
@@ -24,8 +24,15 @@ type ConfigOrFn = NextConfig | ((...a: unknown[]) => NextConfig | Promise<NextCo
24
24
  export declare function withWatchtower(config?: ConfigOrFn, opts?: {
25
25
  sourcemaps?: boolean;
26
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. */
27
+ /**
28
+ * Upload every `.map` under `dir` as `_next/static/<path>` for the release (8 at a time, 429/5xx retried with backoff
29
+ * honoring Retry-After; a failed map does not stop the others), then delete them when none failed. Returns
30
+ * `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
31
+ * gzipped (`Content-Encoding: gzip`).
32
+ */
28
33
  export declare function uploadSourcemaps(o?: SourcemapOptions): Promise<{
29
34
  uploaded: number;
35
+ skipped: number;
36
+ failed: number;
30
37
  }>;
31
38
  export {};
@@ -38,6 +38,7 @@ exports.uploadSourcemaps = uploadSourcemaps;
38
38
  // Build-time helpers for Next.js: `withWatchtower` (next.config) and `uploadSourcemaps` (after `next build`).
39
39
  const fs = __importStar(require("node:fs"));
40
40
  const nodePath = __importStar(require("node:path"));
41
+ const zlib = __importStar(require("node:zlib"));
41
42
  /**
42
43
  * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
43
44
  * `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
@@ -58,7 +59,29 @@ function* maps(dir) {
58
59
  yield p;
59
60
  }
60
61
  }
61
- /** Upload every `.map` under `dir` as `_next/static/<path>` for the release, then delete them. Throws (leaving the files) when an upload fails. */
62
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
63
+ /** The client chunk (`_next/static/...`) a map belongs to: the sibling JS's `//# sourceMappingURL=` target, else the map's own `file` field. */
64
+ function chunkFor(mapFile, name) {
65
+ try {
66
+ const js = mapFile.slice(0, -'.map'.length);
67
+ if (fs.existsSync(js)) {
68
+ const tail = fs.readFileSync(js, 'utf8').slice(-512);
69
+ if (/\/\/[#@] sourceMappingURL=/.test(tail))
70
+ return name.slice(0, -'.map'.length);
71
+ }
72
+ const file = JSON.parse(fs.readFileSync(mapFile, 'utf8')).file;
73
+ if (typeof file === 'string' && file)
74
+ return `${nodePath.posix.dirname(name)}/${nodePath.posix.basename(file)}`;
75
+ }
76
+ catch { /* unreadable: upload without `for` */ }
77
+ return undefined;
78
+ }
79
+ /**
80
+ * Upload every `.map` under `dir` as `_next/static/<path>` for the release (8 at a time, 429/5xx retried with backoff
81
+ * honoring Retry-After; a failed map does not stop the others), then delete them when none failed. Returns
82
+ * `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
83
+ * gzipped (`Content-Encoding: gzip`).
84
+ */
62
85
  async function uploadSourcemaps(o = {}) {
63
86
  const env = process.env;
64
87
  const key = o.apiKey || env.WT_API_KEY;
@@ -70,26 +93,67 @@ async function uploadSourcemaps(o = {}) {
70
93
  throw new Error('WT_PROJECT (project id) is required');
71
94
  if (!release)
72
95
  throw new Error('WT_RELEASE is required');
96
+ const log = o.log || (() => { });
97
+ if (!o.apiUrl && !env.WT_API_URL && env.WT_API)
98
+ log('WT_API is deprecated, use WT_API_URL');
99
+ const base = (o.apiUrl || env.WT_API_URL || env.WT_API || 'https://watchtowerops.net').replace(/\/+$/, '');
73
100
  const dir = nodePath.resolve(o.dir || '.next/static');
74
101
  const f = o.fetch || fetch;
75
- const log = o.log || (() => { });
76
- const root = `${(o.apiUrl || env.WT_API_URL || 'https://api.watchtower.observer').replace(/\/+$/, '')}/v1/projects/${encodeURIComponent(project)}`;
77
- const call = async (path, init, okStatus = []) => {
78
- const res = await f(root + path, { ...init, headers: { authorization: `Bearer ${key}`, ...init.headers } });
79
- if (!res.ok && !okStatus.includes(res.status))
80
- throw new Error(`watchtower ${init.method} ${path.split('?')[0]} -> HTTP ${res.status}`);
102
+ const root = `${base}/v1/projects/${encodeURIComponent(project)}`;
103
+ const send = async (path, init, retries) => {
104
+ for (let attempt = 0;; attempt++) {
105
+ let res;
106
+ try {
107
+ res = await f(root + path, { ...init, headers: { authorization: `Bearer ${key}`, ...init.headers } });
108
+ }
109
+ catch (e) {
110
+ const cause = e.cause;
111
+ throw new Error(`cannot reach ${base} (${cause?.code || cause?.message || e.message}); check WT_API_URL`);
112
+ }
113
+ if ((res.status !== 429 && res.status < 500) || attempt >= retries)
114
+ return res;
115
+ const ra = Number(res.headers.get('retry-after'));
116
+ await sleep(Number.isFinite(ra) && ra > 0 ? Math.min(ra, 30) * 1000 : Math.min(250 * 2 ** attempt, 8000));
117
+ }
81
118
  };
82
119
  const files = fs.existsSync(dir) ? [...maps(dir)] : [];
83
- await call('/releases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ version: release }) }, [409]); // 409: exists
84
- for (const file of files) {
85
- const name = `_next/static/${nodePath.relative(dir, file).split(nodePath.sep).join('/')}`;
86
- await call(`/artifacts?${new URLSearchParams({ kind: 'sourcemap', name, release })}`, {
87
- method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: new Uint8Array(fs.readFileSync(file)),
88
- });
89
- }
90
- if (!o.keep)
120
+ // release create fails fast: no retry, so a bad host or key surfaces at once
121
+ const rel = await send('/releases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ version: release }) }, 0);
122
+ if (!rel.ok && rel.status !== 409)
123
+ throw new Error(`watchtower POST /releases -> HTTP ${rel.status}${rel.status === 401 || rel.status === 403 ? ' (check WT_API_KEY scope ci:write)' : ''}`);
124
+ let uploaded = 0, skipped = 0, failed = 0;
125
+ let next = 0;
126
+ const worker = async () => {
127
+ for (let file = files[next++]; file !== undefined; file = files[next++]) {
128
+ const name = `_next/static/${nodePath.relative(dir, file).split(nodePath.sep).join('/')}`;
129
+ const q = { kind: 'sourcemap', name, release };
130
+ const chunk = chunkFor(file, name);
131
+ if (chunk)
132
+ q.for = chunk;
133
+ try {
134
+ const res = await send(`/artifacts?${new URLSearchParams(q)}`, {
135
+ method: 'POST', headers: { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip' },
136
+ body: new Uint8Array(zlib.gzipSync(fs.readFileSync(file))),
137
+ }, 4);
138
+ if (res.status === 200)
139
+ skipped++;
140
+ else if (res.ok)
141
+ uploaded++;
142
+ else {
143
+ failed++;
144
+ log(`failed ${name}: HTTP ${res.status}`);
145
+ }
146
+ }
147
+ catch (e) {
148
+ failed++;
149
+ log(`failed ${name}: ${e.message}`);
150
+ }
151
+ }
152
+ };
153
+ await Promise.all(Array.from({ length: Math.min(8, files.length) }, worker));
154
+ if (!o.keep && failed === 0)
91
155
  for (const file of files)
92
156
  fs.rmSync(file);
93
- log(`uploaded ${files.length} source maps for release ${release}${o.keep ? '' : ' and deleted them'}`);
94
- return { uploaded: files.length };
157
+ log(`${JSON.stringify({ uploaded, skipped, failed })} source maps for release ${release}${o.keep || failed ? '' : '; deleted the .map files'}`);
158
+ return { uploaded, skipped, failed };
95
159
  }
@@ -4,8 +4,8 @@
4
4
  // Browser SDK: init({ endpoint: '/api/wt', publishableKey: 'wtp_...' }).
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
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)$/;
7
+ // only what the browser SDK calls: /v1/rum/*, /v1/replay/<session>/chunks /v1/logs and /v1/traces
8
+ const ALLOWED = /^\/v1\/(rum\/[A-Za-z0-9/_-]+|replay\/[A-Za-z0-9_-]+\/chunks|logs|traces)$/;
9
9
  const FORWARD = ['content-type', 'content-encoding', 'user-agent'];
10
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
11
  function tunnelHandler(o) {
@@ -1,24 +1,10 @@
1
- import type { ReadableSpan } from '@opentelemetry/sdk-trace';
2
1
  import * as wt from '../index.js';
3
2
  export { withWatchtower, uploadSourcemaps } from './next-build.js';
4
3
  export type { SourcemapOptions } from './next-build.js';
4
+ export { isNextInternal, nextInternalsFilter } from '../next-filter.js';
5
5
  export { tunnelHandler } from './next-tunnel.js';
6
6
  export type { TunnelOptions } from './next-tunnel.js';
7
- export interface NextOptions extends wt.InitOptions {
8
- /**
9
- * Next.js's own spans (`next.span_type` set: load route module, prepare route module, resolve page components, start
10
- * response, middleware, generateMetadata ...). `"sample"` (default) keeps `nextInternalsRate` of them, `"drop"` none,
11
- * `"keep"` all. Request (`BaseServer.handleRequest`), route handler, render, server action and fetch spans, every
12
- * SERVER/CLIENT span and every errored span are always kept. A dropped span's children stay in the trace.
13
- */
14
- nextInternals?: 'drop' | 'sample' | 'keep';
15
- /** Share of internal spans kept with `nextInternals: "sample"`; default 0.1. */
16
- nextInternalsRate?: number;
17
- }
18
- /** Whether `span` is one of Next's internal spans (not a request, route handler, render, server action or fetch). */
19
- export declare function isNextInternal(span: ReadableSpan): boolean;
20
- /** The `spanFilter` for a `nextInternals` mode; `rand` is injectable for tests. */
21
- export declare function nextInternalsFilter(mode?: 'drop' | 'sample' | 'keep', rate?: number, rand?: () => number): (s: ReadableSpan) => boolean;
7
+ export type NextOptions = wt.InitOptions;
22
8
  /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
23
9
  export declare function makeRegister(options?: NextOptions): () => Promise<void>;
24
10
  /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
@@ -33,45 +33,27 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.register = exports.tunnelHandler = exports.uploadSourcemaps = exports.withWatchtower = void 0;
37
- exports.isNextInternal = isNextInternal;
38
- exports.nextInternalsFilter = nextInternalsFilter;
36
+ exports.register = exports.tunnelHandler = exports.nextInternalsFilter = exports.isNextInternal = exports.uploadSourcemaps = exports.withWatchtower = void 0;
39
37
  exports.makeRegister = makeRegister;
40
38
  exports.onRequestError = onRequestError;
41
39
  // instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
42
40
  // or, with options: export const register = makeRegister({ redact }); export { onRequestError } from '@watchtowerobservability/node/next';
43
- const api_1 = require("@opentelemetry/api");
44
41
  const wt = __importStar(require("../index.js"));
45
42
  var next_build_js_1 = require("./next-build.js");
46
43
  Object.defineProperty(exports, "withWatchtower", { enumerable: true, get: function () { return next_build_js_1.withWatchtower; } });
47
44
  Object.defineProperty(exports, "uploadSourcemaps", { enumerable: true, get: function () { return next_build_js_1.uploadSourcemaps; } });
45
+ var next_filter_js_1 = require("../next-filter.js");
46
+ Object.defineProperty(exports, "isNextInternal", { enumerable: true, get: function () { return next_filter_js_1.isNextInternal; } });
47
+ Object.defineProperty(exports, "nextInternalsFilter", { enumerable: true, get: function () { return next_filter_js_1.nextInternalsFilter; } });
48
48
  var next_tunnel_js_1 = require("./next-tunnel.js");
49
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
- }
66
50
  /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
67
51
  function makeRegister(options = {}) {
68
52
  return async function register() {
69
53
  const rt = process.env.NEXT_RUNTIME;
70
54
  if ((rt && rt !== 'nodejs') || !(options.apiKey || process.env.WT_INGEST_KEY))
71
55
  return;
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 });
56
+ wt.init({ ...options, nextInternals: options.nextInternals ?? 'sample' }); // init() applies the filter (once)
75
57
  };
76
58
  }
77
59
  /** 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,45 +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 '@opentelemetry/instrumentation-mysql2': return require('@opentelemetry/instrumentation-mysql2');
31
- case 'winston-transport': return require('winston-transport');
32
- default: return NONE;
33
- }
34
- }
35
- catch (e) {
36
- throw e;
37
- }
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));
38
14
  }
39
15
  function load(id) {
40
- if (typeof require !== 'function')
41
- return (0, node_module_1.createRequire)(`${process.cwd()}/`)(id);
42
- const m = known(id);
43
- 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;
44
28
  }
45
29
  const SDK_PEERS = [
46
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,6 @@
1
+ // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
+ import type { ReadableSpan } from '@opentelemetry/sdk-trace';
3
+ /** Whether `span` is one of Next's internal spans (not a request, route handler, render, server action or fetch). */
4
+ export declare function isNextInternal(span: ReadableSpan): boolean;
5
+ /** The `spanFilter` for a `nextInternals` mode; `rand` is injectable for tests. */
6
+ export declare function nextInternalsFilter(mode?: 'drop' | 'sample' | 'keep', rate?: number, rand?: () => number): (s: ReadableSpan) => boolean;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNextInternal = isNextInternal;
4
+ exports.nextInternalsFilter = nextInternalsFilter;
5
+ // Filter for Next.js's own internal spans (`nextInternals` option of init / makeRegister).
6
+ const api_1 = require("@opentelemetry/api");
7
+ const KEEP_TYPES = new Set([
8
+ 'BaseServer.handleRequest', 'AppRouteRouteHandlers.runHandler', 'AppRender.fetch', 'AppRender.getBodyResult',
9
+ 'Render.getServerSideProps', 'Render.getStaticProps', 'NextNodeServer.runApi',
10
+ ]);
11
+ const KEEP_NAMES = /^(render route|executing api route|fetch |.*server action)/i;
12
+ /** Whether `span` is one of Next's internal spans (not a request, route handler, render, server action or fetch). */
13
+ function isNextInternal(span) {
14
+ const type = span.attributes['next.span_type'];
15
+ if (typeof type !== 'string')
16
+ return false;
17
+ return !KEEP_TYPES.has(type) && !KEEP_NAMES.test(span.name) && span.kind !== 1 && span.kind !== 2 && span.status.code !== api_1.SpanStatusCode.ERROR;
18
+ }
19
+ /** The `spanFilter` for a `nextInternals` mode; `rand` is injectable for tests. */
20
+ function nextInternalsFilter(mode = 'sample', rate = 0.1, rand = Math.random) {
21
+ return (s) => mode === 'keep' || !isNextInternal(s) || (mode === 'sample' && rand() < rate);
22
+ }
@@ -3,7 +3,8 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
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
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) => {
6
+ (0, next_build_js_1.uploadSourcemaps)({ dir: process.argv[2], log: (l) => console.log(`[watchtower] ${l}`) }).then((r) => { if (r.failed > 0)
7
+ process.exit(1); }).catch((e) => {
7
8
  console.error(`[watchtower] source map upload failed: ${e.message}`);
8
9
  process.exit(1);
9
10
  });
@@ -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. */