@sanity/functions 1.6.9 → 1.7.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/src/types.ts CHANGED
@@ -1,481 +1,5 @@
1
- /**
2
- * Callback provided by Sanity CLI when doing local development.
3
- *
4
- * The CLI receives the event data alone: it delivers it to the target function as
5
- * `event.data` and derives the target's context from the calling function's own context.
6
- */
7
- export type InvokeCallback = <T = unknown>(name: string, payload?: Record<string, unknown>, options?: InvokeOptions) => Promise<T>
8
-
9
- /**
10
- * Options provided to invoke
11
- */
12
- export type InvokeOptions = {
13
- // Whether the function should be invoked synchronously
14
- sync?: boolean
15
- }
16
-
17
- /**
18
- * The context object passed to the function handler.
19
- */
20
- export interface FunctionContext {
21
- /** The resource type of the event source; resource type that invoked the function. */
22
- eventResourceType: string
23
- /** The resource ID of the event source; resource ID that invoked the function. */
24
- eventResourceId: string
25
- /** The resource type of the function container; resource type that houses the function. */
26
- functionResourceType: string
27
- /** The resource ID of the function container; resource ID that houses the function. */
28
- functionResourceId: string
29
- /** Sanity lineage token */
30
- lineage?: string | undefined
31
- /**
32
- * `local` is set to `true` when testing your function locally.
33
- * i.e. `sanity function test func-name`
34
- * Otherwise, the property is not set.
35
- */
36
- local?: boolean
37
- invoke?: InvokeCallback
38
- /**
39
- * Options that can be passed to a `@sanity/client` constructor to configure it
40
- * against the project and dataset which triggered the event. Note that you should
41
- * always specify an explicit `apiVersion` in YYYY-MM-DD format (e.g. `2025-05-01`).
42
- *
43
- * @example
44
- * Constructing a client with the options from the context:
45
- * ```ts
46
- * const client = createClient({
47
- * apiVersion: '2025-05-01',
48
- * ...context.clientOptions,
49
- * })
50
- * ```
51
- */
52
- clientOptions: {
53
- apiHost?: string
54
- dataset: string
55
- projectId: string
56
- token: string
57
- }
58
- /** Resource interface that allows access to Blueprint Resources */
59
- resources: ResourcesApi
60
- }
61
-
62
- /**
63
- * The context object passed to the schedule function handler.
64
- */
65
- export interface ScheduledFunctionContext {
66
- /** Sanity lineage token */
67
- lineage?: string | undefined
68
- /**
69
- * `local` is set to `true` when testing your function locally.
70
- * i.e. `sanity function test func-name`
71
- * Otherwise, the property is not set.
72
- */
73
- local?: boolean
74
- invoke?: InvokeCallback
75
- /**
76
- * Options that can be passed to a `@sanity/client` constructor to configure it
77
- * against the project and dataset which triggered the event. Note that you should
78
- * always specify an explicit `apiVersion` in YYYY-MM-DD format (e.g. `2025-05-01`).
79
- *
80
- * @example
81
- * Constructing a client with the options from the context:
82
- * ```ts
83
- * const client = createClient({
84
- * apiVersion: '2025-05-01',
85
- * ...context.clientOptions,
86
- * })
87
- * ```
88
- */
89
- clientOptions?: {
90
- apiHost?: string
91
- dataset?: string
92
- projectId?: string
93
- token?: string
94
- }
95
- /** Resource interface that allows access to Blueprint Resources */
96
- resources: ResourcesApi
97
- }
98
-
99
- /**
100
- * The event object received by the function handler in the case of a document event,
101
- * such as a publish, unpublish, delete or mutation event and similar.
102
- */
103
- export interface DocumentEvent<IData = any> {
104
- /**
105
- * The data delivered to the function. This is the result of applying any configured
106
- * GROQ-projection to the changed document. If no projection is configured, this is
107
- * the document itself.
108
- */
109
- data: IData
110
- }
111
-
112
- /**
113
- * The event object received by the function handler in the case of a sync-tag-invalidate event.
114
- */
115
- export interface SyncTagInvalidateEvent {
116
- /**
117
- * The sync tags for use with cache invalidation and notifying the callback endpoint once tags are invalidated.
118
- */
119
- data: {
120
- /** Array of sync tags to be invalidated. */
121
- syncTags: string[]
122
- }
123
- }
124
-
125
- /**
126
- * A function handler for a document event.
127
- */
128
- export type DocumentEventHandler<IData = any> = (envelope: {context: FunctionContext; event: DocumentEvent<IData>}) => void | Promise<void>
129
-
130
- /**
131
- * A function handler for a schedule event.
132
- */
133
- export type ScheduledEventHandler = (envelope: {context: ScheduledFunctionContext}) => void | Promise<void>
134
-
135
- /**
136
- * A generic function context type which supports all function types
137
- */
138
- export type GenericContext = FunctionContext | ScheduledFunctionContext | SyncTagInvalidateContext
139
-
140
- /**
141
- * A generic function event type which supports all function types
142
- */
143
- export type GenericEvent = DocumentEvent | SyncTagInvalidateEvent
144
-
145
- /**
146
- * A function handler for a pubsub event.
147
- *
148
- * A pubsub function can be triggered by any event source, so the envelope is intentionally
149
- * permissive and needs no narrowing: `context` is any supported context, `event` is any
150
- * supported event, and `done` is optional (present only for sync-tag-invalidate events).
151
- *
152
- * `IResult` is the value the handler resolves to and defaults to `void`. Pubsub is the one
153
- * function type that may be invoked with {@link invoke | `invoke(name, payload, {sync: true})`},
154
- * which returns the handler's resolved value to the caller.
155
- */
156
- export type PubSubEventHandler<IData = any, IResult = void> = (envelope: {
157
- context: GenericContext
158
- event: DocumentEvent<IData> | SyncTagInvalidateEvent
159
- done?: SyncTagInvalidateCallback
160
- }) => IResult | Promise<IResult>
161
-
162
- /**
163
- * A generic function handler that can receive the payload of any function type.
164
- *
165
- * @deprecated Renamed to {@link PubSubEventHandler}. This alias will be removed in the next
166
- * major version.
167
- */
168
- export type EventHandler<IData = any, IResult = void> = PubSubEventHandler<IData, IResult>
169
-
170
- /**
171
- * A callback function to invoke once a sync-tag-invalidate event has been processed. Signals to Sanity that sync tag invalidation has completed.
172
- */
173
- export type SyncTagInvalidateCallback = (syncTags: string[]) => Promise<Response>
174
-
175
- /**
176
- * The context object passed to the sync tag invalidate event handler.
177
- */
178
- export interface SyncTagInvalidateContext extends Omit<FunctionContext, 'clientOptions'> {
179
- /**
180
- * A short-lived token that should be used to notify Sanity of sync tag invalidation routine completion. Recommended to use the `done` helper argument provided to the sync tag invalidate event handler instead of this token directly.
181
- */
182
- callbackToken: string
183
- clientOptions: {
184
- apiHost: string
185
- dataset: string
186
- projectId: string
187
- /**
188
- * An API token for use with the Sanity HTTP API. Note that it may be undefined if the user does not explicitly assign a Robot Token to their function definition.
189
- * @see https://www.sanity.io/docs/blueprints/blueprints-robot-tokens#k8a2a6a24a5c0
190
- */
191
- token?: string
192
- }
193
- /** Resource interface that allows access to Blueprint Resources */
194
- resources: ResourcesApi
195
- }
196
- /**
197
- * A function handler for a sync-tag-invalidate event.
198
- */
199
- export type SyncTagInvalidateEventHandler = (envelope: {
200
- context: SyncTagInvalidateContext
201
- event: SyncTagInvalidateEvent
202
- done: SyncTagInvalidateCallback
203
- }) => void | Promise<void>
204
-
205
- /**
206
- * An interface to describe resources found in a Blueprint
207
- */
208
- export interface BlueprintResource<TType extends string = string> {
209
- id: string
210
- name: string
211
- type: TType
212
- }
213
-
214
- export interface ResourcesApi {
215
- /** Cross-type lookup by name: `context.resources('my-proj')`. */
216
- (name: string): BlueprintResource | undefined
217
- /** Flat array of every resource across types. */
218
- all(): BlueprintResource[]
219
- /** Iterate every resource: `for (const r of context.resources)`. */
220
- [Symbol.iterator](): IterableIterator<BlueprintResource>
221
- /** Type specific lookup by name: `context.cors('my-cors')` */
222
- cors(name: string): BlueprintResource | undefined
223
- dataset(name: string): BlueprintResource | undefined
224
- function(name: string): BlueprintResource<`sanity.function.${string}`> | undefined
225
- project(name: string): BlueprintResource | undefined
226
- role(name: string): BlueprintResource | undefined
227
- webhook(name: string): BlueprintResource | undefined
228
- }
229
-
230
- /**
231
- * The payload for the `invoke` method
232
- */
233
- export type FunctionPayload = {
234
- event: GenericEvent
235
- context: GenericContext
236
- }
237
-
238
- /**
239
- * The definition of a function resource in our resource discovery table
240
- */
241
- export type FunctionResource = {
242
- logicalResourceId: string
243
- physicalResourceId: string
244
- }
245
-
246
- type FunctionResourceKey = 'eventsourcemapping' | 'function' | 'parameter' | 'queue' | 'schedule' | 'subscription' | 'topic'
247
-
248
- export type FunctionResourceEnvelope = {
249
- [K in FunctionResourceKey]-?: {[P in K]: FunctionResource} & {[P in Exclude<FunctionResourceKey, K>]?: FunctionResource}
250
- }[FunctionResourceKey]
251
-
252
- /**
253
- * Durable alias of FunctionsContext
254
- * @alpha Using durables is considered experimental and may change in the future.
255
- * @hidden
256
- */
257
- export type DurableContext = FunctionContext
258
-
259
- /**
260
- * Logger interface for durables.
261
- * @alpha Using durables is considered experimental and may change in the future.
262
- * @hidden
263
- */
264
- export interface DurableLogger {
265
- debug(...params: unknown[]): void
266
- info(...params: unknown[]): void
267
- warn(...params: unknown[]): void
268
- error(...params: unknown[]): void
269
- log(...params: unknown[]): void
270
- }
271
-
272
- /**
273
- * @alpha Using durables is considered experimental and may change in the future.
274
- * @hidden
275
- */
276
- export interface DurableStepCallbackContext {
277
- logger: DurableLogger
278
- }
279
-
280
- /**
281
- * Arguments passed to callbacks that execute a durable attempt.
282
- * step.run & step.waitForCondition
283
- * @alpha Using durables is considered experimental and may change in the future.
284
- * @hidden
285
- */
286
- export interface DurableStepAttemptContext extends DurableStepCallbackContext {
287
- /** Current attempt number, starting at 1. */
288
- attempt: number
289
- }
290
-
291
- /**
292
- * The signature of the duration object passed to the `wait` method of a durable function.
293
- * It can be specified in days, hours, minutes, or seconds.
294
- * @alpha Using durables is considered experimental and may change in the future.
295
- * @hidden
296
- */
297
- export type DurableDuration =
298
- | {days: number; hours?: number; minutes?: number; seconds?: number}
299
- | {hours: number; minutes?: number; seconds?: number}
300
- | {minutes: number; seconds?: number}
301
- | {seconds: number}
302
-
303
- /**
304
- * @alpha Using durables is considered experimental and may change in the future.
305
- * @hidden
306
- */
307
- export type DurableWaitForConditionDecision = {shouldRetry: true; delay: DurableDuration} | {shouldRetry: false}
308
-
309
- /**
310
- * @alpha Using durables is considered experimental and may change in the future.
311
- * @hidden
312
- */
313
- export type DurableStepHandler<TArgs extends unknown[], TReturn> = (...args: TArgs) => TReturn
314
-
315
- /**
316
- * @alpha Using durables is considered experimental and may change in the future.
317
- * @hidden
318
- */
319
- export type DurableStepRunHandler<T = unknown> = DurableStepHandler<[context: DurableStepAttemptContext], T | Promise<T>>
320
-
321
- /**
322
- * @alpha Using durables is considered experimental and may change in the future.
323
- * @hidden
324
- */
325
- export type DurableStepWaitForCallbackHandler = DurableStepHandler<[callbackId: string, context: DurableStepCallbackContext], Promise<void>>
326
-
327
- /**
328
- * @alpha Using durables is considered experimental and may change in the future.
329
- * @hidden
330
- */
331
- export type DurableWaitForConditionPoller<T = unknown> = DurableStepHandler<[state: T, context: DurableStepAttemptContext], Promise<T>>
332
-
333
- /**
334
- * @alpha Using durables is considered experimental and may change in the future.
335
- * @hidden
336
- */
337
- export type DurableWaitForConditionNext<T = unknown> = DurableStepHandler<
338
- [state: T, context: Pick<DurableStepAttemptContext, 'attempt'>],
339
- DurableWaitForConditionDecision
340
- >
341
-
342
- /**
343
- * The interface defining the operations available to a durable function.
344
- * These operations are steps that delegate to other functions, and wait for external callbacks.
345
- * @alpha Using durables is considered experimental and may change in the future.
346
- * @hidden
347
- */
348
- export type DurableOperations = {
349
- /**
350
- * Runs a named step. Its result is recorded, so if the workflow re-runs the step
351
- * is not executed again. Failures are retried on their own.
352
- * similar to ctx.step()
353
- * @remarks cannot be nested inside another step
354
- * @example
355
- * ```ts
356
- * step.run({
357
- * name: 'run-step',
358
- * handler: async ({logger}) => {
359
- * logger.log('Running step')
360
- * }})
361
- * ```
362
- * @param name - Step name
363
- * @param handler - function being executed
364
- * @returns The value returned by the executed function
365
- */
366
- run<T>({name, handler}: {name?: string; handler: DurableStepRunHandler<T>}): Promise<T>
367
-
368
- /**
369
- * Calls another function and awaits its result.
370
- * similar to ctx.invoke()
371
- * @remarks cannot be nested inside another step
372
- * @param name - Step name
373
- * @param handler - Function to be invoked
374
- * @param input - Data passed to the called function
375
- * @returns The value returned by the called function
376
- */
377
- delegate<T>({
378
- name,
379
- handler,
380
- input,
381
- }: {
382
- name?: string
383
- handler: string | BlueprintResource<`sanity.function.${string}`>
384
- input?: unknown
385
- }): Promise<T>
386
-
387
- /**
388
- * Waits for an external callback
389
- * similar to ctx.waitForCallback()
390
- * @remarks cannot be nested inside another step
391
- * @param name - Step name
392
- * @param handler - Receives the generated callbackId and returns a delivered promise
393
- * @returns The value returned by the executed function
394
- */
395
- waitForCallback<T>({name, handler}: {name?: string; handler: DurableStepWaitForCallbackHandler}): Promise<T>
396
-
397
- /**
398
- * Waits for a specified duration
399
- * similar to ctx.wait()
400
- * @remarks cannot be nested inside another step
401
- * @example
402
- * Wait for 30 seconds
403
- * ```ts
404
- * await step.wait({name: 'wait30Sec', duration: { seconds: 30 }});
405
- * ```
406
- * Wait for 2 days and 3 hours
407
- * ```ts
408
- * await step.wait({name: 'waitALongTime', duration: { days: 2, hours: 3 }});
409
- * ```
410
- * @param name - Step name
411
- * @param duration - Amount of time the function will wait before continuing.
412
- * Duration is an object with properties of `seconds`, `minutes`, `hours`, or `days`. Must be at least {seconds: 1}
413
- * @returns Resolves after the duration
414
- */
415
- wait({name, duration}: {name?: string; duration: DurableDuration}): Promise<void>
416
-
417
- /**
418
- * Waits for a specified condition to be met
419
- * similar to ctx.waitForCondition()
420
- * @remarks cannot be nested inside another step
421
- * @example
422
- * ```ts
423
- * await step.waitForCondition({{
424
- * name: 'waitForCondition',
425
- * initial: {
426
- * article: null,
427
- * },
428
- * poller: async (state, {attempt}) => {
429
- * const client = createClient({
430
- * apiVersion: '2026-08-05',
431
- * ...context.clientOptions,
432
- * })
433
- * const article = await client.fetch<Article | null>(
434
- * '*[_type == "article"][0]',
435
- * )
436
- * return {...state, article}
437
- * }
438
- * next: (state, {attempt}) => {
439
- * if (state.article) return {shouldResume: false}
440
- *
441
- * return {
442
- * shouldResume: true,
443
- * delay: {
444
- * seconds: Math.min(attempt * 2, 60),
445
- * },
446
- * }
447
- * },
448
- * },
449
- * )
450
- * ```
451
- * @param name - Step name
452
- * @param initial - Initial state passed to the first poller call.
453
- * @param poller - Called on each attempt with the current state and condition context.
454
- * @param next - A function that determines whether the condition has been met or another check should be run.
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 run.
457
- * @returns The value returned by the executed function
458
- */
459
- waitForCondition<T>({
460
- name,
461
- initial,
462
- next,
463
- poller,
464
- }: {
465
- name?: string
466
- initial: T
467
- poller: DurableWaitForConditionPoller<T>
468
- next: DurableWaitForConditionNext<T>
469
- }): Promise<T>
470
- }
471
-
472
- /**
473
- * @alpha Using durables is considered experimental and may change in the future.
474
- * @hidden
475
- */
476
- export type DurableHandler = (envelope: {
477
- context: DurableContext
478
- event?: GenericEvent
479
- step: DurableOperations
480
- logger: DurableLogger
481
- }) => unknown | Promise<unknown>
1
+ export * from './types/context'
2
+ export * from './types/durables'
3
+ export * from './types/functions'
4
+ export * from './types/invocation'
5
+ export * from './types/resources'