@sanity/runtime-cli 17.20.0 → 17.20.1-next.g1660a2b

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.
Files changed (30) hide show
  1. package/README.md +19 -19
  2. package/dist/actions/blueprints/logs-polling.js +7 -1
  3. package/dist/actions/functions/env/list.d.ts +5 -1
  4. package/dist/actions/functions/env/list.js +5 -5
  5. package/dist/actions/functions/env/remove.d.ts +1 -1
  6. package/dist/actions/functions/env/remove.js +2 -2
  7. package/dist/actions/functions/env/update.d.ts +1 -1
  8. package/dist/actions/functions/env/update.js +2 -2
  9. package/dist/actions/functions/list.js +3 -6
  10. package/dist/actions/functions/logs.d.ts +6 -2
  11. package/dist/actions/functions/logs.js +6 -7
  12. package/dist/constants.js +1 -0
  13. package/dist/cores/functions/test.js +18 -14
  14. package/dist/utils/functions/api-error.d.ts +6 -0
  15. package/dist/utils/functions/api-error.js +25 -0
  16. package/dist/utils/functions/callback/routes.d.ts +10 -0
  17. package/dist/utils/functions/callback/routes.js +34 -0
  18. package/dist/utils/functions/child-process-wrapper.js +17 -1
  19. package/dist/utils/functions/child-runtime/callback.d.ts +15 -0
  20. package/dist/utils/functions/child-runtime/callback.js +152 -0
  21. package/dist/utils/functions/child-runtime/durable.js +25 -0
  22. package/dist/utils/functions/child-runtime/getBatchResults.d.ts +6 -0
  23. package/dist/utils/functions/child-runtime/getBatchResults.js +1 -2
  24. package/dist/utils/functions/child-runtime/step-history.d.ts +1 -1
  25. package/dist/utils/functions/durable-logs.js +5 -0
  26. package/dist/utils/functions/invoke/local.js +79 -2
  27. package/dist/utils/functions/invoke/nested.js +2 -1
  28. package/dist/utils/types.d.ts +42 -2
  29. package/oclif.manifest.json +1052 -1052
  30. package/package.json +1 -1
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.0/src/commands/blueprints/add.ts)_
93
+ _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/blueprints/config.ts)_
130
+ _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/blueprints/deploy.ts)_
186
+ _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/blueprints/destroy.ts)_
224
+ _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/blueprints/doctor.ts)_
256
+ _See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/blueprints/info.ts)_
294
+ _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/blueprints/init.ts)_
358
+ _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/blueprints/logs.ts)_
404
+ _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/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.20.1-next.g1660a2b/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.0/src/commands/blueprints/plan.ts)_
482
+ _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/blueprints/promote.ts)_
518
+ _See code: [src/commands/blueprints/promote.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/blueprints/stacks.ts)_
559
+ _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/functions/add.ts)_
611
+ _See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/functions/dev.ts)_
646
+ _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/functions/env/add.ts)_
679
+ _See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/functions/env/list.ts)_
709
+ _See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/functions/env/remove.ts)_
741
+ _See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/functions/logs.ts)_
781
+ _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/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.0/src/commands/functions/test.ts)_
839
+ _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v17.20.1-next.g1660a2b/src/commands/functions/test.ts)_
840
840
 
841
841
  ## `sanity-run help [COMMAND]`
842
842
 
@@ -10,10 +10,13 @@ export function setupLogPolling(config) {
10
10
  const seenIds = new Set(config.knownIds);
11
11
  let previousLog;
12
12
  let stopped = false;
13
+ let inFlight = false;
13
14
  config.onShowBanner?.();
14
15
  const fetchAndProcessLogs = async () => {
15
- if (stopped)
16
+ // skip the tick while the previous request is open so a slow API does not pile up requests
17
+ if (stopped || inFlight)
16
18
  return;
19
+ inFlight = true;
17
20
  try {
18
21
  const params = operationId ? { operationId } : { stackId };
19
22
  const { ok, logs } = await getLogs(params, auth, fetchFn);
@@ -32,6 +35,9 @@ export function setupLogPolling(config) {
32
35
  // Swallow fetch errors; the operation status poll in callers handles terminal failure.
33
36
  // Logging noise here is not useful.
34
37
  }
38
+ finally {
39
+ inFlight = false;
40
+ }
35
41
  };
36
42
  // Fire immediately, then on interval
37
43
  fetchAndProcessLogs();
@@ -1,7 +1,11 @@
1
1
  import type { Logger } from '../../../utils/logger.js';
2
2
  import type { AuthParams } from '../../../utils/types.js';
3
3
  export declare function list(id: string, auth: AuthParams, logger: Logger): Promise<{
4
+ ok: boolean;
5
+ envvars: never[];
6
+ error: string;
7
+ } | {
4
8
  ok: boolean;
5
9
  envvars: any;
6
- error: any;
10
+ error: null;
7
11
  }>;
@@ -1,4 +1,5 @@
1
1
  import config from '../../../config.js';
2
+ import { extractFunctionsApiErrorMessage } from '../../../utils/functions/api-error.js';
2
3
  import getHeaders from '../../../utils/get-headers.js';
3
4
  import { createTracedFetch } from '../../../utils/traced-fetch.js';
4
5
  const { apiUrl } = config;
@@ -8,10 +9,9 @@ export async function list(id, auth, logger) {
8
9
  headers: getHeaders(auth),
9
10
  method: 'GET',
10
11
  });
12
+ if (!response.ok) {
13
+ return { ok: false, envvars: [], error: await extractFunctionsApiErrorMessage(response) };
14
+ }
11
15
  const json = await response.json();
12
- return {
13
- ok: response.ok,
14
- envvars: json.envvars,
15
- error: response.ok ? null : json?.error?.message,
16
- };
16
+ return { ok: true, envvars: json.envvars, error: null };
17
17
  }
@@ -2,5 +2,5 @@ import type { Logger } from '../../../utils/logger.js';
2
2
  import type { AuthParams } from '../../../utils/types.js';
3
3
  export declare function remove(id: string, key: string, auth: AuthParams, logger: Logger): Promise<{
4
4
  ok: boolean;
5
- error: any;
5
+ error: string | null;
6
6
  }>;
@@ -1,4 +1,5 @@
1
1
  import config from '../../../config.js';
2
+ import { extractFunctionsApiErrorMessage } from '../../../utils/functions/api-error.js';
2
3
  import getHeaders from '../../../utils/get-headers.js';
3
4
  import { createTracedFetch } from '../../../utils/traced-fetch.js';
4
5
  const { apiUrl } = config;
@@ -8,9 +9,8 @@ export async function remove(id, key, auth, logger) {
8
9
  headers: getHeaders(auth),
9
10
  method: 'DELETE',
10
11
  });
11
- const json = response.ok ? undefined : await response.json();
12
12
  return {
13
13
  ok: response.ok,
14
- error: response.ok ? null : json?.error?.message,
14
+ error: response.ok ? null : await extractFunctionsApiErrorMessage(response),
15
15
  };
16
16
  }
@@ -2,5 +2,5 @@ import type { Logger } from '../../../utils/logger.js';
2
2
  import type { AuthParams } from '../../../utils/types.js';
3
3
  export declare function update(id: string, key: string, value: string, auth: AuthParams, logger: Logger): Promise<{
4
4
  ok: boolean;
5
- error: any;
5
+ error: string | null;
6
6
  }>;
@@ -1,4 +1,5 @@
1
1
  import config from '../../../config.js';
2
+ import { extractFunctionsApiErrorMessage } from '../../../utils/functions/api-error.js';
2
3
  import getHeaders from '../../../utils/get-headers.js';
3
4
  import { createTracedFetch } from '../../../utils/traced-fetch.js';
4
5
  const { apiUrl } = config;
@@ -9,9 +10,8 @@ export async function update(id, key, value, auth, logger) {
9
10
  headers: getHeaders(auth),
10
11
  method: 'PUT',
11
12
  });
12
- const json = response.ok ? undefined : await response.json();
13
13
  return {
14
14
  ok: response.ok,
15
- error: response.ok ? null : json?.error?.message,
15
+ error: response.ok ? null : await extractFunctionsApiErrorMessage(response),
16
16
  };
17
17
  }
@@ -1,4 +1,5 @@
1
1
  import config from '../../config.js';
2
+ import { extractFunctionsApiErrorMessage } from '../../utils/functions/api-error.js';
2
3
  import getHeaders from '../../utils/get-headers.js';
3
4
  import { createTracedFetch } from '../../utils/traced-fetch.js';
4
5
  const { apiUrl } = config;
@@ -9,14 +10,10 @@ export async function listFunctions(auth, logger) {
9
10
  headers: getHeaders(auth),
10
11
  method: 'GET',
11
12
  });
12
- const payload = (await response.json());
13
13
  if (!response.ok) {
14
- return {
15
- ok: false,
16
- error: payload.error?.message ?? payload.message ?? 'Failed to list functions',
17
- functions: [],
18
- };
14
+ return { ok: false, error: await extractFunctionsApiErrorMessage(response), functions: [] };
19
15
  }
16
+ const payload = (await response.json());
20
17
  return {
21
18
  ok: true,
22
19
  error: null,
@@ -6,11 +6,15 @@ export interface LoggingOptions {
6
6
  }
7
7
  export declare function logs(id: string, options: LoggingOptions, auth: AuthParams, logger: Logger): Promise<{
8
8
  ok: boolean;
9
- error: any;
9
+ error: string;
10
+ logs: never[];
11
+ } | {
12
+ ok: boolean;
13
+ error: null;
10
14
  logs: any;
11
15
  }>;
12
16
  export declare function deleteLogs(id: string, auth: AuthParams, logger: Logger): Promise<{
13
17
  ok: boolean;
14
- error: any;
18
+ error: string | null;
15
19
  }>;
16
20
  export declare function streamLogs(id: string, auth: AuthParams, onLog: (log: FunctionLog) => void, onOpen: () => void, onError: (error: string) => void, logger: Logger): () => void;
@@ -1,5 +1,6 @@
1
1
  import { EventSource } from 'eventsource';
2
2
  import config from '../../config.js';
3
+ import { extractFunctionsApiErrorMessage } from '../../utils/functions/api-error.js';
3
4
  import getHeaders from '../../utils/get-headers.js';
4
5
  import { createTracedFetch } from '../../utils/traced-fetch.js';
5
6
  const { apiUrl } = config;
@@ -10,12 +11,11 @@ export async function logs(id, options, auth, logger) {
10
11
  headers: getHeaders(auth),
11
12
  method: 'GET',
12
13
  });
14
+ if (!response.ok) {
15
+ return { ok: false, error: await extractFunctionsApiErrorMessage(response), logs: [] };
16
+ }
13
17
  const json = await response.json();
14
- return {
15
- ok: response.ok,
16
- error: response.ok ? null : json?.error?.message,
17
- logs: response.ok ? json.logs : [],
18
- };
18
+ return { ok: true, error: null, logs: json.logs };
19
19
  }
20
20
  export async function deleteLogs(id, auth, logger) {
21
21
  const fetchFn = createTracedFetch(logger);
@@ -23,10 +23,9 @@ export async function deleteLogs(id, auth, logger) {
23
23
  headers: getHeaders(auth),
24
24
  method: 'DELETE',
25
25
  });
26
- const json = response.ok ? null : await response.json();
27
26
  return {
28
27
  ok: response.ok,
29
- error: response.ok ? null : json?.error?.message,
28
+ error: response.ok ? null : await extractFunctionsApiErrorMessage(response),
30
29
  };
31
30
  }
32
31
  // Create streaming logs connection
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,6 @@
1
+ /**
2
+ * Extracts a human-readable error message from a failed Functions HTTP API response.
3
+ * Specific to the Functions API, whose error bodies are produced by its `src/util/response.js` `errorResponse` helper:
4
+ * { error: 'INVALID_INPUT', message: 'Validation error: ...', details?: { errors: [{ message }] } }
5
+ */
6
+ export declare function extractFunctionsApiErrorMessage(response: Response): Promise<string>;
@@ -0,0 +1,25 @@
1
+ import { isRecord } from '../is-record.js';
2
+ import { parseJsonObject } from '../parse-json-object.js';
3
+ /**
4
+ * Extracts a human-readable error message from a failed Functions HTTP API response.
5
+ * Specific to the Functions API, whose error bodies are produced by its `src/util/response.js` `errorResponse` helper:
6
+ * { error: 'INVALID_INPUT', message: 'Validation error: ...', details?: { errors: [{ message }] } }
7
+ */
8
+ export async function extractFunctionsApiErrorMessage(response) {
9
+ const body = parseJsonObject(await response.text().catch(() => ''));
10
+ if (typeof body?.message === 'string' && body.message)
11
+ return body.message;
12
+ const detailMessages = getDetailErrorMessages(body?.details);
13
+ if (detailMessages.length > 0)
14
+ return detailMessages.join('\n');
15
+ if (typeof body?.error === 'string' && body.error)
16
+ return body.error;
17
+ return `HTTP ${response.status} ${response.statusText}`.trim();
18
+ }
19
+ function getDetailErrorMessages(details) {
20
+ if (!isRecord(details) || !Array.isArray(details.errors))
21
+ return [];
22
+ return details.errors
23
+ .map((e) => (isRecord(e) ? e.message : e))
24
+ .filter((m) => typeof m === 'string' && m.length > 0);
25
+ }
@@ -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
+ }