@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.
- package/CHANGELOG.md +70 -0
- package/README.md +13 -7
- package/dist/cjs/buffer.d.ts +3 -0
- package/dist/cjs/filter.d.ts +1 -0
- package/dist/cjs/index.d.ts +13 -0
- package/dist/cjs/index.js +12 -1
- package/dist/cjs/integrations/next-build.d.ts +9 -2
- package/dist/cjs/integrations/next-build.js +81 -17
- package/dist/cjs/integrations/next-tunnel.js +2 -2
- package/dist/cjs/integrations/next.d.ts +2 -16
- package/dist/cjs/integrations/next.js +5 -23
- package/dist/cjs/load.js +20 -36
- package/dist/cjs/metrics.d.ts +2 -0
- package/dist/cjs/next-filter.d.ts +6 -0
- package/dist/cjs/next-filter.js +22 -0
- package/dist/cjs/next-sourcemaps-cli.js +2 -1
- package/dist/cjs/origin.d.ts +1 -0
- package/dist/cjs/redact.d.ts +1 -0
- package/dist/cjs/register.js +11 -0
- package/dist/cjs/sampling.d.ts +1 -0
- package/dist/cjs/scrub.d.ts +1 -0
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/esm/buffer.d.ts +3 -0
- package/dist/esm/filter.d.ts +1 -0
- package/dist/esm/index.d.ts +13 -0
- package/dist/esm/index.js +12 -1
- package/dist/esm/integrations/next-build.d.ts +9 -2
- package/dist/esm/integrations/next-build.js +81 -17
- package/dist/esm/integrations/next-tunnel.js +2 -2
- package/dist/esm/integrations/next.d.ts +2 -16
- package/dist/esm/integrations/next.js +2 -20
- package/dist/esm/load.js +20 -62
- package/dist/esm/metrics.d.ts +2 -0
- package/dist/esm/next-filter.d.ts +6 -0
- package/dist/esm/next-filter.js +18 -0
- package/dist/esm/next-sourcemaps-cli.js +2 -1
- package/dist/esm/origin.d.ts +1 -0
- package/dist/esm/redact.d.ts +1 -0
- package/dist/esm/register.js +11 -0
- package/dist/esm/sampling.d.ts +1 -0
- package/dist/esm/scrub.d.ts +1 -0
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/package.json +13 -2
package/dist/cjs/register.js
CHANGED
|
@@ -14,12 +14,23 @@ if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
|
|
|
14
14
|
const key = Symbol.for('watchtower.node.esm-hook');
|
|
15
15
|
if (!g[key]) {
|
|
16
16
|
g[key] = true;
|
|
17
|
+
// Node 26 prints DEP0205 for module.register(); import-in-the-middle's hook has no sync (registerHooks) form yet,
|
|
18
|
+
// so mute only that one warning for this call.
|
|
19
|
+
const emit = process.emitWarning;
|
|
20
|
+
process.emitWarning = ((w, ...a) => {
|
|
21
|
+
if (JSON.stringify(a).includes('DEP0205'))
|
|
22
|
+
return;
|
|
23
|
+
return emit.call(process, w, ...a);
|
|
24
|
+
});
|
|
17
25
|
try {
|
|
18
26
|
(0, node_module_1.register)('@opentelemetry/instrumentation/hook.mjs', (0, node_url_1.pathToFileURL)(`${process.cwd()}/`));
|
|
19
27
|
}
|
|
20
28
|
catch {
|
|
21
29
|
// @opentelemetry/instrumentation not installed: CommonJS apps are still instrumented
|
|
22
30
|
}
|
|
31
|
+
finally {
|
|
32
|
+
process.emitWarning = emit;
|
|
33
|
+
}
|
|
23
34
|
}
|
|
24
35
|
(0, index_js_1.init)({});
|
|
25
36
|
}
|
package/dist/cjs/sampling.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Attributes, Context, Link, SpanKind } from '@opentelemetry/api';
|
|
2
|
+
// @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
|
|
2
3
|
import type { Sampler, SamplingResult } from '@opentelemetry/sdk-trace';
|
|
3
4
|
export interface SamplingRule {
|
|
4
5
|
name?: string;
|
package/dist/cjs/scrub.d.ts
CHANGED
|
@@ -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
|
/** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
|
|
3
4
|
export declare function looksSecret(seg: string): boolean;
|
package/dist/cjs/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
|
|
2
|
-
export declare const VERSION = "0.7.
|
|
2
|
+
export declare const VERSION = "0.7.2";
|
package/dist/cjs/version.js
CHANGED
package/dist/esm/buffer.d.ts
CHANGED
|
@@ -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. */
|
package/dist/esm/filter.d.ts
CHANGED
|
@@ -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;
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -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/esm/index.js
CHANGED
|
@@ -8,6 +8,7 @@ import { instrumentAll } from './instrument.js';
|
|
|
8
8
|
import { LOG_BODY_KEY, redactor } from './redact.js';
|
|
9
9
|
import { urlScrubber } from './scrub.js';
|
|
10
10
|
import { filterExporter } from './filter.js';
|
|
11
|
+
import { nextInternalsFilter } from './next-filter.js';
|
|
11
12
|
import { checkin as runCheckin } from './checkin.js';
|
|
12
13
|
import { installSignalFlush } from './shutdown.js';
|
|
13
14
|
import { VERSION } from './version.js';
|
|
@@ -298,6 +299,12 @@ function registerGlobals(c) {
|
|
|
298
299
|
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');
|
|
299
300
|
}
|
|
300
301
|
export function init(opts) {
|
|
302
|
+
const nextMode = opts?.nextInternals ?? (process.env.NEXT_RUNTIME ? 'sample' : undefined);
|
|
303
|
+
if (nextMode) {
|
|
304
|
+
const own = nextInternalsFilter(nextMode, opts?.nextInternalsRate);
|
|
305
|
+
const user = opts.spanFilter;
|
|
306
|
+
opts = { ...opts, nextInternals: undefined, spanFilter: user ? (s) => own(s) && user(s) : own }; // cleared: a second init() never stacks the filter
|
|
307
|
+
}
|
|
301
308
|
if (state.current && state.current.uninstall)
|
|
302
309
|
state.current.uninstall();
|
|
303
310
|
void state.current?.profiler?.then((p) => p?.stop());
|
|
@@ -308,9 +315,13 @@ export function init(opts) {
|
|
|
308
315
|
const mode = opts?.instrument ?? (env === 'auto' ? 'auto' : !['0', 'off', 'false', 'no'].includes(env));
|
|
309
316
|
if (mode) {
|
|
310
317
|
const names = instrumentAll({ tracerProvider: c.provider, meterProvider: c.meterProvider }, [c.endpoint, c.apiUrl], mode === 'auto');
|
|
311
|
-
|
|
318
|
+
const logOn = opts?.instrumentLog ?? !['0', 'off', 'false', 'no'].includes((process.env.WT_INSTRUMENT_LOG || '').trim().toLowerCase());
|
|
319
|
+
if (mode === 'auto' && logOn) {
|
|
312
320
|
console.info(`[watchtower] instrumented: ${names.map((n) => n.replace('@opentelemetry/instrumentation-', '')).join(', ') || 'nothing (no supported package found)'}`);
|
|
313
321
|
}
|
|
322
|
+
if (logOn && !['0', 'false', 'off', 'no'].includes((process.env.WATCHTOWER_DB_REQUIRE_PARENT || '').trim().toLowerCase())) {
|
|
323
|
+
console.info('watchtower: requireParent on; queries outside a span are not recorded (WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)');
|
|
324
|
+
}
|
|
314
325
|
}
|
|
315
326
|
if (process.env.WT_PROFILING === '1') {
|
|
316
327
|
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://
|
|
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
|
-
/**
|
|
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 {};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Build-time helpers for Next.js: `withWatchtower` (next.config) and `uploadSourcemaps` (after `next build`).
|
|
2
2
|
import * as fs from 'node:fs';
|
|
3
3
|
import * as nodePath from 'node:path';
|
|
4
|
+
import * as zlib from 'node:zlib';
|
|
4
5
|
/**
|
|
5
6
|
* `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
|
|
6
7
|
* `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
|
|
@@ -21,7 +22,29 @@ function* maps(dir) {
|
|
|
21
22
|
yield p;
|
|
22
23
|
}
|
|
23
24
|
}
|
|
24
|
-
|
|
25
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
26
|
+
/** The client chunk (`_next/static/...`) a map belongs to: the sibling JS's `//# sourceMappingURL=` target, else the map's own `file` field. */
|
|
27
|
+
function chunkFor(mapFile, name) {
|
|
28
|
+
try {
|
|
29
|
+
const js = mapFile.slice(0, -'.map'.length);
|
|
30
|
+
if (fs.existsSync(js)) {
|
|
31
|
+
const tail = fs.readFileSync(js, 'utf8').slice(-512);
|
|
32
|
+
if (/\/\/[#@] sourceMappingURL=/.test(tail))
|
|
33
|
+
return name.slice(0, -'.map'.length);
|
|
34
|
+
}
|
|
35
|
+
const file = JSON.parse(fs.readFileSync(mapFile, 'utf8')).file;
|
|
36
|
+
if (typeof file === 'string' && file)
|
|
37
|
+
return `${nodePath.posix.dirname(name)}/${nodePath.posix.basename(file)}`;
|
|
38
|
+
}
|
|
39
|
+
catch { /* unreadable: upload without `for` */ }
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Upload every `.map` under `dir` as `_next/static/<path>` for the release (8 at a time, 429/5xx retried with backoff
|
|
44
|
+
* honoring Retry-After; a failed map does not stop the others), then delete them when none failed. Returns
|
|
45
|
+
* `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
|
|
46
|
+
* gzipped (`Content-Encoding: gzip`).
|
|
47
|
+
*/
|
|
25
48
|
export async function uploadSourcemaps(o = {}) {
|
|
26
49
|
const env = process.env;
|
|
27
50
|
const key = o.apiKey || env.WT_API_KEY;
|
|
@@ -33,26 +56,67 @@ export async function uploadSourcemaps(o = {}) {
|
|
|
33
56
|
throw new Error('WT_PROJECT (project id) is required');
|
|
34
57
|
if (!release)
|
|
35
58
|
throw new Error('WT_RELEASE is required');
|
|
59
|
+
const log = o.log || (() => { });
|
|
60
|
+
if (!o.apiUrl && !env.WT_API_URL && env.WT_API)
|
|
61
|
+
log('WT_API is deprecated, use WT_API_URL');
|
|
62
|
+
const base = (o.apiUrl || env.WT_API_URL || env.WT_API || 'https://watchtowerops.net').replace(/\/+$/, '');
|
|
36
63
|
const dir = nodePath.resolve(o.dir || '.next/static');
|
|
37
64
|
const f = o.fetch || fetch;
|
|
38
|
-
const
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
65
|
+
const root = `${base}/v1/projects/${encodeURIComponent(project)}`;
|
|
66
|
+
const send = async (path, init, retries) => {
|
|
67
|
+
for (let attempt = 0;; attempt++) {
|
|
68
|
+
let res;
|
|
69
|
+
try {
|
|
70
|
+
res = await f(root + path, { ...init, headers: { authorization: `Bearer ${key}`, ...init.headers } });
|
|
71
|
+
}
|
|
72
|
+
catch (e) {
|
|
73
|
+
const cause = e.cause;
|
|
74
|
+
throw new Error(`cannot reach ${base} (${cause?.code || cause?.message || e.message}); check WT_API_URL`);
|
|
75
|
+
}
|
|
76
|
+
if ((res.status !== 429 && res.status < 500) || attempt >= retries)
|
|
77
|
+
return res;
|
|
78
|
+
const ra = Number(res.headers.get('retry-after'));
|
|
79
|
+
await sleep(Number.isFinite(ra) && ra > 0 ? Math.min(ra, 30) * 1000 : Math.min(250 * 2 ** attempt, 8000));
|
|
80
|
+
}
|
|
44
81
|
};
|
|
45
82
|
const files = fs.existsSync(dir) ? [...maps(dir)] : [];
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
83
|
+
// release create fails fast: no retry, so a bad host or key surfaces at once
|
|
84
|
+
const rel = await send('/releases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ version: release }) }, 0);
|
|
85
|
+
if (!rel.ok && rel.status !== 409)
|
|
86
|
+
throw new Error(`watchtower POST /releases -> HTTP ${rel.status}${rel.status === 401 || rel.status === 403 ? ' (check WT_API_KEY scope ci:write)' : ''}`);
|
|
87
|
+
let uploaded = 0, skipped = 0, failed = 0;
|
|
88
|
+
let next = 0;
|
|
89
|
+
const worker = async () => {
|
|
90
|
+
for (let file = files[next++]; file !== undefined; file = files[next++]) {
|
|
91
|
+
const name = `_next/static/${nodePath.relative(dir, file).split(nodePath.sep).join('/')}`;
|
|
92
|
+
const q = { kind: 'sourcemap', name, release };
|
|
93
|
+
const chunk = chunkFor(file, name);
|
|
94
|
+
if (chunk)
|
|
95
|
+
q.for = chunk;
|
|
96
|
+
try {
|
|
97
|
+
const res = await send(`/artifacts?${new URLSearchParams(q)}`, {
|
|
98
|
+
method: 'POST', headers: { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip' },
|
|
99
|
+
body: new Uint8Array(zlib.gzipSync(fs.readFileSync(file))),
|
|
100
|
+
}, 4);
|
|
101
|
+
if (res.status === 200)
|
|
102
|
+
skipped++;
|
|
103
|
+
else if (res.ok)
|
|
104
|
+
uploaded++;
|
|
105
|
+
else {
|
|
106
|
+
failed++;
|
|
107
|
+
log(`failed ${name}: HTTP ${res.status}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
catch (e) {
|
|
111
|
+
failed++;
|
|
112
|
+
log(`failed ${name}: ${e.message}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
await Promise.all(Array.from({ length: Math.min(8, files.length) }, worker));
|
|
117
|
+
if (!o.keep && failed === 0)
|
|
54
118
|
for (const file of files)
|
|
55
119
|
fs.rmSync(file);
|
|
56
|
-
log(
|
|
57
|
-
return { uploaded
|
|
120
|
+
log(`${JSON.stringify({ uploaded, skipped, failed })} source maps for release ${release}${o.keep || failed ? '' : '; deleted the .map files'}`);
|
|
121
|
+
return { uploaded, skipped, failed };
|
|
58
122
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// First-party tunnel for browser telemetry (ad blockers block third-party telemetry hosts).
|
|
2
2
|
// app/api/wt/[...path]/route.ts: export const { GET, POST } = tunnelHandler({ endpoint: process.env.WT_EDGE_URL! });
|
|
3
3
|
// Browser SDK: init({ endpoint: '/api/wt', publishableKey: 'wtp_...' }).
|
|
4
|
-
// only what the browser SDK calls: /v1/rum/*, /v1/replay/<session>/chunks and /v1/
|
|
5
|
-
const ALLOWED = /^\/v1\/(rum\/[A-Za-z0-9/_-]+|replay\/[A-Za-z0-9_-]+\/chunks|logs)$/;
|
|
4
|
+
// only what the browser SDK calls: /v1/rum/*, /v1/replay/<session>/chunks /v1/logs and /v1/traces
|
|
5
|
+
const ALLOWED = /^\/v1\/(rum\/[A-Za-z0-9/_-]+|replay\/[A-Za-z0-9_-]+\/chunks|logs|traces)$/;
|
|
6
6
|
const FORWARD = ['content-type', 'content-encoding', 'user-agent'];
|
|
7
7
|
/** 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. */
|
|
8
8
|
export 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
|
|
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. */
|
|
@@ -1,34 +1,16 @@
|
|
|
1
1
|
// instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
|
|
2
2
|
// or, with options: export const register = makeRegister({ redact }); export { onRequestError } from '@watchtowerobservability/node/next';
|
|
3
|
-
import { SpanStatusCode } from '@opentelemetry/api';
|
|
4
3
|
import * as wt from '../index.js';
|
|
5
4
|
export { withWatchtower, uploadSourcemaps } from './next-build.js';
|
|
5
|
+
export { isNextInternal, nextInternalsFilter } from '../next-filter.js';
|
|
6
6
|
export { tunnelHandler } from './next-tunnel.js';
|
|
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
|
-
export 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 !== SpanStatusCode.ERROR;
|
|
18
|
-
}
|
|
19
|
-
/** The `spanFilter` for a `nextInternals` mode; `rand` is injectable for tests. */
|
|
20
|
-
export function nextInternalsFilter(mode = 'sample', rate = 0.1, rand = Math.random) {
|
|
21
|
-
return (s) => mode === 'keep' || !isNextInternal(s) || (mode === 'sample' && rand() < rate);
|
|
22
|
-
}
|
|
23
7
|
/** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
|
|
24
8
|
export function makeRegister(options = {}) {
|
|
25
9
|
return async function register() {
|
|
26
10
|
const rt = process.env.NEXT_RUNTIME;
|
|
27
11
|
if ((rt && rt !== 'nodejs') || !(options.apiKey || process.env.WT_INGEST_KEY))
|
|
28
12
|
return;
|
|
29
|
-
|
|
30
|
-
const own = nextInternalsFilter(nextInternals, nextInternalsRate);
|
|
31
|
-
wt.init({ ...init, spanFilter: init.spanFilter ? (s) => own(s) && init.spanFilter(s) : own });
|
|
13
|
+
wt.init({ ...options, nextInternals: options.nextInternals ?? 'sample' }); // init() applies the filter (once)
|
|
32
14
|
};
|
|
33
15
|
}
|
|
34
16
|
/** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
|
package/dist/esm/load.js
CHANGED
|
@@ -1,68 +1,26 @@
|
|
|
1
|
-
// Optional-peer loader
|
|
2
|
-
// file tracer) can follow it; a computed `require(name)` is invisible to them. This is the CommonJS form;
|
|
3
|
-
// scripts/build.mjs prepends `const require = createRequire(import.meta.url)` for dist/esm (webpack follows that too).
|
|
4
|
-
// The cwd fallback only matters when `require` does not exist (test runners running the TS source as ESM).
|
|
1
|
+
// Optional-peer loader (same source for the CommonJS and ESM builds).
|
|
5
2
|
import { createRequire } from 'node:module';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
try { pre["@opentelemetry/resources"] = await import("@opentelemetry/resources"); } catch (e) { pre["@opentelemetry/resources"] = e; }
|
|
14
|
-
try { pre["@opentelemetry/sdk-logs"] = await import("@opentelemetry/sdk-logs"); } catch (e) { pre["@opentelemetry/sdk-logs"] = e; }
|
|
15
|
-
try { pre["@opentelemetry/sdk-metrics"] = await import("@opentelemetry/sdk-metrics"); } catch (e) { pre["@opentelemetry/sdk-metrics"] = e; }
|
|
16
|
-
try { pre["@opentelemetry/sdk-trace"] = await import("@opentelemetry/sdk-trace"); } catch (e) { pre["@opentelemetry/sdk-trace"] = e; }
|
|
17
|
-
try { pre["@opentelemetry/instrumentation-runtime-node"] = await import("@opentelemetry/instrumentation-runtime-node"); } catch (e) { pre["@opentelemetry/instrumentation-runtime-node"] = e; }
|
|
18
|
-
try { pre["@opentelemetry/instrumentation"] = await import("@opentelemetry/instrumentation"); } catch (e) { pre["@opentelemetry/instrumentation"] = e; }
|
|
19
|
-
try { pre["@opentelemetry/instrumentation-http"] = await import("@opentelemetry/instrumentation-http"); } catch (e) { pre["@opentelemetry/instrumentation-http"] = e; }
|
|
20
|
-
try { pre["@opentelemetry/instrumentation-undici"] = await import("@opentelemetry/instrumentation-undici"); } catch (e) { pre["@opentelemetry/instrumentation-undici"] = e; }
|
|
21
|
-
try { pre["@opentelemetry/instrumentation-pg"] = await import("@opentelemetry/instrumentation-pg"); } catch (e) { pre["@opentelemetry/instrumentation-pg"] = e; }
|
|
22
|
-
try { pre["@opentelemetry/instrumentation-ioredis"] = await import("@opentelemetry/instrumentation-ioredis"); } catch (e) { pre["@opentelemetry/instrumentation-ioredis"] = e; }
|
|
23
|
-
try { pre["@opentelemetry/instrumentation-mysql2"] = await import("@opentelemetry/instrumentation-mysql2"); } catch (e) { pre["@opentelemetry/instrumentation-mysql2"] = e; }
|
|
24
|
-
try { pre["winston-transport"] = await import("winston-transport"); } catch (e) { pre["winston-transport"] = e; }
|
|
25
|
-
const nodeRequire = createRequire(import.meta.url);
|
|
26
|
-
const require = (id) => {
|
|
27
|
-
const m = pre[id];
|
|
28
|
-
if (m === undefined) return nodeRequire(id);
|
|
29
|
-
if (m instanceof Error) throw Object.assign(new Error(m.message), { code: m.code === 'ERR_MODULE_NOT_FOUND' ? 'MODULE_NOT_FOUND' : m.code });
|
|
30
|
-
return m.default && typeof m.default === 'object' ? { ...m.default, ...m } : m;
|
|
31
|
-
};
|
|
32
|
-
const NONE = Symbol('not a known peer');
|
|
33
|
-
function known(id) {
|
|
34
|
-
try { // bundlers only tolerate an optional require that is lexically inside try
|
|
35
|
-
switch (id) {
|
|
36
|
-
case '@opentelemetry/context-async-hooks': return require('@opentelemetry/context-async-hooks');
|
|
37
|
-
case '@opentelemetry/core': return require('@opentelemetry/core');
|
|
38
|
-
case '@opentelemetry/exporter-logs-otlp-http': return require('@opentelemetry/exporter-logs-otlp-http');
|
|
39
|
-
case '@opentelemetry/exporter-metrics-otlp-http': return require('@opentelemetry/exporter-metrics-otlp-http');
|
|
40
|
-
case '@opentelemetry/exporter-trace-otlp-http': return require('@opentelemetry/exporter-trace-otlp-http');
|
|
41
|
-
case '@opentelemetry/otlp-transformer': return require('@opentelemetry/otlp-transformer');
|
|
42
|
-
case '@opentelemetry/resources': return require('@opentelemetry/resources');
|
|
43
|
-
case '@opentelemetry/sdk-logs': return require('@opentelemetry/sdk-logs');
|
|
44
|
-
case '@opentelemetry/sdk-metrics': return require('@opentelemetry/sdk-metrics');
|
|
45
|
-
case '@opentelemetry/sdk-trace': return require('@opentelemetry/sdk-trace');
|
|
46
|
-
case '@opentelemetry/instrumentation-runtime-node': return require('@opentelemetry/instrumentation-runtime-node');
|
|
47
|
-
case '@opentelemetry/instrumentation': return require('@opentelemetry/instrumentation');
|
|
48
|
-
case '@opentelemetry/instrumentation-http': return require('@opentelemetry/instrumentation-http');
|
|
49
|
-
case '@opentelemetry/instrumentation-undici': return require('@opentelemetry/instrumentation-undici');
|
|
50
|
-
case '@opentelemetry/instrumentation-pg': return require('@opentelemetry/instrumentation-pg');
|
|
51
|
-
case '@opentelemetry/instrumentation-ioredis': return require('@opentelemetry/instrumentation-ioredis');
|
|
52
|
-
case '@opentelemetry/instrumentation-mysql2': return require('@opentelemetry/instrumentation-mysql2');
|
|
53
|
-
case 'winston-transport': return require('winston-transport');
|
|
54
|
-
default: return NONE;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
catch (e) {
|
|
58
|
-
throw e;
|
|
59
|
-
}
|
|
3
|
+
// Bundlers must NOT follow this: an optional peer the app did not install would make webpack warn "Module not found",
|
|
4
|
+
// and a bare require call on a variable id is a "Critical dependency" warning. createRequire() is opaque to webpack/esbuild/Next's tracer,
|
|
5
|
+
// so peers resolve at run time from the SDK's own location, then from the app root (cwd). Install the peers in the app
|
|
6
|
+
// (pnpm: as direct dependencies); for a Next standalone build add them to outputFileTracingIncludes.
|
|
7
|
+
function resolvers() {
|
|
8
|
+
const from = [typeof __filename === 'string' ? __filename : '', `${process.cwd()}/`].filter(Boolean);
|
|
9
|
+
return from.map((f) => createRequire(f));
|
|
60
10
|
}
|
|
61
11
|
export function load(id) {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
12
|
+
let err;
|
|
13
|
+
for (const r of resolvers()) {
|
|
14
|
+
try {
|
|
15
|
+
return r(id);
|
|
16
|
+
}
|
|
17
|
+
catch (e) {
|
|
18
|
+
if (e?.code !== 'MODULE_NOT_FOUND')
|
|
19
|
+
throw e;
|
|
20
|
+
err ??= e;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
throw err;
|
|
66
24
|
}
|
|
67
25
|
const SDK_PEERS = [
|
|
68
26
|
'@opentelemetry/context-async-hooks', '@opentelemetry/core', '@opentelemetry/exporter-logs-otlp-http',
|
package/dist/esm/metrics.d.ts
CHANGED
|
@@ -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,18 @@
|
|
|
1
|
+
// Filter for Next.js's own internal spans (`nextInternals` option of init / makeRegister).
|
|
2
|
+
import { SpanStatusCode } from '@opentelemetry/api';
|
|
3
|
+
const KEEP_TYPES = new Set([
|
|
4
|
+
'BaseServer.handleRequest', 'AppRouteRouteHandlers.runHandler', 'AppRender.fetch', 'AppRender.getBodyResult',
|
|
5
|
+
'Render.getServerSideProps', 'Render.getStaticProps', 'NextNodeServer.runApi',
|
|
6
|
+
]);
|
|
7
|
+
const KEEP_NAMES = /^(render route|executing api route|fetch |.*server action)/i;
|
|
8
|
+
/** Whether `span` is one of Next's internal spans (not a request, route handler, render, server action or fetch). */
|
|
9
|
+
export function isNextInternal(span) {
|
|
10
|
+
const type = span.attributes['next.span_type'];
|
|
11
|
+
if (typeof type !== 'string')
|
|
12
|
+
return false;
|
|
13
|
+
return !KEEP_TYPES.has(type) && !KEEP_NAMES.test(span.name) && span.kind !== 1 && span.kind !== 2 && span.status.code !== SpanStatusCode.ERROR;
|
|
14
|
+
}
|
|
15
|
+
/** The `spanFilter` for a `nextInternals` mode; `rand` is injectable for tests. */
|
|
16
|
+
export function nextInternalsFilter(mode = 'sample', rate = 0.1, rand = Math.random) {
|
|
17
|
+
return (s) => mode === 'keep' || !isNextInternal(s) || (mode === 'sample' && rand() < rate);
|
|
18
|
+
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// `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.
|
|
3
3
|
import { uploadSourcemaps } from './integrations/next-build.js';
|
|
4
|
-
uploadSourcemaps({ dir: process.argv[2], log: (l) => console.log(`[watchtower] ${l}`) }).
|
|
4
|
+
uploadSourcemaps({ dir: process.argv[2], log: (l) => console.log(`[watchtower] ${l}`) }).then((r) => { if (r.failed > 0)
|
|
5
|
+
process.exit(1); }).catch((e) => {
|
|
5
6
|
console.error(`[watchtower] source map upload failed: ${e.message}`);
|
|
6
7
|
process.exit(1);
|
|
7
8
|
});
|
package/dist/esm/origin.d.ts
CHANGED
package/dist/esm/redact.d.ts
CHANGED
|
@@ -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. */
|
package/dist/esm/register.js
CHANGED
|
@@ -12,12 +12,23 @@ if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
|
|
|
12
12
|
const key = Symbol.for('watchtower.node.esm-hook');
|
|
13
13
|
if (!g[key]) {
|
|
14
14
|
g[key] = true;
|
|
15
|
+
// Node 26 prints DEP0205 for module.register(); import-in-the-middle's hook has no sync (registerHooks) form yet,
|
|
16
|
+
// so mute only that one warning for this call.
|
|
17
|
+
const emit = process.emitWarning;
|
|
18
|
+
process.emitWarning = ((w, ...a) => {
|
|
19
|
+
if (JSON.stringify(a).includes('DEP0205'))
|
|
20
|
+
return;
|
|
21
|
+
return emit.call(process, w, ...a);
|
|
22
|
+
});
|
|
15
23
|
try {
|
|
16
24
|
registerHooks('@opentelemetry/instrumentation/hook.mjs', pathToFileURL(`${process.cwd()}/`));
|
|
17
25
|
}
|
|
18
26
|
catch {
|
|
19
27
|
// @opentelemetry/instrumentation not installed: CommonJS apps are still instrumented
|
|
20
28
|
}
|
|
29
|
+
finally {
|
|
30
|
+
process.emitWarning = emit;
|
|
31
|
+
}
|
|
21
32
|
}
|
|
22
33
|
init({});
|
|
23
34
|
}
|
package/dist/esm/sampling.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Attributes, Context, Link, SpanKind } from '@opentelemetry/api';
|
|
2
|
+
// @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
|
|
2
3
|
import type { Sampler, SamplingResult } from '@opentelemetry/sdk-trace';
|
|
3
4
|
export interface SamplingRule {
|
|
4
5
|
name?: string;
|
package/dist/esm/scrub.d.ts
CHANGED
|
@@ -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
|
/** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
|
|
3
4
|
export declare function looksSecret(seg: string): boolean;
|
package/dist/esm/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
|
|
2
|
-
export declare const VERSION = "0.7.
|
|
2
|
+
export declare const VERSION = "0.7.2";
|
package/dist/esm/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
|
|
2
|
-
export const VERSION = '0.7.
|
|
2
|
+
export const VERSION = '0.7.2';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@watchtowerobservability/node",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.2",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/watchtowerobservability/watchtower-node.git"
|
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
"wt-next-sourcemaps": "./dist/cjs/next-sourcemaps-cli.js"
|
|
18
18
|
},
|
|
19
19
|
"files": [
|
|
20
|
-
"dist"
|
|
20
|
+
"dist",
|
|
21
|
+
"CHANGELOG.md"
|
|
21
22
|
],
|
|
22
23
|
"exports": {
|
|
23
24
|
".": {
|
|
@@ -250,6 +251,16 @@
|
|
|
250
251
|
"default": "./dist/cjs/integrations/orm.js"
|
|
251
252
|
}
|
|
252
253
|
},
|
|
254
|
+
"./messaging": {
|
|
255
|
+
"import": {
|
|
256
|
+
"types": "./dist/esm/integrations/messaging.d.ts",
|
|
257
|
+
"default": "./dist/esm/integrations/messaging.js"
|
|
258
|
+
},
|
|
259
|
+
"require": {
|
|
260
|
+
"types": "./dist/cjs/integrations/messaging.d.ts",
|
|
261
|
+
"default": "./dist/cjs/integrations/messaging.js"
|
|
262
|
+
}
|
|
263
|
+
},
|
|
253
264
|
"./amqp": {
|
|
254
265
|
"import": {
|
|
255
266
|
"types": "./dist/esm/integrations/amqp.d.ts",
|