@vite-hub/workflow 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +32 -8
  2. package/dist/{app-DXUHElAz.js → app-Cpa9qCXr.js} +1 -1
  3. package/dist/{client-CbBg4HlH.js → client-CPxPxsl5.js} +37 -37
  4. package/dist/cloudflare-concurrency-counter-CDHHiMfn.js +136 -0
  5. package/dist/{config-CizNRTMi.js → config-CwCwuZqv.js} +1 -1
  6. package/dist/definition.d.ts +1 -1
  7. package/dist/definition.js +4 -1
  8. package/dist/{delay-CtT3442d.js → delay-JrpW40UF.js} +4 -2
  9. package/dist/durability.d.ts +3 -1
  10. package/dist/durability.js +7 -1
  11. package/dist/{error-diagnostics--2cV_ER1.js → error-diagnostics-35AEmfve.js} +25 -5
  12. package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
  13. package/dist/{errors-CJZuvOcx.d.ts → errors-DwKy5MQ8.d.ts} +1 -1
  14. package/dist/execute-CLmIXnON.js +355 -0
  15. package/dist/index.d.ts +12 -10
  16. package/dist/index.js +3 -3
  17. package/dist/{openworkflow-defaults-DfQWtSRU.js → invariant-Dj2R1eMr.js} +1 -4
  18. package/dist/openworkflow-BiwPTYEz.js +752 -0
  19. package/dist/{openworkflow-CdKbUGGa.d.ts → openworkflow-C65AWQSJ.d.ts} +23 -4
  20. package/dist/openworkflow-defaults-1n0DbLdb.js +4 -0
  21. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-Blwi3jQF.d.ts} +1 -0
  22. package/dist/{operations-BBTmDm2H.js → operations-DyaGK9zW.js} +70 -14
  23. package/dist/operations.d.ts +3 -59
  24. package/dist/operations.js +5 -5
  25. package/dist/results-DBp_bmUP.d.ts +60 -0
  26. package/dist/runtime/cloudflare-concurrency.d.ts +21 -0
  27. package/dist/runtime/cloudflare-concurrency.js +21 -0
  28. package/dist/runtime/cloudflare-runner.d.ts +1 -1
  29. package/dist/runtime/cloudflare-runner.js +7 -3
  30. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  31. package/dist/runtime/cloudflare-vite.js +2 -2
  32. package/dist/runtime/execute.d.ts +8 -2
  33. package/dist/runtime/execute.js +1 -278
  34. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  35. package/dist/runtime/openworkflow-worker.js +2 -2
  36. package/dist/runtime/openworkflow.d.ts +2 -2
  37. package/dist/runtime/openworkflow.js +1 -481
  38. package/dist/runtime/state.d.ts +1 -1
  39. package/dist/runtime/state.js +2 -2
  40. package/dist/runtime/vercel-vite.d.ts +1 -1
  41. package/dist/runtime/vercel-vite.js +2 -2
  42. package/dist/{signals-BHQdxoJo.js → signals-CdaxRNjN.js} +1 -1
  43. package/dist/{types-DvYcvbPG.d.ts → types-CvyOEp0V.d.ts} +33 -4
  44. package/dist/{vercel-Cw_Z9-j4.js → vercel-ADMH2MK8.js} +5 -3
  45. package/dist/vite.d.ts +18 -4
  46. package/dist/vite.js +553 -116
  47. package/package.json +3 -3
  48. package/dist/cloudflare-Sgywkm1N.js +0 -57
@@ -1,481 +1 @@
1
- import { r as invariantError, t as defaultOpenWorkflowSqlitePath } from "../openworkflow-defaults-DfQWtSRU.js";
2
- import { readNonRetryableStepResult, resolveWorkflowStepOptions, runSerializedWorkflowHandler, toDurationMilliseconds, toNonRetryableStepResult, withWorkflowStepTimeout } from "./execute.js";
3
- import { n as createWorkflowError } from "../errors-CZf7oz4k.js";
4
- import { i as runWorkflowProviderOperation, n as getWorkflowProviderStatus, t as toWorkflowRunError } from "../run-error-8p4BtTMv.js";
5
- import { t as emitWorkflowFailed } from "../run-failed-BcSjSU2t.js";
6
- import { t as resolveOpenWorkflowStorage } from "../openworkflow-storage-Dde_f0es.js";
7
- import { t as workflowErrorDiagnostics } from "../error-diagnostics--2cV_ER1.js";
8
- import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime/internal/response";
9
- // src/runtime/openworkflow.ts
10
- const defaultImporter = (specifier) => import(
11
- /* @vite-ignore */
12
- specifier
13
- );
14
- let openWorkflowImporter = defaultImporter;
15
- let runtimes = /* @__PURE__ */ new Map();
16
- async function importOpenWorkflowModule(specifier, importer) {
17
- return await runWorkflowProviderOperation("openworkflow", "import", () => importer(specifier));
18
- }
19
- function readEnv(name) {
20
- const value = (globalThis.process?.env)?.[name];
21
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
22
- }
23
- function resolveRuntimeConfigValue(value) {
24
- if (typeof value === "string" || typeof value === "undefined") return value;
25
- for (const name of getRuntimeEnvNames(value)) {
26
- const resolved = readEnv(name);
27
- if (resolved) return resolved;
28
- }
29
- return typeof value.default === "string" && value.default.trim() ? value.default.trim() : void 0;
30
- }
31
- function getRuntimeEnvNames(value) {
32
- return value.source?.names ?? (value.source?.name ? [value.source.name] : []);
33
- }
34
- function normalizeSqlitePath(path) {
35
- if (/^(?:libsql:|https?:\/\/)/i.test(path)) throw workflowErrorDiagnostics.WORKFLOW_R0018({ message: `OpenWorkflow SQLite storage requires a local SQLite file path, received ${JSON.stringify(path)}.` });
36
- if (/^[a-z][a-z0-9+.-]*:/i.test(path) && !path.startsWith("file:")) throw workflowErrorDiagnostics.WORKFLOW_R0019({ message: `OpenWorkflow SQLite storage received unsupported storage URL ${JSON.stringify(path)}.` });
37
- return path.startsWith("file:") ? path.slice(5) : path;
38
- }
39
- async function prepareSqlitePath(path, importer) {
40
- if (path !== ":memory:") {
41
- const [{ mkdirSync }, { dirname }] = await Promise.all([importOpenWorkflowModule("node:fs", importer), importOpenWorkflowModule("node:path", importer)]);
42
- mkdirSync(dirname(path), { recursive: true });
43
- }
44
- return path;
45
- }
46
- let databaseUrlResolver;
47
- /**
48
- * Makes OpenWorkflow use the Postgres Default Database of the app when no OpenWorkflow storage is configured. The
49
- * generated startup plugin installs it when the build has a Postgres Default Database.
50
- */
51
- function setOpenWorkflowDatabaseUrl(resolve) {
52
- databaseUrlResolver = resolve;
53
- }
54
- function readDatabasePostgresUrl() {
55
- if (!databaseUrlResolver) return void 0;
56
- const url = databaseUrlResolver()?.trim();
57
- if (!url) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_MISSING();
58
- return url;
59
- }
60
- function getOpenWorkflowConfig(config) {
61
- if (config.driver !== "openworkflow") throw workflowErrorDiagnostics.WORKFLOW_R0020({ message: `OpenWorkflow runtime requires workflow.driver "openworkflow", received "${config.driver}".` });
62
- if ("database" in config && config.database !== void 0) throw workflowErrorDiagnostics.WORKFLOW_R0027({ message: "`workflow.database` is not supported. Set `workflow.sqlite.path` or `workflow.postgres.url` explicitly." });
63
- const sqlite = config.sqlite || {};
64
- const postgres = config.postgres || {};
65
- if (postgres.url !== void 0 && sqlite.path !== void 0) throw workflowErrorDiagnostics.WORKFLOW_R0030({ message: "`workflow.postgres.url` and `workflow.sqlite.path` cannot both configure OpenWorkflow storage." });
66
- const explicitSqlitePath = resolveRuntimeConfigValue(sqlite.path);
67
- const explicitPostgresUrl = resolveRuntimeConfigValue(postgres.url)?.trim();
68
- if (sqlite.path !== void 0 && !explicitSqlitePath?.trim()) throw workflowErrorDiagnostics.WORKFLOW_R0028({ message: "`workflow.sqlite.path` must resolve to a non-empty local SQLite path. Check its runtime environment declaration." });
69
- if (postgres.url !== void 0 && !explicitPostgresUrl) throw workflowErrorDiagnostics.WORKFLOW_R0029({ message: "`workflow.postgres.url` must resolve to a non-empty Postgres URL. Check its runtime environment declaration." });
70
- const storage = resolveOpenWorkflowStorage({
71
- postgresUrl: explicitPostgresUrl,
72
- sqlitePath: explicitSqlitePath
73
- }, readEnv);
74
- if (storage.backend === "sqlite" && storage.source !== "default") return {
75
- backend: "sqlite",
76
- namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
77
- path: normalizeSqlitePath(storage.path),
78
- runMigrations: sqlite.runMigrations,
79
- source: "configured"
80
- };
81
- const configuredUrl = storage.backend === "postgres" ? storage.url : void 0;
82
- const url = configuredUrl || readDatabasePostgresUrl();
83
- if (url) return {
84
- backend: "postgres",
85
- namespaceId: postgres.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
86
- runMigrations: postgres.runMigrations,
87
- schema: postgres.schema || readEnv("OPENWORKFLOW_SCHEMA") || "openworkflow",
88
- source: configuredUrl ? "configured" : "database",
89
- url
90
- };
91
- if (/^postgres(?:ql)?:\/\//i.test(readEnv("DATABASE_URL") || "")) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_IGNORED();
92
- return {
93
- backend: "sqlite",
94
- namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
95
- path: defaultOpenWorkflowSqlitePath,
96
- runMigrations: sqlite.runMigrations,
97
- source: "default"
98
- };
99
- }
100
- const postgresSetupWaitMs = 12e4;
101
- const postgresSecondConnectionTimeoutMs = 1e4;
102
- function sleep(ms) {
103
- return new Promise((resolve) => setTimeout(resolve, ms).unref?.());
104
- }
105
- function settlesWithin(task, ms) {
106
- let timer;
107
- return Promise.race([task.then(() => true), new Promise((resolve) => {
108
- timer = setTimeout(() => resolve(false), ms);
109
- timer.unref?.();
110
- })]).finally(() => clearTimeout(timer));
111
- }
112
- async function withPostgresSetupLock(postgres, url, schema, setup) {
113
- const sql = postgres.default(url, {
114
- idle_timeout: 1,
115
- max: 1,
116
- onnotice: () => {}
117
- });
118
- const key = `vitehub:openworkflow:${schema}`;
119
- const deadline = Date.now() + postgresSetupWaitMs;
120
- try {
121
- for (let attempt = 1;; attempt++) {
122
- let result;
123
- await sql.begin(async (transaction) => {
124
- const [lock] = await transaction`select pg_try_advisory_xact_lock(hashtextextended(${key}, 0)) as locked`;
125
- if (!lock?.locked) return;
126
- const probe = postgres.default(url, {
127
- max: 1,
128
- onnotice: () => {}
129
- });
130
- const answered = Promise.resolve(probe`select 1`).then(() => {}, () => {});
131
- if (!await settlesWithin(answered, postgresSecondConnectionTimeoutMs)) {
132
- answered.then(() => probe.end());
133
- throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE();
134
- }
135
- await probe.end();
136
- result = { value: await setup() };
137
- });
138
- if (result) return result.value;
139
- if (Date.now() >= deadline) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_LOCK_TIMEOUT({ seconds: postgresSetupWaitMs / 1e3 });
140
- await sleep(Math.min(250 * attempt, 2e3));
141
- }
142
- } finally {
143
- await sql.end({ timeout: 5 });
144
- }
145
- }
146
- function reportFailedRuns(backend, definitions) {
147
- const failWorkflowRun = async (params) => {
148
- const run = await backend.failWorkflowRun(params);
149
- if (run.status === "failed") await emitWorkflowFailed(run.workflowName, run.idempotencyKey || run.id, run.error ?? params.error, definitions.get(run.workflowName));
150
- return run;
151
- };
152
- return new Proxy(backend, { get(target, property) {
153
- if (property === "failWorkflowRun") return failWorkflowRun;
154
- const value = Reflect.get(target, property);
155
- return typeof value === "function" ? value.bind(target) : value;
156
- } });
157
- }
158
- async function createOpenWorkflowRuntime(options, importer) {
159
- const definitions = /* @__PURE__ */ new Map();
160
- const [{ OpenWorkflow }, backendModule] = await Promise.all([importOpenWorkflowModule("openworkflow", importer), options.backend === "sqlite" ? importOpenWorkflowModule("openworkflow/sqlite", importer) : importOpenWorkflowModule("openworkflow/postgres", importer)]);
161
- const { backend, client } = await runWorkflowProviderOperation("openworkflow", "connect", async () => {
162
- let backend;
163
- if (options.backend === "sqlite") backend = await backendModule.BackendSqlite.connect(await prepareSqlitePath(options.path, importer), {
164
- namespaceId: options.namespaceId,
165
- ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {}
166
- });
167
- else {
168
- const { BackendPostgres } = backendModule;
169
- const connect = () => BackendPostgres.connect(options.url, {
170
- namespaceId: options.namespaceId,
171
- ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {},
172
- schema: options.schema
173
- });
174
- backend = options.runMigrations === false ? await connect() : await withPostgresSetupLock(await importOpenWorkflowModule("postgres", importer), options.url, options.schema, connect);
175
- }
176
- return {
177
- backend,
178
- client: new OpenWorkflow({ backend: reportFailedRuns(backend, definitions) })
179
- };
180
- });
181
- return {
182
- backend,
183
- client,
184
- definitions,
185
- findRunId: createRunIdLookup(backend, options),
186
- workflows: /* @__PURE__ */ new Map()
187
- };
188
- }
189
- function isSqliteHandle(value) {
190
- return typeof value === "object" && value !== null && typeof Reflect.get(value, "prepare") === "function";
191
- }
192
- function isPostgresHandle(value) {
193
- return typeof value === "function";
194
- }
195
- function readRowId(row) {
196
- if (typeof row !== "object" || row === null) return void 0;
197
- const id = Reflect.get(row, "id");
198
- return typeof id === "string" ? id : void 0;
199
- }
200
- function createRunIdLookup(backend, options) {
201
- const connection = Reflect.get(backend, options.backend === "sqlite" ? "db" : "pg");
202
- return async (name, key) => {
203
- if (options.backend === "sqlite" && isSqliteHandle(connection)) return readRowId(connection.prepare(`SELECT "id" FROM "workflow_runs" WHERE "namespace_id" = ? AND "workflow_name" = ? AND "idempotency_key" = ? ORDER BY "created_at" ASC, "id" ASC LIMIT 1`).get(options.namespaceId, name, key));
204
- if (options.backend === "postgres" && isPostgresHandle(connection)) {
205
- const [row] = await connection`SELECT "id" FROM ${connection(options.schema)}.${connection("workflow_runs")} WHERE "namespace_id" = ${options.namespaceId} AND "workflow_name" = ${name} AND "idempotency_key" = ${key} ORDER BY "created_at" ASC, "id" ASC LIMIT 1`;
206
- return readRowId(row);
207
- }
208
- throw invariantError(`OpenWorkflow backends keep their connection in \`db\` (SQLite) or \`pg\` (Postgres), but the ${options.backend} backend has neither`);
209
- };
210
- }
211
- /** The storage that OpenWorkflow uses for `config` now, without credentials. */
212
- function describeOpenWorkflowStorage(config) {
213
- const storage = getOpenWorkflowConfig(config);
214
- return storage.backend === "sqlite" ? {
215
- backend: "sqlite",
216
- location: storage.path,
217
- source: storage.source
218
- } : {
219
- backend: "postgres",
220
- location: `schema ${storage.schema}`,
221
- source: storage.source
222
- };
223
- }
224
- async function getOpenWorkflowRuntime(config) {
225
- const cache = runtimes;
226
- const options = getOpenWorkflowConfig(config);
227
- const key = JSON.stringify(options);
228
- let runtime = cache.get(key);
229
- if (!runtime) {
230
- runtime = createOpenWorkflowRuntime(options, openWorkflowImporter);
231
- cache.set(key, runtime);
232
- runtime.catch(() => {
233
- if (cache.get(key) === runtime) cache.delete(key);
234
- });
235
- }
236
- const resolved = await runtime;
237
- if (cache !== runtimes) throw createWorkflowError({
238
- code: "OPENWORKFLOW_RUNTIME_RESET",
239
- details: { provider: "openworkflow" }
240
- });
241
- return resolved;
242
- }
243
- function toOpenWorkflowRetryPolicy(name, options) {
244
- const { backoff, delay, limit } = resolveWorkflowStepOptions(name, options).retries;
245
- const initial = toDurationMilliseconds(delay);
246
- const coefficient = backoff === "exponential" ? 2 : 1;
247
- return {
248
- backoffCoefficient: coefficient,
249
- initialInterval: `${initial}ms`,
250
- maximumAttempts: limit + 1,
251
- maximumInterval: `${initial * coefficient ** Math.max(limit - 1, 0)}ms`
252
- };
253
- }
254
- function createOpenWorkflowProviderStep(step, workflow) {
255
- return {
256
- async do(name, options, run) {
257
- const output = await step.run({
258
- name,
259
- retryPolicy: toOpenWorkflowRetryPolicy(name, options)
260
- }, async () => {
261
- try {
262
- return await withWorkflowStepTimeout(name, options.timeout, run)();
263
- } catch (error) {
264
- const result = toNonRetryableStepResult(error);
265
- if (result) return result;
266
- throw error;
267
- }
268
- });
269
- const error = readNonRetryableStepResult(output);
270
- if (error) throw error;
271
- return output;
272
- },
273
- sleep: async (name, milliseconds) => await step.sleep(name, `${milliseconds}ms`),
274
- async waitForSignal(name, token) {
275
- const received = await step.waitForSignal({
276
- name,
277
- signal: token
278
- });
279
- if (received === null) throw workflowErrorDiagnostics.WORKFLOW_SIGNAL_TIMEOUT({ name: workflow });
280
- return received.data;
281
- }
282
- };
283
- }
284
- /**
285
- * Sends `value` to a live run that waits for the signal `token`. OpenWorkflow drops early signals and can match
286
- * a wait left behind by cancellation, so check the run before sending.
287
- */
288
- async function resumeOpenWorkflowSignal(config, workflow, id, token, value) {
289
- const runtime = await getOpenWorkflowRuntime(config);
290
- return await runWorkflowProviderOperation("openworkflow", "resume-signal", async () => {
291
- const run = await runtime.backend.getWorkflowRun({ workflowRunId: await runtime.findRunId(workflow, id) ?? id });
292
- if (!run || run.workflowName !== workflow || terminalOpenWorkflowStatuses.has(normalizeOpenWorkflowStatus(run.status))) return false;
293
- const { workflowRunIds } = await runtime.client.sendSignal({
294
- data: value,
295
- signal: token
296
- });
297
- return workflowRunIds.includes(run.id);
298
- });
299
- }
300
- async function registerOpenWorkflowDefinition(runtime, name, definition) {
301
- const existing = runtime.workflows.get(name);
302
- if (existing) return existing;
303
- const openWorkflowDefinition = definition;
304
- runtime.definitions.set(name, definition);
305
- const workflow = runtime.client.defineWorkflow({ name }, async ({ input, run, step }) => {
306
- const stored = await runtime.backend.getWorkflowRun({ workflowRunId: run.id });
307
- return await runSerializedWorkflowHandler({
308
- id: stored?.idempotencyKey || run.id,
309
- name,
310
- payload: input,
311
- provider: "openworkflow",
312
- step: createOpenWorkflowProviderStep(step, name)
313
- }, openWorkflowDefinition);
314
- });
315
- runtime.workflows.set(name, workflow);
316
- return workflow;
317
- }
318
- function normalizeOpenWorkflowStatus(status) {
319
- switch (String(status || "").toLowerCase()) {
320
- case "completed":
321
- case "succeeded": return "completed";
322
- case "canceled": return "cancelled";
323
- case "failed": return "failed";
324
- case "pending": return "queued";
325
- case "running":
326
- case "sleeping": return "running";
327
- default: return "unknown";
328
- }
329
- }
330
- function serializeOpenWorkflowRun(run, name) {
331
- if (!run || run.workflowName !== name) return {
332
- id: run?.id || "",
333
- provider: "openworkflow",
334
- status: "unknown"
335
- };
336
- const result = isSerializedResponse(run.output) ? deserializeResponse(run.output) : run.output;
337
- const status = normalizeOpenWorkflowStatus(run.status);
338
- return {
339
- ...status === "failed" ? { error: toWorkflowRunError(run.error) } : {},
340
- ...run.finishedAt ? { completedAt: run.finishedAt } : {},
341
- createdAt: run.createdAt,
342
- ...run.startedAt ? { startedAt: run.startedAt } : {},
343
- id: run.idempotencyKey || run.id,
344
- metadata: {
345
- namespaceId: run.namespaceId,
346
- version: run.version,
347
- workflowName: run.workflowName
348
- },
349
- payload: run.input,
350
- provider: "openworkflow",
351
- result,
352
- status
353
- };
354
- }
355
- function toWorkflowRunStepError(error) {
356
- const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : void 0;
357
- return { message: typeof message === "string" && message ? message : "Workflow step failed." };
358
- }
359
- function toWorkflowRunSteps(attempts) {
360
- const steps = /* @__PURE__ */ new Map();
361
- for (const attempt of attempts) {
362
- const nonRetryable = readNonRetryableStepResult(attempt.output);
363
- steps.set(attempt.stepName, {
364
- attempt: (steps.get(attempt.stepName)?.attempt ?? 0) + 1,
365
- ...attempt.finishedAt ? { completedAt: attempt.finishedAt } : {},
366
- ...attempt.status === "failed" || nonRetryable ? { error: toWorkflowRunStepError(nonRetryable ?? attempt.error) } : {},
367
- id: attempt.id,
368
- name: attempt.stepName,
369
- ...attempt.context?.kind === "sleep" ? { sleepUntil: new Date(attempt.context.resumeAt) } : {},
370
- ...attempt.startedAt ? { startedAt: attempt.startedAt } : {},
371
- status: nonRetryable ? "failed" : normalizeOpenWorkflowStatus(attempt.status)
372
- });
373
- }
374
- return [...steps.values()];
375
- }
376
- async function listOpenWorkflowStepAttempts(backend, workflowRunId) {
377
- const attempts = [];
378
- let after;
379
- do {
380
- const page = await backend.listStepAttempts({
381
- workflowRunId,
382
- limit: 100,
383
- ...after ? { after } : {}
384
- });
385
- attempts.push(...page.data);
386
- after = page.pagination.next ?? void 0;
387
- } while (after);
388
- return attempts;
389
- }
390
- async function runOpenWorkflow(config, name, payload, definition, options, onDispatch, startAt) {
391
- const runtime = await getOpenWorkflowRuntime(config);
392
- const workflow = await registerOpenWorkflowDefinition(runtime, name, definition);
393
- onDispatch?.();
394
- let firstAcknowledgementUnknown = false;
395
- const handle = await runWorkflowProviderOperation("openworkflow", "run", async () => {
396
- const existingId = options.id ? await runtime.findRunId(name, options.id) ?? options.id : void 0;
397
- const existing = existingId ? await runtime.backend.getWorkflowRun({ workflowRunId: existingId }) : null;
398
- if (existing?.workflowName === name) return { workflowRun: existing };
399
- const runOptions = options.id || startAt !== void 0 ? {
400
- ...options.id ? { idempotencyKey: options.id } : {},
401
- ...startAt === void 0 ? {} : { availableAt: new Date(startAt) }
402
- } : void 0;
403
- const start = () => workflow.run(payload, runOptions);
404
- return await start().catch((error) => {
405
- if (!options.id) throw error;
406
- firstAcknowledgementUnknown = getWorkflowProviderStatus(error) === void 0;
407
- return start();
408
- });
409
- }, { acknowledgement: (_error, status) => firstAcknowledgementUnknown || status === void 0 ? "unknown" : status < 500 ? "rejected" : void 0 });
410
- return await runWorkflowProviderOperation("openworkflow", "run", async () => {
411
- return {
412
- ...serializeOpenWorkflowRun(handle.workflowRun, name),
413
- metadata: {
414
- ...options.id ? { idempotencyKey: options.id } : {},
415
- workflow: name
416
- },
417
- payload: handle.workflowRun.input
418
- };
419
- });
420
- }
421
- async function getOpenWorkflowRun(config, name, id) {
422
- const runtime = await getOpenWorkflowRuntime(config);
423
- return await runWorkflowProviderOperation("openworkflow", "get", async () => {
424
- const run = await runtime.backend.getWorkflowRun({ workflowRunId: await runtime.findRunId(name, id) ?? id });
425
- if (!run || run.workflowName !== name) return {
426
- id,
427
- provider: "openworkflow",
428
- status: "unknown"
429
- };
430
- return {
431
- ...serializeOpenWorkflowRun(run, name),
432
- steps: toWorkflowRunSteps(await listOpenWorkflowStepAttempts(runtime.backend, run.id))
433
- };
434
- });
435
- }
436
- const terminalOpenWorkflowStatuses = /* @__PURE__ */ new Set([
437
- "cancelled",
438
- "completed",
439
- "failed"
440
- ]);
441
- async function cancelOpenWorkflowRun(config, name, id) {
442
- const current = await getOpenWorkflowRun(config, name, id);
443
- if (current.status === "unknown" || terminalOpenWorkflowStatuses.has(current.status)) return current;
444
- const runtime = await getOpenWorkflowRuntime(config);
445
- try {
446
- await runWorkflowProviderOperation("openworkflow", "cancel", async () => await runtime.client.cancelWorkflowRun(await runtime.findRunId(name, id) ?? id));
447
- } catch (error) {
448
- const latest = await getOpenWorkflowRun(config, name, id).catch(() => void 0);
449
- if (latest && terminalOpenWorkflowStatuses.has(latest.status)) return latest;
450
- throw error;
451
- }
452
- return await getOpenWorkflowRun(config, name, id);
453
- }
454
- async function resetOpenWorkflowRuntime() {
455
- openWorkflowImporter = defaultImporter;
456
- databaseUrlResolver = void 0;
457
- await detachOpenWorkflowRuntimes()();
458
- }
459
- /**
460
- * Starts a new runtime cache, so the next acquisition opens a fresh backend. Returns a function that closes the
461
- * backends of the old cache. Call it after the work that still uses them, such as a stopping worker, finishes.
462
- */
463
- function detachOpenWorkflowRuntimes() {
464
- const closing = runtimes;
465
- runtimes = /* @__PURE__ */ new Map();
466
- return () => closeOpenWorkflowRuntimes(closing);
467
- }
468
- async function closeOpenWorkflowRuntimes(closing) {
469
- const fulfilled = (await Promise.allSettled(closing.values())).flatMap((entry) => entry.status === "fulfilled" ? [entry.value] : []);
470
- const failures = (await Promise.allSettled(fulfilled.map((runtime) => Promise.resolve().then(() => runtime.backend.stop())))).flatMap((entry) => entry.status === "rejected" ? [createWorkflowError({
471
- cause: entry.reason,
472
- code: "OPENWORKFLOW_BACKEND_CLOSE_FAILED",
473
- details: { provider: "openworkflow" }
474
- })] : []);
475
- if (failures.length === 1) throw failures[0];
476
- if (failures.length > 1) throw new AggregateError(failures, "OpenWorkflow backend cleanup failed for multiple runtimes.");
477
- }
478
- function setOpenWorkflowImporter(importer) {
479
- openWorkflowImporter = importer;
480
- }
481
- export { cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, resumeOpenWorkflowSignal, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
1
+ export { t as cancelOpenWorkflowRun, n as describeOpenWorkflowStorage, r as detachOpenWorkflowRuntimes, i as findOpenWorkflowRuns, a as getOpenWorkflowRun, o as getOpenWorkflowRuntime, s as listOpenWorkflowRuns, c as registerOpenWorkflowDefinition, l as resetOpenWorkflowRuntime, u as resumeOpenWorkflowSignal, d as runOpenWorkflow, f as setOpenWorkflowDatabaseUrl, p as setOpenWorkflowImporter } from "../openworkflow-BiwPTYEz.js";
@@ -1,4 +1,4 @@
1
- import { f as WorkflowDefinition, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-DvYcvbPG.js";
1
+ import { _ as WorkflowDefinitionRegistry, d as ResolvedWorkflowOptions, h as WorkflowDefinition } from "../types-CvyOEp0V.js";
2
2
  export interface WorkflowRunState<TResult = unknown> {
3
3
  error?: unknown;
4
4
  expiresAt?: number;
@@ -1,6 +1,6 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics--2cV_ER1.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-35AEmfve.js";
2
2
  import { n as setWorkflowDevRecorder } from "../dev-recorder-Dltdmlkv.js";
3
- import { a as resetInlineWorkflowSignals } from "../signals-BHQdxoJo.js";
3
+ import { a as resetInlineWorkflowSignals } from "../signals-CdaxRNjN.js";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  // src/runtime/state.ts
6
6
  const RUNS_LIMIT = 1024;
@@ -1,5 +1,5 @@
1
1
  import { t as VitehubApp } from "../app-wkVFd7m-.js";
2
- import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-DvYcvbPG.js";
2
+ import { _ as WorkflowDefinitionRegistry, d as ResolvedWorkflowOptions } from "../types-CvyOEp0V.js";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  interface VercelRun {
5
5
  cancel: () => Promise<void>;
@@ -1,6 +1,6 @@
1
- import { t as resolveAppFetch } from "../app-DXUHElAz.js";
1
+ import { t as resolveAppFetch } from "../app-Cpa9qCXr.js";
2
2
  import { runWithWorkflowRuntimeEvent, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
3
- import { i as setVercelWorkflowRuntimeModules } from "../vercel-Cw_Z9-j4.js";
3
+ import { i as setVercelWorkflowRuntimeModules } from "../vercel-ADMH2MK8.js";
4
4
  import { waitUntil } from "@vercel/functions";
5
5
  import { H3 } from "h3";
6
6
  // ../internal/src/runtime/vercel-hosted.ts
@@ -1,4 +1,4 @@
1
- import { t as workflowErrorDiagnostics } from "./error-diagnostics--2cV_ER1.js";
1
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-35AEmfve.js";
2
2
  // src/runtime/signals.ts
3
3
  const tokenPrefix = "vhsig1.";
4
4
  const hosts = /* @__PURE__ */ new Set([
@@ -183,14 +183,26 @@ interface WorkflowStepRegistry {}
183
183
  * `server/workflows/`, so `startWorkflow()` checks the name and the payload.
184
184
  */
185
185
  interface WorkflowRegistry {}
186
+ /** Discovered Agent Workflow names. ViteHub writes this registry to `.vitehub/workflow.d.ts`. */
187
+ interface AgentWorkflowRegistry {}
186
188
  /** A Workflow name from `WorkflowRegistry`. Any string before ViteHub writes the registry. */
187
189
  type WorkflowName = [keyof WorkflowRegistry] extends [never] ? string : Extract<keyof WorkflowRegistry, string>;
190
+ type WorkflowRunName = WorkflowName | Extract<keyof AgentWorkflowRegistry, string>;
188
191
  /** The payload type of the Workflow `TName`, from the `payload` that its handler reads. */
189
192
  type WorkflowPayload<TName extends string> = TName extends keyof WorkflowRegistry ? WorkflowRegistry[TName] extends {
190
193
  handler: (context: infer TContext) => unknown;
191
194
  } ? TContext extends {
192
195
  payload: infer TPayload;
193
196
  } ? TPayload : unknown : unknown : unknown;
197
+ type WorkflowRunValue<T> = T extends string | number | boolean | null | undefined | void ? T : T extends Date ? Date | string | null : T extends readonly unknown[] ? { [K in keyof T]: WorkflowRunValue<T[K]> | (undefined extends T[K] ? null : never); } : T extends object ? WorkflowRunObject<T> : unknown;
198
+ type WorkflowRunObject<T extends object> = [keyof T] extends [never] ? unknown : { [K in keyof T]-?: Extract<T[K], (...args: never[]) => unknown>; }[keyof T] extends never ? { [K in keyof T as K extends string | number ? K : never]: WorkflowRunValue<T[K]>; } : unknown;
199
+ type WorkflowRunResultValue<T> = T extends Response ? Response : WorkflowRunValue<T>;
200
+ /** The stored `result` type of a run of the Workflow `TName`, inferred from its handler. */
201
+ type WorkflowResult<TName extends string> = TName extends keyof WorkflowRegistry ? WorkflowRegistry[TName] extends {
202
+ handler: (context: never) => infer TResult;
203
+ } ? WorkflowRunResultValue<Awaited<TResult>> : unknown : unknown;
204
+ type NamedWorkflowRun<TName extends string> = WorkflowRun<WorkflowRunValue<WorkflowPayload<TName>>, WorkflowResult<TName>>;
205
+ type WorkflowHandleRun<TPayload, TResult> = WorkflowRun<WorkflowRunValue<TPayload>, WorkflowRunResultValue<TResult>>;
194
206
  /** A step runs one input through its step file, inside a durable provider step. */
195
207
  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;
196
208
  type StepsInFolder<TFolder> = TFolder extends unknown ? keyof TFolder : never;
@@ -208,8 +220,19 @@ interface WorkflowProviderContext<TPayload = unknown> {
208
220
  name: string;
209
221
  payload: TPayload;
210
222
  provider: WorkflowDriver;
223
+ /** @internal The shared store of a Workflow that sets `concurrency`. The Cloudflare and OpenWorkflow runners pass it. */
224
+ slots?: WorkflowConcurrencySlots;
211
225
  step?: WorkflowProviderStep;
212
226
  }
227
+ /**
228
+ * @internal The place of one run in the count of its Workflow. Both calls are safe to repeat, because a provider can run
229
+ * a step again after a crash. The store frees the place of a run that ended without `release()`.
230
+ */
231
+ interface WorkflowConcurrencySlots {
232
+ /** Gives the run a place when fewer than `limit` runs hold one. Returns `true` when the run holds a place. */
233
+ acquire: (limit: number) => Promise<boolean>;
234
+ release: () => Promise<void>;
235
+ }
213
236
  /** The one object that a Workflow handler receives: the `payload` of the run, the run data, `sleep`, and `steps`. */
214
237
  interface WorkflowExecutionContext<TPayload = unknown> extends Omit<WorkflowProviderContext<TPayload>, "step"> {
215
238
  /**
@@ -247,6 +270,12 @@ interface WorkflowCreateOptions<TPayload = unknown, TResult = unknown> {
247
270
  }
248
271
  /** Options of `defineWorkflow()`, next to `handler`. */
249
272
  interface WorkflowDefinitionOptions<TPayload = unknown, TResult = unknown> {
273
+ /**
274
+ * The most runs of this Workflow that run their handler at the same time, on all servers. A run that starts while the
275
+ * limit is full waits until a run ends. Cloudflare and OpenWorkflow keep the count in their store. Vercel cannot
276
+ * keep it, so a Vercel build fails with `WORKFLOW_CONCURRENCY_VERCEL_UNSUPPORTED`.
277
+ */
278
+ concurrency?: number;
250
279
  /** Vercel native entry. Vercel calls it with the provider context only, so it gets no step runner. */
251
280
  native?: (context: WorkflowProviderContext<TPayload>) => TResult | Promise<TResult>;
252
281
  rootStep?: boolean;
@@ -268,12 +297,12 @@ type WorkflowStartArguments<TPayload> = undefined extends TPayload ? [payload?:
268
297
  type WorkflowResultErrorCode = "RUNTIME_DURATION_INVALID" | "WORKFLOW_CLOUDFLARE_RUN_ID_INVALID" | "WORKFLOW_OPERATION_UNSUPPORTED" | "WORKFLOW_PROVIDER_OPERATION_FAILED" | "WORKFLOW_R0014" | "WORKFLOW_RUN_ID_UNSUPPORTED" | "WORKFLOW_SIGNAL_NOT_WAITING" | "WORKFLOW_SIGNAL_TOKEN_INVALID" | "WORKFLOW_START_DELAY_INVALID";
269
298
  /** `cancel()`, `getRun()`, and `start()` return `[error, data]`, as `cancelWorkflow()`, `getWorkflowRun()`, and `startWorkflow()` do. */
270
299
  interface WorkflowHandle<TPayload = unknown, TResult = unknown> {
271
- cancel: (id: string) => Promise<Result<WorkflowRun<unknown, unknown>, WorkflowResultErrorCode>>;
300
+ cancel: (id: string) => Promise<Result<WorkflowHandleRun<TPayload, TResult>, WorkflowResultErrorCode>>;
272
301
  /** Starts a run after the response, through `waitUntil`. A failure goes to the log. */
273
302
  defer: (...args: WorkflowStartArguments<TPayload>) => void;
274
- getRun: (id: string) => Promise<Result<WorkflowRun<unknown, unknown>, WorkflowResultErrorCode>>;
303
+ getRun: (id: string) => Promise<Result<WorkflowHandleRun<TPayload, TResult>, WorkflowResultErrorCode>>;
275
304
  name: string;
276
- start: (...args: WorkflowStartArguments<TPayload>) => Promise<Result<WorkflowRun<TPayload, TResult>, WorkflowResultErrorCode>>;
305
+ start: (...args: WorkflowStartArguments<TPayload>) => Promise<Result<WorkflowHandleRun<TPayload, TResult>, WorkflowResultErrorCode>>;
277
306
  }
278
307
  /** A duration such as `"30m"` or `"3 days"`, or a `Date` that the run must not start before. */
279
308
  type WorkflowStartDelay = Duration | Date;
@@ -307,4 +336,4 @@ interface DiscoveredWorkflowDefinition {
307
336
  source?: "agent-workflow" | "agent-workflow-recovery" | "inline" | "server-workflows" | "vite-suffix";
308
337
  steps?: string[];
309
338
  }
310
- export { WorkflowRun as A, WorkflowStartOptions as B, WorkflowName as C, WorkflowProviderStep as D, WorkflowProviderContext as E, WorkflowSharedOptions as F, WorkflowStepOptions as G, WorkflowStepBackoff as H, WorkflowSignal as I, WorkflowSteps as J, WorkflowStepRegistry as K, WorkflowSignalResult as L, WorkflowRunStatus as M, WorkflowRunStep as N, WorkflowRegistry as O, WorkflowRuntimeConfigValue as P, WorkflowStartArguments as R, WorkflowModuleDriverOptions as S, WorkflowPayload as T, WorkflowStepContext as U, WorkflowStep as V, WorkflowStepFunction 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, WorkflowStepRetries 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, WorkflowStartDelay as z };
339
+ export { WorkflowSteps as $, WorkflowProviderStep as A, WorkflowSharedOptions as B, WorkflowHandle as C, WorkflowOptions as D, WorkflowName as E, WorkflowRunError as F, WorkflowStartOptions as G, WorkflowSignalResult as H, WorkflowRunName as I, WorkflowStepContext as J, WorkflowStep as K, WorkflowRunStatus as L, WorkflowResult as M, WorkflowResultErrorCode as N, WorkflowPayload as O, WorkflowRun as P, WorkflowStepRetries as Q, WorkflowRunStep as R, WorkflowExecutionContext as S, WorkflowModuleDriverOptions as T, WorkflowStartArguments as U, WorkflowSignal as V, WorkflowStartDelay as W, WorkflowStepOptions as X, WorkflowStepFunction as Y, WorkflowStepRegistry as Z, WorkflowDefinitionRegistry as _, DiscoveredWorkflowDefinition as a, WorkflowDuration as b, OpenWorkflowDriverOptions as c, ResolvedWorkflowOptions as d, VercelWorkflowDriverOptions as f, WorkflowDefinitionOptions as g, WorkflowDefinition as h, CloudflareWorkflowInstance as i, WorkflowRegistry as j, WorkflowProviderContext as k, OpenWorkflowPostgresOptions as l, WorkflowCreateOptions as m, CloudflareWorkflowBinding as n, InferredWorkflowDriverOptions as o, WorkflowConcurrencySlots as p, WorkflowStepBackoff as q, CloudflareWorkflowDriverOptions as r, NamedWorkflowRun as s, AgentWorkflowRegistry as t, OpenWorkflowWorkerOptions as u, WorkflowDriver as v, WorkflowHandler as w, WorkflowDurationUnit as x, WorkflowDriverOptions as y, WorkflowRuntimeConfigValue as z };
@@ -1,7 +1,8 @@
1
1
  import { n as createWorkflowError } from "./errors-CZf7oz4k.js";
2
- import { a as workflowStartAtKey } from "./delay-CtT3442d.js";
2
+ import { s as workflowStartAtKey } from "./delay-JrpW40UF.js";
3
3
  import { a as safeWorkflowName, i as runWorkflowProviderOperation, r as isWorkflowBoundaryError, t as toWorkflowRunError } from "./run-error-8p4BtTMv.js";
4
- import { t as workflowErrorDiagnostics } from "./error-diagnostics--2cV_ER1.js";
4
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-35AEmfve.js";
5
+ import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime/internal/response";
5
6
  // src/runtime/vercel.ts
6
7
  async function loadVercelWorkflowRuntime() {
7
8
  const importVercelWorkflow = new Function("specifier", "return import(specifier)");
@@ -190,7 +191,8 @@ async function inspectVercelWorkflowRun(name, definition, id, payload) {
190
191
  status: normalizeStatus(status)
191
192
  };
192
193
  }), runWorkflowProviderOperation("vercel", "list-steps", async () => normalizeSteps(await runtime.listSteps(id)))]);
193
- const result = snapshot.status === "completed" ? await runWorkflowProviderOperation("vercel", "get-run", () => run.returnValue) : void 0;
194
+ const output = snapshot.status === "completed" ? await runWorkflowProviderOperation("vercel", "get-run", () => run.returnValue) : void 0;
195
+ const result = definition.native && Reflect.get(definition.native, "~vitehubGeneratedRootStep") === true && isSerializedResponse(output) ? deserializeResponse(output) : output;
194
196
  const error = snapshot.status === "failed" ? await readVercelRunError(run) : void 0;
195
197
  return {
196
198
  completedAt: snapshot.completedAt,