@watchtowerobservability/node 0.7.4 → 0.7.6

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 (89) hide show
  1. package/CHANGELOG.md +39 -1
  2. package/README.md +96 -12
  3. package/dist/cjs/attach.d.ts +7 -0
  4. package/dist/cjs/attach.js +29 -0
  5. package/dist/cjs/checkin.js +4 -13
  6. package/dist/cjs/cron/monitor.d.ts +47 -0
  7. package/dist/cjs/cron/monitor.js +95 -0
  8. package/dist/cjs/cron/schedulers.d.ts +36 -0
  9. package/dist/cjs/cron/schedulers.js +65 -0
  10. package/dist/cjs/env.d.ts +10 -0
  11. package/dist/cjs/env.js +98 -1
  12. package/dist/cjs/index.d.ts +50 -6
  13. package/dist/cjs/index.js +114 -37
  14. package/dist/cjs/instrument-for.d.ts +17 -0
  15. package/dist/cjs/instrument-for.js +44 -0
  16. package/dist/cjs/instrument.d.ts +4 -0
  17. package/dist/cjs/instrument.js +32 -1
  18. package/dist/cjs/integrations/bullmq.d.ts +8 -2
  19. package/dist/cjs/integrations/bullmq.js +32 -5
  20. package/dist/cjs/integrations/db.d.ts +7 -2
  21. package/dist/cjs/integrations/db.js +32 -4
  22. package/dist/cjs/integrations/fastify.d.ts +1 -1
  23. package/dist/cjs/integrations/fastify.js +3 -2
  24. package/dist/cjs/integrations/logs.js +16 -5
  25. package/dist/cjs/integrations/next-build.d.ts +31 -8
  26. package/dist/cjs/integrations/next-build.js +183 -34
  27. package/dist/cjs/integrations/next-tunnel.d.ts +6 -1
  28. package/dist/cjs/integrations/next-tunnel.js +13 -2
  29. package/dist/cjs/integrations/postgres.d.ts +2 -0
  30. package/dist/cjs/integrations/postgres.js +43 -1
  31. package/dist/cjs/integrations/temporal.d.ts +97 -0
  32. package/dist/cjs/integrations/temporal.js +144 -0
  33. package/dist/cjs/integrations/util.d.ts +17 -0
  34. package/dist/cjs/integrations/util.js +38 -0
  35. package/dist/cjs/load.d.ts +6 -0
  36. package/dist/cjs/load.js +28 -4
  37. package/dist/cjs/next-doctor-cli.d.ts +2 -0
  38. package/dist/cjs/next-doctor-cli.js +15 -0
  39. package/dist/cjs/next-doctor.d.ts +2 -0
  40. package/dist/cjs/next-doctor.js +50 -0
  41. package/dist/cjs/redact-presets.d.ts +16 -0
  42. package/dist/cjs/redact-presets.js +66 -0
  43. package/dist/cjs/register.js +19 -6
  44. package/dist/cjs/version.d.ts +1 -1
  45. package/dist/cjs/version.js +1 -1
  46. package/dist/esm/attach.d.ts +7 -0
  47. package/dist/esm/attach.js +25 -0
  48. package/dist/esm/checkin.js +4 -13
  49. package/dist/esm/cron/monitor.d.ts +47 -0
  50. package/dist/esm/cron/monitor.js +85 -0
  51. package/dist/esm/cron/schedulers.d.ts +36 -0
  52. package/dist/esm/cron/schedulers.js +61 -0
  53. package/dist/esm/env.d.ts +10 -0
  54. package/dist/esm/env.js +62 -0
  55. package/dist/esm/index.d.ts +50 -6
  56. package/dist/esm/index.js +109 -39
  57. package/dist/esm/instrument-for.d.ts +17 -0
  58. package/dist/esm/instrument-for.js +41 -0
  59. package/dist/esm/instrument.d.ts +4 -0
  60. package/dist/esm/instrument.js +30 -1
  61. package/dist/esm/integrations/bullmq.d.ts +8 -2
  62. package/dist/esm/integrations/bullmq.js +32 -5
  63. package/dist/esm/integrations/db.d.ts +7 -2
  64. package/dist/esm/integrations/db.js +29 -4
  65. package/dist/esm/integrations/fastify.d.ts +1 -1
  66. package/dist/esm/integrations/fastify.js +4 -3
  67. package/dist/esm/integrations/logs.js +16 -5
  68. package/dist/esm/integrations/next-build.d.ts +31 -8
  69. package/dist/esm/integrations/next-build.js +180 -34
  70. package/dist/esm/integrations/next-tunnel.d.ts +6 -1
  71. package/dist/esm/integrations/next-tunnel.js +13 -2
  72. package/dist/esm/integrations/postgres.d.ts +2 -0
  73. package/dist/esm/integrations/postgres.js +43 -2
  74. package/dist/esm/integrations/temporal.d.ts +97 -0
  75. package/dist/esm/integrations/temporal.js +139 -0
  76. package/dist/esm/integrations/util.d.ts +17 -0
  77. package/dist/esm/integrations/util.js +35 -0
  78. package/dist/esm/load.d.ts +6 -0
  79. package/dist/esm/load.js +21 -3
  80. package/dist/esm/next-doctor-cli.d.ts +2 -0
  81. package/dist/esm/next-doctor-cli.js +13 -0
  82. package/dist/esm/next-doctor.d.ts +2 -0
  83. package/dist/esm/next-doctor.js +14 -0
  84. package/dist/esm/redact-presets.d.ts +16 -0
  85. package/dist/esm/redact-presets.js +58 -0
  86. package/dist/esm/register.js +20 -7
  87. package/dist/esm/version.d.ts +1 -1
  88. package/dist/esm/version.js +1 -1
  89. package/package.json +42 -1
@@ -18,17 +18,40 @@ export interface SourcemapOptions {
18
18
  }
19
19
  type NextConfig = Record<string, unknown>;
20
20
  type ConfigOrFn = NextConfig | ((...a: unknown[]) => NextConfig | Promise<NextConfig>);
21
+ export interface WatchtowerNextOptions {
22
+ /**
23
+ * `true` turns on `productionBrowserSourceMaps`. `{ upload: true }` also uploads `.next/static/**\/*.map` when the
24
+ * webpack client build finishes (CI: needs WT_API_KEY, WT_PROJECT; the release is `release` below) and, unless
25
+ * `deleteAfterUpload: false`, deletes the maps. Turbopack has no webpack hooks: run `wt-next-sourcemaps` after `next build`.
26
+ * Other fields are `uploadSourcemaps` options (`apiUrl`, `project`, `inject`, `fetch`, ...).
27
+ */
28
+ sourcemaps?: boolean | (Omit<SourcemapOptions, 'keep' | 'release'> & {
29
+ upload?: boolean;
30
+ deleteAfterUpload?: boolean;
31
+ });
32
+ /** Release: injected as `NEXT_PUBLIC_WT_RELEASE` (read by `<WatchtowerRUM>`). Default WT_RELEASE, then the git sha of the CI/host env. */
33
+ release?: string;
34
+ /** Sentry is in the app (default: `@sentry/nextjs` or `@sentry/node` in package.json): keep the OTel packages it shares bundled. */
35
+ sentry?: boolean;
36
+ }
37
+ /** Is a Sentry Node/Next SDK installed in the app being built? */
38
+ export declare function hasSentry(cwd?: string): boolean;
39
+ /** The `serverExternalPackages` withWatchtower adds; `sentry` drops the packages a bundled Sentry shares. */
40
+ export declare function externalPackages(sentry: boolean): string[];
21
41
  /**
22
- * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
23
- * `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
24
- * (`"build": "next build && wt-next-sourcemaps"`) to upload them and delete the .map files from `.next/static`.
42
+ * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`. Makes `output: 'standalone'` work with no other
43
+ * config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages` and (npm and pnpm layouts) into
44
+ * `outputFileTracingIncludes` for every route. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
45
+ * `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
46
+ * client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
25
47
  */
26
- export declare function withWatchtower(config?: ConfigOrFn, opts?: {
27
- sourcemaps?: boolean;
28
- }): ConfigOrFn;
48
+ export declare function withWatchtower(config?: ConfigOrFn, opts?: WatchtowerNextOptions): ConfigOrFn;
49
+ /** A ustar archive of `[name, bytes]` (names up to 100 bytes). */
50
+ export declare function makeTar(files: [string, Buffer][]): Buffer;
29
51
  /**
30
- * Upload every `.map` under `dir` as `_next/static/<path>` for the release (8 at a time, 429/5xx retried with backoff
31
- * honoring Retry-After; a failed map does not stop the others), then delete them when none failed. Returns
52
+ * Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~120 MB
53
+ * batch (tar.gz plus manifest), falling back to single uploads (8 at a time) when the server has no bundle route.
54
+ * 429/5xx are retried with backoff honoring Retry-After; a failed map does not stop the others. The maps are deleted when none failed. Returns
32
55
  * `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
33
56
  * gzipped (`Content-Encoding: gzip`).
34
57
  */
@@ -3,13 +3,84 @@ import * as fs from 'node:fs';
3
3
  import * as nodePath from 'node:path';
4
4
  import * as zlib from 'node:zlib';
5
5
  import { injectDebugIds } from './next-debugid.js';
6
+ // what the node SDK loads at run time through createRequire (invisible to Next's file tracer): see src/load.ts
7
+ const OTEL = [
8
+ '@opentelemetry/api', '@opentelemetry/context-async-hooks', '@opentelemetry/core', '@opentelemetry/exporter-logs-otlp-http',
9
+ '@opentelemetry/exporter-metrics-otlp-http', '@opentelemetry/exporter-trace-otlp-http', '@opentelemetry/instrumentation',
10
+ // every instrumentation too, so none of ours is bundled against an external base class
11
+ '@opentelemetry/instrumentation-http', '@opentelemetry/instrumentation-ioredis', '@opentelemetry/instrumentation-mysql2',
12
+ '@opentelemetry/instrumentation-pg', '@opentelemetry/instrumentation-runtime-node', '@opentelemetry/instrumentation-undici',
13
+ '@opentelemetry/otlp-transformer', '@opentelemetry/resources', '@opentelemetry/sdk-logs', '@opentelemetry/sdk-metrics',
14
+ '@opentelemetry/sdk-trace',
15
+ ];
16
+ const EXTERNAL = ['@watchtowerobservability/node', ...OTEL];
17
+ // Packages Sentry's own nested OTel copies import. Sentry stays bundled, so externalising these made its bundled
18
+ // `HttpInstrumentation` extend an `InstrumentationBase` that resolved to undefined (B9b). With Sentry present they stay
19
+ // bundled for Sentry, while ours (external) still resolve them from node_modules at run time.
20
+ const SHARED_WITH_SENTRY = new Set(['@opentelemetry/api', '@opentelemetry/instrumentation']);
21
+ /** Is a Sentry Node/Next SDK installed in the app being built? */
22
+ export function hasSentry(cwd = process.cwd()) {
23
+ try {
24
+ const pkg = JSON.parse(fs.readFileSync(nodePath.join(cwd, 'package.json'), 'utf8'));
25
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
26
+ return Object.keys(deps).some((n) => n === '@sentry/nextjs' || n === '@sentry/node');
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ /** The `serverExternalPackages` withWatchtower adds; `sentry` drops the packages a bundled Sentry shares. */
33
+ export function externalPackages(sentry) {
34
+ return sentry ? EXTERNAL.filter((n) => !SHARED_WITH_SENTRY.has(n)) : EXTERNAL;
35
+ }
36
+ const SHA_ENV = ['WT_RELEASE', 'GITHUB_SHA', 'CI_COMMIT_SHA', 'VERCEL_GIT_COMMIT_SHA', 'SOURCE_VERSION', 'BUILD_SHA', 'RENDER_GIT_COMMIT', 'HEROKU_SLUG_COMMIT'];
37
+ const INCLUDE = ['@watchtowerobservability/node', '@opentelemetry'].flatMap((p) => [`./node_modules/${p}/**/*`, `./node_modules/.pnpm/${p.replace('/', '+')}*/**/*`]);
6
38
  /**
7
- * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
8
- * `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
9
- * (`"build": "next build && wt-next-sourcemaps"`) to upload them and delete the .map files from `.next/static`.
39
+ * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`. Makes `output: 'standalone'` work with no other
40
+ * config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages` and (npm and pnpm layouts) into
41
+ * `outputFileTracingIncludes` for every route. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
42
+ * `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
43
+ * client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
10
44
  */
11
45
  export function withWatchtower(config = {}, opts = {}) {
12
- const apply = (c) => (opts.sourcemaps ? { ...c, productionBrowserSourceMaps: true } : c);
46
+ const sm = opts.sourcemaps === true ? {} : opts.sourcemaps || undefined;
47
+ const release = opts.release || SHA_ENV.map((k) => process.env[k]).find((v) => v && v !== 'unknown');
48
+ const apply = (c) => {
49
+ const inc = { ...c.outputFileTracingIncludes };
50
+ inc['/*'] = [...new Set([...(inc['/*'] ?? []), ...INCLUDE])];
51
+ const out = {
52
+ ...c,
53
+ serverExternalPackages: [...new Set([...(c.serverExternalPackages ?? []), ...externalPackages(opts.sentry ?? hasSentry())])],
54
+ outputFileTracingIncludes: inc,
55
+ };
56
+ if (release)
57
+ out.env = { NEXT_PUBLIC_WT_RELEASE: release, ...c.env };
58
+ if (sm)
59
+ out.productionBrowserSourceMaps = true;
60
+ if (sm && 'upload' in sm && sm.upload) {
61
+ const { upload: _u, deleteAfterUpload, ...so } = sm;
62
+ const w = c.webpack;
63
+ out.webpack = (cfg, ctx) => {
64
+ const r = (w ? w(cfg, ctx) : cfg);
65
+ if (!ctx.dev && !ctx.isServer) {
66
+ (r.plugins ??= []).push({
67
+ apply(compiler) {
68
+ compiler.hooks.done.tapPromise('watchtower-sourcemaps', async () => {
69
+ try {
70
+ await uploadSourcemaps({ log: (l) => console.log(`[watchtower] ${l}`), ...so, release, keep: deleteAfterUpload === false });
71
+ }
72
+ catch (e) {
73
+ console.warn(`[watchtower] source map upload skipped: ${e.message}`);
74
+ }
75
+ });
76
+ },
77
+ });
78
+ }
79
+ return r;
80
+ };
81
+ }
82
+ return out;
83
+ };
13
84
  if (typeof config !== 'function')
14
85
  return apply(config);
15
86
  return async (...a) => apply(await config(...a));
@@ -23,6 +94,30 @@ function* maps(dir) {
23
94
  yield p;
24
95
  }
25
96
  }
97
+ /** A ustar archive of `[name, bytes]` (names up to 100 bytes). */
98
+ export function makeTar(files) {
99
+ const parts = [];
100
+ for (const [name, data] of files) {
101
+ const h = Buffer.alloc(512);
102
+ h.write(name, 0, 100, 'utf8');
103
+ h.write('0000644\0', 100);
104
+ h.write('0000000\0', 108);
105
+ h.write('0000000\0', 116);
106
+ h.write(`${data.length.toString(8).padStart(11, '0')}\0`, 124);
107
+ h.write('00000000000\0', 136);
108
+ h.write(' ', 148);
109
+ h.write('0', 156);
110
+ h.write('ustar\0', 257);
111
+ h.write('00', 263);
112
+ let sum = 0;
113
+ for (const b of h)
114
+ sum += b;
115
+ h.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148);
116
+ parts.push(h, data, Buffer.alloc((512 - (data.length % 512)) % 512));
117
+ }
118
+ parts.push(Buffer.alloc(1024));
119
+ return Buffer.concat(parts);
120
+ }
26
121
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27
122
  /** The client chunk (`_next/static/...`) a map belongs to: the sibling JS's `//# sourceMappingURL=` target, else the map's own `file` field. */
28
123
  function chunkFor(mapFile, name) {
@@ -41,8 +136,9 @@ function chunkFor(mapFile, name) {
41
136
  return undefined;
42
137
  }
43
138
  /**
44
- * Upload every `.map` under `dir` as `_next/static/<path>` for the release (8 at a time, 429/5xx retried with backoff
45
- * honoring Retry-After; a failed map does not stop the others), then delete them when none failed. Returns
139
+ * Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~120 MB
140
+ * batch (tar.gz plus manifest), falling back to single uploads (8 at a time) when the server has no bundle route.
141
+ * 429/5xx are retried with backoff honoring Retry-After; a failed map does not stop the others. The maps are deleted when none failed. Returns
46
142
  * `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
47
143
  * gzipped (`Content-Encoding: gzip`).
48
144
  */
@@ -89,38 +185,88 @@ export async function uploadSourcemaps(o = {}) {
89
185
  if (!rel.ok && rel.status !== 409)
90
186
  throw new Error(`watchtower POST /releases -> HTTP ${rel.status}${rel.status === 401 || rel.status === 403 ? ' (check WT_API_KEY scope ci:write)' : ''}`);
91
187
  let uploaded = 0, skipped = 0, failed = 0;
92
- let next = 0;
93
- const worker = async () => {
94
- for (let file = files[next++]; file !== undefined; file = files[next++]) {
95
- const name = `_next/static/${nodePath.relative(dir, file).split(nodePath.sep).join('/')}`;
96
- const q = { kind: 'sourcemap', name, release };
97
- const chunk = chunkFor(file, name);
98
- if (chunk)
99
- q.for = chunk;
100
- const id = ids.get(file);
101
- if (id)
102
- q.debug_id = id;
103
- try {
104
- const res = await send(`/artifacts?${new URLSearchParams(q)}`, {
105
- method: 'POST', headers: { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip' },
106
- body: new Uint8Array(zlib.gzipSync(fs.readFileSync(file))),
107
- }, 4);
108
- if (res.status === 200)
109
- skipped++;
110
- else if (res.ok)
111
- uploaded++;
112
- else {
113
- failed++;
114
- log(`failed ${name}: HTTP ${res.status}`);
115
- }
116
- }
117
- catch (e) {
188
+ const entries = files.map((file) => {
189
+ const name = `_next/static/${nodePath.relative(dir, file).split(nodePath.sep).join('/')}`;
190
+ return { file, name, chunk: chunkFor(file, name), id: ids.get(file) };
191
+ });
192
+ const single = async (e) => {
193
+ const q = { kind: 'sourcemap', name: e.name, release };
194
+ if (e.chunk)
195
+ q.for = e.chunk;
196
+ if (e.id)
197
+ q.debug_id = e.id;
198
+ try {
199
+ const res = await send(`/artifacts?${new URLSearchParams(q)}`, {
200
+ method: 'POST', headers: { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip' },
201
+ body: new Uint8Array(zlib.gzipSync(fs.readFileSync(e.file))),
202
+ }, 4);
203
+ if (res.status === 200)
204
+ skipped++;
205
+ else if (res.ok)
206
+ uploaded++;
207
+ else {
118
208
  failed++;
119
- log(`failed ${name}: ${e.message}`);
209
+ log(`failed ${e.name}: HTTP ${res.status}`);
120
210
  }
121
211
  }
212
+ catch (err) {
213
+ failed++;
214
+ log(`failed ${e.name}: ${err.message}`);
215
+ }
122
216
  };
123
- await Promise.all(Array.from({ length: Math.min(8, files.length) }, worker));
217
+ const concurrently = async (list) => {
218
+ let next = 0;
219
+ const worker = async () => {
220
+ for (let e = list[next++]; e !== undefined; e = list[next++])
221
+ await single(e);
222
+ };
223
+ await Promise.all(Array.from({ length: Math.min(8, list.length) }, worker));
224
+ };
225
+ // One request per batch (tar.gz + manifest). A server without the bundle route (or a request that
226
+ // never got through) falls back to concurrent single uploads for that batch.
227
+ const BATCH_BYTES = 120 * 1024 * 1024;
228
+ const batches = [];
229
+ let cur = [], curBytes = 0;
230
+ for (const e of entries) {
231
+ const size = fs.statSync(e.file).size;
232
+ if (cur.length && curBytes + size > BATCH_BYTES) {
233
+ batches.push(cur);
234
+ cur = [];
235
+ curBytes = 0;
236
+ }
237
+ cur.push(e);
238
+ curBytes += size;
239
+ }
240
+ if (cur.length)
241
+ batches.push(cur);
242
+ for (const batch of batches) {
243
+ let handled = false;
244
+ try {
245
+ const manifest = { files: batch.map((e, i) => ({ path: `m${i}.map`, name: e.name, ...(e.chunk ? { for: e.chunk } : {}), ...(e.id ? { debug_id: e.id } : {}) })) };
246
+ const tar = makeTar([['manifest.json', Buffer.from(JSON.stringify(manifest))], ...batch.map((e, i) => [`m${i}.map`, fs.readFileSync(e.file)])]);
247
+ const res = await send(`/artifacts/bundle?${new URLSearchParams({ release })}`, {
248
+ method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: new Uint8Array(zlib.gzipSync(tar)),
249
+ }, 4);
250
+ const r = res.ok ? (await res.json().catch(() => ({}))) : {};
251
+ if (typeof r.uploaded === 'number') { // anything else is not our bundle route: fall back
252
+ uploaded += r.uploaded;
253
+ skipped += r.skipped || 0;
254
+ failed += r.failed || 0;
255
+ for (const e of r.errors || [])
256
+ log(`failed ${e.name}: ${e.reason}`);
257
+ handled = true;
258
+ }
259
+ else if (res.status === 401 || res.status === 403) {
260
+ throw new Error(`watchtower POST /artifacts/bundle -> HTTP ${res.status} (check WT_API_KEY scope ci:write)`);
261
+ }
262
+ }
263
+ catch (e) {
264
+ if (e.message.startsWith('watchtower ') || e.message.startsWith('cannot reach'))
265
+ throw e;
266
+ }
267
+ if (!handled)
268
+ await concurrently(batch);
269
+ }
124
270
  if (!o.keep && failed === 0)
125
271
  for (const file of files)
126
272
  fs.rmSync(file);
@@ -5,9 +5,14 @@ export interface TunnelOptions {
5
5
  basePath?: string;
6
6
  /** Request body cap in bytes; default 1 MiB (over it: 413). */
7
7
  maxBodyBytes?: number;
8
+ /**
9
+ * Only forward beacons whose publishable key is one of these (`?k=` or a `wtp_` bearer); others get 403. Stops
10
+ * a third party from using your tunnel as a relay for another project's key.
11
+ */
12
+ allowKey?: string | string[];
8
13
  fetch?: typeof fetch;
9
14
  }
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. */
15
+ /** 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, plus the visitor's `Origin`/`Referer` (the edge checks the Origin against the key's allowed origins); cookies and other headers are not. */
11
16
  export declare function tunnelHandler(o: TunnelOptions): {
12
17
  GET: (r: Request) => Promise<Response>;
13
18
  POST: (r: Request) => Promise<Response>;
@@ -3,12 +3,15 @@
3
3
  // Browser SDK: init({ endpoint: '/api/wt', publishableKey: 'wtp_...' }).
4
4
  // only what the browser SDK calls: /v1/rum/*, /v1/replay/<session>/chunks /v1/logs and /v1/traces
5
5
  const ALLOWED = /^\/v1\/(rum\/[A-Za-z0-9/_-]+|replay\/[A-Za-z0-9_-]+\/chunks|logs|traces)$/;
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. */
6
+ // `origin` / `referer`: the edge refuses a browser key without an Origin on the key's allowed origins (403 origin_not_allowed),
7
+ // so the tunnel passes through the visitor's own Origin: add your site's origin to the key's allowed origins.
8
+ const FORWARD = ['content-type', 'content-encoding', 'user-agent', 'origin', 'referer', 'x-wt-sdk', 'x-wt-mask'];
9
+ /** 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, plus the visitor's `Origin`/`Referer` (the edge checks the Origin against the key's allowed origins); cookies and other headers are not. */
8
10
  export function tunnelHandler(o) {
9
11
  const base = (o.basePath ?? '/api/wt').replace(/\/+$/, '');
10
12
  const max = o.maxBodyBytes ?? 1024 * 1024;
11
13
  const edge = o.endpoint.replace(/\/+$/, '');
14
+ const allow = o.allowKey === undefined ? [] : [].concat(o.allowKey);
12
15
  const send = o.fetch ?? fetch;
13
16
  const handle = async (req) => {
14
17
  const url = new URL(req.url);
@@ -21,10 +24,18 @@ export function tunnelHandler(o) {
21
24
  if (v)
22
25
  headers[h] = v;
23
26
  }
27
+ if (!headers.origin && headers.referer) { // same-origin GETs carry no Origin: use the Referer's
28
+ try {
29
+ headers.origin = new URL(headers.referer).origin;
30
+ }
31
+ catch { /* not a URL: forward as is */ }
32
+ }
24
33
  const bearer = /^Bearer (wtp_\S+)$/.exec(req.headers.get('authorization') ?? '');
25
34
  if (bearer)
26
35
  headers.authorization = `Bearer ${bearer[1]}`;
27
36
  const k = url.searchParams.get('k');
37
+ if (allow.length && ![k, bearer?.[1]].some((x) => x && allow.includes(x)))
38
+ return new Response('forbidden', { status: 403 });
28
39
  let body;
29
40
  if (req.method === 'POST') {
30
41
  if (Number(req.headers.get('content-length') ?? 0) > max)
@@ -9,4 +9,6 @@ export { querySummary };
9
9
  * failure. Works for ESM and CJS; returns an unsubscribe function (a no-op when this Node has no
10
10
  * tracing channels).
11
11
  */
12
+ /** Major version of the app's installed `postgres`, or undefined when absent or unreadable. */
13
+ export declare function postgresMajor(from?: string): number | undefined;
12
14
  export declare function instrumentPostgres(opts?: DbOptions): () => void;
@@ -1,8 +1,26 @@
1
1
  import * as dc from 'node:diagnostics_channel';
2
- import { context, SpanStatusCode } from '@opentelemetry/api';
2
+ import { readFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join } from 'node:path';
5
+ import { context, diag, SpanStatusCode } from '@opentelemetry/api';
6
+ import { load } from '../load.js';
3
7
  import { querySummary } from '../sql.js';
4
8
  import { startDbSpan } from './db.js';
5
9
  export { querySummary };
10
+ let warned = false;
11
+ // Warn once, and only when postgres is installed (load is real, but cheap: cached): without tracingChannel nothing would ever be recorded.
12
+ function warnOnce() {
13
+ if (warned)
14
+ return;
15
+ warned = true;
16
+ try {
17
+ load('postgres');
18
+ }
19
+ catch {
20
+ return;
21
+ }
22
+ diag.warn('watchtower: instrumentPostgres() is a no-op: this Node has no diagnostics_channel.tracingChannel; postgres@>=4 on a Node that provides it is required');
23
+ }
6
24
  /**
7
25
  * postgres.js has no OTel instrumentation; since 4.0 it publishes each query on the
8
26
  * `postgres:query` diagnostics tracing channel. This turns those into CLIENT spans (child of the
@@ -11,9 +29,32 @@ export { querySummary };
11
29
  * failure. Works for ESM and CJS; returns an unsubscribe function (a no-op when this Node has no
12
30
  * tracing channels).
13
31
  */
32
+ /** Major version of the app's installed `postgres`, or undefined when absent or unreadable. */
33
+ export function postgresMajor(from = process.cwd()) {
34
+ try {
35
+ // `postgres/package.json` is not exported, so walk up from the resolved entry.
36
+ let dir = dirname(createRequire(join(from, 'noop.js')).resolve('postgres'));
37
+ for (let i = 0; i < 6; i++, dir = dirname(dir)) {
38
+ try {
39
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
40
+ if (pkg.name === 'postgres')
41
+ return Number.parseInt(pkg.version ?? '', 10);
42
+ }
43
+ catch { /* keep walking */ }
44
+ }
45
+ }
46
+ catch { /* not installed */ }
47
+ return undefined;
48
+ }
14
49
  export function instrumentPostgres(opts) {
15
- if (typeof dc.tracingChannel !== 'function')
50
+ if (typeof dc.tracingChannel !== 'function') {
51
+ warnOnce();
16
52
  return () => { };
53
+ }
54
+ const major = postgresMajor();
55
+ if (major !== undefined && major < 4) {
56
+ diag.warn(`watchtower: instrumentPostgres() records nothing with postgres@${major}: the postgres:query channel exists only in postgres@>=4`);
57
+ }
17
58
  const ch = dc.tracingChannel('postgres:query');
18
59
  const spans = new WeakMap();
19
60
  const handlers = {
@@ -0,0 +1,97 @@
1
+ interface ActivityInfo {
2
+ activityType?: string;
3
+ activityId?: string;
4
+ attempt?: number;
5
+ taskQueue?: string;
6
+ workflowType?: string;
7
+ workflowExecution?: {
8
+ workflowId?: string;
9
+ runId?: string;
10
+ };
11
+ retryPolicy?: {
12
+ maximumAttempts?: number;
13
+ };
14
+ }
15
+ interface ActivityCtx {
16
+ info?: ActivityInfo;
17
+ }
18
+ type Next = (input: unknown) => Promise<unknown>;
19
+ export interface TemporalInterceptorOptions {
20
+ /** Retry cap when the activity info does not carry the retry policy; a failure on this attempt (or a non-retryable one) is captured. */
21
+ maxAttempts?: number;
22
+ }
23
+ /** Worker options fragment: `Worker.create({ ..., interceptors: temporalInterceptors() })`. Spans for each activity attempt; the exception is captured on the final attempt only. */
24
+ export declare function temporalInterceptors(o?: TemporalInterceptorOptions): {
25
+ activity: ((ctx: ActivityCtx) => {
26
+ inbound: {
27
+ execute(input: unknown, next: Next): Promise<unknown>;
28
+ };
29
+ })[];
30
+ };
31
+ interface Range {
32
+ start?: number;
33
+ end?: number;
34
+ step?: number;
35
+ }
36
+ type Calendar = Partial<Record<'minute' | 'hour' | 'dayOfMonth' | 'month' | 'dayOfWeek', Range[]>>;
37
+ interface WfRef {
38
+ workflowId?: string;
39
+ firstExecutionRunId?: string;
40
+ runId?: string;
41
+ }
42
+ interface ActionLike {
43
+ takenAt?: Date | string;
44
+ workflow?: WfRef;
45
+ action?: {
46
+ workflow?: WfRef;
47
+ };
48
+ }
49
+ interface Described {
50
+ spec?: {
51
+ cronExpressions?: string[];
52
+ calendars?: Calendar[];
53
+ timezoneName?: string;
54
+ };
55
+ info?: {
56
+ recentActions?: ActionLike[];
57
+ runningActions?: ActionLike[];
58
+ };
59
+ }
60
+ export interface TemporalClientLike {
61
+ options?: {
62
+ namespace?: string;
63
+ };
64
+ schedule: {
65
+ list(): AsyncIterable<{
66
+ scheduleId: string;
67
+ }>;
68
+ getHandle(id: string): {
69
+ describe(): Promise<Described>;
70
+ };
71
+ };
72
+ workflow: {
73
+ getHandle(id: string, runId?: string): {
74
+ describe(): Promise<{
75
+ status?: {
76
+ name?: string;
77
+ };
78
+ startTime?: Date;
79
+ closeTime?: Date;
80
+ }>;
81
+ };
82
+ };
83
+ }
84
+ export interface WatchSchedulesOptions {
85
+ /** Poll period; default 60_000. */
86
+ interval?: number;
87
+ /** Only watch when the client's namespace is one of these (a Temporal client is bound to one namespace). */
88
+ namespaces?: string[];
89
+ }
90
+ /** Crontab (5 fields) for a Temporal schedule spec, or undefined when it has none or is not expressible (intervals, several calendars). */
91
+ export declare function scheduleCron(spec: Described['spec']): {
92
+ cron: string;
93
+ timezone?: string;
94
+ } | undefined;
95
+ /** Poll Temporal Schedules and send a check-in per action (slug `temporal-<scheduleId>`). Returns a stop function. */
96
+ export declare function watchTemporalSchedules(client: TemporalClientLike, o?: WatchSchedulesOptions): () => void;
97
+ export {};