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

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.
@@ -1,22 +0,0 @@
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;
@@ -1,99 +0,0 @@
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
- }
@@ -1,3 +0,0 @@
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;
@@ -1,66 +0,0 @@
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
- }
@@ -1,33 +0,0 @@
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>;
@@ -1,162 +0,0 @@
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
- }
@@ -1,16 +0,0 @@
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>;
@@ -1,69 +0,0 @@
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
- }
@@ -1,21 +0,0 @@
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
- }>;
@@ -1,34 +0,0 @@
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
- }
@@ -1,41 +0,0 @@
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>;