@sanity/runtime-cli 17.20.1 → 17.21.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/README.md CHANGED
@@ -90,7 +90,7 @@ EXAMPLES
90
90
  $ sanity-run blueprints add function --name my-function --fn-type document-create --fn-type document-update --lang js
91
91
  ```
92
92
 
93
- _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/add.ts)_
93
+ _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/add.ts)_
94
94
 
95
95
  ## `sanity-run blueprints config`
96
96
 
@@ -127,7 +127,7 @@ EXAMPLES
127
127
  $ sanity-run blueprints config --edit --project-id <projectId> --stack <name-or-id>
128
128
  ```
129
129
 
130
- _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/config.ts)_
130
+ _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/config.ts)_
131
131
 
132
132
  ## `sanity-run blueprints deploy`
133
133
 
@@ -183,7 +183,7 @@ EXAMPLES
183
183
  $ sanity-run blueprints deploy --new-stack-name <new-name>
184
184
  ```
185
185
 
186
- _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/deploy.ts)_
186
+ _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/deploy.ts)_
187
187
 
188
188
  ## `sanity-run blueprints destroy`
189
189
 
@@ -221,7 +221,7 @@ EXAMPLES
221
221
  $ sanity-run blueprints destroy --stack <name-or-id> --project-id <projectId> --force --no-wait
222
222
  ```
223
223
 
224
- _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/destroy.ts)_
224
+ _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/destroy.ts)_
225
225
 
226
226
  ## `sanity-run blueprints doctor`
227
227
 
@@ -253,7 +253,7 @@ EXAMPLES
253
253
  $ sanity-run blueprints doctor --fix
254
254
  ```
255
255
 
256
- _See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/doctor.ts)_
256
+ _See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/doctor.ts)_
257
257
 
258
258
  ## `sanity-run blueprints info`
259
259
 
@@ -291,7 +291,7 @@ EXAMPLES
291
291
  $ sanity-run blueprints info --organization-id <orgId> --stack <name-or-id>
292
292
  ```
293
293
 
294
- _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/info.ts)_
294
+ _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/info.ts)_
295
295
 
296
296
  ## `sanity-run blueprints init [DIR]`
297
297
 
@@ -355,7 +355,7 @@ EXAMPLES
355
355
  $ sanity-run blueprints init old-stack --type <json|js|ts> --project-id <projectId> --stack-id <existingStackId>
356
356
  ```
357
357
 
358
- _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/init.ts)_
358
+ _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/init.ts)_
359
359
 
360
360
  ## `sanity-run blueprints logs`
361
361
 
@@ -401,7 +401,7 @@ EXAMPLES
401
401
  $ sanity-run blueprints logs --before 2026-05-01T00:00:00Z
402
402
  ```
403
403
 
404
- _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/logs.ts)_
404
+ _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/logs.ts)_
405
405
 
406
406
  ## `sanity-run blueprints mint-deploy-token`
407
407
 
@@ -446,7 +446,7 @@ EXAMPLES
446
446
  $ sanity-run blueprints mint-deploy-token --organization-id <orgId>
447
447
  ```
448
448
 
449
- _See code: [src/commands/blueprints/mint-deploy-token.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/mint-deploy-token.ts)_
449
+ _See code: [src/commands/blueprints/mint-deploy-token.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/mint-deploy-token.ts)_
450
450
 
451
451
  ## `sanity-run blueprints plan`
452
452
 
@@ -479,7 +479,7 @@ EXAMPLES
479
479
  $ sanity-run blueprints plan --organization-id <orgId> --stack <name-or-id>
480
480
  ```
481
481
 
482
- _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/plan.ts)_
482
+ _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/plan.ts)_
483
483
 
484
484
  ## `sanity-run blueprints promote`
485
485
 
@@ -515,7 +515,7 @@ EXAMPLES
515
515
  $ sanity-run blueprints promote --new-stack-name <new-name>
516
516
  ```
517
517
 
518
- _See code: [src/commands/blueprints/promote.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/promote.ts)_
518
+ _See code: [src/commands/blueprints/promote.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/promote.ts)_
519
519
 
520
520
  ## `sanity-run blueprints stacks`
521
521
 
@@ -556,7 +556,7 @@ EXAMPLES
556
556
  $ sanity-run blueprints stacks --organization-id <organizationId> --include-projects
557
557
  ```
558
558
 
559
- _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/blueprints/stacks.ts)_
559
+ _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/blueprints/stacks.ts)_
560
560
 
561
561
  ## `sanity-run functions add`
562
562
 
@@ -608,7 +608,7 @@ EXAMPLES
608
608
  $ sanity-run functions add --name my-function --type document-create --type document-update --lang js
609
609
  ```
610
610
 
611
- _See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/functions/add.ts)_
611
+ _See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/functions/add.ts)_
612
612
 
613
613
  ## `sanity-run functions dev`
614
614
 
@@ -643,7 +643,7 @@ EXAMPLES
643
643
  $ sanity-run functions dev --timeout 60
644
644
  ```
645
645
 
646
- _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/functions/dev.ts)_
646
+ _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/functions/dev.ts)_
647
647
 
648
648
  ## `sanity-run functions env add NAME KEY VALUE`
649
649
 
@@ -676,7 +676,7 @@ EXAMPLES
676
676
  $ sanity-run functions env add --stack <name-or-id> MyFunction API_URL https://api.example.com/
677
677
  ```
678
678
 
679
- _See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/functions/env/add.ts)_
679
+ _See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/functions/env/add.ts)_
680
680
 
681
681
  ## `sanity-run functions env list NAME`
682
682
 
@@ -706,7 +706,7 @@ EXAMPLES
706
706
  $ sanity-run functions env list --stack <name-or-id> MyFunction
707
707
  ```
708
708
 
709
- _See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/functions/env/list.ts)_
709
+ _See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/functions/env/list.ts)_
710
710
 
711
711
  ## `sanity-run functions env remove NAME KEY`
712
712
 
@@ -738,7 +738,7 @@ EXAMPLES
738
738
  $ sanity-run functions env remove --stack <name-or-id> MyFunction API_URL
739
739
  ```
740
740
 
741
- _See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/functions/env/remove.ts)_
741
+ _See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/functions/env/remove.ts)_
742
742
 
743
743
  ## `sanity-run functions logs [NAME]`
744
744
 
@@ -778,7 +778,7 @@ EXAMPLES
778
778
  $ sanity-run functions logs <name> --delete
779
779
  ```
780
780
 
781
- _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/functions/logs.ts)_
781
+ _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/functions/logs.ts)_
782
782
 
783
783
  ## `sanity-run functions test [NAME]`
784
784
 
@@ -836,7 +836,7 @@ EXAMPLES
836
836
  $ sanity-run functions test <name> --event update --data-before '{ "title": "before" }' --data-after '{ "title": "after" }'
837
837
  ```
838
838
 
839
- _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1/src/commands/functions/test.ts)_
839
+ _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0/src/commands/functions/test.ts)_
840
840
 
841
841
  ## `sanity-run help [COMMAND]`
842
842
 
package/dist/constants.js CHANGED
@@ -67,6 +67,7 @@ export const STEP_PHASE_GLYPH = {
67
67
  start: '▶',
68
68
  complete: '✔',
69
69
  error: '✖',
70
+ waiting: '⏸',
70
71
  };
71
72
  /** Stands in for environment variable values, which are never echoed back to the user */
72
73
  export const ENV_MASK = '********';
@@ -3,6 +3,7 @@ import { testAction } from '../../actions/functions/test.js';
3
3
  import config from '../../config.js';
4
4
  import { SANITY_FUNCTION_DURABLE, STEP_PHASE_GLYPH } from '../../constants.js';
5
5
  import { resolveDeployedResources } from '../../utils/blueprints/resolve-deployed-resources.js';
6
+ import { createCallbackRoutes } from '../../utils/functions/callback/routes.js';
6
7
  import { createDurableJsonCollector } from '../../utils/functions/durable-logs.js';
7
8
  import { findFunctionInResources, getFunctionNames } from '../../utils/functions/find.js';
8
9
  import { runFunction } from '../../utils/functions/invoke/nested.js';
@@ -66,19 +67,18 @@ export async function functionTestCore(options) {
66
67
  // Records each nested context.invoke() so they can be surfaced in order after the spinner resolves.
67
68
  const nestedRuns = [];
68
69
  let nestedOrder = 0;
69
- const durableJson = createDurableJsonCollector();
70
- const onStepEvent = plan.isDurable
71
- ? (event) => {
72
- if (flags.json) {
73
- durableJson.record(event);
74
- return;
75
- }
76
- for (const line of renderStepTimeline([event])) {
77
- if (line !== null)
78
- log(line);
79
- }
70
+ const handlerStepEvent = async (event) => {
71
+ if (flags.json) {
72
+ durableJson.record(event);
73
+ return;
80
74
  }
81
- : undefined;
75
+ for (const line of renderStepTimeline([event])) {
76
+ if (line !== null)
77
+ log(line);
78
+ }
79
+ };
80
+ const durableJson = createDurableJsonCollector();
81
+ const onStepEvent = plan.isDurable ? handlerStepEvent : undefined;
82
82
  /**
83
83
  * Re-entrant callback that resolves a nested context.invoke(name, payload):
84
84
  * it finds the named function in the same blueprint, reuses the already
@@ -96,9 +96,11 @@ export async function functionTestCore(options) {
96
96
  log(`↳ BEGIN: invoke('${nestedName}')`);
97
97
  }
98
98
  try {
99
- const result = await runFunction(nestedResource, { payload: nestedPayload, event: 'nested' }, { ...ctx, resources: resolvedResources }, { depth, callStack, onNestedInvoke: runNested, onStepEvent });
100
- if (result.error && isLiveDurable) {
99
+ const result = await runFunction(nestedResource, { payload: nestedPayload, event: 'nested' }, { ...ctx, resources: resolvedResources }, { depth, callStack, onNestedInvoke: runNested, onStepEvent, callbackRoutes });
100
+ if (result.error && (isLiveDurable || plan.isDurable)) {
101
101
  log(result.error.stack || result.error.message);
102
+ // if an error occurs in a nested durable function, we want to fail the callback so the parent durable function can handle it
103
+ callbackRoutes.fail(result.error);
102
104
  }
103
105
  nestedRuns.push({
104
106
  order,
@@ -173,6 +175,7 @@ export async function functionTestCore(options) {
173
175
  }
174
176
  return lines;
175
177
  }
178
+ const callbackRoutes = createCallbackRoutes();
176
179
  const spinner = log.ora('Executing function...').start();
177
180
  const { json: response, logs, error, } = await testAction(resource, invokeOptions, context, {
178
181
  timeout: timeout ? timeout : resource.timeout,
@@ -181,6 +184,7 @@ export async function functionTestCore(options) {
181
184
  callStack: [fnName],
182
185
  onStepEvent,
183
186
  noWait,
187
+ callbackRoutes,
184
188
  });
185
189
  if (error) {
186
190
  spinner.fail('Function execution failed.');
@@ -0,0 +1,10 @@
1
+ import type { CallbackResponse, InvocationError } from '../../types.js';
2
+ type Deliver = (result: CallbackResponse) => void;
3
+ export declare const createCallbackRoutes: () => {
4
+ set: (id: string, deliver: Deliver) => void;
5
+ remove: (id: string) => boolean;
6
+ deliver: (id: string, response: CallbackResponse) => 'ok' | 'unknown' | 'delivered' | 'cancelled';
7
+ fail: (error: InvocationError) => void;
8
+ };
9
+ export type CallbackRoutes = ReturnType<typeof createCallbackRoutes>;
10
+ export {};
@@ -0,0 +1,34 @@
1
+ export const createCallbackRoutes = () => {
2
+ const routes = new Map();
3
+ const finished = new Map();
4
+ const set = (id, deliver) => {
5
+ routes.set(id, deliver);
6
+ };
7
+ const remove = (id) => {
8
+ if (!routes.delete(id))
9
+ return false;
10
+ finished.set(id, 'cancelled');
11
+ return true;
12
+ };
13
+ const deliver = (id, response) => {
14
+ const fn = routes.get(id);
15
+ if (!fn) {
16
+ return finished.get(id) ?? 'unknown';
17
+ }
18
+ routes.delete(id);
19
+ finished.set(id, 'delivered');
20
+ fn(response);
21
+ return 'ok';
22
+ };
23
+ const fail = (error) => {
24
+ for (const [id] of routes.entries()) {
25
+ deliver(id, { ok: false, error });
26
+ }
27
+ };
28
+ return {
29
+ set,
30
+ remove,
31
+ deliver,
32
+ fail,
33
+ };
34
+ };
@@ -2,6 +2,7 @@ import {existsSync, statSync} from 'node:fs'
2
2
  import {isAbsolute, join} from 'node:path'
3
3
  import process from 'node:process'
4
4
  import {pathToFileURL} from 'node:url'
5
+ import {createCallbackHandler} from './child-runtime/callback.js'
5
6
  import {installConsole} from './child-runtime/console.js'
6
7
  import {runDurable} from './child-runtime/durable.js'
7
8
  import {createInvoker} from './child-runtime/invoke.js'
@@ -9,6 +10,7 @@ import {createResourcesApi} from './child-runtime/resources.js'
9
10
 
10
11
  installConsole()
11
12
  const invoker = createInvoker()
13
+ const callback = createCallbackHandler()
12
14
 
13
15
  export function getFunctionSource(src) {
14
16
  const pathToCheck = isAbsolute(src) ? src : join(process.cwd(), src)
@@ -39,9 +41,14 @@ process.on('message', async (data) => {
39
41
  return
40
42
  }
41
43
 
44
+ if (jsonData?.type === 'callback-response') {
45
+ callback.handleResponse(jsonData)
46
+ return
47
+ }
48
+
42
49
  // Otherwise this is the initial start message. Support the legacy untyped
43
50
  // `{srcPath, payload}` shape as well as the new `{type: 'start', ...}`.
44
- const {srcPath, payload, isDurable, noWait} = jsonData
51
+ const {srcPath, payload, isDurable, noWait, callbacks} = jsonData
45
52
  const {context, ...event} = payload
46
53
  let logs = ''
47
54
  let errorLogs = ''
@@ -79,6 +86,13 @@ process.on('message', async (data) => {
79
86
  // Allow the handler to invoke other blueprint functions by name.
80
87
  context.invoke = invoker.invoke
81
88
 
89
+ if (callbacks) {
90
+ context.clientOptions = {
91
+ ...context.clientOptions,
92
+ requestHandler: callback.handleRequest,
93
+ }
94
+ }
95
+
82
96
  if (isDurable) {
83
97
  json = await runDurable(
84
98
  handler,
@@ -87,6 +101,8 @@ process.on('message', async (data) => {
87
101
  emit: (e) => process.send(JSON.stringify({type: 'step-event', event: e})),
88
102
  wait: (ms) => new Promise((resolve) => setTimeout(resolve, noWait ? 0 : ms)),
89
103
  invoke: invoker.delegate,
104
+ registerCallback: callback.register,
105
+ cancelCallback: callback.cancel,
90
106
  },
91
107
  )
92
108
  } else {
@@ -0,0 +1,15 @@
1
+ import type {ParentToChildMessage} from '../../types.js'
2
+
3
+ export function createCallbackHandler(): {
4
+ cancel: (callbackId: string) => void
5
+ register: ({
6
+ callbackId,
7
+ name,
8
+ timeout,
9
+ }: {
10
+ callbackId: string
11
+ name: string
12
+ timeout: number
13
+ }) => Promise<unknown>
14
+ handleResponse: (msg: Extract<ParentToChildMessage, {type: 'callback-response'}>) => void
15
+ }
@@ -0,0 +1,152 @@
1
+ import process from 'node:process'
2
+
3
+ export const createCallbackHandler = () => {
4
+ /**
5
+ * Pending nested `context.registerCallback()` calls, keyed by correlation id. Each entry
6
+ * holds the resolve/reject of the Promise returned to the user's handler; it is
7
+ * settled when the matching `callback-response` arrives from the parent.
8
+ * @type {Map<string, {resolve: (value: unknown) => void, reject: (reason: Error) => void, timer: ReturnType<typeof setTimeout> | undefined}>}
9
+ */
10
+ const pendingResponses = new Map([])
11
+ const pendingRequests = new Map([])
12
+ let nextAttempt = 0
13
+
14
+ // Register a callback with the parent process. Returns a Promise that resolves when the callback is invoked, or rejects if the callback times out.
15
+ const register = ({callbackId, name, timeout}) => {
16
+ return new Promise((resolve, reject) => {
17
+ const timer = timeout
18
+ ? setTimeout(() => {
19
+ cancel(callbackId)
20
+ reject(new Error(`Callback ${callbackId} timed out after ${timeout}ms`))
21
+ }, timeout)
22
+ : undefined
23
+
24
+ pendingResponses.set(callbackId, {resolve, reject, timer})
25
+ process.send(JSON.stringify({type: 'callback-register', callbackId, name}))
26
+ })
27
+ }
28
+
29
+ /**
30
+ * Handle a response from the parent process for a registered callback. This is called when the parent process sends a `callback-response` message.
31
+ */
32
+ const handleResponse = (msg) => {
33
+ if (msg.attempt !== undefined) {
34
+ const entry = removeRequest(msg.attempt)
35
+
36
+ if (!entry) {
37
+ return
38
+ }
39
+
40
+ if (msg.ok) {
41
+ entry.resolve(msg.result)
42
+ } else {
43
+ entry.reject(new Error(msg.error.message))
44
+ }
45
+ return
46
+ }
47
+
48
+ const pendingEntry = pendingResponses.get(msg.callbackId)
49
+ if (!pendingEntry) return
50
+
51
+ pendingResponses.delete(msg.callbackId)
52
+ clearTimeout(pendingEntry?.timer)
53
+ if (msg.ok) {
54
+ pendingEntry.resolve(msg.result)
55
+ return
56
+ }
57
+
58
+ const {message, stack, name} = msg.error
59
+ const error = new Error(message)
60
+ error.stack = stack
61
+ error.name = name
62
+ pendingEntry.reject(error)
63
+ }
64
+
65
+ /**
66
+ * Handle a request from the parent process to invoke a registered callback. This is called when the parent process sends a `callback-request` message.
67
+ */
68
+ const handleRequest = (request, next) => {
69
+ // Match the request from the callback.sucess or callback.failure sanity client functions
70
+ const CALLBACK_URL =
71
+ /^https?:\/\/[^/?#]+\/v[^/?#]+\/functions\/durables\/callback\/([^/?#]+)\/(success|failure)(?:[?#].*)?$/
72
+
73
+ const match = request.method?.toUpperCase() === 'POST' && CALLBACK_URL.exec(request.url)
74
+ if (!match) {
75
+ return next(request)
76
+ }
77
+
78
+ const [, callbackId, outcome] = match
79
+ const {body, timeout} = request
80
+ if (typeof body !== 'string') {
81
+ throw new TypeError('Callback body must be serialized JSON')
82
+ }
83
+
84
+ const timeoutMs = typeof timeout === 'object' && timeout !== null ? timeout.total : timeout
85
+ const signals = [request.signal, timeoutMs > 0 && AbortSignal.timeout(timeoutMs)].filter(
86
+ Boolean,
87
+ )
88
+
89
+ const signal = signals.length > 0 ? AbortSignal.any(signals) : undefined
90
+ signal?.throwIfAborted()
91
+
92
+ return new Promise((resolve, reject) => {
93
+ const attempt = ++nextAttempt
94
+ const onAbort = () => removeRequest(attempt)?.reject(signal.reason)
95
+ pendingRequests.set(attempt, {
96
+ callbackId,
97
+ resolve,
98
+ reject,
99
+ cleanup: () => signal?.removeEventListener('abort', onAbort),
100
+ })
101
+ signal?.addEventListener('abort', onAbort, {once: true})
102
+ try {
103
+ process.send(
104
+ JSON.stringify({type: 'callback-request', callbackId, attempt, outcome, body}),
105
+ (error) => {
106
+ if (error) removeRequest(attempt)?.reject(error)
107
+ },
108
+ )
109
+ } catch (error) {
110
+ removeRequest(attempt)?.reject(error)
111
+ }
112
+ })
113
+ }
114
+
115
+ /**
116
+ * Remove a pending request from the map and clean up its resources. This is called when a request is completed or aborted.
117
+ */
118
+ const removeRequest = (attempt) => {
119
+ const entry = pendingRequests.get(attempt)
120
+ if (!entry) {
121
+ return
122
+ }
123
+
124
+ pendingRequests.delete(attempt)
125
+ entry.cleanup()
126
+ return entry
127
+ }
128
+
129
+ process.once('disconnect', () => {
130
+ const error = new Error('Local callback IPC disconnected')
131
+ for (const attempt of pendingRequests.keys()) removeRequest(attempt)?.reject(error)
132
+ })
133
+
134
+ /**
135
+ * Cancel a pending callback request. This is called when the parent process sends a `callback-cancel` message.
136
+ */
137
+ const cancel = (callbackId) => {
138
+ const pendingEntry = pendingResponses.get(callbackId)
139
+ if (!pendingEntry) return
140
+ pendingResponses.delete(callbackId)
141
+ clearTimeout(pendingEntry?.timer)
142
+ process.send(JSON.stringify({type: 'callback-cancel', callbackId}))
143
+ }
144
+
145
+ return {
146
+ cancel,
147
+ register,
148
+ handleRequest,
149
+ handleResponse,
150
+ removeRequest,
151
+ }
152
+ }
@@ -1,3 +1,4 @@
1
+ import {randomUUID} from 'node:crypto'
1
2
  import {performance} from 'node:perf_hooks'
2
3
  import {inspect} from 'node:util'
3
4
  import {getBatchResults} from './getBatchResults.js'
@@ -205,6 +206,30 @@ export async function runDurable(handler, {context, event, branchName}, io) {
205
206
  }
206
207
  return state
207
208
  }),
209
+ waitForCallback: ({name, submitter, timeout, retry}) => {
210
+ return track(
211
+ name || '',
212
+ 'wait-for-callback',
213
+ async () => {
214
+ const callbackId = randomUUID()
215
+ const result = io.registerCallback({
216
+ callbackId,
217
+ name,
218
+ timeout: durationToMs(timeout),
219
+ })
220
+ io.emit({name, kind: 'wait-for-callback', phase: 'waiting', callbackId})
221
+ try {
222
+ await submitter({callbackId, logger})
223
+ } catch (err) {
224
+ io.cancelCallback(callbackId)
225
+ throw err
226
+ }
227
+
228
+ return await result
229
+ },
230
+ retry,
231
+ )
232
+ },
208
233
  wait: ({name, duration}) =>
209
234
  track(name || '', 'wait', async () => {
210
235
  await io.wait(durationToMs(duration))
@@ -0,0 +1,6 @@
1
+ import type {BatchItem, BatchResult, CompletionReason} from '@sanity/functions'
2
+
3
+ export function getBatchResults(
4
+ outcomes: Array<BatchItem<unknown>>,
5
+ reason: CompletionReason,
6
+ ): Omit<BatchResult<unknown>, 'completionReason'> & {reason: CompletionReason}
@@ -18,8 +18,7 @@ export const getBatchResults = (outcomes, reason) => {
18
18
  /**
19
19
  * Returns an array of outcomes that have succeeded (status 'SUCCEEDED').
20
20
  */
21
- const succeeded = () =>
22
- all.filter((outcome) => outcome.result !== undefined && outcome.status === 'SUCCEEDED')
21
+ const succeeded = () => all.filter((outcome) => outcome.status === 'SUCCEEDED')
23
22
 
24
23
  /**
25
24
  * Returns an array of outcomes that are still in progress (status 'STARTED').
@@ -1,4 +1,4 @@
1
- import type {DurableStepEvent} from './types'
1
+ import type {DurableStepEvent} from '../../types.js'
2
2
 
3
3
  type PendingRetry = {index: number; event: DurableStepEvent; delayMs: number}
4
4
 
@@ -35,6 +35,11 @@ export const createDurableJsonCollector = () => {
35
35
  const step = activeSteps.get(event.name);
36
36
  if (!step)
37
37
  return;
38
+ if (event.phase === 'waiting') {
39
+ step.phase = 'waiting';
40
+ step.callbackId = event.callbackId;
41
+ return;
42
+ }
38
43
  step.phase = event.phase;
39
44
  step.durationMs = event.durationMs;
40
45
  if (event.phase === 'complete') {
@@ -8,6 +8,7 @@ import * as groq from 'groq-js';
8
8
  import config from '../../../config.js';
9
9
  import { SANITY_FUNCTION_DURABLE } from '../../../constants.js';
10
10
  import { groupBlueprintResources } from '../../blueprints/group-resources.js';
11
+ import { isRecord } from '../../is-record.js';
11
12
  import { isGroqContextOptions, } from '../../types.js';
12
13
  import { findFunctionEntryPoint } from '../find-entry-point.js';
13
14
  import { assertConsole } from './assert-console.js';
@@ -50,7 +51,7 @@ export default async function invoke(resource, payload, context, options) {
50
51
  if (!resource.src) {
51
52
  throw new Error(`Function resource "${resource.name}" is missing the 'src' property.`);
52
53
  }
53
- const { forceColor = true, timeout = 10, onNestedInvoke, depth = 0, callStack = [], onStepEvent = () => { }, noWait = false, } = options;
54
+ const { forceColor = true, timeout = 10, onNestedInvoke, depth = 0, callStack = [], onStepEvent = () => { }, noWait = false, callbackRoutes, } = options;
54
55
  // Ensure a user when running a durable is using the provided logger and not the `console`
55
56
  if (resource.type === SANITY_FUNCTION_DURABLE) {
56
57
  const sourcePath = resolve(context.blueprintFileDir, resource.src);
@@ -236,6 +237,80 @@ export default async function invoke(resource, payload, context, options) {
236
237
  catch {
237
238
  return;
238
239
  }
240
+ if (msg?.type === 'callback-register') {
241
+ // if the routes handler is not available, kill the process with an error
242
+ if (!callbackRoutes) {
243
+ child.send(JSON.stringify({
244
+ type: 'callback-response',
245
+ callbackId: msg.callbackId,
246
+ ok: false,
247
+ error: {
248
+ name: 'Error',
249
+ message: 'The callback server is not available',
250
+ },
251
+ }));
252
+ return;
253
+ }
254
+ pauseTimer();
255
+ callbackRoutes.set(msg.callbackId, async (result) => {
256
+ if (child && !child.killed) {
257
+ child.send(JSON.stringify({
258
+ type: 'callback-response',
259
+ callbackId: msg.callbackId,
260
+ ...result,
261
+ }));
262
+ }
263
+ resumeTimer();
264
+ });
265
+ return;
266
+ }
267
+ if (msg.type === 'callback-cancel') {
268
+ if (callbackRoutes?.remove(msg.callbackId)) {
269
+ resumeTimer();
270
+ }
271
+ return;
272
+ }
273
+ if (msg?.type === 'callback-request') {
274
+ const { callbackId, attempt, outcome, body } = msg;
275
+ let response;
276
+ try {
277
+ let value;
278
+ try {
279
+ value = JSON.parse(body);
280
+ }
281
+ catch {
282
+ throw new Error('Invalid callback payload');
283
+ }
284
+ let delivery = { ok: true, result: value };
285
+ if (outcome === 'failure') {
286
+ const fields = isRecord(value) ? value : {};
287
+ delivery = {
288
+ ok: false,
289
+ error: {
290
+ name: 'Error',
291
+ message: typeof fields.errorMessage === 'string' ? fields.errorMessage : '',
292
+ stack: Array.isArray(fields.stackTrace) ? fields.stackTrace.join('\n') : '',
293
+ },
294
+ };
295
+ }
296
+ const result = callbackRoutes?.deliver(callbackId, delivery) ?? 'unknown';
297
+ if (result !== 'ok')
298
+ throw new Error(`Local callback ${callbackId}: ${result}`);
299
+ response = { ok: true, result: null };
300
+ }
301
+ catch (err) {
302
+ response = {
303
+ ok: false,
304
+ error: {
305
+ name: err instanceof Error ? err.name : 'Error',
306
+ message: err instanceof Error ? err.message : String(err),
307
+ stack: err instanceof Error ? (err.stack ?? '') : '',
308
+ },
309
+ };
310
+ }
311
+ child.send(JSON.stringify({ type: 'callback-response', callbackId, attempt, ...response }));
312
+ return;
313
+ }
239
314
  if (msg?.type === 'step-event') {
240
315
  onStepEvent(msg.event);
241
316
  return;
@@ -321,7 +396,8 @@ export default async function invoke(resource, payload, context, options) {
321
396
  ...(isGroqContextOptions(context) && {
322
397
  clientOptions: {
323
398
  ...context.clientOptions,
324
- apiHost: config.apiUrl,
399
+ // trailing slash is being added, but not certain where. Strips it off here to remove `apiHost//vx/`
400
+ apiHost: (context.clientOptions.apiHost ?? config.apiUrl).replace(/\/+$/, ''),
325
401
  },
326
402
  }),
327
403
  },
@@ -332,6 +408,7 @@ export default async function invoke(resource, payload, context, options) {
332
408
  payload,
333
409
  isDurable: resource.type === SANITY_FUNCTION_DURABLE,
334
410
  noWait,
411
+ callbacks: Boolean(callbackRoutes),
335
412
  };
336
413
  child.send(JSON.stringify(startMessage));
337
414
  }
@@ -28,7 +28,7 @@ export function assertNestedInvokeAllowed(name, depth, callStack) {
28
28
  * stack extended by this function, and normalize timings.
29
29
  */
30
30
  export async function runFunction(resource, payload, context, options) {
31
- const { forceColor, timeout, depth = 0, callStack = [], onNestedInvoke, onStepEvent } = options;
31
+ const { forceColor, timeout, depth = 0, callStack = [], onNestedInvoke, onStepEvent, callbackRoutes, } = options;
32
32
  assertNestedInvokeAllowed(resource.name, depth, callStack);
33
33
  const response = await invoke(resource, payload, context, {
34
34
  forceColor,
@@ -37,6 +37,7 @@ export async function runFunction(resource, payload, context, options) {
37
37
  depth,
38
38
  callStack: [...callStack, resource.name],
39
39
  onStepEvent,
40
+ callbackRoutes,
40
41
  });
41
42
  return { ...response, timings: response.timings ?? {} };
42
43
  }
@@ -1,5 +1,6 @@
1
1
  import { type BlueprintCorsOriginResource, type BlueprintDatasetResource, type BlueprintDocumentFunctionResource, type BlueprintDocumentWebhookResource, type BlueprintDurableFunctionResource, type BlueprintMediaLibraryAssetFunctionResource, type BlueprintProjectResource, type BlueprintPubSubFunctionResource, type BlueprintResource, type BlueprintRobotResource, type BlueprintRoleResource, type BlueprintScheduledFunctionResource, type BlueprintStudioResource, type BlueprintSyncTagInvalidateFunctionResource } from '@sanity/blueprints';
2
2
  import { type SANITY_AGENT_TYPE } from '../constants.js';
3
+ import type { CallbackRoutes } from './functions/callback/routes.js';
3
4
  export type ScopeType = 'organization' | 'project';
4
5
  /** Result utility type */
5
6
  export type Result<T, E = string> = {
@@ -165,6 +166,7 @@ export interface InvokeGroqContextOptions extends BaseContextOptions {
165
166
  projectId?: string;
166
167
  organizationId?: string;
167
168
  token?: string;
169
+ apiHost?: string;
168
170
  };
169
171
  /** The resource type of the event source; resource type that invoked the function. */
170
172
  eventResourceType: string;
@@ -201,7 +203,18 @@ export interface InvokeExecutionOptions {
201
203
  onStepEvent?: (event: DurableRuntimeEvent) => void;
202
204
  /** Don't wait the full duration during a wait durable event @internal */
203
205
  noWait?: boolean;
206
+ callbackRoutes?: CallbackRoutes;
204
207
  }
208
+ /**
209
+ * @internal
210
+ */
211
+ export type CallbackResponse = {
212
+ ok: true;
213
+ result: unknown;
214
+ } | {
215
+ ok: false;
216
+ error: InvocationError;
217
+ };
205
218
  export type NestedInvokeMetadata = {
206
219
  origin?: 'step.delegate';
207
220
  };
@@ -223,6 +236,7 @@ export type ParentToChildMessage = {
223
236
  payload: unknown;
224
237
  isDurable?: boolean;
225
238
  noWait?: boolean;
239
+ callbacks?: boolean;
226
240
  } | {
227
241
  type: 'invoke-response';
228
242
  id: string;
@@ -238,6 +252,18 @@ export type ParentToChildMessage = {
238
252
  } | {
239
253
  type: 'step-event';
240
254
  event: DurableRuntimeEvent;
255
+ } | {
256
+ type: 'callback-response';
257
+ callbackId: string;
258
+ ok: true;
259
+ result: unknown;
260
+ attempt?: number;
261
+ } | {
262
+ type: 'callback-response';
263
+ callbackId: string;
264
+ ok: false;
265
+ error: InvocationError;
266
+ attempt?: number;
241
267
  };
242
268
  /**
243
269
  * IPC messages sent from a function child process back up to the parent.
@@ -261,6 +287,19 @@ export type ChildToParentMessage = {
261
287
  } | {
262
288
  type: 'step-event';
263
289
  event: DurableRuntimeEvent;
290
+ } | {
291
+ type: 'callback-register';
292
+ callbackId: string;
293
+ name: string;
294
+ } | {
295
+ type: 'callback-cancel';
296
+ callbackId: string;
297
+ } | {
298
+ type: 'callback-request';
299
+ attempt: number;
300
+ callbackId: string;
301
+ outcome: 'success' | 'failure';
302
+ body: string;
264
303
  };
265
304
  /** @internal */
266
305
  export interface InvocationResponse {
@@ -381,9 +420,9 @@ export type Warning = {
381
420
  suggestions: string[];
382
421
  };
383
422
  /** @internal */
384
- export type DurableOperationSteps = 'run' | 'wait' | 'waitForCondition' | 'delegate';
423
+ export type DurableOperationSteps = 'run' | 'delegate' | 'fanout' | 'wait' | 'wait-for-condition' | 'wait-for-callback';
385
424
  /** @internal */
386
- export type DurableStepPhase = 'start' | 'complete' | 'error';
425
+ export type DurableStepPhase = 'start' | 'complete' | 'error' | 'waiting';
387
426
  /**
388
427
  * Represents a single step in a durable operation
389
428
  */
@@ -398,6 +437,7 @@ export interface DurableStepEvent {
398
437
  attempt?: number;
399
438
  retries?: number;
400
439
  maxAttempts?: number;
440
+ callbackId?: string;
401
441
  }
402
442
  export interface DurableLogEvent {
403
443
  kind: 'log';
@@ -3150,5 +3150,5 @@
3150
3150
  ]
3151
3151
  }
3152
3152
  },
3153
- "version": "17.20.1"
3153
+ "version": "17.21.0"
3154
3154
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sanity/runtime-cli",
3
3
  "description": "Sanity's Runtime CLI for Blueprints and Functions",
4
- "version": "17.20.1",
4
+ "version": "17.21.0",
5
5
  "author": "Sanity Runtime Team",
6
6
  "type": "module",
7
7
  "license": "MIT",