@sanity/functions 1.5.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/types.d.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  /**
2
2
  * Callback provided by Sanity CLI when doing local development
3
+ * @alpha
4
+ * @hidden
3
5
  */
4
6
  export type InvokeCallback = <T = unknown>(name: string, payload: FunctionPayload, options?: InvokeOptions) => Promise<T>;
5
7
  /**
6
8
  * Options provided to invoke
9
+ * @alpha
10
+ * @hidden
7
11
  */
8
12
  export type InvokeOptions = {
9
13
  sync?: boolean;
@@ -20,10 +24,8 @@ export interface FunctionContext {
20
24
  functionResourceType: string;
21
25
  /** The resource ID of the function container; resource ID that houses the function. */
22
26
  functionResourceId: string;
23
- /**
24
- * uniqueId for a pipeline run
25
- */
26
- runId?: string;
27
+ /** Sanity lineage token */
28
+ lineage?: string | undefined;
27
29
  /**
28
30
  * `local` is set to `true` when testing your function locally.
29
31
  * i.e. `sanity function test func-name`
@@ -58,6 +60,8 @@ export interface FunctionContext {
58
60
  * The context object passed to the schedule function handler.
59
61
  */
60
62
  export interface ScheduledFunctionContext {
63
+ /** Sanity lineage token */
64
+ lineage?: string | undefined;
61
65
  /**
62
66
  * `local` is set to `true` when testing your function locally.
63
67
  * i.e. `sanity function test func-name`
@@ -224,14 +228,85 @@ export type FunctionResourceEnvelope = {
224
228
  [P in Exclude<FunctionResourceKey, K>]?: FunctionResource;
225
229
  };
226
230
  }[FunctionResourceKey];
231
+ type DurableLogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
232
+ /**
233
+ * Context logger interface for durables.
234
+ * Exposes console.log through the durable context.
235
+ * @alpha Using durables is considered experimental and may change in the future.
236
+ * @hidden
237
+ */
238
+ interface DurableLogger {
239
+ log?(level: DurableLogLevel, ...params: unknown[]): void;
240
+ debug(...params: unknown[]): void;
241
+ info(...params: unknown[]): void;
242
+ warn(...params: unknown[]): void;
243
+ error(...params: unknown[]): void;
244
+ }
245
+ /**
246
+ * @alpha Using durables is considered experimental and may change in the future.
247
+ * @hidden
248
+ */
249
+ export type DurableContext = FunctionContext & {
250
+ /**
251
+ * Durable logger
252
+ */
253
+ log: DurableLogger;
254
+ /**
255
+ * Current attempt of the active durable operation.
256
+ * Only available in methods that expose the attempt like `waitForCondition`
257
+ */
258
+ attempt?: number;
259
+ /**
260
+ * Unique ID for a durable execution
261
+ */
262
+ runId?: string;
263
+ };
227
264
  /**
228
- * The interface defining the operations available to a pipeline function.
265
+ * The signature of the duration object passed to the `wait` method of a durable function.
266
+ * It can be specified in days, hours, minutes, or seconds.
267
+ * @alpha Using durables is considered experimental and may change in the future.
268
+ * @hidden
269
+ */
270
+ export type DurableDuration = {
271
+ days: number;
272
+ hours?: number;
273
+ minutes?: number;
274
+ seconds?: number;
275
+ } | {
276
+ hours: number;
277
+ minutes?: number;
278
+ seconds?: number;
279
+ } | {
280
+ minutes: number;
281
+ seconds?: number;
282
+ } | {
283
+ seconds: number;
284
+ };
285
+ /**
286
+ * @alpha Using durables is considered experimental and may change in the future.
287
+ * @hidden
288
+ */
289
+ export type DurableWaitForConditionDecision = {
290
+ shouldContinue: true;
291
+ delay: DurableDuration;
292
+ } | {
293
+ shouldContinue: false;
294
+ };
295
+ /**
296
+ * @alpha Using durables is considered experimental and may change in the future.
297
+ * @hidden
298
+ */
299
+ export interface DurableWaitForConditionOptions<T> {
300
+ initial: T;
301
+ next: (state: T, context: DurableContext) => DurableWaitForConditionDecision;
302
+ }
303
+ /**
304
+ * The interface defining the operations available to a durable function.
229
305
  * 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
306
+ * @alpha Using durables is considered experimental and may change in the future.
232
307
  * @hidden
233
308
  */
234
- export interface PipelineOperations {
309
+ export interface DurableOperations {
235
310
  /**
236
311
  * Runs a named step. Its result is recorded, so if the workflow re-runs the step
237
312
  * is not executed again. Failures are retried on their own.
@@ -241,7 +316,7 @@ export interface PipelineOperations {
241
316
  * @param fn - function being executed
242
317
  * @returns The value returned by the executed function
243
318
  */
244
- run<T>(name: string, fn: () => T | Promise<T>): Promise<T>;
319
+ run<T>(name: string, fn: (ctx: DurableContext) => T | Promise<T>): Promise<T>;
245
320
  /**
246
321
  * Calls another function and awaits its result.
247
322
  * similar to ctx.invoke()
@@ -256,18 +331,145 @@ export interface PipelineOperations {
256
331
  * similar to ctx.waitForCallback()
257
332
  * @remarks cannot be nested inside another step
258
333
  * @param name - Step name
259
- * @param fn -Receives the generated callbackId and returns a delivered promise
334
+ * @param fn - Receives the generated callbackId and returns a delivered promise
260
335
  * @returns The value returned by the executed function
261
336
  */
262
- waitForCallback<T>(name: string, fn: (callbackId: string) => Promise<void>): Promise<T>;
337
+ waitForCallback<T>(name: string, fn: (callbackId: string, ctx: DurableContext) => Promise<void>): Promise<T>;
338
+ /**
339
+ * Waits for a specified duration
340
+ * similar to ctx.wait()
341
+ * @remarks cannot be nested inside another step
342
+ * @example
343
+ * Wait for 30 seconds
344
+ * ```ts
345
+ * await step.wait('wait30Sec', { seconds: 30 });
346
+ * ```
347
+ * Wait for 2 days and 3 hours
348
+ * ```ts
349
+ * await step.wait('waitALongTime', { days: 2, hours: 3 });
350
+ * ```
351
+ * @param name - Step name
352
+ * @param duration - Amount of time the function will wait before continuing.
353
+ * Duration is an object with properties of `seconds`, `minutes`, `hours`, or `days`. Must be at least {seconds: 1}
354
+ * @returns Resolves after the duration
355
+ */
356
+ wait(name: string, duration: DurableDuration): Promise<void>;
357
+ /**
358
+ * Waits for a specified duration
359
+ * similar to ctx.wait()
360
+ * @remarks cannot be nested inside another step
361
+ * @example
362
+ * Wait for 30 seconds
363
+ * ```ts
364
+ * await step.wait({ seconds: 30 });
365
+ * ```
366
+ * @param duration - Amount of time the function will wait before continuing.
367
+ * Duration is an object with properties of `seconds`, `minutes`, `hours`, or `days`. Must be at least {seconds: 1}
368
+ * @returns Resolves after the duration
369
+ */
370
+ wait(duration: DurableDuration): Promise<void>;
371
+ /**
372
+ * Waits for a specified condition to be met
373
+ * similar to ctx.waitForCondition()
374
+ * @remarks cannot be nested inside another step
375
+ * @example
376
+ * ```ts
377
+ * await step.waitForCondition(
378
+ * 'waitForCondition',
379
+ * async (state, context) => {
380
+ * context.log.info('Checking for article', {
381
+ * runId: context.runId,
382
+ * attempt: context.attempt,
383
+ * })
384
+ *
385
+ * const client = createClient({
386
+ * apiVersion: '2026-08-05',
387
+ * ...context.clientOptions,
388
+ * })
389
+ * const article = await client.fetch<Article | null>(
390
+ * '*[_type == "article"][0]',
391
+ * )
392
+ * return {...state, article}
393
+ * },
394
+ * {
395
+ * initial: {
396
+ * article: null as Article | null,
397
+ * },
398
+ * next: (state, context) => {
399
+ * if (state.article) return {shouldContinue: false}
400
+ *
401
+ * return {
402
+ * shouldContinue: true,
403
+ * delay: {
404
+ * seconds: Math.min((context.attempt ?? 1) * 2, 60),
405
+ * },
406
+ * }
407
+ * },
408
+ * },
409
+ * )
410
+ * ```
411
+ * @param name - Step name
412
+ * @param fn - Called on each attempt with the current state and durable context.
413
+ * Returns a promise resolving to the updated state,
414
+ * which is passed to next to determine whether the condition has been met or another check should be scheduled.
415
+ * @param options - Configuration options for the condition
416
+ * @returns The value returned by the executed function
417
+ */
418
+ waitForCondition<T>(name: string, fn: (state: T, context: DurableContext) => Promise<T>, options: DurableWaitForConditionOptions<T>): Promise<T>;
419
+ /**
420
+ * Waits for a specified condition to be met
421
+ * similar to ctx.waitForCondition()
422
+ * @remarks cannot be nested inside another step
423
+ * @example
424
+ * ```ts
425
+ * await step.waitForCondition(
426
+ * async (state, context) => {
427
+ * context.log.info('Checking for article', {
428
+ * runId: context.runId,
429
+ * attempt: context.attempt,
430
+ * })
431
+ *
432
+ * const client = createClient({
433
+ * apiVersion: '2026-08-05',
434
+ * ...context.clientOptions,
435
+ * })
436
+ * const article = await client.fetch<Article | null>(
437
+ * '*[_type == "article"][0]',
438
+ * )
439
+ * return {...state, article}
440
+ * },
441
+ * {
442
+ * initial: {
443
+ * article: null as Article | null,
444
+ * },
445
+ * next: (state, context) => {
446
+ * if (state.article) return {shouldContinue: false}
447
+ *
448
+ * return {
449
+ * shouldContinue: true,
450
+ * delay: {
451
+ * seconds: Math.min((context.attempt ?? 1) * 2, 60),
452
+ * },
453
+ * }
454
+ * },
455
+ * },
456
+ * )
457
+ * ```
458
+ * @param fn - Called on each attempt with the current state and durable context.
459
+ * Returns a promise resolving to the updated state,
460
+ * which is passed to next to determine whether the condition has been met or another check should be scheduled.
461
+ * @param options - Configuration options for the condition
462
+ * @returns The value returned by the executed function
463
+ */
464
+ waitForCondition<T>(fn: (state: T, context: DurableContext) => Promise<T>, options: DurableWaitForConditionOptions<T>): Promise<T>;
263
465
  }
264
466
  /**
265
- * @alpha Using pipeline functions is considered experimental and may change in the future.
467
+ * @alpha Using durables is considered experimental and may change in the future.
266
468
  * @hidden
267
469
  */
268
- export type PipelineHandler = (envelope: {
269
- context: FunctionContext;
470
+ export type DurableHandler = (envelope: {
471
+ context: DurableContext;
270
472
  event?: GenericEvent;
271
- step: PipelineOperations;
473
+ step: DurableOperations;
272
474
  }) => unknown | Promise<unknown>;
273
475
  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.1",
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
  *
@@ -53,6 +112,8 @@ async function getResource(name: string, aws: awsLite.AwsLiteClient): Promise<Fu
53
112
  * event source and nothing is returned. Pass `{sync: true}` to invoke the function and
54
113
  * wait for its return value.
55
114
  *
115
+ * @alpha Experimental / preview function not ready for use
116
+ * @hidden
56
117
  * @param name - Name of the function to invoke
57
118
  * @param payload - The `{event, context}` envelope to deliver
58
119
  * @param options - Set `sync: true` to wait for and return the function's result
@@ -63,16 +124,22 @@ export async function invoke<T = unknown>(name: string, payload: FunctionPayload
63
124
  if (!name) throw new Error('Function name was not provided')
64
125
  const sync = options?.sync ?? false
65
126
 
66
- const stringPayload = JSON.stringify(payload)
127
+ // Update lineage or throw error if we exceed the max recursion value
128
+ const outgoingPayload: FunctionPayload = {
129
+ ...payload,
130
+ context: {...payload.context, lineage: buildLineageToken(name, payload.context?.lineage)},
131
+ }
132
+
133
+ const stringPayload = JSON.stringify(outgoingPayload)
67
134
  // Check to make sure payload is not over the max we can handle
68
135
  checkPayloadSize(stringPayload, sync)
69
136
 
70
137
  // Local invoke path for Sanity CLI
71
- if (payload?.context?.local) {
72
- if (!payload?.context?.invoke) {
138
+ if (outgoingPayload?.context?.local) {
139
+ if (!outgoingPayload?.context?.invoke) {
73
140
  throw new Error(`No local invoke handler configured for function: ${name}`)
74
141
  }
75
- return await payload.context.invoke(name, payload, options)
142
+ return await outgoingPayload.context.invoke(name, outgoingPayload, options)
76
143
  }
77
144
 
78
145
  const aws = await getAwsLite()
@@ -80,15 +147,19 @@ export async function invoke<T = unknown>(name: string, payload: FunctionPayload
80
147
 
81
148
  // Look up the function details
82
149
  const resource = await getResource(name, aws)
150
+ const contextResource = payload?.context?.resources?.(name)
83
151
 
84
152
  // Synchronous invocation
85
153
  if (sync === true) {
86
- if (!resource.function) {
154
+ if (!resource.function || !contextResource) {
87
155
  throw new Error(`Function ${name} cannot be invoked synchronously.`)
88
156
  }
157
+ if (contextResource.type !== 'sanity.function.pubsub') {
158
+ throw new Error(`Function ${name} of type ${contextResource.type} cannot be invoked synchronously.`)
159
+ }
89
160
  const {Payload, FunctionError} = await aws.Lambda.Invoke({
90
161
  FunctionName: resource.function.physicalResourceId,
91
- Payload: payload,
162
+ Payload: outgoingPayload,
92
163
  InvocationType: 'RequestResponse',
93
164
  })
94
165
  if (FunctionError) {
@@ -100,28 +171,23 @@ export async function invoke<T = unknown>(name: string, payload: FunctionPayload
100
171
  }
101
172
 
102
173
  // Async invocation by type
103
- if (resource.topic) {
174
+ if (resource.topic && contextResource?.type === 'sanity.function.pubsub') {
104
175
  await aws.SNS.Publish({
105
176
  TopicArn: resource.topic.physicalResourceId,
106
177
  Message: stringPayload,
107
178
  })
108
- } else if (resource.queue) {
179
+ } else if (resource.queue && contextResource?.type === 'sanity.function.queue') {
109
180
  await aws.SQS.SendMessage({
110
181
  MessageBody: stringPayload,
111
182
  QueueUrl: resource.queue.physicalResourceId,
112
183
  })
113
- } else if (resource.function) {
114
- await aws.Lambda.Invoke({
115
- FunctionName: resource.function.physicalResourceId,
116
- Payload: payload,
117
- InvocationType: 'Event',
118
- })
119
184
  } else {
120
185
  throw new Error(`No invokeable resource for function: ${name}`)
121
186
  }
122
187
  return
123
188
  }
124
189
 
190
+ /** @internal */
125
191
  function checkPayloadSize(payload: string, sync: boolean) {
126
192
  if (sync) {
127
193
  if (Buffer.byteLength(payload, 'utf8') > 6 * 1024 * 1024) {