@sanity/functions 1.4.0 → 1.5.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
@@ -1,7 +1,13 @@
1
1
  /**
2
2
  * Callback provided by Sanity CLI when doing local development
3
3
  */
4
- export type InvokeCallback = (name: string, payload: FunctionPayload) => Promise<void>;
4
+ export type InvokeCallback = <T = unknown>(name: string, payload: FunctionPayload, options?: InvokeOptions) => Promise<T>;
5
+ /**
6
+ * Options provided to invoke
7
+ */
8
+ export type InvokeOptions = {
9
+ sync?: boolean;
10
+ };
5
11
  /**
6
12
  * The context object passed to the function handler.
7
13
  */
@@ -14,6 +20,10 @@ export interface FunctionContext {
14
20
  functionResourceType: string;
15
21
  /** The resource ID of the function container; resource ID that houses the function. */
16
22
  functionResourceId: string;
23
+ /**
24
+ * uniqueId for a pipeline run
25
+ */
26
+ runId?: string;
17
27
  /**
18
28
  * `local` is set to `true` when testing your function locally.
19
29
  * i.e. `sanity function test func-name`
@@ -214,4 +224,50 @@ export type FunctionResourceEnvelope = {
214
224
  [P in Exclude<FunctionResourceKey, K>]?: FunctionResource;
215
225
  };
216
226
  }[FunctionResourceKey];
227
+ /**
228
+ * The interface defining the operations available to a pipeline function.
229
+ * 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
232
+ * @hidden
233
+ */
234
+ export interface PipelineOperations {
235
+ /**
236
+ * Runs a named step. Its result is recorded, so if the workflow re-runs the step
237
+ * is not executed again. Failures are retried on their own.
238
+ * similar to ctx.step()
239
+ * @remarks cannot be nested inside another step
240
+ * @param name - Step name
241
+ * @param fn - function being executed
242
+ * @returns The value returned by the executed function
243
+ */
244
+ run<T>(name: string, fn: () => T | Promise<T>): Promise<T>;
245
+ /**
246
+ * Calls another function and awaits its result.
247
+ * similar to ctx.invoke()
248
+ * @remarks cannot be nested inside another step
249
+ * @param name - Step name
250
+ * @param input - Data passed to the called function
251
+ * @returns The value returned by the called function
252
+ */
253
+ delegate<T>(name: string, input?: unknown): Promise<T>;
254
+ /**
255
+ * Waits for an external callback
256
+ * similar to ctx.waitForCallback()
257
+ * @remarks cannot be nested inside another step
258
+ * @param name - Step name
259
+ * @param fn -Receives the generated callbackId and returns a delivered promise
260
+ * @returns The value returned by the executed function
261
+ */
262
+ waitForCallback<T>(name: string, fn: (callbackId: string) => Promise<void>): Promise<T>;
263
+ }
264
+ /**
265
+ * @alpha Using pipeline functions is considered experimental and may change in the future.
266
+ * @hidden
267
+ */
268
+ export type PipelineHandler = (envelope: {
269
+ context: FunctionContext;
270
+ event?: GenericEvent;
271
+ step: PipelineOperations;
272
+ }) => unknown | Promise<unknown>;
217
273
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/functions",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Helper methods and type definitions for Sanity Functions",
5
5
  "keywords": [
6
6
  "sanity",
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './definers.js'
2
2
  export * from './invoke.js'
3
+ export * from './pipelines.js'
3
4
  export * from './types.js'
package/src/invoke.ts CHANGED
@@ -1,9 +1,7 @@
1
1
  import {Buffer} from 'node:buffer'
2
2
  import {env} from 'node:process'
3
3
  import type awsLite from '@aws-lite/client'
4
- import type {FunctionPayload, FunctionResourceEnvelope} from './types.js'
5
-
6
- const MAX_EVENT_SIZE_BYTES = 256 * 1024
4
+ import type {FunctionPayload, FunctionResourceEnvelope, InvokeOptions} from './types.js'
7
5
 
8
6
  let awsPromise: Promise<awsLite.AwsLiteClient> | undefined
9
7
 
@@ -48,22 +46,33 @@ async function getResource(name: string, aws: awsLite.AwsLiteClient): Promise<Fu
48
46
  return result.Item['resources'] as unknown as FunctionResourceEnvelope
49
47
  }
50
48
 
51
- export async function invoke(name: string, payload: FunctionPayload) {
49
+ /**
50
+ * Invokes another Sanity Function.
51
+ *
52
+ * By default the invocation is async: the payload is handed off to the function's
53
+ * event source and nothing is returned. Pass `{sync: true}` to invoke the function and
54
+ * wait for its return value.
55
+ *
56
+ * @param name - Name of the function to invoke
57
+ * @param payload - The `{event, context}` envelope to deliver
58
+ * @param options - Set `sync: true` to wait for and return the function's result
59
+ */
60
+ export async function invoke<T = unknown>(name: string, payload: FunctionPayload, options: InvokeOptions & {sync: true}): Promise<T>
61
+ export async function invoke(name: string, payload: FunctionPayload, options?: InvokeOptions & {sync?: false}): Promise<void>
62
+ export async function invoke<T = unknown>(name: string, payload: FunctionPayload, options?: InvokeOptions): Promise<T | undefined> {
52
63
  if (!name) throw new Error('Function name was not provided')
64
+ const sync = options?.sync ?? false
53
65
 
54
66
  const stringPayload = JSON.stringify(payload)
55
67
  // Check to make sure payload is not over the max we can handle
56
- if (Buffer.byteLength(stringPayload, 'utf8') > MAX_EVENT_SIZE_BYTES) {
57
- throw new Error(`Payload exceeds maximum size of ${MAX_EVENT_SIZE_BYTES / 1024}KB`)
58
- }
68
+ checkPayloadSize(stringPayload, sync)
59
69
 
60
70
  // Local invoke path for Sanity CLI
61
71
  if (payload?.context?.local) {
62
72
  if (!payload?.context?.invoke) {
63
73
  throw new Error(`No local invoke handler configured for function: ${name}`)
64
74
  }
65
- payload.context.invoke(name, payload)
66
- return
75
+ return await payload.context.invoke(name, payload, options)
67
76
  }
68
77
 
69
78
  const aws = await getAwsLite()
@@ -72,7 +81,25 @@ export async function invoke(name: string, payload: FunctionPayload) {
72
81
  // Look up the function details
73
82
  const resource = await getResource(name, aws)
74
83
 
75
- // Determine which method to invoke the function
84
+ // Synchronous invocation
85
+ if (sync === true) {
86
+ if (!resource.function) {
87
+ throw new Error(`Function ${name} cannot be invoked synchronously.`)
88
+ }
89
+ const {Payload, FunctionError} = await aws.Lambda.Invoke({
90
+ FunctionName: resource.function.physicalResourceId,
91
+ Payload: payload,
92
+ InvocationType: 'RequestResponse',
93
+ })
94
+ if (FunctionError) {
95
+ const detail = typeof Payload === 'object' && Payload !== null ? (Payload as {errorMessage?: string}).errorMessage : undefined
96
+ throw new Error(`Function ${name} failed: ${detail ?? FunctionError}`)
97
+ }
98
+ // TODO: can we not type cast? might be an aws-lite issue, why is the return type UInt8BlobAdapter
99
+ return Payload as T
100
+ }
101
+
102
+ // Async invocation by type
76
103
  if (resource.topic) {
77
104
  await aws.SNS.Publish({
78
105
  TopicArn: resource.topic.physicalResourceId,
@@ -92,4 +119,17 @@ export async function invoke(name: string, payload: FunctionPayload) {
92
119
  } else {
93
120
  throw new Error(`No invokeable resource for function: ${name}`)
94
121
  }
122
+ return
123
+ }
124
+
125
+ function checkPayloadSize(payload: string, sync: boolean) {
126
+ if (sync) {
127
+ if (Buffer.byteLength(payload, 'utf8') > 6 * 1024 * 1024) {
128
+ throw new Error(`Payload exceeds maximum size of 6MB`)
129
+ }
130
+ } else {
131
+ if (Buffer.byteLength(payload, 'utf8') > 256 * 1024) {
132
+ throw new Error(`Payload exceeds maximum size of 256KB`)
133
+ }
134
+ }
95
135
  }
@@ -0,0 +1,107 @@
1
+ import type {PipelineHandler} from './types'
2
+
3
+ /**
4
+ * Determine if `createPipeline({}, () => {})` or `createPipeline(() => {})`.
5
+ * @param configOrHandler
6
+ * @param maybeHandler
7
+ * @returns resolved arguments
8
+ */
9
+ const resolveFuncArgs = <TConfig extends {name: string}>(
10
+ configOrHandler: TConfig | PipelineHandler,
11
+ maybeHandler?: PipelineHandler,
12
+ ): {config?: TConfig; handler?: PipelineHandler; hadConfigArg: boolean} => {
13
+ return typeof configOrHandler === 'function'
14
+ ? {config: undefined, handler: configOrHandler, hadConfigArg: false}
15
+ : {config: configOrHandler, handler: maybeHandler, hadConfigArg: true}
16
+ }
17
+
18
+ /**
19
+ * Validates the config to ensure config contains proper elements
20
+ * @param config
21
+ * @returns Errors while validating a config object
22
+ */
23
+ const validateConfig = (config: unknown) => {
24
+ const EVENT_TYPES = ['document', 'media-library', 'cron', 'sync-tag-invalidate']
25
+ const errors: string[] = []
26
+
27
+ if (config === undefined || config === null) {
28
+ errors.push('`config` must be defined')
29
+ return errors
30
+ }
31
+ if (typeof config !== 'object') {
32
+ errors.push('`config` must be an object')
33
+ return errors
34
+ }
35
+
36
+ const name = 'name' in config ? config.name : undefined
37
+ const event = 'event' in config ? config.event : undefined
38
+ if (typeof name !== 'string') errors.push('`config.name` must be a string')
39
+
40
+ if ('event' in config) {
41
+ if (typeof event !== 'object' || event === null) {
42
+ errors.push('`event` must be an object')
43
+ } else if ('type' in event) {
44
+ if (typeof event.type !== 'string') {
45
+ errors.push('`event.type` must be defined')
46
+ } else if (!EVENT_TYPES.includes(event.type)) {
47
+ errors.push(`\`event.type\` must be one of: ${EVENT_TYPES.join(', ')}`)
48
+ }
49
+ }
50
+ }
51
+ return errors
52
+ }
53
+
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.
57
+ * @hidden
58
+ * @param handler
59
+ * @returns The handler function, unmodified.
60
+ */
61
+ export function createPipeline(handler: PipelineHandler): PipelineHandler & {config?: undefined}
62
+
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.
66
+ * @hidden
67
+ * @param config
68
+ * @param handler
69
+ * @returns The handler function, unmodified and the provided config object.
70
+ */
71
+ export function createPipeline<TConfig extends {name: string}>(
72
+ config: TConfig,
73
+ handler: PipelineHandler,
74
+ ): PipelineHandler & {config: TConfig}
75
+
76
+ /**
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.
79
+ * @hidden
80
+ * @public
81
+ * @param configOrHandler
82
+ * @param maybeHandler
83
+ * @returns The handler function, unmodified and the config object if provided
84
+ */
85
+ export function createPipeline<TConfig extends {name: string}>(
86
+ configOrHandler: TConfig | PipelineHandler,
87
+ maybeHandler?: PipelineHandler,
88
+ ): PipelineHandler {
89
+ const {config, handler, hadConfigArg} = resolveFuncArgs(configOrHandler, maybeHandler)
90
+ const errors = [
91
+ ...(hadConfigArg ? validateConfig(config) : []),
92
+ ...(typeof handler !== 'function' ? ['`handler` must be a function'] : []),
93
+ ]
94
+
95
+ if (errors.length > 0) {
96
+ throw new TypeError(errors.join(', '))
97
+ }
98
+ // Separate config from the handler during build
99
+ return Object.assign(handler as PipelineHandler, {config})
100
+ }
101
+
102
+ /**
103
+ * @alpha Pipelines are an experimental feature and may change in the future.
104
+ * @hidden
105
+ * @public
106
+ */
107
+ export const pipeline = {createPipeline}
package/src/types.ts CHANGED
@@ -1,7 +1,15 @@
1
1
  /**
2
2
  * Callback provided by Sanity CLI when doing local development
3
3
  */
4
- export type InvokeCallback = (name: string, payload: FunctionPayload) => Promise<void>
4
+ export type InvokeCallback = <T = unknown>(name: string, payload: FunctionPayload, options?: InvokeOptions) => Promise<T>
5
+
6
+ /**
7
+ * Options provided to invoke
8
+ */
9
+ export type InvokeOptions = {
10
+ // Whether the function should be invoked synchronously
11
+ sync?: boolean
12
+ }
5
13
 
6
14
  /**
7
15
  * The context object passed to the function handler.
@@ -15,6 +23,10 @@ export interface FunctionContext {
15
23
  functionResourceType: string
16
24
  /** The resource ID of the function container; resource ID that houses the function. */
17
25
  functionResourceId: string
26
+ /**
27
+ * uniqueId for a pipeline run
28
+ */
29
+ runId?: string
18
30
  /**
19
31
  * `local` is set to `true` when testing your function locally.
20
32
  * i.e. `sanity function test func-name`
@@ -221,3 +233,53 @@ type FunctionResourceKey = 'eventsourcemapping' | 'function' | 'parameter' | 'qu
221
233
  export type FunctionResourceEnvelope = {
222
234
  [K in FunctionResourceKey]-?: {[P in K]: FunctionResource} & {[P in Exclude<FunctionResourceKey, K>]?: FunctionResource}
223
235
  }[FunctionResourceKey]
236
+
237
+ /**
238
+ * The interface defining the operations available to a pipeline function.
239
+ * These operations are steps that delegate to other functions, and wait for external callbacks.
240
+ * @alpha Using pipeline functions is considered experimental and may change in the future.
241
+ * @public
242
+ * @hidden
243
+ */
244
+ export interface PipelineOperations {
245
+ /**
246
+ * Runs a named step. Its result is recorded, so if the workflow re-runs the step
247
+ * is not executed again. Failures are retried on their own.
248
+ * similar to ctx.step()
249
+ * @remarks cannot be nested inside another step
250
+ * @param name - Step name
251
+ * @param fn - function being executed
252
+ * @returns The value returned by the executed function
253
+ */
254
+ run<T>(name: string, fn: () => T | Promise<T>): Promise<T>
255
+ /**
256
+ * Calls another function and awaits its result.
257
+ * similar to ctx.invoke()
258
+ * @remarks cannot be nested inside another step
259
+ * @param name - Step name
260
+ * @param input - Data passed to the called function
261
+ * @returns The value returned by the called function
262
+ */
263
+ delegate<T>(name: string, input?: unknown): Promise<T>
264
+
265
+ /**
266
+ * Waits for an external callback
267
+ * similar to ctx.waitForCallback()
268
+ * @remarks cannot be nested inside another step
269
+ * @param name - Step name
270
+ * @param fn -Receives the generated callbackId and returns a delivered promise
271
+ * @returns The value returned by the executed function
272
+ */
273
+ waitForCallback<T>(name: string, fn: (callbackId: string) => Promise<void>): Promise<T>
274
+ // @todo: other methods wanted for durables
275
+ }
276
+
277
+ /**
278
+ * @alpha Using pipeline functions is considered experimental and may change in the future.
279
+ * @hidden
280
+ */
281
+ export type PipelineHandler = (envelope: {
282
+ context: FunctionContext
283
+ event?: GenericEvent
284
+ step: PipelineOperations
285
+ }) => unknown | Promise<unknown>