experimental-ash 0.8.2 → 0.9.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 (57) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/dist/docs/public/channels/slack.md +53 -25
  3. package/dist/src/compiled/.vendor-stamp.json +14 -14
  4. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
  5. package/dist/src/compiled/@ai-sdk/google/index.js +4 -4
  6. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  7. package/dist/src/compiled/@ai-sdk/openai/index.js +6 -6
  8. package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
  9. package/dist/src/compiled/@ai-sdk/provider/_json-schema.d.ts +5 -0
  10. package/dist/src/compiled/@ai-sdk/provider/index.d.ts +6632 -1
  11. package/dist/src/compiled/@chat-adapter/slack/_chat-adapter-shared.d.ts +9 -0
  12. package/dist/src/compiled/@chat-adapter/slack/index.d.ts +632 -54
  13. package/dist/src/compiled/@chat-adapter/slack/index.js +25 -29
  14. package/dist/src/compiled/@chat-adapter/slack/package.json +1 -1
  15. package/dist/src/compiled/@chat-adapter/state-memory/index.d.ts +41 -25
  16. package/dist/src/compiled/@chat-adapter/state-memory/package.json +1 -1
  17. package/dist/src/compiled/@standard-schema/spec/index.d.ts +115 -62
  18. package/dist/src/compiled/@vercel/sandbox/index.d.ts +4 -1
  19. package/dist/src/compiled/@vercel/sandbox/index.js +5 -5
  20. package/dist/src/compiled/@workflow/core/index.js +1 -1
  21. package/dist/src/compiled/@workflow/core/runtime.d.ts +6 -2
  22. package/dist/src/compiled/@workflow/core/runtime.js +4 -4
  23. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  24. package/dist/src/compiled/@workflow/errors/_ms.d.ts +4 -0
  25. package/dist/src/compiled/@workflow/errors/error-codes.d.ts +17 -0
  26. package/dist/src/compiled/@workflow/errors/index.d.ts +438 -56
  27. package/dist/src/compiled/@workflow/errors/index.js +1 -1
  28. package/dist/src/compiled/_chunks/node/{auth-CdwuOxMs.js → auth-vbe4XEEK.js} +2 -2
  29. package/dist/src/compiled/_chunks/node/{dist-B6IOtzm1.js → dist-BdWHjlRQ.js} +12 -12
  30. package/dist/src/compiled/_chunks/node/retry-BOcy5BbJ.js +1 -0
  31. package/dist/src/compiled/_chunks/workflow/{context-errors-CXifqq6a.js → context-errors-zbKocOyk.js} +1 -1
  32. package/dist/src/compiled/_chunks/workflow/{dist-BuELZxm6.js → dist-Ci2brnHh.js} +3 -3
  33. package/dist/src/compiled/_chunks/workflow/{resume-hook-CgfgCU87.js → resume-hook-CL8Ed91K.js} +2 -2
  34. package/dist/src/compiled/_chunks/workflow/sleep-Dn3i9nxI.js +1 -0
  35. package/dist/src/compiled/chat/_mdast.d.ts +24 -0
  36. package/dist/src/compiled/chat/_workflow-serde.d.ts +5 -0
  37. package/dist/src/compiled/chat/index.d.ts +3851 -72
  38. package/dist/src/compiled/chat/index.js +1 -1
  39. package/dist/src/compiled/chat/jsx-runtime-DxGwoLu2.d.ts +782 -0
  40. package/dist/src/compiled/chat/package.json +1 -1
  41. package/dist/src/compiled/just-bash/index.js +1 -1
  42. package/dist/src/execution/authorization-challenge-defaults.d.ts +1 -1
  43. package/dist/src/execution/authorization-challenge-defaults.js +1 -1
  44. package/dist/src/internal/application/package.js +1 -1
  45. package/dist/src/public/channels/slack/index.d.ts +1 -1
  46. package/dist/src/public/channels/slack/slack.js +4 -1
  47. package/dist/src/public/channels/slack/slackChannel.d.ts +64 -1
  48. package/dist/src/public/channels/slack/slackChannel.js +50 -7
  49. package/dist/src/runtime/connections/authorization-tokens.d.ts +1 -1
  50. package/dist/src/runtime/connections/authorization-tokens.js +1 -1
  51. package/package.json +16 -16
  52. package/dist/src/compiled/_chunks/node/ms-B2k_qBoq.js +0 -1
  53. package/dist/src/compiled/_chunks/workflow/sleep-BzS_cSYx.js +0 -1
  54. /package/dist/src/compiled/_chunks/workflow/{dist-C9DdsXoK.js → dist-0iNBqPYp.js} +0 -0
  55. /package/dist/src/compiled/_chunks/workflow/{dist-BHbmiLmM.js → dist-D774SUM4.js} +0 -0
  56. /package/dist/src/compiled/_chunks/workflow/{src-CidBwKAD.js → src-ClRYdO4-.js} +0 -0
  57. /package/dist/src/compiled/_chunks/workflow/{symbols-BC0BVTM7.js → symbols-D-4tVV8x.js} +0 -0
@@ -1 +1 @@
1
- import{o as e,r as t}from"../../_chunks/workflow/dist-C9DdsXoK.js";import{a as n,n as r,r as i,s as a}from"../../_chunks/workflow/context-errors-CXifqq6a.js";import{d as o,f as s,s as c}from"../../_chunks/workflow/symbols-BC0BVTM7.js";import{t as l}from"../../_chunks/workflow/sleep-BzS_cSYx.js";function u(e){let t=globalThis[o];return t||i(`createHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-hook`,u),t(e)}function d(e){let{respondWith:t,token:n,...r}=e??{};if(n!==void 0)throw Error("`createWebhook()` does not accept a `token` option. Webhook tokens are always randomly generated. Use `createHook()` with `resumeHook()` for deterministic token patterns.");let i;t!==void 0&&(i={respondWith:t});let o=u({...r,metadata:i,isWebhook:!0}),{url:s}=a();return o.url=`${s}/.well-known/workflow/v1/webhook/${encodeURIComponent(o.token)}`,o}function f(){function e(t,r){n(`defineHook().resume()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,e)}return{create(e){return u(e)},resume:e}}function p(e={}){let{namespace:t}=e,n=globalThis[s](t);return Object.create(globalThis.WritableStream.prototype,{[c]:{value:n,writable:!1}})}function m(){r(`getStepMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata`,m)}function h(){n(`resumeHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,h)}export{t as FatalError,e as RetryableError,u as createHook,d as createWebhook,f as defineHook,m as getStepMetadata,a as getWorkflowMetadata,p as getWritable,h as resumeHook,l as sleep};
1
+ import{o as e,r as t}from"../../_chunks/workflow/dist-0iNBqPYp.js";import{a as n,n as r,r as i,s as a}from"../../_chunks/workflow/context-errors-zbKocOyk.js";import{d as o,f as s,s as c}from"../../_chunks/workflow/symbols-D-4tVV8x.js";import{t as l}from"../../_chunks/workflow/sleep-Dn3i9nxI.js";function u(e){let t=globalThis[o];return t||i(`createHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-hook`,u),t(e)}function d(e){let{respondWith:t,token:n,...r}=e??{};if(n!==void 0)throw Error("`createWebhook()` does not accept a `token` option. Webhook tokens are always randomly generated. Use `createHook()` with `resumeHook()` for deterministic token patterns.");let i;t!==void 0&&(i={respondWith:t});let o=u({...r,metadata:i,isWebhook:!0}),{url:s}=a();return o.url=`${s}/.well-known/workflow/v1/webhook/${encodeURIComponent(o.token)}`,o}function f(){function e(t,r){n(`defineHook().resume()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,e)}return{create(e){return u(e)},resume:e}}function p(e={}){let{namespace:t}=e,n=globalThis[s](t);return Object.create(globalThis.WritableStream.prototype,{[c]:{value:n,writable:!1}})}function m(){r(`getStepMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata`,m)}function h(){n(`resumeHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,h)}export{t as FatalError,e as RetryableError,u as createHook,d as createWebhook,f as defineHook,m as getStepMetadata,a as getWorkflowMetadata,p as getWritable,h as resumeHook,l as sleep};
@@ -0,0 +1,4 @@
1
+ // Auto-generated stub for `ms` types referenced by a vendored .d.ts.
2
+ // Emitted by scripts/vendor-compiled/@workflow/errors.mjs.
3
+
4
+ export type StringValue = string;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Error codes for classifying run failures.
3
+ * These are populated in the `errorCode` field of `run_failed` events
4
+ * and flow through to `StructuredError.code` on the run entity.
5
+ */
6
+ export declare const RUN_ERROR_CODES: {
7
+ /** Error thrown in user workflow or step code */
8
+ readonly USER_ERROR: "USER_ERROR";
9
+ /** Internal runtime error (corrupted event log, missing timestamps) */
10
+ readonly RUNTIME_ERROR: "RUNTIME_ERROR";
11
+ /** Run exceeded the maximum number of queue deliveries */
12
+ readonly MAX_DELIVERIES_EXCEEDED: "MAX_DELIVERIES_EXCEEDED";
13
+ /** Workflow replay exceeded the maximum allowed duration */
14
+ readonly REPLAY_TIMEOUT: "REPLAY_TIMEOUT";
15
+ };
16
+ export type RunErrorCode = (typeof RUN_ERROR_CODES)[keyof typeof RUN_ERROR_CODES];
17
+ //# sourceMappingURL=error-codes.d.ts.map
@@ -1,80 +1,462 @@
1
- export declare const ERROR_SLUGS: Record<string, string>;
1
+ import type { StringValue } from './_ms.js';
2
+ /**
3
+ * @internal
4
+ * All the slugs of the errors used for documentation links.
5
+ */
6
+ export declare const ERROR_SLUGS: {
7
+ readonly NODE_JS_MODULE_IN_WORKFLOW: "node-js-module-in-workflow";
8
+ readonly START_INVALID_WORKFLOW_FUNCTION: "start-invalid-workflow-function";
9
+ readonly SERIALIZATION_FAILED: "serialization-failed";
10
+ readonly WEBHOOK_INVALID_RESPOND_WITH_VALUE: "webhook-invalid-respond-with-value";
11
+ readonly WEBHOOK_RESPONSE_NOT_SENT: "webhook-response-not-sent";
12
+ readonly FETCH_IN_WORKFLOW_FUNCTION: "fetch-in-workflow";
13
+ readonly TIMEOUT_FUNCTIONS_IN_WORKFLOW: "timeout-in-workflow";
14
+ readonly HOOK_CONFLICT: "hook-conflict";
15
+ readonly CORRUPTED_EVENT_LOG: "corrupted-event-log";
16
+ readonly STEP_NOT_REGISTERED: "step-not-registered";
17
+ readonly WORKFLOW_NOT_REGISTERED: "workflow-not-registered";
18
+ };
19
+ type ErrorSlug = (typeof ERROR_SLUGS)[keyof typeof ERROR_SLUGS];
20
+ interface WorkflowErrorOptions extends ErrorOptions {
21
+ /**
22
+ * The slug of the error. This will be used to generate a link to the error documentation.
23
+ */
24
+ slug?: ErrorSlug;
25
+ }
26
+ /**
27
+ * The base class for all Workflow-related errors.
28
+ *
29
+ * This error is thrown by the Workflow SDK when internal operations fail.
30
+ * You can use this class with `instanceof` to catch any Workflow SDK error.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * try {
35
+ * await getRun(runId);
36
+ * } catch (error) {
37
+ * if (error instanceof WorkflowError) {
38
+ * console.error('Workflow SDK error:', error.message);
39
+ * }
40
+ * }
41
+ * ```
42
+ */
2
43
  export declare class WorkflowError extends Error {
3
- readonly cause?: unknown;
4
- constructor(message: string, options?: ErrorOptions & { slug?: string | undefined });
5
- static is(value: unknown): value is WorkflowError;
44
+ readonly cause?: unknown;
45
+ constructor(message: string, options?: WorkflowErrorOptions);
46
+ static is(value: unknown): value is WorkflowError;
6
47
  }
48
+ /**
49
+ * Thrown when a world (storage backend) operation fails unexpectedly.
50
+ *
51
+ * This is the catch-all error for world implementations. Specific,
52
+ * well-known failure modes have dedicated error types (e.g.
53
+ * EntityConflictError, RunExpiredError, ThrottleError). This error
54
+ * covers everything else — validation failures, missing entities
55
+ * without a dedicated type, or unexpected HTTP errors from world-vercel.
56
+ */
7
57
  export declare class WorkflowWorldError extends WorkflowError {
8
- status?: number;
9
- code?: string;
10
- url?: string;
11
- retryAfter?: number;
12
- constructor(
13
- message: string,
14
- options?: {
15
- status?: number | undefined;
16
- url?: string | undefined;
17
- code?: string | undefined;
18
- retryAfter?: number | undefined;
19
- cause?: unknown;
20
- },
21
- );
22
- static is(value: unknown): value is WorkflowWorldError;
58
+ status?: number;
59
+ code?: string;
60
+ url?: string;
61
+ /** Retry-After value in seconds, present on 429 and 425 responses */
62
+ retryAfter?: number;
63
+ constructor(message: string, options?: {
64
+ status?: number;
65
+ url?: string;
66
+ code?: string;
67
+ retryAfter?: number;
68
+ cause?: unknown;
69
+ });
70
+ static is(value: unknown): value is WorkflowWorldError;
23
71
  }
72
+ /**
73
+ * Thrown when a workflow run fails during execution.
74
+ *
75
+ * This error indicates that the workflow encountered a fatal error and cannot
76
+ * continue. It is thrown when awaiting `run.returnValue` on a run whose status
77
+ * is `'failed'`. The `cause` property contains the underlying error with its
78
+ * message, stack trace, and optional error code.
79
+ *
80
+ * Use the static `WorkflowRunFailedError.is()` method for type-safe checking
81
+ * in catch blocks.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * import { WorkflowRunFailedError } from "workflow/internal/errors";
86
+ *
87
+ * try {
88
+ * const result = await run.returnValue;
89
+ * } catch (error) {
90
+ * if (WorkflowRunFailedError.is(error)) {
91
+ * console.error(`Run ${error.runId} failed:`, error.cause.message);
92
+ * }
93
+ * }
94
+ * ```
95
+ */
24
96
  export declare class WorkflowRunFailedError extends WorkflowError {
25
- runId: string;
26
- cause: Error & { code?: string | undefined };
27
- constructor(runId: string, error: unknown);
28
- static is(value: unknown): value is WorkflowRunFailedError;
97
+ runId: string;
98
+ /**
99
+ * The high-level error category (e.g. USER_ERROR, RUNTIME_ERROR) for the
100
+ * failed run, from the run_failed event's `errorCode` field.
101
+ */
102
+ errorCode?: string;
103
+ /**
104
+ * The original thrown value from the failed workflow run, hydrated through
105
+ * the workflow serialization pipeline. Preserves the original type identity
106
+ * (Error subclasses, FatalError, custom classes with WORKFLOW_SERIALIZE, etc.)
107
+ * and custom properties (cause chains, etc.).
108
+ *
109
+ * Note: any JavaScript value can be thrown, so this is typed as `unknown`.
110
+ * Typical values are Error instances, but strings, objects, etc. are also
111
+ * possible.
112
+ */
113
+ cause: unknown;
114
+ constructor(runId: string, error: unknown, options?: {
115
+ errorCode?: string;
116
+ });
117
+ static is(value: unknown): value is WorkflowRunFailedError;
29
118
  }
119
+ /**
120
+ * Thrown when attempting to get results from an incomplete workflow run.
121
+ *
122
+ * This error occurs when you try to access the result of a workflow
123
+ * that is still running or hasn't completed yet.
124
+ */
30
125
  export declare class WorkflowRunNotCompletedError extends WorkflowError {
31
- runId: string;
32
- status: string;
33
- constructor(runId: string, status: string);
34
- static is(value: unknown): value is WorkflowRunNotCompletedError;
126
+ runId: string;
127
+ status: string;
128
+ constructor(runId: string, status: string);
129
+ static is(value: unknown): value is WorkflowRunNotCompletedError;
130
+ }
131
+ /**
132
+ * Thrown when the Workflow runtime encounters an internal error.
133
+ *
134
+ * This error indicates an issue with workflow execution, such as
135
+ * serialization failures, starting an invalid workflow function, or
136
+ * other runtime problems.
137
+ */
138
+ export declare class WorkflowRuntimeError extends WorkflowError {
139
+ constructor(message: string, options?: WorkflowErrorOptions);
140
+ static is(value: unknown): value is WorkflowRuntimeError;
141
+ }
142
+ interface WorkflowBuildErrorOptions extends ErrorOptions {
143
+ /**
144
+ * An optional actionable hint appended to the main message, explaining how
145
+ * the user can resolve the failure. Shown after a blank line.
146
+ */
147
+ hint?: string;
148
+ }
149
+ /**
150
+ * Thrown when the workflow build pipeline (esbuild, SWC transform, file
151
+ * discovery, bundler integration) fails in a way the user can act on.
152
+ *
153
+ * This is distinct from `WorkflowRuntimeError` (which is raised at runtime
154
+ * by the workflow engine) — `WorkflowBuildError` fires during `pnpm build`,
155
+ * `next build`, or equivalent, before any workflow has started executing.
156
+ *
157
+ * Prefer attaching a short, actionable `hint` (e.g. `run \`pnpm install workflow\``)
158
+ * as plain text — the rendering layer is responsible for any styling or
159
+ * "hint:" label. Keeping `hint` plain keeps it useful in non-TTY contexts
160
+ * (CI logs, structured error serialization) where ANSI escapes are noise.
161
+ */
162
+ export declare class WorkflowBuildError extends WorkflowError {
163
+ readonly hint?: string;
164
+ constructor(message: string, options?: WorkflowBuildErrorOptions);
165
+ static is(value: unknown): value is WorkflowBuildError;
166
+ }
167
+ interface SerializationErrorOptions extends ErrorOptions {
168
+ /**
169
+ * An optional actionable hint appended to the main message, explaining how
170
+ * the user can resolve the failure (e.g. "register the class with…" or
171
+ * "move this call inside a step").
172
+ */
173
+ hint?: string;
174
+ }
175
+ /**
176
+ * Thrown when a value cannot be serialized into or deserialized out of the
177
+ * workflow event log.
178
+ *
179
+ * This usually indicates a user-facing mistake: passing a non-serializable
180
+ * value (class without `WORKFLOW_SERIALIZE`, locked stream, direct workflow
181
+ * function reference) into a step boundary, or an unregistered class
182
+ * returning from a step.
183
+ *
184
+ * Internal invariants (corrupted buffers, unknown format bytes) should use
185
+ * `WorkflowRuntimeError` instead — this class is scoped to things the user
186
+ * can fix in their own code.
187
+ */
188
+ export declare class SerializationError extends WorkflowError {
189
+ readonly hint?: string;
190
+ /**
191
+ * Serialization errors are deterministic — if a step returns a non-POJO,
192
+ * replaying the step will always produce the same non-serializable value.
193
+ * Retrying is guaranteed to fail, so these errors are surfaced as fatal
194
+ * and skip the step-retry loop. `FatalError.is()` recognizes any error
195
+ * with `fatal: true` (see `packages/errors/src/index.ts`), so no other
196
+ * wiring is required for user-thrown SerializationErrors.
197
+ */
198
+ readonly fatal = true;
199
+ constructor(message: string, options?: SerializationErrorOptions);
200
+ static is(value: unknown): value is SerializationError;
35
201
  }
36
- export declare class WorkflowRuntimeError extends WorkflowError {}
202
+ /**
203
+ * Thrown when a step function is not registered in the current deployment.
204
+ *
205
+ * This is an infrastructure error — not a user code error. It typically means
206
+ * something went wrong with the bundling/build tooling that caused the step
207
+ * to not get built correctly.
208
+ *
209
+ * When this happens, the step fails (like a FatalError) and control is passed back
210
+ * to the workflow function, which can optionally handle the failure gracefully.
211
+ */
37
212
  export declare class StepNotRegisteredError extends WorkflowRuntimeError {
38
- stepName: string;
39
- constructor(stepName: string);
40
- static is(value: unknown): value is StepNotRegisteredError;
213
+ stepName: string;
214
+ constructor(stepName: string);
215
+ static is(value: unknown): value is StepNotRegisteredError;
41
216
  }
217
+ /**
218
+ * Thrown when a workflow function is not registered in the current deployment.
219
+ *
220
+ * This is an infrastructure error — not a user code error. It typically means:
221
+ * - A run was started against a deployment that does not have the workflow
222
+ * (e.g., the workflow was renamed or moved and a new run targeted the latest deployment)
223
+ * - Something went wrong with the bundling/build tooling that caused the workflow
224
+ * to not get built correctly
225
+ *
226
+ * When this happens, the run fails with a `RUNTIME_ERROR` error code.
227
+ */
42
228
  export declare class WorkflowNotRegisteredError extends WorkflowRuntimeError {
43
- workflowName: string;
44
- constructor(workflowName: string);
45
- static is(value: unknown): value is WorkflowNotRegisteredError;
229
+ workflowName: string;
230
+ constructor(workflowName: string);
231
+ static is(value: unknown): value is WorkflowNotRegisteredError;
46
232
  }
233
+ /**
234
+ * Thrown when performing operations on a workflow run that does not exist.
235
+ *
236
+ * This error occurs when you call methods on a run object (e.g. `run.status`,
237
+ * `run.cancel()`, `run.returnValue`) but the underlying run ID does not match
238
+ * any known workflow run. Note that `getRun(id)` itself is synchronous and will
239
+ * not throw — this error is raised when subsequent operations discover the run
240
+ * is missing.
241
+ *
242
+ * Use the static `WorkflowRunNotFoundError.is()` method for type-safe checking
243
+ * in catch blocks.
244
+ *
245
+ * @example
246
+ * ```ts
247
+ * import { WorkflowRunNotFoundError } from "workflow/internal/errors";
248
+ *
249
+ * try {
250
+ * const status = await run.status;
251
+ * } catch (error) {
252
+ * if (WorkflowRunNotFoundError.is(error)) {
253
+ * console.error(`Run ${error.runId} does not exist`);
254
+ * }
255
+ * }
256
+ * ```
257
+ */
47
258
  export declare class WorkflowRunNotFoundError extends WorkflowError {
48
- runId: string;
49
- constructor(runId: string);
50
- static is(value: unknown): value is WorkflowRunNotFoundError;
259
+ runId: string;
260
+ constructor(runId: string);
261
+ static is(value: unknown): value is WorkflowRunNotFoundError;
51
262
  }
263
+ /**
264
+ * Thrown when a hook token is already in use by another active workflow run.
265
+ *
266
+ * This is a user error — it means the same custom token was passed to
267
+ * `createHook` in two or more concurrent runs. Use a unique token per run
268
+ * (or omit the token to let the runtime generate one automatically).
269
+ */
52
270
  export declare class HookConflictError extends WorkflowError {
53
- token: string;
54
- constructor(token: string);
55
- static is(value: unknown): value is HookConflictError;
271
+ token: string;
272
+ constructor(token: string);
273
+ static is(value: unknown): value is HookConflictError;
56
274
  }
275
+ /**
276
+ * Thrown when calling `resumeHook()` or `resumeWebhook()` with a token that
277
+ * does not match any active hook.
278
+ *
279
+ * Common causes:
280
+ * - The hook has expired (past its TTL)
281
+ * - The hook was already disposed after being consumed
282
+ * - The workflow has not started yet, so the hook does not exist
283
+ *
284
+ * A common pattern is to catch this error and start a new workflow run when
285
+ * the hook does not exist yet (the "resume or start" pattern).
286
+ *
287
+ * Use the static `HookNotFoundError.is()` method for type-safe checking in
288
+ * catch blocks.
289
+ *
290
+ * @example
291
+ * ```ts
292
+ * import { HookNotFoundError } from "workflow/internal/errors";
293
+ *
294
+ * try {
295
+ * await resumeHook(token, payload);
296
+ * } catch (error) {
297
+ * if (HookNotFoundError.is(error)) {
298
+ * // Hook doesn't exist — start a new workflow run instead
299
+ * await startWorkflow("myWorkflow", payload);
300
+ * }
301
+ * }
302
+ * ```
303
+ */
57
304
  export declare class HookNotFoundError extends WorkflowError {
58
- token: string;
59
- constructor(token: string);
60
- static is(value: unknown): value is HookNotFoundError;
305
+ token: string;
306
+ constructor(token: string);
307
+ static is(value: unknown): value is HookNotFoundError;
61
308
  }
62
- export declare class EntityConflictError extends WorkflowWorldError {}
63
- export declare class RunExpiredError extends WorkflowWorldError {}
309
+ /**
310
+ * Thrown when an operation conflicts with the current state of an entity.
311
+ * This includes attempts to modify an entity already in a terminal state,
312
+ * create an entity that already exists, or any other 409-style conflict.
313
+ *
314
+ * The workflow runtime handles this error automatically. Users interacting
315
+ * with world storage backends directly may encounter it.
316
+ */
317
+ export declare class EntityConflictError extends WorkflowWorldError {
318
+ constructor(message: string);
319
+ static is(value: unknown): value is EntityConflictError;
320
+ }
321
+ /**
322
+ * Thrown when a run is no longer available — either because it has been
323
+ * cleaned up, expired, or already reached a terminal state (completed/failed).
324
+ *
325
+ * The workflow runtime handles this error automatically. Users interacting
326
+ * with world storage backends directly may encounter it.
327
+ */
328
+ export declare class RunExpiredError extends WorkflowWorldError {
329
+ constructor(message: string);
330
+ static is(value: unknown): value is RunExpiredError;
331
+ }
332
+ /**
333
+ * Thrown when an operation cannot proceed because a required timestamp
334
+ * (e.g. retryAfter) has not been reached yet.
335
+ *
336
+ * The workflow runtime handles this error automatically. Users interacting
337
+ * with world storage backends directly may encounter it.
338
+ *
339
+ * @property retryAfter - Delay in seconds before the operation can be retried.
340
+ */
64
341
  export declare class TooEarlyError extends WorkflowWorldError {
65
- constructor(message: string, options?: { retryAfter?: number | undefined });
66
- static is(value: unknown): value is TooEarlyError;
342
+ constructor(message: string, options?: {
343
+ retryAfter?: number;
344
+ });
345
+ static is(value: unknown): value is TooEarlyError;
67
346
  }
347
+ /**
348
+ * Thrown when a request is rate limited by the workflow backend.
349
+ *
350
+ * The workflow runtime handles this error automatically with retry logic.
351
+ * Users interacting with world storage backends directly may encounter it
352
+ * if retries are exhausted.
353
+ *
354
+ * @property retryAfter - Delay in seconds before the request can be retried.
355
+ */
68
356
  export declare class ThrottleError extends WorkflowWorldError {
69
- retryAfter?: number;
70
- constructor(message: string, options?: { retryAfter?: number | undefined });
71
- static is(value: unknown): value is ThrottleError;
357
+ retryAfter?: number;
358
+ constructor(message: string, options?: {
359
+ retryAfter?: number;
360
+ });
361
+ static is(value: unknown): value is ThrottleError;
72
362
  }
363
+ /**
364
+ * Thrown when awaiting `run.returnValue` on a workflow run that was cancelled.
365
+ *
366
+ * This error indicates that the workflow was explicitly cancelled (via
367
+ * `run.cancel()`) and will not produce a return value. You can check for
368
+ * cancellation before awaiting the return value by inspecting `run.status`.
369
+ *
370
+ * Use the static `WorkflowRunCancelledError.is()` method for type-safe
371
+ * checking in catch blocks.
372
+ *
373
+ * @example
374
+ * ```ts
375
+ * import { WorkflowRunCancelledError } from "workflow/internal/errors";
376
+ *
377
+ * try {
378
+ * const result = await run.returnValue;
379
+ * } catch (error) {
380
+ * if (WorkflowRunCancelledError.is(error)) {
381
+ * console.log(`Run ${error.runId} was cancelled`);
382
+ * }
383
+ * }
384
+ * ```
385
+ */
73
386
  export declare class WorkflowRunCancelledError extends WorkflowError {
74
- runId: string;
75
- constructor(runId: string);
76
- static is(value: unknown): value is WorkflowRunCancelledError;
387
+ runId: string;
388
+ constructor(runId: string);
389
+ static is(value: unknown): value is WorkflowRunCancelledError;
390
+ }
391
+ /**
392
+ * Thrown when attempting to operate on a workflow run that requires a newer World version.
393
+ *
394
+ * This error occurs when a run was created with a newer spec version than the
395
+ * current World implementation supports. To resolve this, upgrade your
396
+ * `workflow` packages to a version that supports the required spec version.
397
+ *
398
+ * Use the static `RunNotSupportedError.is()` method for type-safe checking in
399
+ * catch blocks.
400
+ *
401
+ * @example
402
+ * ```ts
403
+ * import { RunNotSupportedError } from "workflow/internal/errors";
404
+ *
405
+ * try {
406
+ * const status = await run.status;
407
+ * } catch (error) {
408
+ * if (RunNotSupportedError.is(error)) {
409
+ * console.error(
410
+ * `Run requires spec v${error.runSpecVersion}, ` +
411
+ * `but world supports v${error.worldSpecVersion}`
412
+ * );
413
+ * }
414
+ * }
415
+ * ```
416
+ */
417
+ export declare class RunNotSupportedError extends WorkflowError {
418
+ readonly runSpecVersion: number;
419
+ readonly worldSpecVersion: number;
420
+ constructor(runSpecVersion: number, worldSpecVersion: number);
421
+ static is(value: unknown): value is RunNotSupportedError;
422
+ }
423
+ /**
424
+ * A fatal error is an error that cannot be retried.
425
+ * It will cause the step to fail and the error will
426
+ * be bubbled up to the workflow logic.
427
+ *
428
+ * Any error can opt into the non-retry behavior by setting a `fatal: true`
429
+ * own property. This is how structured error classes that aren't direct
430
+ * `FatalError` subclasses (e.g. context-violation errors) signal to the
431
+ * step handler that retrying will never help — the user's code is calling
432
+ * a workflow-only API from the wrong context, or similar — and burning
433
+ * retry attempts just produces a wall of duplicated log output.
434
+ */
435
+ export declare class FatalError extends Error {
436
+ fatal: boolean;
437
+ constructor(message: string);
438
+ static is(value: unknown): value is FatalError;
439
+ }
440
+ export interface RetryableErrorOptions {
441
+ /**
442
+ * The number of milliseconds to wait before retrying the step.
443
+ * Can also be a duration string (e.g., "5s", "2m") or a Date object.
444
+ * If not provided, the step will be retried after 1 second (1000 milliseconds).
445
+ */
446
+ retryAfter?: number | StringValue | Date;
447
+ }
448
+ /**
449
+ * An error that can happen during a step execution, allowing
450
+ * for configuration of the retry behavior.
451
+ */
452
+ export declare class RetryableError extends Error {
453
+ /**
454
+ * The Date when the step should be retried.
455
+ */
456
+ retryAfter: Date;
457
+ constructor(message: string, options?: RetryableErrorOptions);
458
+ static is(value: unknown): value is RetryableError;
77
459
  }
78
- export declare class RunNotSupportedError extends WorkflowWorldError {}
79
- export declare class FatalError extends WorkflowError {}
80
- export declare class RetryableError extends WorkflowError {}
460
+ export declare const VERCEL_403_ERROR_MESSAGE = "Your current vercel account does not have access to this resource. Use `vercel login` or `vercel switch` to ensure you are linked to the right account.";
461
+ export { RUN_ERROR_CODES, type RunErrorCode } from './error-codes.js';
462
+ //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- import{C as e,S as t,_ as n,a as r,b as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,u as y,v as b,x,y as S}from"../../_chunks/workflow/dist-C9DdsXoK.js";export{v as ERROR_SLUGS,p as EntityConflictError,g as FatalError,u as HookConflictError,r as HookNotFoundError,e as RUN_ERROR_CODES,m as RetryableError,_ as RunExpiredError,a as RunNotSupportedError,d as SerializationError,y as StepNotRegisteredError,o as ThrottleError,s as TooEarlyError,h as VERCEL_403_ERROR_MESSAGE,f as WorkflowBuildError,l as WorkflowError,c as WorkflowNotRegisteredError,n as WorkflowRunCancelledError,b as WorkflowRunFailedError,S as WorkflowRunNotCompletedError,i as WorkflowRunNotFoundError,x as WorkflowRuntimeError,t as WorkflowWorldError};
1
+ import{C as e,S as t,_ as n,a as r,b as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,u as y,v as b,x,y as S}from"../../_chunks/workflow/dist-0iNBqPYp.js";export{v as ERROR_SLUGS,p as EntityConflictError,g as FatalError,u as HookConflictError,r as HookNotFoundError,e as RUN_ERROR_CODES,m as RetryableError,_ as RunExpiredError,a as RunNotSupportedError,d as SerializationError,y as StepNotRegisteredError,o as ThrottleError,s as TooEarlyError,h as VERCEL_403_ERROR_MESSAGE,f as WorkflowBuildError,l as WorkflowError,c as WorkflowNotRegisteredError,n as WorkflowRunCancelledError,b as WorkflowRunFailedError,S as WorkflowRunNotCompletedError,i as WorkflowRunNotFoundError,x as WorkflowRuntimeError,t as WorkflowWorldError};
@@ -1,2 +1,2 @@
1
- import{i as e,o as t,t as n}from"./chunk-Dd2tEFlW.js";import{n as r,t as i}from"./version-BMyZn3Y2.js";import*as a from"node:path";import o from"node:path";import{setTimeout as s}from"node:timers/promises";import*as c from"node:fs/promises";import l from"os";import{homedir as u}from"node:os";import d from"node:fs";const f=r.string().transform((e,t)=>{try{return JSON.parse(e)}catch(e){return t.addIssue({code:r.ZodIssueCode.custom,message:`Invalid JSON: ${e.message}`}),r.NEVER}});var p=n(((t,n)=>{let r=e(`os`),i=e(`path`),a=/^win/i.test(process.platform);function o(e){return i.normalize(i.join(e,`.`))}let s=()=>{let{env:e}=process,t={};return t.home=()=>o(r.homedir?r.homedir():e.HOME),t.temp=()=>o(r.tmpdir?r.tmpdir():e.TMPDIR||e.TEMP||e.TMP),t},c=()=>{let{env:e}=process,t={};return t.home=()=>o(r.homedir?r.homedir():e.USERPROFILE||i.join(e.HOMEDRIVE,e.HOMEPATH)||e.HOME),t.temp=()=>o(r.tmpdir?r.tmpdir():e.TEMP||e.TMP||i.join(e.LOCALAPPDATA||e.SystemRoot||e.windir,`Temp`)),t};n.exports=new class e{constructor(){let t=function(){return new e};this._fn=t;let n=a?c():s();return Object.keys(n).forEach(e=>{this._fn[e]=n[e]}),this._fn}}})),m=n(((t,n)=>{let r=e(`path`),i=p(),a=()=>{let e={};return e.cache=()=>process.env.XDG_CACHE_HOME||r.join(i.home()||i.temp(),`.cache`),e.config=()=>process.env.XDG_CONFIG_HOME||r.join(i.home()||i.temp(),`.config`),e.data=()=>process.env.XDG_DATA_HOME||r.join(i.home()||i.temp(),`.local`,`share`),e.runtime=()=>process.env.XDG_RUNTIME_DIR||void 0,e.state=()=>process.env.XDG_STATE_HOME||r.join(i.home()||i.temp(),`.local`,`state`),e},o=()=>{let e={};return e.cache=()=>process.env.XDG_CACHE_HOME||r.join(r.join(i.home()||i.temp(),`Library`),`Caches`),e.config=()=>process.env.XDG_CONFIG_HOME||r.join(r.join(i.home()||i.temp(),`Library`),`Preferences`),e.data=()=>process.env.XDG_DATA_HOME||r.join(r.join(i.home()||i.temp(),`Library`),`Application Support`),e.runtime=()=>process.env.XDG_RUNTIME_DIR||void 0,e.state=()=>process.env.XDG_STATE_HOME||r.join(r.join(i.home()||i.temp(),`Library`),`State`),e},s=()=>{let e={};return e.cache=()=>{let e=process.env.LOCALAPPDATA||r.join(i.home()||i.temp(),`AppData`,`Local`);return process.env.XDG_CACHE_HOME||r.join(e,`xdg.cache`)},e.config=()=>{let e=process.env.APPDATA||r.join(i.home()||i.temp(),`AppData`,`Roaming`);return process.env.XDG_CONFIG_HOME||r.join(e,`xdg.config`)},e.data=()=>{let e=process.env.APPDATA||r.join(i.home()||i.temp(),`AppData`,`Roaming`);return process.env.XDG_DATA_HOME||r.join(e,`xdg.data`)},e.runtime=()=>process.env.XDG_RUNTIME_DIR||void 0,e.state=()=>{let e=process.env.LOCALAPPDATA||r.join(i.home()||i.temp(),`AppData`,`Local`);return process.env.XDG_STATE_HOME||r.join(e,`xdg.state`)},e},c=()=>{let e=function(){return c()},t={};return t=/^darwin$/i.test(process.platform)?o():/^win/i.test(process.platform)?s():a(),t.configDirs=()=>{let e=[];return e.push(t.config()),process.env.XDG_CONFIG_DIRS&&e.push(...process.env.XDG_CONFIG_DIRS.split(r.delimiter)),e},t.dataDirs=()=>{let e=[];return e.push(t.data()),process.env.XDG_DATA_DIRS&&e.push(...process.env.XDG_DATA_DIRS.split(r.delimiter)),e},Object.keys(t).forEach(n=>{e[n]=t[n]}),e};n.exports=c()})),h=t(n(((t,n)=>{let r=e(`path`),i=e(`os`),a=m(),o=/^win/i.test(process.platform);function s(e,t){if(e||={},typeof e!=`object`&&(e={isolated:e}),e.isolated=e.isolated===void 0||e.isolated===null?t:e.isolated,typeof e.isolated!=`boolean`)throw TypeError(`Expected boolean for "isolated" argument, got ${typeof e.isolated}`);return e}let c=(e,t)=>{let n={};return n.cache=(n={isolated:null})=>(n=s(n,t),r.join(a.cache(),n.isolated?e:``)),n.config=(n={isolated:null})=>(n=s(n,t),r.join(a.config(),n.isolated?e:``)),n.data=(n={isolated:null})=>(n=s(n,t),r.join(a.data(),n.isolated?e:``)),n.runtime=(n={isolated:null})=>(n=s(n,t),a.runtime()?r.join(a.runtime(),n.isolated?e:``):void 0),n.state=(n={isolated:null})=>(n=s(n,t),r.join(a.state(),n.isolated?e:``)),n.configDirs=(n={isolated:null})=>(n=s(n,t),a.configDirs().map(t=>r.join(t,n.isolated?e:``))),n.dataDirs=(n={isolated:null})=>(n=s(n,t),a.dataDirs().map(t=>r.join(t,n.isolated?e:``))),n},l=(e,t)=>{let{env:n}=process,o=i.homedir(),c=i.tmpdir(),l=n.APPDATA||r.join(o||c,`AppData`,`Roaming`),u=n.LOCALAPPDATA||r.join(o||c,`AppData`,`Local`),d={};return d.cache=(i={isolated:null})=>(i=s(i,t),!i.isolated||n.XDG_CACHE_HOME?r.join(a.cache(),i.isolated?e:``):r.join(u,i.isolated?e:``,`Cache`)),d.config=(i={isolated:null})=>(i=s(i,t),!i.isolated||n.XDG_CONFIG_HOME?r.join(a.config(),i.isolated?e:``):r.join(l,i.isolated?e:``,`Config`)),d.data=(i={isolated:null})=>(i=s(i,t),!i.isolated||n.XDG_DATA_HOME?r.join(a.data(),i.isolated?e:``):r.join(l,i.isolated?e:``,`Data`)),d.runtime=(n={isolated:null})=>(n=s(n,t),a.runtime()?r.join(a.runtime(),n.isolated?e:``):void 0),d.state=(i={isolated:null})=>(i=s(i,t),!i.isolated||n.XDG_STATE_HOME?r.join(a.state(),i.isolated?e:``):r.join(u,i.isolated?e:``,`State`)),d.configDirs=(i={isolated:null})=>{i=s(i,t);let a=[d.config(i)];return n.XDG_CONFIG_DIRS&&a.push(...n.XDG_CONFIG_DIRS.split(r.delimiter).map(t=>r.join(t,i.isolated?e:``))),a},d.dataDirs=(i={isolated:null})=>{i=s(i,t);let a=[d.data(i)];return n.XDG_DATA_DIRS&&a.push(...n.XDG_DATA_DIRS.split(r.delimiter).map(t=>r.join(t,i.isolated?e:``))),a},d};n.exports=new class t{constructor(n={name:null,suffix:null,isolated:!0}){let i=function(e={name:null,suffix:null,isolated:!0}){return new t(e)};this._fn=i,n||={},typeof n!=`object`&&(n={name:n});let a=n.name||``;if(typeof a!=`string`)throw TypeError(`Expected string for "name" argument, got ${typeof a}`);let s=n.suffix||``;if(typeof s!=`string`)throw TypeError(`Expected string for "suffix" argument, got ${typeof s}`);let u=n.isolated===void 0||n.isolated===null?!0:n.isolated;if(typeof u!=`boolean`)throw TypeError(`Expected boolean for "isolated" argument, got ${typeof u}`);a||=r.parse(process.pkg?process.execPath:e.main?e.main.filename:process.argv[0]).name,s&&(a+=s),this._fn.$name=()=>a,this._fn.$isolated=()=>u;let d=o?l(a,u):c(a,u);return Object.keys(d).forEach(e=>{this._fn[e]=d[e]}),this._fn}}}))(),1);const g=r.number().transform(e=>new Date(e*1e3)),_=r.object({token:r.string().min(1).optional(),refreshToken:r.string().min(1).optional(),expiresAt:g.optional()}),v=f.pipe(_),y=e=>{try{return d.lstatSync(e).isDirectory()}catch{return!1}},b=()=>{if(process.env.VERCEL_AUTH_CONFIG_DIR)return process.env.VERCEL_AUTH_CONFIG_DIR;let e=(0,h.default)(`com.vercel.cli`).dataDirs();return[...e,o.join(u(),`.now`),...(0,h.default)(`now`).dataDirs()].find(e=>y(e))||e[0]},x=()=>{try{let e=o.join(b(),`auth.json`);return v.parse(d.readFileSync(e,`utf8`))}catch{return null}};function S(e){let t=o.join(b(),`auth.json`);d.mkdirSync(o.dirname(t),{recursive:!0});let n={token:e.token,expiresAt:e.expiresAt&&Math.round(e.expiresAt.getTime()/1e3),refreshToken:e.refreshToken};d.writeFileSync(t,JSON.stringify(n)+`
2
- `)}const C=`${l.hostname()} @ vercel/sandbox/${i} node-${process.version} ${l.platform()} (${l.arch()})`,w=new URL(`https://vercel.com`),T=`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,E=r.object({issuer:r.string().url(),device_authorization_endpoint:r.string().url(),token_endpoint:r.string().url(),revocation_endpoint:r.string().url(),jwks_uri:r.string().url(),introspection_endpoint:r.string().url()});let D;const O=r.object({device_code:r.string(),user_code:r.string(),verification_uri:r.string().url(),verification_uri_complete:r.string().url(),expires_in:r.number(),interval:r.number()}),k=r.object({active:r.literal(!0),client_id:r.string(),session_id:r.string()}).or(r.object({active:r.literal(!1)}));async function A(){if(D)return D;let e=await fetch(new URL(`.well-known/openid-configuration`,w),{headers:{"Content-Type":`application/json`,"user-agent":C}});return D=E.parse(await e.json()),D}async function j(){let e=await A();return{async deviceAuthorizationRequest(){let t=await(await fetch(e.device_authorization_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({client_id:T,scope:`openid offline_access`})})).json(),n=O.safeParse(t);if(!n.success)throw new F(`Failed to parse device authorization response: ${n.error.message}`,t);return{device_code:n.data.device_code,user_code:n.data.user_code,verification_uri:n.data.verification_uri,verification_uri_complete:n.data.verification_uri_complete,expiresAt:Date.now()+n.data.expires_in*1e3,interval:n.data.interval}},async deviceAccessTokenRequest(t){try{return[null,await fetch(e.token_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({client_id:T,grant_type:`urn:ietf:params:oauth:grant-type:device_code`,device_code:t}),signal:AbortSignal.timeout(10*1e3)})]}catch(e){return e instanceof Error?[e]:[Error(`An unknown error occurred. See the logs for details.`,{cause:e})]}},async processTokenResponse(e){let t=await e.json(),n=M.safeParse(t);return n.success?[null,n.data]:[new F(`Failed to parse token response: ${n.error.message}`,t)]},async revokeToken(t){let n=await fetch(e.revocation_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({token:t,client_id:T})});if(!n.ok)return new F(`Revocation request failed`,await n.json())},async refreshToken(t){let n=await fetch(e.token_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({client_id:T,grant_type:`refresh_token`,refresh_token:t})}),[r,i]=await this.processTokenResponse(n);if(r)throw r;return i},async introspectToken(t){let n=await(await fetch(e.introspection_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({token:t})})).json(),r=k.safeParse(n);if(!r.success)throw new F(`Failed to parse introspection response: ${r.error.message}`,n);return r.data}}}const M=r.object({access_token:r.string(),token_type:r.literal(`Bearer`),expires_in:r.number(),refresh_token:r.string().optional(),scope:r.string().optional()}),N=r.object({error:r.enum([`invalid_request`,`invalid_client`,`invalid_grant`,`unauthorized_client`,`unsupported_grant_type`,`invalid_scope`,`server_error`,`authorization_pending`,`slow_down`,`access_denied`,`expired_token`,`unsupported_token_type`]),error_description:r.string().optional(),error_uri:r.string().optional()});function P(e){try{return N.parse(e)}catch(e){return e instanceof r.ZodError?TypeError(`Invalid OAuth error response: ${e.message}`):TypeError(`Failed to parse OAuth error response`)}}var F=class extends Error{constructor(e,t){super(e),this.name=`OAuthError`;let n=P(t);if(n instanceof TypeError){let e=`Unexpected server response: ${JSON.stringify(t)}`;this.cause=Error(e,{cause:n}),this.code=`server_error`;return}let r=n.error;n.error_description&&(r+=`: ${n.error_description}`),n.error_uri&&(r+=` (${n.error_uri})`),this.cause=Error(r),this.code=n.error}};function I(e){return e instanceof F}async function*L({request:e,oauth:t}){let n=new AbortController;try{let r=e.interval*1e3;for(;Date.now()<e.expiresAt;){let[i,a]=await t.deviceAccessTokenRequest(e.device_code);if(i){if(i.message.includes(`timeout`)){r*=2,yield{_tag:`Timeout`,newInterval:r},await s(r,{signal:n.signal});continue}yield{_tag:`Error`,error:i};return}yield{_tag:`Response`,response:a.clone()};let[o,c]=await t.processTokenResponse(a);if(I(o)){let{code:e}=o;switch(e){case`authorization_pending`:await s(r,{signal:n.signal});continue;case`slow_down`:r+=5*1e3,yield{_tag:`SlowDown`,newInterval:r},await s(r,{signal:n.signal});continue;default:yield{_tag:`Error`,error:o.cause};return}}if(o){yield{_tag:`Error`,error:o};return}S({token:c.access_token,expiresAt:new Date(Date.now()+c.expires_in*1e3),refreshToken:c.refresh_token});return}yield{_tag:`Error`,error:Error(`Timed out waiting for authentication. Please try again.`)};return}finally{n.abort()}}var R=class extends Error{constructor(e){super(`HTTP ${e.statusCode}: ${e.responseText}`),this.name=`NotOk`,this.response=e}};async function z(e){let t=await fetch(`https://api.vercel.com${e.endpoint}`,{method:e.method,body:e.body,headers:{Authorization:`Bearer ${e.token}`,"Content-Type":`application/json`}});if(!t.ok){let e=await t.text();try{let{error:t}=JSON.parse(e);e=`${t.code.toUpperCase()}: ${t.message}`}catch{}throw new R({responseText:e,statusCode:t.status})}return await t.json()}const B=f.pipe(r.object({projectId:r.string(),orgId:r.string()}));async function V(e){let t=a.join(e,`.vercel`,`project.json`),n;try{n=await c.readFile(t,`utf-8`)}catch{return null}let r=B.safeParse(n);return r.success?{projectId:r.data.projectId,teamId:r.data.orgId}:null}const H=r.object({teams:r.array(r.object({slug:r.string()})).min(1,`No teams found. Please create a team first.`)}),U=`vercel-sandbox-default-project`;async function W(e){let t=await V(e.cwd??process.cwd());if(t)return{...t,created:!1};let n=e.teamId??await G(e.token),r=!1;try{await z({token:e.token,endpoint:`/v2/projects/vercel-sandbox-default-project?slug=${encodeURIComponent(n)}`})}catch(t){if(!(t instanceof R)||t.response.statusCode!==404)throw t;await z({token:e.token,endpoint:`/v11/projects?slug=${encodeURIComponent(n)}`,method:`POST`,body:JSON.stringify({name:U})}),r=!0}return{projectId:U,teamId:n,created:r}}async function G(e){let{teams:[t]}=await z({token:e,endpoint:`/v2/teams?limit=1`}).then(H.parse);return t.slug}export{j as OAuth,x as getAuth,W as inferScope,I as isOAuthError,L as pollForToken,G as selectTeam,S as updateAuthConfig};
1
+ import{i as e,o as t,t as n}from"./chunk-Dd2tEFlW.js";import{n as r,t as i}from"./version-BMyZn3Y2.js";import*as a from"node:path";import o from"node:path";import{homedir as s}from"node:os";import c from"os";import l from"node:fs";import{setTimeout as u}from"node:timers/promises";import*as d from"node:fs/promises";const f=r.string().transform((e,t)=>{try{return JSON.parse(e)}catch(e){return t.addIssue({code:r.ZodIssueCode.custom,message:`Invalid JSON: ${e.message}`}),r.NEVER}});var p=n(((t,n)=>{let r=e(`os`),i=e(`path`),a=/^win/i.test(process.platform);function o(e){return i.normalize(i.join(e,`.`))}let s=()=>{let{env:e}=process,t={};return t.home=()=>o(r.homedir?r.homedir():e.HOME),t.temp=()=>o(r.tmpdir?r.tmpdir():e.TMPDIR||e.TEMP||e.TMP),t},c=()=>{let{env:e}=process,t={};return t.home=()=>o(r.homedir?r.homedir():e.USERPROFILE||i.join(e.HOMEDRIVE,e.HOMEPATH)||e.HOME),t.temp=()=>o(r.tmpdir?r.tmpdir():e.TEMP||e.TMP||i.join(e.LOCALAPPDATA||e.SystemRoot||e.windir,`Temp`)),t};n.exports=new class e{constructor(){let t=function(){return new e};this._fn=t;let n=a?c():s();return Object.keys(n).forEach(e=>{this._fn[e]=n[e]}),this._fn}}})),m=n(((t,n)=>{let r=e(`path`),i=p(),a=()=>{let e={};return e.cache=()=>process.env.XDG_CACHE_HOME||r.join(i.home()||i.temp(),`.cache`),e.config=()=>process.env.XDG_CONFIG_HOME||r.join(i.home()||i.temp(),`.config`),e.data=()=>process.env.XDG_DATA_HOME||r.join(i.home()||i.temp(),`.local`,`share`),e.runtime=()=>process.env.XDG_RUNTIME_DIR||void 0,e.state=()=>process.env.XDG_STATE_HOME||r.join(i.home()||i.temp(),`.local`,`state`),e},o=()=>{let e={};return e.cache=()=>process.env.XDG_CACHE_HOME||r.join(r.join(i.home()||i.temp(),`Library`),`Caches`),e.config=()=>process.env.XDG_CONFIG_HOME||r.join(r.join(i.home()||i.temp(),`Library`),`Preferences`),e.data=()=>process.env.XDG_DATA_HOME||r.join(r.join(i.home()||i.temp(),`Library`),`Application Support`),e.runtime=()=>process.env.XDG_RUNTIME_DIR||void 0,e.state=()=>process.env.XDG_STATE_HOME||r.join(r.join(i.home()||i.temp(),`Library`),`State`),e},s=()=>{let e={};return e.cache=()=>{let e=process.env.LOCALAPPDATA||r.join(i.home()||i.temp(),`AppData`,`Local`);return process.env.XDG_CACHE_HOME||r.join(e,`xdg.cache`)},e.config=()=>{let e=process.env.APPDATA||r.join(i.home()||i.temp(),`AppData`,`Roaming`);return process.env.XDG_CONFIG_HOME||r.join(e,`xdg.config`)},e.data=()=>{let e=process.env.APPDATA||r.join(i.home()||i.temp(),`AppData`,`Roaming`);return process.env.XDG_DATA_HOME||r.join(e,`xdg.data`)},e.runtime=()=>process.env.XDG_RUNTIME_DIR||void 0,e.state=()=>{let e=process.env.LOCALAPPDATA||r.join(i.home()||i.temp(),`AppData`,`Local`);return process.env.XDG_STATE_HOME||r.join(e,`xdg.state`)},e},c=()=>{let e=function(){return c()},t={};return t=/^darwin$/i.test(process.platform)?o():/^win/i.test(process.platform)?s():a(),t.configDirs=()=>{let e=[];return e.push(t.config()),process.env.XDG_CONFIG_DIRS&&e.push(...process.env.XDG_CONFIG_DIRS.split(r.delimiter)),e},t.dataDirs=()=>{let e=[];return e.push(t.data()),process.env.XDG_DATA_DIRS&&e.push(...process.env.XDG_DATA_DIRS.split(r.delimiter)),e},Object.keys(t).forEach(n=>{e[n]=t[n]}),e};n.exports=c()})),h=t(n(((t,n)=>{let r=e(`path`),i=e(`os`),a=m(),o=/^win/i.test(process.platform);function s(e,t){if(e||={},typeof e!=`object`&&(e={isolated:e}),e.isolated=e.isolated===void 0||e.isolated===null?t:e.isolated,typeof e.isolated!=`boolean`)throw TypeError(`Expected boolean for "isolated" argument, got ${typeof e.isolated}`);return e}let c=(e,t)=>{let n={};return n.cache=(n={isolated:null})=>(n=s(n,t),r.join(a.cache(),n.isolated?e:``)),n.config=(n={isolated:null})=>(n=s(n,t),r.join(a.config(),n.isolated?e:``)),n.data=(n={isolated:null})=>(n=s(n,t),r.join(a.data(),n.isolated?e:``)),n.runtime=(n={isolated:null})=>(n=s(n,t),a.runtime()?r.join(a.runtime(),n.isolated?e:``):void 0),n.state=(n={isolated:null})=>(n=s(n,t),r.join(a.state(),n.isolated?e:``)),n.configDirs=(n={isolated:null})=>(n=s(n,t),a.configDirs().map(t=>r.join(t,n.isolated?e:``))),n.dataDirs=(n={isolated:null})=>(n=s(n,t),a.dataDirs().map(t=>r.join(t,n.isolated?e:``))),n},l=(e,t)=>{let{env:n}=process,o=i.homedir(),c=i.tmpdir(),l=n.APPDATA||r.join(o||c,`AppData`,`Roaming`),u=n.LOCALAPPDATA||r.join(o||c,`AppData`,`Local`),d={};return d.cache=(i={isolated:null})=>(i=s(i,t),!i.isolated||n.XDG_CACHE_HOME?r.join(a.cache(),i.isolated?e:``):r.join(u,i.isolated?e:``,`Cache`)),d.config=(i={isolated:null})=>(i=s(i,t),!i.isolated||n.XDG_CONFIG_HOME?r.join(a.config(),i.isolated?e:``):r.join(l,i.isolated?e:``,`Config`)),d.data=(i={isolated:null})=>(i=s(i,t),!i.isolated||n.XDG_DATA_HOME?r.join(a.data(),i.isolated?e:``):r.join(l,i.isolated?e:``,`Data`)),d.runtime=(n={isolated:null})=>(n=s(n,t),a.runtime()?r.join(a.runtime(),n.isolated?e:``):void 0),d.state=(i={isolated:null})=>(i=s(i,t),!i.isolated||n.XDG_STATE_HOME?r.join(a.state(),i.isolated?e:``):r.join(u,i.isolated?e:``,`State`)),d.configDirs=(i={isolated:null})=>{i=s(i,t);let a=[d.config(i)];return n.XDG_CONFIG_DIRS&&a.push(...n.XDG_CONFIG_DIRS.split(r.delimiter).map(t=>r.join(t,i.isolated?e:``))),a},d.dataDirs=(i={isolated:null})=>{i=s(i,t);let a=[d.data(i)];return n.XDG_DATA_DIRS&&a.push(...n.XDG_DATA_DIRS.split(r.delimiter).map(t=>r.join(t,i.isolated?e:``))),a},d};n.exports=new class t{constructor(n={name:null,suffix:null,isolated:!0}){let i=function(e={name:null,suffix:null,isolated:!0}){return new t(e)};this._fn=i,n||={},typeof n!=`object`&&(n={name:n});let a=n.name||``;if(typeof a!=`string`)throw TypeError(`Expected string for "name" argument, got ${typeof a}`);let s=n.suffix||``;if(typeof s!=`string`)throw TypeError(`Expected string for "suffix" argument, got ${typeof s}`);let u=n.isolated===void 0||n.isolated===null?!0:n.isolated;if(typeof u!=`boolean`)throw TypeError(`Expected boolean for "isolated" argument, got ${typeof u}`);a||=r.parse(process.pkg?process.execPath:e.main?e.main.filename:process.argv[0]).name,s&&(a+=s),this._fn.$name=()=>a,this._fn.$isolated=()=>u;let d=o?l(a,u):c(a,u);return Object.keys(d).forEach(e=>{this._fn[e]=d[e]}),this._fn}}}))(),1);const g=r.number().transform(e=>new Date(e*1e3)),_=r.object({token:r.string().min(1).optional(),refreshToken:r.string().min(1).optional(),expiresAt:g.optional()}),v=f.pipe(_),y=e=>{try{return l.lstatSync(e).isDirectory()}catch{return!1}},b=()=>{if(process.env.VERCEL_AUTH_CONFIG_DIR)return process.env.VERCEL_AUTH_CONFIG_DIR;let e=(0,h.default)(`com.vercel.cli`).dataDirs();return[...e,o.join(s(),`.now`),...(0,h.default)(`now`).dataDirs()].find(e=>y(e))||e[0]},x=()=>{try{let e=o.join(b(),`auth.json`);return v.parse(l.readFileSync(e,`utf8`))}catch{return null}};function S(e){let t=o.join(b(),`auth.json`);l.mkdirSync(o.dirname(t),{recursive:!0});let n={token:e.token,expiresAt:e.expiresAt&&Math.round(e.expiresAt.getTime()/1e3),refreshToken:e.refreshToken};l.writeFileSync(t,JSON.stringify(n)+`
2
+ `)}const C=`${c.hostname()} @ vercel/sandbox/${i} node-${process.version} ${c.platform()} (${c.arch()})`,w=new URL(`https://vercel.com`),T=`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,E=r.object({issuer:r.string().url(),device_authorization_endpoint:r.string().url(),token_endpoint:r.string().url(),revocation_endpoint:r.string().url(),jwks_uri:r.string().url(),introspection_endpoint:r.string().url()});let D;const O=r.object({device_code:r.string(),user_code:r.string(),verification_uri:r.string().url(),verification_uri_complete:r.string().url(),expires_in:r.number(),interval:r.number()}),k=r.object({active:r.literal(!0),client_id:r.string(),session_id:r.string()}).or(r.object({active:r.literal(!1)}));async function A(){if(D)return D;let e=await fetch(new URL(`.well-known/openid-configuration`,w),{headers:{"Content-Type":`application/json`,"user-agent":C}});return D=E.parse(await e.json()),D}async function j(){let e=await A();return{async deviceAuthorizationRequest(){let t=await(await fetch(e.device_authorization_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({client_id:T,scope:`openid offline_access`})})).json(),n=O.safeParse(t);if(!n.success)throw new F(`Failed to parse device authorization response: ${n.error.message}`,t);return{device_code:n.data.device_code,user_code:n.data.user_code,verification_uri:n.data.verification_uri,verification_uri_complete:n.data.verification_uri_complete,expiresAt:Date.now()+n.data.expires_in*1e3,interval:n.data.interval}},async deviceAccessTokenRequest(t){try{return[null,await fetch(e.token_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({client_id:T,grant_type:`urn:ietf:params:oauth:grant-type:device_code`,device_code:t}),signal:AbortSignal.timeout(10*1e3)})]}catch(e){return e instanceof Error?[e]:[Error(`An unknown error occurred. See the logs for details.`,{cause:e})]}},async processTokenResponse(e){let t=await e.json(),n=M.safeParse(t);return n.success?[null,n.data]:[new F(`Failed to parse token response: ${n.error.message}`,t)]},async revokeToken(t){let n=await fetch(e.revocation_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({token:t,client_id:T})});if(!n.ok)return new F(`Revocation request failed`,await n.json())},async refreshToken(t){let n=await fetch(e.token_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({client_id:T,grant_type:`refresh_token`,refresh_token:t})}),[r,i]=await this.processTokenResponse(n);if(r)throw r;return i},async introspectToken(t){let n=await(await fetch(e.introspection_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":C},body:new URLSearchParams({token:t})})).json(),r=k.safeParse(n);if(!r.success)throw new F(`Failed to parse introspection response: ${r.error.message}`,n);return r.data}}}const M=r.object({access_token:r.string(),token_type:r.literal(`Bearer`),expires_in:r.number(),refresh_token:r.string().optional(),scope:r.string().optional()}),N=r.object({error:r.enum([`invalid_request`,`invalid_client`,`invalid_grant`,`unauthorized_client`,`unsupported_grant_type`,`invalid_scope`,`server_error`,`authorization_pending`,`slow_down`,`access_denied`,`expired_token`,`unsupported_token_type`]),error_description:r.string().optional(),error_uri:r.string().optional()});function P(e){try{return N.parse(e)}catch(e){return e instanceof r.ZodError?TypeError(`Invalid OAuth error response: ${e.message}`):TypeError(`Failed to parse OAuth error response`)}}var F=class extends Error{constructor(e,t){super(e),this.name=`OAuthError`;let n=P(t);if(n instanceof TypeError){let e=`Unexpected server response: ${JSON.stringify(t)}`;this.cause=Error(e,{cause:n}),this.code=`server_error`;return}let r=n.error;n.error_description&&(r+=`: ${n.error_description}`),n.error_uri&&(r+=` (${n.error_uri})`),this.cause=Error(r),this.code=n.error}};function I(e){return e instanceof F}async function*L({request:e,oauth:t}){let n=new AbortController;try{let r=e.interval*1e3;for(;Date.now()<e.expiresAt;){let[i,a]=await t.deviceAccessTokenRequest(e.device_code);if(i){if(i.message.includes(`timeout`)){r*=2,yield{_tag:`Timeout`,newInterval:r},await u(r,{signal:n.signal});continue}yield{_tag:`Error`,error:i};return}yield{_tag:`Response`,response:a.clone()};let[o,s]=await t.processTokenResponse(a);if(I(o)){let{code:e}=o;switch(e){case`authorization_pending`:await u(r,{signal:n.signal});continue;case`slow_down`:r+=5*1e3,yield{_tag:`SlowDown`,newInterval:r},await u(r,{signal:n.signal});continue;default:yield{_tag:`Error`,error:o.cause};return}}if(o){yield{_tag:`Error`,error:o};return}S({token:s.access_token,expiresAt:new Date(Date.now()+s.expires_in*1e3),refreshToken:s.refresh_token});return}yield{_tag:`Error`,error:Error(`Timed out waiting for authentication. Please try again.`)};return}finally{n.abort()}}var R=class extends Error{constructor(e){super(`HTTP ${e.statusCode}: ${e.responseText}`),this.name=`NotOk`,this.response=e}};async function z(e){let t=await fetch(`https://api.vercel.com${e.endpoint}`,{method:e.method,body:e.body,headers:{Authorization:`Bearer ${e.token}`,"Content-Type":`application/json`}});if(!t.ok){let e=await t.text();try{let{error:t}=JSON.parse(e);e=`${t.code.toUpperCase()}: ${t.message}`}catch{}throw new R({responseText:e,statusCode:t.status})}return await t.json()}const B=f.pipe(r.object({projectId:r.string(),orgId:r.string()}));async function V(e){let t=a.join(e,`.vercel`,`project.json`),n;try{n=await d.readFile(t,`utf-8`)}catch{return null}let r=B.safeParse(n);return r.success?{projectId:r.data.projectId,teamId:r.data.orgId}:null}const H=r.object({teams:r.array(r.object({slug:r.string()})).min(1,`No teams found. Please create a team first.`)}),U=`vercel-sandbox-default-project`;async function W(e){let t=await V(e.cwd??process.cwd());if(t)return{...t,created:!1};let n=e.teamId??await G(e.token),r=!1;try{await z({token:e.token,endpoint:`/v2/projects/vercel-sandbox-default-project?slug=${encodeURIComponent(n)}`})}catch(t){if(!(t instanceof R)||t.response.statusCode!==404)throw t;await z({token:e.token,endpoint:`/v11/projects?slug=${encodeURIComponent(n)}`,method:`POST`,body:JSON.stringify({name:U})}),r=!0}return{projectId:U,teamId:n,created:r}}async function G(e){let{teams:[t]}=await z({token:e,endpoint:`/v2/teams?limit=1`}).then(H.parse);return t.slug}export{j as OAuth,x as getAuth,W as inferScope,I as isOAuthError,L as pollForToken,G as selectTeam,S as updateAuthConfig};