@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
@@ -0,0 +1,50 @@
1
+ import { E as WorkflowRun, P as WorkflowStartOptions, f as WorkflowDefinition, l as ResolvedWorkflowOptions } from "./types-CnKVDnEp.js";
2
+ //#region src/runtime/openworkflow.d.ts
3
+ type OpenWorkflowModule = typeof import("openworkflow");
4
+ type OpenWorkflowPostgresModule = typeof import("openworkflow/postgres");
5
+ type OpenWorkflowSqliteModule = typeof import("openworkflow/sqlite");
6
+ type OpenWorkflowClient = InstanceType<OpenWorkflowModule["OpenWorkflow"]>;
7
+ type OpenWorkflowBackend = Awaited<ReturnType<OpenWorkflowPostgresModule["BackendPostgres"]["connect"]>> | ReturnType<OpenWorkflowSqliteModule["BackendSqlite"]["connect"]>;
8
+ type OpenWorkflowRunnable = ReturnType<OpenWorkflowClient["defineWorkflow"]>;
9
+ type OpenWorkflowImporter = <T>(specifier: string) => Promise<T>;
10
+ interface OpenWorkflowRuntime {
11
+ backend: OpenWorkflowBackend;
12
+ client: OpenWorkflowClient;
13
+ /** Returns the OpenWorkflow id of the first run of `name` that started with the id `key`. */
14
+ findRunId: (name: string, key: string) => Promise<string | undefined>;
15
+ workflows: Map<string, OpenWorkflowRunnable>;
16
+ }
17
+ /**
18
+ * Where the storage came from: `configured` options or environment variables, the Postgres Default `database` of the
19
+ * app, or the `default` SQLite file.
20
+ */
21
+ type OpenWorkflowStorageSource = "configured" | "database" | "default";
22
+ /**
23
+ * Makes OpenWorkflow use the Postgres Default Database of the app when no OpenWorkflow storage is configured. The
24
+ * generated startup plugin installs it when the build has a Postgres Default Database.
25
+ */
26
+ declare function setOpenWorkflowDatabaseUrl(resolve: (() => string | undefined) | undefined): void;
27
+ /** The storage that OpenWorkflow uses for `config` now, without credentials. */
28
+ declare function describeOpenWorkflowStorage(config: ResolvedWorkflowOptions): {
29
+ backend: "postgres" | "sqlite";
30
+ location: string;
31
+ source: OpenWorkflowStorageSource;
32
+ };
33
+ declare function getOpenWorkflowRuntime(config: ResolvedWorkflowOptions): Promise<OpenWorkflowRuntime>;
34
+ declare function registerOpenWorkflowDefinition(runtime: OpenWorkflowRuntime, name: string, definition: WorkflowDefinition): Promise<OpenWorkflowRunnable>;
35
+ declare function runOpenWorkflow<TPayload = unknown, TResult = unknown>(config: ResolvedWorkflowOptions, name: string, payload: TPayload | undefined, definition: WorkflowDefinition<TPayload, TResult>, options: WorkflowStartOptions, onDispatch?: () => void, startAt?: number): Promise<WorkflowRun<TPayload, TResult>>;
36
+ declare function getOpenWorkflowRun<TPayload = unknown, TResult = unknown>(config: ResolvedWorkflowOptions, name: string, id: string): Promise<WorkflowRun<TPayload, TResult>>;
37
+ /**
38
+ * Cancels a pending or running OpenWorkflow run of this Workflow and returns its state afterwards. A run of another
39
+ * Workflow, or an unknown run, reports `unknown` without being cancelled. A finished run keeps and reports its status.
40
+ */
41
+ declare function cancelOpenWorkflowRun<TPayload = unknown, TResult = unknown>(config: ResolvedWorkflowOptions, name: string, id: string): Promise<WorkflowRun<TPayload, TResult>>;
42
+ declare function resetOpenWorkflowRuntime(): Promise<void>;
43
+ /**
44
+ * Starts a new runtime cache, so the next acquisition opens a fresh backend. Returns a function that closes the
45
+ * backends of the old cache. Call it after the work that still uses them, such as a stopping worker, finishes.
46
+ */
47
+ declare function detachOpenWorkflowRuntimes(): () => Promise<void>;
48
+ declare function setOpenWorkflowImporter(importer: OpenWorkflowImporter): void;
49
+ //#endregion
50
+ export { getOpenWorkflowRun as a, resetOpenWorkflowRuntime as c, setOpenWorkflowImporter as d, detachOpenWorkflowRuntimes as i, runOpenWorkflow as l, cancelOpenWorkflowRun as n, getOpenWorkflowRuntime as o, describeOpenWorkflowStorage as r, registerOpenWorkflowDefinition as s, OpenWorkflowStorageSource as t, setOpenWorkflowDatabaseUrl as u };
@@ -0,0 +1,26 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region ../internal/src/invariant.ts
3
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
5
+ codes: { INTERNAL_INVARIANT_FAILED: {
6
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
7
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
8
+ } }
9
+ });
10
+ /**
11
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
12
+ * Use a code from the package catalog when a developer can cause the error or fix it.
13
+ */
14
+ function invariantError(what) {
15
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
16
+ }
17
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
18
+ function invariant(condition, what) {
19
+ if (!condition) throw invariantError(what);
20
+ }
21
+ //#endregion
22
+ //#region src/internal/openworkflow-defaults.ts
23
+ /** The SQLite file that OpenWorkflow uses without configured storage, relative to the working directory of the server. */
24
+ const defaultOpenWorkflowSqlitePath = ".vitehub/data/openworkflow.sqlite.db";
25
+ //#endregion
26
+ export { invariant as n, invariantError as r, defaultOpenWorkflowSqlitePath as t };
@@ -0,0 +1,28 @@
1
+ //#region src/internal/openworkflow-storage.ts
2
+ /** Select storage once for both the OpenWorkflow runtime and its durability report. Values are already resolved. */
3
+ function resolveOpenWorkflowStorage(input, readEnv) {
4
+ const sqlitePath = input.sqlitePath || (!input.postgresUrl ? readEnv("OPENWORKFLOW_SQLITE_PATH") : void 0);
5
+ if (sqlitePath) return {
6
+ backend: "sqlite",
7
+ path: sqlitePath,
8
+ source: "configured"
9
+ };
10
+ if (input.postgresUrl) return {
11
+ backend: "postgres",
12
+ url: input.postgresUrl,
13
+ source: "`workflow.postgres.url`"
14
+ };
15
+ const url = readEnv("OPENWORKFLOW_POSTGRES_URL");
16
+ if (url) return {
17
+ backend: "postgres",
18
+ url,
19
+ source: "OPENWORKFLOW_POSTGRES_URL"
20
+ };
21
+ return {
22
+ backend: "sqlite",
23
+ path: ".vitehub/data/openworkflow.sqlite.db",
24
+ source: "default"
25
+ };
26
+ }
27
+ //#endregion
28
+ export { resolveOpenWorkflowStorage as t };
@@ -0,0 +1,2 @@
1
+ import { CreateOpenWorkflowWorkerOptions, InstallOpenWorkflowOptions, OpenWorkflowWorkerApp, StartOpenWorkflowWorkerOptions, createOpenWorkflowWorker, installOpenWorkflow, startOpenWorkflowWorker } from "./runtime/openworkflow-worker.js";
2
+ export { CreateOpenWorkflowWorkerOptions, InstallOpenWorkflowOptions, OpenWorkflowWorkerApp, StartOpenWorkflowWorkerOptions, createOpenWorkflowWorker, installOpenWorkflow, startOpenWorkflowWorker };
@@ -0,0 +1,2 @@
1
+ import { createOpenWorkflowWorker, installOpenWorkflow, startOpenWorkflowWorker } from "./runtime/openworkflow-worker.js";
2
+ export { createOpenWorkflowWorker, installOpenWorkflow, startOpenWorkflowWorker };
@@ -0,0 +1,234 @@
1
+ //#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
2
+ /** The Standard Typed interface. This is a base type extended by other specs. */
3
+ interface StandardTypedV1<Input = unknown, Output = Input> {
4
+ /** The Standard properties. */
5
+ readonly "~standard": StandardTypedV1.Props<Input, Output>;
6
+ }
7
+ declare namespace StandardTypedV1 {
8
+ /** The Standard Typed properties interface. */
9
+ interface Props<Input = unknown, Output = Input> {
10
+ /** The version number of the standard. */
11
+ readonly version: 1;
12
+ /** The vendor name of the schema library. */
13
+ readonly vendor: string;
14
+ /** Inferred types associated with the schema. */
15
+ readonly types?: Types<Input, Output> | undefined;
16
+ }
17
+ /** The Standard Typed types interface. */
18
+ interface Types<Input = unknown, Output = Input> {
19
+ /** The input type of the schema. */
20
+ readonly input: Input;
21
+ /** The output type of the schema. */
22
+ readonly output: Output;
23
+ }
24
+ /** Infers the input type of a Standard Typed. */
25
+ type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
26
+ /** Infers the output type of a Standard Typed. */
27
+ type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
28
+ }
29
+ /** The Standard Schema interface. */
30
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
31
+ /** The Standard Schema properties. */
32
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
33
+ }
34
+ declare namespace StandardSchemaV1 {
35
+ /** The Standard Schema properties interface. */
36
+ interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
37
+ /** Validates unknown input values. */
38
+ readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
39
+ }
40
+ /** The result interface of the validate function. */
41
+ type Result<Output> = SuccessResult<Output> | FailureResult;
42
+ /** The result interface if validation succeeds. */
43
+ interface SuccessResult<Output> {
44
+ /** The typed output value. */
45
+ readonly value: Output;
46
+ /** A falsy value for `issues` indicates success. */
47
+ readonly issues?: undefined;
48
+ }
49
+ interface Options {
50
+ /** Explicit support for additional vendor-specific parameters, if needed. */
51
+ readonly libraryOptions?: Record<string, unknown> | undefined;
52
+ }
53
+ /** The result interface if validation fails. */
54
+ interface FailureResult {
55
+ /** The issues of failed validation. */
56
+ readonly issues: ReadonlyArray<Issue>;
57
+ }
58
+ /** The issue interface of the failure output. */
59
+ interface Issue {
60
+ /** The error message of the issue. */
61
+ readonly message: string;
62
+ /** The path of the issue, if any. */
63
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
64
+ }
65
+ /** The path segment interface of the issue. */
66
+ interface PathSegment {
67
+ /** The key representing a path segment. */
68
+ readonly key: PropertyKey;
69
+ }
70
+ /** The Standard types interface. */
71
+ interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
72
+ /** Infers the input type of a Standard. */
73
+ type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
74
+ /** Infers the output type of a Standard. */
75
+ type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
76
+ }
77
+ //#endregion
78
+ //#region ../internal/src/operation-definition.d.ts
79
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
80
+ type OperationKind = "read" | "write" | "destructive";
81
+ /** The signed-in user of a call. */
82
+ interface OperationUser {
83
+ id: string;
84
+ name?: string;
85
+ email?: string;
86
+ image?: string;
87
+ [key: string]: unknown;
88
+ }
89
+ /** The Agent Actor when an agent calls through a capability or MCP on behalf of a user. */
90
+ interface OperationActor {
91
+ id: string;
92
+ kind?: string;
93
+ label?: string;
94
+ meta?: object;
95
+ }
96
+ /** The checked Console access of a call. `vite-hub` issues it. `ConsoleAccess` has this shape. */
97
+ interface OperationAccess {
98
+ readonly mode: string;
99
+ /**
100
+ * The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
101
+ * operation of the section), `"<section>:read"` (only the operations that read), or `"<section>:<scope>"` (only the
102
+ * calls of a scoped operation for that scope, such as `"blob:media"` for one Blob store). `"<section>:<scope>:read"`
103
+ * allows only the reads of that scope.
104
+ */
105
+ readonly sections: "all" | readonly string[];
106
+ readonly user?: OperationUser;
107
+ }
108
+ interface OperationContext {
109
+ /** The checked Console access of the call. */
110
+ access: OperationAccess;
111
+ /** The signed-in user, or null. */
112
+ user: OperationUser | null;
113
+ /** The Agent Actor when an agent calls on behalf of `user`. */
114
+ actor?: OperationActor;
115
+ surface: "console" | "cli" | "mcp" | "agent";
116
+ /** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
117
+ development?: boolean;
118
+ env?: Record<string, unknown>;
119
+ waitUntil?: (task: Promise<unknown>) => void;
120
+ request?: Request;
121
+ /**
122
+ * The request event of the HTTP request that carries the call, when there is one: the Request of the Console route,
123
+ * with its Standard Context. Operations hand it to app hooks that read the request's own session, such as `identify`
124
+ * of Comments.
125
+ */
126
+ event?: unknown;
127
+ /** Operations set a success status here, such as 202 for an accepted call. */
128
+ response?: {
129
+ status?: number;
130
+ };
131
+ /**
132
+ * An agent or an MCP client may pass `lease: "override"` to `content.save`, `content.remove`, and `content.restore`
133
+ * only when the developer allowed it. Defaults to false, so a model cannot take over a document that a person is editing.
134
+ */
135
+ overrideLeases?: boolean;
136
+ /**
137
+ * What an Agent may read of the Channel conversations, set by `operations({ conversations })`. `participant`: only the
138
+ * threads that the Actor takes part in. `all`: every thread. Unset: none.
139
+ */
140
+ conversations?: "all" | "participant";
141
+ }
142
+ interface OperationDefinition<Input, Output> {
143
+ /** `<section>.<verb>`, such as `content.publish`. Unique per app. */
144
+ name: string;
145
+ /** One sentence. Becomes the CLI help line and the MCP tool description. */
146
+ description: string;
147
+ /**
148
+ * Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
149
+ * from the input, for operations that serve several sections. Section ids cannot contain `:`; it is reserved for
150
+ * scope and read-only grants. A function that returns an invalid id denies the call.
151
+ */
152
+ section: string | false | ((input: Input) => string | undefined);
153
+ /**
154
+ * The part of a string `section` that one call uses, such as the Blob store that the input names. The call then needs
155
+ * the section (every scope) or `"<section>:<scope>"` (only this scope). A scope that is empty, is `read`, or has a
156
+ * `:` needs the whole section.
157
+ */
158
+ scope?: (input: Input) => string | undefined;
159
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
160
+ kind: OperationKind;
161
+ /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
162
+ input: StandardSchemaV1<unknown, Input>;
163
+ output?: StandardSchemaV1<unknown, Output>;
164
+ cli?: {
165
+ /** Defaults: namespace = section, command = verb. */
166
+ namespace?: string;
167
+ /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
168
+ command?: string;
169
+ /** Input keys read from positional arguments, in order. */
170
+ positional?: string[];
171
+ /** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
172
+ format?: (output: Output) => string;
173
+ /** `vitehub <namespace>` runs this command when no command is named. */
174
+ default?: boolean;
175
+ };
176
+ /** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
177
+ maxRequestBytes?: number;
178
+ /**
179
+ * Returns true when this call only reads, such as a dry run of a `destructive` operation. The CLI then skips the
180
+ * confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
181
+ */
182
+ readOnlyWhen?: (input: Input) => boolean;
183
+ /**
184
+ * How MCP offers the operation as a tool. `false`: MCP does not offer it, such as an editor transport that only the
185
+ * Console uses. `title`: the short title that clients show, instead of the name in words. `format`: the text of a
186
+ * result for the Agent, such as a list of lines. The result stays the structured content. Without `format`, the text
187
+ * is the result as JSON.
188
+ */
189
+ mcp?: false | {
190
+ title?: string;
191
+ format?: (output: NoInfer<Output>) => string;
192
+ };
193
+ /** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
194
+ user?: false;
195
+ /**
196
+ * The operation runs code of the app, such as a workflow, a job, a task, or a schedule. The Console registers it only
197
+ * when `console.invoke` is on, which is the default in development and off in a production build.
198
+ */
199
+ invoke?: true;
200
+ run: (input: Input, context: OperationContext) => Output | Promise<Output>;
201
+ }
202
+ /** An operation of any input and output, as a registry holds it. */
203
+ interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
204
+ readOnlyWhen?: (input: never) => boolean;
205
+ cli?: {
206
+ namespace?: string;
207
+ command?: string;
208
+ default?: boolean;
209
+ positional?: string[];
210
+ format?: (output: never) => string;
211
+ };
212
+ mcp?: false | {
213
+ title?: string;
214
+ format?: (output: never) => string;
215
+ };
216
+ input: StandardSchemaV1;
217
+ output?: StandardSchemaV1;
218
+ run: (input: never, context: OperationContext) => unknown;
219
+ scope?: (input: never) => string | undefined;
220
+ section: string | false | ((input: never) => string | undefined);
221
+ }
222
+ /** The contribution of one plugin: operations, or a module that exports them. */
223
+ interface OperationContributionEntry {
224
+ /** The absolute path of the module that generated code imports, such as `ownModule(import.meta.url, "operations")`. */
225
+ module: string;
226
+ /** Named export that holds an operation or an array of operations. Defaults to `default`. */
227
+ export?: string;
228
+ /** Loads the export in the tool process, for a module that the tool cannot resolve by name. */
229
+ load?: () => Promise<unknown>;
230
+ /** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
231
+ runtime?: false;
232
+ }
233
+ //#endregion
234
+ export { OperationContributionEntry as n, AnyOperation as t };
@@ -0,0 +1,329 @@
1
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-8YNJ37rP.js";
2
+ import { a as resumeWorkflow, i as getWorkflowRun, o as startWorkflow, t as cancelWorkflow } from "./client-CU5rELC0.js";
3
+ import { t as isRecord } from "./object-Da1zyPCR.js";
4
+ import { t as getWorkflowDevRecorder } from "./dev-recorder-CTN5Fkao.js";
5
+ import { n as redactInspectionValue, t as redactInspectionText } from "./inspect-B72iFyj-.js";
6
+ import { t as toWorkflowRunError } from "./run-error-DBWqiJHH.js";
7
+ import { getInlineWorkflowDefinitions, getWorkflowRuntimeConfig, getWorkflowRuntimeRegistry } from "./runtime/state.js";
8
+ import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime";
9
+ //#region src/results.ts
10
+ const inlineRunNote = "Runs the Workflow inline in the Nitro runtime, as the app does in development. Inline runs are not durable and have no retries.";
11
+ function unsupported(note) {
12
+ return {
13
+ note,
14
+ supported: false
15
+ };
16
+ }
17
+ /**
18
+ * Operations that each provider supports. A supported operation can still fail when the runtime decides, for example
19
+ * cancel on an inline Vercel run.
20
+ */
21
+ function resolveWorkflowOperationSupport(provider) {
22
+ if (provider === "cloudflare") return {
23
+ cancel: {
24
+ note: "Terminates a queued, running, waiting, or paused run through the Cloudflare Workflow binding. A finished run keeps its status. Inline runs return an unsupported error.",
25
+ supported: true
26
+ },
27
+ get: {
28
+ note: "Reads the run from the Cloudflare Workflow binding when the runtime has one.",
29
+ supported: true
30
+ },
31
+ resume: unsupported("Cloudflare Workflows do not support ViteHub signals."),
32
+ start: {
33
+ note: `Uses the Cloudflare Workflow binding when the runtime has one. Otherwise: ${inlineRunNote}`,
34
+ supported: true
35
+ }
36
+ };
37
+ if (provider === "openworkflow") return {
38
+ cancel: {
39
+ note: "Cancels a pending or running run in OpenWorkflow storage. A step that is already running finishes, but its worker records no further steps or result.",
40
+ supported: true
41
+ },
42
+ get: {
43
+ note: "Reads the run from OpenWorkflow storage.",
44
+ supported: true
45
+ },
46
+ resume: unsupported("OpenWorkflow does not support ViteHub signals."),
47
+ start: {
48
+ note: "Enqueues the run in OpenWorkflow storage. The run stays queued until an OpenWorkflow worker processes the same storage.",
49
+ supported: true
50
+ }
51
+ };
52
+ return {
53
+ cancel: {
54
+ note: "Only native Vercel Workflow runs can be cancelled. Inline runs return an unsupported error.",
55
+ supported: true
56
+ },
57
+ get: {
58
+ note: "Reads inline runs, which expire 5 minutes after they finish. Native Vercel Workflow runs need the Workflow DevKit runtime.",
59
+ supported: true
60
+ },
61
+ resume: {
62
+ note: "Signals need a native Vercel Workflow run and the Workflow DevKit runtime.",
63
+ supported: true
64
+ },
65
+ start: {
66
+ note: `${inlineRunNote} Native Vercel Workflow Definitions need the Workflow DevKit runtime.`,
67
+ supported: true
68
+ }
69
+ };
70
+ }
71
+ //#endregion
72
+ //#region src/runtime/operations.ts
73
+ const maxRememberedRuns = 1024;
74
+ /** The HTTP status that the CLI, the Console, and Agents report for each code of a failed operation. */
75
+ const operationStatus = {
76
+ VERCEL_WORKFLOW_SDK_LOAD_FAILED: 501,
77
+ WORKFLOW_DEFINITION_NOT_FOUND: 404,
78
+ WORKFLOW_DISABLED: 409,
79
+ WORKFLOW_NATIVE_ENTRY_INVALID: 501,
80
+ WORKFLOW_NATIVE_ENTRY_REQUIRED: 501,
81
+ WORKFLOW_OPERATION_FAILED: 500,
82
+ WORKFLOW_OPERATION_UNSUPPORTED: 501,
83
+ WORKFLOW_PROVIDER_OPERATION_FAILED: 502,
84
+ WORKFLOW_REGISTRY_MISSING: 409,
85
+ WORKFLOW_RUN_AMBIGUOUS: 400,
86
+ WORKFLOW_RUN_NOT_FOUND: 404,
87
+ WORKFLOW_RUN_UNKNOWN: 400,
88
+ WORKFLOW_RUNS_UNAVAILABLE: 409
89
+ };
90
+ /** Gives an operation error the status of its code and the redacted message that the CLI and the Console report. */
91
+ function failure(error, message = error.message) {
92
+ return Object.defineProperties(error, {
93
+ status: {
94
+ configurable: true,
95
+ enumerable: false,
96
+ value: operationStatus[errorCode(error) ?? ""] ?? 500,
97
+ writable: true
98
+ },
99
+ statusMessage: {
100
+ configurable: true,
101
+ enumerable: false,
102
+ value: redactInspectionText(message),
103
+ writable: true
104
+ }
105
+ });
106
+ }
107
+ function hasStatus(error) {
108
+ return error instanceof Error && typeof Reflect.get(error, "status") === "number" && typeof Reflect.get(error, "code") === "string";
109
+ }
110
+ /**
111
+ * Checks the Fetch Response fields, not one realm's constructor, so a Response from another Fetch implementation also
112
+ * matches. `status` and `headers` alone also match an HTTP client result, such as an Axios response, so the body fields
113
+ * are checked too. The Agent package has the same check.
114
+ */
115
+ function isResponse$1(value) {
116
+ if (typeof value !== "object" || value === null) return false;
117
+ const response = value;
118
+ return typeof response.status === "number" && typeof response.headers?.get === "function" && typeof response.bodyUsed === "boolean" && typeof response.clone === "function" && typeof response.text === "function";
119
+ }
120
+ function jsonReplacer(_key, value) {
121
+ if (typeof value === "bigint") return value.toString();
122
+ if (value instanceof Error) return serializeError(value);
123
+ if (isResponse$1(value)) return { response: {
124
+ status: value.status,
125
+ statusText: value.statusText
126
+ } };
127
+ return value;
128
+ }
129
+ function toJsonValue(value) {
130
+ if (value === void 0) return void 0;
131
+ try {
132
+ const text = JSON.stringify(value, jsonReplacer);
133
+ return text === void 0 ? void 0 : redactInspectionValue(JSON.parse(text));
134
+ } catch {
135
+ return "[unserializable]";
136
+ }
137
+ }
138
+ function errorCode(error) {
139
+ if (!error || typeof error !== "object") return;
140
+ const code = Reflect.get(error, "code");
141
+ return typeof code === "string" ? code : void 0;
142
+ }
143
+ function serializeError(error) {
144
+ const code = errorCode(error);
145
+ return {
146
+ ...code ? { code } : {},
147
+ message: redactInspectionText(error.message),
148
+ ...error.name && error.name !== "Error" ? { name: error.name } : {}
149
+ };
150
+ }
151
+ function toIsoDate(value) {
152
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? void 0 : value.toISOString();
153
+ return typeof value === "string" ? value : void 0;
154
+ }
155
+ function isErrorLike(value) {
156
+ return value instanceof Error || isRecord(value) && typeof value.message === "string";
157
+ }
158
+ async function readResult(result) {
159
+ if (!isResponse$1(result)) return result;
160
+ const text = await result.clone().text();
161
+ if (!text) return void 0;
162
+ try {
163
+ return JSON.parse(text);
164
+ } catch {
165
+ return text;
166
+ }
167
+ }
168
+ /**
169
+ * Converts a runtime Workflow run to JSON data. The view omits the start
170
+ * payload and redacts credentials in the metadata, result, and error message.
171
+ */
172
+ async function toWorkflowRunView(run, workflow) {
173
+ const createdAt = toIsoDate(run.createdAt);
174
+ const startedAt = toIsoDate(run.startedAt);
175
+ const completedAt = toIsoDate(run.completedAt);
176
+ const error = run.error ? {
177
+ ...run.error,
178
+ message: redactInspectionText(run.error.message)
179
+ } : void 0;
180
+ const metadata = toJsonValue(run.metadata);
181
+ const result = toJsonValue(await readResult(run.result));
182
+ return {
183
+ ...completedAt ? { completedAt } : {},
184
+ ...createdAt ? { createdAt } : {},
185
+ ...error ? { error } : {},
186
+ id: run.id,
187
+ ...metadata === void 0 ? {} : { metadata },
188
+ provider: run.provider,
189
+ ...result === void 0 ? {} : { result },
190
+ ...startedAt ? { startedAt } : {},
191
+ status: run.status,
192
+ workflow
193
+ };
194
+ }
195
+ function runtimeFailure(operation, provider, error) {
196
+ if (hasStatus(error)) return error;
197
+ const code = errorCode(error);
198
+ if (code === "WORKFLOW_OPERATION_UNSUPPORTED") return failure(workflowErrorDiagnostics.WORKFLOW_OPERATION_UNSUPPORTED({
199
+ cause: error,
200
+ operation,
201
+ provider
202
+ }));
203
+ if (code === "WORKFLOW_DISABLED") return failure(workflowErrorDiagnostics.WORKFLOW_DISABLED({ cause: error }));
204
+ if (code === "WORKFLOW_DEFINITION_NOT_FOUND") return failure(workflowErrorDiagnostics.WORKFLOW_DEFINITION_NOT_FOUND({ cause: error }));
205
+ if (error instanceof Error && (code === "VERCEL_WORKFLOW_SDK_LOAD_FAILED" || code === "WORKFLOW_NATIVE_ENTRY_INVALID" || code === "WORKFLOW_NATIVE_ENTRY_REQUIRED")) return failure(error, `workflow ${operation} needs the Vercel Workflow DevKit runtime, which the runtime could not load.`);
206
+ if (error instanceof Error && code === "WORKFLOW_PROVIDER_OPERATION_FAILED") return failure(error, `workflow ${operation} failed in the ${provider} provider.${error.cause instanceof Error && error.cause.message ? ` ${error.cause.message}` : ""}`);
207
+ if (error instanceof Error && code) return failure(error);
208
+ const message = error instanceof Error ? error.message : String(error);
209
+ return failure(workflowErrorDiagnostics.WORKFLOW_OPERATION_FAILED({ cause: error }), message || "The Workflow operation failed.");
210
+ }
211
+ function startableWorkflows() {
212
+ return [.../* @__PURE__ */ new Set([...Object.keys(getWorkflowRuntimeRegistry() ?? {}), ...getInlineWorkflowDefinitions().keys()])].sort();
213
+ }
214
+ const startedRuns = /* @__PURE__ */ new Map();
215
+ function rememberRun(id, workflow) {
216
+ startedRuns.delete(id);
217
+ startedRuns.set(id, workflow);
218
+ if (startedRuns.size > maxRememberedRuns) {
219
+ const oldest = startedRuns.keys().next().value;
220
+ if (oldest !== void 0) startedRuns.delete(oldest);
221
+ }
222
+ }
223
+ /**
224
+ * Runs one Workflow operation in the runtime of the app, so it uses the same Workflow state and registry as the app.
225
+ * It redacts credentials in run data and error messages. Failures are catalog errors with an HTTP `status`.
226
+ */
227
+ async function runWorkflowOperation(operation, input) {
228
+ const runtimeConfig = getWorkflowRuntimeConfig();
229
+ if (runtimeConfig === false) throw failure(workflowErrorDiagnostics.WORKFLOW_DISABLED());
230
+ const provider = runtimeConfig?.driver ?? "vercel";
231
+ const support = resolveWorkflowOperationSupport(provider)[operation];
232
+ if (!support.supported) throw failure(workflowErrorDiagnostics.WORKFLOW_OPERATION_UNSUPPORTED({
233
+ note: support.note,
234
+ operation,
235
+ provider
236
+ }));
237
+ try {
238
+ return await run(operation, input);
239
+ } catch (error) {
240
+ throw runtimeFailure(operation, provider, error);
241
+ }
242
+ }
243
+ async function run(operation, input) {
244
+ if (operation === "start") {
245
+ const { payload, workflow } = input;
246
+ const workflows = startableWorkflows();
247
+ if (!workflows.includes(workflow)) {
248
+ if (!getWorkflowRuntimeRegistry()) throw failure(workflowErrorDiagnostics.WORKFLOW_REGISTRY_MISSING({ workflow }));
249
+ const available = workflows.length ? ` Available Workflows: ${workflows.join(", ")}.` : " The Workflow registry of the runtime is empty.";
250
+ throw failure(workflowErrorDiagnostics.WORKFLOW_DEFINITION_NOT_FOUND({
251
+ available,
252
+ workflow
253
+ }));
254
+ }
255
+ const started = await startWorkflow(workflow, payload);
256
+ rememberRun(started.id, workflow);
257
+ return { run: await toWorkflowRunView(started, workflow) };
258
+ }
259
+ if (operation === "resume") {
260
+ const { payload, token } = input;
261
+ const signal = await resumeWorkflow(token, payload);
262
+ return { signal: {
263
+ id: signal.id,
264
+ provider: signal.provider
265
+ } };
266
+ }
267
+ const { runId, workflow: named } = input;
268
+ const workflow = named ?? startedRuns.get(runId);
269
+ if (!workflow) throw failure(workflowErrorDiagnostics.WORKFLOW_RUN_UNKNOWN({ runId }));
270
+ return { run: await toWorkflowRunView(operation === "get" ? await getWorkflowRun(workflow, runId) : await cancelWorkflow(workflow, runId), workflow) };
271
+ }
272
+ /** The run history of `vite dev`. Hosted providers keep their own history, which ViteHub does not list. */
273
+ function devRecorder() {
274
+ if (getWorkflowRuntimeConfig() === false) throw failure(workflowErrorDiagnostics.WORKFLOW_DISABLED());
275
+ const recorder = getWorkflowDevRecorder();
276
+ if (!recorder) throw failure(workflowErrorDiagnostics.WORKFLOW_RUNS_UNAVAILABLE());
277
+ return recorder;
278
+ }
279
+ function devRunView(record) {
280
+ return {
281
+ ...record.completedAt ? { completedAt: record.completedAt } : {},
282
+ createdAt: record.createdAt,
283
+ id: record.id,
284
+ ...record.status === "failed" ? { error: toWorkflowRunError(record.error) } : {},
285
+ provider: record.provider,
286
+ ...record.status === "completed" ? { result: isSerializedResponse(record.result) ? deserializeResponse(record.result) : record.result } : {},
287
+ ...record.startedAt ? { startedAt: record.startedAt } : {},
288
+ status: record.status
289
+ };
290
+ }
291
+ function stepView(step) {
292
+ const output = step.status === "completed" ? toJsonValue(step.output) : void 0;
293
+ return {
294
+ ...step.completedAt ? { completedAt: step.completedAt.toISOString() } : {},
295
+ ...step.status === "failed" ? { error: isErrorLike(step.error) ? serializeError(step.error) : { message: redactInspectionText(String(step.error)) } } : {},
296
+ name: step.name,
297
+ ...output === void 0 ? {} : { output },
298
+ startedAt: step.startedAt.toISOString(),
299
+ status: step.status
300
+ };
301
+ }
302
+ /** Lists the runs that `vite dev` recorded, newest first. */
303
+ async function listWorkflowRuns(input) {
304
+ const records = devRecorder().list().filter((record) => (input.workflow === void 0 || record.workflow === input.workflow) && (input.status === void 0 || record.status === input.status)).slice(0, input.limit ?? 200);
305
+ return { runs: await Promise.all(records.map(async (record) => ({
306
+ ...await toWorkflowRunView(devRunView(record), record.workflow),
307
+ stepCount: record.steps.length
308
+ }))) };
309
+ }
310
+ /** Shows one run that `vite dev` recorded, with its steps, result, and error. */
311
+ async function showWorkflowRun(input) {
312
+ const matches = devRecorder().list().filter((record) => record.id === input.id && (input.workflow === void 0 || record.workflow === input.workflow));
313
+ if (matches.length === 0) throw failure(workflowErrorDiagnostics.WORKFLOW_RUN_NOT_FOUND({ id: input.id }));
314
+ if (matches.length > 1) throw failure(workflowErrorDiagnostics.WORKFLOW_RUN_AMBIGUOUS({
315
+ id: input.id,
316
+ workflows: matches.map((record) => record.workflow).join(", ")
317
+ }));
318
+ const record = matches[0];
319
+ return { run: {
320
+ ...await toWorkflowRunView(devRunView(record), record.workflow),
321
+ steps: record.steps.map(stepView)
322
+ } };
323
+ }
324
+ /** Removes the runs that `vite dev` recorded. A run that is still active finishes but is not listed again. */
325
+ function clearWorkflowRuns() {
326
+ return { cleared: devRecorder().clear() };
327
+ }
328
+ //#endregion
329
+ export { clearWorkflowRuns, listWorkflowRuns, runWorkflowOperation, showWorkflowRun, toWorkflowRunView };