@fliwright/vitest 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fliwright contributors.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @fliwright/vitest
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Vitest fixtures for Fliwright Flutter E2E tests.
4
+
5
+ ```ts
6
+ import { expect, test } from '@fliwright/vitest';
7
+
8
+ test('increments the counter', async ({ page }) => {
9
+ await page.locator('text=Increment').click();
10
+ await expect(page.locator('text=Count: 1')).toBeVisible();
11
+ });
12
+ ```
13
+
14
+ Use `fliwright init` to create compatible configuration and a test-only Flutter
15
+ entrypoint. The current supported Vitest version is 5.0.5.
@@ -0,0 +1,73 @@
1
+ import { RunArtifactStore, TimelineArtifactStore, TimelineRecorder } from '@fliwright/core';
2
+ import type { FliwrightLogger, RecordingMode, RunSession, RunSessionResult, TimelineRunMode, TimelineNode } from '@fliwright/core';
3
+ import type { RunnerTask } from 'vitest';
4
+ import { FinalizationBudget } from './FinalizationBudget.js';
5
+ /** Shared by the runner and fixture module, including separate Vitest module graphs. */
6
+ export declare class AttemptContext {
7
+ readonly session: RunSession;
8
+ readonly runId: string;
9
+ readonly testId: string;
10
+ readonly testName: string;
11
+ readonly attemptId: string;
12
+ recorder: TimelineRecorder;
13
+ artifactStore: TimelineArtifactStore;
14
+ runStore: RunArtifactStore;
15
+ recordingMode: RecordingMode;
16
+ logger?: FliwrightLogger;
17
+ failureContextPath?: string;
18
+ validate?: () => Error | undefined;
19
+ /** aroundEach setup can skip before Vitest enters the attempt hooks. */
20
+ onSetupSkipped?: () => Promise<void>;
21
+ /** Automatic fixtures can resolve before onBeforeTryTask inside aroundEach. */
22
+ beforeFixtures?: () => Promise<void>;
23
+ runnerEntered: boolean;
24
+ readonly evidenceErrors: string[];
25
+ beforeFinish?: (signal: AbortSignal) => Promise<void>;
26
+ onFailure?: (error: unknown, node: TimelineNode, signal: AbortSignal) => Promise<void>;
27
+ readonly runnerErrors: NonNullable<RunSessionResult['runnerErrors']>;
28
+ private readonly failures;
29
+ private progressQueue;
30
+ private journal;
31
+ private progressClosed;
32
+ persistenceIncomplete: boolean;
33
+ private readonly progressController;
34
+ private readonly finalizationScope;
35
+ finalization: FinalizationBudget;
36
+ /** Reserve a small part of the same deadline for writing the terminal result. */
37
+ get persistenceReserveMs(): number;
38
+ get finalizationSignal(): AbortSignal | undefined;
39
+ get runsRoot(): string;
40
+ recordEvidenceIssue(error: unknown): void;
41
+ finalizeStep(stage: string, work: (signal: AbortSignal) => Promise<void>): Promise<void>;
42
+ constructor(session: RunSession, runId: string, testId: string, testName: string, attemptId: string);
43
+ configure(options: {
44
+ runsRoot: string;
45
+ mode: TimelineRunMode;
46
+ logger: FliwrightLogger;
47
+ recordingMode?: RecordingMode;
48
+ testFinalizationBudgetMs?: number;
49
+ }): Promise<void>;
50
+ /** Resolve policy before an endpoint wait can be canceled, without opening an App connection. */
51
+ configureRecordingPolicy(options: {
52
+ recordingMode?: RecordingMode;
53
+ testFinalizationBudgetMs?: number;
54
+ }): void;
55
+ /**
56
+ * Seed a durable running marker before fixture setup can finish. The parent
57
+ * process uses this marker to recover an attempt whose worker disappeared.
58
+ * Configured runs roots are available through the CLI/preset environment;
59
+ * fixture configuration writes the marker again for config-only callers.
60
+ */
61
+ initialize(): Promise<void>;
62
+ private persistRunning;
63
+ private makeArtifactStore;
64
+ private makeRecorder;
65
+ private persistNodeProgress;
66
+ ignorePriorFailures(task: RunnerTask): void;
67
+ captureRunnerFailures(task: RunnerTask, phase: 'setup-or-body' | 'teardown' | 'final'): Promise<void>;
68
+ persist(result: RunSessionResult, finalized?: boolean, budget?: FinalizationBudget): Promise<void>;
69
+ private applyEvidenceIssues;
70
+ private appendJournal;
71
+ }
72
+ export declare function setAttemptContext(task: RunnerTask, context: AttemptContext): void;
73
+ export declare function requireAttemptContext(task: RunnerTask): AttemptContext;
@@ -0,0 +1,296 @@
1
+ import { mkdir, rename, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { RunArtifactStore, RunProgressJournal, TimelineArtifactStore, TimelineRecorder, projectRunTrace, resolveFliwrightRunsRoot, mergeFliwrightConfig, readFliwrightEnvironment, } from '@fliwright/core';
4
+ import { FinalizationBudget } from './FinalizationBudget.js';
5
+ import { AsyncLocalStorage } from 'node:async_hooks';
6
+ const attemptKey = Symbol.for('@fliwright/vitest/active-attempt');
7
+ /** Shared by the runner and fixture module, including separate Vitest module graphs. */
8
+ export class AttemptContext {
9
+ session;
10
+ runId;
11
+ testId;
12
+ testName;
13
+ attemptId;
14
+ recorder;
15
+ artifactStore;
16
+ runStore;
17
+ recordingMode;
18
+ logger;
19
+ failureContextPath;
20
+ validate;
21
+ /** aroundEach setup can skip before Vitest enters the attempt hooks. */
22
+ onSetupSkipped;
23
+ /** Automatic fixtures can resolve before onBeforeTryTask inside aroundEach. */
24
+ beforeFixtures;
25
+ runnerEntered = false;
26
+ evidenceErrors = [];
27
+ beforeFinish;
28
+ onFailure;
29
+ runnerErrors = [];
30
+ failures = new WeakSet();
31
+ progressQueue = Promise.resolve();
32
+ journal;
33
+ progressClosed = false;
34
+ persistenceIncomplete = false;
35
+ progressController = new AbortController();
36
+ finalizationScope = new AsyncLocalStorage();
37
+ finalization;
38
+ /** Reserve a small part of the same deadline for writing the terminal result. */
39
+ get persistenceReserveMs() { return Math.min(250, this.finalization.timeoutMs / 5); }
40
+ get finalizationSignal() { return this.finalizationScope.getStore(); }
41
+ get runsRoot() { return dirname(this.runStore.runDir); }
42
+ recordEvidenceIssue(error) {
43
+ const message = this.session.redactReport(error instanceof Error ? error.message : String(error));
44
+ if (!this.evidenceErrors.includes(message))
45
+ this.evidenceErrors.push(message);
46
+ }
47
+ async finalizeStep(stage, work) {
48
+ try {
49
+ await this.finalization.run(stage, (signal) => this.finalizationScope.run(signal, () => work(signal)), this.persistenceReserveMs);
50
+ }
51
+ catch (error) {
52
+ this.recordEvidenceIssue(error);
53
+ }
54
+ }
55
+ constructor(session, runId, testId, testName, attemptId) {
56
+ this.session = session;
57
+ this.runId = runId;
58
+ this.testId = testId;
59
+ this.testName = testName;
60
+ this.attemptId = attemptId;
61
+ this.finalization = new FinalizationBudget(mergeFliwrightConfig({
62
+ environment: readFliwrightEnvironment(process.env),
63
+ }).recording.testFinalizationBudgetMs);
64
+ this.recordingMode = process.env.FLIWRIGHT_RECORDING_MODE === 'off' ? 'off'
65
+ : process.env.FLIWRIGHT_RECORDING_MODE === 'full' ? 'full' : 'standard';
66
+ this.configureRecordingPolicy({});
67
+ this.runStore = new RunArtifactStore({ runsRoot: resolveFliwrightRunsRoot({ projectRoot: process.env.FLIWRIGHT_PROJECT_ROOT }), runId });
68
+ this.artifactStore = this.makeArtifactStore();
69
+ this.journal = new RunProgressJournal(this.runStore, testId, attemptId);
70
+ this.recorder = this.makeRecorder();
71
+ session.bindRecorder(this.recorder);
72
+ session.configureProgressPersistence((result) => {
73
+ if (this.progressClosed)
74
+ return Promise.resolve();
75
+ // Each snapshot is owned by this attempt; serialize writes from concurrent
76
+ // branches so an older snapshot cannot overwrite a newer one.
77
+ const timeline = this.session.redactReport(this.recorder.toJSON());
78
+ if (this.recordingMode !== 'off')
79
+ result.eventsPath = 'events.jsonl';
80
+ this.progressQueue = this.progressQueue.then(async () => {
81
+ if (this.progressClosed)
82
+ return;
83
+ if (this.recordingMode !== 'off')
84
+ await this.appendJournal(result, timeline);
85
+ if (this.progressClosed)
86
+ return;
87
+ await this.runStore.writeAttemptResult(this.testId, this.attemptId, result, { signal: this.progressController.signal });
88
+ if (this.progressClosed)
89
+ return;
90
+ if (this.recordingMode !== 'off')
91
+ await this.artifactStore.writeTimeline(timeline, { signal: this.progressController.signal });
92
+ }).catch((error) => {
93
+ if (!this.progressController.signal.aborted)
94
+ this.recordEvidenceIssue(error);
95
+ });
96
+ return this.progressQueue;
97
+ });
98
+ }
99
+ async configure(options) {
100
+ await this.recorder.flushProgress();
101
+ await this.progressQueue;
102
+ const store = new RunArtifactStore({ runsRoot: options.runsRoot, runId: this.runId });
103
+ if (store.runDir !== this.runStore.runDir)
104
+ this.journal = new RunProgressJournal(store, this.testId, this.attemptId);
105
+ this.runStore = store;
106
+ this.artifactStore = this.makeArtifactStore();
107
+ this.logger = options.logger;
108
+ this.configureRecordingPolicy(options);
109
+ this.recorder = this.makeRecorder(options.mode);
110
+ this.session.bindRecorder(this.recorder);
111
+ await this.persistRunning();
112
+ }
113
+ /** Resolve policy before an endpoint wait can be canceled, without opening an App connection. */
114
+ configureRecordingPolicy(options) {
115
+ this.recordingMode = options.recordingMode ?? this.recordingMode;
116
+ this.session.configureRecording({ mode: this.recordingMode, captureEvidence: async () => (this.recordingMode === 'off' ? { status: 'disabled' }
117
+ : { status: 'unavailable', error: 'No app evidence source was configured for this attempt.' }) });
118
+ if (options.testFinalizationBudgetMs !== undefined) {
119
+ this.finalization = new FinalizationBudget(options.testFinalizationBudgetMs);
120
+ }
121
+ }
122
+ /**
123
+ * Seed a durable running marker before fixture setup can finish. The parent
124
+ * process uses this marker to recover an attempt whose worker disappeared.
125
+ * Configured runs roots are available through the CLI/preset environment;
126
+ * fixture configuration writes the marker again for config-only callers.
127
+ */
128
+ async initialize() {
129
+ // Fixture policy is not resolved yet. Keep only the recovery marker until
130
+ // configure() decides whether process recording is enabled.
131
+ if (process.env.FLIWRIGHT_RUNS_ROOT) {
132
+ await this.runStore.writeAttemptResult(this.testId, this.attemptId, this.session.snapshot());
133
+ }
134
+ }
135
+ async persistRunning() {
136
+ const result = this.session.snapshot();
137
+ if (this.recordingMode !== 'off')
138
+ result.eventsPath = 'events.jsonl';
139
+ if (this.recordingMode !== 'off')
140
+ await this.appendJournal(result, this.recorder.toJSON());
141
+ await this.runStore.writeAttemptResult(this.testId, this.attemptId, result);
142
+ }
143
+ makeArtifactStore() {
144
+ return new TimelineArtifactStore({ runId: this.runId,
145
+ attemptDir: this.runStore.attemptDir(this.testId, this.attemptId) });
146
+ }
147
+ makeRecorder(mode) {
148
+ return new TimelineRecorder({ runId: this.runId, testName: this.testName, mode, logger: this.logger,
149
+ onChange: (data) => this.persistNodeProgress(data),
150
+ onPersistenceError: (error) => {
151
+ this.evidenceErrors.push(this.session.redactReport(error instanceof Error ? error.message : String(error)));
152
+ },
153
+ });
154
+ }
155
+ async persistNodeProgress(data) {
156
+ if (this.recordingMode === 'off' || this.progressClosed)
157
+ return;
158
+ const result = this.session.snapshot();
159
+ result.eventsPath = 'events.jsonl';
160
+ // Timeline mutations may contain input/error metadata; use the same privacy
161
+ // boundary as RunSession operation snapshots before persisting any node.
162
+ const timeline = this.session.redactReport(data);
163
+ this.progressQueue = this.progressQueue.then(async () => {
164
+ if (!this.progressClosed)
165
+ await this.appendJournal(result, timeline);
166
+ });
167
+ await this.progressQueue;
168
+ }
169
+ ignorePriorFailures(task) {
170
+ for (const error of task.result?.errors ?? [])
171
+ this.failures.add(error);
172
+ }
173
+ async captureRunnerFailures(task, phase) {
174
+ const errors = task.result?.errors ?? [];
175
+ for (let index = 0; index < errors.length; index++) {
176
+ const original = errors[index];
177
+ if (this.failures.has(original))
178
+ continue;
179
+ this.failures.add(original);
180
+ const error = this.session.redactReport(original);
181
+ errors[index] = error;
182
+ this.failures.add(error);
183
+ this.runnerErrors.push({ message: error.message ?? String(error), stack: error.stack, phase });
184
+ const node = this.recorder.startNode('failure', error.message ?? this.testName, { metadata: { phase } });
185
+ this.recorder.failNode(node.id, {
186
+ code: 'unknown', title: this.testName, message: error.message ?? String(error),
187
+ recoveryHints: [{ kind: 'observe', description: 'Inspect the saved failure evidence and runner error.' }],
188
+ cause: error,
189
+ });
190
+ await this.finalizeStep('Failure evidence', async (signal) => {
191
+ await this.recorder.flushProgress();
192
+ if (this.recordingMode !== 'off')
193
+ for (const kind of ['screenshot', 'snapshot', 'diagnostics']) {
194
+ if (signal.aborted)
195
+ return;
196
+ const evidence = await this.session.checkpoint({ kind, reason: 'failure', operationId: node.id });
197
+ if (signal.aborted)
198
+ return;
199
+ this.recorder.addArtifacts(node.id, (evidence.artifactPaths ?? []).map((path) => ({ kind, path })));
200
+ }
201
+ });
202
+ await this.finalizeStep('Failure projection', async (signal) => { await this.onFailure?.(error, node, signal); });
203
+ await this.finalizeStep('Failure progress flush', () => this.recorder.flushProgress());
204
+ }
205
+ }
206
+ async persist(result, finalized = false, budget = this.finalization) {
207
+ const reserveMs = Math.min(250, budget.timeoutMs / 5);
208
+ let flushed = this.progressClosed;
209
+ try {
210
+ if (!this.progressClosed)
211
+ await budget.run('Progress flush', async () => {
212
+ await this.recorder.flushProgress();
213
+ await this.progressQueue;
214
+ }, reserveMs / 2);
215
+ flushed = true;
216
+ }
217
+ catch (error) {
218
+ this.persistenceIncomplete = true;
219
+ this.recordEvidenceIssue(error);
220
+ }
221
+ // Late evidence and queued progress must not overwrite terminal snapshots.
222
+ this.progressClosed = true;
223
+ this.progressController.abort();
224
+ result.finalized = finalized;
225
+ this.applyEvidenceIssues(result);
226
+ if (this.recordingMode !== 'off')
227
+ try {
228
+ await budget.run('Artifact persistence', async (signal) => {
229
+ result.eventsPath = 'events.jsonl';
230
+ const data = this.session.redactReport(this.recorder.complete(result.testOutcome));
231
+ if (flushed)
232
+ await this.appendJournal(result, data, finalized, signal);
233
+ if (signal.aborted)
234
+ return;
235
+ // A trace references only artifacts already owned by this attempt.
236
+ const traceDir = join(this.artifactStore.runDir, 'trace');
237
+ await mkdir(traceDir, { recursive: true });
238
+ if (signal.aborted)
239
+ return;
240
+ const tracePath = join(traceDir, 'trace.json');
241
+ const temporaryPath = `${tracePath}.${process.pid}.tmp`;
242
+ await writeFile(temporaryPath, JSON.stringify(projectRunTrace(result, data), null, 2), { signal });
243
+ if (signal.aborted)
244
+ return;
245
+ await rename(temporaryPath, tracePath);
246
+ if (signal.aborted)
247
+ return;
248
+ await this.artifactStore.writeTimeline(data, { signal });
249
+ }, reserveMs / 4);
250
+ }
251
+ catch (error) {
252
+ this.persistenceIncomplete = true;
253
+ this.recordEvidenceIssue(error);
254
+ }
255
+ this.applyEvidenceIssues(result);
256
+ try {
257
+ await budget.run('Result persistence', (signal) => this.runStore.writeAttemptResult(this.testId, this.attemptId, result, { signal }));
258
+ }
259
+ catch (error) {
260
+ this.persistenceIncomplete = true;
261
+ this.recordEvidenceIssue(error);
262
+ this.applyEvidenceIssues(result);
263
+ }
264
+ }
265
+ applyEvidenceIssues(result) {
266
+ if (!this.evidenceErrors.length)
267
+ return;
268
+ if (result.evidenceStatus !== 'disabled')
269
+ result.evidenceStatus = 'partial';
270
+ result.evidenceIssues = [...new Set([...(result.evidenceIssues ?? []), ...this.evidenceErrors])];
271
+ }
272
+ async appendJournal(result, timeline, finalized = false, signal = this.progressController.signal) {
273
+ try {
274
+ await this.journal.append(result, timeline, finalized, { signal });
275
+ }
276
+ catch (error) {
277
+ if (signal.aborted)
278
+ return;
279
+ const message = this.session.redactReport(`Progress journal persistence failed: ${error instanceof Error ? error.message : String(error)}`);
280
+ if (!this.evidenceErrors.includes(message))
281
+ this.evidenceErrors.push(message);
282
+ result.evidenceStatus = 'partial';
283
+ result.evidenceIssues = [...new Set([...(result.evidenceIssues ?? []), message])];
284
+ }
285
+ }
286
+ }
287
+ export function setAttemptContext(task, context) {
288
+ // Keep recorder/session internals out of Vitest's task serialization.
289
+ Object.defineProperty(task, attemptKey, { value: context, configurable: true });
290
+ }
291
+ export function requireAttemptContext(task) {
292
+ const context = task[attemptKey];
293
+ if (!context)
294
+ throw new Error('Fliwright fixtures require the Fliwright runner. Configure fliwrightPreset() in vitest.config.ts.');
295
+ return context;
296
+ }
@@ -0,0 +1,15 @@
1
+ /** One time allowance shared by Fliwright-owned teardown stages, excluding project hooks. */
2
+ export declare class FinalizationBudget {
3
+ readonly timeoutMs: number;
4
+ private deadline?;
5
+ private availableMs;
6
+ private active;
7
+ constructor(timeoutMs: number);
8
+ begin(): void;
9
+ pause(): void;
10
+ get remainingMs(): number;
11
+ run<T>(stage: string, work: (signal: AbortSignal) => Promise<T>, reserveMs?: number): Promise<T>;
12
+ }
13
+ export declare class FinalizationTimeoutError extends Error {
14
+ constructor(stage: string, budgetMs: number);
15
+ }
@@ -0,0 +1,57 @@
1
+ /** One time allowance shared by Fliwright-owned teardown stages, excluding project hooks. */
2
+ export class FinalizationBudget {
3
+ timeoutMs;
4
+ deadline;
5
+ availableMs;
6
+ active = 0;
7
+ constructor(timeoutMs) {
8
+ this.timeoutMs = timeoutMs;
9
+ this.availableMs = timeoutMs;
10
+ }
11
+ begin() {
12
+ this.deadline ??= performance.now() + this.availableMs;
13
+ }
14
+ pause() {
15
+ if (this.active !== 0 || this.deadline === undefined)
16
+ return;
17
+ this.availableMs = this.remainingMs;
18
+ this.deadline = undefined;
19
+ }
20
+ get remainingMs() {
21
+ return this.deadline === undefined ? this.availableMs : Math.max(0, this.deadline - performance.now());
22
+ }
23
+ async run(stage, work, reserveMs = 0) {
24
+ this.begin();
25
+ const remaining = this.remainingMs - reserveMs;
26
+ const timeout = new FinalizationTimeoutError(stage, this.timeoutMs);
27
+ if (remaining <= 0) {
28
+ this.pause();
29
+ throw timeout;
30
+ }
31
+ this.active++;
32
+ const controller = new AbortController();
33
+ let timer;
34
+ try {
35
+ return await Promise.race([
36
+ Promise.resolve().then(() => work(controller.signal)),
37
+ new Promise((_, reject) => {
38
+ timer = setTimeout(() => {
39
+ controller.abort(timeout);
40
+ reject(timeout);
41
+ }, Math.ceil(remaining));
42
+ }),
43
+ ]);
44
+ }
45
+ finally {
46
+ clearTimeout(timer);
47
+ this.active--;
48
+ this.pause();
49
+ }
50
+ }
51
+ }
52
+ export class FinalizationTimeoutError extends Error {
53
+ constructor(stage, budgetMs) {
54
+ super(`${stage} exceeded the ${budgetMs}ms test finalization budget.`);
55
+ this.name = 'FinalizationTimeoutError';
56
+ }
57
+ }
@@ -0,0 +1,6 @@
1
+ import type { Reporter } from 'vitest/node';
2
+ /** Parent-side persistence fallback for direct Vitest runs using fliwrightPreset. */
3
+ export declare class FliwrightRecoveryReporter implements Reporter {
4
+ onTestRunEnd(modules: Parameters<NonNullable<Reporter['onTestRunEnd']>>[0]): Promise<void>;
5
+ }
6
+ export default FliwrightRecoveryReporter;
@@ -0,0 +1,15 @@
1
+ import { restoreRunAttempts } from '@fliwright/core';
2
+ /** Parent-side persistence fallback for direct Vitest runs using fliwrightPreset. */
3
+ export class FliwrightRecoveryReporter {
4
+ async onTestRunEnd(modules) {
5
+ for (const module of modules)
6
+ for (const test of module.children.allTests()) {
7
+ const meta = test.meta();
8
+ const attempts = meta.fliwrightRecovery;
9
+ for (const attempt of attempts ?? []) {
10
+ await restoreRunAttempts([attempt], attempt.result.runId, attempt.runsRoot);
11
+ }
12
+ }
13
+ }
14
+ }
15
+ export default FliwrightRecoveryReporter;
@@ -0,0 +1,8 @@
1
+ import type { EndpointLease } from '@fliwright/core';
2
+ import type { RunnerTask } from 'vitest';
3
+ /** The runner and fixtures may live in separate Vitest module graphs. */
4
+ export declare function getTaskEndpointLease(task: RunnerTask): EndpointLease | undefined;
5
+ export declare function setTaskEndpointLease(task: RunnerTask, lease: EndpointLease): void;
6
+ /** Runtime skip bypasses the final task hook; both runner and fixture must finish. */
7
+ export declare function finishTaskEndpointLeasePhase(task: RunnerTask, phase: 'cleanupComplete' | 'skipFinalized'): Promise<void>;
8
+ export declare function releaseTaskEndpointLease(task: RunnerTask): Promise<void>;
@@ -0,0 +1,28 @@
1
+ const leaseKey = Symbol.for('@fliwright/vitest/task-endpoint-lease');
2
+ /** The runner and fixtures may live in separate Vitest module graphs. */
3
+ export function getTaskEndpointLease(task) {
4
+ return task[leaseKey]?.lease;
5
+ }
6
+ export function setTaskEndpointLease(task, lease) {
7
+ task[leaseKey] = { lease };
8
+ }
9
+ /** Runtime skip bypasses the final task hook; both runner and fixture must finish. */
10
+ export async function finishTaskEndpointLeasePhase(task, phase) {
11
+ const state = task[leaseKey];
12
+ if (!state)
13
+ return;
14
+ state[phase] = true;
15
+ if (state.cleanupComplete && state.skipFinalized)
16
+ await releaseTaskEndpointLease(task);
17
+ }
18
+ export async function releaseTaskEndpointLease(task) {
19
+ const lease = getTaskEndpointLease(task);
20
+ if (!lease)
21
+ return;
22
+ try {
23
+ await lease.release();
24
+ }
25
+ finally {
26
+ delete task[leaseKey];
27
+ }
28
+ }
@@ -0,0 +1,8 @@
1
+ import type { RunnerTask, RunnerTestCase, TestAPI } from 'vitest';
2
+ type PrepareTask = (task: RunnerTestCase, signal: AbortSignal) => Promise<void>;
3
+ /** Bind preparation through public test metadata without wrapping the body.
4
+ * Symbol keys stay within the worker and are omitted from reporter serialization.
5
+ */
6
+ export declare function withTaskPreparation<T extends object>(test: TestAPI<T>, prepare: PrepareTask): TestAPI<T>;
7
+ export declare function prepareRegisteredTask(task: RunnerTask, signal: AbortSignal): Promise<void>;
8
+ export {};
@@ -0,0 +1,52 @@
1
+ const prepareKey = Symbol.for('@fliwright/vitest/prepare-task');
2
+ /** Bind preparation through public test metadata without wrapping the body.
3
+ * Symbol keys stay within the worker and are omitted from reporter serialization.
4
+ */
5
+ export function withTaskPreparation(test, prepare) {
6
+ const proxies = new WeakMap();
7
+ const variants = new Set(['concurrent', 'skip', 'only', 'todo', 'fails']);
8
+ const factories = new Set(['each', 'for', 'skipIf', 'runIf', 'extend']);
9
+ const wrap = (target) => {
10
+ const existing = proxies.get(target);
11
+ if (existing)
12
+ return existing;
13
+ const proxy = new Proxy(target, {
14
+ apply(fn, receiver, args) {
15
+ const [name, optionsOrHandler, handlerOrTimeout] = args;
16
+ // Let Vitest reject removed overloads and malformed handler pairs.
17
+ if ((typeof handlerOrTimeout === 'object' && handlerOrTimeout !== null)
18
+ || (typeof optionsOrHandler === 'function' && typeof handlerOrTimeout === 'function')) {
19
+ return Reflect.apply(fn, receiver, args);
20
+ }
21
+ const options = typeof optionsOrHandler === 'object' && optionsOrHandler !== null
22
+ ? optionsOrHandler
23
+ : typeof handlerOrTimeout === 'number' ? { timeout: handlerOrTimeout } : {};
24
+ const handler = typeof optionsOrHandler === 'function' ? optionsOrHandler : handlerOrTimeout;
25
+ return Reflect.apply(fn, receiver, [name, {
26
+ ...options, meta: { ...options.meta, [prepareKey]: prepare },
27
+ }, handler]);
28
+ },
29
+ get(fn, property, receiver) {
30
+ const value = Reflect.get(fn, property, receiver);
31
+ if (typeof value !== 'function')
32
+ return value;
33
+ if (typeof property === 'string' && variants.has(property))
34
+ return wrap(value);
35
+ if (typeof property === 'string' && factories.has(property)) {
36
+ return (...args) => {
37
+ const result = Reflect.apply(value, fn, args);
38
+ return typeof result === 'function' ? wrap(result) : result;
39
+ };
40
+ }
41
+ return value;
42
+ },
43
+ });
44
+ proxies.set(target, proxy);
45
+ return proxy;
46
+ };
47
+ return wrap(test);
48
+ }
49
+ export async function prepareRegisteredTask(task, signal) {
50
+ if (task.type === 'test')
51
+ await task.meta[prepareKey]?.(task, signal);
52
+ }