@vite-hub/workflow 0.0.4 → 0.3.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 (65) hide show
  1. package/README.md +168 -47
  2. package/dist/{_app-DgwN4ulW.d.ts → app-BojnC_yf.d.ts} +1 -4
  3. package/dist/{app-BZpq2cwC.js → app-CmMq8l4t.js} +2 -1
  4. package/dist/client-CU5rELC0.js +658 -0
  5. package/dist/{cloudflare-D0Di-QYL.js → cloudflare-BfFnNWB0.js} +20 -4
  6. package/dist/cloudflare-env-CGLx7lUd.js +115 -0
  7. package/dist/cloudflare-env-lookup-CfX6wZKb.d.ts +4 -0
  8. package/dist/{cloudflare-env-CIjdFTv6.d.ts → cloudflare-shared-CTqh_a2s.d.ts} +2 -2
  9. package/dist/config-DCvRDlxA.js +145 -0
  10. package/dist/definition.d.ts +19 -0
  11. package/dist/definition.js +31 -0
  12. package/dist/delay--ESDybVT.js +81 -0
  13. package/dist/dev-recorder-CTN5Fkao.js +10 -0
  14. package/dist/durability.d.ts +23 -0
  15. package/dist/durability.js +62 -0
  16. package/dist/error-diagnostics-8YNJ37rP.js +286 -0
  17. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  18. package/dist/errors-DCqRnZpN.js +35 -0
  19. package/dist/errors-DVwFb6Fd.d.ts +56 -0
  20. package/dist/index.d.ts +23 -71
  21. package/dist/index.js +23 -378
  22. package/dist/inspect-B72iFyj-.js +70 -0
  23. package/dist/object-Da1zyPCR.js +11 -0
  24. package/dist/openworkflow-TEaNk0LV.d.ts +50 -0
  25. package/dist/openworkflow-defaults-DDig2M4s.js +26 -0
  26. package/dist/openworkflow-storage-Dj9zUAsk.js +28 -0
  27. package/dist/openworkflow.d.ts +2 -0
  28. package/dist/openworkflow.js +2 -0
  29. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  30. package/dist/operations-B0L8kV5s.js +329 -0
  31. package/dist/operations.d.ts +71 -0
  32. package/dist/operations.js +314 -0
  33. package/dist/out-fRNaVslw.js +20357 -0
  34. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  35. package/dist/run-error-DBWqiJHH.js +110 -0
  36. package/dist/runtime/cloudflare-runner.d.ts +7 -19
  37. package/dist/runtime/cloudflare-runner.js +27 -10
  38. package/dist/runtime/cloudflare-shared.d.ts +2 -1
  39. package/dist/runtime/cloudflare-shared.js +1 -1
  40. package/dist/runtime/cloudflare-vite.d.ts +10 -11
  41. package/dist/runtime/cloudflare-vite.js +47 -1
  42. package/dist/runtime/dev-runs.d.ts +4 -0
  43. package/dist/runtime/dev-runs.js +73 -0
  44. package/dist/runtime/execute.d.ts +24 -7
  45. package/dist/runtime/execute.js +135 -6
  46. package/dist/runtime/openworkflow-worker.d.ts +34 -9
  47. package/dist/runtime/openworkflow-worker.js +156 -37
  48. package/dist/runtime/openworkflow.d.ts +2 -23
  49. package/dist/runtime/openworkflow.js +289 -46
  50. package/dist/runtime/state.d.ts +22 -21
  51. package/dist/runtime/state.js +99 -25
  52. package/dist/runtime/vercel-vite.d.ts +10 -12
  53. package/dist/runtime/vercel-vite.js +7 -4
  54. package/dist/types-CnKVDnEp.d.ts +241 -0
  55. package/dist/{vercel-B0MuIVgJ.js → vercel-BZU_O6ay.js} +78 -24
  56. package/dist/vite.d.ts +529 -23
  57. package/dist/vite.js +2789 -1609
  58. package/package.json +62 -34
  59. package/dist/cloudflare-env-DjxQNbrx.js +0 -58
  60. package/dist/cloudflare-shared-BVVgDSdq.d.ts +0 -1
  61. package/dist/cloudflare-vite-BkDgB6Sr.js +0 -46
  62. package/dist/config-BHknO_rT.js +0 -136
  63. package/dist/provider-operation-CW2cYfVy.js +0 -65
  64. package/dist/runtime-type-DGUn8Ple.js +0 -37
  65. package/dist/types-B9RdRkKh.d.ts +0 -169
@@ -1,23 +1,36 @@
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
2
+ import { assertWorkflowDefinitionName } from "../definition.js";
3
+ import { n as setWorkflowDevRecorder } from "../dev-recorder-CTN5Fkao.js";
1
4
  import { AsyncLocalStorage } from "node:async_hooks";
2
5
  //#region src/runtime/state.ts
3
6
  const RUNS_LIMIT = 1024;
4
- const RUNS_TTL_MS = 300 * 1e3;
7
+ const RUNS_TTL_MS = 3e5;
5
8
  let runtimeConfig;
6
9
  let runtimeRegistry;
7
10
  const inlineRegistry = /* @__PURE__ */ new Map();
8
11
  const loadingRegistryEntries = /* @__PURE__ */ new Map();
9
12
  const loadedRegistryEntries = /* @__PURE__ */ new Map();
13
+ let runtimeRegistryGeneration = 0;
10
14
  let fallbackEvent;
11
15
  const eventStorage = new AsyncLocalStorage();
12
16
  const loadingRegistryStorage = new AsyncLocalStorage();
13
17
  const loadingInlineRegistryStorage = new AsyncLocalStorage();
18
+ const loadingGenerationStorage = new AsyncLocalStorage();
14
19
  const runs = /* @__PURE__ */ new Map();
20
+ const inFlightRuns = /* @__PURE__ */ new Map();
21
+ const fallbackRunKeys = /* @__PURE__ */ new Set();
22
+ let collectedRuns;
23
+ const completedRuns = /* @__PURE__ */ new Map();
24
+ function isWeakReference(reference) {
25
+ return reference !== null && "deref" in reference;
26
+ }
15
27
  function getRunKey(name, id) {
16
- return `${name}\0${id}`;
28
+ return JSON.stringify([name, id]);
17
29
  }
18
30
  function pruneWorkflowRuns() {
19
31
  const now = Date.now();
20
- for (const [key, run] of runs) if (run.expiresAt && run.expiresAt <= now) runs.delete(key);
32
+ for (const [key, run] of completedRuns) if (run.expiresAt && run.expiresAt <= now) completedRuns.delete(key);
33
+ while (completedRuns.size > RUNS_LIMIT) completedRuns.delete(completedRuns.keys().next().value);
21
34
  }
22
35
  function setWorkflowRuntimeConfig(config) {
23
36
  runtimeConfig = config;
@@ -26,6 +39,8 @@ function getWorkflowRuntimeConfig() {
26
39
  return runtimeConfig;
27
40
  }
28
41
  function setWorkflowRuntimeRegistry(registry) {
42
+ if (runtimeRegistry !== registry) loadingRegistryEntries.clear();
43
+ runtimeRegistryGeneration++;
29
44
  runtimeRegistry = registry;
30
45
  loadedRegistryEntries.clear();
31
46
  }
@@ -42,7 +57,12 @@ function takeInlineWorkflowDefinition(name) {
42
57
  return definition;
43
58
  }
44
59
  function isWorkflowHandle(value) {
45
- return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.defer === "function" && typeof value.getRun === "function" && typeof value.run === "function";
60
+ if (typeof value !== "object" || value === null) return false;
61
+ const candidate = value;
62
+ if (typeof candidate.name !== "string") return false;
63
+ if (typeof candidate.defer !== "function") return false;
64
+ if (typeof candidate.getRun !== "function") return false;
65
+ return typeof candidate.start === "function";
46
66
  }
47
67
  function findExportedInlineWorkflowDefinition(name, loaded, definitions) {
48
68
  const namedDefinition = definitions.get(name);
@@ -83,13 +103,14 @@ function consumeInlineWorkflowDefinition(name, expected) {
83
103
  return definition;
84
104
  }
85
105
  function registerInlineWorkflowDefinition(name, definition) {
86
- if (!name || typeof name !== "string") throw new TypeError("`createWorkflow()` requires a workflow name.");
106
+ if (!name || typeof name !== "string") throw workflowErrorDiagnostics.WORKFLOW_R0023({ message: "`createWorkflow()` requires a workflow name." });
87
107
  const loadingDefinitions = loadingInlineRegistryStorage.getStore();
108
+ const loadingGeneration = loadingGenerationStorage.getStore();
88
109
  const existing = inlineRegistry.get(name);
89
110
  if (existing && existing !== definition) {
90
- if (!loadingDefinitions) throw new Error(`Duplicate workflow name "${name}" from inline definitions.`);
111
+ if (!loadingDefinitions) throw workflowErrorDiagnostics.WORKFLOW_R0024({ message: `Duplicate workflow name "${name}" from inline definitions.` });
91
112
  }
92
- inlineRegistry.set(name, definition);
113
+ if (loadingGeneration === void 0 || loadingGeneration === runtimeRegistryGeneration) inlineRegistry.set(name, definition);
93
114
  loadingDefinitions?.set(name, definition);
94
115
  }
95
116
  function enterWorkflowRuntimeEvent(event) {
@@ -105,11 +126,12 @@ async function runWithWorkflowRuntimeEvent(event, run) {
105
126
  return await eventStorage.run(event, run);
106
127
  }
107
128
  async function loadWorkflowDefinition(name) {
129
+ const generation = runtimeRegistryGeneration;
108
130
  const inlineDefinition = inlineRegistry.get(name);
109
- const entry = runtimeRegistry?.[name];
131
+ const entry = runtimeRegistry && Object.hasOwn(runtimeRegistry, name) ? runtimeRegistry[name] : void 0;
110
132
  if (entry && loadedRegistryEntries.has(name)) return loadedRegistryEntries.get(name);
111
133
  if (inlineDefinition) {
112
- if (entry) throw new Error(`Duplicate workflow name "${name}" from inline and discovered definitions.`);
134
+ if (entry) throw workflowErrorDiagnostics.WORKFLOW_R0025({ message: `Duplicate workflow name "${name}" from inline and discovered definitions.` });
113
135
  return inlineDefinition;
114
136
  }
115
137
  if (!entry) return;
@@ -120,15 +142,22 @@ async function loadWorkflowDefinition(name) {
120
142
  nextActiveLoads.add(name);
121
143
  const loadingEntry = Promise.resolve().then(() => loadingRegistryStorage.run(nextActiveLoads, async () => {
122
144
  const loadingInlineDefinitions = /* @__PURE__ */ new Map();
123
- const loaded = await loadingInlineRegistryStorage.run(loadingInlineDefinitions, entry);
124
- if (!loaded || typeof loaded !== "object") return;
125
- const registeredInlineDefinition = loadingInlineDefinitions.get(name) ?? consumeInlineWorkflowDefinition(name);
126
- if (registeredInlineDefinition) {
127
- consumeInlineWorkflowDefinition(name, registeredInlineDefinition);
128
- return registeredInlineDefinition;
145
+ let loaded;
146
+ try {
147
+ loaded = await loadingGenerationStorage.run(generation, () => loadingInlineRegistryStorage.run(loadingInlineDefinitions, entry));
148
+ } catch (error) {
149
+ for (const [definitionName, definition] of loadingInlineDefinitions) if (inlineRegistry.get(definitionName) === definition) inlineRegistry.delete(definitionName);
150
+ throw error;
129
151
  }
152
+ if (!loaded || typeof loaded !== "object") return;
153
+ const registeredInlineDefinition = loadingInlineDefinitions.get(name) ?? (generation === runtimeRegistryGeneration ? consumeInlineWorkflowDefinition(name) : void 0);
154
+ if (registeredInlineDefinition) consumeInlineWorkflowDefinition(name, registeredInlineDefinition);
130
155
  const definition = "default" in loaded ? loaded.default : loaded;
131
- if (definition && typeof definition.handler === "function") return definition;
156
+ if (definition && typeof definition.handler === "function") {
157
+ assertWorkflowDefinitionName(name, definition);
158
+ return definition;
159
+ }
160
+ if (registeredInlineDefinition) return registeredInlineDefinition;
132
161
  const exportedInlineDefinition = findExportedInlineWorkflowDefinition(name, loaded, loadingInlineDefinitions);
133
162
  if (!exportedInlineDefinition) return void 0;
134
163
  consumeInlineWorkflowDefinition(exportedInlineDefinition.name, exportedInlineDefinition.definition);
@@ -137,43 +166,88 @@ async function loadWorkflowDefinition(name) {
137
166
  loadingRegistryEntries.set(name, loadingEntry);
138
167
  try {
139
168
  const loaded = await loadingEntry;
140
- loadedRegistryEntries.set(name, loaded);
169
+ if (generation === runtimeRegistryGeneration && loadingRegistryEntries.get(name) === loadingEntry) loadedRegistryEntries.set(name, loaded);
141
170
  return loaded;
142
171
  } finally {
143
- loadingRegistryEntries.delete(name);
172
+ if (loadingRegistryEntries.get(name) === loadingEntry) loadingRegistryEntries.delete(name);
144
173
  }
145
174
  }
146
- function setWorkflowRun(name, id, promise) {
175
+ function setWorkflowRun(name, id, promise, payload, retainInFlight = false) {
147
176
  pruneWorkflowRuns();
148
- if (runs.size >= RUNS_LIMIT) {
149
- const oldest = runs.keys().next().value;
150
- if (oldest !== void 0) runs.delete(oldest);
151
- }
177
+ const key = getRunKey(name, id);
178
+ const canUseWeakReferences = globalThis.WeakRef !== void 0 && globalThis.FinalizationRegistry !== void 0;
179
+ if (canUseWeakReferences) collectedRuns ??= new FinalizationRegistry(({ key, reference }) => {
180
+ if (runs.get(key) === reference) runs.delete(key);
181
+ });
182
+ const previous = runs.get(key);
183
+ if (previous && canUseWeakReferences) collectedRuns?.unregister(previous);
184
+ fallbackRunKeys.delete(key);
185
+ completedRuns.delete(key);
152
186
  const state = {
187
+ payload,
153
188
  promise: promise.then((resolved) => {
154
189
  state.status = resolved.status;
155
190
  state.result = resolved.result;
156
191
  state.error = resolved.error;
157
192
  state.expiresAt = Date.now() + RUNS_TTL_MS;
193
+ if (inFlightRuns.get(key) === state) inFlightRuns.delete(key);
194
+ const active = runs.get(key);
195
+ if ((active && isWeakReference(active) ? active.deref() : active) === state) {
196
+ runs.delete(key);
197
+ fallbackRunKeys.delete(key);
198
+ if (isWeakReference(reference)) collectedRuns?.unregister(reference);
199
+ completedRuns.set(key, state);
200
+ pruneWorkflowRuns();
201
+ }
158
202
  return resolved;
159
203
  }),
160
204
  status: "running"
161
205
  };
162
- runs.set(getRunKey(name, id), state);
206
+ const reference = canUseWeakReferences ? new WeakRef(state) : state;
207
+ runs.set(key, reference);
208
+ if (retainInFlight) inFlightRuns.set(key, state);
209
+ if (isWeakReference(reference)) collectedRuns?.register(state, {
210
+ key,
211
+ reference
212
+ }, reference);
213
+ else {
214
+ fallbackRunKeys.add(key);
215
+ while (fallbackRunKeys.size > RUNS_LIMIT) {
216
+ const oldest = fallbackRunKeys.values().next().value;
217
+ fallbackRunKeys.delete(oldest);
218
+ runs.delete(oldest);
219
+ inFlightRuns.delete(oldest);
220
+ }
221
+ }
163
222
  return state;
164
223
  }
165
224
  function getWorkflowRunState(name, id) {
166
225
  pruneWorkflowRuns();
167
- return runs.get(getRunKey(name, id));
226
+ const key = getRunKey(name, id);
227
+ const inFlight = inFlightRuns.get(key);
228
+ if (inFlight) return inFlight;
229
+ const reference = runs.get(key);
230
+ const state = reference && isWeakReference(reference) ? reference.deref() : reference;
231
+ if (reference && !state) {
232
+ runs.delete(key);
233
+ if (isWeakReference(reference)) collectedRuns?.unregister(reference);
234
+ }
235
+ return state ?? completedRuns.get(key);
168
236
  }
169
237
  function resetWorkflowRuntime() {
238
+ runtimeRegistryGeneration++;
170
239
  runtimeConfig = void 0;
171
240
  runtimeRegistry = void 0;
172
241
  inlineRegistry.clear();
173
242
  loadingRegistryEntries.clear();
174
243
  loadedRegistryEntries.clear();
175
244
  fallbackEvent = void 0;
245
+ for (const reference of runs.values()) if (isWeakReference(reference)) collectedRuns?.unregister(reference);
176
246
  runs.clear();
247
+ inFlightRuns.clear();
248
+ fallbackRunKeys.clear();
249
+ completedRuns.clear();
250
+ setWorkflowDevRecorder(void 0);
177
251
  }
178
252
  //#endregion
179
253
  export { enterWorkflowRuntimeEvent, getInlineWorkflowDefinitions, getWorkflowRunState, getWorkflowRuntimeConfig, getWorkflowRuntimeEvent, getWorkflowRuntimeRegistry, loadWorkflowDefinition, registerInlineWorkflowDefinition, resetWorkflowRuntime, runWithWorkflowRuntimeEvent, setWorkflowRun, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry, takeInlineWorkflowDefinition, takeInlineWorkflowDefinitionForModule };
@@ -1,7 +1,6 @@
1
- import { h as WorkflowDefinitionRegistry, l as ResolvedWorkflowOptions } from "../types-B9RdRkKh.js";
2
- import { t as WorkflowApp } from "../_app-DgwN4ulW.js";
1
+ import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
2
+ import { t as VitehubApp } from "../app-BojnC_yf.js";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
-
5
4
  //#region src/runtime/vercel.d.ts
6
5
  interface VercelRun {
7
6
  cancel: () => Promise<void>;
@@ -40,7 +39,7 @@ interface VercelWorkflowRuntimeModule {
40
39
  getWorld: () => Promise<{
41
40
  steps: {
42
41
  list: (options: unknown) => Promise<{
43
- cursor?: string;
42
+ cursor?: string | null;
44
43
  data: unknown[];
45
44
  hasMore: boolean;
46
45
  }>;
@@ -48,23 +47,22 @@ interface VercelWorkflowRuntimeModule {
48
47
  }> | {
49
48
  steps: {
50
49
  list: (options: unknown) => Promise<{
51
- cursor?: string;
50
+ cursor?: string | null;
52
51
  data: unknown[];
53
52
  hasMore: boolean;
54
53
  }>;
55
54
  };
56
55
  };
57
56
  }
58
- declare function setVercelWorkflowRuntimeModules(api: VercelWorkflowApiModule, runtime: VercelWorkflowRuntimeModule): void;
57
+ export declare function setVercelWorkflowRuntimeModules(api: VercelWorkflowApiModule, runtime: VercelWorkflowRuntimeModule): void;
59
58
  //#endregion
60
59
  //#region src/runtime/vercel-vite.d.ts
61
- declare function runWithVercelWorkflowRuntimeEvent<T>(req: unknown, res: unknown, run: () => T | Promise<T>): Promise<T>;
60
+ export declare function runWithVercelWorkflowRuntimeEvent<T>(req: unknown, res: unknown, run: () => T | Promise<T>): Promise<T>;
62
61
  interface WorkflowVercelServerOptions {
63
- app?: WorkflowApp;
62
+ app?: VitehubApp;
64
63
  registry?: WorkflowDefinitionRegistry;
65
64
  workflow?: false | ResolvedWorkflowOptions;
66
65
  }
67
- type WorkflowVercelServer = (req: IncomingMessage, res: ServerResponse) => unknown;
68
- declare function createWorkflowVercelServer(options?: WorkflowVercelServerOptions): WorkflowVercelServer;
69
- //#endregion
70
- export { WorkflowVercelServer, createWorkflowVercelServer, runWithVercelWorkflowRuntimeEvent, setVercelWorkflowRuntimeModules };
66
+ export type WorkflowVercelServer = (req: IncomingMessage, res: ServerResponse) => unknown;
67
+ export declare function createWorkflowVercelServer(options?: WorkflowVercelServerOptions): WorkflowVercelServer;
68
+ //#endregion
@@ -1,23 +1,26 @@
1
1
  import { runWithWorkflowRuntimeEvent, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
2
- import { i as setVercelWorkflowRuntimeModules } from "../vercel-B0MuIVgJ.js";
3
- import { t as resolveAppFetch } from "../app-BZpq2cwC.js";
2
+ import { i as setVercelWorkflowRuntimeModules } from "../vercel-BZU_O6ay.js";
3
+ import { t as resolveAppFetch } from "../app-CmMq8l4t.js";
4
4
  import { waitUntil } from "@vercel/functions";
5
5
  import { H3 } from "h3";
6
6
  //#region ../internal/src/runtime/vercel-hosted.ts
7
7
  function createVercelHostedServer(adapter) {
8
- const app = new H3();
9
8
  const appHandler = resolveAppFetch(adapter.label, adapter.app);
10
9
  let nodeHandlerPromise;
11
10
  return function hostedVercelServer(req, res) {
12
11
  const handle = async () => {
13
12
  nodeHandlerPromise ||= (async () => {
13
+ const app = new H3();
14
14
  if (appHandler) {
15
15
  const { fromWebHandler } = await import("h3");
16
16
  app.use(fromWebHandler(async (request, context) => await appHandler(request, context)));
17
17
  }
18
18
  const { toNodeHandler } = await import("h3/node");
19
19
  return toNodeHandler(app);
20
- })();
20
+ })().catch((error) => {
21
+ nodeHandlerPromise = void 0;
22
+ throw error;
23
+ });
21
24
  return (await nodeHandlerPromise)(req, res);
22
25
  };
23
26
  if (adapter.onRequest) return adapter.onRequest({
@@ -0,0 +1,241 @@
1
+ //#region src/types.d.ts
2
+ type WorkflowDriver = "cloudflare" | "openworkflow" | "vercel";
3
+ interface CloudflareWorkflowBinding<TPayload = unknown> {
4
+ createBatch: (batch: Array<{
5
+ id: string;
6
+ params?: TPayload;
7
+ }>) => Promise<CloudflareWorkflowInstance[]>;
8
+ get: (id: string) => Promise<CloudflareWorkflowInstance>;
9
+ }
10
+ interface CloudflareWorkflowInstance {
11
+ id: string;
12
+ status: () => Promise<unknown>;
13
+ /** Stops the instance. Cloudflare rejects the call when the instance has already finished. */
14
+ terminate: () => Promise<void>;
15
+ }
16
+ interface WorkflowSharedOptions {
17
+ binding?: string;
18
+ name?: string;
19
+ }
20
+ interface CloudflareWorkflowDriverOptions extends WorkflowSharedOptions {
21
+ driver: "cloudflare";
22
+ }
23
+ interface VercelWorkflowDriverOptions extends WorkflowSharedOptions {
24
+ driver: "vercel";
25
+ }
26
+ interface OpenWorkflowPostgresOptions {
27
+ namespaceId?: string;
28
+ runMigrations?: boolean;
29
+ schema?: string;
30
+ url?: WorkflowRuntimeConfigValue;
31
+ }
32
+ interface WorkflowRuntimeEnvDeclarationLike {
33
+ default?: unknown;
34
+ kind: "env-variable";
35
+ source?: {
36
+ kind: "env";
37
+ name: string;
38
+ names?: string[];
39
+ };
40
+ }
41
+ type WorkflowRuntimeConfigValue = string | WorkflowRuntimeEnvDeclarationLike;
42
+ interface OpenWorkflowSqliteOptions {
43
+ namespaceId?: string;
44
+ path?: WorkflowRuntimeConfigValue;
45
+ runMigrations?: boolean;
46
+ }
47
+ interface OpenWorkflowWorkerOptions {
48
+ /** How many runs one worker executes at once. Defaults to 10. Each Agent turn uses two runs. */
49
+ concurrency?: number;
50
+ }
51
+ /**
52
+ * The OpenWorkflow worker that the Nitro server starts. `false` keeps the server from starting it, for apps that run
53
+ * a separate worker process with `startOpenWorkflowWorker()`.
54
+ */
55
+ type OpenWorkflowWorkerOption = false | OpenWorkflowWorkerOptions;
56
+ interface OpenWorkflowDriverOptions extends WorkflowSharedOptions {
57
+ postgres?: OpenWorkflowPostgresOptions;
58
+ driver: "openworkflow";
59
+ /**
60
+ * `vite dev` keeps runs in the local SQLite file, even when `DATABASE_URL` or `OPENWORKFLOW_POSTGRES_URL` is set.
61
+ * `true` lets it use that storage, so the dev server can run the runs of a shared database. Builds ignore it.
62
+ */
63
+ remote?: boolean;
64
+ sqlite?: OpenWorkflowSqliteOptions;
65
+ worker?: OpenWorkflowWorkerOption;
66
+ }
67
+ interface InferredWorkflowDriverOptions extends WorkflowSharedOptions {
68
+ postgres?: OpenWorkflowPostgresOptions;
69
+ driver?: undefined;
70
+ /** See `OpenWorkflowProviderOptions.remote`. */
71
+ remote?: boolean;
72
+ sqlite?: OpenWorkflowSqliteOptions;
73
+ worker?: OpenWorkflowWorkerOption;
74
+ }
75
+ type WorkflowDriverOptions = CloudflareWorkflowDriverOptions | OpenWorkflowDriverOptions | VercelWorkflowDriverOptions;
76
+ type WorkflowModuleDriverOptions = InferredWorkflowDriverOptions | WorkflowDriverOptions;
77
+ type WorkflowOptions = false | WorkflowModuleDriverOptions;
78
+ type ResolvedWorkflowOptions = WorkflowDriverOptions;
79
+ /** The failure of a failed Workflow Run. Every provider fills it, and it is safe to send as JSON. */
80
+ interface WorkflowRunError {
81
+ /** Code of the thrown error, when it has one. */
82
+ code?: string;
83
+ message: string;
84
+ /** Name of the thrown error, when it is not `Error`. */
85
+ name?: string;
86
+ }
87
+ interface WorkflowRun<TPayload = unknown, TResult = unknown> {
88
+ completedAt?: Date;
89
+ createdAt?: Date;
90
+ /** Set when `status` is `failed`. */
91
+ error?: WorkflowRunError;
92
+ id: string;
93
+ provider: WorkflowDriver;
94
+ result?: TResult;
95
+ startedAt?: Date;
96
+ status: WorkflowRunStatus;
97
+ steps?: WorkflowRunStep[];
98
+ metadata?: unknown;
99
+ payload?: TPayload;
100
+ }
101
+ type WorkflowRunStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | "unknown";
102
+ interface WorkflowRunStep {
103
+ attempt: number;
104
+ completedAt?: Date;
105
+ error?: {
106
+ code?: string;
107
+ message: string;
108
+ };
109
+ id: string;
110
+ name: string;
111
+ /** The time a sleep step wakes. Only a `context.sleep()` step has it. */
112
+ sleepUntil?: Date;
113
+ startedAt?: Date;
114
+ status: WorkflowRunStatus;
115
+ }
116
+ interface WorkflowStepOptions {
117
+ retries?: {
118
+ backoff?: string;
119
+ delay?: string;
120
+ limit?: number;
121
+ };
122
+ }
123
+ type WorkflowStepFunction<TInput = unknown, TResult = unknown> = (input: TInput) => TResult | Promise<TResult>;
124
+ interface WorkflowProviderStep {
125
+ do?: <TResult>(name: string, options: WorkflowStepOptions, run: () => TResult | Promise<TResult>) => Promise<TResult>;
126
+ /** Sleeps for a number of milliseconds. ViteHub names each sleep by call order. */
127
+ sleep?: (name: string, milliseconds: number) => Promise<void>;
128
+ /** Sleeps until a date. Without it, ViteHub sleeps for the time that is left until the date. */
129
+ sleepUntil?: (name: string, date: Date) => Promise<void>;
130
+ }
131
+ type WorkflowDurationUnit = "second" | "minute" | "hour" | "day" | "week" | "month" | "year";
132
+ /**
133
+ * A sleep duration: milliseconds, or a string such as `'30 seconds'` or `'1 day'`. Cloudflare and OpenWorkflow read
134
+ * this form the same way. A month is 30 days and a year is 365.25 days.
135
+ */
136
+ type WorkflowDuration = number | `${number} ${WorkflowDurationUnit}` | `${number} ${WorkflowDurationUnit}s`;
137
+ /**
138
+ * The step files of each folder Workflow, by Workflow name and step name. ViteHub writes it to
139
+ * `.vitehub/workflow.d.ts` from the numbered files in `server/workflows/<name>/`.
140
+ */
141
+ interface WorkflowStepRegistry {}
142
+ /** A step runs one input through its step file, inside a durable provider step. */
143
+ 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; };
146
+ /** Run data that a provider gives to ViteHub before ViteHub adds the step runner. */
147
+ interface WorkflowProviderContext<TPayload = unknown> {
148
+ id?: string;
149
+ name: string;
150
+ payload: TPayload;
151
+ provider: WorkflowDriver;
152
+ step?: WorkflowProviderStep;
153
+ }
154
+ interface WorkflowExecutionContext<TPayload = unknown, TName extends string = string> extends Omit<WorkflowProviderContext<TPayload>, "step"> {
155
+ name: TName;
156
+ /** The provider step runner. Use `context.sleep()` to sleep. */
157
+ step?: Omit<WorkflowProviderStep, "sleep" | "sleepUntil">;
158
+ /**
159
+ * Sleeps for a duration such as `'1 day'` or a number of milliseconds, or until a `Date`. Only a folder Workflow's
160
+ * `index.ts` can sleep. In a single-file Workflow it throws `WORKFLOW_ROOT_STEP_SLEEP`. The sleep is durable on
161
+ * Cloudflare and OpenWorkflow. Inline runs (`vite dev` and Vercel handlers) wait with a timer, which is not durable.
162
+ */
163
+ sleep: (until: WorkflowDuration | Date) => Promise<void>;
164
+ /** Step functions from the numbered files in the Workflow folder. Empty when the Workflow has no step files. */
165
+ steps: WorkflowSteps<TName>;
166
+ }
167
+ type WorkflowHandler<TPayload = unknown, TResult = unknown, TName extends string = string> = (payload: TPayload, context: WorkflowExecutionContext<TPayload, TName>) => TResult | Promise<TResult>;
168
+ type WorkflowRunIdValue = boolean | null | number | string | undefined | {
169
+ readonly [key: string]: WorkflowRunIdValue;
170
+ } | readonly WorkflowRunIdValue[];
171
+ interface WorkflowCreateOptions<TPayload = unknown, TResult = unknown> {
172
+ handler?: WorkflowHandler<TPayload, TResult>;
173
+ id?: (context: {
174
+ name: string;
175
+ payload?: TPayload;
176
+ }) => Promise<WorkflowRunIdValue> | WorkflowRunIdValue;
177
+ /** @internal Identifies the Agent Workflow handler that the Agent package creates for an Agent turn. */
178
+ internalAgentWorkflow?: true;
179
+ name?: string;
180
+ rootStep?: boolean;
181
+ }
182
+ interface WorkflowDefinitionOptions<TPayload = unknown, TResult = unknown> {
183
+ id?: string;
184
+ /** Vercel native entry. Vercel calls it with the provider context only, so it gets no step runner. */
185
+ native?: (context: WorkflowProviderContext<TPayload>) => TResult | Promise<TResult>;
186
+ rootStep?: boolean;
187
+ }
188
+ interface WorkflowDefinition<TPayload = unknown, TResult = unknown, TName extends string = string> {
189
+ /** @internal Identifies provider-generated Agent invocation recovery definitions. */
190
+ internalAgentInvocationRecovery?: true;
191
+ /** @internal Identifies the inline Agent Workflow handler that the Agent package creates for an Agent turn. */
192
+ 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>;
197
+ }
198
+ /** Omission is valid only when the handler accepts undefined. */
199
+ type WorkflowStartArguments<TPayload> = undefined extends TPayload ? [payload?: TPayload, options?: WorkflowStartOptions] : [payload: TPayload, options?: WorkflowStartOptions];
200
+ interface WorkflowHandle<TPayload = unknown, TResult = unknown> {
201
+ cancel: (id: string) => Promise<WorkflowRun<unknown, unknown>>;
202
+ /** Starts a run after the response, through `waitUntil`. A failure goes to the log. */
203
+ defer: (...args: WorkflowStartArguments<TPayload>) => void;
204
+ getRun: (id: string) => Promise<WorkflowRun<unknown, unknown>>;
205
+ name: string;
206
+ start: (...args: WorkflowStartArguments<TPayload>) => Promise<WorkflowRun<TPayload, TResult>>;
207
+ }
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;
210
+ interface WorkflowStartOptions {
211
+ /** Starts the run later. A `Date` in the past starts it now. */
212
+ delay?: WorkflowStartDelay;
213
+ id?: string;
214
+ }
215
+ interface WorkflowSignalResult {
216
+ id: string;
217
+ provider: WorkflowDriver;
218
+ }
219
+ /**
220
+ * Maps Workflow names to module loaders. The registry does not know each
221
+ * payload type, so it uses `never` as the payload. A definition with any
222
+ * payload type fits without a cast.
223
+ */
224
+ interface WorkflowDefinitionRegistry {
225
+ [name: string]: (() => Promise<{
226
+ default?: WorkflowDefinition<never, unknown, never>;
227
+ [exportName: string]: unknown;
228
+ } | WorkflowDefinition<never, unknown, never>>) & {
229
+ /** @internal Identifies provider-generated Agent invocation recovery definitions without evaluating their modules. */
230
+ internalAgentInvocationRecovery?: true;
231
+ };
232
+ }
233
+ interface DiscoveredWorkflowDefinition {
234
+ agentIdentity?: string;
235
+ handler: string;
236
+ name: string;
237
+ source?: "agent-workflow" | "agent-workflow-recovery" | "inline" | "server-workflows" | "vite-suffix";
238
+ steps?: string[];
239
+ }
240
+ //#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 };