@watchtowerobservability/node 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +88 -9
  2. package/dist/cjs/checkin.d.ts +7 -0
  3. package/dist/cjs/checkin.js +18 -0
  4. package/dist/cjs/env.d.ts +12 -0
  5. package/dist/cjs/env.js +37 -0
  6. package/dist/cjs/errors.d.ts +8 -0
  7. package/dist/cjs/errors.js +23 -0
  8. package/dist/cjs/filter.d.ts +2 -0
  9. package/dist/cjs/filter.js +16 -0
  10. package/dist/cjs/index.d.ts +48 -10
  11. package/dist/cjs/index.js +119 -53
  12. package/dist/cjs/instrument.d.ts +10 -0
  13. package/dist/cjs/instrument.js +74 -0
  14. package/dist/cjs/integrations/db.d.ts +3 -0
  15. package/dist/cjs/integrations/db.js +4 -1
  16. package/dist/cjs/integrations/genai-agents.d.ts +4 -1
  17. package/dist/cjs/integrations/genai-agents.js +27 -24
  18. package/dist/cjs/integrations/genai-frameworks.d.ts +25 -0
  19. package/dist/cjs/integrations/genai-frameworks.js +211 -0
  20. package/dist/cjs/integrations/genai.d.ts +1 -0
  21. package/dist/cjs/integrations/genai.js +7 -2
  22. package/dist/cjs/integrations/next-build.d.ts +31 -0
  23. package/dist/cjs/integrations/next-build.js +95 -0
  24. package/dist/cjs/integrations/next-tunnel.d.ts +14 -0
  25. package/dist/cjs/integrations/next-tunnel.js +52 -0
  26. package/dist/cjs/integrations/next.d.ts +24 -1
  27. package/dist/cjs/integrations/next.js +39 -7
  28. package/dist/cjs/load.js +37 -5
  29. package/dist/cjs/next-sourcemaps-cli.d.ts +2 -0
  30. package/dist/cjs/next-sourcemaps-cli.js +9 -0
  31. package/dist/cjs/origin.d.ts +9 -0
  32. package/dist/cjs/origin.js +43 -0
  33. package/dist/cjs/redact.d.ts +8 -0
  34. package/dist/cjs/redact.js +43 -0
  35. package/dist/cjs/register.d.ts +1 -0
  36. package/dist/cjs/register.js +29 -0
  37. package/dist/cjs/sampling.d.ts +53 -0
  38. package/dist/cjs/sampling.js +98 -0
  39. package/dist/cjs/scrub.d.ts +7 -0
  40. package/dist/cjs/scrub.js +39 -0
  41. package/dist/cjs/shutdown.d.ts +14 -0
  42. package/dist/cjs/shutdown.js +26 -0
  43. package/dist/cjs/sql.js +11 -1
  44. package/dist/cjs/version.d.ts +2 -0
  45. package/dist/cjs/version.js +5 -0
  46. package/dist/esm/checkin.d.ts +7 -0
  47. package/dist/esm/checkin.js +15 -0
  48. package/dist/esm/env.d.ts +12 -0
  49. package/dist/esm/env.js +33 -0
  50. package/dist/esm/errors.d.ts +8 -0
  51. package/dist/esm/errors.js +22 -0
  52. package/dist/esm/filter.d.ts +2 -0
  53. package/dist/esm/filter.js +13 -0
  54. package/dist/esm/index.d.ts +48 -10
  55. package/dist/esm/index.js +117 -53
  56. package/dist/esm/instrument.d.ts +10 -0
  57. package/dist/esm/instrument.js +71 -0
  58. package/dist/esm/integrations/db.d.ts +3 -0
  59. package/dist/esm/integrations/db.js +5 -2
  60. package/dist/esm/integrations/genai-agents.d.ts +4 -1
  61. package/dist/esm/integrations/genai-agents.js +4 -4
  62. package/dist/esm/integrations/genai-frameworks.d.ts +25 -0
  63. package/dist/esm/integrations/genai-frameworks.js +206 -0
  64. package/dist/esm/integrations/genai.d.ts +1 -0
  65. package/dist/esm/integrations/genai.js +3 -1
  66. package/dist/esm/integrations/next-build.d.ts +31 -0
  67. package/dist/esm/integrations/next-build.js +58 -0
  68. package/dist/esm/integrations/next-tunnel.d.ts +14 -0
  69. package/dist/esm/integrations/next-tunnel.js +49 -0
  70. package/dist/esm/integrations/next.d.ts +24 -1
  71. package/dist/esm/integrations/next.js +32 -6
  72. package/dist/esm/load.js +80 -2
  73. package/dist/esm/next-sourcemaps-cli.d.ts +2 -0
  74. package/dist/esm/next-sourcemaps-cli.js +7 -0
  75. package/dist/esm/origin.d.ts +9 -0
  76. package/dist/esm/origin.js +39 -0
  77. package/dist/esm/redact.d.ts +8 -0
  78. package/dist/esm/redact.js +39 -0
  79. package/dist/esm/register.d.ts +1 -0
  80. package/dist/esm/register.js +27 -0
  81. package/dist/esm/sampling.d.ts +53 -0
  82. package/dist/esm/sampling.js +91 -0
  83. package/dist/esm/scrub.d.ts +7 -0
  84. package/dist/esm/scrub.js +34 -0
  85. package/dist/esm/shutdown.d.ts +14 -0
  86. package/dist/esm/shutdown.js +23 -0
  87. package/dist/esm/sql.js +11 -1
  88. package/dist/esm/version.d.ts +2 -0
  89. package/dist/esm/version.js +2 -0
  90. package/package.json +40 -2
@@ -0,0 +1,206 @@
1
+ // GenAI spans for the TypeScript agent frameworks: LangGraph.js (a LangChain.js callback handler), the Vercel AI SDK
2
+ // agent loop (generateText / streamText with several steps) and Mastra agents. Same shape as the Python
3
+ // instrumentors and `genai-agents.ts`: `invoke_agent` / `chat` / `execute_tool` spans, nested as the run nests,
4
+ // never any prompt, completion or tool argument text. CrewAI has no JavaScript port, so there is no CrewAI hook here.
5
+ // Nothing is imported from the frameworks: each function takes their object.
6
+ import { context, SpanStatusCode, trace } from '@opentelemetry/api';
7
+ import { obj, s, start } from './genai-agents.js';
8
+ const num = (v) => (typeof v === 'number' ? v : undefined);
9
+ const thenable = (v) => !!v && typeof v.then === 'function';
10
+ function fail(span, e) {
11
+ span.recordException(e);
12
+ span.setStatus({ code: SpanStatusCode.ERROR, message: e?.message });
13
+ }
14
+ /**
15
+ * langchainCallbackHandler(): pass it as `callbacks: [handler]` to a LangChain.js model, chain or LangGraph.js graph
16
+ * (`graph.invoke(input, { callbacks: [handler] })`). LangGraph nodes (chains whose metadata names `langgraph_node`)
17
+ * and the graph itself become `invoke_agent` spans, tools `execute_tool`, model calls `chat`, nested as they run;
18
+ * plain LCEL chains get no span. Returns a plain handler object (LangChain wraps it) with the open spans for tests.
19
+ */
20
+ export function langchainCallbackHandler() {
21
+ const open = new Map(), up = new Map();
22
+ const begin = (runId, parentId, name, attrs) => {
23
+ up.set(runId, parentId);
24
+ let p = parentId;
25
+ while (p !== undefined && !open.has(p))
26
+ p = up.get(p); // a parent without a span: skip to its own parent
27
+ open.set(runId, start(name, attrs, p === undefined ? undefined : open.get(p)));
28
+ };
29
+ const close = (runId, error) => {
30
+ up.delete(runId);
31
+ const span = open.get(runId);
32
+ open.delete(runId);
33
+ if (span && error !== undefined)
34
+ fail(span, error);
35
+ return span;
36
+ };
37
+ const llmStart = (extra, llm) => (runId, parentId) => {
38
+ const p = obj(obj(extra).invocation_params), k = obj(obj(llm).kwargs);
39
+ const model = s(p.model) || s(p.model_name) || s(k.model) || s(k.modelName);
40
+ begin(runId, parentId, `chat ${model}`.trim(), { 'gen_ai.operation.name': 'chat', 'gen_ai.system': 'langchain', 'gen_ai.request.model': model });
41
+ };
42
+ const ender = (runId, error) => { close(runId, error)?.end(); };
43
+ const h = {
44
+ open,
45
+ handleChatModelStart: (llm, _m, runId, parentId, extra) => llmStart(extra, llm)(runId, parentId),
46
+ handleLLMStart: (llm, _p, runId, parentId, extra) => llmStart(extra, llm)(runId, parentId),
47
+ handleLLMEnd: (output, runId) => {
48
+ const span = close(runId);
49
+ if (!span)
50
+ return;
51
+ const o = obj(output), tu = obj(obj(o.llmOutput).tokenUsage);
52
+ const first = Array.isArray(o.generations) && Array.isArray(o.generations[0]) ? obj(o.generations[0][0]) : {};
53
+ const msg = obj(first.message), um = obj(msg.usage_metadata), rm = obj(msg.response_metadata);
54
+ const input = num(tu.promptTokens) ?? num(um.input_tokens), out = num(tu.completionTokens) ?? num(um.output_tokens);
55
+ if (input !== undefined)
56
+ span.setAttribute('gen_ai.usage.input_tokens', input);
57
+ if (out !== undefined)
58
+ span.setAttribute('gen_ai.usage.output_tokens', out);
59
+ if (s(rm.model_name))
60
+ span.setAttribute('gen_ai.response.model', s(rm.model_name));
61
+ if (s(rm.finish_reason))
62
+ span.setAttribute('gen_ai.response.finish_reasons', [s(rm.finish_reason)]);
63
+ span.end();
64
+ },
65
+ handleLLMError: (e, runId) => ender(runId, e),
66
+ handleChainStart: (_c, _i, runId, parentId, _t, metadata, _rt, runName) => {
67
+ const m = obj(metadata), node = s(m.langgraph_node);
68
+ // only LangGraph runs get spans (the graph root and its nodes); plain LCEL chains are noise
69
+ if (!node && !(parentId === undefined && m.langgraph_step !== undefined)) {
70
+ up.set(runId, parentId);
71
+ return;
72
+ }
73
+ const who = node && runName === node ? node : runName || node || 'graph';
74
+ begin(runId, parentId, `invoke_agent ${who}`, { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': who, 'gen_ai.system': 'langgraph' });
75
+ },
76
+ handleChainEnd: (_o, runId) => ender(runId),
77
+ handleChainError: (e, runId) => ender(runId, e),
78
+ handleToolStart: (tool, _i, runId, parentId, _t, _m, runName) => {
79
+ const name = runName || s(obj(tool).name) || s(obj(obj(tool).kwargs).name);
80
+ begin(runId, parentId, `execute_tool ${name}`.trim(), { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': name });
81
+ },
82
+ handleToolEnd: (_o, runId) => ender(runId),
83
+ handleToolError: (e, runId) => ender(runId, e),
84
+ };
85
+ return h;
86
+ }
87
+ /** Wraps every `execute` of an AI SDK / Mastra tool set so each call is an `execute_tool` span under the agent run. */
88
+ function wrapTools(tools, root) {
89
+ const out = {};
90
+ for (const [name, t] of Object.entries(obj(tools))) {
91
+ const tool = obj(t), exec = tool.execute;
92
+ if (typeof exec !== 'function') {
93
+ out[name] = t;
94
+ continue;
95
+ }
96
+ out[name] = {
97
+ ...tool,
98
+ execute: (...a) => {
99
+ const sp = start(`execute_tool ${name}`, { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': name }, root);
100
+ const done = (e) => { if (e !== undefined)
101
+ fail(sp, e); sp.end(); };
102
+ try {
103
+ const r = exec.apply(tool, a);
104
+ if (thenable(r))
105
+ r.then(() => done(), (e) => done(e ?? new Error('tool failed')));
106
+ else
107
+ done();
108
+ return r;
109
+ }
110
+ catch (e) {
111
+ done(e);
112
+ throw e;
113
+ }
114
+ },
115
+ };
116
+ }
117
+ return out;
118
+ }
119
+ /**
120
+ * One agent run as an `invoke_agent` span. `onStepFinish` (injected, the caller's own still runs) turns every model
121
+ * step into a `chat` span with usage, timed from the previous step's end; tool `execute` calls become
122
+ * `execute_tool` spans. `optsAt` is the position of the options argument. A stream ends the run in `onFinish` /
123
+ * `onError`; a promise ends it when it settles.
124
+ */
125
+ function agentRun(system, name, orig, self, args, optsAt, stream) {
126
+ const root = start(`invoke_agent ${name}`.trim(), { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': name, 'gen_ai.system': system });
127
+ let ended = false, last = Date.now();
128
+ const end = (e) => { if (ended)
129
+ return; ended = true; if (e !== undefined)
130
+ fail(root, e); root.end(); };
131
+ const opts = { ...obj(args[optsAt]) };
132
+ const onStep = opts.onStepFinish, onFinish = opts.onFinish, onError = opts.onError;
133
+ opts.onStepFinish = (e) => {
134
+ const d = obj(e), u = obj(d.usage), r = obj(d.response);
135
+ const model = s(r.modelId) || s(r.model) || s(d.model);
136
+ const sp = start(`chat ${model}`.trim(), { 'gen_ai.operation.name': 'chat', 'gen_ai.system': system, 'gen_ai.response.model': model }, root, last);
137
+ const input = num(u.inputTokens) ?? num(u.promptTokens), out = num(u.outputTokens) ?? num(u.completionTokens);
138
+ if (input !== undefined)
139
+ sp.setAttribute('gen_ai.usage.input_tokens', input);
140
+ if (out !== undefined)
141
+ sp.setAttribute('gen_ai.usage.output_tokens', out);
142
+ if (s(d.finishReason))
143
+ sp.setAttribute('gen_ai.response.finish_reasons', [s(d.finishReason)]);
144
+ sp.end();
145
+ last = Date.now();
146
+ return onStep?.(e);
147
+ };
148
+ if (stream) {
149
+ opts.onFinish = (e) => { end(); return onFinish?.(e); };
150
+ opts.onError = (e) => { end(obj(e).error ?? e ?? new Error('stream failed')); return onError?.(e); };
151
+ }
152
+ if (opts.tools)
153
+ opts.tools = wrapTools(opts.tools, root);
154
+ const a = [...args];
155
+ a[optsAt] = opts;
156
+ let res;
157
+ try {
158
+ res = context.with(trace.setSpan(context.active(), root), () => orig.apply(self, a));
159
+ }
160
+ catch (e) {
161
+ end(e);
162
+ throw e;
163
+ }
164
+ if (!stream) {
165
+ // side branch only: the caller keeps the framework's own promise
166
+ if (thenable(res))
167
+ res.then(() => end(), (e) => end(e ?? new Error('run failed')));
168
+ else
169
+ end();
170
+ }
171
+ return res;
172
+ }
173
+ /**
174
+ * instrumentVercelAI({ generateText, streamText }) with the functions from `ai`: returns wrapped copies (ES module
175
+ * exports cannot be patched). Pass `agentName` to name the run (default: the `experimental_telemetry.functionId`, else `agent`).
176
+ * const { generateText } = instrumentVercelAI({ generateText: ai.generateText });
177
+ * A multi-step loop (`maxSteps` / `stopWhen`) gives one `invoke_agent` span with a `chat` span per step and an
178
+ * `execute_tool` span per tool call.
179
+ */
180
+ export function instrumentVercelAI(ai, agentName) {
181
+ const out = { ...ai };
182
+ const nameOf = (a) => agentName || s(obj(obj(a[0]).experimental_telemetry).functionId) || 'agent';
183
+ if (typeof ai.generateText === 'function') {
184
+ const f = ai.generateText;
185
+ out.generateText = function (...a) { return agentRun('vercel_ai', nameOf(a), f, this, a, 0, false); };
186
+ }
187
+ if (typeof ai.streamText === 'function') {
188
+ const f = ai.streamText;
189
+ out.streamText = function (...a) { return agentRun('vercel_ai', nameOf(a), f, this, a, 0, true); };
190
+ }
191
+ return out;
192
+ }
193
+ /** instrumentMastra(agent): wraps `agent.generate` and `agent.stream` of a Mastra `Agent`; the run is named after the agent. Returns the agent. */
194
+ export function instrumentMastra(agent) {
195
+ const a = agent;
196
+ const name = s(a.name) || 'agent';
197
+ for (const [method, stream] of [['generate', false], ['stream', true]]) {
198
+ const f = a[method];
199
+ if (typeof f !== 'function' || f.__wt)
200
+ continue;
201
+ const wrapped = function (...args) { return agentRun('mastra', name, f, this, args, 1, stream); };
202
+ wrapped.__wt = true;
203
+ a[method] = wrapped;
204
+ }
205
+ return agent;
206
+ }
@@ -1,4 +1,5 @@
1
1
  export { instrumentLlamaIndex, instrumentOpenAIAgents } from './genai-agents.js';
2
+ export { instrumentMastra, instrumentVercelAI, langchainCallbackHandler } from './genai-frameworks.js';
2
3
  /**
3
4
  * instrumentOpenAI(new OpenAI()): chat.completions.create and responses.create. Returns the client.
4
5
  * For an OpenAI-compatible gateway pass its name: instrumentOpenAI(new OpenAI({ baseURL: litellmUrl }), 'litellm').
@@ -1,10 +1,12 @@
1
1
  // GenAI spans (OTel GenAI semconv) for the openai, anthropic, AWS Bedrock, Google GenAI, Mistral and Ollama SDKs (and
2
- // LiteLLM through its OpenAI-compatible proxy), LlamaIndex and the OpenAI Agents SDK (genai-agents.ts), and a
2
+ // LiteLLM through its OpenAI-compatible proxy), LlamaIndex and the OpenAI Agents SDK (genai-agents.ts), LangGraph.js,
3
+ // Mastra and the Vercel AI SDK agent loop (genai-frameworks.ts), and a
3
4
  // telemetry option for the Vercel AI SDK. Streams record time to first chunk, usage and tool calls (genai-stream.ts).
4
5
  // Prompt and completion text is never recorded.
5
6
  import { context, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
6
7
  import { applyExtract, extract, tapStream } from './genai-stream.js';
7
8
  export { instrumentLlamaIndex, instrumentOpenAIAgents } from './genai-agents.js';
9
+ export { instrumentMastra, instrumentVercelAI, langchainCallbackHandler } from './genai-frameworks.js';
8
10
  const DONE = Symbol('wt.instrumented');
9
11
  const plain = (b) => (b || {});
10
12
  function wrap(target, method, system, req = plain) {
@@ -0,0 +1,31 @@
1
+ export interface SourcemapOptions {
2
+ /** Directory holding the client build; default `.next/static`. */
3
+ dir?: string;
4
+ /** Default WT_API_URL, then https://api.watchtower.observer. */
5
+ apiUrl?: string;
6
+ /** A key with scope `ci:write` (it covers releases and artifacts; `admin:write` also works). Default WT_API_KEY. */
7
+ apiKey?: string;
8
+ /** Project id or slug the maps belong to. Default WT_PROJECT. */
9
+ project?: string;
10
+ /** Release version: must equal the `release` the browser SDK reports. Default WT_RELEASE. */
11
+ release?: string;
12
+ /** Keep the .map files after a successful upload (default: delete them so they are never served). */
13
+ keep?: boolean;
14
+ fetch?: typeof fetch;
15
+ log?: (line: string) => void;
16
+ }
17
+ type NextConfig = Record<string, unknown>;
18
+ type ConfigOrFn = NextConfig | ((...a: unknown[]) => NextConfig | Promise<NextConfig>);
19
+ /**
20
+ * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
21
+ * `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
22
+ * (`"build": "next build && wt-next-sourcemaps"`) to upload them and delete the .map files from `.next/static`.
23
+ */
24
+ export declare function withWatchtower(config?: ConfigOrFn, opts?: {
25
+ sourcemaps?: boolean;
26
+ }): ConfigOrFn;
27
+ /** Upload every `.map` under `dir` as `_next/static/<path>` for the release, then delete them. Throws (leaving the files) when an upload fails. */
28
+ export declare function uploadSourcemaps(o?: SourcemapOptions): Promise<{
29
+ uploaded: number;
30
+ }>;
31
+ export {};
@@ -0,0 +1,58 @@
1
+ // Build-time helpers for Next.js: `withWatchtower` (next.config) and `uploadSourcemaps` (after `next build`).
2
+ import * as fs from 'node:fs';
3
+ import * as nodePath from 'node:path';
4
+ /**
5
+ * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
6
+ * `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
7
+ * (`"build": "next build && wt-next-sourcemaps"`) to upload them and delete the .map files from `.next/static`.
8
+ */
9
+ export function withWatchtower(config = {}, opts = {}) {
10
+ const apply = (c) => (opts.sourcemaps ? { ...c, productionBrowserSourceMaps: true } : c);
11
+ if (typeof config !== 'function')
12
+ return apply(config);
13
+ return async (...a) => apply(await config(...a));
14
+ }
15
+ function* maps(dir) {
16
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
17
+ const p = nodePath.join(dir, e.name);
18
+ if (e.isDirectory())
19
+ yield* maps(p);
20
+ else if (e.name.endsWith('.map'))
21
+ yield p;
22
+ }
23
+ }
24
+ /** Upload every `.map` under `dir` as `_next/static/<path>` for the release, then delete them. Throws (leaving the files) when an upload fails. */
25
+ export async function uploadSourcemaps(o = {}) {
26
+ const env = process.env;
27
+ const key = o.apiKey || env.WT_API_KEY;
28
+ const project = o.project || env.WT_PROJECT;
29
+ const release = o.release || env.WT_RELEASE;
30
+ if (!key)
31
+ throw new Error('WT_API_KEY is required (a key with scope ci:write)');
32
+ if (!project)
33
+ throw new Error('WT_PROJECT (project id) is required');
34
+ if (!release)
35
+ throw new Error('WT_RELEASE is required');
36
+ const dir = nodePath.resolve(o.dir || '.next/static');
37
+ const f = o.fetch || fetch;
38
+ const log = o.log || (() => { });
39
+ const root = `${(o.apiUrl || env.WT_API_URL || 'https://api.watchtower.observer').replace(/\/+$/, '')}/v1/projects/${encodeURIComponent(project)}`;
40
+ const call = async (path, init, okStatus = []) => {
41
+ const res = await f(root + path, { ...init, headers: { authorization: `Bearer ${key}`, ...init.headers } });
42
+ if (!res.ok && !okStatus.includes(res.status))
43
+ throw new Error(`watchtower ${init.method} ${path.split('?')[0]} -> HTTP ${res.status}`);
44
+ };
45
+ const files = fs.existsSync(dir) ? [...maps(dir)] : [];
46
+ await call('/releases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ version: release }) }, [409]); // 409: exists
47
+ for (const file of files) {
48
+ const name = `_next/static/${nodePath.relative(dir, file).split(nodePath.sep).join('/')}`;
49
+ await call(`/artifacts?${new URLSearchParams({ kind: 'sourcemap', name, release })}`, {
50
+ method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: new Uint8Array(fs.readFileSync(file)),
51
+ });
52
+ }
53
+ if (!o.keep)
54
+ for (const file of files)
55
+ fs.rmSync(file);
56
+ log(`uploaded ${files.length} source maps for release ${release}${o.keep ? '' : ' and deleted them'}`);
57
+ return { uploaded: files.length };
58
+ }
@@ -0,0 +1,14 @@
1
+ export interface TunnelOptions {
2
+ /** Edge base URL the requests are forwarded to. */
3
+ endpoint: string;
4
+ /** Route prefix to strip; default `/api/wt`. */
5
+ basePath?: string;
6
+ /** Request body cap in bytes; default 1 MiB (over it: 413). */
7
+ maxBodyBytes?: number;
8
+ fetch?: typeof fetch;
9
+ }
10
+ /** Next route handlers `{ GET, POST }` forwarding allow-listed RUM paths to the edge. Only the publishable key (`?k=` or a `wtp_` bearer) is forwarded as auth; cookies and other headers are not. */
11
+ export declare function tunnelHandler(o: TunnelOptions): {
12
+ GET: (r: Request) => Promise<Response>;
13
+ POST: (r: Request) => Promise<Response>;
14
+ };
@@ -0,0 +1,49 @@
1
+ // First-party tunnel for browser telemetry (ad blockers block third-party telemetry hosts).
2
+ // app/api/wt/[...path]/route.ts: export const { GET, POST } = tunnelHandler({ endpoint: process.env.WT_EDGE_URL! });
3
+ // Browser SDK: init({ endpoint: '/api/wt', publishableKey: 'wtp_...' }).
4
+ // only what the browser SDK calls: /v1/rum/*, /v1/replay/<session>/chunks and /v1/logs
5
+ const ALLOWED = /^\/v1\/(rum\/[A-Za-z0-9/_-]+|replay\/[A-Za-z0-9_-]+\/chunks|logs)$/;
6
+ const FORWARD = ['content-type', 'content-encoding', 'user-agent'];
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
+ export function tunnelHandler(o) {
9
+ const base = (o.basePath ?? '/api/wt').replace(/\/+$/, '');
10
+ const max = o.maxBodyBytes ?? 1024 * 1024;
11
+ const edge = o.endpoint.replace(/\/+$/, '');
12
+ const send = o.fetch ?? fetch;
13
+ const handle = async (req) => {
14
+ const url = new URL(req.url);
15
+ const path = url.pathname.startsWith(base) ? url.pathname.slice(base.length) : url.pathname;
16
+ if (!ALLOWED.test(path) || path.includes('..'))
17
+ return new Response('not found', { status: 404 });
18
+ const headers = {};
19
+ for (const h of FORWARD) {
20
+ const v = req.headers.get(h);
21
+ if (v)
22
+ headers[h] = v;
23
+ }
24
+ const bearer = /^Bearer (wtp_\S+)$/.exec(req.headers.get('authorization') ?? '');
25
+ if (bearer)
26
+ headers.authorization = `Bearer ${bearer[1]}`;
27
+ const k = url.searchParams.get('k');
28
+ let body;
29
+ if (req.method === 'POST') {
30
+ if (Number(req.headers.get('content-length') ?? 0) > max)
31
+ return new Response('payload too large', { status: 413 });
32
+ body = await req.arrayBuffer();
33
+ if (body.byteLength > max)
34
+ return new Response('payload too large', { status: 413 });
35
+ }
36
+ try {
37
+ const res = await send(`${edge}${path}${k ? `?k=${encodeURIComponent(k)}` : ''}`, { method: req.method, headers, body });
38
+ const out = new Headers();
39
+ const ct = res.headers.get('content-type');
40
+ if (ct)
41
+ out.set('content-type', ct);
42
+ return new Response(res.status === 204 ? null : await res.arrayBuffer(), { status: res.status, headers: out });
43
+ }
44
+ catch {
45
+ return new Response('bad gateway', { status: 502 });
46
+ }
47
+ };
48
+ return { GET: handle, POST: handle };
49
+ }
@@ -1,5 +1,28 @@
1
+ import type { ReadableSpan } from '@opentelemetry/sdk-trace';
2
+ import * as wt from '../index.js';
3
+ export { withWatchtower, uploadSourcemaps } from './next-build.js';
4
+ export type { SourcemapOptions } from './next-build.js';
5
+ export { tunnelHandler } from './next-tunnel.js';
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;
22
+ /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
23
+ export declare function makeRegister(options?: NextOptions): () => Promise<void>;
1
24
  /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
2
- export declare function register(): Promise<void>;
25
+ export declare const register: () => Promise<void>;
3
26
  /** Next.js onRequestError: server render, route handler and server action errors. */
4
27
  export declare function onRequestError(err: unknown, request?: {
5
28
  path?: string;
@@ -1,12 +1,38 @@
1
1
  // instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
2
+ // or, with options: export const register = makeRegister({ redact }); export { onRequestError } from '@watchtowerobservability/node/next';
3
+ import { SpanStatusCode } from '@opentelemetry/api';
2
4
  import * as wt from '../index.js';
3
- /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
4
- export async function register() {
5
- const rt = process.env.NEXT_RUNTIME;
6
- if ((rt && rt !== 'nodejs') || !process.env.WT_INGEST_KEY)
7
- return;
8
- wt.init({});
5
+ export { withWatchtower, uploadSourcemaps } from './next-build.js';
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);
9
22
  }
23
+ /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
24
+ export function makeRegister(options = {}) {
25
+ return async function register() {
26
+ const rt = process.env.NEXT_RUNTIME;
27
+ if ((rt && rt !== 'nodejs') || !(options.apiKey || process.env.WT_INGEST_KEY))
28
+ return;
29
+ const { nextInternals, nextInternalsRate, ...init } = options;
30
+ const own = nextInternalsFilter(nextInternals, nextInternalsRate);
31
+ wt.init({ ...init, spanFilter: init.spanFilter ? (s) => own(s) && init.spanFilter(s) : own });
32
+ };
33
+ }
34
+ /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
35
+ export const register = makeRegister();
10
36
  /** Next.js onRequestError: server render, route handler and server action errors. */
11
37
  export async function onRequestError(err, request, context) {
12
38
  const c = context || {};
package/dist/esm/load.js CHANGED
@@ -1,5 +1,83 @@
1
+ // Optional-peer loader. Each peer is required by a LITERAL name inside a try block so bundlers (webpack, esbuild, Next's
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
5
  import { createRequire } from 'node:module';
2
- const req = createRequire(import.meta.url);
6
+ const pre = {};
7
+ try { pre["@opentelemetry/context-async-hooks"] = await import("@opentelemetry/context-async-hooks"); } catch (e) { pre["@opentelemetry/context-async-hooks"] = e; }
8
+ try { pre["@opentelemetry/core"] = await import("@opentelemetry/core"); } catch (e) { pre["@opentelemetry/core"] = e; }
9
+ try { pre["@opentelemetry/exporter-logs-otlp-http"] = await import("@opentelemetry/exporter-logs-otlp-http"); } catch (e) { pre["@opentelemetry/exporter-logs-otlp-http"] = e; }
10
+ try { pre["@opentelemetry/exporter-metrics-otlp-http"] = await import("@opentelemetry/exporter-metrics-otlp-http"); } catch (e) { pre["@opentelemetry/exporter-metrics-otlp-http"] = e; }
11
+ try { pre["@opentelemetry/exporter-trace-otlp-http"] = await import("@opentelemetry/exporter-trace-otlp-http"); } catch (e) { pre["@opentelemetry/exporter-trace-otlp-http"] = e; }
12
+ try { pre["@opentelemetry/otlp-transformer"] = await import("@opentelemetry/otlp-transformer"); } catch (e) { pre["@opentelemetry/otlp-transformer"] = e; }
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
+ }
60
+ }
3
61
  export function load(id) {
4
- return req(id);
62
+ if (typeof require !== 'function')
63
+ return createRequire(`${process.cwd()}/`)(id);
64
+ const m = known(id);
65
+ return m === NONE ? require(id) : m;
66
+ }
67
+ const SDK_PEERS = [
68
+ '@opentelemetry/context-async-hooks', '@opentelemetry/core', '@opentelemetry/exporter-logs-otlp-http',
69
+ '@opentelemetry/exporter-metrics-otlp-http', '@opentelemetry/exporter-trace-otlp-http', '@opentelemetry/otlp-transformer',
70
+ '@opentelemetry/resources', '@opentelemetry/sdk-logs', '@opentelemetry/sdk-metrics', '@opentelemetry/sdk-trace',
71
+ ];
72
+ /** Load an OpenTelemetry SDK package (an optional peer); a missing one throws an error naming what to install. */
73
+ export function need(id) {
74
+ try {
75
+ return load(id);
76
+ }
77
+ catch (e) {
78
+ if (e?.code === 'MODULE_NOT_FOUND' && String(e.message).includes(id)) {
79
+ throw new Error(`@watchtowerobservability/node needs the OpenTelemetry SDK, which is not installed (missing ${id}). Run: npm install ${SDK_PEERS.join(' ')}`);
80
+ }
81
+ throw e;
82
+ }
5
83
  }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
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
+ import { uploadSourcemaps } from './integrations/next-build.js';
4
+ uploadSourcemaps({ dir: process.argv[2], log: (l) => console.log(`[watchtower] ${l}`) }).catch((e) => {
5
+ console.error(`[watchtower] source map upload failed: ${e.message}`);
6
+ process.exit(1);
7
+ });
@@ -0,0 +1,9 @@
1
+ import type { SpanProcessor } from '@opentelemetry/sdk-trace';
2
+ export interface Frame {
3
+ file: string;
4
+ line: number;
5
+ fn?: string;
6
+ }
7
+ /** The first application frame of a V8 stack, or undefined. */
8
+ export declare function firstAppFrame(stack: string): Frame | undefined;
9
+ export declare function codeOrigin(): SpanProcessor;
@@ -0,0 +1,39 @@
1
+ const FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):\d+\)?$/;
2
+ const SKIP = /node_modules|^node:|[\\/]watchtower[\\/](?:dist|src)[\\/]|@watchtowerobservability[\\/]node/;
3
+ /** The first application frame of a V8 stack, or undefined. */
4
+ export function firstAppFrame(stack) {
5
+ for (const line of stack.split('\n').slice(1)) {
6
+ const m = FRAME.exec(line);
7
+ if (!m)
8
+ continue;
9
+ const file = m[2].replace(/^file:\/\//, '');
10
+ if (SKIP.test(file) || SKIP.test(line.trim().slice(3)))
11
+ continue;
12
+ return { file, line: Number(m[3]), fn: m[1] && m[1] !== '<anonymous>' ? m[1] : undefined };
13
+ }
14
+ return undefined;
15
+ }
16
+ export function codeOrigin() {
17
+ return {
18
+ onStart(span) {
19
+ const s = span;
20
+ if (s.attributes?.['code.filepath'] !== undefined)
21
+ return;
22
+ const holder = {};
23
+ const prev = Error.stackTraceLimit;
24
+ Error.stackTraceLimit = 30;
25
+ Error.captureStackTrace(holder);
26
+ Error.stackTraceLimit = prev;
27
+ const f = firstAppFrame(holder.stack ?? '');
28
+ if (!f)
29
+ return;
30
+ s.setAttribute('code.filepath', f.file);
31
+ s.setAttribute('code.lineno', f.line);
32
+ if (f.fn)
33
+ s.setAttribute('code.function', f.fn);
34
+ },
35
+ onEnd() { },
36
+ shutdown: () => Promise.resolve(),
37
+ forceFlush: () => Promise.resolve(),
38
+ };
39
+ }
@@ -0,0 +1,8 @@
1
+ import type { SpanProcessor } from '@opentelemetry/sdk-trace';
2
+ export type RedactHook = (key: string, value: unknown) => unknown;
3
+ /** Hook keys for the non-attribute fields. Event attributes (incl. exception.message / exception.stacktrace) use their own keys. */
4
+ export declare const SPAN_NAME_KEY = "span.name";
5
+ export declare const STATUS_MESSAGE_KEY = "status.message";
6
+ export declare const LOG_BODY_KEY = "log.body";
7
+ /** Span processor that redacts the name, status message, attributes, every event's and link's attributes before export. */
8
+ export declare function redactor(hook: RedactHook): SpanProcessor;