@sanity/functions 1.8.1 → 1.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.
@@ -26,6 +26,25 @@ export interface DurableLogger {
26
26
  export interface DurableStepCallbackContext {
27
27
  logger: DurableLogger;
28
28
  }
29
+ /**
30
+ * Context parameter passed to a branch method of a `step.fanout` execution.
31
+ * @alpha Using durables is considered experimental and may change in the future.
32
+ * @hidden
33
+ */
34
+ export interface DurableStepContext extends DurableStepCallbackContext {
35
+ step: DurableOperations;
36
+ }
37
+ export interface DurableFanoutBranchContext extends DurableStepContext {
38
+ }
39
+ /**
40
+ * Context parameter passed to the top-level `durableEventHandler` method.
41
+ * @alpha Using durables is considered experimental and may change in the future.
42
+ * @hidden
43
+ */
44
+ export interface DurableTopLevelContext extends DurableStepContext {
45
+ context: DurableContext;
46
+ event?: GenericEvent;
47
+ }
29
48
  /**
30
49
  * Arguments passed to callbacks that execute a durable attempt.
31
50
  * step.run & step.waitForCondition
@@ -85,6 +104,11 @@ export type DurableStepHandler<TArgs extends unknown[], TReturn> = (...args: TAr
85
104
  * @hidden
86
105
  */
87
106
  export type DurableStepRunHandler<T = unknown> = DurableStepHandler<[context: DurableStepAttemptContext], T | Promise<T>>;
107
+ /**
108
+ * @alpha Using durables is considered experimental and may change in the future.
109
+ * @hidden
110
+ */
111
+ export type DurableStepFanoutHandler<T = unknown> = DurableStepHandler<[context: DurableFanoutBranchContext], T | Promise<T>>;
88
112
  /**
89
113
  * @alpha Using durables is considered experimental and may change in the future.
90
114
  * @hidden
@@ -103,6 +127,109 @@ export type DurableWaitForConditionNext<T = unknown> = DurableStepHandler<[
103
127
  state: T,
104
128
  context: Pick<DurableStepAttemptContext, 'attempt'>
105
129
  ], DurableWaitForConditionDecision>;
130
+ /**
131
+ * @alpha Using durables is considered experimental and may change in the future.
132
+ * @hidden
133
+ */
134
+ export type BatchItemSucceededStatus = 'SUCCEEDED';
135
+ /**
136
+ * @alpha Using durables is considered experimental and may change in the future.
137
+ * @hidden
138
+ */
139
+ export type BatchItemFailedStatus = 'FAILED';
140
+ /**
141
+ * @alpha Using durables is considered experimental and may change in the future.
142
+ * @hidden
143
+ */
144
+ export type BatchItemStartedStatus = 'STARTED';
145
+ /**
146
+ * @alpha Using durables is considered experimental and may change in the future.
147
+ * @hidden
148
+ */
149
+ export type BatchItemStatus = BatchItemSucceededStatus | BatchItemFailedStatus | BatchItemStartedStatus;
150
+ /**
151
+ * Reason why a batch operation (map, parallel, or concurrent execution)
152
+ * completed.
153
+ *
154
+ * - `ALL_COMPLETED`: every item finished.
155
+ * - `MIN_SUCCESSFUL_REACHED`: CompletionConfig.minSuccessful was reached.
156
+ * - `FAILURE_TOLERANCE_EXCEEDED`: a failure threshold was exceeded.
157
+ * - `CUSTOM_COMPLETION_SUCCEEDED`: a custom CompletionConfig.shouldComplete
158
+ * predicate signalled completion with a `SUCCEEDED` outcome before all items
159
+ * finished.
160
+ * - `CUSTOM_COMPLETION_FAILED`: a custom CompletionConfig.shouldComplete
161
+ * predicate signalled completion with a `FAILED` outcome before all items
162
+ * finished.
163
+ * @alpha Using durables is considered experimental and may change in the future.
164
+ * @hidden
165
+ * @remarks copied from AWS Durable Execution SDK
166
+ */
167
+ export type CompletionReason = 'ALL_COMPLETED' | 'MIN_SUCCESSFUL_REACHED' | 'FAILURE_TOLERANCE_EXCEEDED' | 'CUSTOM_COMPLETION_SUCCEEDED' | 'CUSTOM_COMPLETION_FAILED';
168
+ /**
169
+ * The result of a `step.fanout` branch.
170
+ * @alpha Using durables is considered experimental and may change in the future.
171
+ * @hidden
172
+ * @remarks copied from AWS Durable Execution SDK
173
+ */
174
+ export interface BatchItem<TResult> {
175
+ /** The result value if the item succeeded */
176
+ result?: TResult;
177
+ /** The error if the item failed */
178
+ error?: Error;
179
+ /** Index of the item in the original array */
180
+ index: number;
181
+ /** Status of the item execution */
182
+ status: BatchItemStatus;
183
+ }
184
+ /**
185
+ * @alpha Using durables is considered experimental and may change in the future.
186
+ * @hidden
187
+ * @remarks copied from AWS Durable Execution SDK
188
+ */
189
+ export interface BatchResult<TResult> {
190
+ /**
191
+ * All items in the batch with their results/errors.
192
+ */
193
+ all: Array<BatchItem<TResult>>;
194
+ /** Returns only the items that succeeded */
195
+ succeeded(): Array<BatchItem<TResult> & {
196
+ result: TResult;
197
+ }>;
198
+ /** Returns only the items that failed */
199
+ failed(): Array<BatchItem<TResult> & {
200
+ error: Error;
201
+ }>;
202
+ /**
203
+ * Returns only the items that are still in progress (STARTED) — items that
204
+ * were in flight when the batch completed early (e.g. via CompletionConfig.minSuccessful
205
+ * or a custom CompletionConfig.shouldComplete).
206
+ */
207
+ started(): Array<BatchItem<TResult> & {
208
+ status: BatchItemStartedStatus;
209
+ }>;
210
+ /** Overall status of the batch (SUCCEEDED if no failures, FAILED otherwise) */
211
+ status: BatchItemSucceededStatus | BatchItemFailedStatus;
212
+ /** Reason why the batch completed */
213
+ completionReason: CompletionReason;
214
+ /** Whether any item in the batch failed */
215
+ hasFailure: boolean;
216
+ /** Throws the first error if any item failed */
217
+ throwIfError(): void;
218
+ /** Returns array of all successful results */
219
+ getResults(): Array<TResult>;
220
+ /** Returns array of all errors */
221
+ getErrors(): Array<Error>;
222
+ /** Number of successful items */
223
+ successCount: number;
224
+ /** Number of failed items */
225
+ failureCount: number;
226
+ /**
227
+ * Number of started but not completed items. Not guaranteed to be stable across suspend/resume
228
+ */
229
+ startedCount: number;
230
+ /** Total number of items */
231
+ totalCount: number;
232
+ }
106
233
  /**
107
234
  * The interface defining the operations available to a durable function.
108
235
  * These operations are steps that delegate to other functions, and wait for external callbacks.
@@ -143,6 +270,55 @@ export type DurableOperations = {
143
270
  handler: DurableStepRunHandler<T>;
144
271
  retry?: DurableRetryStrategy;
145
272
  }): Promise<T>;
273
+ /**
274
+ * Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual `step` operations available.
275
+ * @remarks By using the generic, you can set a single, homogeneous return type for all branches.
276
+ * @example
277
+ * ```ts
278
+ * step.fanout<string>({
279
+ * name: 'parallel-runs',
280
+ * branches: [async ({step, logger}) => {
281
+ * logger.log('Running first function in parallel')
282
+ * return 'first'
283
+ * }, async ({step, logger}) => {
284
+ * logger.log('Running second function in parallel')
285
+ * return 'second'
286
+ * }],
287
+ * })
288
+ * ```
289
+ * @param name - Step name
290
+ * @param branches - functions being executed in parallel
291
+ * @returns A batch result of values returned or errors thrown by all branches.
292
+ */
293
+ fanout<T>({ name, branches }: {
294
+ name?: string;
295
+ branches: DurableStepFanoutHandler<T>[];
296
+ }): Promise<BatchResult<T>>;
297
+ /**
298
+ * Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual `step` operations available.
299
+ * @remarks This overload provides automatic type inference for heterogeneous branch return types. When branches return different types, the result will be `BatchResult<T1 | T2 | ...>`.
300
+ * Use the explicit type parameter overloads above for strict homogeneous type checking.
301
+ * @example
302
+ * ```ts
303
+ * step.fanout<string>({
304
+ * name: 'parallel-runs',
305
+ * branches: [async ({step, logger}) => {
306
+ * logger.log('Running first function in parallel')
307
+ * return 'first'
308
+ * }, async ({step, logger}) => {
309
+ * logger.log('Running second function in parallel')
310
+ * return 'second'
311
+ * }],
312
+ * })
313
+ * ```
314
+ * @param name - Step name
315
+ * @param branches - functions being executed in parallel
316
+ * @returns A batch result of values returned or errors thrown by all branches.
317
+ */
318
+ fanout<Branches extends readonly unknown[]>({ name, branches, }: {
319
+ name?: string;
320
+ branches: Branches;
321
+ }): Promise<BatchResult<Branches[number] extends DurableStepFanoutHandler<infer ReturnType> ? ReturnType : never>>;
146
322
  /**
147
323
  * Calls another function and awaits its result.
148
324
  * similar to ctx.invoke()
@@ -265,9 +441,4 @@ export type DurableOperations = {
265
441
  * @alpha Using durables is considered experimental and may change in the future.
266
442
  * @hidden
267
443
  */
268
- export type DurableHandler = (envelope: {
269
- context: DurableContext;
270
- event?: GenericEvent;
271
- step: DurableOperations;
272
- logger: DurableLogger;
273
- }) => unknown | Promise<unknown>;
444
+ export type DurableHandler = (envelope: DurableTopLevelContext) => unknown | Promise<unknown>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/functions",
3
- "version": "1.8.1",
3
+ "version": "1.9.0",
4
4
  "description": "Helper methods and type definitions for Sanity Functions",
5
5
  "keywords": [
6
6
  "sanity",
@@ -56,12 +56,12 @@
56
56
  "@aws-lite/sns-types": "^0.0.11",
57
57
  "@aws-lite/sqs": "^0.2.4",
58
58
  "@aws-lite/sqs-types": "^0.2.7",
59
- "@biomejs/biome": "2.5.8",
59
+ "@biomejs/biome": "2.5.15",
60
60
  "@types/node": "^22",
61
- "@vitest/coverage-v8": "4.1.10",
61
+ "@vitest/coverage-v8": "5.0.4",
62
62
  "rimraf": "^6.1.2",
63
63
  "typescript": "^7.0.2",
64
- "vitest": "4.1.10"
64
+ "vitest": "5.0.4"
65
65
  },
66
66
  "engines": {
67
67
  "node": ">=22"
@@ -30,6 +30,26 @@ export interface DurableStepCallbackContext {
30
30
  logger: DurableLogger
31
31
  }
32
32
 
33
+ /**
34
+ * Context parameter passed to a branch method of a `step.fanout` execution.
35
+ * @alpha Using durables is considered experimental and may change in the future.
36
+ * @hidden
37
+ */
38
+ export interface DurableStepContext extends DurableStepCallbackContext {
39
+ step: DurableOperations
40
+ }
41
+ export interface DurableFanoutBranchContext extends DurableStepContext {}
42
+
43
+ /**
44
+ * Context parameter passed to the top-level `durableEventHandler` method.
45
+ * @alpha Using durables is considered experimental and may change in the future.
46
+ * @hidden
47
+ */
48
+ export interface DurableTopLevelContext extends DurableStepContext {
49
+ context: DurableContext
50
+ event?: GenericEvent
51
+ }
52
+
33
53
  /**
34
54
  * Arguments passed to callbacks that execute a durable attempt.
35
55
  * step.run & step.waitForCondition
@@ -81,6 +101,12 @@ export type DurableStepHandler<TArgs extends unknown[], TReturn> = (...args: TAr
81
101
  */
82
102
  export type DurableStepRunHandler<T = unknown> = DurableStepHandler<[context: DurableStepAttemptContext], T | Promise<T>>
83
103
 
104
+ /**
105
+ * @alpha Using durables is considered experimental and may change in the future.
106
+ * @hidden
107
+ */
108
+ export type DurableStepFanoutHandler<T = unknown> = DurableStepHandler<[context: DurableFanoutBranchContext], T | Promise<T>>
109
+
84
110
  /**
85
111
  * @alpha Using durables is considered experimental and may change in the future.
86
112
  * @hidden
@@ -102,6 +128,121 @@ export type DurableWaitForConditionNext<T = unknown> = DurableStepHandler<
102
128
  DurableWaitForConditionDecision
103
129
  >
104
130
 
131
+ /**
132
+ * @alpha Using durables is considered experimental and may change in the future.
133
+ * @hidden
134
+ */
135
+ export type BatchItemSucceededStatus = 'SUCCEEDED'
136
+ /**
137
+ * @alpha Using durables is considered experimental and may change in the future.
138
+ * @hidden
139
+ */
140
+ export type BatchItemFailedStatus = 'FAILED'
141
+ /**
142
+ * @alpha Using durables is considered experimental and may change in the future.
143
+ * @hidden
144
+ */
145
+ export type BatchItemStartedStatus = 'STARTED'
146
+ /**
147
+ * @alpha Using durables is considered experimental and may change in the future.
148
+ * @hidden
149
+ */
150
+ export type BatchItemStatus = BatchItemSucceededStatus | BatchItemFailedStatus | BatchItemStartedStatus
151
+ /**
152
+ * Reason why a batch operation (map, parallel, or concurrent execution)
153
+ * completed.
154
+ *
155
+ * - `ALL_COMPLETED`: every item finished.
156
+ * - `MIN_SUCCESSFUL_REACHED`: CompletionConfig.minSuccessful was reached.
157
+ * - `FAILURE_TOLERANCE_EXCEEDED`: a failure threshold was exceeded.
158
+ * - `CUSTOM_COMPLETION_SUCCEEDED`: a custom CompletionConfig.shouldComplete
159
+ * predicate signalled completion with a `SUCCEEDED` outcome before all items
160
+ * finished.
161
+ * - `CUSTOM_COMPLETION_FAILED`: a custom CompletionConfig.shouldComplete
162
+ * predicate signalled completion with a `FAILED` outcome before all items
163
+ * finished.
164
+ * @alpha Using durables is considered experimental and may change in the future.
165
+ * @hidden
166
+ * @remarks copied from AWS Durable Execution SDK
167
+ */
168
+ export type CompletionReason =
169
+ | 'ALL_COMPLETED'
170
+ | 'MIN_SUCCESSFUL_REACHED'
171
+ | 'FAILURE_TOLERANCE_EXCEEDED'
172
+ | 'CUSTOM_COMPLETION_SUCCEEDED'
173
+ | 'CUSTOM_COMPLETION_FAILED'
174
+ /**
175
+ * The result of a `step.fanout` branch.
176
+ * @alpha Using durables is considered experimental and may change in the future.
177
+ * @hidden
178
+ * @remarks copied from AWS Durable Execution SDK
179
+ */
180
+ export interface BatchItem<TResult> {
181
+ /** The result value if the item succeeded */
182
+ result?: TResult
183
+ /** The error if the item failed */
184
+ error?: Error
185
+ /** Index of the item in the original array */
186
+ index: number
187
+ /** Status of the item execution */
188
+ status: BatchItemStatus
189
+ }
190
+ /**
191
+ * @alpha Using durables is considered experimental and may change in the future.
192
+ * @hidden
193
+ * @remarks copied from AWS Durable Execution SDK
194
+ */
195
+ export interface BatchResult<TResult> {
196
+ /**
197
+ * All items in the batch with their results/errors.
198
+ */
199
+ all: Array<BatchItem<TResult>>
200
+ /** Returns only the items that succeeded */
201
+ succeeded(): Array<
202
+ BatchItem<TResult> & {
203
+ result: TResult
204
+ }
205
+ >
206
+ /** Returns only the items that failed */
207
+ failed(): Array<
208
+ BatchItem<TResult> & {
209
+ error: Error
210
+ }
211
+ >
212
+ /**
213
+ * Returns only the items that are still in progress (STARTED) — items that
214
+ * were in flight when the batch completed early (e.g. via CompletionConfig.minSuccessful
215
+ * or a custom CompletionConfig.shouldComplete).
216
+ */
217
+ started(): Array<
218
+ BatchItem<TResult> & {
219
+ status: BatchItemStartedStatus
220
+ }
221
+ >
222
+ /** Overall status of the batch (SUCCEEDED if no failures, FAILED otherwise) */
223
+ status: BatchItemSucceededStatus | BatchItemFailedStatus
224
+ /** Reason why the batch completed */
225
+ completionReason: CompletionReason
226
+ /** Whether any item in the batch failed */
227
+ hasFailure: boolean
228
+ /** Throws the first error if any item failed */
229
+ throwIfError(): void
230
+ /** Returns array of all successful results */
231
+ getResults(): Array<TResult>
232
+ /** Returns array of all errors */
233
+ getErrors(): Array<Error>
234
+ /** Number of successful items */
235
+ successCount: number
236
+ /** Number of failed items */
237
+ failureCount: number
238
+ /**
239
+ * Number of started but not completed items. Not guaranteed to be stable across suspend/resume
240
+ */
241
+ startedCount: number
242
+ /** Total number of items */
243
+ totalCount: number
244
+ }
245
+
105
246
  /**
106
247
  * The interface defining the operations available to a durable function.
107
248
  * These operations are steps that delegate to other functions, and wait for external callbacks.
@@ -138,6 +279,57 @@ export type DurableOperations = {
138
279
  * @returns The value returned by the executed function
139
280
  */
140
281
  run<T>({name, handler, retry}: {name?: string; handler: DurableStepRunHandler<T>; retry?: DurableRetryStrategy}): Promise<T>
282
+
283
+ /**
284
+ * Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual `step` operations available.
285
+ * @remarks By using the generic, you can set a single, homogeneous return type for all branches.
286
+ * @example
287
+ * ```ts
288
+ * step.fanout<string>({
289
+ * name: 'parallel-runs',
290
+ * branches: [async ({step, logger}) => {
291
+ * logger.log('Running first function in parallel')
292
+ * return 'first'
293
+ * }, async ({step, logger}) => {
294
+ * logger.log('Running second function in parallel')
295
+ * return 'second'
296
+ * }],
297
+ * })
298
+ * ```
299
+ * @param name - Step name
300
+ * @param branches - functions being executed in parallel
301
+ * @returns A batch result of values returned or errors thrown by all branches.
302
+ */
303
+ fanout<T>({name, branches}: {name?: string; branches: DurableStepFanoutHandler<T>[]}): Promise<BatchResult<T>>
304
+ /**
305
+ * Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual `step` operations available.
306
+ * @remarks This overload provides automatic type inference for heterogeneous branch return types. When branches return different types, the result will be `BatchResult<T1 | T2 | ...>`.
307
+ * Use the explicit type parameter overloads above for strict homogeneous type checking.
308
+ * @example
309
+ * ```ts
310
+ * step.fanout<string>({
311
+ * name: 'parallel-runs',
312
+ * branches: [async ({step, logger}) => {
313
+ * logger.log('Running first function in parallel')
314
+ * return 'first'
315
+ * }, async ({step, logger}) => {
316
+ * logger.log('Running second function in parallel')
317
+ * return 'second'
318
+ * }],
319
+ * })
320
+ * ```
321
+ * @param name - Step name
322
+ * @param branches - functions being executed in parallel
323
+ * @returns A batch result of values returned or errors thrown by all branches.
324
+ */
325
+ fanout<Branches extends readonly unknown[]>({
326
+ name,
327
+ branches,
328
+ }: {
329
+ name?: string
330
+ branches: Branches
331
+ }): Promise<BatchResult<Branches[number] extends DurableStepFanoutHandler<infer ReturnType> ? ReturnType : never>>
332
+
141
333
  /**
142
334
  * Calls another function and awaits its result.
143
335
  * similar to ctx.invoke()
@@ -267,9 +459,4 @@ export type DurableOperations = {
267
459
  * @alpha Using durables is considered experimental and may change in the future.
268
460
  * @hidden
269
461
  */
270
- export type DurableHandler = (envelope: {
271
- context: DurableContext
272
- event?: GenericEvent
273
- step: DurableOperations
274
- logger: DurableLogger
275
- }) => unknown | Promise<unknown>
462
+ export type DurableHandler = (envelope: DurableTopLevelContext) => unknown | Promise<unknown>