@sanity/functions 1.3.1 → 1.4.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,9 @@
1
+ /**
2
+ * Callback provided by Sanity CLI when doing local development
3
+ */
4
+ export type InvokeCallback = (name: string, payload: FunctionPayload) => Promise<void>;
1
5
  /**
2
6
  * The context object passed to the function handler.
3
- *
4
- * @beta
5
7
  */
6
8
  export interface FunctionContext {
7
9
  /** The resource type of the event source; resource type that invoked the function. */
@@ -18,6 +20,7 @@ export interface FunctionContext {
18
20
  * Otherwise, the property is not set.
19
21
  */
20
22
  local?: boolean;
23
+ invoke?: InvokeCallback;
21
24
  /**
22
25
  * Options that can be passed to a `@sanity/client` constructor to configure it
23
26
  * against the project and dataset which triggered the event. Note that you should
@@ -31,7 +34,6 @@ export interface FunctionContext {
31
34
  * ...context.clientOptions,
32
35
  * })
33
36
  * ```
34
- * @beta
35
37
  */
36
38
  clientOptions: {
37
39
  apiHost?: string;
@@ -39,11 +41,11 @@ export interface FunctionContext {
39
41
  projectId: string;
40
42
  token: string;
41
43
  };
44
+ /** Resource interface that allows access to Blueprint Resources */
45
+ resources: ResourcesApi;
42
46
  }
43
47
  /**
44
48
  * The context object passed to the schedule function handler.
45
- *
46
- * @beta
47
49
  */
48
50
  export interface ScheduledFunctionContext {
49
51
  /**
@@ -52,6 +54,7 @@ export interface ScheduledFunctionContext {
52
54
  * Otherwise, the property is not set.
53
55
  */
54
56
  local?: boolean;
57
+ invoke?: InvokeCallback;
55
58
  /**
56
59
  * Options that can be passed to a `@sanity/client` constructor to configure it
57
60
  * against the project and dataset which triggered the event. Note that you should
@@ -65,7 +68,6 @@ export interface ScheduledFunctionContext {
65
68
  * ...context.clientOptions,
66
69
  * })
67
70
  * ```
68
- * @beta
69
71
  */
70
72
  clientOptions?: {
71
73
  apiHost?: string;
@@ -73,33 +75,27 @@ export interface ScheduledFunctionContext {
73
75
  projectId?: string;
74
76
  token?: string;
75
77
  };
78
+ /** Resource interface that allows access to Blueprint Resources */
79
+ resources: ResourcesApi;
76
80
  }
77
81
  /**
78
82
  * The event object received by the function handler in the case of a document event,
79
83
  * such as a publish, unpublish, delete or mutation event and similar.
80
- *
81
- * @beta
82
84
  */
83
85
  export interface DocumentEvent<IData = any> {
84
86
  /**
85
87
  * The data delivered to the function. This is the result of applying any configured
86
88
  * GROQ-projection to the changed document. If no projection is configured, this is
87
89
  * the document itself.
88
- *
89
- * @beta
90
90
  */
91
91
  data: IData;
92
92
  }
93
93
  /**
94
94
  * The event object received by the function handler in the case of a sync-tag-invalidate event.
95
- *
96
- * @beta
97
95
  */
98
96
  export interface SyncTagInvalidateEvent {
99
97
  /**
100
98
  * The sync tags for use with cache invalidation and notifying the callback endpoint once tags are invalidated.
101
- *
102
- * @beta
103
99
  */
104
100
  data: {
105
101
  /** Array of sync tags to be invalidated. */
@@ -108,8 +104,6 @@ export interface SyncTagInvalidateEvent {
108
104
  }
109
105
  /**
110
106
  * A function handler for a document event.
111
- *
112
- * @beta
113
107
  */
114
108
  export type DocumentEventHandler<IData = any> = (envelope: {
115
109
  context: FunctionContext;
@@ -117,22 +111,37 @@ export type DocumentEventHandler<IData = any> = (envelope: {
117
111
  }) => void | Promise<void>;
118
112
  /**
119
113
  * A function handler for a schedule event.
120
- *
121
- * @beta
122
114
  */
123
115
  export type ScheduledEventHandler = (envelope: {
124
116
  context: ScheduledFunctionContext;
125
117
  }) => void | Promise<void>;
126
118
  /**
127
- * A callback function to invoke once a sync-tag-invalidate event has been processed. Signals to Sanity that sync tag invalidation has completed.
119
+ * A generic function context type which supports all function types
120
+ */
121
+ export type GenericContext = FunctionContext | ScheduledFunctionContext | SyncTagInvalidateContext;
122
+ /**
123
+ * A generic function event type which supports all function types
124
+ */
125
+ export type GenericEvent = DocumentEvent | SyncTagInvalidateEvent;
126
+ /**
127
+ * A generic function handler that can receive the payload of any function type.
128
128
  *
129
- * @beta
129
+ * The envelope is intentionally permissive so a single handler can be registered
130
+ * regardless of the event source without narrowing: `context` is any supported
131
+ * context, `event` is any supported event, and `done` is optional (present only
132
+ * for sync-tag-invalidate events).
133
+ */
134
+ export type EventHandler<IData = any> = (envelope: {
135
+ context: GenericContext;
136
+ event: DocumentEvent<IData> | SyncTagInvalidateEvent;
137
+ done?: SyncTagInvalidateCallback;
138
+ }) => void | Promise<void>;
139
+ /**
140
+ * A callback function to invoke once a sync-tag-invalidate event has been processed. Signals to Sanity that sync tag invalidation has completed.
130
141
  */
131
142
  export type SyncTagInvalidateCallback = (syncTags: string[]) => Promise<Response>;
132
143
  /**
133
144
  * The context object passed to the sync tag invalidate event handler.
134
- *
135
- * @beta
136
145
  */
137
146
  export interface SyncTagInvalidateContext extends Omit<FunctionContext, 'clientOptions'> {
138
147
  /**
@@ -149,14 +158,60 @@ export interface SyncTagInvalidateContext extends Omit<FunctionContext, 'clientO
149
158
  */
150
159
  token?: string;
151
160
  };
161
+ /** Resource interface that allows access to Blueprint Resources */
162
+ resources: ResourcesApi;
152
163
  }
153
164
  /**
154
165
  * A function handler for a sync-tag-invalidate event.
155
- *
156
- * @beta
157
166
  */
158
167
  export type SyncTagInvalidateEventHandler = (envelope: {
159
168
  context: SyncTagInvalidateContext;
160
169
  event: SyncTagInvalidateEvent;
161
170
  done: SyncTagInvalidateCallback;
162
171
  }) => void | Promise<void>;
172
+ /**
173
+ * An interface to describe resources found in a Blueprint
174
+ */
175
+ export interface BlueprintResource {
176
+ id: string;
177
+ name: string;
178
+ type: string;
179
+ }
180
+ export interface ResourcesApi {
181
+ /** Cross-type lookup by name: `context.resources('my-proj')`. */
182
+ (name: string): BlueprintResource | undefined;
183
+ /** Flat array of every resource across types. */
184
+ all(): BlueprintResource[];
185
+ /** Iterate every resource: `for (const r of context.resources)`. */
186
+ [Symbol.iterator](): IterableIterator<BlueprintResource>;
187
+ /** Type specific lookup by name: `context.cors('my-cors')` */
188
+ cors(name: string): BlueprintResource | undefined;
189
+ dataset(name: string): BlueprintResource | undefined;
190
+ function(name: string): BlueprintResource | undefined;
191
+ project(name: string): BlueprintResource | undefined;
192
+ role(name: string): BlueprintResource | undefined;
193
+ webhook(name: string): BlueprintResource | undefined;
194
+ }
195
+ /**
196
+ * The payload for the `invoke` method
197
+ */
198
+ export type FunctionPayload = {
199
+ event: GenericEvent;
200
+ context: GenericContext;
201
+ };
202
+ /**
203
+ * The definition of a function resource in our resource discovery table
204
+ */
205
+ export type FunctionResource = {
206
+ logicalResourceId: string;
207
+ physicalResourceId: string;
208
+ };
209
+ type FunctionResourceKey = 'eventsourcemapping' | 'function' | 'parameter' | 'queue' | 'schedule' | 'subscription' | 'topic';
210
+ export type FunctionResourceEnvelope = {
211
+ [K in FunctionResourceKey]-?: {
212
+ [P in K]: FunctionResource;
213
+ } & {
214
+ [P in Exclude<FunctionResourceKey, K>]?: FunctionResource;
215
+ };
216
+ }[FunctionResourceKey];
217
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/functions",
3
- "version": "1.3.1",
3
+ "version": "1.4.0",
4
4
  "description": "Helper methods and type definitions for Sanity Functions",
5
5
  "keywords": [
6
6
  "sanity",
@@ -47,8 +47,17 @@
47
47
  "typecheck": "tsc --noEmit --project tsconfig.test.json"
48
48
  },
49
49
  "devDependencies": {
50
+ "@aws-lite/client": "^0.23.6",
51
+ "@aws-lite/dynamodb": "^0.3.9",
52
+ "@aws-lite/dynamodb-types": "^0.3.12",
53
+ "@aws-lite/lambda": "^0.1.5",
54
+ "@aws-lite/lambda-types": "^0.1.6",
55
+ "@aws-lite/sns": "^0.0.8",
56
+ "@aws-lite/sns-types": "^0.0.11",
57
+ "@aws-lite/sqs": "^0.2.4",
58
+ "@aws-lite/sqs-types": "^0.2.7",
50
59
  "@biomejs/biome": "2.3.12",
51
- "@types/node": "^20",
60
+ "@types/node": "^22",
52
61
  "@vitest/coverage-v8": "^4.0.18",
53
62
  "rimraf": "^6.1.2",
54
63
  "typedoc": "^0.28.16",
@@ -56,9 +65,16 @@
56
65
  "vitest": "4.0.18"
57
66
  },
58
67
  "engines": {
59
- "node": ">=20.19"
68
+ "node": ">=22"
60
69
  },
61
70
  "publishConfig": {
62
71
  "access": "public"
72
+ },
73
+ "peerDependencies": {
74
+ "@aws-lite/client": "^0.23.6",
75
+ "@aws-lite/dynamodb": "^0.3.9",
76
+ "@aws-lite/lambda": "^0.1.5",
77
+ "@aws-lite/sns": "^0.0.8",
78
+ "@aws-lite/sqs": "^0.2.4"
63
79
  }
64
80
  }
@@ -0,0 +1,4 @@
1
+ declare module '@aws-lite/dynamodb'
2
+ declare module '@aws-lite/lambda'
3
+ declare module '@aws-lite/sns'
4
+ declare module '@aws-lite/sqs'
package/src/definers.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type {DocumentEventHandler, ScheduledEventHandler, SyncTagInvalidateEventHandler} from './types.js'
1
+ import type {DocumentEventHandler, EventHandler, ScheduledEventHandler, SyncTagInvalidateEventHandler} from './types.js'
2
2
 
3
3
  /**
4
4
  * Defines a "document event" function handler.
@@ -16,8 +16,6 @@ export function documentEventHandler<IData = any>(handler: DocumentEventHandler<
16
16
  * Defines a "scheduled event" function handler.
17
17
  * Returns the handler function as-is, only providing the types and doing basic validation.
18
18
  *
19
- * @alpha
20
- * @hidden
21
19
  * @param handler - The event handler function to use.
22
20
  * @returns The handler function, unmodified.
23
21
  */
@@ -37,3 +35,15 @@ export function syncTagInvalidateEventHandler(handler: SyncTagInvalidateEventHan
37
35
  if (typeof handler !== 'function') throw new TypeError('`handler` must be a function')
38
36
  return handler
39
37
  }
38
+
39
+ /**
40
+ * Defines a "generic" function handler.
41
+ * Returns the handler function as-is, only providing the types and doing basic validation.
42
+ *
43
+ * @param handler - The event handler function to use.
44
+ * @returns The handler function, unmodified.
45
+ */
46
+ export function eventHandler<IData = any>(handler: EventHandler<IData>): EventHandler<IData> {
47
+ if (typeof handler !== 'function') throw new TypeError('`handler` must be a function')
48
+ return handler
49
+ }
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './definers.js'
2
+ export * from './invoke.js'
2
3
  export * from './types.js'
package/src/invoke.ts ADDED
@@ -0,0 +1,95 @@
1
+ import {Buffer} from 'node:buffer'
2
+ import {env} from 'node:process'
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
7
+
8
+ let awsPromise: Promise<awsLite.AwsLiteClient> | undefined
9
+
10
+ const PARTITION_KEY = 'arc-app-res'
11
+
12
+ /**
13
+ * lazy load aws-lite
14
+ */
15
+ function getAwsLite() {
16
+ if (!awsPromise) {
17
+ awsPromise = (async () => {
18
+ const {default: awsLite} = await import('@aws-lite/client')
19
+ return awsLite({
20
+ plugins: [import('@aws-lite/dynamodb'), import('@aws-lite/lambda'), import('@aws-lite/sns'), import('@aws-lite/sqs')],
21
+ })
22
+ })().catch((err) => {
23
+ awsPromise = undefined
24
+ throw err
25
+ })
26
+ }
27
+ return awsPromise
28
+ }
29
+
30
+ /**
31
+ * Gets a specific resource based off of function name
32
+ * @param {string} name
33
+ */
34
+ async function getResource(name: string, aws: awsLite.AwsLiteClient): Promise<FunctionResourceEnvelope> {
35
+ const TableName = env['SANITY_DISCO']
36
+ if (!TableName) throw new Error('SANITY_DISCO env var not set')
37
+
38
+ const result = await aws.DynamoDB.GetItem({
39
+ TableName,
40
+ Key: {
41
+ PK: PARTITION_KEY,
42
+ SK: name,
43
+ },
44
+ ProjectionExpression: 'resources',
45
+ })
46
+ if (!result?.Item) throw new Error(`Function not found: ${name}`)
47
+ if (!result.Item['resources']) throw new Error(`Resource record for ${name} is missing resources`)
48
+ return result.Item['resources'] as unknown as FunctionResourceEnvelope
49
+ }
50
+
51
+ export async function invoke(name: string, payload: FunctionPayload) {
52
+ if (!name) throw new Error('Function name was not provided')
53
+
54
+ const stringPayload = JSON.stringify(payload)
55
+ // 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
+ }
59
+
60
+ // Local invoke path for Sanity CLI
61
+ if (payload?.context?.local) {
62
+ if (!payload?.context?.invoke) {
63
+ throw new Error(`No local invoke handler configured for function: ${name}`)
64
+ }
65
+ payload.context.invoke(name, payload)
66
+ return
67
+ }
68
+
69
+ const aws = await getAwsLite()
70
+ if (!aws) throw new Error(`Unable to invoke function: ${name}`)
71
+
72
+ // Look up the function details
73
+ const resource = await getResource(name, aws)
74
+
75
+ // Determine which method to invoke the function
76
+ if (resource.topic) {
77
+ await aws.SNS.Publish({
78
+ TopicArn: resource.topic.physicalResourceId,
79
+ Message: stringPayload,
80
+ })
81
+ } else if (resource.queue) {
82
+ await aws.SQS.SendMessage({
83
+ MessageBody: stringPayload,
84
+ QueueUrl: resource.queue.physicalResourceId,
85
+ })
86
+ } else if (resource.function) {
87
+ await aws.Lambda.Invoke({
88
+ FunctionName: resource.function.physicalResourceId,
89
+ Payload: payload,
90
+ InvocationType: 'Event',
91
+ })
92
+ } else {
93
+ throw new Error(`No invokeable resource for function: ${name}`)
94
+ }
95
+ }
package/src/types.ts CHANGED
@@ -1,7 +1,10 @@
1
+ /**
2
+ * Callback provided by Sanity CLI when doing local development
3
+ */
4
+ export type InvokeCallback = (name: string, payload: FunctionPayload) => Promise<void>
5
+
1
6
  /**
2
7
  * The context object passed to the function handler.
3
- *
4
- * @beta
5
8
  */
6
9
  export interface FunctionContext {
7
10
  /** The resource type of the event source; resource type that invoked the function. */
@@ -18,6 +21,7 @@ export interface FunctionContext {
18
21
  * Otherwise, the property is not set.
19
22
  */
20
23
  local?: boolean
24
+ invoke?: InvokeCallback
21
25
  /**
22
26
  * Options that can be passed to a `@sanity/client` constructor to configure it
23
27
  * against the project and dataset which triggered the event. Note that you should
@@ -31,7 +35,6 @@ export interface FunctionContext {
31
35
  * ...context.clientOptions,
32
36
  * })
33
37
  * ```
34
- * @beta
35
38
  */
36
39
  clientOptions: {
37
40
  apiHost?: string
@@ -39,12 +42,12 @@ export interface FunctionContext {
39
42
  projectId: string
40
43
  token: string
41
44
  }
45
+ /** Resource interface that allows access to Blueprint Resources */
46
+ resources: ResourcesApi
42
47
  }
43
48
 
44
49
  /**
45
50
  * The context object passed to the schedule function handler.
46
- *
47
- * @beta
48
51
  */
49
52
  export interface ScheduledFunctionContext {
50
53
  /**
@@ -53,6 +56,7 @@ export interface ScheduledFunctionContext {
53
56
  * Otherwise, the property is not set.
54
57
  */
55
58
  local?: boolean
59
+ invoke?: InvokeCallback
56
60
  /**
57
61
  * Options that can be passed to a `@sanity/client` constructor to configure it
58
62
  * against the project and dataset which triggered the event. Note that you should
@@ -66,7 +70,6 @@ export interface ScheduledFunctionContext {
66
70
  * ...context.clientOptions,
67
71
  * })
68
72
  * ```
69
- * @beta
70
73
  */
71
74
  clientOptions?: {
72
75
  apiHost?: string
@@ -74,35 +77,29 @@ export interface ScheduledFunctionContext {
74
77
  projectId?: string
75
78
  token?: string
76
79
  }
80
+ /** Resource interface that allows access to Blueprint Resources */
81
+ resources: ResourcesApi
77
82
  }
78
83
 
79
84
  /**
80
85
  * The event object received by the function handler in the case of a document event,
81
86
  * such as a publish, unpublish, delete or mutation event and similar.
82
- *
83
- * @beta
84
87
  */
85
88
  export interface DocumentEvent<IData = any> {
86
89
  /**
87
90
  * The data delivered to the function. This is the result of applying any configured
88
91
  * GROQ-projection to the changed document. If no projection is configured, this is
89
92
  * the document itself.
90
- *
91
- * @beta
92
93
  */
93
94
  data: IData
94
95
  }
95
96
 
96
97
  /**
97
98
  * The event object received by the function handler in the case of a sync-tag-invalidate event.
98
- *
99
- * @beta
100
99
  */
101
100
  export interface SyncTagInvalidateEvent {
102
101
  /**
103
102
  * The sync tags for use with cache invalidation and notifying the callback endpoint once tags are invalidated.
104
- *
105
- * @beta
106
103
  */
107
104
  data: {
108
105
  /** Array of sync tags to be invalidated. */
@@ -112,29 +109,45 @@ export interface SyncTagInvalidateEvent {
112
109
 
113
110
  /**
114
111
  * A function handler for a document event.
115
- *
116
- * @beta
117
112
  */
118
113
  export type DocumentEventHandler<IData = any> = (envelope: {context: FunctionContext; event: DocumentEvent<IData>}) => void | Promise<void>
119
114
 
120
115
  /**
121
116
  * A function handler for a schedule event.
122
- *
123
- * @beta
124
117
  */
125
118
  export type ScheduledEventHandler = (envelope: {context: ScheduledFunctionContext}) => void | Promise<void>
126
119
 
127
120
  /**
128
- * A callback function to invoke once a sync-tag-invalidate event has been processed. Signals to Sanity that sync tag invalidation has completed.
121
+ * A generic function context type which supports all function types
122
+ */
123
+ export type GenericContext = FunctionContext | ScheduledFunctionContext | SyncTagInvalidateContext
124
+
125
+ /**
126
+ * A generic function event type which supports all function types
127
+ */
128
+ export type GenericEvent = DocumentEvent | SyncTagInvalidateEvent
129
+
130
+ /**
131
+ * A generic function handler that can receive the payload of any function type.
129
132
  *
130
- * @beta
133
+ * The envelope is intentionally permissive so a single handler can be registered
134
+ * regardless of the event source without narrowing: `context` is any supported
135
+ * context, `event` is any supported event, and `done` is optional (present only
136
+ * for sync-tag-invalidate events).
137
+ */
138
+ export type EventHandler<IData = any> = (envelope: {
139
+ context: GenericContext
140
+ event: DocumentEvent<IData> | SyncTagInvalidateEvent
141
+ done?: SyncTagInvalidateCallback
142
+ }) => void | Promise<void>
143
+
144
+ /**
145
+ * A callback function to invoke once a sync-tag-invalidate event has been processed. Signals to Sanity that sync tag invalidation has completed.
131
146
  */
132
147
  export type SyncTagInvalidateCallback = (syncTags: string[]) => Promise<Response>
133
148
 
134
149
  /**
135
150
  * The context object passed to the sync tag invalidate event handler.
136
- *
137
- * @beta
138
151
  */
139
152
  export interface SyncTagInvalidateContext extends Omit<FunctionContext, 'clientOptions'> {
140
153
  /**
@@ -151,14 +164,60 @@ export interface SyncTagInvalidateContext extends Omit<FunctionContext, 'clientO
151
164
  */
152
165
  token?: string
153
166
  }
167
+ /** Resource interface that allows access to Blueprint Resources */
168
+ resources: ResourcesApi
154
169
  }
155
170
  /**
156
171
  * A function handler for a sync-tag-invalidate event.
157
- *
158
- * @beta
159
172
  */
160
173
  export type SyncTagInvalidateEventHandler = (envelope: {
161
174
  context: SyncTagInvalidateContext
162
175
  event: SyncTagInvalidateEvent
163
176
  done: SyncTagInvalidateCallback
164
177
  }) => void | Promise<void>
178
+
179
+ /**
180
+ * An interface to describe resources found in a Blueprint
181
+ */
182
+ export interface BlueprintResource {
183
+ id: string
184
+ name: string
185
+ type: string
186
+ }
187
+ export interface ResourcesApi {
188
+ /** Cross-type lookup by name: `context.resources('my-proj')`. */
189
+ (name: string): BlueprintResource | undefined
190
+ /** Flat array of every resource across types. */
191
+ all(): BlueprintResource[]
192
+ /** Iterate every resource: `for (const r of context.resources)`. */
193
+ [Symbol.iterator](): IterableIterator<BlueprintResource>
194
+ /** Type specific lookup by name: `context.cors('my-cors')` */
195
+ cors(name: string): BlueprintResource | undefined
196
+ dataset(name: string): BlueprintResource | undefined
197
+ function(name: string): BlueprintResource | undefined
198
+ project(name: string): BlueprintResource | undefined
199
+ role(name: string): BlueprintResource | undefined
200
+ webhook(name: string): BlueprintResource | undefined
201
+ }
202
+
203
+ /**
204
+ * The payload for the `invoke` method
205
+ */
206
+ export type FunctionPayload = {
207
+ event: GenericEvent
208
+ context: GenericContext
209
+ }
210
+
211
+ /**
212
+ * The definition of a function resource in our resource discovery table
213
+ */
214
+ export type FunctionResource = {
215
+ logicalResourceId: string
216
+ physicalResourceId: string
217
+ }
218
+
219
+ type FunctionResourceKey = 'eventsourcemapping' | 'function' | 'parameter' | 'queue' | 'schedule' | 'subscription' | 'topic'
220
+
221
+ export type FunctionResourceEnvelope = {
222
+ [K in FunctionResourceKey]-?: {[P in K]: FunctionResource} & {[P in Exclude<FunctionResourceKey, K>]?: FunctionResource}
223
+ }[FunctionResourceKey]