@vite-hub/workflow 0.3.1 → 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 (41) hide show
  1. package/README.md +52 -35
  2. package/dist/{app-CmMq8l4t.js → app-He0GTrYZ.js} +1 -1
  3. package/dist/{client-CU5rELC0.js → client-DkwOxEiT.js} +88 -39
  4. package/dist/{cloudflare-BfFnNWB0.js → cloudflare-BHfClPvT.js} +1 -1
  5. package/dist/{config-DCvRDlxA.js → config-C3DvtjfJ.js} +1 -1
  6. package/dist/definition.d.ts +10 -11
  7. package/dist/definition.js +24 -22
  8. package/dist/{delay--ESDybVT.js → delay-D1-nq_VE.js} +6 -41
  9. package/dist/durability.d.ts +1 -1
  10. package/dist/{error-diagnostics-8YNJ37rP.js → error-diagnostics-0V2T3JFw.js} +45 -14
  11. package/dist/{error-diagnostics-DSkCJC_L.js → error-diagnostics-CQ4BUqRe.js} +5 -1
  12. package/dist/{errors-DVwFb6Fd.d.ts → errors-uhP8DZTi.d.ts} +12 -1
  13. package/dist/index.d.ts +30 -11
  14. package/dist/index.js +12 -5
  15. package/dist/{openworkflow-TEaNk0LV.d.ts → openworkflow-BhzxV_Y3.d.ts} +3 -1
  16. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
  17. package/dist/{operations-B0L8kV5s.js → operations-D_WJwjrS.js} +9 -5
  18. package/dist/operations.d.ts +2 -2
  19. package/dist/operations.js +2 -2
  20. package/dist/{out-fRNaVslw.js → out-DxLKolA0.js} +1 -1
  21. package/dist/{rolldown-runtime-CMFfr-1z.js → rolldown-runtime-B4iAMlE-.js} +10 -1
  22. package/dist/run-failed-gVGo1BaF.js +18 -0
  23. package/dist/runtime/cloudflare-runner.d.ts +1 -1
  24. package/dist/runtime/cloudflare-runner.js +17 -5
  25. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  26. package/dist/runtime/cloudflare-vite.js +2 -2
  27. package/dist/runtime/execute.d.ts +25 -4
  28. package/dist/runtime/execute.js +108 -15
  29. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  30. package/dist/runtime/openworkflow-worker.js +1 -1
  31. package/dist/runtime/openworkflow.d.ts +1 -1
  32. package/dist/runtime/openworkflow.js +37 -11
  33. package/dist/runtime/state.d.ts +1 -1
  34. package/dist/runtime/state.js +2 -6
  35. package/dist/runtime/vercel-vite.d.ts +1 -1
  36. package/dist/runtime/vercel-vite.js +2 -2
  37. package/dist/{types-CnKVDnEp.d.ts → types-Dsmwsdlv.d.ts} +67 -26
  38. package/dist/{vercel-BZU_O6ay.js → vercel-DTvm61iY.js} +4 -4
  39. package/dist/vite.d.ts +17 -11
  40. package/dist/vite.js +1116 -529
  41. package/package.json +4 -4
@@ -1,17 +1,105 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
2
2
  import { r as isNonRetryableError, t as NonRetryableError } from "../errors-DCqRnZpN.js";
3
3
  import { t as getWorkflowDevRecorder } from "../dev-recorder-CTN5Fkao.js";
4
4
  import { isResponse, serializeResponse, toResponse } from "@vite-hub/runtime";
5
5
  //#region src/runtime/execute.ts
6
- const defaultStepOptions = { retries: {
6
+ const defaultRetries = {
7
7
  backoff: "exponential",
8
8
  delay: "10 seconds",
9
9
  limit: 3
10
- } };
11
- async function runProviderStep(step, name, run, options = defaultStepOptions) {
12
- if (typeof step?.do === "function") return await step.do(name, options, run);
10
+ };
11
+ const stepOptionKeys = /* @__PURE__ */ new Set(["retries", "timeout"]);
12
+ const retryOptionKeys = /* @__PURE__ */ new Set([
13
+ "backoff",
14
+ "delay",
15
+ "limit"
16
+ ]);
17
+ function isPlainObject(value) {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19
+ }
20
+ /**
21
+ * Checks the options of a step and fills in the default retries. A step file, `context.step.do()`, and every provider
22
+ * read the options through this function, so an invalid value fails the same way everywhere.
23
+ */
24
+ function resolveWorkflowStepOptions(step, options) {
25
+ const invalid = (option, value) => workflowErrorDiagnostics.WORKFLOW_STEP_OPTIONS_INVALID({
26
+ option,
27
+ step,
28
+ value: typeof value === "string" ? JSON.stringify(value) : String(value)
29
+ });
30
+ if (options === void 0) return { retries: { ...defaultRetries } };
31
+ if (!isPlainObject(options)) throw invalid("options", options);
32
+ for (const key of Object.keys(options)) if (!stepOptionKeys.has(key)) throw invalid(key, options[key]);
33
+ const retries = options.retries ?? {};
34
+ if (!isPlainObject(retries)) throw invalid("retries", retries);
35
+ for (const key of Object.keys(retries)) if (!retryOptionKeys.has(key)) throw invalid(`retries.${key}`, retries[key]);
36
+ const { backoff = defaultRetries.backoff, delay = defaultRetries.delay, limit = defaultRetries.limit } = retries;
37
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0) throw invalid("retries.limit", limit);
38
+ if (toDurationMilliseconds(delay) === void 0) throw invalid("retries.delay", delay);
39
+ if (backoff !== "constant" && backoff !== "exponential") throw invalid("retries.backoff", backoff);
40
+ const timeout = options.timeout;
41
+ if (timeout !== void 0 && !toDurationMilliseconds(timeout)) throw invalid("timeout", timeout);
42
+ return {
43
+ retries: {
44
+ backoff,
45
+ delay,
46
+ limit
47
+ },
48
+ ...timeout === void 0 ? {} : { timeout }
49
+ };
50
+ }
51
+ /** Calls `callback` after `milliseconds`, also when that is longer than one Node timer can wait. Returns a cancel function. */
52
+ function onTimeout(milliseconds, callback) {
53
+ const deadline = Date.now() + milliseconds;
54
+ let timer;
55
+ const arm = () => {
56
+ timer = setTimeout(() => Date.now() >= deadline ? callback() : arm(), Math.min(Math.max(deadline - Date.now(), 0), maxTimerDelay));
57
+ };
58
+ arm();
59
+ return () => clearTimeout(timer);
60
+ }
61
+ /**
62
+ * Runs one attempt of a step. When `timeout` passes, the step's `signal` aborts and the attempt fails with
63
+ * `WORKFLOW_STEP_TIMEOUT`, so the provider retries it. A step that ignores the signal keeps running in the background:
64
+ * JavaScript cannot stop a promise.
65
+ */
66
+ async function runWorkflowStepAttempt(step, timeout, run) {
67
+ const controller = new AbortController();
68
+ const milliseconds = timeout === void 0 ? void 0 : toDurationMilliseconds(timeout);
69
+ if (milliseconds === void 0) return await run({ signal: controller.signal });
70
+ const label = typeof timeout === "number" ? `${timeout} ms` : String(timeout);
71
+ let cancel = () => {};
72
+ const expired = new Promise((_resolve, reject) => {
73
+ cancel = onTimeout(milliseconds, () => {
74
+ const error = workflowErrorDiagnostics.WORKFLOW_STEP_TIMEOUT({
75
+ step,
76
+ timeout: label
77
+ });
78
+ controller.abort(error);
79
+ reject(error);
80
+ });
81
+ });
82
+ try {
83
+ return await Promise.race([Promise.resolve().then(() => run({ signal: controller.signal })), expired]);
84
+ } finally {
85
+ cancel();
86
+ }
87
+ }
88
+ const timedAttempts = /* @__PURE__ */ new WeakSet();
89
+ /** Adds a timeout once, including when a provider receives an already wrapped folder step. */
90
+ function withWorkflowStepTimeout(name, timeout, run) {
91
+ if (timeout === void 0 || timedAttempts.has(run)) return run;
92
+ const attempt = () => runWorkflowStepAttempt(name, timeout, run);
93
+ timedAttempts.add(attempt);
94
+ return attempt;
95
+ }
96
+ async function runProviderStep(step, name, run, options) {
97
+ const resolved = resolveWorkflowStepOptions(name, options);
98
+ const attempt = () => runWorkflowStepAttempt(name, resolved.timeout, run);
99
+ timedAttempts.add(attempt);
100
+ if (typeof step?.do === "function") return await step.do(name, resolved, attempt);
13
101
  const recorder = getWorkflowDevRecorder();
14
- return recorder ? await recorder.step(name, run) : await run();
102
+ return recorder ? await recorder.step(name, attempt) : await attempt();
15
103
  }
16
104
  /** `01.create-user.ts` becomes the `createUser` step. */
17
105
  function toStepPropertyName(file) {
@@ -25,7 +113,7 @@ function createWorkflowSteps(context, stepModules) {
25
113
  const previousName = names.get(propertyName);
26
114
  if (previousName) throw workflowErrorDiagnostics.WORKFLOW_C0010({ message: `[vitehub] Workflow step files ${JSON.stringify(previousName)} and ${JSON.stringify(module.name)} both normalize to the \`${propertyName}\` step property. Rename one file so each step property is unique.` });
27
115
  names.set(propertyName, module.name);
28
- return [propertyName, async (input) => await runProviderStep(context.step, `${context.name}/${module.name}`, () => module.run(input))];
116
+ return [propertyName, async (input) => await runProviderStep(context.step, `${context.name}/${module.name}`, (stepContext) => module.run(input, stepContext), module.options)];
29
117
  }));
30
118
  }
31
119
  /** The units of a sleep duration, in milliseconds. Cloudflare reads a month as 30 days and a year as 365.25 days. */
@@ -39,16 +127,21 @@ const durationUnits = {
39
127
  year: 315576e5
40
128
  };
41
129
  const durationPattern = /^(\d+(?:\.\d+)?) (second|minute|hour|day|week|month|year)s?$/;
130
+ /** The milliseconds of a `WorkflowDuration`: a number of 0 or more, or a string such as `'30 seconds'`. */
131
+ function toDurationMilliseconds(value) {
132
+ if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : void 0;
133
+ if (typeof value !== "string") return void 0;
134
+ const match = durationPattern.exec(value);
135
+ return match ? Number(match[1]) * durationUnits[match[2]] : void 0;
136
+ }
42
137
  /** A sleep target: a number of milliseconds, or a date. */
43
138
  function toSleepTarget(name, until) {
44
139
  if (Object.prototype.toString.call(until) === "[object Date]") {
45
140
  const date = new Date(until.getTime());
46
141
  if (Number.isFinite(date.getTime())) return date;
47
- } else if (typeof until === "number") {
48
- if (Number.isFinite(until) && until >= 0) return until;
49
- } else if (typeof until === "string") {
50
- const match = durationPattern.exec(until);
51
- if (match) return Number(match[1]) * durationUnits[match[2]];
142
+ } else {
143
+ const milliseconds = toDurationMilliseconds(until);
144
+ if (milliseconds !== void 0) return milliseconds;
52
145
  }
53
146
  const value = typeof until === "string" ? JSON.stringify(until) : String(until);
54
147
  throw workflowErrorDiagnostics.WORKFLOW_SLEEP_DURATION_INVALID({
@@ -115,7 +208,7 @@ function readNonRetryableStepResult(value) {
115
208
  * so the provider does not retry it and run the code before the sleep again.
116
209
  */
117
210
  async function runInRootStep(context, definition, encode) {
118
- if (definition.options?.rootStep === false) return await encode(await definition.handler(context.payload, toExecutionContext(context, createSleep(context))));
211
+ if (definition.rootStep === false) return await encode(await definition.handler(toExecutionContext(context, createSleep(context))));
119
212
  let slept = false;
120
213
  const sleepError = () => workflowErrorDiagnostics.WORKFLOW_ROOT_STEP_SLEEP({ name: context.name });
121
214
  const sleep = async () => {
@@ -124,7 +217,7 @@ async function runInRootStep(context, definition, encode) {
124
217
  };
125
218
  const output = await runProviderStep(context.step, context.name, async () => {
126
219
  try {
127
- const value = await encode(await definition.handler(context.payload, toExecutionContext(context, sleep)));
220
+ const value = await encode(await definition.handler(toExecutionContext(context, sleep)));
128
221
  return slept ? rootStepSleepResult : value;
129
222
  } catch (error) {
130
223
  if (slept) return rootStepSleepResult;
@@ -151,4 +244,4 @@ async function runSerializedWorkflowHandler(context, definition) {
151
244
  return await runInRootStep(context, definition, toStoredWorkflowResult);
152
245
  }
153
246
  //#endregion
154
- export { createWorkflowSteps, readNonRetryableStepResult, runProviderStep, runSerializedWorkflowHandler, runWorkflowHandler, toNonRetryableStepResult, toStepPropertyName };
247
+ export { createWorkflowSteps, readNonRetryableStepResult, resolveWorkflowStepOptions, runProviderStep, runSerializedWorkflowHandler, runWorkflowHandler, runWorkflowStepAttempt, toDurationMilliseconds, toNonRetryableStepResult, toStepPropertyName, withWorkflowStepTimeout };
@@ -1,5 +1,5 @@
1
- import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
2
- import { o as getOpenWorkflowRuntime } from "../openworkflow-TEaNk0LV.js";
1
+ import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-Dsmwsdlv.js";
2
+ import { o as getOpenWorkflowRuntime } from "../openworkflow-BhzxV_Y3.js";
3
3
  import { ViteHubError } from "@vite-hub/runtime";
4
4
  import { ShutdownApp } from "@vite-hub/runtime/internal/shutdown";
5
5
  //#region src/runtime/openworkflow-worker.d.ts
@@ -1,4 +1,4 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
2
2
  import { n as createWorkflowError } from "../errors-DCqRnZpN.js";
3
3
  import { i as runWorkflowProviderOperation } from "../run-error-DBWqiJHH.js";
4
4
  import { describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter } from "./openworkflow.js";
@@ -1,2 +1,2 @@
1
- import { a as getOpenWorkflowRun, c as resetOpenWorkflowRuntime, d as setOpenWorkflowImporter, i as detachOpenWorkflowRuntimes, l as runOpenWorkflow, n as cancelOpenWorkflowRun, o as getOpenWorkflowRuntime, r as describeOpenWorkflowStorage, s as registerOpenWorkflowDefinition, t as OpenWorkflowStorageSource, u as setOpenWorkflowDatabaseUrl } from "../openworkflow-TEaNk0LV.js";
1
+ import { a as getOpenWorkflowRun, c as resetOpenWorkflowRuntime, d as setOpenWorkflowImporter, i as detachOpenWorkflowRuntimes, l as runOpenWorkflow, n as cancelOpenWorkflowRun, o as getOpenWorkflowRuntime, r as describeOpenWorkflowStorage, s as registerOpenWorkflowDefinition, t as OpenWorkflowStorageSource, u as setOpenWorkflowDatabaseUrl } from "../openworkflow-BhzxV_Y3.js";
2
2
  export { OpenWorkflowStorageSource, cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
@@ -1,9 +1,10 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
2
2
  import { t as resolveOpenWorkflowStorage } from "../openworkflow-storage-Dj9zUAsk.js";
3
3
  import { n as createWorkflowError } from "../errors-DCqRnZpN.js";
4
- import { readNonRetryableStepResult, runSerializedWorkflowHandler, toNonRetryableStepResult } from "./execute.js";
4
+ import { readNonRetryableStepResult, resolveWorkflowStepOptions, runSerializedWorkflowHandler, toDurationMilliseconds, toNonRetryableStepResult, withWorkflowStepTimeout } from "./execute.js";
5
5
  import { r as invariantError, t as defaultOpenWorkflowSqlitePath } from "../openworkflow-defaults-DDig2M4s.js";
6
6
  import { i as runWorkflowProviderOperation, n as getWorkflowProviderStatus, t as toWorkflowRunError } from "../run-error-DBWqiJHH.js";
7
+ import { t as emitWorkflowFailed } from "../run-failed-gVGo1BaF.js";
7
8
  import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime";
8
9
  //#region src/runtime/openworkflow.ts
9
10
  const defaultImporter = (specifier) => import(
@@ -163,7 +164,24 @@ async function withPostgresSetupLock(postgres, url, schema, setup) {
163
164
  await sql.end({ timeout: 5 });
164
165
  }
165
166
  }
167
+ /**
168
+ * The backend that the OpenWorkflow client and its workers use. OpenWorkflow retries a failed run by its retry policy, so
169
+ * only `failWorkflowRun()` knows when a run ends as `failed`. This wrapper sends `workflow.failed` then.
170
+ */
171
+ function reportFailedRuns(backend, definitions) {
172
+ const failWorkflowRun = async (params) => {
173
+ const run = await backend.failWorkflowRun(params);
174
+ if (run.status === "failed") await emitWorkflowFailed(run.workflowName, run.idempotencyKey || run.id, run.error ?? params.error, definitions.get(run.workflowName));
175
+ return run;
176
+ };
177
+ return new Proxy(backend, { get(target, property) {
178
+ if (property === "failWorkflowRun") return failWorkflowRun;
179
+ const value = Reflect.get(target, property);
180
+ return typeof value === "function" ? value.bind(target) : value;
181
+ } });
182
+ }
166
183
  async function createOpenWorkflowRuntime(options, importer) {
184
+ const definitions = /* @__PURE__ */ new Map();
167
185
  const [{ OpenWorkflow }, backendModule] = await Promise.all([importOpenWorkflowModule("openworkflow", importer), options.backend === "sqlite" ? importOpenWorkflowModule("openworkflow/sqlite", importer) : importOpenWorkflowModule("openworkflow/postgres", importer)]);
168
186
  const { backend, client } = await runWorkflowProviderOperation("openworkflow", "connect", async () => {
169
187
  let backend;
@@ -182,12 +200,13 @@ async function createOpenWorkflowRuntime(options, importer) {
182
200
  }
183
201
  return {
184
202
  backend,
185
- client: new OpenWorkflow({ backend })
203
+ client: new OpenWorkflow({ backend: reportFailedRuns(backend, definitions) })
186
204
  };
187
205
  });
188
206
  return {
189
207
  backend,
190
208
  client,
209
+ definitions,
191
210
  findRunId: createRunIdLookup(backend, options),
192
211
  workflows: /* @__PURE__ */ new Map()
193
212
  };
@@ -250,13 +269,19 @@ async function getOpenWorkflowRuntime(config) {
250
269
  });
251
270
  return resolved;
252
271
  }
253
- function toOpenWorkflowRetryPolicy(options) {
254
- const retries = options.retries;
255
- if (!retries) return;
272
+ /**
273
+ * OpenWorkflow counts attempts, and `limit` counts the retries after the first attempt. OpenWorkflow caps each wait at
274
+ * `maximumInterval`, 100 seconds by default, so the cap is the longest wait that the policy asks for.
275
+ */
276
+ function toOpenWorkflowRetryPolicy(name, options) {
277
+ const { backoff, delay, limit } = resolveWorkflowStepOptions(name, options).retries;
278
+ const initial = toDurationMilliseconds(delay);
279
+ const coefficient = backoff === "exponential" ? 2 : 1;
256
280
  return {
257
- ...retries.backoff ? { backoffCoefficient: retries.backoff === "exponential" ? 2 : 1 } : {},
258
- ...retries.delay ? { initialInterval: retries.delay } : {},
259
- ...typeof retries.limit === "number" ? { maximumAttempts: retries.limit } : {}
281
+ backoffCoefficient: coefficient,
282
+ initialInterval: `${initial}ms`,
283
+ maximumAttempts: limit + 1,
284
+ maximumInterval: `${initial * coefficient ** Math.max(limit - 1, 0)}ms`
260
285
  };
261
286
  }
262
287
  function createOpenWorkflowProviderStep(step) {
@@ -264,10 +289,10 @@ function createOpenWorkflowProviderStep(step) {
264
289
  async do(name, options, run) {
265
290
  const output = await step.run({
266
291
  name,
267
- ...toOpenWorkflowRetryPolicy(options) ? { retryPolicy: toOpenWorkflowRetryPolicy(options) } : {}
292
+ retryPolicy: toOpenWorkflowRetryPolicy(name, options)
268
293
  }, async () => {
269
294
  try {
270
- return await run();
295
+ return await withWorkflowStepTimeout(name, options.timeout, run)();
271
296
  } catch (error) {
272
297
  const result = toNonRetryableStepResult(error);
273
298
  if (result) return result;
@@ -285,6 +310,7 @@ async function registerOpenWorkflowDefinition(runtime, name, definition) {
285
310
  const existing = runtime.workflows.get(name);
286
311
  if (existing) return existing;
287
312
  const openWorkflowDefinition = definition;
313
+ runtime.definitions.set(name, definition);
288
314
  const workflow = runtime.client.defineWorkflow({ name }, async ({ input, run, step }) => {
289
315
  const stored = await runtime.backend.getWorkflowRun({ workflowRunId: run.id });
290
316
  return await runSerializedWorkflowHandler({
@@ -1,4 +1,4 @@
1
- import { f as WorkflowDefinition, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
1
+ import { f as WorkflowDefinition, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-Dsmwsdlv.js";
2
2
  //#region src/runtime/state.d.ts
3
3
  export interface WorkflowRunState<TResult = unknown> {
4
4
  error?: unknown;
@@ -1,5 +1,4 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
2
- import { assertWorkflowDefinitionName } from "../definition.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
3
2
  import { n as setWorkflowDevRecorder } from "../dev-recorder-CTN5Fkao.js";
4
3
  import { AsyncLocalStorage } from "node:async_hooks";
5
4
  //#region src/runtime/state.ts
@@ -153,10 +152,7 @@ async function loadWorkflowDefinition(name) {
153
152
  const registeredInlineDefinition = loadingInlineDefinitions.get(name) ?? (generation === runtimeRegistryGeneration ? consumeInlineWorkflowDefinition(name) : void 0);
154
153
  if (registeredInlineDefinition) consumeInlineWorkflowDefinition(name, registeredInlineDefinition);
155
154
  const definition = "default" in loaded ? loaded.default : loaded;
156
- if (definition && typeof definition.handler === "function") {
157
- assertWorkflowDefinitionName(name, definition);
158
- return definition;
159
- }
155
+ if (definition && typeof definition.handler === "function") return definition;
160
156
  if (registeredInlineDefinition) return registeredInlineDefinition;
161
157
  const exportedInlineDefinition = findExportedInlineWorkflowDefinition(name, loaded, loadingInlineDefinitions);
162
158
  if (!exportedInlineDefinition) return void 0;
@@ -1,4 +1,4 @@
1
- import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
1
+ import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-Dsmwsdlv.js";
2
2
  import { t as VitehubApp } from "../app-BojnC_yf.js";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  //#region src/runtime/vercel.d.ts
@@ -1,6 +1,6 @@
1
1
  import { runWithWorkflowRuntimeEvent, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
2
- import { i as setVercelWorkflowRuntimeModules } from "../vercel-BZU_O6ay.js";
3
- import { t as resolveAppFetch } from "../app-CmMq8l4t.js";
2
+ import { i as setVercelWorkflowRuntimeModules } from "../vercel-DTvm61iY.js";
3
+ import { t as resolveAppFetch } from "../app-He0GTrYZ.js";
4
4
  import { waitUntil } from "@vercel/functions";
5
5
  import { H3 } from "h3";
6
6
  //#region ../internal/src/runtime/vercel-hosted.ts
@@ -1,3 +1,4 @@
1
+ import { Duration, Result } from "@vite-hub/runtime";
1
2
  //#region src/types.d.ts
2
3
  type WorkflowDriver = "cloudflare" | "openworkflow" | "vercel";
3
4
  interface CloudflareWorkflowBinding<TPayload = unknown> {
@@ -113,14 +114,30 @@ interface WorkflowRunStep {
113
114
  startedAt?: Date;
114
115
  status: WorkflowRunStatus;
115
116
  }
117
+ /** How the wait between retries grows: `exponential` doubles it after each retry, `constant` keeps it. */
118
+ type WorkflowStepBackoff = "constant" | "exponential";
119
+ /** When a step runs again after it throws. The defaults are `{ limit: 3, delay: '10 seconds', backoff: 'exponential' }`. */
120
+ interface WorkflowStepRetries {
121
+ backoff?: WorkflowStepBackoff;
122
+ /** How long to wait before the first retry. */
123
+ delay?: WorkflowDuration;
124
+ /** How many times to run the step again after the first attempt fails. `0` runs it once. */
125
+ limit?: number;
126
+ }
127
+ /**
128
+ * The options of one step. A step file exports them as `retries` and `timeout`. `timeout` is the time limit of one
129
+ * attempt: when it passes, the step's `signal` aborts and the attempt fails with `WORKFLOW_STEP_TIMEOUT`.
130
+ */
116
131
  interface WorkflowStepOptions {
117
- retries?: {
118
- backoff?: string;
119
- delay?: string;
120
- limit?: number;
121
- };
132
+ retries?: WorkflowStepRetries;
133
+ timeout?: WorkflowDuration;
122
134
  }
123
- type WorkflowStepFunction<TInput = unknown, TResult = unknown> = (input: TInput) => TResult | Promise<TResult>;
135
+ /** The second argument of a step function. */
136
+ interface WorkflowStepContext {
137
+ /** Aborts when the `timeout` of the step passes. Pass it to `fetch()` and other calls that take a signal. */
138
+ signal: AbortSignal;
139
+ }
140
+ type WorkflowStepFunction<TInput = unknown, TResult = unknown> = (input: TInput, context: WorkflowStepContext) => TResult | Promise<TResult>;
124
141
  interface WorkflowProviderStep {
125
142
  do?: <TResult>(name: string, options: WorkflowStepOptions, run: () => TResult | Promise<TResult>) => Promise<TResult>;
126
143
  /** Sleeps for a number of milliseconds. ViteHub names each sleep by call order. */
@@ -139,10 +156,30 @@ type WorkflowDuration = number | `${number} ${WorkflowDurationUnit}` | `${number
139
156
  * `.vitehub/workflow.d.ts` from the numbered files in `server/workflows/<name>/`.
140
157
  */
141
158
  interface WorkflowStepRegistry {}
159
+ /**
160
+ * The Workflow Definitions of the app, by name. ViteHub writes it to `.vitehub/workflow.d.ts` from the files in
161
+ * `server/workflows/`, so `startWorkflow()` checks the name and the payload.
162
+ */
163
+ interface WorkflowRegistry {}
164
+ /** A Workflow name from `WorkflowRegistry`. Any string before ViteHub writes the registry. */
165
+ type WorkflowName = [keyof WorkflowRegistry] extends [never] ? string : Extract<keyof WorkflowRegistry, string>;
166
+ /** The payload type of the Workflow `TName`, from the `payload` that its handler reads. */
167
+ type WorkflowPayload<TName extends string> = TName extends keyof WorkflowRegistry ? WorkflowRegistry[TName] extends {
168
+ handler: (context: infer TContext) => unknown;
169
+ } ? TContext extends {
170
+ payload: infer TPayload;
171
+ } ? TPayload : unknown : unknown : unknown;
142
172
  /** A step runs one input through its step file, inside a durable provider step. */
143
173
  type WorkflowStep<TStep> = TStep extends ((...args: infer TArguments) => infer TResult) ? (...input: TArguments extends [] ? [] : TArguments extends [unknown, ...unknown[]] ? [input: TArguments[0]] : [input?: TArguments[0]]) => Promise<Awaited<TResult>> : never;
144
- /** The step functions of the Workflow `TName`. Empty for a Workflow without step files. */
145
- type WorkflowSteps<TName extends string = string> = TName extends keyof WorkflowStepRegistry ? { readonly [TStep in keyof WorkflowStepRegistry[TName]]: WorkflowStep<WorkflowStepRegistry[TName][TStep]>; } : { readonly [TStep in never]: never; };
174
+ type StepsInFolder<TFolder> = TFolder extends unknown ? keyof TFolder : never;
175
+ type StepInFolder<TFolder, TStep> = TFolder extends unknown ? TStep extends keyof TFolder ? WorkflowStep<TFolder[TStep]> : never : never;
176
+ type WorkflowStepFolders = WorkflowStepRegistry[keyof WorkflowStepRegistry];
177
+ /**
178
+ * The step functions of the folder Workflows. A definition does not name its Workflow, so `steps` has the steps of
179
+ * every folder Workflow: a step name that no folder has is a type error. A shared step name accepts only inputs
180
+ * valid for all its implementations and returns any of their results. At runtime, a Workflow gets only its own steps.
181
+ */
182
+ type WorkflowSteps = { readonly [TStep in StepsInFolder<WorkflowStepFolders>]: StepInFolder<WorkflowStepFolders, TStep>; };
146
183
  /** Run data that a provider gives to ViteHub before ViteHub adds the step runner. */
147
184
  interface WorkflowProviderContext<TPayload = unknown> {
148
185
  id?: string;
@@ -151,8 +188,8 @@ interface WorkflowProviderContext<TPayload = unknown> {
151
188
  provider: WorkflowDriver;
152
189
  step?: WorkflowProviderStep;
153
190
  }
154
- interface WorkflowExecutionContext<TPayload = unknown, TName extends string = string> extends Omit<WorkflowProviderContext<TPayload>, "step"> {
155
- name: TName;
191
+ /** The one object that a Workflow handler receives: the `payload` of the run, the run data, `sleep`, and `steps`. */
192
+ interface WorkflowExecutionContext<TPayload = unknown> extends Omit<WorkflowProviderContext<TPayload>, "step"> {
156
193
  /** The provider step runner. Use `context.sleep()` to sleep. */
157
194
  step?: Omit<WorkflowProviderStep, "sleep" | "sleepUntil">;
158
195
  /**
@@ -162,9 +199,9 @@ interface WorkflowExecutionContext<TPayload = unknown, TName extends string = st
162
199
  */
163
200
  sleep: (until: WorkflowDuration | Date) => Promise<void>;
164
201
  /** Step functions from the numbered files in the Workflow folder. Empty when the Workflow has no step files. */
165
- steps: WorkflowSteps<TName>;
202
+ steps: WorkflowSteps;
166
203
  }
167
- type WorkflowHandler<TPayload = unknown, TResult = unknown, TName extends string = string> = (payload: TPayload, context: WorkflowExecutionContext<TPayload, TName>) => TResult | Promise<TResult>;
204
+ type WorkflowHandler<TPayload = unknown, TResult = unknown> = (context: WorkflowExecutionContext<TPayload>) => TResult | Promise<TResult>;
168
205
  type WorkflowRunIdValue = boolean | null | number | string | undefined | {
169
206
  readonly [key: string]: WorkflowRunIdValue;
170
207
  } | readonly WorkflowRunIdValue[];
@@ -179,34 +216,38 @@ interface WorkflowCreateOptions<TPayload = unknown, TResult = unknown> {
179
216
  name?: string;
180
217
  rootStep?: boolean;
181
218
  }
219
+ /** Options of `defineWorkflow()`, next to `handler`. */
182
220
  interface WorkflowDefinitionOptions<TPayload = unknown, TResult = unknown> {
183
- id?: string;
184
221
  /** Vercel native entry. Vercel calls it with the provider context only, so it gets no step runner. */
185
222
  native?: (context: WorkflowProviderContext<TPayload>) => TResult | Promise<TResult>;
186
223
  rootStep?: boolean;
187
224
  }
188
- interface WorkflowDefinition<TPayload = unknown, TResult = unknown, TName extends string = string> {
225
+ /** A Workflow Definition: `defineWorkflow({ handler, ...options })`. Its file path is its name. */
226
+ interface WorkflowDefinition<TPayload = unknown, TResult = unknown> extends WorkflowDefinitionOptions<TPayload, TResult> {
189
227
  /** @internal Identifies provider-generated Agent invocation recovery definitions. */
190
228
  internalAgentInvocationRecovery?: true;
191
229
  /** @internal Identifies the inline Agent Workflow handler that the Agent package creates for an Agent turn. */
192
230
  internalAgentWorkflow?: true;
193
- handler: WorkflowHandler<TPayload, TResult, TName>;
194
- /** The discovered Workflow name. `defineWorkflow()` sets it; inline and generated definitions may leave it out. */
195
- name?: string;
196
- options?: WorkflowDefinitionOptions<TPayload, TResult>;
231
+ handler: WorkflowHandler<TPayload, TResult>;
197
232
  }
198
233
  /** Omission is valid only when the handler accepts undefined. */
199
234
  type WorkflowStartArguments<TPayload> = undefined extends TPayload ? [payload?: TPayload, options?: WorkflowStartOptions] : [payload: TPayload, options?: WorkflowStartOptions];
235
+ /**
236
+ * Codes that `startWorkflow()`, `getWorkflowRun()`, `cancelWorkflow()`, `resumeWorkflow()`, and the methods of a
237
+ * WorkflowHandle return in the `[error, data]` tuple. Config errors throw instead.
238
+ */
239
+ type WorkflowResultErrorCode = "RUNTIME_DURATION_INVALID" | "WORKFLOW_CLOUDFLARE_RUN_ID_INVALID" | "WORKFLOW_OPERATION_UNSUPPORTED" | "WORKFLOW_PROVIDER_OPERATION_FAILED" | "WORKFLOW_R0014" | "WORKFLOW_RUN_ID_UNSUPPORTED" | "WORKFLOW_START_DELAY_INVALID";
240
+ /** `cancel()`, `getRun()`, and `start()` return `[error, data]`, as `cancelWorkflow()`, `getWorkflowRun()`, and `startWorkflow()` do. */
200
241
  interface WorkflowHandle<TPayload = unknown, TResult = unknown> {
201
- cancel: (id: string) => Promise<WorkflowRun<unknown, unknown>>;
242
+ cancel: (id: string) => Promise<Result<WorkflowRun<unknown, unknown>, WorkflowResultErrorCode>>;
202
243
  /** Starts a run after the response, through `waitUntil`. A failure goes to the log. */
203
244
  defer: (...args: WorkflowStartArguments<TPayload>) => void;
204
- getRun: (id: string) => Promise<WorkflowRun<unknown, unknown>>;
245
+ getRun: (id: string) => Promise<Result<WorkflowRun<unknown, unknown>, WorkflowResultErrorCode>>;
205
246
  name: string;
206
- start: (...args: WorkflowStartArguments<TPayload>) => Promise<WorkflowRun<TPayload, TResult>>;
247
+ start: (...args: WorkflowStartArguments<TPayload>) => Promise<Result<WorkflowRun<TPayload, TResult>, WorkflowResultErrorCode>>;
207
248
  }
208
- /** Milliseconds, a duration such as `"30 minutes"` or `"3 days"`, or a `Date` that the run must not start before. */
209
- type WorkflowStartDelay = number | string | Date;
249
+ /** A duration such as `"30m"` or `"3 days"`, or a `Date` that the run must not start before. */
250
+ type WorkflowStartDelay = Duration | Date;
210
251
  interface WorkflowStartOptions {
211
252
  /** Starts the run later. A `Date` in the past starts it now. */
212
253
  delay?: WorkflowStartDelay;
@@ -223,9 +264,9 @@ interface WorkflowSignalResult {
223
264
  */
224
265
  interface WorkflowDefinitionRegistry {
225
266
  [name: string]: (() => Promise<{
226
- default?: WorkflowDefinition<never, unknown, never>;
267
+ default?: WorkflowDefinition<never, unknown>;
227
268
  [exportName: string]: unknown;
228
- } | WorkflowDefinition<never, unknown, never>>) & {
269
+ } | WorkflowDefinition<never, unknown>>) & {
229
270
  /** @internal Identifies provider-generated Agent invocation recovery definitions without evaluating their modules. */
230
271
  internalAgentInvocationRecovery?: true;
231
272
  };
@@ -238,4 +279,4 @@ interface DiscoveredWorkflowDefinition {
238
279
  steps?: string[];
239
280
  }
240
281
  //#endregion
241
- export { WorkflowRuntimeConfigValue as A, WorkflowOptions as C, WorkflowRunError as D, WorkflowRun as E, WorkflowStep as F, WorkflowStepFunction as I, WorkflowStepOptions as L, WorkflowSignalResult as M, WorkflowStartDelay as N, WorkflowRunStatus as O, WorkflowStartOptions as P, WorkflowStepRegistry as R, WorkflowModuleDriverOptions as S, WorkflowProviderStep as T, WorkflowDuration as _, InferredWorkflowDriverOptions as a, WorkflowHandle as b, OpenWorkflowWorkerOptions as c, WorkflowCreateOptions as d, WorkflowDefinition as f, WorkflowDriverOptions as g, WorkflowDriver as h, DiscoveredWorkflowDefinition as i, WorkflowSharedOptions as j, WorkflowRunStep as k, ResolvedWorkflowOptions as l, WorkflowDefinitionRegistry as m, CloudflareWorkflowDriverOptions as n, OpenWorkflowDriverOptions as o, WorkflowDefinitionOptions as p, CloudflareWorkflowInstance as r, OpenWorkflowPostgresOptions as s, CloudflareWorkflowBinding as t, VercelWorkflowDriverOptions as u, WorkflowDurationUnit as v, WorkflowProviderContext as w, WorkflowHandler as x, WorkflowExecutionContext as y, WorkflowSteps as z };
282
+ export { WorkflowRun as A, WorkflowStep as B, WorkflowName as C, WorkflowProviderStep as D, WorkflowProviderContext as E, WorkflowSharedOptions as F, WorkflowStepRegistry as G, WorkflowStepContext as H, WorkflowSignalResult as I, WorkflowStepRetries as K, WorkflowStartArguments as L, WorkflowRunStatus as M, WorkflowRunStep as N, WorkflowRegistry as O, WorkflowRuntimeConfigValue as P, WorkflowStartDelay as R, WorkflowModuleDriverOptions as S, WorkflowPayload as T, WorkflowStepFunction as U, WorkflowStepBackoff as V, WorkflowStepOptions as W, WorkflowDuration as _, InferredWorkflowDriverOptions as a, WorkflowHandle as b, OpenWorkflowWorkerOptions as c, WorkflowCreateOptions as d, WorkflowDefinition as f, WorkflowDriverOptions as g, WorkflowDriver as h, DiscoveredWorkflowDefinition as i, WorkflowRunError as j, WorkflowResultErrorCode as k, ResolvedWorkflowOptions as l, WorkflowDefinitionRegistry as m, CloudflareWorkflowDriverOptions as n, OpenWorkflowDriverOptions as o, WorkflowDefinitionOptions as p, WorkflowSteps as q, CloudflareWorkflowInstance as r, OpenWorkflowPostgresOptions as s, CloudflareWorkflowBinding as t, VercelWorkflowDriverOptions as u, WorkflowDurationUnit as v, WorkflowOptions as w, WorkflowHandler as x, WorkflowExecutionContext as y, WorkflowStartOptions as z };
@@ -1,6 +1,6 @@
1
- import { t as workflowErrorDiagnostics } from "./error-diagnostics-8YNJ37rP.js";
1
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
2
2
  import { n as createWorkflowError } from "./errors-DCqRnZpN.js";
3
- import { a as workflowStartAtKey } from "./delay--ESDybVT.js";
3
+ import { a as workflowStartAtKey } from "./delay-D1-nq_VE.js";
4
4
  import { a as safeWorkflowName, i as runWorkflowProviderOperation, r as isWorkflowBoundaryError, t as toWorkflowRunError } from "./run-error-DBWqiJHH.js";
5
5
  //#region src/runtime/vercel.ts
6
6
  async function loadVercelWorkflowRuntime() {
@@ -165,7 +165,7 @@ async function readVercelRunError(run) {
165
165
  return toWorkflowRunError(void 0);
166
166
  }
167
167
  function getNativeWorkflowName(name, definition) {
168
- const workflowName = (definition.options?.native)?.workflowId;
168
+ const workflowName = definition.native?.workflowId;
169
169
  if (!workflowName) throw createWorkflowError({
170
170
  code: "WORKFLOW_NATIVE_ENTRY_INVALID",
171
171
  details: {
@@ -215,7 +215,7 @@ async function inspectVercelWorkflowRun(name, definition, id, payload) {
215
215
  };
216
216
  }
217
217
  async function startVercelWorkflow(name, definition, payload, observeSettlement, onDispatch, startAt) {
218
- const native = definition.options?.native;
218
+ const native = definition.native;
219
219
  if (!native) throw createWorkflowError({
220
220
  code: "WORKFLOW_NATIVE_ENTRY_REQUIRED",
221
221
  details: {
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { C as WorkflowOptions, i as DiscoveredWorkflowDefinition } from "./types-CnKVDnEp.js";
2
- import { n as OperationContributionEntry } from "./operation-definition-8gOe-ubD.js";
3
- import { Plugin, ResolvedConfig, UserConfig } from "vite";
4
- import { Plugin as Plugin$1 } from "esbuild";
1
+ import { i as DiscoveredWorkflowDefinition, w as WorkflowOptions } from "./types-Dsmwsdlv.js";
2
+ import { n as OperationContributionEntry } from "./operation-definition-nmRu_O3V.js";
3
+ import { Plugin, ResolvedConfig, Rolldown, UserConfig } from "vite";
5
4
  //#region src/internal/runtime-modules.d.ts
6
5
  type WorkflowRuntimeModuleName = "cloudflare-runner" | "cloudflare-vite" | "dev-runs" | "execute" | "openworkflow-worker" | "state" | "vercel-vite";
7
6
  /**
@@ -142,7 +141,7 @@ interface ProviderOutputEnvironmentOwner {
142
141
  nitro: {
143
142
  name: string;
144
143
  setup: (nitro: {
145
- options: {
144
+ options: NitroPackageLoadingOptions & {
146
145
  static?: boolean;
147
146
  };
148
147
  }) => void;
@@ -152,6 +151,11 @@ interface ProviderOutputEnvironmentOwner {
152
151
  environment?: object;
153
152
  } | undefined) => boolean;
154
153
  }
154
+ type NitroPackageLoadingOptions = {
155
+ devServer?: {
156
+ runner?: string;
157
+ };
158
+ };
155
159
  //#endregion
156
160
  //#region src/discovery.d.ts
157
161
  export declare function discoverWorkflowDefinitions(options: {
@@ -165,7 +169,10 @@ export declare function discoverWorkflowDefinitions(options: {
165
169
  }): DiscoveredWorkflowDefinition[];
166
170
  //#endregion
167
171
  //#region src/internal/registry-types.d.ts
168
- /** Types `steps` in `defineWorkflow(name, handler)` with the step files of each folder Workflow. */
172
+ /**
173
+ * Types `startWorkflow()` with the name and payload of each Workflow Definition (`WorkflowRegistry`), and `steps` with
174
+ * the step files of each folder Workflow (`WorkflowStepRegistry`).
175
+ */
169
176
  export declare function createWorkflowTypes(file: string, definitions: DiscoveredWorkflowDefinition[], importBase?: string): string;
170
177
  //#endregion
171
178
  //#region ../internal/src/console.d.ts
@@ -481,6 +488,8 @@ interface ViteHubConsoleDocumentHint {
481
488
  * failing without a reason.
482
489
  */
483
490
  interface ViteHubConsoleDocumentSetup {
491
+ /** The project has GitHub Sources but no document collections. */
492
+ sourceHeadsOnly?: true;
484
493
  /** Present when no user can read anything because the owner has no access policy. */
485
494
  access?: ViteHubConsoleDocumentHint;
486
495
  /**
@@ -529,7 +538,7 @@ export type WorkflowVitePlugin = Plugin & Partial<Pick<ProviderOutputEnvironment
529
538
  createNitroConfig?: (options: WorkflowNitroConfigOptions) => Promise<Record<string, unknown>>;
530
539
  prepareScheduleRuntime?: (artifactDir?: string, config?: ResolvedConfig) => Promise<{
531
540
  bundleAlias: Record<string, string>;
532
- bundlePlugins?: Plugin$1[];
541
+ bundlePlugins?: Rolldown.Plugin[];
533
542
  native: boolean;
534
543
  registryFile: string;
535
544
  runtimeModules: {
@@ -544,7 +553,6 @@ interface InternalWorkflowModuleOptions {
544
553
  /** The module that exports `getPostgresConnectionUrl()`. Default `@vite-hub/database`. */
545
554
  databaseImport?: string;
546
555
  hosting?: string;
547
- implicitlyEnabled?: boolean;
548
556
  importBase?: string;
549
557
  providerImportAliases?: Record<string, string>;
550
558
  /**
@@ -553,12 +561,10 @@ interface InternalWorkflowModuleOptions {
553
561
  */
554
562
  includeUserAppEntry?: boolean | string;
555
563
  workspaceDependencyRuntimeImports?: {
556
- sandboxTask?: string;
557
- sandboxTaskRuntimeState?: string;
558
564
  shellWorkspace?: string;
559
565
  };
560
566
  workspaceRuntimeModule?: string;
561
567
  }
562
- export declare function hubWorkflow(options?: WorkflowOptions, internalOptions?: InternalWorkflowModuleOptions): WorkflowVitePlugin;
568
+ export declare function hubWorkflow(workflow?: WorkflowOptions, internalOptions?: InternalWorkflowModuleOptions): WorkflowVitePlugin;
563
569
  //#endregion
564
570
  export type { WorkflowInspectionOptions };