@watchtowerobservability/node 0.0.0-stage → 0.3.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 (181) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +304 -2
  3. package/dist/cjs/appsec.d.ts +95 -0
  4. package/dist/cjs/appsec.js +206 -0
  5. package/dist/cjs/buffer.d.ts +49 -0
  6. package/dist/cjs/buffer.js +134 -0
  7. package/dist/cjs/errors.d.ts +17 -0
  8. package/dist/cjs/errors.js +55 -0
  9. package/dist/cjs/index.d.ts +123 -0
  10. package/dist/cjs/index.js +315 -0
  11. package/dist/cjs/integrations/amqp.d.ts +13 -0
  12. package/dist/cjs/integrations/amqp.js +96 -0
  13. package/dist/cjs/integrations/azure-functions.d.ts +18 -0
  14. package/dist/cjs/integrations/azure-functions.js +97 -0
  15. package/dist/cjs/integrations/bullmq.d.ts +19 -0
  16. package/dist/cjs/integrations/bullmq.js +83 -0
  17. package/dist/cjs/integrations/cache.d.ts +13 -0
  18. package/dist/cjs/integrations/cache.js +51 -0
  19. package/dist/cjs/integrations/db.d.ts +62 -0
  20. package/dist/cjs/integrations/db.js +288 -0
  21. package/dist/cjs/integrations/duckdb.d.ts +22 -0
  22. package/dist/cjs/integrations/duckdb.js +66 -0
  23. package/dist/cjs/integrations/express.d.ts +25 -0
  24. package/dist/cjs/integrations/express.js +58 -0
  25. package/dist/cjs/integrations/fastify.d.ts +6 -0
  26. package/dist/cjs/integrations/fastify.js +44 -0
  27. package/dist/cjs/integrations/genai-agents.d.ts +36 -0
  28. package/dist/cjs/integrations/genai-agents.js +124 -0
  29. package/dist/cjs/integrations/genai-stream.d.ts +19 -0
  30. package/dist/cjs/integrations/genai-stream.js +135 -0
  31. package/dist/cjs/integrations/genai.d.ts +18 -0
  32. package/dist/cjs/integrations/genai.js +150 -0
  33. package/dist/cjs/integrations/graphile-worker.d.ts +22 -0
  34. package/dist/cjs/integrations/graphile-worker.js +50 -0
  35. package/dist/cjs/integrations/koa.d.ts +19 -0
  36. package/dist/cjs/integrations/koa.js +34 -0
  37. package/dist/cjs/integrations/lambda.d.ts +11 -0
  38. package/dist/cjs/integrations/lambda.js +68 -0
  39. package/dist/cjs/integrations/level.d.ts +18 -0
  40. package/dist/cjs/integrations/level.js +71 -0
  41. package/dist/cjs/integrations/lmdb.d.ts +26 -0
  42. package/dist/cjs/integrations/lmdb.js +78 -0
  43. package/dist/cjs/integrations/logs.d.ts +10 -0
  44. package/dist/cjs/integrations/logs.js +77 -0
  45. package/dist/cjs/integrations/messaging.d.ts +17 -0
  46. package/dist/cjs/integrations/messaging.js +73 -0
  47. package/dist/cjs/integrations/mqtt.d.ts +7 -0
  48. package/dist/cjs/integrations/mqtt.js +41 -0
  49. package/dist/cjs/integrations/nats.d.ts +17 -0
  50. package/dist/cjs/integrations/nats.js +73 -0
  51. package/dist/cjs/integrations/nestjs.d.ts +16 -0
  52. package/dist/cjs/integrations/nestjs.js +30 -0
  53. package/dist/cjs/integrations/next.d.ts +11 -0
  54. package/dist/cjs/integrations/next.js +59 -0
  55. package/dist/cjs/integrations/orm.d.ts +47 -0
  56. package/dist/cjs/integrations/orm.js +93 -0
  57. package/dist/cjs/integrations/pg-boss.d.ts +8 -0
  58. package/dist/cjs/integrations/pg-boss.js +63 -0
  59. package/dist/cjs/integrations/pools.d.ts +41 -0
  60. package/dist/cjs/integrations/pools.js +94 -0
  61. package/dist/cjs/integrations/postgres.d.ts +12 -0
  62. package/dist/cjs/integrations/postgres.js +92 -0
  63. package/dist/cjs/integrations/prisma.d.ts +3 -0
  64. package/dist/cjs/integrations/prisma.js +33 -0
  65. package/dist/cjs/integrations/sqlite.d.ts +36 -0
  66. package/dist/cjs/integrations/sqlite.js +125 -0
  67. package/dist/cjs/integrations/util.d.ts +9 -0
  68. package/dist/cjs/integrations/util.js +37 -0
  69. package/dist/cjs/jest.d.ts +21 -0
  70. package/dist/cjs/jest.js +45 -0
  71. package/dist/cjs/load.d.ts +1 -0
  72. package/dist/cjs/load.js +11 -0
  73. package/dist/cjs/metrics.d.ts +10 -0
  74. package/dist/cjs/metrics.js +81 -0
  75. package/dist/cjs/package.json +1 -0
  76. package/dist/cjs/payload.d.ts +42 -0
  77. package/dist/cjs/payload.js +145 -0
  78. package/dist/cjs/pprof.d.ts +6 -0
  79. package/dist/cjs/pprof.js +88 -0
  80. package/dist/cjs/probes.d.ts +97 -0
  81. package/dist/cjs/probes.js +422 -0
  82. package/dist/cjs/profiling.d.ts +84 -0
  83. package/dist/cjs/profiling.js +263 -0
  84. package/dist/cjs/reporter-core.d.ts +32 -0
  85. package/dist/cjs/reporter-core.js +102 -0
  86. package/dist/cjs/sql.d.ts +19 -0
  87. package/dist/cjs/sql.js +332 -0
  88. package/dist/cjs/test-plan.d.ts +102 -0
  89. package/dist/cjs/test-plan.js +352 -0
  90. package/dist/cjs/vitest.d.ts +27 -0
  91. package/dist/cjs/vitest.js +52 -0
  92. package/dist/esm/appsec.d.ts +95 -0
  93. package/dist/esm/appsec.js +193 -0
  94. package/dist/esm/buffer.d.ts +49 -0
  95. package/dist/esm/buffer.js +92 -0
  96. package/dist/esm/errors.d.ts +17 -0
  97. package/dist/esm/errors.js +50 -0
  98. package/dist/esm/index.d.ts +123 -0
  99. package/dist/esm/index.js +264 -0
  100. package/dist/esm/integrations/amqp.d.ts +13 -0
  101. package/dist/esm/integrations/amqp.js +92 -0
  102. package/dist/esm/integrations/azure-functions.d.ts +18 -0
  103. package/dist/esm/integrations/azure-functions.js +60 -0
  104. package/dist/esm/integrations/bullmq.d.ts +19 -0
  105. package/dist/esm/integrations/bullmq.js +79 -0
  106. package/dist/esm/integrations/cache.d.ts +13 -0
  107. package/dist/esm/integrations/cache.js +46 -0
  108. package/dist/esm/integrations/db.d.ts +62 -0
  109. package/dist/esm/integrations/db.js +239 -0
  110. package/dist/esm/integrations/duckdb.d.ts +22 -0
  111. package/dist/esm/integrations/duckdb.js +29 -0
  112. package/dist/esm/integrations/express.d.ts +25 -0
  113. package/dist/esm/integrations/express.js +54 -0
  114. package/dist/esm/integrations/fastify.d.ts +6 -0
  115. package/dist/esm/integrations/fastify.js +41 -0
  116. package/dist/esm/integrations/genai-agents.d.ts +36 -0
  117. package/dist/esm/integrations/genai-agents.js +118 -0
  118. package/dist/esm/integrations/genai-stream.d.ts +19 -0
  119. package/dist/esm/integrations/genai-stream.js +130 -0
  120. package/dist/esm/integrations/genai.d.ts +18 -0
  121. package/dist/esm/integrations/genai.js +138 -0
  122. package/dist/esm/integrations/graphile-worker.d.ts +22 -0
  123. package/dist/esm/integrations/graphile-worker.js +46 -0
  124. package/dist/esm/integrations/koa.d.ts +19 -0
  125. package/dist/esm/integrations/koa.js +31 -0
  126. package/dist/esm/integrations/lambda.d.ts +11 -0
  127. package/dist/esm/integrations/lambda.js +32 -0
  128. package/dist/esm/integrations/level.d.ts +18 -0
  129. package/dist/esm/integrations/level.js +35 -0
  130. package/dist/esm/integrations/lmdb.d.ts +26 -0
  131. package/dist/esm/integrations/lmdb.js +42 -0
  132. package/dist/esm/integrations/logs.d.ts +10 -0
  133. package/dist/esm/integrations/logs.js +40 -0
  134. package/dist/esm/integrations/messaging.d.ts +17 -0
  135. package/dist/esm/integrations/messaging.js +64 -0
  136. package/dist/esm/integrations/mqtt.d.ts +7 -0
  137. package/dist/esm/integrations/mqtt.js +38 -0
  138. package/dist/esm/integrations/nats.d.ts +17 -0
  139. package/dist/esm/integrations/nats.js +70 -0
  140. package/dist/esm/integrations/nestjs.d.ts +16 -0
  141. package/dist/esm/integrations/nestjs.js +26 -0
  142. package/dist/esm/integrations/next.d.ts +11 -0
  143. package/dist/esm/integrations/next.js +22 -0
  144. package/dist/esm/integrations/orm.d.ts +47 -0
  145. package/dist/esm/integrations/orm.js +86 -0
  146. package/dist/esm/integrations/pg-boss.d.ts +8 -0
  147. package/dist/esm/integrations/pg-boss.js +60 -0
  148. package/dist/esm/integrations/pools.d.ts +41 -0
  149. package/dist/esm/integrations/pools.js +89 -0
  150. package/dist/esm/integrations/postgres.d.ts +12 -0
  151. package/dist/esm/integrations/postgres.js +55 -0
  152. package/dist/esm/integrations/prisma.d.ts +3 -0
  153. package/dist/esm/integrations/prisma.js +30 -0
  154. package/dist/esm/integrations/sqlite.d.ts +36 -0
  155. package/dist/esm/integrations/sqlite.js +84 -0
  156. package/dist/esm/integrations/util.d.ts +9 -0
  157. package/dist/esm/integrations/util.js +32 -0
  158. package/dist/esm/jest.d.ts +21 -0
  159. package/dist/esm/jest.js +41 -0
  160. package/dist/esm/load.d.ts +1 -0
  161. package/dist/esm/load.js +5 -0
  162. package/dist/esm/metrics.d.ts +10 -0
  163. package/dist/esm/metrics.js +44 -0
  164. package/dist/esm/package.json +1 -0
  165. package/dist/esm/payload.d.ts +42 -0
  166. package/dist/esm/payload.js +131 -0
  167. package/dist/esm/pprof.d.ts +6 -0
  168. package/dist/esm/pprof.js +85 -0
  169. package/dist/esm/probes.d.ts +97 -0
  170. package/dist/esm/probes.js +412 -0
  171. package/dist/esm/profiling.d.ts +84 -0
  172. package/dist/esm/profiling.js +251 -0
  173. package/dist/esm/reporter-core.d.ts +32 -0
  174. package/dist/esm/reporter-core.js +63 -0
  175. package/dist/esm/sql.d.ts +19 -0
  176. package/dist/esm/sql.js +324 -0
  177. package/dist/esm/test-plan.d.ts +102 -0
  178. package/dist/esm/test-plan.js +336 -0
  179. package/dist/esm/vitest.d.ts +27 -0
  180. package/dist/esm/vitest.js +48 -0
  181. package/package.json +379 -4
@@ -0,0 +1,206 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isUserBlocked = exports.DENYLIST = void 0;
4
+ exports.setRuleset = setRuleset;
5
+ exports.inspect = inspect;
6
+ exports.clientIp = clientIp;
7
+ exports.fromNode = fromNode;
8
+ exports.annotate = annotate;
9
+ exports.handleRequest = handleRequest;
10
+ exports.appsecMiddleware = appsecMiddleware;
11
+ exports.trackLogin = trackLogin;
12
+ exports.startAppsec = startAppsec;
13
+ // App and API Protection in-app WAF (W52). `startAppsec()` polls the project's ruleset from the
14
+ // edge (`GET /v1/appsec/ruleset`, an ingestion key with scope `probes:read`, ETag, every `poll_s`):
15
+ // mode, enabled pattern rules and the denylist. `appsecMiddleware()` (Express, Connect, any
16
+ // `(req, res, next)` stack) or `handleRequest(req, res)` (plain `http`, Fastify `onRequest`, Koa)
17
+ // inspects each request before the handler: path, query, User-Agent, other header values and an
18
+ // already parsed body, percent-decoded once, against the same rules the worker runs over stored
19
+ // spans. A match is recorded on the active server span (`appsec.event`, `appsec.rule_id`,
20
+ // `appsec.category`, `appsec.blocked`); in `block` mode, and for denylisted IPs or users in any
21
+ // mode, the request is answered with 403 problem+json and the handler never runs.
22
+ // Nothing is fetched or inspected until `startAppsec` is called; with no ruleset yet every
23
+ // request passes. Rules are matched case-insensitively; a rule that does not compile is skipped.
24
+ const api_1 = require("@opentelemetry/api");
25
+ /** Rule id recorded for denylist blocks (the worker reports them as their own signal). */
26
+ exports.DENYLIST = 'denylist';
27
+ const BODY_MAX = 64 * 1024;
28
+ let mode = 'monitor';
29
+ let compiled = [];
30
+ let denyIp = new Map();
31
+ let denyUser = new Map();
32
+ const expiryMap = (list) => new Map((list || []).map((e) => [e.value, e.expires_at ? e.expires_at * 1000 : Infinity]));
33
+ /** Replace the active ruleset (what the poller calls; tests may call it directly). */
34
+ function setRuleset(r) {
35
+ mode = r?.mode === 'block' ? 'block' : 'monitor';
36
+ compiled = [];
37
+ for (const rule of r?.rules || []) {
38
+ try {
39
+ compiled.push({ rule, re: new RegExp(rule.pattern, 'i') });
40
+ }
41
+ catch {
42
+ // not portable to JavaScript: skipped here, the worker still evaluates it
43
+ }
44
+ }
45
+ denyIp = expiryMap(r?.denylist?.ip);
46
+ denyUser = expiryMap(r?.denylist?.user);
47
+ }
48
+ const listed = (m, v, now) => !!v && (m.get(v) ?? 0) > now;
49
+ /** Whether `id` is on the user denylist (call after authentication to refuse a listed user). */
50
+ const isUserBlocked = (id, now = Date.now()) => listed(denyUser, id, now);
51
+ exports.isUserBlocked = isUserBlocked;
52
+ /** Judge one request. Denylisted callers are blocked in either mode. */
53
+ function inspect(req, now = Date.now()) {
54
+ if (listed(denyIp, req.ip, now) || listed(denyUser, req.user, now)) {
55
+ return { action: 'block', rule_id: exports.DENYLIST, category: 'abuse' };
56
+ }
57
+ for (const { rule, re } of compiled) {
58
+ for (const f of rule.fields) {
59
+ const v = req[f];
60
+ if (!v)
61
+ continue;
62
+ const m = re.exec(v);
63
+ if (m) {
64
+ return { action: mode === 'block' ? 'block' : 'monitor', rule_id: rule.id, category: rule.category, match: m[0].slice(0, 200) };
65
+ }
66
+ }
67
+ }
68
+ return { action: 'allow' };
69
+ }
70
+ const decode = (s, form = false) => {
71
+ const x = form ? s.replace(/\+/g, ' ') : s;
72
+ try {
73
+ return decodeURIComponent(x);
74
+ }
75
+ catch {
76
+ return x;
77
+ }
78
+ };
79
+ const first = (v) => (Array.isArray(v) ? v[0] : v);
80
+ /** Client IP: first `X-Forwarded-For` hop, else `X-Real-IP`, else the socket peer.
81
+ * shortcut: trusts the forwarding headers; run behind a proxy that overwrites them. */
82
+ function clientIp(req) {
83
+ const xff = first(req.headers?.['x-forwarded-for']);
84
+ if (xff)
85
+ return xff.split(',')[0].trim();
86
+ return first(req.headers?.['x-real-ip']) || req.socket?.remoteAddress?.replace(/^::ffff:/, '');
87
+ }
88
+ /** Decode a Node request into the inspector's fields. */
89
+ function fromNode(req, user) {
90
+ const url = req.originalUrl || req.url || '/';
91
+ const q = url.indexOf('?');
92
+ const headers = Object.entries(req.headers || {})
93
+ .filter(([k]) => k !== 'user-agent')
94
+ .map(([, v]) => (Array.isArray(v) ? v.join(', ') : v || ''))
95
+ .join('\n');
96
+ let body;
97
+ if (typeof req.body === 'string')
98
+ body = req.body.slice(0, BODY_MAX);
99
+ else if (req.body && typeof req.body === 'object') {
100
+ try {
101
+ body = JSON.stringify(req.body).slice(0, BODY_MAX);
102
+ }
103
+ catch {
104
+ body = undefined;
105
+ }
106
+ }
107
+ return {
108
+ path: decode(q < 0 ? url : url.slice(0, q)),
109
+ query: q < 0 ? '' : decode(url.slice(q + 1), true),
110
+ user_agent: first(req.headers?.['user-agent']) || '',
111
+ headers,
112
+ body,
113
+ ip: clientIp(req),
114
+ user,
115
+ };
116
+ }
117
+ /** Record a decision on the active span. */
118
+ function annotate(d, ip) {
119
+ const span = api_1.trace.getActiveSpan();
120
+ if (!span)
121
+ return;
122
+ if (ip)
123
+ span.setAttribute('appsec.client_ip', ip);
124
+ if (d.action === 'allow')
125
+ return;
126
+ span.setAttributes({
127
+ 'appsec.event': true,
128
+ 'appsec.rule_id': d.rule_id || '',
129
+ 'appsec.category': d.category || '',
130
+ 'appsec.blocked': d.action === 'block',
131
+ });
132
+ }
133
+ const PROBLEM = JSON.stringify({
134
+ type: 'about:blank',
135
+ title: 'Forbidden',
136
+ status: 403,
137
+ detail: 'Request blocked by Watchtower App and API Protection',
138
+ });
139
+ /** Inspect and, when blocked, answer 403. Returns true when the request was answered. */
140
+ function handleRequest(req, res, user) {
141
+ if (!compiled.length && !denyIp.size && !denyUser.size)
142
+ return false;
143
+ const r = fromNode(req, user);
144
+ const d = inspect(r);
145
+ annotate(d, r.ip);
146
+ if (d.action !== 'block')
147
+ return false;
148
+ res.statusCode = 403;
149
+ res.setHeader?.('content-type', 'application/problem+json');
150
+ res.end(PROBLEM);
151
+ return true;
152
+ }
153
+ /** Connect-style middleware; `user(req)` names the caller when the app already knows it. */
154
+ function appsecMiddleware(o = {}) {
155
+ return (req, res, next) => {
156
+ if (!handleRequest(req, res, o.user?.(req)))
157
+ next();
158
+ };
159
+ }
160
+ /** Mark the current request as a login attempt; failed ones feed the account-takeover rules. */
161
+ function trackLogin(login, success) {
162
+ const span = api_1.trace.getActiveSpan();
163
+ span?.setAttributes({ 'appsec.login': login, 'appsec.login.success': success });
164
+ if (success)
165
+ span?.setAttribute('appsec.auth', true);
166
+ }
167
+ /** Fetch the ruleset now and keep polling; `stop()` ends the polling. */
168
+ function startAppsec(o = {}) {
169
+ const env = process.env;
170
+ const base = (o.apiUrl || env.WT_API_URL || 'https://api.watchtower.dev').replace(/\/$/, '');
171
+ const key = o.key || env.WT_INGEST_KEY || '';
172
+ const service = o.service || env.WT_SERVICE || env.OTEL_SERVICE_NAME || 'unknown';
173
+ const f = o.fetch || globalThis.fetch;
174
+ let etag = '';
175
+ let timer;
176
+ let stopped = false;
177
+ let pollS = 30;
178
+ const poll = async () => {
179
+ try {
180
+ const res = await f(`${base}/v1/appsec/ruleset?service=${encodeURIComponent(service)}`, {
181
+ headers: { Authorization: `Bearer ${key}`, ...(etag ? { 'If-None-Match': etag } : {}) },
182
+ });
183
+ if (res.status === 200) {
184
+ const body = (await res.json());
185
+ setRuleset(body);
186
+ etag = res.headers.get('etag') || '';
187
+ pollS = Math.max(10, body.poll_s || 30);
188
+ }
189
+ }
190
+ catch {
191
+ // keep the last ruleset; try again on the next poll
192
+ }
193
+ if (!stopped) {
194
+ timer = setTimeout(() => void poll(), pollS * 1000);
195
+ timer.unref?.();
196
+ }
197
+ };
198
+ return {
199
+ ready: poll(),
200
+ stop() {
201
+ stopped = true;
202
+ if (timer)
203
+ clearTimeout(timer);
204
+ },
205
+ };
206
+ }
@@ -0,0 +1,49 @@
1
+ import type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';
2
+ import type { LogRecordExporter, ReadableLogRecord } from '@opentelemetry/sdk-logs';
3
+ import { AggregationTemporality } from '@opentelemetry/sdk-metrics';
4
+ import type { InstrumentType, PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics';
5
+ type Done = Parameters<SpanExporter['export']>[1];
6
+ /** What the spool wraps: a span, log record or metric exporter; `B` is one export batch. */
7
+ export interface BatchExporter<B> {
8
+ export(batch: B, done: Done): void;
9
+ shutdown(): Promise<void>;
10
+ forceFlush?(): Promise<void>;
11
+ }
12
+ export interface SpoolOptions<B = ReadableSpan[]> {
13
+ maxFiles?: number;
14
+ encode?: (batch: B) => Uint8Array;
15
+ }
16
+ /** OTLP/JSON encoders for the three signals. */
17
+ export declare const encodeSpans: (spans: ReadableSpan[]) => Uint8Array;
18
+ export declare const encodeLogs: (logs: ReadableLogRecord[]) => Uint8Array;
19
+ export declare const encodeMetrics: (rm: ResourceMetrics) => Uint8Array;
20
+ export declare class SpoolExporter<B = ReadableSpan[]> implements BatchExporter<B> {
21
+ private readonly inner;
22
+ private readonly dir;
23
+ private readonly url;
24
+ private readonly headers;
25
+ private readonly fetch;
26
+ private readonly maxFiles;
27
+ private readonly encode;
28
+ constructor(inner: BatchExporter<B>, dir: string, url: string, headers: Record<string, string>, fetch: typeof globalThis.fetch, opts?: SpoolOptions<B>);
29
+ private _files;
30
+ replay(): Promise<void>;
31
+ export(batch: B, done: Done): void;
32
+ private _spool;
33
+ shutdown(): Promise<void>;
34
+ forceFlush(): Promise<void>;
35
+ }
36
+ /** A spool for log records: same directory rules, `/v1/logs` replay. */
37
+ export declare const spoolLogs: (inner: LogRecordExporter, dir: string, url: string, headers: Record<string, string>, fetch: typeof globalThis.fetch, opts?: {
38
+ maxFiles?: number;
39
+ }) => SpoolExporter<ReadableLogRecord[]>;
40
+ /** A spool for metrics (`/v1/metrics` replay); the reader still asks the real exporter for temporality. */
41
+ export declare class MetricSpool extends SpoolExporter<ResourceMetrics> implements PushMetricExporter {
42
+ private readonly metricInner;
43
+ constructor(metricInner: PushMetricExporter, dir: string, url: string, headers: Record<string, string>, fetch: typeof globalThis.fetch, opts?: {
44
+ maxFiles?: number;
45
+ });
46
+ selectAggregationTemporality(t: InstrumentType): AggregationTemporality;
47
+ forceFlush(): Promise<void>;
48
+ }
49
+ export {};
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.MetricSpool = exports.spoolLogs = exports.SpoolExporter = exports.encodeMetrics = exports.encodeLogs = exports.encodeSpans = void 0;
37
+ // Offline buffer: failed OTLP batches (spans, log records or metrics) are spooled to disk, at most
38
+ // `maxFiles` batches per signal directory (oldest dropped), and replayed oldest first before the
39
+ // next export, so they go out as soon as the endpoint is reachable again.
40
+ const fs = __importStar(require("node:fs"));
41
+ const path = __importStar(require("node:path"));
42
+ const crypto = __importStar(require("node:crypto"));
43
+ const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
44
+ const otlp_transformer_1 = require("@opentelemetry/otlp-transformer");
45
+ /** OTLP/JSON encoders for the three signals. */
46
+ const encodeSpans = (spans) => Buffer.from(otlp_transformer_1.JsonTraceSerializer.serializeRequest(spans));
47
+ exports.encodeSpans = encodeSpans;
48
+ const encodeLogs = (logs) => Buffer.from(otlp_transformer_1.JsonLogsSerializer.serializeRequest(logs));
49
+ exports.encodeLogs = encodeLogs;
50
+ const encodeMetrics = (rm) => Buffer.from(otlp_transformer_1.JsonMetricsSerializer.serializeRequest(rm));
51
+ exports.encodeMetrics = encodeMetrics;
52
+ class SpoolExporter {
53
+ inner;
54
+ dir;
55
+ url;
56
+ headers;
57
+ fetch;
58
+ maxFiles;
59
+ encode;
60
+ constructor(inner, dir, url, headers, fetch, opts) {
61
+ this.inner = inner;
62
+ this.dir = dir;
63
+ this.url = url;
64
+ this.headers = headers;
65
+ this.fetch = fetch;
66
+ this.maxFiles = (opts && opts.maxFiles) || 500;
67
+ this.encode = (opts && opts.encode) || exports.encodeSpans;
68
+ fs.mkdirSync(dir, { recursive: true });
69
+ }
70
+ _files() {
71
+ return fs.readdirSync(this.dir)
72
+ .map((n) => ({ n, t: fs.statSync(path.join(this.dir, n)).mtimeMs }))
73
+ .sort((a, b) => a.t - b.t || a.n.localeCompare(b.n))
74
+ .map((f) => f.n);
75
+ }
76
+ async replay() {
77
+ for (const n of this._files()) {
78
+ const p = path.join(this.dir, n);
79
+ try {
80
+ const res = await this.fetch(this.url, {
81
+ method: 'POST',
82
+ headers: { ...this.headers, 'Content-Type': 'application/json' },
83
+ body: fs.readFileSync(p),
84
+ });
85
+ if (!res.ok)
86
+ return;
87
+ }
88
+ catch {
89
+ return; // still offline; keep order
90
+ }
91
+ fs.unlinkSync(p);
92
+ }
93
+ }
94
+ export(batch, done) {
95
+ void this.replay().then(() => this.inner.export(batch, (r) => {
96
+ if (r.code !== 0)
97
+ this._spool(this.encode(batch));
98
+ done(r);
99
+ }));
100
+ }
101
+ _spool(payload) {
102
+ const files = this._files();
103
+ for (const old of files.slice(0, Math.max(0, files.length - this.maxFiles + 1))) {
104
+ fs.unlinkSync(path.join(this.dir, old)); // drop-oldest
105
+ }
106
+ fs.writeFileSync(path.join(this.dir, `${crypto.randomUUID()}.json`), payload);
107
+ }
108
+ shutdown() {
109
+ return this.inner.shutdown();
110
+ }
111
+ forceFlush() {
112
+ return this.inner.forceFlush ? this.inner.forceFlush() : Promise.resolve();
113
+ }
114
+ }
115
+ exports.SpoolExporter = SpoolExporter;
116
+ /** A spool for log records: same directory rules, `/v1/logs` replay. */
117
+ const spoolLogs = (inner, dir, url, headers, fetch, opts) => new SpoolExporter(inner, dir, url, headers, fetch, { ...opts, encode: exports.encodeLogs });
118
+ exports.spoolLogs = spoolLogs;
119
+ /** A spool for metrics (`/v1/metrics` replay); the reader still asks the real exporter for temporality. */
120
+ class MetricSpool extends SpoolExporter {
121
+ metricInner;
122
+ constructor(metricInner, dir, url, headers, fetch, opts) {
123
+ super(metricInner, dir, url, headers, fetch, { ...opts, encode: exports.encodeMetrics });
124
+ this.metricInner = metricInner;
125
+ }
126
+ selectAggregationTemporality(t) {
127
+ const pick = this.metricInner.selectAggregationTemporality;
128
+ return pick ? pick.call(this.metricInner, t) : sdk_metrics_1.AggregationTemporality.CUMULATIVE; // the SDK default
129
+ }
130
+ forceFlush() {
131
+ return this.metricInner.forceFlush();
132
+ }
133
+ }
134
+ exports.MetricSpool = MetricSpool;
@@ -0,0 +1,17 @@
1
+ export interface CaptureContext {
2
+ /** false for crashes (uncaught); default true. Keys starting with `wt.` are dropped. */
3
+ handled?: boolean;
4
+ attributes?: Record<string, string | number | boolean | undefined>;
5
+ }
6
+ /** The slice of `process` the hooks need; tests pass an EventEmitter. */
7
+ export interface ProcessLike {
8
+ on(event: string, listener: (arg: unknown) => void): unknown;
9
+ off(event: string, listener: (arg: unknown) => void): unknown;
10
+ listenerCount(event: string): number;
11
+ exit(code?: number): unknown;
12
+ }
13
+ export declare function dropReserved<T>(attrs?: Record<string, T>): Record<string, T>;
14
+ /** Record err on the active span (or a new `exception` span). Returns the trace id. */
15
+ export declare function captureException(err: unknown, ctx?: CaptureContext): string;
16
+ /** uncaughtException / unhandledRejection hooks. Exits like Node would, but only when we are the sole listener. */
17
+ export declare function installProcessHandlers(flush: () => Promise<unknown>, proc?: ProcessLike): () => void;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dropReserved = dropReserved;
4
+ exports.captureException = captureException;
5
+ exports.installProcessHandlers = installProcessHandlers;
6
+ // Error capture: an exception becomes an OTel span event (exception.*) with trace and span ids.
7
+ const api_1 = require("@opentelemetry/api");
8
+ const captured = new WeakMap(); // error object -> traceId, so framework + process hooks never double-report
9
+ function dropReserved(attrs) {
10
+ return Object.fromEntries(Object.entries(attrs || {}).filter(([k]) => !k.startsWith('wt.')));
11
+ }
12
+ /** Record err on the active span (or a new `exception` span). Returns the trace id. */
13
+ function captureException(err, ctx) {
14
+ const o = ctx || {};
15
+ const e = err instanceof Error ? err : new Error(typeof err === 'string' ? err : JSON.stringify(err));
16
+ const seen = captured.get(e);
17
+ if (seen !== undefined)
18
+ return seen;
19
+ const attrs = { 'error.handled': o.handled !== false, ...dropReserved(o.attributes) };
20
+ const active = api_1.trace.getActiveSpan();
21
+ const span = active && active.isRecording() ? active : api_1.trace.getTracer('watchtower').startSpan('exception');
22
+ span.setAttributes(attrs);
23
+ span.recordException(e);
24
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: e.message });
25
+ const traceId = span.spanContext().traceId;
26
+ if (span !== active)
27
+ span.end();
28
+ captured.set(e, traceId);
29
+ return traceId;
30
+ }
31
+ /** uncaughtException / unhandledRejection hooks. Exits like Node would, but only when we are the sole listener. */
32
+ function installProcessHandlers(flush, proc) {
33
+ const p = proc || process;
34
+ const exitAfterFlush = () => Promise.race([flush(), new Promise((r) => setTimeout(r, 2000).unref())]).finally(() => p.exit(1));
35
+ const onException = (e) => {
36
+ captureException(e, { handled: false, attributes: { 'error.mechanism': 'uncaughtException' } });
37
+ if (p.listenerCount('uncaughtException') > 1)
38
+ return;
39
+ console.error(e);
40
+ exitAfterFlush();
41
+ };
42
+ const onRejection = (reason) => {
43
+ captureException(reason, { handled: false, attributes: { 'error.mechanism': 'unhandledRejection' } });
44
+ if (p.listenerCount('unhandledRejection') > 1)
45
+ return;
46
+ console.error(reason);
47
+ exitAfterFlush();
48
+ };
49
+ p.on('uncaughtException', onException);
50
+ p.on('unhandledRejection', onRejection);
51
+ return () => {
52
+ p.off('uncaughtException', onException);
53
+ p.off('unhandledRejection', onRejection);
54
+ };
55
+ }
@@ -0,0 +1,123 @@
1
+ import { inspect } from 'node:util';
2
+ import { metrics, trace } from '@opentelemetry/api';
3
+ import type { Tracer } from '@opentelemetry/api';
4
+ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
5
+ import { LoggerProvider } from '@opentelemetry/sdk-logs';
6
+ import type { MeterProvider } from '@opentelemetry/sdk-metrics';
7
+ import { captureException } from './errors.js';
8
+ import type { CaptureContext } from './errors.js';
9
+ import type { Profiler } from './profiling.js';
10
+ export { captureException, metrics, trace };
11
+ export { setCaptureRules, capturePayload } from './payload.js';
12
+ export type { CaptureRule } from './payload.js';
13
+ export type { CaptureContext };
14
+ export declare const DEFAULT_ENDPOINT = "http://localhost:4318";
15
+ export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
16
+ export interface InitOptions {
17
+ /** Ingest key; defaults to WT_INGEST_KEY. */
18
+ apiKey?: string;
19
+ /** Defaults to WT_ENVIRONMENT. */
20
+ environment?: string;
21
+ /** Defaults to WT_RELEASE. */
22
+ release?: string;
23
+ /** Hook uncaughtException / unhandledRejection (default true). */
24
+ captureProcessErrors?: boolean;
25
+ /** Replace the log exporter (tests). */
26
+ logExporter?: unknown;
27
+ /** Export OTLP logs; defaults to WATCHTOWER_LOGS (on unless `off`; OTEL_LOGS_EXPORTER=none also turns it off). */
28
+ logs?: boolean;
29
+ /** Export OTLP metrics; defaults to WATCHTOWER_METRICS (on unless `off`; OTEL_METRICS_EXPORTER=none also turns it off). */
30
+ metrics?: boolean;
31
+ /** Replace the metric exporter (tests). */
32
+ metricExporter?: unknown;
33
+ /** OTLP/HTTP base URL; defaults to WT_OTLP_ENDPOINT or http://localhost:4318. */
34
+ endpoint?: string;
35
+ /** REST API base URL for getPrompt/score; defaults to WT_API_URL or endpoint. */
36
+ apiUrl?: string;
37
+ project?: string;
38
+ /** Defaults to WT_SERVICE. */
39
+ serviceName?: string;
40
+ /** Resource attributes; keys starting with `wt.` are dropped. */
41
+ resource?: Record<string, string | number | boolean>;
42
+ /** Called for every span attribute before export; return the value to keep. */
43
+ redact?: (key: string, value: unknown) => unknown;
44
+ /** Directory for the offline buffer. */
45
+ bufferDir?: string;
46
+ /** Fetch the service's payload capture rules (APM-016) and record bodies/GraphQL where a rule matches; defaults to WT_CAPTURE_RULES=1. */
47
+ captureRules?: boolean;
48
+ /** Replace the span exporter (tests). */
49
+ exporter?: unknown;
50
+ fetch?: typeof fetch;
51
+ }
52
+ export interface EvalRow {
53
+ case: number;
54
+ traceId: string;
55
+ scores: Record<string, unknown>;
56
+ errors: Record<string, string>;
57
+ }
58
+ export interface EvalOptions {
59
+ name?: string;
60
+ errorTolerance?: boolean;
61
+ /** Rows of an earlier run; cases that finished without errors are kept, not re-run. */
62
+ resume?: EvalRow[];
63
+ }
64
+ export type Scorers = Record<string, (testCase: any, output: any) => unknown | Promise<unknown>>;
65
+ export type EvalTask = (input: any) => unknown | Promise<unknown>;
66
+ export interface ScoreOptions {
67
+ name?: string;
68
+ spanId?: string;
69
+ comment?: string;
70
+ }
71
+ /** Drop caller-supplied wt.* keys: tenant identity comes only from the key. */
72
+ export declare function safeResource(attrs?: Record<string, unknown>): Record<string, unknown>;
73
+ export declare class Client {
74
+ readonly endpoint: string;
75
+ readonly apiUrl: string;
76
+ readonly project: string | undefined;
77
+ readonly headers: {
78
+ Authorization: string;
79
+ };
80
+ readonly fetch: typeof fetch;
81
+ readonly redact: InitOptions['redact'];
82
+ readonly provider: NodeTracerProvider;
83
+ readonly tracer: Tracer;
84
+ readonly loggerProvider: LoggerProvider;
85
+ readonly logger: ReturnType<LoggerProvider['getLogger']>;
86
+ /** Set when metrics are on; `init` makes it the global meter provider (`metrics.getMeter`). */
87
+ readonly meterProvider?: MeterProvider;
88
+ private readonly stopRuntime;
89
+ uninstall?: () => void;
90
+ /** Set when WT_PROFILING=1 started the continuous profiler. */
91
+ profiler?: Promise<Profiler | undefined>;
92
+ constructor(opts: InitOptions);
93
+ /** Emit an OTLP log record; trace and span ids come from the active context. */
94
+ log(level: LogLevel, body: string, attributes?: Record<string, unknown>): void;
95
+ forceFlush(): Promise<unknown>;
96
+ toJSON(): {
97
+ endpoint: string;
98
+ project: string | undefined;
99
+ headers: {
100
+ Authorization: string;
101
+ };
102
+ };
103
+ [inspect.custom](): string;
104
+ private _call;
105
+ getPrompt(promptId: string): Promise<unknown>;
106
+ score(traceId: string, value: number | boolean | string, o?: ScoreOptions): Promise<unknown>;
107
+ /** Run task per case under a span; record each scorer result as a score when a project is set. */
108
+ evaluate(dataset: unknown[], task: EvalTask, scorers: Scorers, o?: EvalOptions): Promise<EvalRow[]>;
109
+ /** Re-run only the cases that errored or are missing in `previous`. */
110
+ evaluateResume(dataset: unknown[], task: EvalTask, scorers: Scorers, previous: EvalRow[], o?: EvalOptions): Promise<EvalRow[]>;
111
+ /** Wrap fn in a span. */
112
+ observe<A extends unknown[], R>(name: string, fn: (...a: A) => R): (...a: A) => R;
113
+ shutdown(): Promise<void>;
114
+ }
115
+ export declare function init(opts: InitOptions): Client;
116
+ export declare const flush: () => Promise<unknown>;
117
+ export declare const log: (l: LogLevel, b: string, a?: Record<string, unknown>) => void;
118
+ export declare const getPrompt: (id: string) => Promise<unknown>;
119
+ export declare const score: (t: string, v: number | boolean | string, o?: ScoreOptions) => Promise<unknown>;
120
+ export declare const evaluate: (d: unknown[], t: EvalTask, s: Scorers, o?: EvalOptions) => Promise<EvalRow[]>;
121
+ export declare const evaluateResume: (d: unknown[], t: EvalTask, s: Scorers, prev: EvalRow[], o?: EvalOptions) => Promise<EvalRow[]>;
122
+ export declare const observe: <A extends unknown[], R>(n: string, f: (...a: A) => R) => ((...a: A) => R);
123
+ export declare const shutdown: () => Promise<void>;