@workflow/vitest 4.0.1-beta.1 → 4.0.1-beta.11

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.md ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ <http://www.apache.org/licenses/>
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Vercel Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export declare function setup(): Promise<void>;
2
+ //# sourceMappingURL=global-setup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"global-setup.d.ts","sourceRoot":"","sources":["../src/global-setup.ts"],"names":[],"mappings":"AAEA,wBAAsB,KAAK,kBAE1B"}
@@ -0,0 +1,5 @@
1
+ import { buildWorkflowTests } from './index.js';
2
+ export async function setup() {
3
+ await buildWorkflowTests();
4
+ }
5
+ //# sourceMappingURL=global-setup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"global-setup.js","sourceRoot":"","sources":["../src/global-setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAEhD,MAAM,CAAC,KAAK,UAAU,KAAK;IACzB,MAAM,kBAAkB,EAAE,CAAC;AAC7B,CAAC"}
@@ -0,0 +1,88 @@
1
+ import type { Run } from '@workflow/core/runtime';
2
+ import type { Hook } from '@workflow/world';
3
+ import type { Plugin } from 'vite';
4
+ export interface WorkflowTestOptions {
5
+ /**
6
+ * The working directory of the project (where workflows/ lives).
7
+ * Defaults to process.cwd().
8
+ */
9
+ cwd?: string;
10
+ }
11
+ /**
12
+ * Vitest plugin for workflow testing. Handles SWC transforms, bundle building,
13
+ * and in-process handler registration automatically.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * // vitest.config.ts
18
+ * import { workflow } from '@workflow/vitest';
19
+ * import { defineConfig } from 'vitest/config';
20
+ *
21
+ * export default defineConfig({
22
+ * plugins: [workflow()],
23
+ * });
24
+ * ```
25
+ */
26
+ export declare function workflow(): Plugin[];
27
+ /**
28
+ * Build workflow bundles for testing. Run this in vitest globalSetup.
29
+ * This builds the workflow and step bundles to disk so they can be
30
+ * imported by the test workers.
31
+ */
32
+ export declare function buildWorkflowTests(options?: WorkflowTestOptions): Promise<void>;
33
+ /**
34
+ * Set up in-process handler routing for workflow tests.
35
+ * Run this in vitest setupFiles (which executes in each test worker process).
36
+ *
37
+ * Imports the pre-built bundles, creates a local world with direct handlers,
38
+ * and sets it as the global world.
39
+ */
40
+ export declare function setupWorkflowTests(options?: WorkflowTestOptions): Promise<void>;
41
+ /**
42
+ * Tear down the workflow test world. Call this in afterAll or vitest teardown.
43
+ */
44
+ export declare function teardownWorkflowTests(): Promise<void>;
45
+ export interface WaitOptions {
46
+ /** Maximum time to wait in milliseconds. Defaults to 30000. */
47
+ timeout?: number;
48
+ /** Polling interval in milliseconds. Defaults to 100. */
49
+ pollInterval?: number;
50
+ }
51
+ /**
52
+ * Wait until the workflow has a pending `sleep()` call.
53
+ *
54
+ * Polls the event log for a `wait_created` event without a corresponding
55
+ * `wait_completed` event. Returns the correlation ID of the pending sleep,
56
+ * which can be passed to `run.wakeUp({ correlationIds: [id] })` to target
57
+ * a specific sleep call.
58
+ *
59
+ * @returns The correlation ID of the first pending sleep.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * const run = await start(myWorkflow, []);
64
+ * const sleepId = await waitForSleep(run);
65
+ * await run.wakeUp({ correlationIds: [sleepId] });
66
+ * const result = await run.returnValue;
67
+ * ```
68
+ */
69
+ export declare function waitForSleep(run: Run<any>, options?: WaitOptions): Promise<string>;
70
+ /**
71
+ * Wait until the workflow has created a hook that hasn't been received yet.
72
+ *
73
+ * Polls the hook list and event log for a hook matching the optional `token`
74
+ * filter that hasn't had a `hook_received` event. Returns the matching hook,
75
+ * which you can then resume with `resumeHook(hook.token, data)`.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * const run = await start(myWorkflow, ["doc-1"]);
80
+ * const hook = await waitForHook(run);
81
+ * await resumeHook(hook.token, { approved: true });
82
+ * const result = await run.returnValue;
83
+ * ```
84
+ */
85
+ export declare function waitForHook(run: Run<any>, options?: WaitOptions & {
86
+ token?: string;
87
+ }): Promise<Hook>;
88
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAGlD,OAAO,KAAK,EAAS,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAMnD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AA8CnC,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAMD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,QAAQ,IAAI,MAAM,EAAE,CAkBnC;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,CAAC,EAAE,mBAAmB,GAC5B,OAAO,CAAC,IAAI,CAAC,CAOf;AAID;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,CAAC,EAAE,mBAAmB,GAC5B,OAAO,CAAC,IAAI,CAAC,CAwDf;AAED;;GAEG;AACH,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAI3D;AAED,MAAM,WAAW,WAAW;IAC1B,+DAA+D;IAC/D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yDAAyD;IACzD,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AA0BD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,YAAY,CAChC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,EACb,OAAO,CAAC,EAAE,WAAW,GACpB,OAAO,CAAC,MAAM,CAAC,CA4BjB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,WAAW,CAC/B,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,EACb,OAAO,CAAC,EAAE,WAAW,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GACzC,OAAO,CAAC,IAAI,CAAC,CAgCf"}
package/dist/index.js ADDED
@@ -0,0 +1,245 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { BaseBuilder, createBaseBuilderConfig } from '@workflow/builders';
5
+ import { setWorld } from '@workflow/core/runtime';
6
+ import { workflowTransformPlugin } from '@workflow/rollup';
7
+ import { createLocalWorld, initDataDir, } from '@workflow/world-local';
8
+ class VitestBuilder extends BaseBuilder {
9
+ #outDir;
10
+ constructor(workingDir, outDir) {
11
+ super({
12
+ ...createBaseBuilderConfig({
13
+ workingDir,
14
+ dirs: ['.'],
15
+ }),
16
+ // 'next' target produces ESM bundles with Node.js-compatible output,
17
+ // which is what we need for in-process vitest execution.
18
+ buildTarget: 'next',
19
+ suppressCreateWorkflowsBundleLogs: true,
20
+ suppressCreateWebhookBundleLogs: true,
21
+ suppressCreateManifestLogs: true,
22
+ });
23
+ this.#outDir = outDir;
24
+ }
25
+ get shouldLogBaseBuilderInfo() {
26
+ return false;
27
+ }
28
+ async build() {
29
+ const inputFiles = await this.getInputFiles();
30
+ await mkdir(this.#outDir, { recursive: true });
31
+ await this.createWorkflowsBundle({
32
+ outfile: join(this.#outDir, 'workflows.mjs'),
33
+ bundleFinalOutput: false,
34
+ format: 'esm',
35
+ inputFiles,
36
+ });
37
+ await this.createStepsBundle({
38
+ outfile: join(this.#outDir, 'steps.mjs'),
39
+ externalizeNonSteps: true,
40
+ rewriteTsExtensions: true,
41
+ format: 'esm',
42
+ inputFiles,
43
+ });
44
+ }
45
+ }
46
+ function getOutDir(cwd) {
47
+ return join(cwd, '.workflow-vitest');
48
+ }
49
+ /**
50
+ * Vitest plugin for workflow testing. Handles SWC transforms, bundle building,
51
+ * and in-process handler registration automatically.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * // vitest.config.ts
56
+ * import { workflow } from '@workflow/vitest';
57
+ * import { defineConfig } from 'vitest/config';
58
+ *
59
+ * export default defineConfig({
60
+ * plugins: [workflow()],
61
+ * });
62
+ * ```
63
+ */
64
+ export function workflow() {
65
+ const dir = fileURLToPath(new URL('.', import.meta.url));
66
+ return [
67
+ workflowTransformPlugin({
68
+ exclude: [join(process.cwd(), '.workflow-vitest') + '/'],
69
+ }),
70
+ {
71
+ name: 'workflow:vitest',
72
+ config() {
73
+ return {
74
+ test: {
75
+ globalSetup: [join(dir, 'global-setup.js')],
76
+ setupFiles: [join(dir, 'setup-file.js')],
77
+ },
78
+ };
79
+ },
80
+ },
81
+ ];
82
+ }
83
+ /**
84
+ * Build workflow bundles for testing. Run this in vitest globalSetup.
85
+ * This builds the workflow and step bundles to disk so they can be
86
+ * imported by the test workers.
87
+ */
88
+ export async function buildWorkflowTests(options) {
89
+ const cwd = options?.cwd ?? process.cwd();
90
+ const outDir = getOutDir(cwd);
91
+ const builder = new VitestBuilder(cwd, outDir);
92
+ await builder.build();
93
+ // Pre-create the shared data directory so workers don't race on mkdir
94
+ await initDataDir(join(cwd, '.workflow-data'));
95
+ }
96
+ let world;
97
+ /**
98
+ * Set up in-process handler routing for workflow tests.
99
+ * Run this in vitest setupFiles (which executes in each test worker process).
100
+ *
101
+ * Imports the pre-built bundles, creates a local world with direct handlers,
102
+ * and sets it as the global world.
103
+ */
104
+ export async function setupWorkflowTests(options) {
105
+ // Clean up previous world if re-initialized (e.g. across test files)
106
+ if (world) {
107
+ setWorld(undefined);
108
+ await world.close?.();
109
+ world = undefined;
110
+ }
111
+ const cwd = options?.cwd ?? process.cwd();
112
+ const outDir = getOutDir(cwd);
113
+ // Lazy-load bundles on first dispatch instead of eagerly at setup time.
114
+ // Eager native import() during setupFiles loads step dependencies into
115
+ // the module cache before vi.mock() can intercept them, breaking mocks
116
+ // in unit tests that never execute workflows.
117
+ function createLazyHandler(bundlePath) {
118
+ let handler;
119
+ let loading;
120
+ return async (req) => {
121
+ if (!handler) {
122
+ // If the import rejects (e.g. missing bundle), the rejected promise is
123
+ // cached so all subsequent calls fail fast with the same error.
124
+ loading ??= import(
125
+ /* @vite-ignore */ pathToFileURL(bundlePath).href).then((mod) => mod.POST);
126
+ handler = await loading;
127
+ }
128
+ return handler(req);
129
+ };
130
+ }
131
+ // Each vitest worker uses a unique tag to isolate its test data.
132
+ // All workers write to the shared .workflow-data directory so runs
133
+ // are visible to the observability dashboard, but clear() only
134
+ // deletes files matching the worker's tag.
135
+ const poolId = process.env.VITEST_POOL_ID ?? '0';
136
+ world = createLocalWorld({
137
+ dataDir: join(cwd, '.workflow-data'),
138
+ tag: `vitest-${poolId}`,
139
+ });
140
+ await world.start?.();
141
+ await world.clear();
142
+ world.registerHandler('__wkf_workflow_', createLazyHandler(join(outDir, 'workflows.mjs')));
143
+ world.registerHandler('__wkf_step_', createLazyHandler(join(outDir, 'steps.mjs')));
144
+ setWorld(world);
145
+ }
146
+ /**
147
+ * Tear down the workflow test world. Call this in afterAll or vitest teardown.
148
+ */
149
+ export async function teardownWorkflowTests() {
150
+ setWorld(undefined);
151
+ await world?.close?.();
152
+ world = undefined;
153
+ }
154
+ function getWorldOrThrow() {
155
+ if (!world) {
156
+ throw new Error('Workflow test world is not initialized. Call setupWorkflowTests() first.');
157
+ }
158
+ return world;
159
+ }
160
+ async function fetchAllEvents(w, runId) {
161
+ const allEvents = [];
162
+ let cursor = null;
163
+ do {
164
+ const result = await w.events.list({
165
+ runId,
166
+ pagination: { limit: 1000, ...(cursor ? { cursor } : {}) },
167
+ resolveData: 'none',
168
+ });
169
+ allEvents.push(...result.data);
170
+ cursor = result.hasMore ? result.cursor : null;
171
+ } while (cursor);
172
+ return allEvents;
173
+ }
174
+ /**
175
+ * Wait until the workflow has a pending `sleep()` call.
176
+ *
177
+ * Polls the event log for a `wait_created` event without a corresponding
178
+ * `wait_completed` event. Returns the correlation ID of the pending sleep,
179
+ * which can be passed to `run.wakeUp({ correlationIds: [id] })` to target
180
+ * a specific sleep call.
181
+ *
182
+ * @returns The correlation ID of the first pending sleep.
183
+ *
184
+ * @example
185
+ * ```ts
186
+ * const run = await start(myWorkflow, []);
187
+ * const sleepId = await waitForSleep(run);
188
+ * await run.wakeUp({ correlationIds: [sleepId] });
189
+ * const result = await run.returnValue;
190
+ * ```
191
+ */
192
+ export async function waitForSleep(run, options) {
193
+ const w = getWorldOrThrow();
194
+ const timeout = options?.timeout ?? 30_000;
195
+ const pollInterval = options?.pollInterval ?? 100;
196
+ const deadline = Date.now() + timeout;
197
+ while (Date.now() < deadline) {
198
+ const events = await fetchAllEvents(w, run.runId);
199
+ const waitCompletedIds = new Set(events
200
+ .filter((e) => e.eventType === 'wait_completed')
201
+ .map((e) => e.correlationId));
202
+ const pendingSleep = events.find((e) => e.eventType === 'wait_created' && !waitCompletedIds.has(e.correlationId));
203
+ if (pendingSleep?.correlationId)
204
+ return pendingSleep.correlationId;
205
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
206
+ }
207
+ throw new Error(`waitForSleep timed out after ${timeout}ms: no pending sleep found for run ${run.runId}`);
208
+ }
209
+ /**
210
+ * Wait until the workflow has created a hook that hasn't been received yet.
211
+ *
212
+ * Polls the hook list and event log for a hook matching the optional `token`
213
+ * filter that hasn't had a `hook_received` event. Returns the matching hook,
214
+ * which you can then resume with `resumeHook(hook.token, data)`.
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * const run = await start(myWorkflow, ["doc-1"]);
219
+ * const hook = await waitForHook(run);
220
+ * await resumeHook(hook.token, { approved: true });
221
+ * const result = await run.returnValue;
222
+ * ```
223
+ */
224
+ export async function waitForHook(run, options) {
225
+ const w = getWorldOrThrow();
226
+ const timeout = options?.timeout ?? 30_000;
227
+ const pollInterval = options?.pollInterval ?? 100;
228
+ const deadline = Date.now() + timeout;
229
+ while (Date.now() < deadline) {
230
+ const [hooks, events] = await Promise.all([
231
+ w.hooks.list({ runId: run.runId }).then((r) => r.data),
232
+ fetchAllEvents(w, run.runId),
233
+ ]);
234
+ const receivedCorrelationIds = new Set(events
235
+ .filter((e) => e.eventType === 'hook_received')
236
+ .map((e) => e.correlationId));
237
+ const pendingHook = hooks.find((h) => !receivedCorrelationIds.has(h.hookId) &&
238
+ (!options?.token || h.token === options.token));
239
+ if (pendingHook)
240
+ return pendingHook;
241
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
242
+ }
243
+ throw new Error(`waitForHook timed out after ${timeout}ms: no pending hook found for run ${run.runId}${options?.token ? ` with token "${options.token}"` : ''}`);
244
+ }
245
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAE1E,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EACL,gBAAgB,EAChB,WAAW,GAEZ,MAAM,uBAAuB,CAAC;AAG/B,MAAM,aAAc,SAAQ,WAAW;IACrC,OAAO,CAAS;IAEhB,YAAY,UAAkB,EAAE,MAAc;QAC5C,KAAK,CAAC;YACJ,GAAG,uBAAuB,CAAC;gBACzB,UAAU;gBACV,IAAI,EAAE,CAAC,GAAG,CAAC;aACZ,CAAC;YACF,qEAAqE;YACrE,yDAAyD;YACzD,WAAW,EAAE,MAAM;YACnB,iCAAiC,EAAE,IAAI;YACvC,+BAA+B,EAAE,IAAI;YACrC,0BAA0B,EAAE,IAAI;SACjC,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IA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B,GAAG,IAAI,GAAG,CACpC,MAAM;aACH,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,KAAK,eAAe,CAAC;aAC9C,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,CAC/B,CAAC;QAEF,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAC5B,CAAC,CAAC,EAAE,EAAE,CACJ,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC;YACrC,CAAC,CAAC,OAAO,EAAE,KAAK,IAAI,CAAC,CAAC,KAAK,KAAK,OAAO,CAAC,KAAK,CAAC,CACjD,CAAC;QAEF,IAAI,WAAW;YAAE,OAAO,WAAW,CAAC;QAEpC,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,MAAM,IAAI,KAAK,CACb,+BAA+B,OAAO,qCAAqC,GAAG,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,gBAAgB,OAAO,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAChJ,CAAC;AACJ,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=setup-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-file.d.ts","sourceRoot":"","sources":["../src/setup-file.ts"],"names":[],"mappings":""}
@@ -0,0 +1,7 @@
1
+ import { afterAll } from 'vitest';
2
+ import { setupWorkflowTests, teardownWorkflowTests } from './index.js';
3
+ await setupWorkflowTests();
4
+ afterAll(async () => {
5
+ await teardownWorkflowTests();
6
+ });
7
+ //# sourceMappingURL=setup-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-file.js","sourceRoot":"","sources":["../src/setup-file.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAEvE,MAAM,kBAAkB,EAAE,CAAC;AAE3B,QAAQ,CAAC,KAAK,IAAI,EAAE;IAClB,MAAM,qBAAqB,EAAE,CAAC;AAChC,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@workflow/vitest",
3
- "version": "4.0.1-beta.1",
4
- "description": "Vitest plugin for testing Workflow DevKit workflows",
3
+ "version": "4.0.1-beta.11",
4
+ "description": "Vitest plugin for testing Workflow SDK workflows",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -23,22 +23,17 @@
23
23
  "url": "https://github.com/vercel/workflow.git",
24
24
  "directory": "packages/vitest"
25
25
  },
26
- "scripts": {
27
- "build": "tsc",
28
- "clean": "tsc --build --clean && rm -rf dist ||:",
29
- "dev": "tsc --watch"
30
- },
31
26
  "dependencies": {
32
- "@workflow/builders": "workspace:*",
33
- "@workflow/core": "workspace:*",
34
- "@workflow/rollup": "workspace:*",
35
- "@workflow/world": "workspace:*",
36
- "@workflow/world-local": "workspace:*"
27
+ "@workflow/core": "4.2.0-beta.74",
28
+ "@workflow/builders": "4.0.1-beta.65",
29
+ "@workflow/rollup": "4.0.0-beta.31",
30
+ "@workflow/world": "4.1.0-beta.14",
31
+ "@workflow/world-local": "4.1.0-beta.47"
37
32
  },
38
33
  "devDependencies": {
39
- "@types/node": "catalog:",
40
- "@workflow/tsconfig": "workspace:*",
41
- "vite": "7.1.12"
34
+ "@types/node": "22.19.0",
35
+ "vite": "7.1.12",
36
+ "@workflow/tsconfig": "4.0.1-beta.0"
42
37
  },
43
38
  "peerDependencies": {
44
39
  "vite": ">=6.0.0",
@@ -48,5 +43,10 @@
48
43
  "vite": {
49
44
  "optional": true
50
45
  }
46
+ },
47
+ "scripts": {
48
+ "build": "tsc",
49
+ "clean": "tsc --build --clean && rm -rf dist ||:",
50
+ "dev": "tsc --watch"
51
51
  }
52
- }
52
+ }