@sanity/functions 1.6.8 → 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,471 +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 {
209
- id: string
210
- name: string
211
- type: string
212
- }
213
- export interface ResourcesApi {
214
- /** Cross-type lookup by name: `context.resources('my-proj')`. */
215
- (name: string): BlueprintResource | undefined
216
- /** Flat array of every resource across types. */
217
- all(): BlueprintResource[]
218
- /** Iterate every resource: `for (const r of context.resources)`. */
219
- [Symbol.iterator](): IterableIterator<BlueprintResource>
220
- /** Type specific lookup by name: `context.cors('my-cors')` */
221
- cors(name: string): BlueprintResource | undefined
222
- dataset(name: string): BlueprintResource | undefined
223
- function(name: string): BlueprintResource | undefined
224
- project(name: string): BlueprintResource | undefined
225
- role(name: string): BlueprintResource | undefined
226
- webhook(name: string): BlueprintResource | undefined
227
- }
228
-
229
- /**
230
- * The payload for the `invoke` method
231
- */
232
- export type FunctionPayload = {
233
- event: GenericEvent
234
- context: GenericContext
235
- }
236
-
237
- /**
238
- * The definition of a function resource in our resource discovery table
239
- */
240
- export type FunctionResource = {
241
- logicalResourceId: string
242
- physicalResourceId: string
243
- }
244
-
245
- type FunctionResourceKey = 'eventsourcemapping' | 'function' | 'parameter' | 'queue' | 'schedule' | 'subscription' | 'topic'
246
-
247
- export type FunctionResourceEnvelope = {
248
- [K in FunctionResourceKey]-?: {[P in K]: FunctionResource} & {[P in Exclude<FunctionResourceKey, K>]?: FunctionResource}
249
- }[FunctionResourceKey]
250
-
251
- /**
252
- * Durable alias of FunctionsContext
253
- * @alpha Using durables is considered experimental and may change in the future.
254
- * @hidden
255
- */
256
- export type DurableContext = FunctionContext
257
-
258
- /**
259
- * Logger interface for durables.
260
- * @alpha Using durables is considered experimental and may change in the future.
261
- * @hidden
262
- */
263
- export interface DurableLogger {
264
- debug(...params: unknown[]): void
265
- info(...params: unknown[]): void
266
- warn(...params: unknown[]): void
267
- error(...params: unknown[]): void
268
- log(...params: unknown[]): void
269
- }
270
-
271
- /**
272
- * @alpha Using durables is considered experimental and may change in the future.
273
- * @hidden
274
- */
275
- export interface DurableStepCallbackContext {
276
- logger: DurableLogger
277
- }
278
-
279
- /**
280
- * Arguments passed to callbacks that execute a durable attempt.
281
- * step.run & step.waitForCondition
282
- * @alpha Using durables is considered experimental and may change in the future.
283
- * @hidden
284
- */
285
- export interface DurableStepAttemptContext extends DurableStepCallbackContext {
286
- /** Current attempt number, starting at 1. */
287
- attempt: number
288
- }
289
-
290
- /**
291
- * The signature of the duration object passed to the `wait` method of a durable function.
292
- * It can be specified in days, hours, minutes, or seconds.
293
- * @alpha Using durables is considered experimental and may change in the future.
294
- * @hidden
295
- */
296
- export type DurableDuration =
297
- | {days: number; hours?: number; minutes?: number; seconds?: number}
298
- | {hours: number; minutes?: number; seconds?: number}
299
- | {minutes: number; seconds?: number}
300
- | {seconds: number}
301
-
302
- /**
303
- * @alpha Using durables is considered experimental and may change in the future.
304
- * @hidden
305
- */
306
- export type DurableWaitForConditionDecision = {shouldRetry: true; delay: DurableDuration} | {shouldRetry: false}
307
-
308
- /**
309
- * @alpha Using durables is considered experimental and may change in the future.
310
- * @hidden
311
- */
312
- export type DurableStepHandler<TArgs extends unknown[], TReturn> = (...args: TArgs) => TReturn
313
-
314
- /**
315
- * @alpha Using durables is considered experimental and may change in the future.
316
- * @hidden
317
- */
318
- export type DurableStepRunHandler<T = unknown> = DurableStepHandler<[context: DurableStepAttemptContext], T | Promise<T>>
319
-
320
- /**
321
- * @alpha Using durables is considered experimental and may change in the future.
322
- * @hidden
323
- */
324
- export type DurableStepWaitForCallbackHandler = DurableStepHandler<[callbackId: string, context: DurableStepCallbackContext], Promise<void>>
325
-
326
- /**
327
- * @alpha Using durables is considered experimental and may change in the future.
328
- * @hidden
329
- */
330
- export type DurableWaitForConditionPoller<T = unknown> = DurableStepHandler<[state: T, context: DurableStepAttemptContext], Promise<T>>
331
-
332
- /**
333
- * @alpha Using durables is considered experimental and may change in the future.
334
- * @hidden
335
- */
336
- export type DurableWaitForConditionNext<T = unknown> = DurableStepHandler<
337
- [state: T, context: Pick<DurableStepAttemptContext, 'attempt'>],
338
- DurableWaitForConditionDecision
339
- >
340
-
341
- /**
342
- * The interface defining the operations available to a durable function.
343
- * These operations are steps that delegate to other functions, and wait for external callbacks.
344
- * @alpha Using durables is considered experimental and may change in the future.
345
- * @hidden
346
- */
347
- export type DurableOperations = {
348
- /**
349
- * Runs a named step. Its result is recorded, so if the workflow re-runs the step
350
- * is not executed again. Failures are retried on their own.
351
- * similar to ctx.step()
352
- * @remarks cannot be nested inside another step
353
- * @example
354
- * ```ts
355
- * step.run({
356
- * name: 'run-step',
357
- * handler: async ({logger}) => {
358
- * logger.log('Running step')
359
- * }})
360
- * ```
361
- * @param name - Step name
362
- * @param handler - function being executed
363
- * @returns The value returned by the executed function
364
- */
365
- run<T>({name, handler}: {name?: string; handler: DurableStepRunHandler<T>}): Promise<T>
366
-
367
- /**
368
- * Calls another function and awaits its result.
369
- * similar to ctx.invoke()
370
- * @remarks cannot be nested inside another step
371
- * @param name - Step name
372
- * @param input - Data passed to the called function
373
- * @returns The value returned by the called function
374
- */
375
- delegate<T>({name, input}: {name?: string; input?: unknown}): Promise<T>
376
-
377
- /**
378
- * Waits for an external callback
379
- * similar to ctx.waitForCallback()
380
- * @remarks cannot be nested inside another step
381
- * @param name - Step name
382
- * @param handler - Receives the generated callbackId and returns a delivered promise
383
- * @returns The value returned by the executed function
384
- */
385
- waitForCallback<T>({name, handler}: {name?: string; handler: DurableStepWaitForCallbackHandler}): Promise<T>
386
-
387
- /**
388
- * Waits for a specified duration
389
- * similar to ctx.wait()
390
- * @remarks cannot be nested inside another step
391
- * @example
392
- * Wait for 30 seconds
393
- * ```ts
394
- * await step.wait({name: 'wait30Sec', duration: { seconds: 30 }});
395
- * ```
396
- * Wait for 2 days and 3 hours
397
- * ```ts
398
- * await step.wait({name: 'waitALongTime', duration: { days: 2, hours: 3 }});
399
- * ```
400
- * @param name - Step name
401
- * @param duration - Amount of time the function will wait before continuing.
402
- * Duration is an object with properties of `seconds`, `minutes`, `hours`, or `days`. Must be at least {seconds: 1}
403
- * @returns Resolves after the duration
404
- */
405
- wait({name, duration}: {name?: string; duration: DurableDuration}): Promise<void>
406
-
407
- /**
408
- * Waits for a specified condition to be met
409
- * similar to ctx.waitForCondition()
410
- * @remarks cannot be nested inside another step
411
- * @example
412
- * ```ts
413
- * await step.waitForCondition({{
414
- * name: 'waitForCondition',
415
- * initial: {
416
- * article: null,
417
- * },
418
- * poller: async (state, {attempt}) => {
419
- * const client = createClient({
420
- * apiVersion: '2026-08-05',
421
- * ...context.clientOptions,
422
- * })
423
- * const article = await client.fetch<Article | null>(
424
- * '*[_type == "article"][0]',
425
- * )
426
- * return {...state, article}
427
- * }
428
- * next: (state, {attempt}) => {
429
- * if (state.article) return {shouldResume: false}
430
- *
431
- * return {
432
- * shouldResume: true,
433
- * delay: {
434
- * seconds: Math.min(attempt * 2, 60),
435
- * },
436
- * }
437
- * },
438
- * },
439
- * )
440
- * ```
441
- * @param name - Step name
442
- * @param initial - Initial state passed to the first poller call.
443
- * @param poller - Called on each attempt with the current state and condition context.
444
- * @param next - A function that determines whether the condition has been met or another check should be run.
445
- * Returns a promise resolving to the updated state,
446
- * which is passed to next to determine whether the condition has been met or another check should be run.
447
- * @returns The value returned by the executed function
448
- */
449
- waitForCondition<T>({
450
- name,
451
- initial,
452
- next,
453
- poller,
454
- }: {
455
- name?: string
456
- initial: T
457
- poller: DurableWaitForConditionPoller<T>
458
- next: DurableWaitForConditionNext<T>
459
- }): Promise<T>
460
- }
461
-
462
- /**
463
- * @alpha Using durables is considered experimental and may change in the future.
464
- * @hidden
465
- */
466
- export type DurableHandler = (envelope: {
467
- context: DurableContext
468
- event?: GenericEvent
469
- step: DurableOperations
470
- logger: DurableLogger
471
- }) => 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'