@warlock.js/core 4.13.0 → 4.14.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.
- package/CHANGELOG.md +98 -0
- package/esm/generations/add-command.action.mjs +18 -6
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/tests/index.d.mts +3 -2
- package/esm/tests/index.mjs +2 -2
- package/esm/tests/test-connectors-selection.d.mts +14 -0
- package/esm/tests/test-connectors-selection.d.mts.map +1 -0
- package/esm/tests/test-connectors-selection.mjs +72 -0
- package/esm/tests/test-connectors-selection.mjs.map +1 -0
- package/esm/tests/test-lifecycle-state.mjs +27 -0
- package/esm/tests/test-lifecycle-state.mjs.map +1 -0
- package/esm/tests/test-setup-timeout.mjs +53 -0
- package/esm/tests/test-setup-timeout.mjs.map +1 -0
- package/esm/tests/vitest-setup.d.mts +64 -8
- package/esm/tests/vitest-setup.d.mts.map +1 -1
- package/esm/tests/vitest-setup.mjs +317 -11
- package/esm/tests/vitest-setup.mjs.map +1 -1
- package/package.json +12 -12
- package/skills/test-http/SKILL.md +8 -2
- package/skills/test-service/SKILL.md +159 -20
|
@@ -1,14 +1,70 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { TestConnectorsSelection } from "./test-connectors-selection.mjs";
|
|
2
|
+
|
|
2
3
|
//#region ../core/src/tests/vitest-setup.d.ts
|
|
3
|
-
type
|
|
4
|
-
|
|
4
|
+
type TestSetupOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* Which connectors to start.
|
|
7
|
+
*
|
|
8
|
+
* Precedence is `explicit non-undefined option > tests.connectors config >
|
|
9
|
+
* true`. Omitting the property, or passing `undefined`, lets project config
|
|
10
|
+
* apply — so an optional variable that happens to be `undefined` cannot erase
|
|
11
|
+
* it.
|
|
12
|
+
*/
|
|
13
|
+
connectors?: TestConnectorsSelection;
|
|
5
14
|
};
|
|
6
15
|
/**
|
|
7
|
-
*
|
|
16
|
+
* Raised by the lifecycle itself, never by the runtime it manages — a conflict
|
|
17
|
+
* between two calls, or a refusal to reuse a runtime that did not close.
|
|
8
18
|
*/
|
|
9
|
-
declare
|
|
10
|
-
|
|
11
|
-
}
|
|
19
|
+
declare class TestLifecycleError extends Error {
|
|
20
|
+
constructor(message: string);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Bootstrap the test runtime and start the selected connectors.
|
|
24
|
+
*
|
|
25
|
+
* ⚠ Runs once per TEST FILE, not once per worker: `setupFiles` is executed for
|
|
26
|
+
* every file and its module registry is rebuilt with it, measured across both
|
|
27
|
+
* pools with isolation on and off. The lifecycle state lives on the runtime
|
|
28
|
+
* context rather than in this module precisely so that a rebuild cannot hide a
|
|
29
|
+
* runtime that is still up.
|
|
30
|
+
*
|
|
31
|
+
* Repeated calls:
|
|
32
|
+
*
|
|
33
|
+
* - concurrent calls with the same effective selection share one startup;
|
|
34
|
+
* - while ready, the same effective selection is a no-op;
|
|
35
|
+
* - while starting or ready, a DIFFERENT effective selection rejects and leaves
|
|
36
|
+
* the live runtime untouched;
|
|
37
|
+
* - a failed setup unwinds and returns to idle, so a clean retry is allowed;
|
|
38
|
+
* - after a successful `teardownTest`, a later setup may use a different
|
|
39
|
+
* selection.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* // let project config decide, falling back to the default set
|
|
43
|
+
* await setupTest();
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* // bootstrap only — no connectors, whatever config says
|
|
47
|
+
* await setupTest({ connectors: false });
|
|
48
|
+
*/
|
|
49
|
+
declare function setupTest(options?: TestSetupOptions): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Shut the test runtime down and release the lifecycle.
|
|
52
|
+
*
|
|
53
|
+
* - idle is a no-op;
|
|
54
|
+
* - concurrent calls share one attempt;
|
|
55
|
+
* - a call made while setup is still running waits for that attempt to settle,
|
|
56
|
+
* then closes the runtime if it succeeded;
|
|
57
|
+
* - the local "ready" state is always cleared, including when shutdown rejects;
|
|
58
|
+
* - a shutdown rejection is surfaced, never swallowed, and poisons the
|
|
59
|
+
* lifecycle — a reported close failure is not proof that anything closed, so
|
|
60
|
+
* later `setupTest` calls refuse until the worker is restarted or a retry
|
|
61
|
+
* fully succeeds.
|
|
62
|
+
*
|
|
63
|
+
* ⚠ Individual connector shutdown failures are caught and logged inside
|
|
64
|
+
* `connectorsManager.shutdown()`, so they never reach this function and never
|
|
65
|
+
* poison anything. This lifecycle can only surface what that layer reports.
|
|
66
|
+
*/
|
|
67
|
+
declare function teardownTest(): Promise<void>;
|
|
12
68
|
//#endregion
|
|
13
|
-
export { setupTest };
|
|
69
|
+
export { TestLifecycleError, TestSetupOptions, setupTest, teardownTest };
|
|
14
70
|
//# sourceMappingURL=vitest-setup.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vitest-setup.d.mts","names":[],"sources":["../../../../../../../core/src/tests/vitest-setup.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"vitest-setup.d.mts","names":[],"sources":["../../../../../../../core/src/tests/vitest-setup.ts"],"mappings":";;;KAoDY,gBAAA;EAAA;;;;AAS0B;AAOtC;;;EAPE,UAAA,GAAa,uBAAuB;AAAA;;;;AAQF;cADvB,kBAAA,SAA2B,KAAK;cACxB,OAAA;AAAA;;;;;;AAqC+C;AAgDpE;;;;AAA6C;;;;;;;;;;;;;;;;;iBAhDvB,SAAA,CAAU,OAAA,GAAU,gBAAA,GAAmB,OAAO;;;;;;;;;;;;;;;;;;iBAgD9C,YAAA,IAAgB,OAAO"}
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { config } from "../config/config-getter.mjs";
|
|
2
|
-
import "../config/index.mjs";
|
|
3
1
|
import { Application } from "../application/application.mjs";
|
|
4
2
|
import { bootstrap } from "../bootstrap.mjs";
|
|
5
3
|
import { connectorsManager } from "../connectors/connectors-manager.mjs";
|
|
@@ -7,30 +5,338 @@ import "../connectors/index.mjs";
|
|
|
7
5
|
import { warlockConfigManager } from "../warlock-config/warlock-config.manager.mjs";
|
|
8
6
|
import { filesOrchestrator } from "../dev-server/files-orchestrator.mjs";
|
|
9
7
|
import { loadConfigFiles } from "../config/load-config-files.mjs";
|
|
8
|
+
import { describeConnectorsSelection, isSameConnectorsSelection, normalizeConnectorNames, readRequestedConnectors, resolveEffectiveConnectors } from "./test-connectors-selection.mjs";
|
|
9
|
+
import { getTestLifecycleRegistry } from "./test-lifecycle-state.mjs";
|
|
10
|
+
import { DEFAULT_TEST_SETUP_TIMEOUT, describeExpiredSetup, readConfiguredSetupTimeout, scheduleRealTimeout } from "./test-setup-timeout.mjs";
|
|
10
11
|
|
|
11
12
|
//#region ../core/src/tests/vitest-setup.ts
|
|
12
|
-
let isSetupComplete = false;
|
|
13
13
|
/**
|
|
14
|
-
*
|
|
14
|
+
* Worker test lifecycle — `setupTest` / `teardownTest`.
|
|
15
|
+
*
|
|
16
|
+
* Implements `contracts/2026-08-12-test-worker-lifecycle.md`. The pair is
|
|
17
|
+
* context-scoped, not "once per worker": Vitest runs `setupFiles` before EVERY
|
|
18
|
+
* test file and rebuilds the module registry each time, so the harness that
|
|
19
|
+
* calls `setupTest` owns pairing it with `teardownTest` in the same runtime
|
|
20
|
+
* context.
|
|
21
|
+
*
|
|
22
|
+
* Ownership, stated once because teardown is wider than it looks:
|
|
23
|
+
*
|
|
24
|
+
* - the runtime assumes exclusive ownership of the process-local
|
|
25
|
+
* `connectorsManager` for its lifetime;
|
|
26
|
+
* - it owns the framework bootstrap, the application shutdown hooks, and the
|
|
27
|
+
* connectors it starts — including the `connectors: false` case, where
|
|
28
|
+
* bootstrap still registers hooks;
|
|
29
|
+
* - teardown is MANAGER-WIDE. `connectorsManager.shutdown()` has no selective
|
|
30
|
+
* ownership handle, so a lifecycle that started two connectors still closes
|
|
31
|
+
* every connector the manager holds. Mixing `setupTest` with manual connector
|
|
32
|
+
* startup in the same process is unsupported for exactly that reason.
|
|
33
|
+
* - HTTP global setup stays separately owned by `startHttpTestServer` /
|
|
34
|
+
* `stopHttpTestServer`.
|
|
15
35
|
*/
|
|
16
|
-
|
|
17
|
-
|
|
36
|
+
/**
|
|
37
|
+
* Raised by the lifecycle itself, never by the runtime it manages — a conflict
|
|
38
|
+
* between two calls, or a refusal to reuse a runtime that did not close.
|
|
39
|
+
*/
|
|
40
|
+
var TestLifecycleError = class extends Error {
|
|
41
|
+
constructor(message) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = "TestLifecycleError";
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const POISONED_MESSAGE = "setupTest() refuses to start a test runtime: an earlier teardownTest() reported a shutdown failure, so the connectors, ports and pools it owned are not known to be closed. Restart the Vitest worker before setting up again, or call teardownTest() to retry the shutdown — the lifecycle only returns to idle on a fully successful retry.";
|
|
47
|
+
/**
|
|
48
|
+
* Bootstrap the test runtime and start the selected connectors.
|
|
49
|
+
*
|
|
50
|
+
* ⚠ Runs once per TEST FILE, not once per worker: `setupFiles` is executed for
|
|
51
|
+
* every file and its module registry is rebuilt with it, measured across both
|
|
52
|
+
* pools with isolation on and off. The lifecycle state lives on the runtime
|
|
53
|
+
* context rather than in this module precisely so that a rebuild cannot hide a
|
|
54
|
+
* runtime that is still up.
|
|
55
|
+
*
|
|
56
|
+
* Repeated calls:
|
|
57
|
+
*
|
|
58
|
+
* - concurrent calls with the same effective selection share one startup;
|
|
59
|
+
* - while ready, the same effective selection is a no-op;
|
|
60
|
+
* - while starting or ready, a DIFFERENT effective selection rejects and leaves
|
|
61
|
+
* the live runtime untouched;
|
|
62
|
+
* - a failed setup unwinds and returns to idle, so a clean retry is allowed;
|
|
63
|
+
* - after a successful `teardownTest`, a later setup may use a different
|
|
64
|
+
* selection.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* // let project config decide, falling back to the default set
|
|
68
|
+
* await setupTest();
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* // bootstrap only — no connectors, whatever config says
|
|
72
|
+
* await setupTest({ connectors: false });
|
|
73
|
+
*/
|
|
74
|
+
async function setupTest(options) {
|
|
75
|
+
const registry = getTestLifecycleRegistry();
|
|
76
|
+
const requested = readRequestedConnectors(options?.connectors);
|
|
77
|
+
if (registry.state === "poisoned") throw new TestLifecycleError(POISONED_MESSAGE);
|
|
78
|
+
if (registry.state === "stopping" && registry.teardownAttempt) {
|
|
79
|
+
await settled(registry.teardownAttempt);
|
|
80
|
+
return setupTest(options);
|
|
81
|
+
}
|
|
82
|
+
if (registry.state === "ready") {
|
|
83
|
+
assertReadySelectionMatches(registry.activeSelection, requested);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (registry.state === "starting" && registry.setupAttempt) {
|
|
87
|
+
const attempt = registry.setupAttempt;
|
|
88
|
+
await assertPendingSetupMatches(attempt, requested);
|
|
89
|
+
return attempt.completion;
|
|
90
|
+
}
|
|
91
|
+
return startTestRuntime(requested);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Shut the test runtime down and release the lifecycle.
|
|
95
|
+
*
|
|
96
|
+
* - idle is a no-op;
|
|
97
|
+
* - concurrent calls share one attempt;
|
|
98
|
+
* - a call made while setup is still running waits for that attempt to settle,
|
|
99
|
+
* then closes the runtime if it succeeded;
|
|
100
|
+
* - the local "ready" state is always cleared, including when shutdown rejects;
|
|
101
|
+
* - a shutdown rejection is surfaced, never swallowed, and poisons the
|
|
102
|
+
* lifecycle — a reported close failure is not proof that anything closed, so
|
|
103
|
+
* later `setupTest` calls refuse until the worker is restarted or a retry
|
|
104
|
+
* fully succeeds.
|
|
105
|
+
*
|
|
106
|
+
* ⚠ Individual connector shutdown failures are caught and logged inside
|
|
107
|
+
* `connectorsManager.shutdown()`, so they never reach this function and never
|
|
108
|
+
* poison anything. This lifecycle can only surface what that layer reports.
|
|
109
|
+
*/
|
|
110
|
+
async function teardownTest() {
|
|
111
|
+
const registry = getTestLifecycleRegistry();
|
|
112
|
+
if (registry.state === "stopping" && registry.teardownAttempt) return registry.teardownAttempt;
|
|
113
|
+
if (registry.state === "starting" && registry.setupAttempt) {
|
|
114
|
+
await settled(registry.setupAttempt.completion);
|
|
115
|
+
return teardownTest();
|
|
116
|
+
}
|
|
117
|
+
if (registry.state === "idle") return;
|
|
118
|
+
registry.state = "stopping";
|
|
119
|
+
const attempt = Promise.resolve().then(() => runTestRuntimeShutdown());
|
|
120
|
+
registry.teardownAttempt = attempt;
|
|
121
|
+
return attempt;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Arm the hang guard for one setup attempt.
|
|
125
|
+
*
|
|
126
|
+
* Armed at the default BEFORE the attempt runs, because `tests.setupTimeout` is
|
|
127
|
+
* not readable until the attempt has loaded config — and loading config is
|
|
128
|
+
* itself one of the steps that can hang. `rearm` then narrows or widens it the
|
|
129
|
+
* moment config arrives.
|
|
130
|
+
*/
|
|
131
|
+
function armSetupBound(registry) {
|
|
132
|
+
const schedule = registry.scheduleTimeout ?? scheduleRealTimeout;
|
|
133
|
+
const armedAt = Date.now();
|
|
134
|
+
let handle;
|
|
135
|
+
let expired = false;
|
|
136
|
+
let closed = false;
|
|
137
|
+
let expire = () => void 0;
|
|
138
|
+
const expiry = new Promise((_resolve, reject) => {
|
|
139
|
+
expire = reject;
|
|
140
|
+
});
|
|
141
|
+
expiry.catch(() => void 0);
|
|
142
|
+
const expireNow = (bound) => {
|
|
143
|
+
if (closed) return;
|
|
144
|
+
closed = true;
|
|
145
|
+
expired = true;
|
|
146
|
+
handle?.cancel();
|
|
147
|
+
handle = void 0;
|
|
148
|
+
expire(new TestLifecycleError(describeExpiredSetup(bound)));
|
|
149
|
+
};
|
|
150
|
+
const armFor = (bound, delay) => {
|
|
151
|
+
if (closed) return;
|
|
152
|
+
handle?.cancel();
|
|
153
|
+
if (delay <= 0) {
|
|
154
|
+
expireNow(bound);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
handle = schedule(delay, () => expireNow(bound));
|
|
158
|
+
};
|
|
159
|
+
const initialBound = registry.setupTimeoutOverride ?? 12e4;
|
|
160
|
+
armFor(initialBound, initialBound);
|
|
161
|
+
return {
|
|
162
|
+
expiry,
|
|
163
|
+
rearm: (next) => armFor(next, next - (Date.now() - armedAt)),
|
|
164
|
+
settle: () => {
|
|
165
|
+
closed = true;
|
|
166
|
+
handle?.cancel();
|
|
167
|
+
handle = void 0;
|
|
168
|
+
},
|
|
169
|
+
hasExpired: () => expired
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Race one setup attempt against its bound.
|
|
174
|
+
*
|
|
175
|
+
* The losing attempt is NOT cancellable — nothing here can interrupt a bootstrap
|
|
176
|
+
* stuck in a socket connect — so when the bound wins, the lifecycle is poisoned
|
|
177
|
+
* and every later state write from that abandoned attempt is dropped. That
|
|
178
|
+
* dropping happens in `runTestRuntimeStartup`, guarded on `hasExpired()`;
|
|
179
|
+
* without it the still-running attempt would quietly overwrite `poisoned` with
|
|
180
|
+
* `ready` or `idle` and hand the next caller a runtime nobody owns.
|
|
181
|
+
*/
|
|
182
|
+
async function awaitSetupWithinBound(attempt, bound, registry) {
|
|
183
|
+
try {
|
|
184
|
+
await Promise.race([attempt, bound.expiry]);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (bound.hasExpired()) {
|
|
187
|
+
registry.state = "poisoned";
|
|
188
|
+
registry.activeSelection = void 0;
|
|
189
|
+
registry.setupAttempt = void 0;
|
|
190
|
+
}
|
|
191
|
+
throw error;
|
|
192
|
+
} finally {
|
|
193
|
+
bound.settle();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Open a new setup attempt and publish it before it runs.
|
|
198
|
+
*/
|
|
199
|
+
function startTestRuntime(requested) {
|
|
200
|
+
const registry = getTestLifecycleRegistry();
|
|
201
|
+
let publishEffectiveSelection = () => void 0;
|
|
202
|
+
let failEffectiveSelection = () => void 0;
|
|
203
|
+
const effectiveSelection = new Promise((resolve, reject) => {
|
|
204
|
+
publishEffectiveSelection = resolve;
|
|
205
|
+
failEffectiveSelection = reject;
|
|
206
|
+
});
|
|
207
|
+
effectiveSelection.catch(() => void 0);
|
|
208
|
+
const bound = armSetupBound(registry);
|
|
209
|
+
const attempt = Promise.resolve().then(() => runTestRuntimeStartup(requested, publishEffectiveSelection, failEffectiveSelection, bound));
|
|
210
|
+
attempt.catch(() => void 0);
|
|
211
|
+
const completion = awaitSetupWithinBound(attempt, bound, registry);
|
|
212
|
+
registry.state = "starting";
|
|
213
|
+
registry.setupAttempt = {
|
|
214
|
+
requested,
|
|
215
|
+
effectiveSelection,
|
|
216
|
+
completion
|
|
217
|
+
};
|
|
218
|
+
return completion;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* The startup attempt itself.
|
|
222
|
+
*
|
|
223
|
+
* On failure: best-effort unwind, reset bookkeeping, rethrow the ORIGINAL error
|
|
224
|
+
* unchanged. A cleanup failure is a secondary diagnostic and never replaces the
|
|
225
|
+
* cause the caller needs to read.
|
|
226
|
+
*/
|
|
227
|
+
async function runTestRuntimeStartup(requested, publishEffectiveSelection, failEffectiveSelection, bound) {
|
|
228
|
+
const registry = getTestLifecycleRegistry();
|
|
18
229
|
try {
|
|
19
230
|
Application.setEnvironment("test");
|
|
20
231
|
await warlockConfigManager.load();
|
|
21
232
|
await bootstrap();
|
|
22
233
|
await filesOrchestrator.init();
|
|
23
234
|
await loadConfigFiles(true);
|
|
24
|
-
const
|
|
25
|
-
if (
|
|
26
|
-
|
|
27
|
-
|
|
235
|
+
const configuredTimeout = readConfiguredSetupTimeout();
|
|
236
|
+
if (configuredTimeout !== void 0) bound.rearm(configuredTimeout);
|
|
237
|
+
const effectiveSelection = resolveEffectiveConnectors(requested);
|
|
238
|
+
if (!bound.hasExpired()) registry.activeSelection = effectiveSelection;
|
|
239
|
+
publishEffectiveSelection(effectiveSelection);
|
|
240
|
+
await startSelectedConnectors(effectiveSelection);
|
|
241
|
+
if (!bound.hasExpired()) {
|
|
242
|
+
registry.state = "ready";
|
|
243
|
+
registry.setupAttempt = void 0;
|
|
244
|
+
}
|
|
28
245
|
} catch (error) {
|
|
246
|
+
failEffectiveSelection(error);
|
|
247
|
+
await unwindPartialStartup();
|
|
248
|
+
if (!bound.hasExpired()) {
|
|
249
|
+
registry.state = "idle";
|
|
250
|
+
registry.activeSelection = void 0;
|
|
251
|
+
registry.setupAttempt = void 0;
|
|
252
|
+
}
|
|
29
253
|
console.error("[vitest-setup] Failed to setup test environment:", error);
|
|
30
254
|
throw error;
|
|
31
255
|
}
|
|
32
256
|
}
|
|
257
|
+
/**
|
|
258
|
+
* `false` means none at all. Everything else starts something: an array starts
|
|
259
|
+
* exactly those, and `true` starts the default set — all but http, which is the
|
|
260
|
+
* global setup's job and shared across every worker.
|
|
261
|
+
*/
|
|
262
|
+
async function startSelectedConnectors(selection) {
|
|
263
|
+
if (selection === false) return;
|
|
264
|
+
if (Array.isArray(selection)) {
|
|
265
|
+
await connectorsManager.start(normalizeConnectorNames(selection));
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
await connectorsManager.startWithout(["http"]);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Best-effort teardown of whatever a failed startup managed to start.
|
|
272
|
+
*
|
|
273
|
+
* Runs while an error is already in flight, so no step here may throw and every
|
|
274
|
+
* step is attempted independently.
|
|
275
|
+
*/
|
|
276
|
+
async function unwindPartialStartup() {
|
|
277
|
+
await attemptCleanupStep("application shutdown hooks", () => Application.runShutdownHooks());
|
|
278
|
+
await attemptCleanupStep("connectors shutdown", () => connectorsManager.shutdown());
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Run one cleanup step, isolating its failure so the next step still runs.
|
|
282
|
+
*/
|
|
283
|
+
async function attemptCleanupStep(step, run) {
|
|
284
|
+
try {
|
|
285
|
+
await run();
|
|
286
|
+
} catch (error) {
|
|
287
|
+
console.error(`[vitest-setup] Cleanup after a failed setup did not complete (${step}):`, error);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* The teardown attempt itself.
|
|
292
|
+
*/
|
|
293
|
+
async function runTestRuntimeShutdown() {
|
|
294
|
+
const registry = getTestLifecycleRegistry();
|
|
295
|
+
let shutdownSucceeded = false;
|
|
296
|
+
try {
|
|
297
|
+
await connectorsManager.shutdown();
|
|
298
|
+
shutdownSucceeded = true;
|
|
299
|
+
} finally {
|
|
300
|
+
registry.activeSelection = void 0;
|
|
301
|
+
registry.setupAttempt = void 0;
|
|
302
|
+
registry.teardownAttempt = void 0;
|
|
303
|
+
registry.state = shutdownSucceeded ? "idle" : "poisoned";
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Reject when a ready runtime was set up with a different selection.
|
|
308
|
+
*/
|
|
309
|
+
function assertReadySelectionMatches(activeSelection, requested) {
|
|
310
|
+
if (activeSelection === void 0) return;
|
|
311
|
+
assertSelectionsMatch(activeSelection, resolveEffectiveConnectors(requested));
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Reject when an in-flight setup attempt is starting a different selection.
|
|
315
|
+
*/
|
|
316
|
+
async function assertPendingSetupMatches(attempt, requested) {
|
|
317
|
+
const pending = attempt.requested;
|
|
318
|
+
if (!pending.isExplicit && !requested.isExplicit) return;
|
|
319
|
+
if (pending.isExplicit && requested.isExplicit) {
|
|
320
|
+
assertSelectionsMatch(pending.selection, requested.selection);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
assertSelectionsMatch(await attempt.effectiveSelection, resolveEffectiveConnectors(requested));
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Name both selections: a caller looking at this message has to be able to tell
|
|
327
|
+
* which call to change without reading the framework's source.
|
|
328
|
+
*/
|
|
329
|
+
function assertSelectionsMatch(activeSelection, requestedSelection) {
|
|
330
|
+
if (isSameConnectorsSelection(activeSelection, requestedSelection)) return;
|
|
331
|
+
throw new TestLifecycleError(`setupTest() is already using ${describeConnectorsSelection(activeSelection)}, and this call asked for ${describeConnectorsSelection(requestedSelection)}. One test runtime serves one connector selection — call teardownTest() before setting up a different one.`);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Await an attempt for its state transition only, not its result.
|
|
335
|
+
*/
|
|
336
|
+
function settled(attempt) {
|
|
337
|
+
return attempt.catch(() => void 0);
|
|
338
|
+
}
|
|
33
339
|
|
|
34
340
|
//#endregion
|
|
35
|
-
export { setupTest };
|
|
341
|
+
export { TestLifecycleError, setupTest, teardownTest };
|
|
36
342
|
//# sourceMappingURL=vitest-setup.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vitest-setup.mjs","names":[],"sources":["../../../../../../../core/src/tests/vitest-setup.ts"],"sourcesContent":["/**\n * Vitest Setup File\n *\n * This file runs in each Vitest worker thread before tests execute.\n * It bootstraps the framework and starts necessary connectors so tests\n * have access to database connections and other shared resources.\n */\nimport { GenericObject } from \"@mongez/reinforcements\";\nimport { Application } from \"../application/application\";\nimport { bootstrap } from \"../bootstrap\";\nimport { config } from \"../config\";\nimport { loadConfigFiles } from \"../config/load-config-files\";\nimport { ConnectorName, connectorsManager } from \"../connectors\";\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\n\n// Global flag to prevent duplicate setup within the same worker\nlet isSetupComplete = false;\n\ntype TestSetup = {\n connectors?: boolean | ConnectorName[];\n};\n\n/**\n * Setup function that runs once per worker thread\n */\nexport async function setupTest({ connectors = true }: TestSetup = {}) {\n // Skip if already set up in this worker\n if (isSetupComplete) {\n return;\n }\n\n try {\n // 1. Set environment to test\n Application.setEnvironment(\"test\");\n\n await warlockConfigManager.load();\n await bootstrap();\n\n await filesOrchestrator.init();\n await loadConfigFiles(true);\n\n // 2. Load test configuration.\n //\n // The default matters: `config.get` resolves an absent key to its default,\n // and ITS default is `null` — not `{}`. `warlock add test` does not generate\n // `src/config/tests.ts`, so reading `.connectors` off the result threw\n // \"Cannot read properties of null\" on the generated default path.\n const testConfig = config.get<GenericObject>(\"tests\", {});\n\n // 3. Choose the connectors.\n //\n // `??`, not `||`: `false` is a meaningful configured value (\"start none\")\n // and `||` discarded it, falling through to the branch that starts\n // everything. The type and the skill both document `false` as \"start none\",\n // so the old behaviour was the exact opposite of the promise.\n const connectorsToStart = testConfig?.connectors ?? connectors;\n\n // `false` means none at all. Everything else starts something: an array\n // starts exactly those, and `true` starts all but http — http is the global\n // setup's job, shared across every worker.\n if (connectorsToStart !== false) {\n if (Array.isArray(connectorsToStart)) {\n await connectorsManager.start(connectorsToStart);\n } else {\n await connectorsManager.startWithout([\"http\"]);\n }\n }\n\n // Set even when no connectors were started: setup DID complete, and a second\n // call in the same worker must stay a no-op either way.\n isSetupComplete = true;\n } catch (error) {\n console.error(\"[vitest-setup] Failed to setup test environment:\", error);\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;AAiBA,IAAI,kBAAkB;;;;AAStB,eAAsB,UAAU,EAAE,aAAa,SAAoB,CAAC,GAAG;CAErE,IAAI,iBACF;CAGF,IAAI;EAEF,YAAY,eAAe,MAAM;EAEjC,MAAM,qBAAqB,KAAK;EAChC,MAAM,UAAU;EAEhB,MAAM,kBAAkB,KAAK;EAC7B,MAAM,gBAAgB,IAAI;EAgB1B,MAAM,oBARa,OAAO,IAAmB,SAAS,CAAC,CAQpB,CAAC,EAAE,cAAc;EAKpD,IAAI,sBAAsB,OACxB,IAAI,MAAM,QAAQ,iBAAiB,GACjC,MAAM,kBAAkB,MAAM,iBAAiB;OAE/C,MAAM,kBAAkB,aAAa,CAAC,MAAM,CAAC;EAMjD,kBAAkB;CACpB,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;EACvE,MAAM;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"vitest-setup.mjs","names":[],"sources":["../../../../../../../core/src/tests/vitest-setup.ts"],"sourcesContent":["/**\r\n * Worker test lifecycle — `setupTest` / `teardownTest`.\r\n *\r\n * Implements `contracts/2026-08-12-test-worker-lifecycle.md`. The pair is\r\n * context-scoped, not \"once per worker\": Vitest runs `setupFiles` before EVERY\r\n * test file and rebuilds the module registry each time, so the harness that\r\n * calls `setupTest` owns pairing it with `teardownTest` in the same runtime\r\n * context.\r\n *\r\n * Ownership, stated once because teardown is wider than it looks:\r\n *\r\n * - the runtime assumes exclusive ownership of the process-local\r\n * `connectorsManager` for its lifetime;\r\n * - it owns the framework bootstrap, the application shutdown hooks, and the\r\n * connectors it starts — including the `connectors: false` case, where\r\n * bootstrap still registers hooks;\r\n * - teardown is MANAGER-WIDE. `connectorsManager.shutdown()` has no selective\r\n * ownership handle, so a lifecycle that started two connectors still closes\r\n * every connector the manager holds. Mixing `setupTest` with manual connector\r\n * startup in the same process is unsupported for exactly that reason.\r\n * - HTTP global setup stays separately owned by `startHttpTestServer` /\r\n * `stopHttpTestServer`.\r\n */\r\nimport { Application } from \"../application/application\";\r\nimport { bootstrap } from \"../bootstrap\";\r\nimport { loadConfigFiles } from \"../config/load-config-files\";\r\nimport { connectorsManager } from \"../connectors\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport {\r\n describeConnectorsSelection,\r\n isSameConnectorsSelection,\r\n normalizeConnectorNames,\r\n readRequestedConnectors,\r\n resolveEffectiveConnectors,\r\n} from \"./test-connectors-selection\";\r\nimport type {\r\n RequestedTestConnectors,\r\n TestConnectorsSelection,\r\n} from \"./test-connectors-selection\";\r\nimport { getTestLifecycleRegistry } from \"./test-lifecycle-state\";\r\nimport type { TestLifecycleRegistry, TestSetupAttempt } from \"./test-lifecycle-state\";\r\nimport {\r\n DEFAULT_TEST_SETUP_TIMEOUT,\r\n describeExpiredSetup,\r\n readConfiguredSetupTimeout,\r\n scheduleRealTimeout,\r\n} from \"./test-setup-timeout\";\r\nimport type { TestTimeoutHandle } from \"./test-setup-timeout\";\r\n\r\nexport type { TestConnectorsSelection } from \"./test-connectors-selection\";\r\n\r\nexport type TestSetupOptions = {\r\n /**\r\n * Which connectors to start.\r\n *\r\n * Precedence is `explicit non-undefined option > tests.connectors config >\r\n * true`. Omitting the property, or passing `undefined`, lets project config\r\n * apply — so an optional variable that happens to be `undefined` cannot erase\r\n * it.\r\n */\r\n connectors?: TestConnectorsSelection;\r\n};\r\n\r\n/**\r\n * Raised by the lifecycle itself, never by the runtime it manages — a conflict\r\n * between two calls, or a refusal to reuse a runtime that did not close.\r\n */\r\nexport class TestLifecycleError extends Error {\r\n public constructor(message: string) {\r\n super(message);\r\n\r\n this.name = \"TestLifecycleError\";\r\n }\r\n}\r\n\r\nconst POISONED_MESSAGE =\r\n \"setupTest() refuses to start a test runtime: an earlier teardownTest() reported a shutdown failure, so the connectors, ports and pools it owned are not known to be closed. Restart the Vitest worker before setting up again, or call teardownTest() to retry the shutdown — the lifecycle only returns to idle on a fully successful retry.\";\r\n\r\n/**\r\n * Bootstrap the test runtime and start the selected connectors.\r\n *\r\n * ⚠ Runs once per TEST FILE, not once per worker: `setupFiles` is executed for\r\n * every file and its module registry is rebuilt with it, measured across both\r\n * pools with isolation on and off. The lifecycle state lives on the runtime\r\n * context rather than in this module precisely so that a rebuild cannot hide a\r\n * runtime that is still up.\r\n *\r\n * Repeated calls:\r\n *\r\n * - concurrent calls with the same effective selection share one startup;\r\n * - while ready, the same effective selection is a no-op;\r\n * - while starting or ready, a DIFFERENT effective selection rejects and leaves\r\n * the live runtime untouched;\r\n * - a failed setup unwinds and returns to idle, so a clean retry is allowed;\r\n * - after a successful `teardownTest`, a later setup may use a different\r\n * selection.\r\n *\r\n * @example\r\n * // let project config decide, falling back to the default set\r\n * await setupTest();\r\n *\r\n * @example\r\n * // bootstrap only — no connectors, whatever config says\r\n * await setupTest({ connectors: false });\r\n */\r\nexport async function setupTest(options?: TestSetupOptions): Promise<void> {\r\n const registry = getTestLifecycleRegistry();\r\n const requested = readRequestedConnectors(options?.connectors);\r\n\r\n if (registry.state === \"poisoned\") {\r\n throw new TestLifecycleError(POISONED_MESSAGE);\r\n }\r\n\r\n if (registry.state === \"stopping\" && registry.teardownAttempt) {\r\n await settled(registry.teardownAttempt);\r\n\r\n return setupTest(options);\r\n }\r\n\r\n if (registry.state === \"ready\") {\r\n assertReadySelectionMatches(registry.activeSelection, requested);\r\n\r\n return;\r\n }\r\n\r\n if (registry.state === \"starting\" && registry.setupAttempt) {\r\n const attempt = registry.setupAttempt;\r\n\r\n await assertPendingSetupMatches(attempt, requested);\r\n\r\n return attempt.completion;\r\n }\r\n\r\n return startTestRuntime(requested);\r\n}\r\n\r\n/**\r\n * Shut the test runtime down and release the lifecycle.\r\n *\r\n * - idle is a no-op;\r\n * - concurrent calls share one attempt;\r\n * - a call made while setup is still running waits for that attempt to settle,\r\n * then closes the runtime if it succeeded;\r\n * - the local \"ready\" state is always cleared, including when shutdown rejects;\r\n * - a shutdown rejection is surfaced, never swallowed, and poisons the\r\n * lifecycle — a reported close failure is not proof that anything closed, so\r\n * later `setupTest` calls refuse until the worker is restarted or a retry\r\n * fully succeeds.\r\n *\r\n * ⚠ Individual connector shutdown failures are caught and logged inside\r\n * `connectorsManager.shutdown()`, so they never reach this function and never\r\n * poison anything. This lifecycle can only surface what that layer reports.\r\n */\r\nexport async function teardownTest(): Promise<void> {\r\n const registry = getTestLifecycleRegistry();\r\n\r\n if (registry.state === \"stopping\" && registry.teardownAttempt) {\r\n return registry.teardownAttempt;\r\n }\r\n\r\n if (registry.state === \"starting\" && registry.setupAttempt) {\r\n // A runtime that is still opening cannot be closed halfway. Wait for the\r\n // attempt to settle: a failed one has already unwound itself and left the\r\n // lifecycle idle, which the re-entry below then reads as \"nothing to do\".\r\n await settled(registry.setupAttempt.completion);\r\n\r\n return teardownTest();\r\n }\r\n\r\n if (registry.state === \"idle\") {\r\n return;\r\n }\r\n\r\n registry.state = \"stopping\";\r\n\r\n // Deferred by a microtask so the registry is fully published before the\r\n // attempt's first line runs — a synchronous throw would otherwise reach the\r\n // `finally` below, and reset the state, before this function had recorded\r\n // that a teardown was in flight at all.\r\n const attempt = Promise.resolve().then(() => runTestRuntimeShutdown());\r\n\r\n registry.teardownAttempt = attempt;\r\n\r\n return attempt;\r\n}\r\n\r\n/**\r\n * The setup attempt's hang guard, as the lifecycle consumes it.\r\n *\r\n * The bound's POLICY — the default, the config key, the message — lives in\r\n * `test-setup-timeout.ts`. What expiry MEANS lives here.\r\n *\r\n * @internal\r\n */\r\ntype SetupBound = {\r\n /**\r\n * Rejects with the expiry error. Never resolves: the attempt is the only side\r\n * of the race that can succeed.\r\n */\r\n readonly expiry: Promise<never>;\r\n\r\n /**\r\n * Re-aim the bound at `next` ms measured from when the ATTEMPT STARTED, once\r\n * config has made `tests.setupTimeout` readable.\r\n */\r\n rearm(next: number): void;\r\n\r\n /** The race is over — cancel whatever timer is still pending. */\r\n settle(): void;\r\n\r\n /** Whether the bound, rather than the attempt, won the race. */\r\n hasExpired(): boolean;\r\n};\r\n\r\n/**\r\n * Arm the hang guard for one setup attempt.\r\n *\r\n * Armed at the default BEFORE the attempt runs, because `tests.setupTimeout` is\r\n * not readable until the attempt has loaded config — and loading config is\r\n * itself one of the steps that can hang. `rearm` then narrows or widens it the\r\n * moment config arrives.\r\n */\r\nfunction armSetupBound(registry: TestLifecycleRegistry): SetupBound {\r\n const schedule = registry.scheduleTimeout ?? scheduleRealTimeout;\r\n const armedAt = Date.now();\r\n\r\n let handle: TestTimeoutHandle | undefined;\r\n let expired = false;\r\n let closed = false;\r\n let expire: (error: unknown) => void = () => undefined;\r\n\r\n const expiry = new Promise<never>((_resolve, reject) => {\r\n expire = reject;\r\n });\r\n\r\n // Only `awaitSetupWithinBound` observes this, and only until the attempt wins\r\n // — after that nobody is listening, and an unobserved rejection surfaces as an\r\n // unhandled rejection that fails an unrelated test file. Same reason as the\r\n // `effectiveSelection` barrier below.\r\n expiry.catch(() => undefined);\r\n\r\n const expireNow = (bound: number): void => {\r\n if (closed) {\r\n return;\r\n }\r\n\r\n closed = true;\r\n expired = true;\r\n\r\n handle?.cancel();\r\n handle = undefined;\r\n\r\n expire(new TestLifecycleError(describeExpiredSetup(bound)));\r\n };\r\n\r\n const armFor = (bound: number, delay: number): void => {\r\n if (closed) {\r\n return;\r\n }\r\n\r\n handle?.cancel();\r\n\r\n // Already overdue. A bound the attempt has ALREADY exceeded must fire now,\r\n // not be rescheduled for time that was spent before it was known.\r\n if (delay <= 0) {\r\n expireNow(bound);\r\n\r\n return;\r\n }\r\n\r\n handle = schedule(delay, () => expireNow(bound));\r\n };\r\n\r\n const initialBound = registry.setupTimeoutOverride ?? DEFAULT_TEST_SETUP_TIMEOUT;\r\n\r\n armFor(initialBound, initialBound);\r\n\r\n return {\r\n expiry,\r\n\r\n // Measured from `armedAt`, never from now: adding a configured bound to the\r\n // time already spent would make the real bound default-plus-configured, and\r\n // a project that lowered the key would get a LONGER guard than the default.\r\n rearm: (next) => armFor(next, next - (Date.now() - armedAt)),\r\n\r\n settle: () => {\r\n closed = true;\r\n\r\n handle?.cancel();\r\n handle = undefined;\r\n },\r\n\r\n hasExpired: () => expired,\r\n };\r\n}\r\n\r\n/**\r\n * Race one setup attempt against its bound.\r\n *\r\n * The losing attempt is NOT cancellable — nothing here can interrupt a bootstrap\r\n * stuck in a socket connect — so when the bound wins, the lifecycle is poisoned\r\n * and every later state write from that abandoned attempt is dropped. That\r\n * dropping happens in `runTestRuntimeStartup`, guarded on `hasExpired()`;\r\n * without it the still-running attempt would quietly overwrite `poisoned` with\r\n * `ready` or `idle` and hand the next caller a runtime nobody owns.\r\n */\r\nasync function awaitSetupWithinBound(\r\n attempt: Promise<void>,\r\n bound: SetupBound,\r\n registry: TestLifecycleRegistry,\r\n): Promise<void> {\r\n try {\r\n await Promise.race([attempt, bound.expiry]);\r\n } catch (error) {\r\n if (bound.hasExpired()) {\r\n registry.state = \"poisoned\";\r\n registry.activeSelection = undefined;\r\n registry.setupAttempt = undefined;\r\n }\r\n\r\n throw error;\r\n } finally {\r\n bound.settle();\r\n }\r\n}\r\n\r\n/**\r\n * Open a new setup attempt and publish it before it runs.\r\n */\r\nfunction startTestRuntime(requested: RequestedTestConnectors): Promise<void> {\r\n const registry = getTestLifecycleRegistry();\r\n\r\n let publishEffectiveSelection: (selection: TestConnectorsSelection) => void = () => undefined;\r\n let failEffectiveSelection: (error: unknown) => void = () => undefined;\r\n\r\n const effectiveSelection = new Promise<TestConnectorsSelection>((resolve, reject) => {\r\n publishEffectiveSelection = resolve;\r\n failEffectiveSelection = reject;\r\n });\r\n\r\n // Only the mixed explicit/config comparison ever awaits this barrier, so its\r\n // rejection is usually unobserved — and an unobserved rejection would surface\r\n // as an unhandled rejection and fail an unrelated test file.\r\n effectiveSelection.catch(() => undefined);\r\n\r\n const bound = armSetupBound(registry);\r\n\r\n const attempt = Promise.resolve().then(() =>\r\n runTestRuntimeStartup(requested, publishEffectiveSelection, failEffectiveSelection, bound),\r\n );\r\n\r\n // The attempt outlives a bound that beat it, and by then `completion` has\r\n // already rejected with the expiry error — so the attempt's own late rejection\r\n // has no observer. Same unhandled-rejection hazard as above.\r\n attempt.catch(() => undefined);\r\n\r\n // `teardownTest` waits on this same promise, which is how a teardown requested\r\n // during setup inherits the bound. There is deliberately no second timer and\r\n // no separate teardown deadline.\r\n const completion = awaitSetupWithinBound(attempt, bound, registry);\r\n\r\n registry.state = \"starting\";\r\n registry.setupAttempt = { requested, effectiveSelection, completion };\r\n\r\n return completion;\r\n}\r\n\r\n/**\r\n * The startup attempt itself.\r\n *\r\n * On failure: best-effort unwind, reset bookkeeping, rethrow the ORIGINAL error\r\n * unchanged. A cleanup failure is a secondary diagnostic and never replaces the\r\n * cause the caller needs to read.\r\n */\r\nasync function runTestRuntimeStartup(\r\n requested: RequestedTestConnectors,\r\n publishEffectiveSelection: (selection: TestConnectorsSelection) => void,\r\n failEffectiveSelection: (error: unknown) => void,\r\n bound: SetupBound,\r\n): Promise<void> {\r\n const registry = getTestLifecycleRegistry();\r\n\r\n try {\r\n Application.setEnvironment(\"test\");\r\n\r\n await warlockConfigManager.load();\r\n await bootstrap();\r\n\r\n await filesOrchestrator.init();\r\n await loadConfigFiles(true);\r\n\r\n // The first point at which `tests.setupTimeout` is readable at all. An\r\n // invalid value throws from here and takes the normal failure path — falling\r\n // back to the default would silently erase what the project configured.\r\n const configuredTimeout = readConfiguredSetupTimeout();\r\n\r\n if (configuredTimeout !== undefined) {\r\n bound.rearm(configuredTimeout);\r\n }\r\n\r\n // Resolved here and not at call time: the config layer is only readable once\r\n // the four steps above have run.\r\n const effectiveSelection = resolveEffectiveConnectors(requested);\r\n\r\n // Every state write below is conditional on this attempt still being the one\r\n // the lifecycle is waiting for. Once the bound has expired the lifecycle is\r\n // poisoned and this attempt is abandoned — it may still be running, but it\r\n // no longer speaks for the runtime.\r\n if (!bound.hasExpired()) {\r\n registry.activeSelection = effectiveSelection;\r\n }\r\n\r\n publishEffectiveSelection(effectiveSelection);\r\n\r\n await startSelectedConnectors(effectiveSelection);\r\n\r\n if (!bound.hasExpired()) {\r\n registry.state = \"ready\";\r\n registry.setupAttempt = undefined;\r\n }\r\n } catch (error) {\r\n failEffectiveSelection(error);\r\n\r\n await unwindPartialStartup();\r\n\r\n if (!bound.hasExpired()) {\r\n registry.state = \"idle\";\r\n registry.activeSelection = undefined;\r\n registry.setupAttempt = undefined;\r\n }\r\n\r\n console.error(\"[vitest-setup] Failed to setup test environment:\", error);\r\n\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * `false` means none at all. Everything else starts something: an array starts\r\n * exactly those, and `true` starts the default set — all but http, which is the\r\n * global setup's job and shared across every worker.\r\n */\r\nasync function startSelectedConnectors(selection: TestConnectorsSelection): Promise<void> {\r\n if (selection === false) {\r\n return;\r\n }\r\n\r\n if (Array.isArray(selection)) {\r\n await connectorsManager.start(normalizeConnectorNames(selection));\r\n\r\n return;\r\n }\r\n\r\n await connectorsManager.startWithout([\"http\"]);\r\n}\r\n\r\n/**\r\n * Best-effort teardown of whatever a failed startup managed to start.\r\n *\r\n * Runs while an error is already in flight, so no step here may throw and every\r\n * step is attempted independently.\r\n */\r\nasync function unwindPartialStartup(): Promise<void> {\r\n // Two steps rather than one: `connectorsManager.shutdown()` runs the\r\n // application hooks itself, but it runs them FIRST and does not isolate their\r\n // rejection — so a hook that rejects would take the connector teardown down\r\n // with it and leave every connector up. Both calls are idempotent, so running\r\n // the hooks on their own first costs nothing and means neither failure can\r\n // skip the other step.\r\n await attemptCleanupStep(\"application shutdown hooks\", () => Application.runShutdownHooks());\r\n await attemptCleanupStep(\"connectors shutdown\", () => connectorsManager.shutdown());\r\n}\r\n\r\n/**\r\n * Run one cleanup step, isolating its failure so the next step still runs.\r\n */\r\nasync function attemptCleanupStep(step: string, run: () => Promise<void>): Promise<void> {\r\n try {\r\n await run();\r\n } catch (error) {\r\n // Reported, not thrown — it is secondary to the startup error about to be\r\n // rethrown, and losing that one to this would be the worse outcome.\r\n console.error(`[vitest-setup] Cleanup after a failed setup did not complete (${step}):`, error);\r\n }\r\n}\r\n\r\n/**\r\n * The teardown attempt itself.\r\n */\r\nasync function runTestRuntimeShutdown(): Promise<void> {\r\n const registry = getTestLifecycleRegistry();\r\n let shutdownSucceeded = false;\r\n\r\n try {\r\n // Manager-wide, and deliberately called whatever the selection was: with\r\n // `connectors: false` nothing was started, but bootstrap still registered\r\n // application shutdown hooks, and the manager runs those first (see\r\n // `connectors-manager.ts` — `Application.runShutdownHooks()` is its first\r\n // line). Skipping the call to \"match\" an empty selection would leak them.\r\n await connectorsManager.shutdown();\r\n\r\n shutdownSucceeded = true;\r\n } finally {\r\n // In a `finally`, not after the `await`: a rejected shutdown must not leave\r\n // the lifecycle claiming a runtime it no longer owns. Poisoned rather than\r\n // idle, because a cleared flag does not prove that ports, sockets, pools or\r\n // timers closed.\r\n registry.activeSelection = undefined;\r\n registry.setupAttempt = undefined;\r\n registry.teardownAttempt = undefined;\r\n registry.state = shutdownSucceeded ? \"idle\" : \"poisoned\";\r\n }\r\n}\r\n\r\n/**\r\n * Reject when a ready runtime was set up with a different selection.\r\n */\r\nfunction assertReadySelectionMatches(\r\n activeSelection: TestConnectorsSelection | undefined,\r\n requested: RequestedTestConnectors,\r\n): void {\r\n if (activeSelection === undefined) {\r\n return;\r\n }\r\n\r\n // Config is loaded by the time anything is ready, so the config-derived layer\r\n // is resolvable right here.\r\n const requestedSelection = resolveEffectiveConnectors(requested);\r\n\r\n assertSelectionsMatch(activeSelection, requestedSelection);\r\n}\r\n\r\n/**\r\n * Reject when an in-flight setup attempt is starting a different selection.\r\n */\r\nasync function assertPendingSetupMatches(\r\n attempt: TestSetupAttempt,\r\n requested: RequestedTestConnectors,\r\n): Promise<void> {\r\n const pending = attempt.requested;\r\n\r\n // Two calls that both defer to project config resolve to the same thing by\r\n // construction — knowable without waiting for config to load.\r\n if (!pending.isExplicit && !requested.isExplicit) {\r\n return;\r\n }\r\n\r\n if (pending.isExplicit && requested.isExplicit) {\r\n assertSelectionsMatch(pending.selection, requested.selection);\r\n\r\n return;\r\n }\r\n\r\n // Mixed: one side is config-derived and config is not readable until the\r\n // running attempt has loaded it, so wait for that barrier first.\r\n const activeSelection = await attempt.effectiveSelection;\r\n const requestedSelection = resolveEffectiveConnectors(requested);\r\n\r\n assertSelectionsMatch(activeSelection, requestedSelection);\r\n}\r\n\r\n/**\r\n * Name both selections: a caller looking at this message has to be able to tell\r\n * which call to change without reading the framework's source.\r\n */\r\nfunction assertSelectionsMatch(\r\n activeSelection: TestConnectorsSelection,\r\n requestedSelection: TestConnectorsSelection,\r\n): void {\r\n if (isSameConnectorsSelection(activeSelection, requestedSelection)) {\r\n return;\r\n }\r\n\r\n throw new TestLifecycleError(\r\n `setupTest() is already using ${describeConnectorsSelection(activeSelection)}, and this call asked for ${describeConnectorsSelection(requestedSelection)}. One test runtime serves one connector selection — call teardownTest() before setting up a different one.`,\r\n );\r\n}\r\n\r\n/**\r\n * Await an attempt for its state transition only, not its result.\r\n */\r\nfunction settled(attempt: Promise<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",
|
|
39
|
-
"@warlock.js/auth": "4.
|
|
40
|
-
"@warlock.js/cache": "4.
|
|
41
|
-
"@warlock.js/cascade": "4.
|
|
42
|
-
"@warlock.js/context": "4.
|
|
43
|
-
"@warlock.js/logger": "4.
|
|
44
|
-
"@warlock.js/seal": "4.
|
|
45
|
-
"@warlock.js/fs": "4.
|
|
39
|
+
"@warlock.js/auth": "4.14.0",
|
|
40
|
+
"@warlock.js/cache": "4.14.0",
|
|
41
|
+
"@warlock.js/cascade": "4.14.0",
|
|
42
|
+
"@warlock.js/context": "4.14.0",
|
|
43
|
+
"@warlock.js/logger": "4.14.0",
|
|
44
|
+
"@warlock.js/seal": "4.14.0",
|
|
45
|
+
"@warlock.js/fs": "4.14.0",
|
|
46
46
|
"chokidar": "^5.0.0",
|
|
47
47
|
"dayjs": "^1.11.19",
|
|
48
48
|
"es-module-lexer": "^2.0.0",
|
|
@@ -68,15 +68,15 @@
|
|
|
68
68
|
"react": "^19.2.3",
|
|
69
69
|
"react-dom": "^19.2.3",
|
|
70
70
|
"@react-email/render": "^2.0.5",
|
|
71
|
-
"@warlock.js/herald": "4.
|
|
72
|
-
"@warlock.js/ai": "4.
|
|
73
|
-
"@warlock.js/access": "4.
|
|
74
|
-
"@warlock.js/notifications": "4.
|
|
71
|
+
"@warlock.js/herald": "4.14.0",
|
|
72
|
+
"@warlock.js/ai": "4.14.0",
|
|
73
|
+
"@warlock.js/access": "4.14.0",
|
|
74
|
+
"@warlock.js/notifications": "4.14.0"
|
|
75
75
|
},
|
|
76
76
|
"bin": {
|
|
77
77
|
"warlock": "bin/warlock.js"
|
|
78
78
|
},
|
|
79
|
-
"version": "4.
|
|
79
|
+
"version": "4.14.0",
|
|
80
80
|
"type": "module",
|
|
81
81
|
"main": "./esm/index.mjs",
|
|
82
82
|
"module": "./esm/index.mjs",
|
|
@@ -126,7 +126,7 @@ export default defineConfig({
|
|
|
126
126
|
plugins: [lowerStage3Decorators(), mongezVite()],
|
|
127
127
|
test: {
|
|
128
128
|
globalSetup: "./src/test-global-setup.ts", // ← starts the HTTP server
|
|
129
|
-
setupFiles: ["./src/test-setup.ts"], // ←
|
|
129
|
+
setupFiles: ["./src/test-setup.ts"], // ← setupTest + afterAll(teardownTest), per test file
|
|
130
130
|
environment: "node",
|
|
131
131
|
globals: false,
|
|
132
132
|
include: ["src/app/**/*.test.ts"],
|
|
@@ -134,7 +134,13 @@ export default defineConfig({
|
|
|
134
134
|
});
|
|
135
135
|
```
|
|
136
136
|
|
|
137
|
-
Both files (and this config, with `lowerStage3Decorators()` first so decorated models load) are created by `warlock add test`. The split is intentional: `globalSetup` runs ONCE in the main vitest process; `setupFiles` runs
|
|
137
|
+
Both files (and this config, with `lowerStage3Decorators()` first so decorated models load) are created by `warlock add test`. The split is intentional: `globalSetup` runs **ONCE** in the main vitest process; `setupFiles` runs **before every test file**.
|
|
138
|
+
|
|
139
|
+
⚠ **Corrected in 4.14.0.** This line previously said `setupFiles` runs "per worker thread". **It does not** — Vitest runs it before each test file, and the setup module's registry is rebuilt every time. Measured across all four `pool` × `isolate` combinations.
|
|
140
|
+
|
|
141
|
+
**So the service-layer framework is file-scoped: bootstrapped by `setupTest` and closed by the `afterAll(teardownTest)` the setup file registers, once per test file.** ⚠ **`setupTest` alone is not the whole wiring — the paired teardown is mandatory from 4.14.0**; see the `test-service` skill.
|
|
142
|
+
|
|
143
|
+
**HTTP is the exception and stays in `globalSetup`**, which genuinely does run once in the main vitest process and owns a real port. **That split is the point:** one server for the whole run, one framework per test file.
|
|
138
144
|
|
|
139
145
|
## HTTP request helpers
|
|
140
146
|
|