@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,102 @@
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`/`afterAll`, 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
+ /** needed for WT_TIA_RECORD=1 */
57
+ afterAll?(fn: (suite: PlanTask) => unknown): void;
58
+ }
59
+ /** Applies the plan in a Vitest setup file. Decisions go to `task.meta.wt` for the reporter. */
60
+ export declare function vitestSetup(hooks: VitestHooks): void;
61
+ interface CircusBlock {
62
+ name: string;
63
+ parent?: CircusBlock;
64
+ children?: ({
65
+ type?: string;
66
+ name: string;
67
+ } & Partial<CircusTest>)[];
68
+ }
69
+ interface CircusTest {
70
+ name: string;
71
+ mode?: string;
72
+ status?: string;
73
+ errors: unknown[];
74
+ parent?: CircusBlock;
75
+ }
76
+ export interface CircusEvent {
77
+ name: string;
78
+ test?: CircusTest;
79
+ describeBlock?: CircusBlock;
80
+ }
81
+ type JestEnvBase = new (...args: any[]) => {
82
+ global: Record<string | symbol, unknown>;
83
+ handleTestEvent?(event: CircusEvent, state: unknown): unknown;
84
+ };
85
+ /**
86
+ * Wraps a Jest test environment class so it applies the plan: skips disabled/unaffected tests on
87
+ * `test_start`, raises `jest.retryTimes` for describe blocks holding a new test, and turns a
88
+ * quarantined test's failure into a skip that keeps its failure message (the reporter reads it).
89
+ */
90
+ export declare function jestEnvironment<B extends JestEnvBase>(Base: B): B;
91
+ /** One <testsuite>; a test retried k times gets k failed attempts ahead of its final result. */
92
+ export declare function toJunit(suite: string, tests: TestRecord[]): string;
93
+ /** Posts the results as JUnit when WT_CI_RUN_ID is set; never throws. */
94
+ export declare function uploadResults(client: Client | null, suite: string, tests: TestRecord[]): Promise<boolean>;
95
+ /** Repository-relative files with an executed statement in an istanbul coverage object. */
96
+ export declare function coveredFiles(cov: unknown, root?: string): string[];
97
+ /**
98
+ * Uploads the coverage of one test file for its tests (`suite::rest` ids); never throws.
99
+ * Needs WT_API_URL, WT_PROJECT_ID and WT_API_KEY (the coverage map needs a project API key).
100
+ */
101
+ export declare function uploadCoverage(file: string | undefined, ids: string[], cov: unknown, fetchImpl?: typeof globalThis.fetch): Promise<boolean>;
102
+ export {};
@@ -0,0 +1,336 @@
1
+ // Test optimization for Vitest and Jest, the same contract as the pytest plugin. Opt in with
2
+ // WT_TEST_OPTIMIZATION=1 (plus WT_INGEST_KEY, WT_PROJECT_ID and WT_API_URL; WT_API_KEY, when set,
3
+ // authenticates the project API calls instead of the ingest key):
4
+ // - a global setup asks `POST /v1/projects/{prj}/tests/plan` once and hands the plan to the
5
+ // workers through a file;
6
+ // - disabled tests are skipped, and so are tests Test Impact Analysis marks unaffected by the
7
+ // changed files (WT_CHANGED_FILES comma-separated, or `git diff --name-only $WT_GIT_BASE...HEAD`);
8
+ // - quarantined tests run, but a failure is turned into a skip (the run stays green) and the
9
+ // reporter records it as a quarantined failure;
10
+ // - a test the project has never seen is retried up to `efd_retries` times (early flake detection).
11
+ // The reporters upload the results as JUnit (`POST /v1/projects/{prj}/test-runs`) when
12
+ // WT_CI_RUN_ID is set, which feeds flaky-test detection and auto-quarantine.
13
+ // With WT_TIA_RECORD=1 (and WT_API_KEY) each test file's istanbul coverage (Vitest
14
+ // `coverage.provider: 'istanbul'`, Jest `--coverage`) is uploaded as the per-test coverage map
15
+ // (`PUT /v1/projects/{prj}/tests/coverage-map`): every test of the file gets the files the file
16
+ // executed plus the test file itself, which Test Impact Analysis then uses to skip tests.
17
+ //
18
+ // Ids are `<suite>::<file relative to cwd> > <describe>... > <test>`, suite = WT_TEST_SUITE or
19
+ // the framework name. Vitest:
20
+ // globalSetup: ['./wt-global.mjs'] // export { default } from '@watchtowerobservability/node/test-plan'
21
+ // setupFiles: ['./wt-setup.ts'] // import { beforeAll, afterEach } from 'vitest';
22
+ // // import { vitestSetup } from '@watchtowerobservability/node/test-plan';
23
+ // // vitestSetup({ beforeAll, afterEach, afterAll });
24
+ // Jest: globalSetup as above, and testEnvironment: './wt-env.js' with
25
+ // module.exports = require('@watchtowerobservability/node/test-plan').jestEnvironment(require('jest-environment-node').TestEnvironment);
26
+ import { execFileSync } from 'node:child_process';
27
+ import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
28
+ import { tmpdir } from 'node:os';
29
+ import { join, relative, sep } from 'node:path';
30
+ import { clientFor } from './reporter-core.js';
31
+ const PLAN_ENV = 'WT_TEST_PLAN_FILE';
32
+ export const suiteName = (framework) => process.env.WT_TEST_SUITE || framework;
33
+ export function testId(suite, file, names) {
34
+ const f = file ? relative(process.cwd(), file).split(sep).join('/') : '';
35
+ return `${suite}::${[f, ...names].filter(Boolean).join(' > ')}`;
36
+ }
37
+ export function changedFiles() {
38
+ const env = process.env.WT_CHANGED_FILES;
39
+ if (env)
40
+ return env.split(',').map((f) => f.trim()).filter(Boolean);
41
+ const base = process.env.WT_GIT_BASE;
42
+ if (!base || base.startsWith('-'))
43
+ return [];
44
+ try {
45
+ const out = execFileSync('git', ['diff', '--name-only', `${base}...HEAD`, '--'], { encoding: 'utf8', timeout: 30_000 });
46
+ return out.split(/\s+/).filter(Boolean);
47
+ }
48
+ catch (_e) {
49
+ return [];
50
+ }
51
+ }
52
+ function apiHeaders(client) {
53
+ const key = process.env.WT_API_KEY;
54
+ return key ? { Authorization: `Bearer ${key}` } : { ...client.headers };
55
+ }
56
+ const projectUrl = (client, path) => `${client.apiUrl}/v1/projects/${encodeURIComponent(client.project || '')}/${path}`;
57
+ /** The session plan; `null` without a project or when the API is unreachable (then everything runs). */
58
+ export async function fetchTestPlan(client, tests = []) {
59
+ if (!client || !client.project)
60
+ return null;
61
+ try {
62
+ const res = await client.fetch(projectUrl(client, 'tests/plan'), {
63
+ method: 'POST',
64
+ headers: { ...apiHeaders(client), 'Content-Type': 'application/json' },
65
+ body: JSON.stringify({ changed_files: changedFiles(), tests }),
66
+ });
67
+ return res.ok ? (await res.json()) : null;
68
+ }
69
+ catch (_e) {
70
+ return null;
71
+ }
72
+ }
73
+ let cached;
74
+ /** The plan the global setup wrote (workers and reporters), cached per process. */
75
+ export function loadPlan() {
76
+ if (cached === undefined) {
77
+ const f = process.env[PLAN_ENV];
78
+ try {
79
+ cached = f ? JSON.parse(readFileSync(f, 'utf8')) : null;
80
+ }
81
+ catch (_e) {
82
+ cached = null;
83
+ }
84
+ }
85
+ return cached;
86
+ }
87
+ /** Vitest/Jest global setup: fetch the plan once and publish it to the workers (which inherit the env). */
88
+ export default async function globalSetup() {
89
+ if (process.env.WT_TEST_OPTIMIZATION !== '1')
90
+ return;
91
+ const client = clientFor({});
92
+ const plan = await fetchTestPlan(client);
93
+ if (client)
94
+ await client.shutdown().catch(() => { });
95
+ if (!plan)
96
+ return;
97
+ // shortcut: the file (a few KB) stays in the OS temp dir; Jest has no teardown return to remove it
98
+ const file = join(mkdtempSync(join(tmpdir(), 'wt-plan-')), 'plan.json');
99
+ writeFileSync(file, JSON.stringify(plan));
100
+ process.env[PLAN_ENV] = file;
101
+ cached = plan;
102
+ }
103
+ /** Decides per test id; with no plan nothing is skipped or retried. */
104
+ export function decider(plan) {
105
+ if (!plan)
106
+ return () => ({ retries: 0 });
107
+ const disabled = new Set(plan.disabled || []);
108
+ const skippable = new Set(plan.skippable || []);
109
+ const fresh = new Set(plan.new_tests || []);
110
+ const quarantined = new Map((plan.quarantined || []).map((q) => [q.id, q.ticket_url || 'no ticket']));
111
+ return (id) => {
112
+ const d = { retries: 0 };
113
+ const q = quarantined.get(id);
114
+ if (disabled.has(id))
115
+ d.skip = 'disabled';
116
+ else if (skippable.has(id) && q === undefined)
117
+ d.skip = 'unaffected';
118
+ if (q !== undefined)
119
+ d.quarantined = q;
120
+ if (fresh.has(id)) {
121
+ d.isNew = true;
122
+ d.retries = Math.max(0, plan.efd_retries || 0);
123
+ }
124
+ return d;
125
+ };
126
+ }
127
+ /** Ids of the tests in `t` that ran (a skipped test executed nothing, so it gets no coverage). */
128
+ function ranIds(t, suite, file, names, out) {
129
+ for (const c of t.tasks || []) {
130
+ const ran = c.mode !== 'skip' && c.mode !== 'todo' && !!c.result?.state && c.result.state !== 'skip';
131
+ if (c.tasks)
132
+ ranIds(c, suite, file, [...names, c.name], out);
133
+ else if (ran)
134
+ out.push(testId(suite, file, [...names, c.name]));
135
+ }
136
+ return out;
137
+ }
138
+ /** Applies the plan in a Vitest setup file. Decisions go to `task.meta.wt` for the reporter. */
139
+ export function vitestSetup(hooks) {
140
+ if (process.env.WT_TIA_RECORD === '1' && hooks.afterAll) {
141
+ const suite = suiteName('vitest');
142
+ const g = globalThis;
143
+ hooks.afterAll((file) => uploadCoverage(file.filepath, ranIds(file, suite, file.filepath, [], []), g.__VITEST_COVERAGE__ || g.__coverage__));
144
+ }
145
+ const plan = loadPlan();
146
+ if (!plan)
147
+ return;
148
+ const decide = decider(plan);
149
+ const suite = suiteName('vitest');
150
+ const walk = (t, file, names) => {
151
+ for (const c of t.tasks || []) {
152
+ const path = [...names, c.name];
153
+ if (c.tasks) {
154
+ walk(c, file, path);
155
+ continue;
156
+ }
157
+ const d = decide(testId(suite, file, path));
158
+ c.meta = { ...c.meta, wt: d };
159
+ if (d.skip && (c.mode === 'run' || c.mode === 'queued'))
160
+ c.mode = 'skip';
161
+ if (d.retries > (c.retry || 0))
162
+ c.retry = d.retries;
163
+ }
164
+ };
165
+ // a setup file's beforeAll runs on the file suite after collection, before any test
166
+ hooks.beforeAll((file) => walk(file, file.filepath, []));
167
+ hooks.afterEach((ctx) => {
168
+ const d = ctx.task.meta?.wt;
169
+ if (!d?.quarantined || ctx.task.result?.state !== 'fail')
170
+ return;
171
+ const msg = ctx.task.result.errors?.[0]?.message || 'failed';
172
+ ctx.task.meta = { ...ctx.task.meta, wtQuarantinedFailure: msg.slice(0, 2000) };
173
+ ctx.skip(`quarantined in Watchtower (${d.quarantined})`);
174
+ });
175
+ }
176
+ const RETRY_TIMES = Symbol.for('RETRY_TIMES');
177
+ /**
178
+ * Wraps a Jest test environment class so it applies the plan: skips disabled/unaffected tests on
179
+ * `test_start`, raises `jest.retryTimes` for describe blocks holding a new test, and turns a
180
+ * quarantined test's failure into a skip that keeps its failure message (the reporter reads it).
181
+ */
182
+ export function jestEnvironment(Base) {
183
+ return class WatchtowerEnvironment extends Base {
184
+ wtFile;
185
+ wtDecide = decider(loadPlan());
186
+ wtSuite = suiteName('jest');
187
+ wtRetrySaved = [];
188
+ wtRan = [];
189
+ // any[]: see JestEnvBase
190
+ constructor(...args) {
191
+ super(...args);
192
+ this.wtFile = args[1]?.testPath || '';
193
+ }
194
+ wtId(test) {
195
+ const names = [test.name];
196
+ for (let b = test.parent; b && b.parent; b = b.parent)
197
+ names.unshift(b.name);
198
+ return testId(this.wtSuite, this.wtFile, names);
199
+ }
200
+ async handleTestEvent(event, state) {
201
+ if (super.handleTestEvent)
202
+ await super.handleTestEvent(event, state);
203
+ const t = event.test;
204
+ if (event.name === 'test_done' && t && process.env.WT_TIA_RECORD === '1')
205
+ this.wtRan.push(this.wtId(t));
206
+ if (event.name === 'run_finish' && process.env.WT_TIA_RECORD === '1') {
207
+ await uploadCoverage(this.wtFile, this.wtRan, this.global.__coverage__);
208
+ return;
209
+ }
210
+ if (event.name === 'test_start' && t) {
211
+ if (this.wtDecide(this.wtId(t)).skip)
212
+ t.mode = 'skip';
213
+ }
214
+ else if (event.name === 'test_done' && t && t.errors.length > 0 && this.wtDecide(this.wtId(t)).quarantined) {
215
+ t.status = 'skip'; // reported as pending; the errors stay as failureMessages
216
+ }
217
+ else if (event.name === 'run_describe_start' && event.describeBlock) {
218
+ const b = event.describeBlock;
219
+ const prev = this.global[RETRY_TIMES];
220
+ this.wtRetrySaved.push(prev);
221
+ // shortcut: Jest retries per describe block, so other failing tests in a block holding a new
222
+ // test are retried too; fine for flake detection, upgrade if circus gets per-test retries
223
+ const n = Math.max(0, ...(b.children || []).filter((c) => c.type === 'test').map((c) => this.wtDecide(this.wtId({ name: c.name, parent: b })).retries));
224
+ if (n > (Number(prev) || 0))
225
+ this.global[RETRY_TIMES] = n;
226
+ }
227
+ else if (event.name === 'run_describe_finish') {
228
+ this.global[RETRY_TIMES] = this.wtRetrySaved.pop();
229
+ }
230
+ }
231
+ };
232
+ }
233
+ // ---------------------------------------------------------------- JUnit upload
234
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
235
+ /** One <testsuite>; a test retried k times gets k failed attempts ahead of its final result. */
236
+ export function toJunit(suite, tests) {
237
+ const prefix = `${suite}::`;
238
+ const cases = [];
239
+ for (const t of tests) {
240
+ const id = t.id || `${prefix}${t.name}`;
241
+ const name = esc(id.startsWith(prefix) ? id.slice(prefix.length) : id);
242
+ const time = ((t.durationMs || 0) / 1000).toFixed(3);
243
+ const fail = `<failure message="${esc(String(t.message || 'failed').slice(0, 500))}"/>`;
244
+ for (let i = 0; i < (t.attempts || 0); i++)
245
+ cases.push(`<testcase name="${name}" time="0">${fail}</testcase>`);
246
+ const body = t.outcome === 'failed' ? fail : t.outcome === 'skipped' ? '<skipped/>' : '';
247
+ cases.push(`<testcase name="${name}" time="${time}">${body}</testcase>`);
248
+ }
249
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<testsuites><testsuite name="${esc(suite)}">${cases.join('')}</testsuite></testsuites>\n`;
250
+ }
251
+ /** Posts the results as JUnit when WT_CI_RUN_ID is set; never throws. */
252
+ export async function uploadResults(client, suite, tests) {
253
+ const env = process.env;
254
+ const runId = env.WT_CI_RUN_ID;
255
+ if (!client || !client.project || !runId || tests.length === 0)
256
+ return false;
257
+ const form = new FormData();
258
+ const fields = [
259
+ ['run_id', runId],
260
+ ['branch', env.WT_BRANCH || env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME || env.CI_COMMIT_REF_NAME],
261
+ ['sha', env.WT_SHA || env.GITHUB_SHA || env.CI_COMMIT_SHA],
262
+ ['suite', suite],
263
+ ];
264
+ for (const [k, v] of fields)
265
+ if (v)
266
+ form.append(k, v.slice(0, 200));
267
+ form.append('file', new Blob([toJunit(suite, tests)], { type: 'application/xml' }), 'junit.xml');
268
+ try {
269
+ const res = await client.fetch(projectUrl(client, 'test-runs'), { method: 'POST', headers: apiHeaders(client), body: form });
270
+ return res.ok;
271
+ }
272
+ catch (_e) {
273
+ return false;
274
+ }
275
+ }
276
+ // ---------------------------------------------------------------- Test Impact Analysis recording
277
+ let rootCache;
278
+ /** The repository top level (git diff paths are relative to it), else the working directory. */
279
+ function repoRoot() {
280
+ if (rootCache === undefined) {
281
+ try {
282
+ rootCache = execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 10_000 }).trim() || process.cwd();
283
+ }
284
+ catch (_e) {
285
+ rootCache = process.cwd();
286
+ }
287
+ }
288
+ return rootCache;
289
+ }
290
+ const repoRel = (f, root) => relative(root, f).split(sep).join('/');
291
+ /** Repository-relative files with an executed statement in an istanbul coverage object. */
292
+ export function coveredFiles(cov, root = repoRoot()) {
293
+ const out = new Set();
294
+ if (!cov || typeof cov !== 'object')
295
+ return [];
296
+ for (const [key, fc] of Object.entries(cov)) {
297
+ if (!fc || !fc.s || !Object.values(fc.s).some((n) => n > 0))
298
+ continue;
299
+ const f = repoRel(fc.path || key, root);
300
+ if (f && !f.startsWith('..'))
301
+ out.add(f);
302
+ }
303
+ return [...out].sort();
304
+ }
305
+ /**
306
+ * Uploads the coverage of one test file for its tests (`suite::rest` ids); never throws.
307
+ * Needs WT_API_URL, WT_PROJECT_ID and WT_API_KEY (the coverage map needs a project API key).
308
+ */
309
+ export async function uploadCoverage(file, ids, cov, fetchImpl = globalThis.fetch) {
310
+ const env = process.env;
311
+ const [api, project, key] = [env.WT_API_URL, env.WT_PROJECT_ID, env.WT_API_KEY];
312
+ if (!api || !project || !key || ids.length === 0)
313
+ return false;
314
+ const root = repoRoot();
315
+ const files = coveredFiles(cov, root);
316
+ if (file) {
317
+ const self = repoRel(file, root);
318
+ if (self && !self.startsWith('..') && !files.includes(self))
319
+ files.push(self);
320
+ }
321
+ const tests = [...new Set(ids)].slice(0, 20_000).map((id) => {
322
+ const i = id.indexOf('::');
323
+ return { suite: i < 0 ? '' : id.slice(0, i), test: i < 0 ? id : id.slice(i + 2), files: files.slice(0, 2000) };
324
+ });
325
+ try {
326
+ const res = await fetchImpl(`${api.replace(/\/+$/, '')}/v1/projects/${encodeURIComponent(project)}/tests/coverage-map`, {
327
+ method: 'PUT',
328
+ headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
329
+ body: JSON.stringify({ sha: (env.WT_SHA || env.GITHUB_SHA || env.CI_COMMIT_SHA || '').slice(0, 64), tests }),
330
+ });
331
+ return res.ok;
332
+ }
333
+ catch (_e) {
334
+ return false;
335
+ }
336
+ }
@@ -0,0 +1,27 @@
1
+ import type { ReporterOptions } from './reporter-core.js';
2
+ import type { TestDecision } from './test-plan.js';
3
+ /** The slice of Vitest's task tree this reporter reads. */
4
+ export interface VitestTask {
5
+ type?: string;
6
+ name: string;
7
+ filepath?: string;
8
+ mode?: string;
9
+ meta?: {
10
+ wt?: TestDecision;
11
+ wtQuarantinedFailure?: string;
12
+ };
13
+ result?: {
14
+ state?: string;
15
+ duration?: number;
16
+ retryCount?: number;
17
+ errors?: {
18
+ message?: string;
19
+ }[];
20
+ };
21
+ tasks?: VitestTask[];
22
+ }
23
+ export default class WatchtowerVitestReporter {
24
+ private readonly client;
25
+ constructor(options?: ReporterOptions);
26
+ onFinished(files?: VitestTask[]): Promise<void>;
27
+ }
@@ -0,0 +1,48 @@
1
+ // Vitest reporter: `reporters: ['default', ['@watchtowerobservability/node/vitest', { /* apiKey, client, ... */ }]]`
2
+ // (or `new WatchtowerVitestReporter(opts)` in vitest.config). Reads the file/task tree handed to
3
+ // `onFinished`, which every Vitest version still calls. With the test-plan setup (test-plan.ts) it
4
+ // also reports quarantined failures and retries, and uploads JUnit when WT_CI_RUN_ID is set.
5
+ import { clientFor, reportTests, outcome } from './reporter-core.js';
6
+ import { suiteName, testId, uploadResults } from './test-plan.js';
7
+ function collect(task, names, file, out, end) {
8
+ // a file task's name is its path; keep it out of test names
9
+ const path = task.filepath ? [] : [...names, task.name];
10
+ const f = task.filepath || file;
11
+ if (task.type === 'test' || task.type === 'custom') {
12
+ const r = task.result || {};
13
+ const wt = task.meta?.wt;
14
+ const qFail = task.meta?.wtQuarantinedFailure;
15
+ const retried = r.retryCount || 0;
16
+ out.push({
17
+ name: path.join(' '),
18
+ id: testId(suiteName('vitest'), f, path),
19
+ outcome: qFail ? 'failed' : outcome(task.mode === 'skip' || task.mode === 'todo' ? 'skip' : r.state),
20
+ durationMs: Math.round(r.duration || 0),
21
+ message: qFail || (r.errors && r.errors[0] && r.errors[0].message),
22
+ endMs: end,
23
+ quarantined: qFail ? wt?.quarantined || 'no ticket' : undefined,
24
+ isNew: wt?.isNew,
25
+ // every retry before the final attempt was a failure
26
+ attempts: r.state === 'fail' || r.state === 'pass' ? retried : 0,
27
+ });
28
+ return;
29
+ }
30
+ for (const t of task.tasks || [])
31
+ collect(t, path, f, out, end);
32
+ }
33
+ export default class WatchtowerVitestReporter {
34
+ client;
35
+ constructor(options) {
36
+ this.client = clientFor(options);
37
+ }
38
+ async onFinished(files) {
39
+ const tests = [];
40
+ const end = Date.now();
41
+ for (const f of files || [])
42
+ collect(f, [], undefined, tests, end);
43
+ await reportTests(this.client, tests, 'vitest');
44
+ await uploadResults(this.client, suiteName('vitest'), tests);
45
+ if (this.client)
46
+ await this.client.shutdown().catch(() => { });
47
+ }
48
+ }