@sanity/runtime-cli 17.21.2 → 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 +990 -990
  34. package/package.json +41 -20
@@ -0,0 +1,66 @@
1
+ // Self-contained code emitted into browser contracts and function bundles.
2
+ export const jsonGuard = `function isJson(value, seen = new WeakSet(), depth = 0) {
3
+ if (depth > 100) return false
4
+ if (value === undefined || value === null) return true
5
+ if (typeof value === 'string' || typeof value === 'boolean') return true
6
+ if (typeof value === 'number') return Number.isFinite(value)
7
+ if (typeof value !== 'object' || seen.has(value) || Object.getOwnPropertySymbols(value).length) return false
8
+ seen.add(value)
9
+ try {
10
+ if (Array.isArray(value)) {
11
+ if (Object.keys(value).length !== value.length) return false
12
+ for (let index = 0; index < value.length; index++) {
13
+ if (!Object.hasOwn(value, index) || value[index] === undefined || !isJson(value[index], seen, depth + 1)) return false
14
+ }
15
+ return true
16
+ }
17
+ const prototype = Object.getPrototypeOf(value)
18
+ return (prototype === Object.prototype || prototype === null) && Object.values(value).every(item => isJson(item, seen, depth + 1))
19
+ } finally { seen.delete(value) }
20
+ }`;
21
+ export function validatorSource(schema) {
22
+ return `(value) => isJson(value) && (${validationExpression(schema, 'value')})`;
23
+ }
24
+ function validationExpression(schema, value, depth = 0) {
25
+ switch (schema.kind) {
26
+ case 'void':
27
+ return `${value} === undefined`;
28
+ case 'never':
29
+ return 'false';
30
+ case 'null':
31
+ return `${value} === null`;
32
+ case 'literal':
33
+ return `${value} === ${JSON.stringify(schema.value)}`;
34
+ case 'number':
35
+ return `(typeof ${value} === 'number' && Number.isFinite(${value}))`;
36
+ case 'string':
37
+ case 'boolean':
38
+ return `typeof ${value} === '${schema.kind}'`;
39
+ case 'union':
40
+ return `(${schema.variants.map((item) => `(${validationExpression(item, value, depth + 1)})`).join(' || ')})`;
41
+ case 'array': {
42
+ const item = `item${depth}`;
43
+ return `(Array.isArray(${value}) && ${value}.every(${item} => ${validationExpression(schema.items, item, depth + 1)}))`;
44
+ }
45
+ case 'object': {
46
+ const checks = [
47
+ `${value} !== null`,
48
+ `typeof ${value} === 'object'`,
49
+ `!Array.isArray(${value})`,
50
+ ];
51
+ for (const [name, property] of Object.entries(schema.properties)) {
52
+ const member = `${value}[${JSON.stringify(name)}]`;
53
+ const present = `Object.hasOwn(${value}, ${JSON.stringify(name)})`;
54
+ const check = validationExpression(property.schema, member, depth + 1);
55
+ checks.push(property.optional
56
+ ? `(!${present} || ${member} === undefined || (${check}))`
57
+ : `(${present} && (${check}))`);
58
+ }
59
+ if (schema.additional) {
60
+ const key = `key${depth}`;
61
+ checks.push(`Object.keys(${value}).every(${key} => ${JSON.stringify(Object.keys(schema.properties))}.includes(${key}) || (${validationExpression(schema.additional, `${value}[${key}]`, depth + 1)}))`);
62
+ }
63
+ return `(${checks.join(' && ')})`;
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,33 @@
1
+ import { type ContractSchema } from './contracts/schema.js';
2
+ import { type FunctionTrigger } from './schedule.js';
3
+ interface FunctionContractBase {
4
+ name: string;
5
+ src: string;
6
+ entryPoint: string;
7
+ }
8
+ /** A function the app calls, with validated input and output. */
9
+ export interface PubSubFunctionContract extends FunctionContractBase {
10
+ type: 'pubsub';
11
+ input: ContractSchema;
12
+ output: ContractSchema;
13
+ }
14
+ /** A function Sanity runs on a schedule. It is not callable from the app. */
15
+ export type ScheduledFunctionContract = FunctionContractBase & Extract<FunctionTrigger, {
16
+ type: 'cron';
17
+ }>;
18
+ export type FunctionContract = PubSubFunctionContract | ScheduledFunctionContract;
19
+ export type { FunctionTrigger, ScheduledFunctionEvent } from './schedule.js';
20
+ /** The trigger to deploy for a function contract. */
21
+ export declare function functionTrigger(contract: FunctionContract): FunctionTrigger;
22
+ /** Discover input and output types without loading or executing function code. */
23
+ export declare function generateFunctionContracts(options: {
24
+ workDir: string;
25
+ functions: {
26
+ name: string;
27
+ src: string;
28
+ }[];
29
+ }): Promise<FunctionContract[]>;
30
+ /** Check app consumers after regenerating their function registry. */
31
+ export declare function checkFunctionTypes(workDir: string): void;
32
+ /** Emit a standalone declaration registry and browser-safe validators. */
33
+ export declare function writeFunctionContracts(workDir: string, allContracts: FunctionContract[]): Promise<void>;
@@ -0,0 +1,162 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import ts from 'typescript-compiler';
4
+ import { findFunctionEntryPoint } from '../utils/functions/find-entry-point.js';
5
+ import { contractType, schemaFromType } from './contracts/schema.js';
6
+ import { jsonGuard, validatorSource } from './contracts/validation.js';
7
+ import { scheduledTrigger, scheduleFields } from './schedule.js';
8
+ /** The trigger to deploy for a function contract. */
9
+ export function functionTrigger(contract) {
10
+ if (contract.type === 'pubsub')
11
+ return { type: 'pubsub' };
12
+ const { event, timezone } = contract;
13
+ return { type: 'cron', event, ...(timezone ? { timezone } : {}) };
14
+ }
15
+ /** Discover input and output types without loading or executing function code. */
16
+ export async function generateFunctionContracts(options) {
17
+ const entries = await Promise.all(options.functions.map(async (fn) => ({
18
+ ...fn,
19
+ entryPoint: await findFunctionEntryPoint(path.resolve(options.workDir, fn.src), fn.name),
20
+ })));
21
+ const config = readProjectConfig(options.workDir);
22
+ const program = ts.createProgram(entries.map((fn) => fn.entryPoint), {
23
+ target: ts.ScriptTarget.ESNext,
24
+ module: ts.ModuleKind.ESNext,
25
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
26
+ ...config?.options,
27
+ allowJs: true,
28
+ checkJs: true,
29
+ noEmit: true,
30
+ strict: true,
31
+ strictNullChecks: true,
32
+ skipLibCheck: true,
33
+ composite: false,
34
+ incremental: false,
35
+ declaration: false,
36
+ declarationMap: false,
37
+ tsBuildInfoFile: undefined,
38
+ });
39
+ assertDiagnostics(ts.getPreEmitDiagnostics(program), options.workDir);
40
+ const checker = program.getTypeChecker();
41
+ return entries.map((fn) => readContract(checker, program, fn));
42
+ }
43
+ /** Check app consumers after regenerating their function registry. */
44
+ export function checkFunctionTypes(workDir) {
45
+ const config = readProjectConfig(workDir);
46
+ if (!config)
47
+ return;
48
+ const program = ts.createProgram({
49
+ rootNames: config.fileNames,
50
+ options: { ...config.options, noEmit: true, incremental: false, tsBuildInfoFile: undefined },
51
+ projectReferences: config.projectReferences,
52
+ });
53
+ assertDiagnostics(ts.getPreEmitDiagnostics(program), workDir);
54
+ }
55
+ function readProjectConfig(workDir) {
56
+ const configPath = ts.findConfigFile(workDir, ts.sys.fileExists);
57
+ if (!configPath)
58
+ return undefined;
59
+ const config = ts.readConfigFile(configPath, ts.sys.readFile);
60
+ if (config.error)
61
+ assertDiagnostics([config.error], workDir);
62
+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, path.dirname(configPath));
63
+ assertDiagnostics(parsed.errors, workDir);
64
+ return parsed;
65
+ }
66
+ function assertDiagnostics(diagnostics, workDir) {
67
+ const errors = diagnostics.filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error);
68
+ if (errors.length)
69
+ throw new Error(ts.formatDiagnostics(errors, {
70
+ getCanonicalFileName: (file) => file,
71
+ getCurrentDirectory: () => workDir,
72
+ getNewLine: () => '\n',
73
+ }));
74
+ }
75
+ function readContract(checker, program, fn) {
76
+ const source = program.getSourceFile(fn.entryPoint);
77
+ const module = source && checker.getSymbolAtLocation(source);
78
+ const exported = module && checker.getExportsOfModule(module).find((item) => item.getName() === 'handler');
79
+ if (!source || !exported)
80
+ throw new Error(`Function "${fn.name}" must export handler.`);
81
+ const handlerType = checker.getTypeOfSymbolAtLocation(exported, source);
82
+ const schedule = handlerType.getProperty('schedule');
83
+ if (schedule)
84
+ return { ...fn, ...readSchedule(checker, source, handlerType, schedule, fn.name) };
85
+ const signatures = handlerType.getCallSignatures();
86
+ if (signatures.length !== 1)
87
+ throw new Error(`Function "${fn.name}" must have one handler signature.`);
88
+ const signature = signatures[0];
89
+ if (signature.parameters.length > 1)
90
+ throw new Error(`Function "${fn.name}" must accept a single FunctionArgs envelope.`);
91
+ let input = { kind: 'void' };
92
+ const parameter = signature.parameters[0];
93
+ if (parameter) {
94
+ const args = checker.getTypeOfSymbolAtLocation(parameter, source);
95
+ const event = args.getProperty('event');
96
+ const eventType = event && checker.getTypeOfSymbolAtLocation(event, source);
97
+ const data = eventType?.getProperty('data');
98
+ if (!data)
99
+ throw new Error(`Function "${fn.name}" must annotate its input with FunctionArgs<Input>.`);
100
+ input = schemaFromType(checker, checker.getTypeOfSymbolAtLocation(data, source), `${fn.name} input`, true);
101
+ }
102
+ const isObjectInput = (schema) => schema.kind === 'object' || (schema.kind === 'union' && schema.variants.every(isObjectInput));
103
+ if (input.kind !== 'void' && !isObjectInput(input))
104
+ throw new Error(`Function "${fn.name}" input must be a JSON object or omitted. Put scalar values inside an input object.`);
105
+ const returnType = checker.getReturnTypeOfSignature(signature);
106
+ const output = schemaFromType(checker, checker.getAwaitedType(returnType) ?? returnType, `${fn.name} output`, true);
107
+ return { ...fn, type: 'pubsub', input, output };
108
+ }
109
+ /** Read a scheduledHandler's schedule from its literal types, without running the module. */
110
+ function readSchedule(checker, source, handlerType, schedule, name) {
111
+ const literal = (type) => type?.isStringLiteral() ? type.value : undefined;
112
+ const typeOf = (symbol) => symbol && checker.getTypeOfSymbolAtLocation(symbol, source);
113
+ const notLiteral = (what) => new Error(`Function "${name}" must declare its ${what} as a literal in scheduledHandler. Values computed at runtime or read from the environment cannot be deployed.`);
114
+ const scheduleType = typeOf(schedule);
115
+ const expression = literal(scheduleType);
116
+ let event;
117
+ if (expression !== undefined) {
118
+ event = { expression };
119
+ }
120
+ else {
121
+ const fields = scheduleFields.map((field) => [
122
+ field,
123
+ literal(typeOf(scheduleType?.getProperty(field))),
124
+ ]);
125
+ if (fields.some(([, value]) => value === undefined))
126
+ throw notLiteral('schedule');
127
+ event = Object.fromEntries(fields);
128
+ }
129
+ const timezoneType = typeOf(handlerType.getProperty('timezone'));
130
+ let timezone;
131
+ if (timezoneType && !(timezoneType.flags & ts.TypeFlags.Undefined)) {
132
+ timezone = literal(timezoneType);
133
+ if (timezone === undefined)
134
+ throw notLiteral('timezone');
135
+ }
136
+ return scheduledTrigger(name, event, timezone);
137
+ }
138
+ const generatedHeader = '// Generated by Sanity CLI. Do not edit.\n';
139
+ /** Emit a standalone declaration registry and browser-safe validators. */
140
+ export async function writeFunctionContracts(workDir, allContracts) {
141
+ // Scheduled functions have no caller, so the app only sees callable functions.
142
+ const contracts = allContracts.filter((fn) => fn.type === 'pubsub');
143
+ const declarations = `${generatedHeader}import '@sanity/sdk'\n\ndeclare module '@sanity/sdk' {\n interface AppFunctionRegistry {\n${contracts.map((fn) => ` ${JSON.stringify(fn.name)}: {input: ${contractType(fn.input)}; output: ${contractType(fn.output)}}`).join('\n')}\n }\n}\n`;
144
+ const client = `${generatedHeader}${jsonGuard}\nexport const functionContracts = Object.fromEntries([\n${contracts.map((fn) => `[${JSON.stringify(fn.name)}, {hasInput: ${fn.input.kind !== 'void'}, validateInput: ${validatorSource(fn.input)}, validateOutput: ${validatorSource(fn.output)}}]`).join(',\n')}\n])\n`;
145
+ await writeGenerated(path.join(workDir, 'sanity.functions.d.ts'), declarations);
146
+ await writeGenerated(path.join(workDir, '.sanity', 'function-contracts.js'), client);
147
+ }
148
+ async function writeGenerated(file, content) {
149
+ try {
150
+ const previous = await readFile(file, 'utf8');
151
+ if (!previous.startsWith(generatedHeader))
152
+ throw new Error(`Refusing to overwrite non-generated file ${file}. Move it before generating function contracts.`);
153
+ if (previous === content)
154
+ return;
155
+ }
156
+ catch (error) {
157
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
158
+ throw error;
159
+ }
160
+ await mkdir(path.dirname(file), { recursive: true });
161
+ await writeFile(file, content);
162
+ }
@@ -0,0 +1,16 @@
1
+ import type { CoreResult } from '../cores/index.js';
2
+ import { type FunctionTrigger } from './schedule.js';
3
+ /** Deploy already-built PubSub and scheduled functions to an app-owned organization stack. */
4
+ export declare function deployFunctions(options: {
5
+ appId: string;
6
+ organizationId: string;
7
+ stackId: string;
8
+ workDir: string;
9
+ functions: ({
10
+ name: string;
11
+ src: string;
12
+ } & FunctionTrigger)[];
13
+ token: string;
14
+ fetchFn: typeof fetch;
15
+ log: (message: string) => void;
16
+ }): Promise<CoreResult>;
@@ -0,0 +1,69 @@
1
+ import { getStack } from '../actions/blueprints/stacks.js';
2
+ import { deployResourcesCore } from '../cores/blueprints/deploy.js';
3
+ import { Logger } from '../utils/logger.js';
4
+ import { readFunctionBuild } from './artifacts.js';
5
+ import { scheduledTrigger } from './schedule.js';
6
+ import { assertAppFunctionStack, isAppFunctionResource } from './stack.js';
7
+ /** Deploy already-built PubSub and scheduled functions to an app-owned organization stack. */
8
+ export async function deployFunctions(options) {
9
+ const { organizationId, stackId, workDir, fetchFn } = options;
10
+ const auth = {
11
+ token: options.token,
12
+ scopeType: 'organization',
13
+ scopeId: organizationId,
14
+ };
15
+ const result = await getStack({ stackId, auth, fetchFn });
16
+ if (!result.ok)
17
+ return { success: false, error: result.error || 'Could not read app function stack' };
18
+ const stack = result.stack;
19
+ try {
20
+ assertAppFunctionStack(stack, options);
21
+ }
22
+ catch (error) {
23
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
24
+ }
25
+ if (!stack.resources.every(isAppFunctionResource)) {
26
+ return {
27
+ success: false,
28
+ error: 'The app function stack contains other resource types. Use a dedicated app function stack.',
29
+ };
30
+ }
31
+ const resources = [];
32
+ for (const fn of options.functions) {
33
+ let resource;
34
+ try {
35
+ const { src } = await readFunctionBuild({ name: fn.name, src: fn.src, workDir });
36
+ const common = { name: fn.name, src, transpile: false, autoResolveDeps: false };
37
+ if (fn.type === 'pubsub') {
38
+ resource = { ...common, type: 'sanity.function.pubsub' };
39
+ }
40
+ else {
41
+ // Revalidate: --no-build deploys a manifest written by an earlier build.
42
+ const { event, timezone } = scheduledTrigger(fn.name, fn.event, fn.timezone);
43
+ resource = {
44
+ ...common,
45
+ type: 'sanity.function.cron',
46
+ event,
47
+ ...(timezone ? { timezone: timezone } : {}),
48
+ };
49
+ }
50
+ }
51
+ catch (error) {
52
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
53
+ }
54
+ resources.push(resource);
55
+ }
56
+ return deployResourcesCore({
57
+ auth,
58
+ stackId,
59
+ scopeType: 'organization',
60
+ scopeId: organizationId,
61
+ deployedStack: stack,
62
+ resources,
63
+ workDir,
64
+ fetchFn,
65
+ bin: 'sanity',
66
+ flags: {},
67
+ log: Logger(options.log, { json: true }),
68
+ });
69
+ }
@@ -0,0 +1,21 @@
1
+ import { type BlueprintScheduledFunctionConfigEvent, type BlueprintScheduledFunctionResource, type BlueprintScheduledFunctionResourceEvent } from '@sanity/blueprints';
2
+ /** IANA timezone names accepted by Blueprint scheduled functions. */
3
+ export type ScheduleTimezone = NonNullable<BlueprintScheduledFunctionResource['timezone']>;
4
+ /** Explicit cron fields stored for a scheduled app function. */
5
+ export type ScheduledFunctionEvent = BlueprintScheduledFunctionResourceEvent;
6
+ /** How Sanity invokes an app function. */
7
+ export type FunctionTrigger = {
8
+ type: 'pubsub';
9
+ } | {
10
+ type: 'cron';
11
+ event: ScheduledFunctionEvent;
12
+ timezone?: string;
13
+ };
14
+ export declare const scheduleFields: readonly ['minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
15
+ /**
16
+ * Validate a schedule with the Blueprint rules and normalize natural language or cron
17
+ * expressions to explicit fields, so build output and deploys agree on the same schedule.
18
+ */
19
+ export declare function scheduledTrigger(name: string, event: BlueprintScheduledFunctionConfigEvent, timezone?: string): Extract<FunctionTrigger, {
20
+ type: 'cron';
21
+ }>;
@@ -0,0 +1,34 @@
1
+ import { defineScheduledFunction, validateScheduledFunction, } from '@sanity/blueprints';
2
+ export const scheduleFields = ['minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
3
+ /**
4
+ * Validate a schedule with the Blueprint rules and normalize natural language or cron
5
+ * expressions to explicit fields, so build output and deploys agree on the same schedule.
6
+ */
7
+ export function scheduledTrigger(name, event, timezone) {
8
+ try {
9
+ // Blueprints only exposes its expression parser through the definer. The definer records
10
+ // validation errors for blueprint files instead of throwing, so validate separately.
11
+ const parsed = 'expression' in event
12
+ ? defineScheduledFunction({ name, event: { expression: event.expression } }).event
13
+ : event;
14
+ const { minute, hour, dayOfMonth, month, dayOfWeek } = parsed;
15
+ const trigger = {
16
+ type: 'cron',
17
+ event: { minute, hour, dayOfMonth, month, dayOfWeek },
18
+ ...(timezone === undefined ? {} : { timezone }),
19
+ };
20
+ const errors = validateScheduledFunction({
21
+ name,
22
+ type: 'sanity.function.cron',
23
+ event: trigger.event,
24
+ ...(timezone === undefined ? {} : { timezone: timezone }),
25
+ });
26
+ if (errors.length)
27
+ throw new Error(errors.map((error) => error.message).join(' '));
28
+ return trigger;
29
+ }
30
+ catch (error) {
31
+ const message = error instanceof Error ? error.message : String(error);
32
+ throw new Error(`Function "${name}" has an invalid schedule: ${message}`, { cause: error });
33
+ }
34
+ }
@@ -0,0 +1,41 @@
1
+ import type { CoreResult } from '../cores/index.js';
2
+ import type { Stack, StackSummary } from '../utils/types.js';
3
+ interface AppFunctionIdentity {
4
+ appId: string;
5
+ organizationId: string;
6
+ }
7
+ /** Shared ownership check for provisioning and deploying an app's function stack. */
8
+ export declare function assertAppFunctionStack(stack: Stack | StackSummary, { appId, organizationId }: AppFunctionIdentity): void;
9
+ /** Resolve or create a dedicated app stack using the Blueprint stack operations. */
10
+ export declare function ensureFunctionStack(options: AppFunctionIdentity & {
11
+ token: string;
12
+ fetchFn: typeof fetch;
13
+ stackId?: string;
14
+ dryRun?: boolean;
15
+ }): Promise<{
16
+ created: boolean;
17
+ id: string;
18
+ } | null>;
19
+ /** App stacks hold only the function types the CLI deploys, so other resources are never replaced. */
20
+ export declare function isAppFunctionResource(resource: {
21
+ type: string;
22
+ }): boolean;
23
+ export { BLUEPRINTS_API_VERSION } from '../config.js';
24
+ /** Scope and transport for looking up an app's function stack. */
25
+ export interface FunctionStackOptions extends AppFunctionIdentity {
26
+ token: string;
27
+ fetchFn: typeof fetch;
28
+ stackId?: string;
29
+ }
30
+ /** Read-only stack metadata for an undeploy plan. */
31
+ export interface FunctionStackInfo {
32
+ id: string;
33
+ functions: string[];
34
+ }
35
+ /** Find an app-owned stack without creating one, and verify all resources are app functions. */
36
+ export declare function inspectFunctionStack(options: FunctionStackOptions): Promise<FunctionStackInfo | null>;
37
+ /** Destroy an app's stack using Blueprint deletion and operation polling. Missing stacks are already clean. */
38
+ export declare function destroyFunctionStack(options: FunctionStackOptions & {
39
+ stackId: string;
40
+ log: (message: string) => void;
41
+ }): Promise<CoreResult>;
@@ -0,0 +1,153 @@
1
+ import { createStack, destroyStack, getStack, listStacks } from '../actions/blueprints/stacks.js';
2
+ import { waitForDestruction } from '../cores/blueprints/destroy.js';
3
+ import { Logger } from '../utils/logger.js';
4
+ /** Shared ownership check for provisioning and deploying an app's function stack. */
5
+ export function assertAppFunctionStack(stack, { appId, organizationId }) {
6
+ if (!stack ||
7
+ typeof stack.id !== 'string' ||
8
+ !stack.id ||
9
+ stack.name !== appFunctionStackName(appId) ||
10
+ stack.scopeType !== 'organization' ||
11
+ stack.scopeId !== organizationId) {
12
+ throw new Error(`The function stack does not belong to app "${appId}" in organization "${organizationId}". Check .sanity/app-functions.json.`);
13
+ }
14
+ }
15
+ /** Resolve or create a dedicated app stack using the Blueprint stack operations. */
16
+ export async function ensureFunctionStack(options) {
17
+ const { appId, organizationId, token, fetchFn, stackId, dryRun = false } = options;
18
+ const auth = { token, scopeType: 'organization', scopeId: organizationId };
19
+ const name = appFunctionStackName(appId);
20
+ const logger = Logger(() => { }, { json: true });
21
+ const resolved = (stack, created) => {
22
+ assertAppFunctionStack(stack, options);
23
+ return { created, id: stack.id };
24
+ };
25
+ if (stackId) {
26
+ const result = await getStack({ stackId, auth, fetchFn });
27
+ if (result.ok)
28
+ return resolved(result.stack, false);
29
+ if (result.response?.status !== 404)
30
+ throw stackRequestError(result);
31
+ }
32
+ async function findStack() {
33
+ let cursor;
34
+ const cursors = new Set();
35
+ do {
36
+ const result = await listStacks(auth, logger, { fetchFn, cursor, limit: 500 });
37
+ if (!result.ok)
38
+ throw stackRequestError(result);
39
+ if (!Array.isArray(result.stacks))
40
+ throw new Error('Invalid Blueprint stack list response.');
41
+ const stack = result.stacks.find((item) => item?.name === name);
42
+ if (stack)
43
+ return stack;
44
+ if (result.response?.headers.get('x-has-more') !== 'true')
45
+ return undefined;
46
+ cursor = result.response.headers.get('x-cursor') ?? undefined;
47
+ if (!cursor || cursors.has(cursor))
48
+ throw new Error('Cannot read the next page of Blueprint stacks. Try again.');
49
+ cursors.add(cursor);
50
+ } while (cursor);
51
+ return undefined;
52
+ }
53
+ const existing = await findStack();
54
+ if (existing)
55
+ return resolved(existing, false);
56
+ if (dryRun)
57
+ return null;
58
+ const result = await createStack({
59
+ auth,
60
+ logger,
61
+ fetchFn,
62
+ stackMutation: {
63
+ name,
64
+ scopeType: auth.scopeType,
65
+ scopeId: auth.scopeId,
66
+ document: { resources: [] },
67
+ },
68
+ });
69
+ if (result.ok)
70
+ return resolved(result.stack, true);
71
+ if (result.response?.status === 409) {
72
+ const concurrent = await findStack();
73
+ if (concurrent)
74
+ return resolved(concurrent, false);
75
+ }
76
+ throw stackRequestError(result);
77
+ }
78
+ const appFunctionResourceTypes = new Set(['sanity.function.pubsub', 'sanity.function.cron']);
79
+ /** App stacks hold only the function types the CLI deploys, so other resources are never replaced. */
80
+ export function isAppFunctionResource(resource) {
81
+ return appFunctionResourceTypes.has(resource.type);
82
+ }
83
+ function appFunctionStackName(appId) {
84
+ return `app-${appId}`;
85
+ }
86
+ function stackRequestError(result) {
87
+ const status = result.response ? ` (${result.response.status})` : '';
88
+ return new Error(`Blueprint stack request failed${status}: ${result.error || result.response?.statusText || 'Unknown error'}`);
89
+ }
90
+ export { BLUEPRINTS_API_VERSION } from '../config.js';
91
+ /** Find an app-owned stack without creating one, and verify all resources are app functions. */
92
+ export async function inspectFunctionStack(options) {
93
+ const found = await ensureFunctionStack({ ...options, dryRun: true });
94
+ if (!found)
95
+ return null;
96
+ const stack = await readOwnedFunctionStack({ ...options, stackId: found.id });
97
+ return stack ? { id: stack.id, functions: stack.resources.map((resource) => resource.name) } : null;
98
+ }
99
+ /** Destroy an app's stack using Blueprint deletion and operation polling. Missing stacks are already clean. */
100
+ export async function destroyFunctionStack(options) {
101
+ try {
102
+ const stack = await readOwnedFunctionStack(options);
103
+ if (!stack)
104
+ return { success: true };
105
+ const log = Logger(options.log, { json: true });
106
+ const auth = {
107
+ token: options.token,
108
+ scopeType: 'organization',
109
+ scopeId: options.organizationId,
110
+ };
111
+ const result = await destroyStack({
112
+ stackId: stack.id,
113
+ auth,
114
+ logger: log,
115
+ fetchFn: options.fetchFn,
116
+ });
117
+ if (!result.ok) {
118
+ if (result.response?.status === 404)
119
+ return { success: true };
120
+ return { success: false, error: result.error, requestId: result.requestId };
121
+ }
122
+ return await waitForDestruction({
123
+ stackId: stack.id,
124
+ stackName: stack.name,
125
+ operationId: result.stack.operationId,
126
+ requestId: result.requestId,
127
+ auth,
128
+ log,
129
+ bin: 'sanity',
130
+ fetchFn: options.fetchFn,
131
+ });
132
+ }
133
+ catch (error) {
134
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
135
+ }
136
+ }
137
+ async function readOwnedFunctionStack(options) {
138
+ const auth = {
139
+ token: options.token,
140
+ scopeType: 'organization',
141
+ scopeId: options.organizationId,
142
+ };
143
+ const result = await getStack({ stackId: options.stackId, auth, fetchFn: options.fetchFn });
144
+ if (!result.ok) {
145
+ if (result.response?.status === 404)
146
+ return null;
147
+ throw stackRequestError(result);
148
+ }
149
+ assertAppFunctionStack(result.stack, options);
150
+ if (!result.stack.resources.every(isAppFunctionResource))
151
+ throw new Error('The app function stack contains other resource types. Manage it with sanity blueprints instead.');
152
+ return result.stack;
153
+ }
@@ -64,11 +64,11 @@ class ConsolePanel extends ApiBaseElement {
64
64
 
65
65
  if (this.api.store.preserveLog) {
66
66
  // Nested output was already appended live during the run; keep it in place.
67
- this.consoleOutput.innerText = this.consoleOutput.innerText + update
67
+ this.consoleOutput.textContent = this.consoleOutput.textContent + update
68
68
  } else {
69
69
  // Re-render so the nested output is shown in call order rather than the
70
70
  // completion order it streamed in (and so it survives this overwrite).
71
- this.consoleOutput.innerText = update + this.renderNestedEntries()
71
+ this.consoleOutput.textContent = update + this.renderNestedEntries()
72
72
  }
73
73
  }
74
74
 
@@ -96,7 +96,7 @@ class ConsolePanel extends ApiBaseElement {
96
96
  const text = `↳ BEGIN: invoke('${name}')\n${body.trim()}\n↳ END: invoke('${name}')\n`
97
97
  this.nestedEntries.push({order, text})
98
98
  // Append live for immediate feedback; the final result render reorders.
99
- this.consoleOutput.innerText = this.consoleOutput.innerText + text
99
+ this.consoleOutput.textContent = this.consoleOutput.textContent + text
100
100
  }
101
101
 
102
102
  // A new invocation is starting; drop the previous run's nested output.
@@ -108,7 +108,7 @@ class ConsolePanel extends ApiBaseElement {
108
108
  const backUp = this.api.store.preserveLog
109
109
  this.api.store.result = {logs: undefined, error: undefined}
110
110
  this.nestedEntries = []
111
- this.consoleOutput.innerText = ''
111
+ this.consoleOutput.textContent = ''
112
112
  this.api.store.preserveLog = backUp
113
113
  }
114
114
 
@@ -74,18 +74,18 @@ class ResponsePanel extends ApiBaseElement {
74
74
  })
75
75
  this.api.store.response.dispatch(transaction)
76
76
 
77
- this.size.innerText = json ? prettyBytes(JSON.stringify(json).length) : ''
77
+ this.size.textContent = json ? prettyBytes(JSON.stringify(json).length) : ''
78
78
 
79
79
  if (timings && 'bundle' in timings && 'execute' in timings) {
80
80
  const bundleTime = prettyMilliseconds(timings.bundle)
81
81
  const executeTime = prettyMilliseconds(timings.execute)
82
- this.time.innerText = `${executeTime} (+${bundleTime} bundle time)`
82
+ this.time.textContent = `${executeTime} (+${bundleTime} bundle time)`
83
83
  this.time.dateTime = `PT${executeTime / 1000}S`
84
84
  } else if (timings && 'execute' in timings) {
85
- this.time.innerText = prettyMilliseconds(timings.execute)
85
+ this.time.textContent = prettyMilliseconds(timings.execute)
86
86
  this.time.dateTime = `PT${timings.execute / 1000}S`
87
87
  } else {
88
- this.time.innerText = ''
88
+ this.time.textContent = ''
89
89
  this.time.dateTime = ''
90
90
  }
91
91
  } else {
@@ -93,8 +93,8 @@ class ResponsePanel extends ApiBaseElement {
93
93
  changes: {from: 0, to: this.api.store.response.state.doc.length, insert: ''},
94
94
  })
95
95
  this.api.store.response.dispatch(transaction)
96
- this.size.innerText = ''
97
- this.time.innerText = ''
96
+ this.size.textContent = ''
97
+ this.time.textContent = ''
98
98
  this.time.removeAttribute('datetime')
99
99
  }
100
100
  }