@sanity/runtime-cli 17.21.2-next.g6c4136d → 17.21.3-app-functions.g1a9a040

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 (34) hide show
  1. package/README.md +19 -19
  2. package/dist/actions/blueprints/stacks.d.ts +9 -3
  3. package/dist/actions/blueprints/stacks.js +11 -8
  4. package/dist/actions/blueprints/wait-for-operation.d.ts +1 -0
  5. package/dist/actions/blueprints/wait-for-operation.js +1 -1
  6. package/dist/cores/blueprints/deploy.d.ts +8 -0
  7. package/dist/cores/blueprints/deploy.js +12 -4
  8. package/dist/cores/blueprints/destroy.d.ts +14 -1
  9. package/dist/cores/blueprints/destroy.js +2 -1
  10. package/dist/functions/artifacts.d.ts +13 -0
  11. package/dist/functions/artifacts.js +26 -0
  12. package/dist/functions/build.d.ts +15 -0
  13. package/dist/functions/build.js +30 -0
  14. package/dist/functions/contractPlugin.d.ts +7 -0
  15. package/dist/functions/contractPlugin.js +32 -0
  16. package/dist/functions/contracts/schema.d.ts +22 -0
  17. package/dist/functions/contracts/schema.js +99 -0
  18. package/dist/functions/contracts/validation.d.ts +3 -0
  19. package/dist/functions/contracts/validation.js +66 -0
  20. package/dist/functions/contracts.d.ts +33 -0
  21. package/dist/functions/contracts.js +162 -0
  22. package/dist/functions/deploy.d.ts +16 -0
  23. package/dist/functions/deploy.js +69 -0
  24. package/dist/functions/schedule.d.ts +21 -0
  25. package/dist/functions/schedule.js +34 -0
  26. package/dist/functions/stack.d.ts +41 -0
  27. package/dist/functions/stack.js +153 -0
  28. package/dist/server/static/components/console-panel.js +4 -4
  29. package/dist/server/static/components/response-panel.js +6 -6
  30. package/dist/server/static/vendor/vendor.bundle.js +127 -78
  31. package/dist/utils/functions/transpile/function.d.ts +7 -1
  32. package/dist/utils/functions/transpile/function.js +15 -9
  33. package/oclif.manifest.json +1 -1
  34. package/package.json +41 -20
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.21.2-next.g6c4136d/src/commands/blueprints/add.ts)_
93
+ _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/config.ts)_
130
+ _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/deploy.ts)_
186
+ _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/destroy.ts)_
224
+ _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/doctor.ts)_
256
+ _See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/info.ts)_
294
+ _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/init.ts)_
358
+ _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/logs.ts)_
404
+ _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/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.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/plan.ts)_
482
+ _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/promote.ts)_
518
+ _See code: [src/commands/blueprints/promote.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/blueprints/stacks.ts)_
559
+ _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/functions/add.ts)_
611
+ _See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/functions/dev.ts)_
646
+ _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/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.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/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.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/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.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/functions/logs.ts)_
781
+ _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/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.21.2-next.g6c4136d/src/commands/functions/test.ts)_
839
+ _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.3-app-functions.g1a9a040/src/commands/functions/test.ts)_
840
840
 
841
841
  ## `sanity-run help [COMMAND]`
842
842
 
@@ -13,7 +13,11 @@ type ListStacksResponse = {
13
13
  stacks?: unknown;
14
14
  response?: Response;
15
15
  };
16
- export declare function listStacks(auth: AuthParams, logger: Logger): Promise<ListStacksResponse>;
16
+ export declare function listStacks(auth: AuthParams, logger: Logger, options?: {
17
+ fetchFn?: typeof fetch;
18
+ cursor?: string;
19
+ limit?: number;
20
+ }): Promise<ListStacksResponse>;
17
21
  type GetStackResponse = {
18
22
  ok: true;
19
23
  error: null;
@@ -31,10 +35,11 @@ export declare function getStack({ stackId, auth, fetchFn, }: {
31
35
  fetchFn: typeof fetch;
32
36
  }): Promise<GetStackResponse>;
33
37
  type CreateStackResponse = GetStackResponse;
34
- export declare function createStack({ stackMutation, auth, logger, }: {
38
+ export declare function createStack({ stackMutation, auth, logger, fetchFn, }: {
35
39
  stackMutation: StackMutation;
36
40
  auth: AuthParams;
37
41
  logger: Logger;
42
+ fetchFn?: typeof fetch;
38
43
  }): Promise<CreateStackResponse>;
39
44
  export declare function createEmptyStack({ token, scopeType, scopeId, name, logger, }: {
40
45
  token: string;
@@ -133,9 +138,10 @@ export declare function promoteStack({ stackId, auth, logger, name, }: {
133
138
  name?: string;
134
139
  }): Promise<PromoteStackResponse>;
135
140
  type DestroyStackResponse = UpdateStackResponse;
136
- export declare function destroyStack({ stackId, auth, logger, }: {
141
+ export declare function destroyStack({ stackId, auth, logger, fetchFn, }: {
137
142
  stackId: string;
138
143
  auth: AuthParams;
139
144
  logger: Logger;
145
+ fetchFn?: typeof fetch;
140
146
  }): Promise<DestroyStackResponse>;
141
147
  export {};
@@ -3,10 +3,15 @@ import getHeaders from '../../utils/get-headers.js';
3
3
  import { getRequestId } from '../../utils/request-id.js';
4
4
  import { createTracedFetch } from '../../utils/traced-fetch.js';
5
5
  export const stacksUrl = blueprintsUrl('stacks');
6
- export async function listStacks(auth, logger) {
7
- const fetchFn = createTracedFetch(logger);
6
+ export async function listStacks(auth, logger, options = {}) {
7
+ const fetchFn = options.fetchFn ?? createTracedFetch(logger);
8
+ const url = new URL(stacksUrl);
9
+ if (options.cursor)
10
+ url.searchParams.set('cursor', options.cursor);
11
+ if (options.limit !== undefined)
12
+ url.searchParams.set('limit', String(options.limit));
8
13
  try {
9
- const response = await fetchFn(stacksUrl, {
14
+ const response = await fetchFn(url.toString(), {
10
15
  method: 'GET',
11
16
  headers: getHeaders(auth),
12
17
  });
@@ -27,7 +32,7 @@ export async function listStacks(auth, logger) {
27
32
  }
28
33
  export async function getStack({ stackId, auth, fetchFn, }) {
29
34
  try {
30
- const response = await fetchFn(`${stacksUrl}/${stackId}`, {
35
+ const response = await fetchFn(`${stacksUrl}/${encodeURIComponent(stackId)}`, {
31
36
  method: 'GET',
32
37
  headers: getHeaders(auth),
33
38
  });
@@ -46,9 +51,8 @@ export async function getStack({ stackId, auth, fetchFn, }) {
46
51
  };
47
52
  }
48
53
  }
49
- export async function createStack({ stackMutation, auth, logger, }) {
54
+ export async function createStack({ stackMutation, auth, logger, fetchFn = createTracedFetch(logger), }) {
50
55
  try {
51
- const fetchFn = createTracedFetch(logger);
52
56
  const response = await fetchFn(stacksUrl, {
53
57
  method: 'POST',
54
58
  headers: getHeaders(auth),
@@ -194,8 +198,7 @@ export async function promoteStack({ stackId, auth, logger, name, }) {
194
198
  };
195
199
  }
196
200
  }
197
- export async function destroyStack({ stackId, auth, logger, }) {
198
- const fetchFn = createTracedFetch(logger);
201
+ export async function destroyStack({ stackId, auth, logger, fetchFn = createTracedFetch(logger), }) {
199
202
  try {
200
203
  const response = await fetchFn(`${stacksUrl}/${stackId}`, {
201
204
  method: 'DELETE',
@@ -8,6 +8,7 @@ export interface WaitForOperationOptions {
8
8
  log: Logger;
9
9
  bin: string;
10
10
  verbose?: boolean;
11
+ fetchFn?: typeof fetch;
11
12
  /** Keep the operation queryable after the stack is gone (destroy). */
12
13
  includeDestroyed?: boolean;
13
14
  /** Noun for the idle message, e.g. "deployment" or "destruction". */
@@ -9,7 +9,7 @@ import { classifyOperationPoll, getOperation } from './operations.js';
9
9
  */
10
10
  export async function waitForOperation(options) {
11
11
  const { stackId, operationId, auth, log, bin, verbose = false, includeDestroyed, progressNoun, } = options;
12
- const fetchFn = createTracedFetch(log);
12
+ const fetchFn = options.fetchFn ?? createTracedFetch(log);
13
13
  const waitFor = createWaitFor({
14
14
  bin,
15
15
  log,
@@ -1,3 +1,4 @@
1
+ import type { BlueprintResource } from '@sanity/blueprints';
1
2
  import type { ReadBlueprintResult } from '../../actions/blueprints/blueprint.js';
2
3
  import type { AuthParams, ScopeType, Stack } from '../../utils/types.js';
3
4
  import type { CoreConfig, CoreResult } from '../index.js';
@@ -19,3 +20,10 @@ export interface BlueprintDeployOptions extends CoreConfig {
19
20
  };
20
21
  }
21
22
  export declare function blueprintDeployCore(options: BlueprintDeployOptions): Promise<CoreResult>;
23
+ export interface ResourceDeployOptions extends Omit<BlueprintDeployOptions, 'blueprint'> {
24
+ resources: BlueprintResource[];
25
+ workDir: string;
26
+ fetchFn?: typeof fetch;
27
+ }
28
+ /** Deploy an in-memory resource list using the same pipeline as a Blueprint file. */
29
+ export declare function deployResourcesCore(options: ResourceDeployOptions): Promise<CoreResult>;
@@ -14,16 +14,23 @@ import { styleText } from '../../utils/style-text.js';
14
14
  import { createTracedFetch } from '../../utils/traced-fetch.js';
15
15
  import { getWarnings } from '../../utils/warnings.js';
16
16
  export async function blueprintDeployCore(options) {
17
- const { bin = 'sanity', log: logger, auth, stackId, scopeType, scopeId, deployedStack, blueprint, cliVersion, flags, } = options;
17
+ return deployResourcesCore({
18
+ ...options,
19
+ resources: options.blueprint.resources,
20
+ workDir: dirname(options.blueprint.fileInfo.blueprintFilePath),
21
+ });
22
+ }
23
+ /** Deploy an in-memory resource list using the same pipeline as a Blueprint file. */
24
+ export async function deployResourcesCore(options) {
25
+ const { bin = 'sanity', log: logger, auth, stackId, scopeType, scopeId, deployedStack, workDir: blueprintFileDir, cliVersion, flags, } = options;
18
26
  const { verbose } = flags;
19
27
  const noWait = flags['no-wait'] || false;
20
28
  const stackName = flags['new-stack-name'] ?? deployedStack.name;
21
29
  const installer = flags['fn-installer'] || undefined;
22
- const blueprintFileDir = dirname(blueprint.fileInfo.blueprintFilePath);
23
30
  const workspaceWarnings = getWarnings({ dir: blueprintFileDir });
24
31
  logger(`Deploying "${stackName}" ${niceId(deployedStack.id)}...`);
25
32
  try {
26
- const fetchFn = createTracedFetch(logger);
33
+ const fetchFn = options.fetchFn ?? createTracedFetch(logger);
27
34
  const { ok: checkOk, stack: currentStack } = await getStack({ stackId, auth, fetchFn });
28
35
  if (!checkOk) {
29
36
  return { success: false, error: 'Failed to check current Stack status' };
@@ -39,7 +46,7 @@ export async function blueprintDeployCore(options) {
39
46
  ],
40
47
  };
41
48
  }
42
- const resources = [...blueprint.resources];
49
+ const resources = [...options.resources];
43
50
  let spinner;
44
51
  const preDeployResult = await preDeploy({
45
52
  scopeType,
@@ -143,6 +150,7 @@ export async function blueprintDeployCore(options) {
143
150
  bin,
144
151
  verbose,
145
152
  progressNoun: 'deployment',
153
+ fetchFn,
146
154
  });
147
155
  if (outcome.type === 'completed') {
148
156
  logger(styleText(['bold', 'green'], 'Stack deployment completed!'));
@@ -1,5 +1,5 @@
1
1
  import { type LocatedBlueprintsConfig } from '../../actions/blueprints/config.js';
2
- import type { ScopeType } from '../../utils/types.js';
2
+ import type { AuthParams, ScopeType } from '../../utils/types.js';
3
3
  import type { CoreConfig, CoreResult } from '../index.js';
4
4
  export interface BlueprintDestroyOptions extends CoreConfig {
5
5
  token: string;
@@ -20,3 +20,16 @@ export interface BlueprintDestroyOptions extends CoreConfig {
20
20
  };
21
21
  }
22
22
  export declare function blueprintDestroyCore(options: BlueprintDestroyOptions): Promise<CoreResult>;
23
+ type WaitForDestructionOptions = {
24
+ stackId: string;
25
+ stackName: string;
26
+ operationId: string;
27
+ requestId?: string;
28
+ auth: AuthParams;
29
+ log: CoreConfig['log'];
30
+ bin: string;
31
+ verbose?: boolean;
32
+ fetchFn?: typeof fetch;
33
+ };
34
+ export declare function waitForDestruction(options: WaitForDestructionOptions): Promise<CoreResult>;
35
+ export {};
@@ -150,7 +150,7 @@ function afterDestroyAccepted(options) {
150
150
  }
151
151
  return waitForDestruction(options);
152
152
  }
153
- async function waitForDestruction(options) {
153
+ export async function waitForDestruction(options) {
154
154
  const { stackId, stackName, operationId, requestId, auth, log, bin, verbose = false } = options;
155
155
  log(styleText('dim', 'Stack destruction progress:'));
156
156
  log('');
@@ -163,6 +163,7 @@ async function waitForDestruction(options) {
163
163
  verbose,
164
164
  includeDestroyed: true,
165
165
  progressNoun: 'destruction',
166
+ fetchFn: options.fetchFn,
166
167
  });
167
168
  if (outcome.type === 'completed') {
168
169
  log(styleText(['bold', 'magenta'], 'Stack destruction completed!'));
@@ -0,0 +1,13 @@
1
+ export declare const functionOutputFileName = "index.js";
2
+ /** Metadata for a compiled function, resolved without loading its handler. */
3
+ export interface FunctionBuild {
4
+ name: string;
5
+ src: string;
6
+ entryPoint: string;
7
+ }
8
+ /** Validate artifacts produced by buildFunction before packaging or deployment. */
9
+ export declare function readFunctionBuild(options: {
10
+ name: string;
11
+ src: string;
12
+ workDir: string;
13
+ }): Promise<FunctionBuild>;
@@ -0,0 +1,26 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { findFunctionEntryPoint } from '../utils/functions/find-entry-point.js';
4
+ export const functionOutputFileName = 'index.js';
5
+ /** Validate artifacts produced by buildFunction before packaging or deployment. */
6
+ export async function readFunctionBuild(options) {
7
+ const { name, workDir } = options;
8
+ const src = path.resolve(workDir, options.src);
9
+ try {
10
+ const pkg = JSON.parse(await readFile(path.join(src, 'package.json'), 'utf8'));
11
+ if (!pkg ||
12
+ typeof pkg !== 'object' ||
13
+ !('main' in pkg) ||
14
+ pkg.main !== functionOutputFileName ||
15
+ !('type' in pkg) ||
16
+ pkg.type !== 'module')
17
+ throw new Error('The function package metadata does not match its build format.');
18
+ const entryPoint = await findFunctionEntryPoint(src, name);
19
+ if (entryPoint !== path.join(src, functionOutputFileName))
20
+ throw new Error(`The compiled entry ${functionOutputFileName} is missing.`);
21
+ return { name, src, entryPoint };
22
+ }
23
+ catch (error) {
24
+ throw new Error(`Function "${name}" is not built. Run sanity build first.`, { cause: error });
25
+ }
26
+ }
@@ -0,0 +1,15 @@
1
+ import { type FunctionContract } from './contracts.js';
2
+ export interface BuildFunctionOptions {
3
+ name: string;
4
+ contract?: FunctionContract;
5
+ /** Function directory or entry file, relative to workDir. */
6
+ src: string;
7
+ workDir: string;
8
+ /** Build output directory, relative to workDir. Its contents are replaced. */
9
+ outDir: string;
10
+ }
11
+ /** Build a standalone ESM function bundle without a blueprint, stack, or ZIP. */
12
+ export declare function buildFunction({ name, src, workDir, outDir, contract, }: BuildFunctionOptions): Promise<{
13
+ outputDir: string;
14
+ }>;
15
+ export { type FunctionBuild, readFunctionBuild } from './artifacts.js';
@@ -0,0 +1,30 @@
1
+ import path from 'node:path';
2
+ import { findFunctionEntryPoint } from '../utils/functions/find-entry-point.js';
3
+ import { transpileFunction } from '../utils/functions/transpile/function.js';
4
+ import { functionOutputFileName } from './artifacts.js';
5
+ import { functionContractPlugin } from './contractPlugin.js';
6
+ import { generateFunctionContracts } from './contracts.js';
7
+ /** Build a standalone ESM function bundle without a blueprint, stack, or ZIP. */
8
+ export async function buildFunction({ name, src, workDir, outDir, contract, }) {
9
+ const functionPath = path.resolve(workDir, src);
10
+ const entryPoint = await findFunctionEntryPoint(functionPath, name);
11
+ const resolvedContract = contract ?? (await generateFunctionContracts({ workDir, functions: [{ name, src }] }))[0];
12
+ if (resolvedContract.entryPoint !== entryPoint || resolvedContract.name !== name)
13
+ throw new Error(`Function contract does not match "${name}".`);
14
+ // Scheduled functions take no app input and return nothing, so they need no validation entry.
15
+ const validation = resolvedContract.type === 'pubsub' ? functionContractPlugin(resolvedContract) : undefined;
16
+ const result = await transpileFunction({
17
+ resource: resolvedContract.type === 'pubsub'
18
+ ? { name, src, type: 'sanity.function.pubsub' }
19
+ : { name, src, type: 'sanity.function.cron', event: resolvedContract.event },
20
+ functionPath,
21
+ entryPoint: validation?.entryPoint ?? entryPoint,
22
+ plugins: validation ? [validation.plugin] : [],
23
+ workDir,
24
+ outDir: path.resolve(workDir, outDir),
25
+ outputFileName: functionOutputFileName,
26
+ bundle: true,
27
+ });
28
+ return { outputDir: result.outputDir };
29
+ }
30
+ export { readFunctionBuild } from './artifacts.js';
@@ -0,0 +1,7 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { PubSubFunctionContract } from './contracts.js';
3
+ /** Build a validating PubSub entry around the original handler. */
4
+ export declare function functionContractPlugin(contract: PubSubFunctionContract): {
5
+ entryPoint: string;
6
+ plugin: Plugin;
7
+ };
@@ -0,0 +1,32 @@
1
+ import { jsonGuard, validatorSource } from './contracts/validation.js';
2
+ /** Build a validating PubSub entry around the original handler. */
3
+ export function functionContractPlugin(contract) {
4
+ const entryPoint = `virtual:sanity-function-contract:${contract.name}`;
5
+ const resolvedId = `\0${entryPoint}`;
6
+ const source = `import {handler as implementation} from ${JSON.stringify(contract.entryPoint.replaceAll('\\', '/'))}
7
+ ${jsonGuard}
8
+ const validateInput = ${validatorSource(contract.input)}
9
+ const validateOutput = ${validatorSource(contract.output)}
10
+ export async function handler(envelope) {
11
+ let input = envelope?.event?.data
12
+ ${contract.input.kind === 'void' ? "if (input !== null && typeof input === 'object' && !Array.isArray(input) && Object.keys(input).length === 0) input = undefined" : ''}
13
+ if (!validateInput(input)) throw new TypeError(${JSON.stringify(`Invalid input for function "${contract.name}". Match its declared input type.`)})
14
+ const result = await implementation(envelope)
15
+ if (!validateOutput(result)) throw new TypeError(${JSON.stringify(`Function "${contract.name}" returned data that does not match its declared return type.`)})
16
+ return result
17
+ }`;
18
+ return {
19
+ entryPoint,
20
+ plugin: {
21
+ name: 'sanity/function-contract',
22
+ resolveId(id) {
23
+ if (id === entryPoint)
24
+ return resolvedId;
25
+ },
26
+ load(id) {
27
+ if (id === resolvedId)
28
+ return source;
29
+ },
30
+ },
31
+ };
32
+ }
@@ -0,0 +1,22 @@
1
+ import ts from 'typescript-compiler';
2
+ export type ContractSchema = {
3
+ kind: 'string' | 'number' | 'boolean' | 'null' | 'void' | 'never';
4
+ } | {
5
+ kind: 'literal';
6
+ value: string | number | boolean;
7
+ } | {
8
+ kind: 'array';
9
+ items: ContractSchema;
10
+ } | {
11
+ kind: 'union';
12
+ variants: ContractSchema[];
13
+ } | {
14
+ kind: 'object';
15
+ properties: Record<string, {
16
+ optional: boolean;
17
+ schema: ContractSchema;
18
+ }>;
19
+ additional?: ContractSchema;
20
+ };
21
+ export declare function schemaFromType(checker: ts.TypeChecker, type: ts.Type, location: string, allowVoid?: boolean, parents?: Set<ts.Type>): ContractSchema;
22
+ export declare function contractType(schema: ContractSchema): string;
@@ -0,0 +1,99 @@
1
+ import ts from 'typescript-compiler';
2
+ export function schemaFromType(checker, type, location, allowVoid = false, parents = new Set()) {
3
+ const fail = (reason) => {
4
+ throw new Error(`${location}: ${reason} (${checker.typeToString(type)}). Use a concrete JSON-compatible type.`);
5
+ };
6
+ const flags = type.flags;
7
+ if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.TypeParameter))
8
+ return fail('Unresolved or untyped contract');
9
+ if (flags & ts.TypeFlags.Never)
10
+ return { kind: 'never' };
11
+ if (flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) {
12
+ if (!allowVoid)
13
+ return fail('Undefined is only supported for optional object fields or a void result');
14
+ return { kind: 'void' };
15
+ }
16
+ if (flags & ts.TypeFlags.Null)
17
+ return { kind: 'null' };
18
+ if (flags & ts.TypeFlags.StringLiteral)
19
+ return { kind: 'literal', value: type.value };
20
+ if (flags & ts.TypeFlags.NumberLiteral)
21
+ return { kind: 'literal', value: type.value };
22
+ if (flags & ts.TypeFlags.BooleanLiteral)
23
+ return { kind: 'literal', value: checker.typeToString(type) === 'true' };
24
+ if (flags & ts.TypeFlags.String)
25
+ return { kind: 'string' };
26
+ if (flags & ts.TypeFlags.Number)
27
+ return { kind: 'number' };
28
+ if (flags & ts.TypeFlags.Boolean)
29
+ return { kind: 'boolean' };
30
+ if (parents.has(type) || parents.size > 64)
31
+ return fail('Recursive or excessively nested contract');
32
+ const next = new Set(parents).add(type);
33
+ if (type.isUnion())
34
+ return {
35
+ kind: 'union',
36
+ variants: type.types.map((item) => schemaFromType(checker, item, location, allowVoid, next)),
37
+ };
38
+ if (checker.isTupleType(type))
39
+ return fail('Tuple contracts are not supported; use an array');
40
+ if (checker.isArrayType(type)) {
41
+ const element = checker.getTypeArguments(type)[0];
42
+ return { kind: 'array', items: schemaFromType(checker, element, `${location}[]`, false, next) };
43
+ }
44
+ if (!(flags & (ts.TypeFlags.Object | ts.TypeFlags.Intersection)))
45
+ return fail('Unsupported contract');
46
+ if (type.getCallSignatures().length || type.getConstructSignatures().length)
47
+ return fail('Functions and constructors cannot cross the function boundary');
48
+ if (type
49
+ .getSymbol()
50
+ ?.getDeclarations()
51
+ ?.some((declaration) => ts.isClassDeclaration(declaration) || ts.isClassExpression(declaration)))
52
+ return fail('Class instances cannot cross the function boundary');
53
+ if (checker.getIndexTypeOfType(type, ts.IndexKind.Number))
54
+ return fail('Numeric index signatures are not supported; use an array or string-keyed record');
55
+ const properties = Object.create(null);
56
+ for (const property of checker.getPropertiesOfType(type)) {
57
+ const name = property.getName();
58
+ if (name.startsWith('__@'))
59
+ return fail('Symbol properties cannot cross the function boundary');
60
+ const declaration = property.valueDeclaration ?? property.declarations?.[0];
61
+ if (!declaration)
62
+ return fail(`Cannot resolve property ${name}`);
63
+ const propertyType = checker.getTypeOfSymbolAtLocation(property, declaration);
64
+ const optional = !!(property.flags & ts.SymbolFlags.Optional);
65
+ const members = optional
66
+ ? (propertyType.isUnion() ? propertyType.types : [propertyType]).filter((member) => !(member.flags & ts.TypeFlags.Undefined))
67
+ : [propertyType];
68
+ const schemas = members.map((member) => schemaFromType(checker, member, `${location}.${name}`, false, next));
69
+ properties[name] = {
70
+ optional,
71
+ schema: schemas.length === 0
72
+ ? { kind: 'never' }
73
+ : schemas.length === 1
74
+ ? schemas[0]
75
+ : { kind: 'union', variants: schemas },
76
+ };
77
+ }
78
+ const indexType = checker.getIndexTypeOfType(type, ts.IndexKind.String);
79
+ const additional = indexType
80
+ ? schemaFromType(checker, indexType, `${location}[key]`, false, next)
81
+ : undefined;
82
+ return { kind: 'object', properties, ...(additional ? { additional } : {}) };
83
+ }
84
+ export function contractType(schema) {
85
+ switch (schema.kind) {
86
+ case 'literal':
87
+ return JSON.stringify(schema.value);
88
+ case 'array':
89
+ return `(${contractType(schema.items)})[]`;
90
+ case 'union':
91
+ return schema.variants.map(contractType).join(' | ');
92
+ case 'object':
93
+ return `{${Object.entries(schema.properties)
94
+ .map(([name, property]) => `${JSON.stringify(name)}${property.optional ? '?' : ''}: ${contractType(property.schema)};`)
95
+ .join(' ')}${schema.additional ? `[key: string]: ${contractType(schema.additional)};` : ''}}`;
96
+ default:
97
+ return schema.kind;
98
+ }
99
+ }
@@ -0,0 +1,3 @@
1
+ import type { ContractSchema } from './schema.js';
2
+ export declare const jsonGuard = "function isJson(value, seen = new WeakSet(), depth = 0) {\n if (depth > 100) return false\n if (value === undefined || value === null) return true\n if (typeof value === 'string' || typeof value === 'boolean') return true\n if (typeof value === 'number') return Number.isFinite(value)\n if (typeof value !== 'object' || seen.has(value) || Object.getOwnPropertySymbols(value).length) return false\n seen.add(value)\n try {\n if (Array.isArray(value)) {\n if (Object.keys(value).length !== value.length) return false\n for (let index = 0; index < value.length; index++) {\n if (!Object.hasOwn(value, index) || value[index] === undefined || !isJson(value[index], seen, depth + 1)) return false\n }\n return true\n }\n const prototype = Object.getPrototypeOf(value)\n return (prototype === Object.prototype || prototype === null) && Object.values(value).every(item => isJson(item, seen, depth + 1))\n } finally { seen.delete(value) }\n}";
3
+ export declare function validatorSource(schema: ContractSchema): string;