@vite-hub/workflow 0.1.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +173 -55
  2. package/dist/{app-CzPoP84f.js → app-He0GTrYZ.js} +1 -1
  3. package/dist/client-DkwOxEiT.js +707 -0
  4. package/dist/{cloudflare-nF4abPd4.js → cloudflare-BHfClPvT.js} +2 -2
  5. package/dist/{cloudflare-env-BNrYo29x.js → cloudflare-env-CGLx7lUd.js} +44 -42
  6. package/dist/cloudflare-env-lookup-CfX6wZKb.d.ts +4 -0
  7. package/dist/{cloudflare-env-CIjdFTv6.d.ts → cloudflare-shared-CTqh_a2s.d.ts} +2 -2
  8. package/dist/{config-IJMb0eeZ.js → config-C3DvtjfJ.js} +41 -40
  9. package/dist/definition.d.ts +18 -0
  10. package/dist/definition.js +33 -0
  11. package/dist/delay-D1-nq_VE.js +46 -0
  12. package/dist/dev-recorder-CTN5Fkao.js +10 -0
  13. package/dist/durability.d.ts +23 -0
  14. package/dist/durability.js +62 -0
  15. package/dist/error-diagnostics-0V2T3JFw.js +317 -0
  16. package/dist/error-diagnostics-CQ4BUqRe.js +270 -0
  17. package/dist/errors-DCqRnZpN.js +35 -0
  18. package/dist/errors-uhP8DZTi.d.ts +67 -0
  19. package/dist/index.d.ts +35 -63
  20. package/dist/index.js +15 -19
  21. package/dist/object-Da1zyPCR.js +11 -0
  22. package/dist/openworkflow-BhzxV_Y3.d.ts +52 -0
  23. package/dist/openworkflow-defaults-DDig2M4s.js +26 -0
  24. package/dist/openworkflow-storage-Dj9zUAsk.js +28 -0
  25. package/dist/openworkflow.d.ts +2 -0
  26. package/dist/openworkflow.js +2 -0
  27. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
  28. package/dist/operations-D_WJwjrS.js +333 -0
  29. package/dist/operations.d.ts +40 -6
  30. package/dist/operations.js +163 -736
  31. package/dist/{out-CsaJxg8m.js → out-DxLKolA0.js} +32 -1430
  32. package/dist/{rolldown-runtime-CMFfr-1z.js → rolldown-runtime-B4iAMlE-.js} +10 -1
  33. package/dist/run-error-DBWqiJHH.js +110 -0
  34. package/dist/run-failed-gVGo1BaF.js +18 -0
  35. package/dist/runtime/cloudflare-runner.d.ts +3 -5
  36. package/dist/runtime/cloudflare-runner.js +39 -45
  37. package/dist/runtime/cloudflare-shared.d.ts +2 -2
  38. package/dist/runtime/cloudflare-shared.js +1 -1
  39. package/dist/runtime/cloudflare-vite.d.ts +3 -2
  40. package/dist/runtime/cloudflare-vite.js +47 -1
  41. package/dist/runtime/dev-runs.d.ts +4 -0
  42. package/dist/runtime/dev-runs.js +73 -0
  43. package/dist/runtime/execute.d.ts +42 -5
  44. package/dist/runtime/execute.js +216 -17
  45. package/dist/runtime/openworkflow-worker.d.ts +29 -2
  46. package/dist/runtime/openworkflow-worker.js +156 -38
  47. package/dist/runtime/openworkflow.d.ts +2 -21
  48. package/dist/runtime/openworkflow.js +307 -44
  49. package/dist/runtime/state.d.ts +3 -1
  50. package/dist/runtime/state.js +6 -6
  51. package/dist/runtime/vercel-vite.d.ts +1 -1
  52. package/dist/runtime/vercel-vite.js +7 -4
  53. package/dist/types-Dsmwsdlv.d.ts +282 -0
  54. package/dist/{vercel-D-ZNtB_u.js → vercel-DTvm61iY.js} +53 -24
  55. package/dist/vite.d.ts +228 -30
  56. package/dist/vite.js +2640 -1449
  57. package/package.json +28 -50
  58. package/dist/client-DsGM3M4U.js +0 -389
  59. package/dist/cloudflare-shared-CaxrMD1A.d.ts +0 -1
  60. package/dist/cloudflare-vite-B3IabBsv.js +0 -47
  61. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  62. package/dist/error-diagnostics-pwNFvAHP.js +0 -67
  63. package/dist/operations-B_rYG71W.js +0 -230
  64. package/dist/provider-operation-CW2cYfVy.js +0 -65
  65. package/dist/runtime-type-DBCvIh5x.js +0 -7
  66. package/dist/types-D82WmfZa.d.ts +0 -180
@@ -0,0 +1,707 @@
1
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
2
+ import { n as createWorkflowError } from "./errors-DCqRnZpN.js";
3
+ import { a as encodeNameHex, n as getCloudflareWorkflowBindingName } from "./cloudflare-BHfClPvT.js";
4
+ import { a as getCloudflareEnv, n as resolveWaitUntil } from "./cloudflare-env-CGLx7lUd.js";
5
+ import { t as normalizeWorkflowOptions } from "./config-C3DvtjfJ.js";
6
+ import { i as toCloudflareStartParams, r as resolveWorkflowStartAt } from "./delay-D1-nq_VE.js";
7
+ import { t as getWorkflowDevRecorder } from "./dev-recorder-CTN5Fkao.js";
8
+ import { runSerializedWorkflowHandler } from "./runtime/execute.js";
9
+ import { a as safeWorkflowName, i as runWorkflowProviderOperation, t as toWorkflowRunError } from "./run-error-DBWqiJHH.js";
10
+ import { t as emitWorkflowFailed } from "./run-failed-gVGo1BaF.js";
11
+ import { cancelOpenWorkflowRun, getOpenWorkflowRun, runOpenWorkflow } from "./runtime/openworkflow.js";
12
+ import { getInlineWorkflowDefinitions, getWorkflowRunState, getWorkflowRuntimeConfig, getWorkflowRuntimeEvent, getWorkflowRuntimeRegistry, loadWorkflowDefinition, registerInlineWorkflowDefinition, runWithWorkflowRuntimeEvent, setWorkflowRun } from "./runtime/state.js";
13
+ import { a as startVercelWorkflow, n as inspectVercelWorkflowRun, r as resumeVercelWorkflowSignal, t as cancelVercelWorkflow } from "./vercel-DTvm61iY.js";
14
+ import { deserializeResponse, getViteHubErrorShape, isRuntimeDiagnostic, isSerializedResponse, toResultError } from "@vite-hub/runtime";
15
+ import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
16
+ //#region ../internal/src/runtime/random.ts
17
+ function randomId(prefix) {
18
+ const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
19
+ return prefix ? `${prefix}_${body}` : body;
20
+ }
21
+ //#endregion
22
+ //#region src/integrations/vercel.ts
23
+ function getVercelWorkflowName(name) {
24
+ return `workflow--${encodeNameHex(name)}`;
25
+ }
26
+ //#endregion
27
+ //#region src/runtime/adapters.ts
28
+ function resolveDispatchObserver(event) {
29
+ if (!event || typeof event !== "object") return void 0;
30
+ const candidate = Object.hasOwn(event, "onDispatch") ? Reflect.get(event, "onDispatch") : void 0;
31
+ return typeof candidate === "function" ? candidate : void 0;
32
+ }
33
+ function resolveSettlementObserver(event) {
34
+ if (!event || typeof event !== "object") return void 0;
35
+ const candidate = Object.hasOwn(event, "settled") ? Reflect.get(event, "settled") : void 0;
36
+ if (typeof candidate === "function") return candidate;
37
+ const context = Object.hasOwn(event, "context") ? Reflect.get(event, "context") : void 0;
38
+ if (!context || typeof context !== "object") return void 0;
39
+ const contextObject = Object(context);
40
+ const nested = Object.hasOwn(contextObject, "settled") ? Reflect.get(contextObject, "settled") : void 0;
41
+ return typeof nested === "function" ? nested : void 0;
42
+ }
43
+ function unsupportedOperation(provider, operation) {
44
+ throw createWorkflowError({
45
+ code: "WORKFLOW_OPERATION_UNSUPPORTED",
46
+ details: {
47
+ operation,
48
+ provider
49
+ }
50
+ });
51
+ }
52
+ /**
53
+ * True on a development server: `vite dev` installs the run history. Code that ViteHub did not start, such as a test
54
+ * runner, has no history, so `NODE_ENV` decides there.
55
+ */
56
+ function isDevelopmentServer() {
57
+ if (getWorkflowDevRecorder()) return true;
58
+ const mode = globalThis.process?.env?.NODE_ENV;
59
+ return mode === "development" || mode === "test";
60
+ }
61
+ /**
62
+ * The Cloudflare Workflow binding of `name`. Only a development server runs the Workflow inline without it. Elsewhere,
63
+ * a missing binding fails, because an inline run is not durable.
64
+ */
65
+ function resolveCloudflareBinding(event, binding, name, definition) {
66
+ const env = getCloudflareEnv(event);
67
+ const bindingName = definition?.internalAgentInvocationRecovery ? getCloudflareWorkflowBindingName(name) : binding || getCloudflareWorkflowBindingName(name);
68
+ if (env && Object.hasOwn(env, bindingName)) return env[bindingName];
69
+ if (isDevelopmentServer()) return void 0;
70
+ throw workflowErrorDiagnostics.WORKFLOW_R0036({
71
+ binding: bindingName,
72
+ name
73
+ });
74
+ }
75
+ function resolveCloudflareInspectionBinding(event, binding, name) {
76
+ return resolveCloudflareBinding(event, binding, name, getWorkflowRuntimeRegistry()?.[name]);
77
+ }
78
+ /** The start can have reached Cloudflare, so the acknowledgement is unknown. */
79
+ function invalidCloudflareWorkflowStart(cause) {
80
+ return createWorkflowError({
81
+ ...cause === void 0 ? {} : { cause },
82
+ code: "WORKFLOW_PROVIDER_OPERATION_FAILED",
83
+ details: {
84
+ acknowledgement: "unknown",
85
+ operation: "create",
86
+ provider: "cloudflare",
87
+ reason: "Cloudflare Workflow provider returned an invalid workflow instance."
88
+ }
89
+ });
90
+ }
91
+ function normalizeCloudflareWorkflowStart(value, expectedId) {
92
+ if (typeof value !== "object" || value === null) throw invalidCloudflareWorkflowStart();
93
+ let id;
94
+ try {
95
+ id = Reflect.get(value, "id");
96
+ } catch (cause) {
97
+ throw invalidCloudflareWorkflowStart(cause);
98
+ }
99
+ if (typeof id !== "string" || !id || id !== expectedId) throw invalidCloudflareWorkflowStart();
100
+ return { id };
101
+ }
102
+ const cloudflareInstanceIdPattern = /^[a-zA-Z0-9_][a-zA-Z0-9_-]{0,99}$/;
103
+ /** The array-form `createBatch` accepts reserved ids, unlike the object form. */
104
+ function isCloudflareInstanceId(id) {
105
+ return cloudflareInstanceIdPattern.test(id);
106
+ }
107
+ const cloudflareStatusMap = {
108
+ cancelled: "cancelled",
109
+ complete: "completed",
110
+ completed: "completed",
111
+ errored: "failed",
112
+ failed: "failed",
113
+ paused: "running",
114
+ queued: "queued",
115
+ running: "running",
116
+ success: "completed",
117
+ terminated: "cancelled",
118
+ waiting: "running",
119
+ waitingforpause: "running"
120
+ };
121
+ function normalizeCloudflareStatus(status) {
122
+ const value = typeof status === "object" && status && Object.hasOwn(status, "status") ? status.status : status;
123
+ const normalized = String(value || "").toLowerCase();
124
+ return Object.hasOwn(cloudflareStatusMap, normalized) ? cloudflareStatusMap[normalized] : "unknown";
125
+ }
126
+ /** The run result from Cloudflare status: the stored value, or a `Response` when the handler returned one. */
127
+ function cloudflareRunResult(metadata) {
128
+ if (typeof metadata !== "object" || metadata === null || !Object.hasOwn(metadata, "output")) return void 0;
129
+ const output = metadata.output;
130
+ return isSerializedResponse(output) ? deserializeResponse(output) : output;
131
+ }
132
+ /** The `error` member of a Cloudflare `status()` record. */
133
+ function ownStatusError(metadata) {
134
+ if (typeof metadata !== "object" || metadata === null || !Object.hasOwn(metadata, "error")) return void 0;
135
+ return Reflect.get(metadata, "error");
136
+ }
137
+ /** Cloudflare `get(id)` rejects with `instance.not_found` when no instance has the id. */
138
+ function isCloudflareInstanceNotFound(error) {
139
+ if (typeof error !== "object" || error === null) return false;
140
+ try {
141
+ const message = Reflect.get(error, "message");
142
+ return typeof message === "string" && message.includes("instance.not_found");
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+ /**
148
+ * The Cloudflare Workflows service refused the call: its error carries a service code such as `(instance.already_exists)`,
149
+ * or local Miniflare rejected the instance id. A lost connection has neither.
150
+ */
151
+ function isCloudflareRejection(error) {
152
+ if (typeof error !== "object" || error === null) return false;
153
+ try {
154
+ const message = Reflect.get(error, "message");
155
+ return typeof message === "string" && /\((?:instance|workflow)\.[a-z_]+\)|^Workflow instance has invalid id/.test(message);
156
+ } catch {
157
+ return false;
158
+ }
159
+ }
160
+ function hasUnknownWorkflowAcknowledgement(error) {
161
+ if (!error || typeof error !== "object") return false;
162
+ const details = error.details;
163
+ return Boolean(details && typeof details === "object" && details.acknowledgement === "unknown");
164
+ }
165
+ /** Reads a Cloudflare Workflow instance and its run. A missing instance has no `instance` and reports `unknown`. */
166
+ async function readCloudflareRun(binding, id) {
167
+ const instance = await runWorkflowProviderOperation("cloudflare", "get", async () => {
168
+ try {
169
+ return await binding.get(id);
170
+ } catch (error) {
171
+ if (isCloudflareInstanceNotFound(error)) return void 0;
172
+ throw error;
173
+ }
174
+ });
175
+ if (!instance) return { run: {
176
+ id,
177
+ provider: "cloudflare",
178
+ status: "unknown"
179
+ } };
180
+ const metadata = await runWorkflowProviderOperation("cloudflare", "status", () => instance.status());
181
+ const status = normalizeCloudflareStatus(metadata);
182
+ return {
183
+ instance,
184
+ run: {
185
+ ...status === "failed" ? { error: toWorkflowRunError(ownStatusError(metadata)) } : {},
186
+ id,
187
+ metadata,
188
+ provider: "cloudflare",
189
+ result: status === "completed" ? cloudflareRunResult(metadata) : void 0,
190
+ status
191
+ }
192
+ };
193
+ }
194
+ const finishedRunStatuses = /* @__PURE__ */ new Set([
195
+ "cancelled",
196
+ "completed",
197
+ "failed"
198
+ ]);
199
+ /**
200
+ * Terminates a Cloudflare Workflow instance that has not finished and returns its run afterwards. A finished run keeps
201
+ * and reports its status, and a missing run reports `unknown`, as on OpenWorkflow.
202
+ */
203
+ async function cancelCloudflareRun(binding, id) {
204
+ const { instance, run } = await readCloudflareRun(binding, id);
205
+ if (!instance || run.status === "unknown" || finishedRunStatuses.has(run.status)) return run;
206
+ try {
207
+ await runWorkflowProviderOperation("cloudflare", "cancel", () => instance.terminate());
208
+ } catch (error) {
209
+ const latest = await readCloudflareRun(binding, id).catch(() => void 0);
210
+ if (latest && finishedRunStatuses.has(latest.run.status)) return latest.run;
211
+ throw error;
212
+ }
213
+ return (await readCloudflareRun(binding, id)).run;
214
+ }
215
+ function createCloudflareAdapter(config) {
216
+ const adapter = {
217
+ async cancel({ event, id, name }) {
218
+ const binding = resolveCloudflareInspectionBinding(event, config.binding, name);
219
+ return binding ? await cancelCloudflareRun(binding, id) : await inlineAdapter(config).cancel({
220
+ event,
221
+ id,
222
+ name
223
+ });
224
+ },
225
+ async get({ event, id, name }) {
226
+ const binding = resolveCloudflareInspectionBinding(event, config.binding, name);
227
+ if (binding) return (await readCloudflareRun(binding, id)).run;
228
+ return await inlineAdapter(config).get({
229
+ event,
230
+ id,
231
+ name
232
+ });
233
+ },
234
+ async run(context) {
235
+ const { definition, event, id, name, payload, startAt } = context;
236
+ if (!isCloudflareInstanceId(id)) throw workflowErrorDiagnostics.WORKFLOW_CLOUDFLARE_RUN_ID_INVALID({ id });
237
+ const binding = resolveCloudflareBinding(event, config.binding, name, definition);
238
+ if (binding) {
239
+ resolveDispatchObserver(event)?.();
240
+ let created = false;
241
+ const start = () => runWorkflowProviderOperation("cloudflare", "create", async () => {
242
+ const [instance] = await binding.createBatch([{
243
+ id,
244
+ params: toCloudflareStartParams(payload, startAt)
245
+ }]);
246
+ created = instance !== void 0;
247
+ return normalizeCloudflareWorkflowStart(instance || await binding.get(id), id);
248
+ }, { acknowledgement: (error, status) => status === void 0 ? isCloudflareRejection(error) ? "rejected" : "unknown" : status < 500 ? "rejected" : void 0 });
249
+ const instance = await start().catch(async (firstError) => {
250
+ try {
251
+ return await start();
252
+ } catch (retryError) {
253
+ if (hasUnknownWorkflowAcknowledgement(firstError)) throw firstError;
254
+ throw retryError;
255
+ }
256
+ });
257
+ if (!created) return await adapter.get({
258
+ event,
259
+ id,
260
+ name
261
+ });
262
+ return {
263
+ id: instance.id,
264
+ payload,
265
+ provider: "cloudflare",
266
+ status: "queued"
267
+ };
268
+ }
269
+ return await inlineAdapter(config).run(context);
270
+ },
271
+ resume: () => unsupportedOperation("cloudflare", "signals")
272
+ };
273
+ return adapter;
274
+ }
275
+ const warnedInlineOpenWorkflowNames = /* @__PURE__ */ new Set();
276
+ /**
277
+ * Every OpenWorkflow worker registers the Workflow Definitions of the build registry when it starts: discovered
278
+ * Workflows and discovered Agent Workflows. Any worker can claim a run, so a run of an inline
279
+ * `createWorkflow(name, handler)` could wait in storage on a worker that never registers it. Those runs execute inline
280
+ * in this process. A turn of an Agent that is not discovered fails with `WORKFLOW_AGENT_NOT_DISCOVERED`, so Agent turns are
281
+ * never inline.
282
+ */
283
+ function isDurableOpenWorkflowDefinition(name) {
284
+ const registry = getWorkflowRuntimeRegistry();
285
+ return Boolean(registry && Object.hasOwn(registry, name));
286
+ }
287
+ function createOpenWorkflowAdapter(config) {
288
+ const inline = inlineAdapter(config);
289
+ return {
290
+ cancel: async ({ event, id, name }) => isDurableOpenWorkflowDefinition(name) ? await cancelOpenWorkflowRun(config, name, id) : await inline.cancel({
291
+ event,
292
+ id,
293
+ name
294
+ }),
295
+ get: async ({ event, id, name }) => isDurableOpenWorkflowDefinition(name) ? await getOpenWorkflowRun(config, name, id) : await inline.get({
296
+ event,
297
+ id,
298
+ name
299
+ }),
300
+ resume: () => unsupportedOperation("openworkflow", "signals"),
301
+ run: async (context) => {
302
+ const { definition, event, name, options, payload, startAt } = context;
303
+ if (isDurableOpenWorkflowDefinition(name)) return await runOpenWorkflow(config, name, payload, definition, options, resolveDispatchObserver(event), startAt);
304
+ if (definition?.internalAgentWorkflow || definition?.internalAgentInvocationRecovery) throw workflowErrorDiagnostics.WORKFLOW_AGENT_NOT_DISCOVERED({ name });
305
+ if (!warnedInlineOpenWorkflowNames.has(name)) {
306
+ warnedInlineOpenWorkflowNames.add(name);
307
+ console.warn(`[vitehub:workflow] The Workflow ${JSON.stringify(name)} is not a discovered file, so OpenWorkflow workers cannot run it. Its runs execute inline in this process and are not durable. Move it to server/workflows/ to make it durable.`);
308
+ }
309
+ return {
310
+ ...await inline.run(context),
311
+ metadata: {
312
+ mode: "inline",
313
+ workflow: name
314
+ }
315
+ };
316
+ }
317
+ };
318
+ }
319
+ /** `setTimeout` fires at once for a delay above 2^31 - 1 ms (about 24.8 days), so a long wait uses several timers. */
320
+ const maximumTimerDelay = 2147483647;
321
+ async function waitUntilTime(startAt) {
322
+ while (startAt !== void 0 && startAt > Date.now()) await new Promise((resolve) => setTimeout(resolve, Math.min(startAt - Date.now(), maximumTimerDelay)));
323
+ }
324
+ function inlineAdapter(config) {
325
+ return {
326
+ cancel: () => unsupportedOperation(config.driver, "cancellation"),
327
+ async get({ id, name }) {
328
+ const run = getWorkflowRunState(name, id);
329
+ if (run) {
330
+ if (run.status === "running") return {
331
+ id,
332
+ provider: config.driver,
333
+ status: run.startAt === void 0 ? "running" : "queued"
334
+ };
335
+ return {
336
+ ...run.status === "failed" ? { error: toWorkflowRunError(run.error) } : {},
337
+ id,
338
+ provider: config.driver,
339
+ result: isSerializedResponse(run.result) ? deserializeResponse(run.result) : run.result,
340
+ status: run.status
341
+ };
342
+ }
343
+ return {
344
+ id,
345
+ provider: config.driver,
346
+ status: "unknown"
347
+ };
348
+ },
349
+ async run({ definition, event, id, name, payload, startAt }) {
350
+ const existing = getWorkflowRunState(name, id);
351
+ if (existing) return {
352
+ ...existing.status === "failed" ? { error: toWorkflowRunError(existing.error) } : {},
353
+ id,
354
+ metadata: config.driver === "vercel" ? {
355
+ mode: "inline",
356
+ workflow: getVercelWorkflowName(name)
357
+ } : void 0,
358
+ payload: existing.payload,
359
+ provider: config.driver,
360
+ result: isSerializedResponse(existing.result) ? deserializeResponse(existing.result) : existing.result,
361
+ status: existing.status === "running" ? "queued" : existing.status
362
+ };
363
+ resolveDispatchObserver(event)?.();
364
+ const recordRun = getWorkflowDevRecorder()?.start(name, id, config.driver);
365
+ const execute = () => runSerializedWorkflowHandler({
366
+ id,
367
+ name,
368
+ payload,
369
+ provider: config.driver
370
+ }, definition);
371
+ const run = waitUntilTime(startAt).then(() => {
372
+ runState.startAt = void 0;
373
+ return recordRun ? recordRun(execute) : execute();
374
+ }).then((result) => ({
375
+ result,
376
+ status: "completed"
377
+ })).catch((error) => ({
378
+ error,
379
+ status: "failed"
380
+ }));
381
+ const runState = setWorkflowRun(name, id, run, payload, true);
382
+ runState.startAt = startAt;
383
+ const notify = runState.promise.then(async (outcome) => {
384
+ if (outcome.status === "failed") await emitWorkflowFailed(name, id, outcome.error, definition);
385
+ });
386
+ resolveWaitUntil(event)?.(notify);
387
+ return {
388
+ id,
389
+ metadata: config.driver === "vercel" ? {
390
+ mode: "inline",
391
+ workflow: getVercelWorkflowName(name)
392
+ } : void 0,
393
+ payload,
394
+ provider: config.driver,
395
+ status: "queued"
396
+ };
397
+ },
398
+ resume: () => unsupportedOperation(config.driver, "signals")
399
+ };
400
+ }
401
+ /**
402
+ * True when Workflow DevKit runs the `native` entry. `vite dev` does not run the Workflow DevKit transform, so the
403
+ * dev server runs the normal handler inline, as for every other Workflow there.
404
+ */
405
+ function runsNatively(definition) {
406
+ return Boolean(definition?.native) && !getWorkflowDevRecorder();
407
+ }
408
+ /** Whether a registered Workflow has a native Vercel entry, so a run of it can wait for a signal. */
409
+ async function hasNativeWorkflowDefinition() {
410
+ const names = /* @__PURE__ */ new Set([...Object.keys(getWorkflowRuntimeRegistry() ?? {}), ...getInlineWorkflowDefinitions().keys()]);
411
+ for (const name of names) if ((await loadWorkflowDefinition(name))?.native) return true;
412
+ return false;
413
+ }
414
+ function createVercelAdapter(config) {
415
+ const fallback = inlineAdapter(config);
416
+ return {
417
+ async cancel({ id, name }) {
418
+ const definition = await loadWorkflowDefinition(name);
419
+ if (!runsNatively(definition)) return await fallback.cancel({
420
+ event: void 0,
421
+ id,
422
+ name
423
+ });
424
+ return await cancelVercelWorkflow(name, definition, id);
425
+ },
426
+ async get({ id, name }) {
427
+ const definition = await loadWorkflowDefinition(name);
428
+ return runsNatively(definition) ? await inspectVercelWorkflowRun(name, definition, id) : await fallback.get({
429
+ event: void 0,
430
+ id,
431
+ name
432
+ });
433
+ },
434
+ async resume(token, payload) {
435
+ if (getWorkflowDevRecorder()) unsupportedOperation(config.driver, "signals");
436
+ try {
437
+ return await resumeVercelWorkflowSignal(token, payload);
438
+ } catch (error) {
439
+ if (getViteHubErrorShape(error)?.code === "VERCEL_WORKFLOW_SDK_LOAD_FAILED" && !await hasNativeWorkflowDefinition()) unsupportedOperation(config.driver, "signals");
440
+ throw error;
441
+ }
442
+ },
443
+ async run(context) {
444
+ const { definition, event, name, payload, startAt } = context;
445
+ if (!runsNatively(definition)) return await fallback.run(context);
446
+ return await startVercelWorkflow(name, definition, payload, resolveSettlementObserver(event), resolveDispatchObserver(event), startAt);
447
+ }
448
+ };
449
+ }
450
+ function getWorkflowRuntimeAdapter(config) {
451
+ if (config.driver === "cloudflare") return createCloudflareAdapter(config);
452
+ if (config.driver === "openworkflow") return createOpenWorkflowAdapter(config);
453
+ return createVercelAdapter(config);
454
+ }
455
+ //#endregion
456
+ //#region src/runtime/test-client.ts
457
+ /** The started runs of the current test. `vite-hub/test` reads the same list. */
458
+ function workflowTestRuns(test) {
459
+ return test.backend("workflow", () => []);
460
+ }
461
+ function toWorkflowRun(run, provider) {
462
+ return {
463
+ id: run.id,
464
+ payload: run.payload,
465
+ provider,
466
+ status: run.status
467
+ };
468
+ }
469
+ /** Records the run and does not start its handler, so a test asserts what the app started. */
470
+ function recordWorkflowTestRun(test, provider, input) {
471
+ const runs = workflowTestRuns(test);
472
+ const existing = runs.find((run) => run.workflow === input.name && run.id === input.id);
473
+ if (existing) return toWorkflowRun(existing, provider);
474
+ const run = {
475
+ deferred: input.deferred,
476
+ id: input.id,
477
+ payload: structuredClone(input.payload),
478
+ status: "queued",
479
+ workflow: input.name
480
+ };
481
+ runs.push(run);
482
+ return toWorkflowRun(run, provider);
483
+ }
484
+ /** Returns a recorded run, or a run with status `unknown` when the test started no run with this id. */
485
+ function getWorkflowTestRun(test, provider, name, id, cancel = false) {
486
+ const run = workflowTestRuns(test).find((item) => item.workflow === name && item.id === id);
487
+ if (!run) return {
488
+ id,
489
+ provider,
490
+ status: "unknown"
491
+ };
492
+ if (cancel) run.status = "cancelled";
493
+ return toWorkflowRun(run, provider);
494
+ }
495
+ //#endregion
496
+ //#region src/runtime/client.ts
497
+ const resultErrorCodes = /* @__PURE__ */ new Set([
498
+ "RUNTIME_DURATION_INVALID",
499
+ "WORKFLOW_CLOUDFLARE_RUN_ID_INVALID",
500
+ "WORKFLOW_OPERATION_UNSUPPORTED",
501
+ "WORKFLOW_PROVIDER_OPERATION_FAILED",
502
+ "WORKFLOW_R0014",
503
+ "WORKFLOW_RUN_ID_UNSUPPORTED",
504
+ "WORKFLOW_START_DELAY_INVALID"
505
+ ]);
506
+ function resultError(diagnostic) {
507
+ return toResultError(diagnostic);
508
+ }
509
+ /**
510
+ * Returns a runtime failure of a Workflow call as a catalog error. The providers throw `ViteHubError` inside the
511
+ * package. The catalog error keeps its `details` in `data` and the provider error in `cause`. Config errors throw.
512
+ */
513
+ function toWorkflowResultError(error) {
514
+ if (isRuntimeDiagnostic(error) && resultErrorCodes.has(error.code)) return resultError(error);
515
+ const shape = getViteHubErrorShape(error);
516
+ if (!shape || !resultErrorCodes.has(shape.code)) throw error;
517
+ const cause = error instanceof Error ? error.cause : void 0;
518
+ const details = shape.details ?? {};
519
+ if (shape.code === "WORKFLOW_PROVIDER_OPERATION_FAILED") return resultError(workflowErrorDiagnostics.WORKFLOW_PROVIDER_OPERATION_FAILED({
520
+ ...details,
521
+ cause
522
+ }));
523
+ if (shape.code === "WORKFLOW_RUN_ID_UNSUPPORTED") return resultError(workflowErrorDiagnostics.WORKFLOW_RUN_ID_UNSUPPORTED({ cause }));
524
+ return resultError(workflowErrorDiagnostics.WORKFLOW_OPERATION_UNSUPPORTED({
525
+ cause,
526
+ operation: details.operation,
527
+ provider: details.provider
528
+ }));
529
+ }
530
+ /** Runs one Workflow call and returns its runtime failure as `[error, undefined]`. */
531
+ async function toWorkflowResult(run) {
532
+ try {
533
+ return [void 0, await run()];
534
+ } catch (error) {
535
+ return [toWorkflowResultError(error), void 0];
536
+ }
537
+ }
538
+ function getActiveWorkflowConfig() {
539
+ const config = getWorkflowRuntimeConfig();
540
+ if (config === false) throw createWorkflowError({ code: "WORKFLOW_DISABLED" });
541
+ return config || normalizeWorkflowOptions(void 0, { hosting: "vercel" });
542
+ }
543
+ async function loadRequiredWorkflowDefinition(name) {
544
+ const definition = await loadWorkflowDefinition(name);
545
+ if (!definition) throw createWorkflowError({
546
+ code: "WORKFLOW_DEFINITION_NOT_FOUND",
547
+ details: safeWorkflowName(name) ? { name } : void 0
548
+ });
549
+ return definition;
550
+ }
551
+ function normalizeWorkflowRunIdValue(value) {
552
+ if (value === void 0) return null;
553
+ if (value === null || typeof value !== "object") return value;
554
+ if (Array.isArray(value)) return value.map((item) => normalizeWorkflowRunIdValue(item));
555
+ const record = value;
556
+ return Object.fromEntries(Object.keys(record).filter((key) => record[key] !== void 0).sort().map((key) => [key, normalizeWorkflowRunIdValue(record[key])]));
557
+ }
558
+ async function sha256Hex(value) {
559
+ const data = new TextEncoder().encode(value);
560
+ const digest = await crypto.subtle.digest("SHA-256", data);
561
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
562
+ }
563
+ async function createStableWorkflowRunId(name, value) {
564
+ const hash = await sha256Hex(`${name}:${JSON.stringify(normalizeWorkflowRunIdValue(value))}`);
565
+ return `${name.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 67) || "workflow"}-${hash.slice(0, 32)}`;
566
+ }
567
+ async function resolveWorkflowStartOptions(name, payload, createOptions, startOptions) {
568
+ if (startOptions.id || !createOptions?.id) return startOptions;
569
+ return {
570
+ ...startOptions,
571
+ id: await createStableWorkflowRunId(name, await createOptions.id({
572
+ name,
573
+ payload
574
+ }))
575
+ };
576
+ }
577
+ function createWorkflow(nameOrOptions, handlerOrOptions, options) {
578
+ let name;
579
+ let handler;
580
+ let createOptions;
581
+ if (typeof nameOrOptions === "object" && nameOrOptions !== null) {
582
+ createOptions = nameOrOptions;
583
+ if (!createOptions.name || typeof createOptions.name !== "string") throw workflowErrorDiagnostics.WORKFLOW_R0009({ message: "`createWorkflow()` requires a workflow name." });
584
+ if (typeof createOptions.handler !== "function") throw workflowErrorDiagnostics.WORKFLOW_R0010({ message: "`createWorkflow()` requires a workflow handler." });
585
+ name = createOptions.name;
586
+ handler = createOptions.handler;
587
+ } else {
588
+ name = nameOrOptions;
589
+ if (!name || typeof name !== "string") throw workflowErrorDiagnostics.WORKFLOW_R0011({ message: "`createWorkflow()` requires a workflow name." });
590
+ handler = typeof handlerOrOptions === "function" ? handlerOrOptions : typeof handlerOrOptions === "object" && handlerOrOptions !== null ? handlerOrOptions.handler : void 0;
591
+ createOptions = typeof handlerOrOptions === "function" ? options : handlerOrOptions;
592
+ if (handler !== void 0 && typeof handler !== "function") throw workflowErrorDiagnostics.WORKFLOW_R0012({ message: "`createWorkflow()` requires a workflow handler." });
593
+ if (handler === void 0 && handlerOrOptions !== void 0 && (typeof handlerOrOptions !== "object" || handlerOrOptions === null)) throw workflowErrorDiagnostics.WORKFLOW_R0013({ message: "`createWorkflow()` options must be an object." });
594
+ }
595
+ if (handler !== void 0) registerInlineWorkflowDefinition(name, {
596
+ handler,
597
+ ...createOptions?.internalAgentWorkflow ? { internalAgentWorkflow: true } : {},
598
+ ...createOptions?.rootStep === void 0 ? {} : { rootStep: createOptions.rootStep }
599
+ });
600
+ return {
601
+ cancel: (id) => cancelWorkflow(name, id),
602
+ name,
603
+ defer: (payload, options = {}) => deferWorkflowStart(name, async () => await startWorkflowRun(name, payload, await resolveWorkflowStartOptions(name, payload, createOptions, options), true)),
604
+ getRun: (id) => getWorkflowRun(name, id),
605
+ async start(payload, options = {}) {
606
+ const startOptions = await resolveWorkflowStartOptions(name, payload, createOptions, options);
607
+ return await toWorkflowResult(() => startWorkflowRun(name, payload, startOptions));
608
+ }
609
+ };
610
+ }
611
+ async function startWorkflow(name, payload, options = {}) {
612
+ return await toWorkflowResult(() => startWorkflowRun(name, payload, options));
613
+ }
614
+ async function startWorkflowRun(name, payload, options, deferred = false) {
615
+ const config = getActiveWorkflowConfig();
616
+ const id = options.id || randomId("wrun");
617
+ const startAt = resolveWorkflowStartAt(options.delay);
618
+ const definition = await loadRequiredWorkflowDefinition(name);
619
+ if (config.driver === "vercel" && definition.native && options.id) throw createWorkflowError({
620
+ code: "WORKFLOW_RUN_ID_UNSUPPORTED",
621
+ details: {
622
+ ...safeWorkflowName(name) ? { name } : {},
623
+ provider: "vercel"
624
+ }
625
+ });
626
+ const test = getViteHubTestMode();
627
+ if (test) return recordWorkflowTestRun(test, config.driver, {
628
+ deferred,
629
+ id,
630
+ name,
631
+ payload
632
+ });
633
+ return await getWorkflowRuntimeAdapter(config).run({
634
+ definition,
635
+ event: getWorkflowRuntimeEvent(),
636
+ id,
637
+ name,
638
+ options,
639
+ payload,
640
+ startAt
641
+ });
642
+ }
643
+ /**
644
+ * Reads one run and returns `[error, run]`. A provider failure is `error`. A run that the provider does not know has
645
+ * `status: "unknown"`. Config errors throw.
646
+ */
647
+ async function getWorkflowRun(name, id) {
648
+ const config = getActiveWorkflowConfig();
649
+ const test = getViteHubTestMode();
650
+ if (test) return [void 0, getWorkflowTestRun(test, config.driver, name, id)];
651
+ return await toWorkflowResult(() => getWorkflowRuntimeAdapter(config).get({
652
+ event: getWorkflowRuntimeEvent(),
653
+ id,
654
+ name
655
+ }));
656
+ }
657
+ /**
658
+ * Cancels one run and returns `[error, run]`. A provider failure, or a provider that cannot cancel the run, is
659
+ * `error`. Config errors, for example an unknown Workflow name, throw.
660
+ */
661
+ async function cancelWorkflow(name, id) {
662
+ const config = getActiveWorkflowConfig();
663
+ const definition = await loadRequiredWorkflowDefinition(name);
664
+ const test = getViteHubTestMode();
665
+ if (test) {
666
+ if (config.driver === "vercel" && !definition.native) return [resultError(workflowErrorDiagnostics.WORKFLOW_OPERATION_UNSUPPORTED({
667
+ operation: "cancellation",
668
+ provider: config.driver
669
+ })), void 0];
670
+ return [void 0, getWorkflowTestRun(test, config.driver, name, id, true)];
671
+ }
672
+ return await toWorkflowResult(() => getWorkflowRuntimeAdapter(config).cancel({
673
+ event: getWorkflowRuntimeEvent(),
674
+ id,
675
+ name
676
+ }));
677
+ }
678
+ /**
679
+ * Resumes a run that waits for a signal and returns `[error, signal]`. `token` is the opaque token that the provider
680
+ * gave the waiting step. An empty token or a provider failure is `error`. Config errors throw.
681
+ */
682
+ async function resumeWorkflow(token, payload) {
683
+ if (!token || typeof token !== "string") return [resultError(workflowErrorDiagnostics.WORKFLOW_R0014({ message: "`resumeWorkflow()` requires an opaque signal token." })), void 0];
684
+ const config = getActiveWorkflowConfig();
685
+ if (getViteHubTestMode()) return [resultError(workflowErrorDiagnostics.WORKFLOW_OPERATION_UNSUPPORTED({
686
+ operation: "signals",
687
+ provider: config.driver
688
+ })), void 0];
689
+ return await toWorkflowResult(() => getWorkflowRuntimeAdapter(config).resume(token, payload));
690
+ }
691
+ function deferWorkflowStart(name, start) {
692
+ const request = getWorkflowRuntimeEvent();
693
+ const promise = runWithWorkflowRuntimeEvent(request, start).then(() => void 0, (error) => {
694
+ console.error(`[vitehub] Deferred Workflow start failed for "${name}"`, error);
695
+ });
696
+ const waitUntil = resolveWaitUntil(request);
697
+ if (typeof waitUntil === "function") waitUntil(promise);
698
+ }
699
+ /**
700
+ * Starts a run after the response, through `waitUntil`. It returns nothing: a failure goes to the log.
701
+ * Call `startWorkflow()` when the caller needs the run ID or the start error.
702
+ */
703
+ function deferWorkflow(...[name, payload, options = {}]) {
704
+ deferWorkflowStart(name, () => startWorkflowRun(name, payload, options, true));
705
+ }
706
+ //#endregion
707
+ export { resumeWorkflow as a, getWorkflowRun as i, createWorkflow as n, startWorkflow as o, deferWorkflow as r, cancelWorkflow as t };