@sanity/functions 1.5.0 → 1.6.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.
package/dist/types.d.ts CHANGED
@@ -20,10 +20,8 @@ export interface FunctionContext {
20
20
  functionResourceType: string;
21
21
  /** The resource ID of the function container; resource ID that houses the function. */
22
22
  functionResourceId: string;
23
- /**
24
- * uniqueId for a pipeline run
25
- */
26
- runId?: string;
23
+ /** Sanity lineage token */
24
+ lineage?: string | undefined;
27
25
  /**
28
26
  * `local` is set to `true` when testing your function locally.
29
27
  * i.e. `sanity function test func-name`
@@ -58,6 +56,8 @@ export interface FunctionContext {
58
56
  * The context object passed to the schedule function handler.
59
57
  */
60
58
  export interface ScheduledFunctionContext {
59
+ /** Sanity lineage token */
60
+ lineage?: string | undefined;
61
61
  /**
62
62
  * `local` is set to `true` when testing your function locally.
63
63
  * i.e. `sanity function test func-name`
@@ -224,14 +224,85 @@ export type FunctionResourceEnvelope = {
224
224
  [P in Exclude<FunctionResourceKey, K>]?: FunctionResource;
225
225
  };
226
226
  }[FunctionResourceKey];
227
+ type DurableLogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
227
228
  /**
228
- * The interface defining the operations available to a pipeline function.
229
+ * Context logger interface for durables.
230
+ * Exposes console.log through the durable context.
231
+ * @alpha Using durables is considered experimental and may change in the future.
232
+ * @hidden
233
+ */
234
+ interface DurableLogger {
235
+ log?(level: DurableLogLevel, ...params: unknown[]): void;
236
+ debug(...params: unknown[]): void;
237
+ info(...params: unknown[]): void;
238
+ warn(...params: unknown[]): void;
239
+ error(...params: unknown[]): void;
240
+ }
241
+ /**
242
+ * @alpha Using durables is considered experimental and may change in the future.
243
+ * @hidden
244
+ */
245
+ export type DurableContext = FunctionContext & {
246
+ /**
247
+ * Durable logger
248
+ */
249
+ log: DurableLogger;
250
+ /**
251
+ * Current attempt of the active durable operation.
252
+ * Only available in methods that expose the attempt like `waitForCondition`
253
+ */
254
+ attempt?: number;
255
+ /**
256
+ * Unique ID for a durable execution
257
+ */
258
+ runId?: string;
259
+ };
260
+ /**
261
+ * The signature of the duration object passed to the `wait` method of a durable function.
262
+ * It can be specified in days, hours, minutes, or seconds.
263
+ * @alpha Using durables is considered experimental and may change in the future.
264
+ * @hidden
265
+ */
266
+ export type DurableDuration = {
267
+ days: number;
268
+ hours?: number;
269
+ minutes?: number;
270
+ seconds?: number;
271
+ } | {
272
+ hours: number;
273
+ minutes?: number;
274
+ seconds?: number;
275
+ } | {
276
+ minutes: number;
277
+ seconds?: number;
278
+ } | {
279
+ seconds: number;
280
+ };
281
+ /**
282
+ * @alpha Using durables is considered experimental and may change in the future.
283
+ * @hidden
284
+ */
285
+ export type DurableWaitForConditionDecision = {
286
+ shouldContinue: true;
287
+ delay: DurableDuration;
288
+ } | {
289
+ shouldContinue: false;
290
+ };
291
+ /**
292
+ * @alpha Using durables is considered experimental and may change in the future.
293
+ * @hidden
294
+ */
295
+ export interface DurableWaitForConditionOptions<T> {
296
+ initial: T;
297
+ next: (state: T, context: DurableContext) => DurableWaitForConditionDecision;
298
+ }
299
+ /**
300
+ * The interface defining the operations available to a durable function.
229
301
  * These operations are steps that delegate to other functions, and wait for external callbacks.
230
- * @alpha Using pipeline functions is considered experimental and may change in the future.
231
- * @public
302
+ * @alpha Using durables is considered experimental and may change in the future.
232
303
  * @hidden
233
304
  */
234
- export interface PipelineOperations {
305
+ export interface DurableOperations {
235
306
  /**
236
307
  * Runs a named step. Its result is recorded, so if the workflow re-runs the step
237
308
  * is not executed again. Failures are retried on their own.
@@ -241,7 +312,7 @@ export interface PipelineOperations {
241
312
  * @param fn - function being executed
242
313
  * @returns The value returned by the executed function
243
314
  */
244
- run<T>(name: string, fn: () => T | Promise<T>): Promise<T>;
315
+ run<T>(name: string, fn: (ctx: DurableContext) => T | Promise<T>): Promise<T>;
245
316
  /**
246
317
  * Calls another function and awaits its result.
247
318
  * similar to ctx.invoke()
@@ -256,18 +327,145 @@ export interface PipelineOperations {
256
327
  * similar to ctx.waitForCallback()
257
328
  * @remarks cannot be nested inside another step
258
329
  * @param name - Step name
259
- * @param fn -Receives the generated callbackId and returns a delivered promise
330
+ * @param fn - Receives the generated callbackId and returns a delivered promise
260
331
  * @returns The value returned by the executed function
261
332
  */
262
- waitForCallback<T>(name: string, fn: (callbackId: string) => Promise<void>): Promise<T>;
333
+ waitForCallback<T>(name: string, fn: (callbackId: string, ctx: DurableContext) => Promise<void>): Promise<T>;
334
+ /**
335
+ * Waits for a specified duration
336
+ * similar to ctx.wait()
337
+ * @remarks cannot be nested inside another step
338
+ * @example
339
+ * Wait for 30 seconds
340
+ * ```ts
341
+ * await step.wait('wait30Sec', { seconds: 30 });
342
+ * ```
343
+ * Wait for 2 days and 3 hours
344
+ * ```ts
345
+ * await step.wait('waitALongTime', { days: 2, hours: 3 });
346
+ * ```
347
+ * @param name - Step name
348
+ * @param duration - Amount of time the function will wait before continuing.
349
+ * Duration is an object with properties of `seconds`, `minutes`, `hours`, or `days`. Must be at least {seconds: 1}
350
+ * @returns Resolves after the duration
351
+ */
352
+ wait(name: string, duration: DurableDuration): Promise<void>;
353
+ /**
354
+ * Waits for a specified duration
355
+ * similar to ctx.wait()
356
+ * @remarks cannot be nested inside another step
357
+ * @example
358
+ * Wait for 30 seconds
359
+ * ```ts
360
+ * await step.wait({ seconds: 30 });
361
+ * ```
362
+ * @param duration - Amount of time the function will wait before continuing.
363
+ * Duration is an object with properties of `seconds`, `minutes`, `hours`, or `days`. Must be at least {seconds: 1}
364
+ * @returns Resolves after the duration
365
+ */
366
+ wait(duration: DurableDuration): Promise<void>;
367
+ /**
368
+ * Waits for a specified condition to be met
369
+ * similar to ctx.waitForCondition()
370
+ * @remarks cannot be nested inside another step
371
+ * @example
372
+ * ```ts
373
+ * await step.waitForCondition(
374
+ * 'waitForCondition',
375
+ * async (state, context) => {
376
+ * context.log.info('Checking for article', {
377
+ * runId: context.runId,
378
+ * attempt: context.attempt,
379
+ * })
380
+ *
381
+ * const client = createClient({
382
+ * apiVersion: '2026-08-05',
383
+ * ...context.clientOptions,
384
+ * })
385
+ * const article = await client.fetch<Article | null>(
386
+ * '*[_type == "article"][0]',
387
+ * )
388
+ * return {...state, article}
389
+ * },
390
+ * {
391
+ * initial: {
392
+ * article: null as Article | null,
393
+ * },
394
+ * next: (state, context) => {
395
+ * if (state.article) return {shouldContinue: false}
396
+ *
397
+ * return {
398
+ * shouldContinue: true,
399
+ * delay: {
400
+ * seconds: Math.min((context.attempt ?? 1) * 2, 60),
401
+ * },
402
+ * }
403
+ * },
404
+ * },
405
+ * )
406
+ * ```
407
+ * @param name - Step name
408
+ * @param fn - Called on each attempt with the current state and durable context.
409
+ * Returns a promise resolving to the updated state,
410
+ * which is passed to next to determine whether the condition has been met or another check should be scheduled.
411
+ * @param options - Configuration options for the condition
412
+ * @returns The value returned by the executed function
413
+ */
414
+ waitForCondition<T>(name: string, fn: (state: T, context: DurableContext) => Promise<T>, options: DurableWaitForConditionOptions<T>): Promise<T>;
415
+ /**
416
+ * Waits for a specified condition to be met
417
+ * similar to ctx.waitForCondition()
418
+ * @remarks cannot be nested inside another step
419
+ * @example
420
+ * ```ts
421
+ * await step.waitForCondition(
422
+ * async (state, context) => {
423
+ * context.log.info('Checking for article', {
424
+ * runId: context.runId,
425
+ * attempt: context.attempt,
426
+ * })
427
+ *
428
+ * const client = createClient({
429
+ * apiVersion: '2026-08-05',
430
+ * ...context.clientOptions,
431
+ * })
432
+ * const article = await client.fetch<Article | null>(
433
+ * '*[_type == "article"][0]',
434
+ * )
435
+ * return {...state, article}
436
+ * },
437
+ * {
438
+ * initial: {
439
+ * article: null as Article | null,
440
+ * },
441
+ * next: (state, context) => {
442
+ * if (state.article) return {shouldContinue: false}
443
+ *
444
+ * return {
445
+ * shouldContinue: true,
446
+ * delay: {
447
+ * seconds: Math.min((context.attempt ?? 1) * 2, 60),
448
+ * },
449
+ * }
450
+ * },
451
+ * },
452
+ * )
453
+ * ```
454
+ * @param fn - Called on each attempt with the current state and durable context.
455
+ * Returns a promise resolving to the updated state,
456
+ * which is passed to next to determine whether the condition has been met or another check should be scheduled.
457
+ * @param options - Configuration options for the condition
458
+ * @returns The value returned by the executed function
459
+ */
460
+ waitForCondition<T>(fn: (state: T, context: DurableContext) => Promise<T>, options: DurableWaitForConditionOptions<T>): Promise<T>;
263
461
  }
264
462
  /**
265
- * @alpha Using pipeline functions is considered experimental and may change in the future.
463
+ * @alpha Using durables is considered experimental and may change in the future.
266
464
  * @hidden
267
465
  */
268
- export type PipelineHandler = (envelope: {
269
- context: FunctionContext;
466
+ export type DurableHandler = (envelope: {
467
+ context: DurableContext;
270
468
  event?: GenericEvent;
271
- step: PipelineOperations;
469
+ step: DurableOperations;
272
470
  }) => unknown | Promise<unknown>;
273
471
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/functions",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Helper methods and type definitions for Sanity Functions",
5
5
  "keywords": [
6
6
  "sanity",
@@ -1,15 +1,15 @@
1
- import type {PipelineHandler} from './types'
1
+ import type {DurableHandler} from './types'
2
2
 
3
3
  /**
4
- * Determine if `createPipeline({}, () => {})` or `createPipeline(() => {})`.
4
+ * Determine if `createDurable({}, () => {})` or `createDurable(() => {})`.
5
5
  * @param configOrHandler
6
6
  * @param maybeHandler
7
7
  * @returns resolved arguments
8
8
  */
9
9
  const resolveFuncArgs = <TConfig extends {name: string}>(
10
- configOrHandler: TConfig | PipelineHandler,
11
- maybeHandler?: PipelineHandler,
12
- ): {config?: TConfig; handler?: PipelineHandler; hadConfigArg: boolean} => {
10
+ configOrHandler: TConfig | DurableHandler,
11
+ maybeHandler?: DurableHandler,
12
+ ): {config?: TConfig; handler?: DurableHandler; hadConfigArg: boolean} => {
13
13
  return typeof configOrHandler === 'function'
14
14
  ? {config: undefined, handler: configOrHandler, hadConfigArg: false}
15
15
  : {config: configOrHandler, handler: maybeHandler, hadConfigArg: true}
@@ -52,40 +52,37 @@ const validateConfig = (config: unknown) => {
52
52
  }
53
53
 
54
54
  /**
55
- * Pipeline creation function that can be called with or without a config object.
56
- * @alpha Pipelines are an experimental feature and may change in the future.
55
+ * Durables creation function that can be called with or without a config object.
56
+ * @alpha Durables are an experimental feature and may change in the future.
57
57
  * @hidden
58
58
  * @param handler
59
59
  * @returns The handler function, unmodified.
60
60
  */
61
- export function createPipeline(handler: PipelineHandler): PipelineHandler & {config?: undefined}
61
+ export function createDurable(handler: DurableHandler): DurableHandler & {config?: undefined}
62
62
 
63
63
  /**
64
- * Pipeline creation function that can be called with or without a config object.
65
- * @alpha Pipelines are an experimental feature and may change in the future.
64
+ * Durables creation function that can be called with or without a config object.
65
+ * @alpha Durables are an experimental feature and may change in the future.
66
66
  * @hidden
67
67
  * @param config
68
68
  * @param handler
69
69
  * @returns The handler function, unmodified and the provided config object.
70
70
  */
71
- export function createPipeline<TConfig extends {name: string}>(
72
- config: TConfig,
73
- handler: PipelineHandler,
74
- ): PipelineHandler & {config: TConfig}
71
+ export function createDurable<TConfig extends {name: string}>(config: TConfig, handler: DurableHandler): DurableHandler & {config: TConfig}
75
72
 
76
73
  /**
77
- * Pipeline creation function that can be called with or without a config object.
78
- * @alpha Pipelines are an experimental feature and may change in the future.
74
+ * Durables creation function that can be called with or without a config object.
75
+ * @alpha Durable functions are an experimental feature and may change in the future.
79
76
  * @hidden
80
77
  * @public
81
78
  * @param configOrHandler
82
79
  * @param maybeHandler
83
80
  * @returns The handler function, unmodified and the config object if provided
84
81
  */
85
- export function createPipeline<TConfig extends {name: string}>(
86
- configOrHandler: TConfig | PipelineHandler,
87
- maybeHandler?: PipelineHandler,
88
- ): PipelineHandler {
82
+ export function createDurable<TConfig extends {name: string}>(
83
+ configOrHandler: TConfig | DurableHandler,
84
+ maybeHandler?: DurableHandler,
85
+ ): DurableHandler {
89
86
  const {config, handler, hadConfigArg} = resolveFuncArgs(configOrHandler, maybeHandler)
90
87
  const errors = [
91
88
  ...(hadConfigArg ? validateConfig(config) : []),
@@ -96,12 +93,12 @@ export function createPipeline<TConfig extends {name: string}>(
96
93
  throw new TypeError(errors.join(', '))
97
94
  }
98
95
  // Separate config from the handler during build
99
- return Object.assign(handler as PipelineHandler, {config})
96
+ return Object.assign(handler as DurableHandler, {config})
100
97
  }
101
98
 
102
99
  /**
103
- * @alpha Pipelines are an experimental feature and may change in the future.
100
+ * @alpha Durable functions are an experimental feature and may change in the future.
104
101
  * @hidden
105
102
  * @public
106
103
  */
107
- export const pipeline = {createPipeline}
104
+ export const durable = {createDurable}
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export * from './definers.js'
2
+ export * from './durables.js'
2
3
  export * from './invoke.js'
3
- export * from './pipelines.js'
4
4
  export * from './types.js'
package/src/invoke.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import {Buffer} from 'node:buffer'
2
+ import crypto from 'node:crypto'
2
3
  import {env} from 'node:process'
3
4
  import type awsLite from '@aws-lite/client'
4
5
  import type {FunctionPayload, FunctionResourceEnvelope, InvokeOptions} from './types.js'
@@ -6,8 +7,11 @@ import type {FunctionPayload, FunctionResourceEnvelope, InvokeOptions} from './t
6
7
  let awsPromise: Promise<awsLite.AwsLiteClient> | undefined
7
8
 
8
9
  const PARTITION_KEY = 'arc-app-res'
10
+ /** @internal */
11
+ export const MAX_RECURSION_COUNT = 16
9
12
 
10
13
  /**
14
+ * @internal
11
15
  * lazy load aws-lite
12
16
  */
13
17
  function getAwsLite() {
@@ -26,6 +30,7 @@ function getAwsLite() {
26
30
  }
27
31
 
28
32
  /**
33
+ * @internal
29
34
  * Gets a specific resource based off of function name
30
35
  * @param {string} name
31
36
  */
@@ -46,6 +51,60 @@ async function getResource(name: string, aws: awsLite.AwsLiteClient): Promise<Fu
46
51
  return result.Item['resources'] as unknown as FunctionResourceEnvelope
47
52
  }
48
53
 
54
+ /**
55
+ * @internal
56
+ * Generate a short UUID.
57
+ * @param {number} [length] - The length of the UUID to generate.
58
+ * @param {string} [characters] - The characters to use to generate the UUID.
59
+ * @returns {string} The generated UUID.
60
+ */
61
+ export function genID(length = 32, characters = '23456789abcdefghijklmnopqrstuvwxyz') {
62
+ let result = ''
63
+ const bytes = crypto.randomBytes(length)
64
+ for (let i = 0; i < length; i++) {
65
+ result += characters[bytes[i] % characters.length]
66
+ }
67
+ return result
68
+ }
69
+
70
+ /**
71
+ * @internal
72
+ * Builds the new lineage token given the existing token.
73
+ * @param {string} name
74
+ * @param {string | undefined} lineage
75
+ * @param {object} options
76
+ * @param {number} options.maxRecursionCount The maximum recursion depth
77
+ * @returns The new lineage token with the count incremented
78
+ */
79
+ export function buildLineageToken(name: string, lineage: string | undefined) {
80
+ let recursionCount = 0
81
+ try {
82
+ if (lineage) {
83
+ // split the token, usually into two parts
84
+ const parts = lineage.trim().split(':')
85
+ if (parts.length > 1) {
86
+ // the current count is in the last part
87
+ const count = parts[parts.length - 1]
88
+ recursionCount = Number.parseInt(count, 10)
89
+
90
+ // if parsing didn't work or the value was invalid, reset to 0
91
+ if (Number.isNaN(recursionCount) || recursionCount < 0) {
92
+ recursionCount = 0
93
+ }
94
+
95
+ // this handles whitespace, and also if the first parts of the token contained colons
96
+ lineage = parts.slice(0, -1).join(':')
97
+ }
98
+ }
99
+ } catch {
100
+ // ignore
101
+ }
102
+ if (recursionCount >= MAX_RECURSION_COUNT) {
103
+ throw new Error(`Function ${name} exceeded the maximum recursion depth of ${MAX_RECURSION_COUNT}`)
104
+ }
105
+ return `${lineage || genID(32)}:${recursionCount + 1}`
106
+ }
107
+
49
108
  /**
50
109
  * Invokes another Sanity Function.
51
110
  *
@@ -63,16 +122,22 @@ export async function invoke<T = unknown>(name: string, payload: FunctionPayload
63
122
  if (!name) throw new Error('Function name was not provided')
64
123
  const sync = options?.sync ?? false
65
124
 
66
- const stringPayload = JSON.stringify(payload)
125
+ // Update lineage or throw error if we exceed the max recursion value
126
+ const outgoingPayload: FunctionPayload = {
127
+ ...payload,
128
+ context: {...payload.context, lineage: buildLineageToken(name, payload.context?.lineage)},
129
+ }
130
+
131
+ const stringPayload = JSON.stringify(outgoingPayload)
67
132
  // Check to make sure payload is not over the max we can handle
68
133
  checkPayloadSize(stringPayload, sync)
69
134
 
70
135
  // Local invoke path for Sanity CLI
71
- if (payload?.context?.local) {
72
- if (!payload?.context?.invoke) {
136
+ if (outgoingPayload?.context?.local) {
137
+ if (!outgoingPayload?.context?.invoke) {
73
138
  throw new Error(`No local invoke handler configured for function: ${name}`)
74
139
  }
75
- return await payload.context.invoke(name, payload, options)
140
+ return await outgoingPayload.context.invoke(name, outgoingPayload, options)
76
141
  }
77
142
 
78
143
  const aws = await getAwsLite()
@@ -80,15 +145,19 @@ export async function invoke<T = unknown>(name: string, payload: FunctionPayload
80
145
 
81
146
  // Look up the function details
82
147
  const resource = await getResource(name, aws)
148
+ const contextResource = payload?.context?.resources?.(name)
83
149
 
84
150
  // Synchronous invocation
85
151
  if (sync === true) {
86
- if (!resource.function) {
152
+ if (!resource.function || !contextResource) {
87
153
  throw new Error(`Function ${name} cannot be invoked synchronously.`)
88
154
  }
155
+ if (contextResource.type !== 'sanity.function.pubsub') {
156
+ throw new Error(`Function ${name} of type ${contextResource.type} cannot be invoked synchronously.`)
157
+ }
89
158
  const {Payload, FunctionError} = await aws.Lambda.Invoke({
90
159
  FunctionName: resource.function.physicalResourceId,
91
- Payload: payload,
160
+ Payload: outgoingPayload,
92
161
  InvocationType: 'RequestResponse',
93
162
  })
94
163
  if (FunctionError) {
@@ -100,28 +169,23 @@ export async function invoke<T = unknown>(name: string, payload: FunctionPayload
100
169
  }
101
170
 
102
171
  // Async invocation by type
103
- if (resource.topic) {
172
+ if (resource.topic && contextResource?.type === 'sanity.function.pubsub') {
104
173
  await aws.SNS.Publish({
105
174
  TopicArn: resource.topic.physicalResourceId,
106
175
  Message: stringPayload,
107
176
  })
108
- } else if (resource.queue) {
177
+ } else if (resource.queue && contextResource?.type === 'sanity.function.queue') {
109
178
  await aws.SQS.SendMessage({
110
179
  MessageBody: stringPayload,
111
180
  QueueUrl: resource.queue.physicalResourceId,
112
181
  })
113
- } else if (resource.function) {
114
- await aws.Lambda.Invoke({
115
- FunctionName: resource.function.physicalResourceId,
116
- Payload: payload,
117
- InvocationType: 'Event',
118
- })
119
182
  } else {
120
183
  throw new Error(`No invokeable resource for function: ${name}`)
121
184
  }
122
185
  return
123
186
  }
124
187
 
188
+ /** @internal */
125
189
  function checkPayloadSize(payload: string, sync: boolean) {
126
190
  if (sync) {
127
191
  if (Buffer.byteLength(payload, 'utf8') > 6 * 1024 * 1024) {