@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,278 +1 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics--2cV_ER1.js";
2
- import { n as createWorkflowError, r as isNonRetryableError, t as NonRetryableError } from "../errors-CZf7oz4k.js";
3
- import { t as getWorkflowDevRecorder } from "../dev-recorder-Dltdmlkv.js";
4
- import { n as createWorkflowSignalToken, r as openInlineWorkflowSignal, s as waitForInlineWorkflowSignal, t as closeInlineWorkflowSignals } from "../signals-BHQdxoJo.js";
5
- import { isResponse, serializeResponse, toResponse } from "@vite-hub/runtime/internal/response";
6
- // src/runtime/execute.ts
7
- const defaultRetries = {
8
- backoff: "exponential",
9
- delay: "10 seconds",
10
- limit: 3
11
- };
12
- const stepOptionKeys = /* @__PURE__ */ new Set(["retries", "timeout"]);
13
- const retryOptionKeys = /* @__PURE__ */ new Set([
14
- "backoff",
15
- "delay",
16
- "limit"
17
- ]);
18
- function isPlainObject(value) {
19
- return typeof value === "object" && value !== null && !Array.isArray(value);
20
- }
21
- /**
22
- * Checks the options of a step and fills in the default retries. A step file, `context.step.do()`, and every provider
23
- * read the options through this function, so an invalid value fails the same way everywhere.
24
- */
25
- function resolveWorkflowStepOptions(step, options) {
26
- const invalid = (option, value) => workflowErrorDiagnostics.WORKFLOW_STEP_OPTIONS_INVALID({
27
- option,
28
- step,
29
- value: typeof value === "string" ? JSON.stringify(value) : String(value)
30
- });
31
- if (options === void 0) return { retries: { ...defaultRetries } };
32
- if (!isPlainObject(options)) throw invalid("options", options);
33
- for (const key of Object.keys(options)) if (!stepOptionKeys.has(key)) throw invalid(key, options[key]);
34
- const retries = options.retries ?? {};
35
- if (!isPlainObject(retries)) throw invalid("retries", retries);
36
- for (const key of Object.keys(retries)) if (!retryOptionKeys.has(key)) throw invalid(`retries.${key}`, retries[key]);
37
- const { backoff = defaultRetries.backoff, delay = defaultRetries.delay, limit = defaultRetries.limit } = retries;
38
- if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0) throw invalid("retries.limit", limit);
39
- if (toDurationMilliseconds(delay) === void 0) throw invalid("retries.delay", delay);
40
- if (backoff !== "constant" && backoff !== "exponential") throw invalid("retries.backoff", backoff);
41
- const timeout = options.timeout;
42
- if (timeout !== void 0 && !toDurationMilliseconds(timeout)) throw invalid("timeout", timeout);
43
- return {
44
- retries: {
45
- backoff,
46
- delay,
47
- limit
48
- },
49
- ...timeout === void 0 ? {} : { timeout }
50
- };
51
- }
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);
101
- const recorder = getWorkflowDevRecorder();
102
- return recorder ? await recorder.step(name, attempt) : await attempt();
103
- }
104
- /** `01.create-user.ts` becomes the `createUser` step. */
105
- function toStepPropertyName(file) {
106
- return file.split("/").pop().replace(/\.(?:c|m)?[jt]s$/i, "").replace(/^\d+[.-]?/, "").replace(/[-_.]+([a-z0-9])/gi, (_, char) => char.toUpperCase());
107
- }
108
- function createWorkflowSteps(context, stepModules) {
109
- const names = /* @__PURE__ */ new Map();
110
- return Object.fromEntries(stepModules.map((module) => {
111
- const propertyName = toStepPropertyName(module.name);
112
- if (!propertyName) throw workflowErrorDiagnostics.WORKFLOW_C0011({ message: `[vitehub] Workflow step file ${JSON.stringify(module.name)} normalizes to an empty step property. Rename the file so the step property is non-empty.` });
113
- const previousName = names.get(propertyName);
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.` });
115
- names.set(propertyName, module.name);
116
- return [propertyName, async (input) => await runProviderStep(context.step, `${context.name}/${module.name}`, (stepContext) => module.run(input, stepContext), module.options)];
117
- }));
118
- }
119
- const durationUnits = {
120
- second: 1e3,
121
- minute: 6e4,
122
- hour: 36e5,
123
- day: 864e5,
124
- week: 6048e5,
125
- month: 2592e6,
126
- year: 315576e5
127
- };
128
- const durationPattern = /^(\d+(?:\.\d+)?) (second|minute|hour|day|week|month|year)s?$/;
129
- /** The milliseconds of a `WorkflowDuration`: a number of 0 or more, or a string such as `'30 seconds'`. */
130
- function toDurationMilliseconds(value) {
131
- if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : void 0;
132
- if (typeof value !== "string") return void 0;
133
- const match = durationPattern.exec(value);
134
- return match ? Number(match[1]) * durationUnits[match[2]] : void 0;
135
- }
136
- function toSleepTarget(name, until) {
137
- if (Object.prototype.toString.call(until) === "[object Date]") {
138
- const date = new Date(until.getTime());
139
- if (Number.isFinite(date.getTime())) return date;
140
- } else {
141
- const milliseconds = toDurationMilliseconds(until);
142
- if (milliseconds !== void 0) return milliseconds;
143
- }
144
- const value = typeof until === "string" ? JSON.stringify(until) : String(until);
145
- throw workflowErrorDiagnostics.WORKFLOW_SLEEP_DURATION_INVALID({
146
- name,
147
- value
148
- });
149
- }
150
- const maxTimerDelay = 2147483647;
151
- async function waitUntil(time) {
152
- for (let left = time - Date.now(); left > 0; left = time - Date.now()) await new Promise((resolve) => setTimeout(resolve, Math.min(left, maxTimerDelay)));
153
- }
154
- function createSleep(context) {
155
- let count = 0;
156
- return async (until) => {
157
- const target = toSleepTarget(context.name, until);
158
- const name = `sleep-${++count}`;
159
- const step = context.step;
160
- if (step?.sleep) {
161
- if (typeof target === "number") return await step.sleep(name, target);
162
- if (step.sleepUntil) return await step.sleepUntil(name, target);
163
- return await step.sleep(name, Math.max(0, target.getTime() - Date.now()));
164
- }
165
- const time = typeof target === "number" ? Date.now() + target : target.getTime();
166
- await runProviderStep(void 0, name, async () => await waitUntil(time));
167
- };
168
- }
169
- function createSignals(context, wait) {
170
- let count = 0;
171
- const inlineTokens = [];
172
- const createSignal = () => {
173
- if (context.provider === "vercel") throw workflowErrorDiagnostics.WORKFLOW_SIGNAL_VERCEL_UNSUPPORTED({ name: context.name });
174
- const step = context.step;
175
- if (step?.do && !step.waitForSignal) throw createWorkflowError({
176
- code: "WORKFLOW_OPERATION_UNSUPPORTED",
177
- details: {
178
- operation: "signals",
179
- provider: context.provider
180
- }
181
- });
182
- const name = `signal-${++count}`;
183
- const inline = !step?.waitForSignal;
184
- const token = createWorkflowSignalToken({
185
- host: inline ? "inline" : context.provider,
186
- run: context.id ?? "",
187
- signal: name,
188
- workflow: context.name
189
- });
190
- if (inline) {
191
- openInlineWorkflowSignal(token);
192
- inlineTokens.push(token);
193
- }
194
- let waiting;
195
- return {
196
- token,
197
- wait: () => waiting ??= wait ? wait() : inline ? runProviderStep(void 0, name, async () => await waitForInlineWorkflowSignal(token)) : step.waitForSignal(name, token)
198
- };
199
- };
200
- return {
201
- close: () => closeInlineWorkflowSignals(inlineTokens),
202
- createSignal
203
- };
204
- }
205
- function toExecutionContext(context, sleep, createSignal) {
206
- return {
207
- ...context,
208
- createSignal,
209
- sleep,
210
- steps: {}
211
- };
212
- }
213
- const rootStepSleepResult = { "~vitehubRootStepSleep": true };
214
- const rootStepSignalResult = { "~vitehubRootStepSignal": true };
215
- function toNonRetryableStepResult(error) {
216
- if (!isNonRetryableError(error)) return void 0;
217
- const code = Reflect.get(error, "code");
218
- return { "~vitehubNonRetryableError": {
219
- ...typeof code === "string" ? { code } : {},
220
- message: error.message,
221
- name: error.name
222
- } };
223
- }
224
- function readNonRetryableStepResult(value) {
225
- if (typeof value !== "object" || value === null || !Object.hasOwn(value, "~vitehubNonRetryableError")) return void 0;
226
- const { code, message, name } = value["~vitehubNonRetryableError"];
227
- const error = new NonRetryableError(message);
228
- error.name = name;
229
- return code === void 0 ? error : Object.assign(error, { code });
230
- }
231
- async function runInRootStep(context, definition, encode) {
232
- if (definition.rootStep === false) {
233
- const signals = createSignals(context);
234
- try {
235
- return await encode(await definition.handler(toExecutionContext(context, createSleep(context), signals.createSignal)));
236
- } finally {
237
- signals.close();
238
- }
239
- }
240
- let suspended;
241
- const sleepError = () => workflowErrorDiagnostics.WORKFLOW_ROOT_STEP_SLEEP({ name: context.name });
242
- const signalError = () => workflowErrorDiagnostics.WORKFLOW_ROOT_STEP_SIGNAL({ name: context.name });
243
- const sleep = async () => {
244
- suspended = rootStepSleepResult;
245
- throw sleepError();
246
- };
247
- const signals = createSignals(context, async () => {
248
- suspended = rootStepSignalResult;
249
- throw signalError();
250
- });
251
- const output = await runProviderStep(context.step, context.name, async () => {
252
- try {
253
- const value = await encode(await definition.handler(toExecutionContext(context, sleep, signals.createSignal)));
254
- return suspended ?? value;
255
- } catch (error) {
256
- if (suspended) return suspended;
257
- throw error;
258
- } finally {
259
- signals.close();
260
- }
261
- });
262
- if (typeof output === "object" && output !== null && "~vitehubRootStepSleep" in output) throw sleepError();
263
- if (typeof output === "object" && output !== null && "~vitehubRootStepSignal" in output) throw signalError();
264
- return output;
265
- }
266
- async function runWorkflowHandler(context, definition) {
267
- return toResponse(await runInRootStep(context, definition, (value) => value));
268
- }
269
- async function toStoredWorkflowResult(value) {
270
- if (isResponse(value)) return await serializeResponse(value);
271
- const json = JSON.stringify(value);
272
- return json === void 0 ? void 0 : JSON.parse(json);
273
- }
274
- /** Encode inside the root step so both checkpoints and final outputs survive replay. */
275
- async function runSerializedWorkflowHandler(context, definition) {
276
- return await runInRootStep(context, definition, toStoredWorkflowResult);
277
- }
278
- export { createWorkflowSteps, readNonRetryableStepResult, resolveWorkflowStepOptions, runProviderStep, runSerializedWorkflowHandler, runWorkflowHandler, runWorkflowStepAttempt, toDurationMilliseconds, toNonRetryableStepResult, toStepPropertyName, withWorkflowStepTimeout };
1
+ export { t as createWorkflowSteps, n as readNonRetryableStepResult, r as rejectDirectGeneratedWorkflowCall, i as resolveWorkflowStepOptions, a as runProviderStep, o as runSerializedWorkflowHandler, s as runWorkflowHandler, c as runWorkflowRootStep, l as runWorkflowStepAttempt, u as toDurationMilliseconds, d as toNonRetryableStepResult, f as toStepPropertyName, p as withWorkflowStepTimeout } from "../execute-CLmIXnON.js";
@@ -1,5 +1,5 @@
1
- import { o as getOpenWorkflowRuntime } from "../openworkflow-CdKbUGGa.js";
2
- import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-DvYcvbPG.js";
1
+ import { c as getOpenWorkflowRuntime } from "../openworkflow-C65AWQSJ.js";
2
+ import { _ as WorkflowDefinitionRegistry, d as ResolvedWorkflowOptions } from "../types-CvyOEp0V.js";
3
3
  import { ViteHubError } from "@vite-hub/runtime";
4
4
  import { ShutdownApp } from "@vite-hub/runtime/internal/shutdown";
5
5
  type OpenWorkflowWorker = ReturnType<Awaited<ReturnType<typeof getOpenWorkflowRuntime>>["client"]["newWorker"]>;
@@ -1,8 +1,8 @@
1
- import { describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter } from "./openworkflow.js";
1
+ import { c as registerOpenWorkflowDefinition, f as setOpenWorkflowDatabaseUrl, n as describeOpenWorkflowStorage, o as getOpenWorkflowRuntime, p as setOpenWorkflowImporter, r as detachOpenWorkflowRuntimes } from "../openworkflow-BiwPTYEz.js";
2
2
  import { i as runWorkflowProviderOperation } from "../run-error-8p4BtTMv.js";
3
3
  import { getWorkflowRuntimeConfig, getWorkflowRuntimeRegistry, loadWorkflowDefinition, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
4
4
  import { n as createWorkflowError } from "../errors-CZf7oz4k.js";
5
- import { t as workflowErrorDiagnostics } from "../error-diagnostics--2cV_ER1.js";
5
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-35AEmfve.js";
6
6
  import { ViteHubError } from "@vite-hub/runtime";
7
7
  import { onShutdown } from "@vite-hub/runtime/internal/shutdown";
8
8
  // src/runtime/openworkflow-worker.ts
@@ -1,2 +1,2 @@
1
- import { a as getOpenWorkflowRun, c as resetOpenWorkflowRuntime, d as setOpenWorkflowDatabaseUrl, f as setOpenWorkflowImporter, i as detachOpenWorkflowRuntimes, l as resumeOpenWorkflowSignal, n as cancelOpenWorkflowRun, o as getOpenWorkflowRuntime, r as describeOpenWorkflowStorage, s as registerOpenWorkflowDefinition, t as OpenWorkflowStorageSource, u as runOpenWorkflow } from "../openworkflow-CdKbUGGa.js";
2
- export { OpenWorkflowStorageSource, cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, resumeOpenWorkflowSignal, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
1
+ import { a as detachOpenWorkflowRuntimes, c as getOpenWorkflowRuntime, d as resetOpenWorkflowRuntime, f as resumeOpenWorkflowSignal, h as setOpenWorkflowImporter, i as describeOpenWorkflowStorage, l as listOpenWorkflowRuns, m as setOpenWorkflowDatabaseUrl, n as OpenWorkflowStorageSource, o as findOpenWorkflowRuns, p as runOpenWorkflow, r as cancelOpenWorkflowRun, s as getOpenWorkflowRun, t as OpenWorkflowRunListing, u as registerOpenWorkflowDefinition } from "../openworkflow-C65AWQSJ.js";
2
+ export { OpenWorkflowRunListing, OpenWorkflowStorageSource, cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, findOpenWorkflowRuns, getOpenWorkflowRun, getOpenWorkflowRuntime, listOpenWorkflowRuns, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, resumeOpenWorkflowSignal, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };