@watchtowerobservability/node 0.0.0-stage → 0.2.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 (105) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +121 -2
  3. package/dist/cjs/buffer.d.ts +49 -0
  4. package/dist/cjs/buffer.js +134 -0
  5. package/dist/cjs/errors.d.ts +17 -0
  6. package/dist/cjs/errors.js +55 -0
  7. package/dist/cjs/index.d.ts +120 -0
  8. package/dist/cjs/index.js +302 -0
  9. package/dist/cjs/integrations/azure-functions.d.ts +18 -0
  10. package/dist/cjs/integrations/azure-functions.js +97 -0
  11. package/dist/cjs/integrations/express.d.ts +25 -0
  12. package/dist/cjs/integrations/express.js +58 -0
  13. package/dist/cjs/integrations/fastify.d.ts +6 -0
  14. package/dist/cjs/integrations/fastify.js +44 -0
  15. package/dist/cjs/integrations/genai-agents.d.ts +36 -0
  16. package/dist/cjs/integrations/genai-agents.js +124 -0
  17. package/dist/cjs/integrations/genai-stream.d.ts +19 -0
  18. package/dist/cjs/integrations/genai-stream.js +135 -0
  19. package/dist/cjs/integrations/genai.d.ts +18 -0
  20. package/dist/cjs/integrations/genai.js +150 -0
  21. package/dist/cjs/integrations/koa.d.ts +19 -0
  22. package/dist/cjs/integrations/koa.js +34 -0
  23. package/dist/cjs/integrations/lambda.d.ts +11 -0
  24. package/dist/cjs/integrations/lambda.js +68 -0
  25. package/dist/cjs/integrations/logs.d.ts +10 -0
  26. package/dist/cjs/integrations/logs.js +77 -0
  27. package/dist/cjs/integrations/nestjs.d.ts +16 -0
  28. package/dist/cjs/integrations/nestjs.js +30 -0
  29. package/dist/cjs/integrations/next.d.ts +11 -0
  30. package/dist/cjs/integrations/next.js +59 -0
  31. package/dist/cjs/integrations/prisma.d.ts +3 -0
  32. package/dist/cjs/integrations/prisma.js +33 -0
  33. package/dist/cjs/integrations/util.d.ts +9 -0
  34. package/dist/cjs/integrations/util.js +37 -0
  35. package/dist/cjs/jest.d.ts +21 -0
  36. package/dist/cjs/jest.js +45 -0
  37. package/dist/cjs/load.d.ts +1 -0
  38. package/dist/cjs/load.js +11 -0
  39. package/dist/cjs/metrics.d.ts +10 -0
  40. package/dist/cjs/metrics.js +81 -0
  41. package/dist/cjs/package.json +1 -0
  42. package/dist/cjs/payload.d.ts +42 -0
  43. package/dist/cjs/payload.js +145 -0
  44. package/dist/cjs/probes.d.ts +97 -0
  45. package/dist/cjs/probes.js +422 -0
  46. package/dist/cjs/profiling.d.ts +81 -0
  47. package/dist/cjs/profiling.js +253 -0
  48. package/dist/cjs/reporter-core.d.ts +32 -0
  49. package/dist/cjs/reporter-core.js +102 -0
  50. package/dist/cjs/test-plan.d.ts +93 -0
  51. package/dist/cjs/test-plan.js +262 -0
  52. package/dist/cjs/vitest.d.ts +27 -0
  53. package/dist/cjs/vitest.js +52 -0
  54. package/dist/esm/buffer.d.ts +49 -0
  55. package/dist/esm/buffer.js +92 -0
  56. package/dist/esm/errors.d.ts +17 -0
  57. package/dist/esm/errors.js +50 -0
  58. package/dist/esm/index.d.ts +120 -0
  59. package/dist/esm/index.js +251 -0
  60. package/dist/esm/integrations/azure-functions.d.ts +18 -0
  61. package/dist/esm/integrations/azure-functions.js +60 -0
  62. package/dist/esm/integrations/express.d.ts +25 -0
  63. package/dist/esm/integrations/express.js +54 -0
  64. package/dist/esm/integrations/fastify.d.ts +6 -0
  65. package/dist/esm/integrations/fastify.js +41 -0
  66. package/dist/esm/integrations/genai-agents.d.ts +36 -0
  67. package/dist/esm/integrations/genai-agents.js +118 -0
  68. package/dist/esm/integrations/genai-stream.d.ts +19 -0
  69. package/dist/esm/integrations/genai-stream.js +130 -0
  70. package/dist/esm/integrations/genai.d.ts +18 -0
  71. package/dist/esm/integrations/genai.js +138 -0
  72. package/dist/esm/integrations/koa.d.ts +19 -0
  73. package/dist/esm/integrations/koa.js +31 -0
  74. package/dist/esm/integrations/lambda.d.ts +11 -0
  75. package/dist/esm/integrations/lambda.js +32 -0
  76. package/dist/esm/integrations/logs.d.ts +10 -0
  77. package/dist/esm/integrations/logs.js +40 -0
  78. package/dist/esm/integrations/nestjs.d.ts +16 -0
  79. package/dist/esm/integrations/nestjs.js +26 -0
  80. package/dist/esm/integrations/next.d.ts +11 -0
  81. package/dist/esm/integrations/next.js +22 -0
  82. package/dist/esm/integrations/prisma.d.ts +3 -0
  83. package/dist/esm/integrations/prisma.js +30 -0
  84. package/dist/esm/integrations/util.d.ts +9 -0
  85. package/dist/esm/integrations/util.js +32 -0
  86. package/dist/esm/jest.d.ts +21 -0
  87. package/dist/esm/jest.js +41 -0
  88. package/dist/esm/load.d.ts +1 -0
  89. package/dist/esm/load.js +5 -0
  90. package/dist/esm/metrics.d.ts +10 -0
  91. package/dist/esm/metrics.js +44 -0
  92. package/dist/esm/package.json +1 -0
  93. package/dist/esm/payload.d.ts +42 -0
  94. package/dist/esm/payload.js +131 -0
  95. package/dist/esm/probes.d.ts +97 -0
  96. package/dist/esm/probes.js +412 -0
  97. package/dist/esm/profiling.d.ts +81 -0
  98. package/dist/esm/profiling.js +242 -0
  99. package/dist/esm/reporter-core.d.ts +32 -0
  100. package/dist/esm/reporter-core.js +63 -0
  101. package/dist/esm/test-plan.d.ts +93 -0
  102. package/dist/esm/test-plan.js +248 -0
  103. package/dist/esm/vitest.d.ts +27 -0
  104. package/dist/esm/vitest.js +48 -0
  105. package/package.json +219 -4
@@ -0,0 +1,253 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Profiler = void 0;
4
+ exports.enableAsyncSpanLabels = enableAsyncSpanLabels;
5
+ exports.withSpan = withSpan;
6
+ exports.takeIntervals = takeIntervals;
7
+ exports.foldProfile = foldProfile;
8
+ exports.foldedBody = foldedBody;
9
+ exports.ingestUrl = ingestUrl;
10
+ exports.startProfiling = startProfiling;
11
+ // Continuous CPU profiler on V8's own sampler (`node:inspector`, no native addon): every
12
+ // `periodMs` the CPU profile is folded into stacks and posted to the gateway's
13
+ // Pyroscope-compatible `/ingest` as `<service>.cpu` (format `folded`). Best effort: a failed
14
+ // upload is counted and dropped. `withSpan` labels samples taken while its function runs, joined
15
+ // on V8's sample timestamps, so a trace links to its exact profile.
16
+ const node_async_hooks_1 = require("node:async_hooks");
17
+ const node_inspector_1 = require("node:inspector");
18
+ const node_v8_1 = require("node:v8");
19
+ const api_1 = require("@opentelemetry/api");
20
+ const intervals = [];
21
+ const MAX_INTERVALS = 100_000;
22
+ function nowUs() {
23
+ return Number(process.hrtime.bigint() / 1000n);
24
+ }
25
+ /** The span of the running code, carried across `await` once async labels are on. */
26
+ const spanStore = new node_async_hooks_1.AsyncLocalStorage();
27
+ /** Promises created under a span, and that span. */
28
+ const tagged = new WeakMap();
29
+ /** The interval each `before` opened, for its `after`; `null` for an unlabeled continuation. */
30
+ const running = [];
31
+ let asyncSpans = false;
32
+ function open(prefix) {
33
+ if (intervals.length >= MAX_INTERVALS)
34
+ return null;
35
+ const iv = { start: nowUs(), end: Number.MAX_SAFE_INTEGER, prefix };
36
+ intervals.push(iv);
37
+ return iv;
38
+ }
39
+ /**
40
+ * Opt-in (overhead unmeasured): `withSpan` also labels its async function's code after each
41
+ * `await`. The span rides in an AsyncLocalStorage; a promise created under it is tagged, and each
42
+ * run of its continuation (V8 promise hooks `before` to `after`) is one more interval. Plain
43
+ * callbacks it starts (timers, events) are labeled only from their own `await`s on.
44
+ */
45
+ function enableAsyncSpanLabels() {
46
+ if (asyncSpans)
47
+ return;
48
+ asyncSpans = true;
49
+ node_v8_1.promiseHooks.createHook({
50
+ init(promise) {
51
+ const p = spanStore.getStore(); // init runs synchronously, in the creating code's context
52
+ if (p)
53
+ tagged.set(promise, p);
54
+ },
55
+ before(promise) {
56
+ if (running.length >= 1_000)
57
+ running.length = 0; // afters lost to an uncaught exception
58
+ const p = tagged.get(promise);
59
+ running.push(p ? open(p) : null);
60
+ },
61
+ after() {
62
+ const iv = running.pop();
63
+ if (iv)
64
+ iv.end = nowUs();
65
+ },
66
+ });
67
+ }
68
+ /**
69
+ * Labels samples taken while `fn` runs with a span (default: the active OpenTelemetry span). Only
70
+ * `fn`'s synchronous part, unless [[enableAsyncSpanLabels]] (or the profiler's `asyncSpans`) is on.
71
+ */
72
+ function withSpan(fn, ids) {
73
+ const sc = ids ?? api_1.trace.getActiveSpan()?.spanContext();
74
+ if (!sc || intervals.length >= MAX_INTERVALS)
75
+ return fn();
76
+ const prefix = `span_id=${sc.spanId},trace_id=${sc.traceId}\t`;
77
+ const iv = open(prefix);
78
+ try {
79
+ return asyncSpans ? spanStore.run(prefix, fn) : fn();
80
+ }
81
+ finally {
82
+ iv.end = nowUs();
83
+ }
84
+ }
85
+ /** Takes the intervals a profile up to `until` can need; open ones stay for the next profile. */
86
+ function takeIntervals(until) {
87
+ const out = intervals.slice();
88
+ const keep = out.filter((iv) => iv.end > until);
89
+ intervals.length = 0;
90
+ intervals.push(...keep);
91
+ return out;
92
+ }
93
+ /** The innermost span at `t`; `sorted` is by start. */
94
+ function prefixAt(sorted, t) {
95
+ let lo = 0;
96
+ let hi = sorted.length;
97
+ while (lo < hi) {
98
+ const mid = (lo + hi) >> 1;
99
+ if (sorted[mid].start <= t)
100
+ lo = mid + 1;
101
+ else
102
+ hi = mid;
103
+ }
104
+ for (let i = lo - 1; i >= 0 && i >= lo - 16; i--)
105
+ if (sorted[i].end >= t)
106
+ return sorted[i].prefix;
107
+ return '';
108
+ }
109
+ const MAX_DEPTH = 128;
110
+ function frameName(f) {
111
+ const file = f.url ? f.url.split('/').pop() : '';
112
+ const name = f.functionName || '(anonymous)';
113
+ return (file ? `${name} (${file}:${f.lineNumber + 1})` : name).replace(/;/g, ':');
114
+ }
115
+ /** Root-first folded stacks with their sample counts; V8's synthetic `(root)` is left out. */
116
+ function foldProfile(p, spans = []) {
117
+ const parent = new Map();
118
+ const byId = new Map();
119
+ for (const n of p.nodes) {
120
+ byId.set(n.id, n);
121
+ for (const c of n.children ?? [])
122
+ parent.set(c, n.id);
123
+ }
124
+ const counts = new Map();
125
+ const sorted = [...spans].sort((a, b) => a.start - b.start);
126
+ let t = p.startTime ?? 0;
127
+ for (const [i, id] of (p.samples ?? []).entries()) {
128
+ t += p.timeDeltas?.[i] ?? 0;
129
+ const names = [];
130
+ for (let cur = id; cur !== undefined && names.length < MAX_DEPTH; cur = parent.get(cur)) {
131
+ const n = byId.get(cur);
132
+ if (!n || n.callFrame.functionName === '(root)')
133
+ break;
134
+ if (n.callFrame.functionName === '(idle)' || n.callFrame.functionName === '(program)') {
135
+ names.length = 0;
136
+ break;
137
+ }
138
+ names.push(frameName(n.callFrame));
139
+ }
140
+ if (names.length === 0)
141
+ continue;
142
+ const key = prefixAt(sorted, t) + names.reverse().join(';');
143
+ counts.set(key, (counts.get(key) ?? 0) + 1);
144
+ }
145
+ return counts;
146
+ }
147
+ function foldedBody(counts) {
148
+ let out = '';
149
+ for (const [k, n] of counts)
150
+ out += `${k} ${n}\n`;
151
+ return out;
152
+ }
153
+ function ingestUrl(endpoint, service, tags, fromS, untilS, hz) {
154
+ const labels = Object.entries(tags).filter(([, v]) => v).sort(([a], [b]) => a.localeCompare(b))
155
+ .map(([k, v]) => `${k}=${v}`).join(',');
156
+ const q = new URLSearchParams({
157
+ name: `${service}.cpu{${labels}}`, from: String(Math.floor(fromS)), until: String(Math.floor(untilS)),
158
+ format: 'folded', sampleRate: String(hz), spyName: 'watchtower-node', units: 'samples',
159
+ });
160
+ return `${endpoint.replace(/\/+$/, '')}/ingest?${q}`;
161
+ }
162
+ class Profiler {
163
+ uploaded = 0;
164
+ dropped = 0;
165
+ key;
166
+ endpoint;
167
+ service;
168
+ tags;
169
+ intervalUs;
170
+ periodMs;
171
+ session;
172
+ timer;
173
+ from = 0;
174
+ constructor(o = {}) {
175
+ const key = o.apiKey ?? process.env.WT_INGEST_KEY;
176
+ if (!key)
177
+ throw new Error('apiKey is required');
178
+ this.key = key;
179
+ this.endpoint = o.endpoint ?? process.env.WT_OTLP_ENDPOINT ?? 'http://localhost:4318';
180
+ this.service = o.service ?? process.env.WT_SERVICE ?? 'app';
181
+ this.tags = { env: process.env.WT_ENVIRONMENT, version: process.env.WT_RELEASE, ...o.tags };
182
+ this.intervalUs = Math.min(Math.max(o.intervalUs ?? 10_000, 1_000), 1_000_000);
183
+ this.periodMs = Math.max(o.periodMs ?? 15_000, 1_000);
184
+ if (o.asyncSpans)
185
+ enableAsyncSpanLabels();
186
+ }
187
+ /** Not printable with the key. */
188
+ [Symbol.for('nodejs.util.inspect.custom')]() {
189
+ return `Profiler { service: '${this.service}' }`;
190
+ }
191
+ post(method, params) {
192
+ return new Promise((resolve, reject) => {
193
+ this.session.post(method, params ?? {}, (err, res) => (err ? reject(err) : resolve(res)));
194
+ });
195
+ }
196
+ async start() {
197
+ if (this.session)
198
+ return this;
199
+ this.session = new node_inspector_1.Session();
200
+ this.session.connect();
201
+ await this.post('Profiler.enable');
202
+ await this.post('Profiler.setSamplingInterval', { interval: this.intervalUs });
203
+ await this.post('Profiler.start');
204
+ this.from = Date.now() / 1000;
205
+ this.timer = setInterval(() => void this.flush(true), this.periodMs);
206
+ this.timer.unref();
207
+ return this;
208
+ }
209
+ /** Stop the current profile, upload it and (when `restart`) start the next one. */
210
+ async flush(restart) {
211
+ if (!this.session)
212
+ return;
213
+ const until = Date.now() / 1000;
214
+ const { profile } = await this.post('Profiler.stop');
215
+ const from = this.from;
216
+ if (restart) {
217
+ await this.post('Profiler.start');
218
+ this.from = until;
219
+ }
220
+ const counts = foldProfile(profile, takeIntervals(nowUs()));
221
+ if (counts.size)
222
+ await this.upload(counts, from, until);
223
+ }
224
+ async upload(counts, fromS, untilS) {
225
+ try {
226
+ const hz = Math.round(1_000_000 / this.intervalUs);
227
+ const r = await fetch(ingestUrl(this.endpoint, this.service, this.tags, fromS, untilS, hz), {
228
+ method: 'POST', body: foldedBody(counts),
229
+ headers: { authorization: `Bearer ${this.key}`, 'content-type': 'text/plain' },
230
+ signal: AbortSignal.timeout(10_000),
231
+ });
232
+ if (r.ok)
233
+ this.uploaded++;
234
+ else
235
+ this.dropped++;
236
+ }
237
+ catch {
238
+ this.dropped++;
239
+ }
240
+ }
241
+ async stop() {
242
+ if (this.timer)
243
+ clearInterval(this.timer);
244
+ await this.flush(false).catch(() => undefined);
245
+ this.session?.disconnect();
246
+ this.session = undefined;
247
+ }
248
+ }
249
+ exports.Profiler = Profiler;
250
+ /** Start a [[Profiler]] with the SDK's environment defaults. */
251
+ function startProfiling(o = {}) {
252
+ return new Profiler(o).start();
253
+ }
@@ -0,0 +1,32 @@
1
+ import type { Client, InitOptions } from './index.js';
2
+ export interface ReporterOptions {
3
+ client?: Client;
4
+ apiKey?: string;
5
+ serviceName?: string;
6
+ /** Extra options passed to `init` when the reporter creates its own client. */
7
+ init?: InitOptions;
8
+ }
9
+ export type TestOutcome = 'passed' | 'failed' | 'skipped';
10
+ export interface TestRecord {
11
+ name: string;
12
+ outcome: TestOutcome;
13
+ durationMs?: number;
14
+ message?: string;
15
+ endMs?: number;
16
+ /** `suite::file > describe > test` (see test-plan.ts) */
17
+ id?: string;
18
+ /** ticket of a quarantined test; its failure did not fail the run */
19
+ quarantined?: string;
20
+ /** a test the project had never seen (early flake detection) */
21
+ isNew?: boolean;
22
+ /** failed attempts before the final result (retries) */
23
+ attempts?: number;
24
+ }
25
+ /** Client from `opts.client`, else `WT_INGEST_KEY` (+ `WT_PROJECT_ID`); `null` when neither is set. */
26
+ export declare function clientFor(opts?: ReporterOptions): Client | null;
27
+ /**
28
+ * tests: [{ name, outcome: 'passed'|'failed'|'skipped', durationMs, message?, endMs? }]
29
+ * Spans are created after the fact, so start/end times are set explicitly.
30
+ */
31
+ export declare function reportTests(client: Client | null, tests: TestRecord[], framework?: string): Promise<number>;
32
+ export declare const outcome: (s?: string) => TestOutcome;
@@ -0,0 +1,102 @@
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.outcome = void 0;
37
+ exports.clientFor = clientFor;
38
+ exports.reportTests = reportTests;
39
+ // Shared by the Jest and Vitest reporters: every finished test becomes a span named
40
+ // `test <full name>` with `test.outcome` / `test.duration_ms`, and, with a project, a
41
+ // `test_pass` score (1 passed, 0 failed; skipped tests get no score). Telemetry failures never
42
+ // fail the test run.
43
+ const api_1 = require("@opentelemetry/api");
44
+ const wt = __importStar(require("./index.js"));
45
+ /** Client from `opts.client`, else `WT_INGEST_KEY` (+ `WT_PROJECT_ID`); `null` when neither is set. */
46
+ function clientFor(opts) {
47
+ const o = opts || {};
48
+ if (o.client)
49
+ return o.client;
50
+ const apiKey = o.apiKey || process.env.WT_INGEST_KEY;
51
+ if (!apiKey)
52
+ return null;
53
+ return wt.init({ apiKey, serviceName: o.serviceName || 'tests', ...o.init });
54
+ }
55
+ /**
56
+ * tests: [{ name, outcome: 'passed'|'failed'|'skipped', durationMs, message?, endMs? }]
57
+ * Spans are created after the fact, so start/end times are set explicitly.
58
+ */
59
+ async function reportTests(client, tests, framework = 'test') {
60
+ if (!client)
61
+ return 0;
62
+ let n = 0;
63
+ for (const t of tests) {
64
+ try {
65
+ const end = t.endMs || Date.now();
66
+ const span = client.tracer.startSpan(`test ${t.name}`, { startTime: end - (t.durationMs || 0) });
67
+ span.setAttribute('test.outcome', t.outcome);
68
+ span.setAttribute('test.duration_ms', t.durationMs || 0);
69
+ // OTel test semconv plus the attributes the pytest plugin sets
70
+ const id = t.id || t.name;
71
+ span.setAttribute('test.framework', framework);
72
+ span.setAttribute('test.suite.name', id.includes('::') ? id.slice(0, id.indexOf('::')) : framework);
73
+ span.setAttribute('test.case.name', id);
74
+ span.setAttribute('test.case.result.status', t.outcome === 'passed' ? 'pass' : t.outcome === 'failed' ? 'fail' : 'skip');
75
+ if (t.quarantined)
76
+ span.setAttribute('test.quarantined', true);
77
+ if (t.isNew) {
78
+ span.setAttribute('test.is_new', true);
79
+ span.setAttribute('test.efd.retries', t.attempts || 0);
80
+ span.setAttribute('test.is_flaky', (t.attempts || 0) > 0 && t.outcome === 'passed');
81
+ }
82
+ if (t.outcome === 'failed') {
83
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: String(t.message || 'failed').slice(0, 500) });
84
+ }
85
+ const traceId = span.spanContext().traceId;
86
+ span.end(end);
87
+ n += 1;
88
+ if (client.project && t.outcome !== 'skipped') {
89
+ await client.score(traceId, t.outcome === 'passed' ? 1 : 0, { name: 'test_pass', comment: t.name });
90
+ }
91
+ }
92
+ catch (_e) { /* telemetry down must not fail tests */ }
93
+ }
94
+ try {
95
+ await client.provider.forceFlush();
96
+ }
97
+ catch (_e) { /* same */ }
98
+ return n;
99
+ }
100
+ const OUTCOME = { passed: 'passed', pass: 'passed', failed: 'failed', fail: 'failed' };
101
+ const outcome = (s) => OUTCOME[s] || 'skipped';
102
+ exports.outcome = outcome;
@@ -0,0 +1,93 @@
1
+ import type { TestRecord } from './reporter-core.js';
2
+ import type { Client } from './index.js';
3
+ export interface TestPlan {
4
+ quarantined: {
5
+ id: string;
6
+ ticket_url?: string | null;
7
+ owner?: string | null;
8
+ }[];
9
+ disabled: string[];
10
+ skippable: string[];
11
+ new_tests: string[];
12
+ efd_retries: number;
13
+ }
14
+ /** What the plan says about one test. */
15
+ export interface TestDecision {
16
+ skip?: 'disabled' | 'unaffected';
17
+ /** ticket URL (or "no ticket") of a quarantined test */
18
+ quarantined?: string;
19
+ isNew?: boolean;
20
+ retries: number;
21
+ }
22
+ export declare const suiteName: (framework: string) => string;
23
+ export declare function testId(suite: string, file: string | undefined, names: string[]): string;
24
+ export declare function changedFiles(): string[];
25
+ /** The session plan; `null` without a project or when the API is unreachable (then everything runs). */
26
+ export declare function fetchTestPlan(client: Client | null, tests?: string[]): Promise<TestPlan | null>;
27
+ /** The plan the global setup wrote (workers and reporters), cached per process. */
28
+ export declare function loadPlan(): TestPlan | null;
29
+ /** Vitest/Jest global setup: fetch the plan once and publish it to the workers (which inherit the env). */
30
+ export default function globalSetup(): Promise<void>;
31
+ /** Decides per test id; with no plan nothing is skipped or retried. */
32
+ export declare function decider(plan: TestPlan | null): (id: string) => TestDecision;
33
+ /** The slice of a Vitest task the setup reads and changes. */
34
+ export interface PlanTask {
35
+ type?: string;
36
+ name: string;
37
+ mode?: string;
38
+ retry?: number;
39
+ filepath?: string;
40
+ tasks?: PlanTask[];
41
+ meta?: Record<string, unknown>;
42
+ result?: {
43
+ state?: string;
44
+ errors?: {
45
+ message?: string;
46
+ }[];
47
+ };
48
+ }
49
+ /** Vitest's `beforeAll`/`afterEach`, passed in so this package does not import Vitest. */
50
+ export interface VitestHooks {
51
+ beforeAll(fn: (suite: PlanTask) => unknown): void;
52
+ afterEach(fn: (ctx: {
53
+ task: PlanTask;
54
+ skip(note?: string): void;
55
+ }) => unknown): void;
56
+ }
57
+ /** Applies the plan in a Vitest setup file. Decisions go to `task.meta.wt` for the reporter. */
58
+ export declare function vitestSetup(hooks: VitestHooks): void;
59
+ interface CircusBlock {
60
+ name: string;
61
+ parent?: CircusBlock;
62
+ children?: ({
63
+ type?: string;
64
+ name: string;
65
+ } & Partial<CircusTest>)[];
66
+ }
67
+ interface CircusTest {
68
+ name: string;
69
+ mode?: string;
70
+ status?: string;
71
+ errors: unknown[];
72
+ parent?: CircusBlock;
73
+ }
74
+ export interface CircusEvent {
75
+ name: string;
76
+ test?: CircusTest;
77
+ describeBlock?: CircusBlock;
78
+ }
79
+ type JestEnvBase = new (...args: any[]) => {
80
+ global: Record<string | symbol, unknown>;
81
+ handleTestEvent?(event: CircusEvent, state: unknown): unknown;
82
+ };
83
+ /**
84
+ * Wraps a Jest test environment class so it applies the plan: skips disabled/unaffected tests on
85
+ * `test_start`, raises `jest.retryTimes` for describe blocks holding a new test, and turns a
86
+ * quarantined test's failure into a skip that keeps its failure message (the reporter reads it).
87
+ */
88
+ export declare function jestEnvironment<B extends JestEnvBase>(Base: B): B;
89
+ /** One <testsuite>; a test retried k times gets k failed attempts ahead of its final result. */
90
+ export declare function toJunit(suite: string, tests: TestRecord[]): string;
91
+ /** Posts the results as JUnit when WT_CI_RUN_ID is set; never throws. */
92
+ export declare function uploadResults(client: Client | null, suite: string, tests: TestRecord[]): Promise<boolean>;
93
+ export {};