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