@sanity/blueprints 0.27.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/definers/functions/durable.d.ts +0 -1
- package/dist/definers/functions/durable.js +3 -4
- package/dist/definers/functions/durable.js.map +1 -1
- package/dist/definers/functions/queue.js +3 -3
- package/dist/definers/functions/queue.js.map +1 -1
- package/dist/resolve/by-name.d.ts +7 -0
- package/dist/resolve/by-name.js +13 -0
- package/dist/resolve/by-name.js.map +1 -0
- package/dist/resolve/import.d.ts +16 -0
- package/dist/resolve/import.js +48 -0
- package/dist/resolve/import.js.map +1 -0
- package/dist/resolve/index.d.ts +18 -0
- package/dist/resolve/index.js +19 -0
- package/dist/resolve/index.js.map +1 -0
- package/dist/resolve/load.d.ts +53 -0
- package/dist/resolve/load.js +155 -0
- package/dist/resolve/load.js.map +1 -0
- package/dist/resolve/stack-config.d.ts +49 -0
- package/dist/resolve/stack-config.js +108 -0
- package/dist/resolve/stack-config.js.map +1 -0
- package/dist/resolve/stack.d.ts +23 -0
- package/dist/resolve/stack.js +91 -0
- package/dist/resolve/stack.js.map +1 -0
- package/dist/resolve/types.d.ts +165 -0
- package/dist/resolve/types.js +2 -0
- package/dist/resolve/types.js.map +1 -0
- package/dist/types/functions/index.d.ts +58 -10
- package/dist/utils/debounce.d.ts +20 -0
- package/dist/utils/debounce.js +46 -0
- package/dist/utils/debounce.js.map +1 -0
- package/dist/validation/functions.d.ts +9 -0
- package/dist/validation/functions.js +66 -9
- package/dist/validation/functions.js.map +1 -1
- package/package.json +16 -7
- package/src/definers/functions/durable.ts +3 -4
- package/src/definers/functions/queue.ts +3 -3
- package/src/resolve/by-name.ts +11 -0
- package/src/resolve/import.ts +52 -0
- package/src/resolve/index.ts +33 -0
- package/src/resolve/load.ts +166 -0
- package/src/resolve/stack-config.ts +116 -0
- package/src/resolve/stack.ts +100 -0
- package/src/resolve/types.ts +179 -0
- package/src/types/functions/index.ts +70 -19
- package/src/utils/debounce.ts +53 -0
- package/src/validation/functions.ts +78 -12
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/blueprints",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.28.0",
|
|
4
4
|
"description": "Helper methods and type definitions for Sanity Blueprints",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -26,6 +26,12 @@
|
|
|
26
26
|
"import": "./dist/index.js",
|
|
27
27
|
"default": "./dist/index.js"
|
|
28
28
|
},
|
|
29
|
+
"./resolve": {
|
|
30
|
+
"source": "./src/resolve/index.ts",
|
|
31
|
+
"types": "./dist/resolve/index.d.ts",
|
|
32
|
+
"import": "./dist/resolve/index.js",
|
|
33
|
+
"default": "./dist/resolve/index.js"
|
|
34
|
+
},
|
|
29
35
|
"./package.json": "./package.json"
|
|
30
36
|
},
|
|
31
37
|
"main": "dist/index.js",
|
|
@@ -34,7 +40,7 @@
|
|
|
34
40
|
"src"
|
|
35
41
|
],
|
|
36
42
|
"scripts": {
|
|
37
|
-
"build": "
|
|
43
|
+
"build": "rm -rf dist && tsc",
|
|
38
44
|
"coverage": "vitest --coverage",
|
|
39
45
|
"docs:typedoc": "npx -y -p typescript@6 -p typedoc@0.28.20 typedoc --options typedoc.json",
|
|
40
46
|
"docs:watch": "npm run docs:typedoc && open ./docs/html/index.html && npm run docs:typedoc -- --watch",
|
|
@@ -49,19 +55,22 @@
|
|
|
49
55
|
"typecheck": "tsc --noEmit --project tsconfig.test.json"
|
|
50
56
|
},
|
|
51
57
|
"devDependencies": {
|
|
52
|
-
"@biomejs/biome": "2.5.
|
|
58
|
+
"@biomejs/biome": "2.5.14",
|
|
53
59
|
"@types/node": "^22",
|
|
54
|
-
"@vitest/coverage-v8": "^
|
|
55
|
-
"rimraf": "^6.1.3",
|
|
60
|
+
"@vitest/coverage-v8": "^5.0.1",
|
|
56
61
|
"typescript": "^7.0.2",
|
|
57
|
-
"vitest": "
|
|
62
|
+
"vitest": "5.0.1"
|
|
58
63
|
},
|
|
59
64
|
"peerDependencies": {
|
|
60
|
-
"vite": ">= 8"
|
|
65
|
+
"vite": ">= 8",
|
|
66
|
+
"jiti": "^2"
|
|
61
67
|
},
|
|
62
68
|
"peerDependenciesMeta": {
|
|
63
69
|
"vite": {
|
|
64
70
|
"optional": true
|
|
71
|
+
},
|
|
72
|
+
"jiti": {
|
|
73
|
+
"optional": true
|
|
65
74
|
}
|
|
66
75
|
},
|
|
67
76
|
"engines": {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {type BlueprintDurableConfig, type BlueprintDurableFunctionResource, validateDurableFunction} from '../../index.js'
|
|
2
|
+
import {createDebounceObject} from '../../utils/debounce.js'
|
|
2
3
|
import {parseDuration} from '../../utils/parse-duration.js'
|
|
3
4
|
import {runValidation} from '../../utils/validation.js'
|
|
4
5
|
import {defineFunction} from './index.js'
|
|
@@ -14,7 +15,6 @@ import {defineFunction} from './index.js'
|
|
|
14
15
|
* event: {type: 'document', on: ['create'], filter: "_type == 'post'"},
|
|
15
16
|
* concurrency: 5,
|
|
16
17
|
* debounce: 10,
|
|
17
|
-
* debounceKey: 'document._id',
|
|
18
18
|
* })
|
|
19
19
|
* ```
|
|
20
20
|
*
|
|
@@ -28,15 +28,14 @@ import {defineFunction} from './index.js'
|
|
|
28
28
|
* @returns The validated durable function resource
|
|
29
29
|
*/
|
|
30
30
|
export function defineDurableFunction(functionConfig: BlueprintDurableConfig): BlueprintDurableFunctionResource {
|
|
31
|
-
const {name, event, concurrency, debounce,
|
|
31
|
+
const {name, event, concurrency, debounce, src, durableTimeout} = functionConfig
|
|
32
32
|
const functionResource: BlueprintDurableFunctionResource = {
|
|
33
33
|
...defineFunction({...functionConfig, src: src ?? `functions/${name}`}, {skipValidation: true}),
|
|
34
34
|
type: 'sanity.function.durable',
|
|
35
35
|
...(event !== undefined && {event}),
|
|
36
36
|
...(durableTimeout !== undefined && {durableTimeout: parseDuration(durableTimeout, 's')}),
|
|
37
37
|
...(concurrency !== undefined && {concurrency}),
|
|
38
|
-
...(debounce !== undefined && {debounce}),
|
|
39
|
-
...(debounceKey !== undefined && {debounceKey}),
|
|
38
|
+
...(debounce !== undefined && {debounce: createDebounceObject(debounce)}),
|
|
40
39
|
}
|
|
41
40
|
|
|
42
41
|
runValidation(() => validateDurableFunction(functionResource))
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {type BlueprintQueueFunctionConfig, type BlueprintQueueFunctionResource, validateQueueFunction} from '../../index.js'
|
|
2
|
+
import {createDebounceObject} from '../../utils/debounce.js'
|
|
2
3
|
import {runValidation} from '../../utils/validation.js'
|
|
3
4
|
import {defineFunction} from './index.js'
|
|
4
5
|
/**
|
|
@@ -30,14 +31,13 @@ import {defineFunction} from './index.js'
|
|
|
30
31
|
* @returns The validated queue function resource
|
|
31
32
|
*/
|
|
32
33
|
export function defineQueueFunction(functionConfig: BlueprintQueueFunctionConfig): BlueprintQueueFunctionResource {
|
|
33
|
-
const {concurrency = 1, fifo = true, dlq = true, debounce,
|
|
34
|
+
const {concurrency = 1, fifo = true, dlq = true, debounce, event} = functionConfig
|
|
34
35
|
|
|
35
36
|
const functionResource: BlueprintQueueFunctionResource = {
|
|
36
37
|
...defineFunction(functionConfig, {skipValidation: true}),
|
|
37
38
|
type: 'sanity.function.queue',
|
|
38
39
|
...(concurrency !== undefined && {concurrency}),
|
|
39
|
-
...(debounce !== undefined && {debounce}),
|
|
40
|
-
...(debounceKey !== undefined && {debounceKey}),
|
|
40
|
+
...(debounce !== undefined && {debounce: createDebounceObject(debounce)}),
|
|
41
41
|
...(dlq !== undefined && {dlq}),
|
|
42
42
|
...(event !== undefined && {event}),
|
|
43
43
|
...(fifo !== undefined && {fifo}),
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Key resources by name. A resource without a string `name` is left out, and a later resource with the same name replaces an earlier one.
|
|
3
|
+
* @internal
|
|
4
|
+
*/
|
|
5
|
+
export function byName<T extends {name?: unknown}>(resources: T[]): Record<string, T> {
|
|
6
|
+
const keyed: Record<string, T> = {}
|
|
7
|
+
for (const resource of resources) {
|
|
8
|
+
if (typeof resource?.name === 'string') keyed[resource.name] = resource
|
|
9
|
+
}
|
|
10
|
+
return keyed
|
|
11
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {createRequire} from 'node:module'
|
|
2
|
+
import {pathToFileURL} from 'node:url'
|
|
3
|
+
import type {BlueprintLoader} from './types.js'
|
|
4
|
+
|
|
5
|
+
type CreateJiti = (id: string) => {import(id: string, options: {default: true}): Promise<unknown>}
|
|
6
|
+
|
|
7
|
+
/*
|
|
8
|
+
* Error strings thrown by Node when importing a .ts file.
|
|
9
|
+
* Indicators to attempt again with jiti.
|
|
10
|
+
*/
|
|
11
|
+
const RETRY_WITH_JITI = new Set([
|
|
12
|
+
'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX',
|
|
13
|
+
'ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING',
|
|
14
|
+
'ERR_UNKNOWN_FILE_EXTENSION',
|
|
15
|
+
'ERR_MODULE_NOT_FOUND',
|
|
16
|
+
])
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Import a file natively and return its default export
|
|
20
|
+
* @internal
|
|
21
|
+
*/
|
|
22
|
+
export async function importNative(path: string): Promise<unknown> {
|
|
23
|
+
const imported: {default?: unknown} = await import(pathToFileURL(path).href)
|
|
24
|
+
return imported.default
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Whether jiti may be able to import a file that the native import could not
|
|
29
|
+
* @internal
|
|
30
|
+
*/
|
|
31
|
+
export function canRetryWithJiti(error: unknown): boolean {
|
|
32
|
+
return error instanceof Error && 'code' in error && RETRY_WITH_JITI.has(String(error.code))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A jiti loader, when jiti resolves from the blueprint file or from this package
|
|
37
|
+
* @internal
|
|
38
|
+
*/
|
|
39
|
+
export async function findJiti(path: string): Promise<BlueprintLoader | undefined> {
|
|
40
|
+
for (const from of [path, import.meta.url]) {
|
|
41
|
+
let resolved: string
|
|
42
|
+
try {
|
|
43
|
+
resolved = createRequire(from).resolve('jiti')
|
|
44
|
+
} catch {
|
|
45
|
+
continue
|
|
46
|
+
}
|
|
47
|
+
const {createJiti}: {createJiti?: CreateJiti} = await import(pathToFileURL(resolved).href)
|
|
48
|
+
if (typeof createJiti !== 'function') continue
|
|
49
|
+
return (file) => createJiti(file).import(pathToFileURL(file).href, {default: true})
|
|
50
|
+
}
|
|
51
|
+
return undefined
|
|
52
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@sanity/blueprints/resolve`
|
|
3
|
+
*
|
|
4
|
+
* A Blueprint declares resources. A Stack is its deployed counterpart.
|
|
5
|
+
* {@link readBlueprint} reads local blueprint.
|
|
6
|
+
* {@link readStack} reads remote stack.
|
|
7
|
+
*
|
|
8
|
+
* This entry point imports Node built-ins, so it is separate from `@sanity/blueprints`.
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @categoryDescription Resolve
|
|
14
|
+
* These functions read a blueprint from disk, resolve the Stack it deploys to, and read that Stack from the Blueprints API.
|
|
15
|
+
*/
|
|
16
|
+
export {
|
|
17
|
+
BLUEPRINT_FILE_NAMES,
|
|
18
|
+
findBlueprintFile,
|
|
19
|
+
loadBlueprintFile,
|
|
20
|
+
readBlueprint,
|
|
21
|
+
} from './load.js'
|
|
22
|
+
export {
|
|
23
|
+
DEFAULT_BLUEPRINTS_API_VERSION,
|
|
24
|
+
readStack,
|
|
25
|
+
} from './stack.js'
|
|
26
|
+
export {
|
|
27
|
+
readStackConfigFile,
|
|
28
|
+
resolveStackConfig,
|
|
29
|
+
STACK_CONFIG_DIR,
|
|
30
|
+
STACK_CONFIG_FILE,
|
|
31
|
+
stackIdsFromEnv,
|
|
32
|
+
} from './stack-config.js'
|
|
33
|
+
export * from './types.js'
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import {existsSync, readFileSync, statSync} from 'node:fs'
|
|
2
|
+
import {dirname, extname, join, resolve} from 'node:path'
|
|
3
|
+
import {cwd} from 'node:process'
|
|
4
|
+
import type {Blueprint, BlueprintModule} from '../index.js'
|
|
5
|
+
import {byName} from './by-name.js'
|
|
6
|
+
import {canRetryWithJiti, findJiti, importNative} from './import.js'
|
|
7
|
+
import {readStackConfigFile, resolveStackConfig, stackIdsFromEnv} from './stack-config.js'
|
|
8
|
+
import type {BlueprintInfo, BlueprintLoader, LoadBlueprintFileOptions, LoadedBlueprintFile, ReadBlueprintOptions} from './types.js'
|
|
9
|
+
|
|
10
|
+
const EXTENSIONS = ['.json', '.js', '.mjs', '.ts']
|
|
11
|
+
const BASE_NAMES = EXTENSIONS.map((ext) => `blueprint${ext}`)
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The file names {@link findBlueprintFile} looks for, in order
|
|
15
|
+
* @internal
|
|
16
|
+
* @private
|
|
17
|
+
* @category Resolve
|
|
18
|
+
*/
|
|
19
|
+
export const BLUEPRINT_FILE_NAMES = [...BASE_NAMES, ...BASE_NAMES.map((name) => `sanity.${name}`)]
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Find a blueprint file
|
|
23
|
+
*
|
|
24
|
+
* Returns a file path as is. Searches a directory, then its parents, for {@link BLUEPRINT_FILE_NAMES}.
|
|
25
|
+
*
|
|
26
|
+
* @param path A blueprint file or directory. Defaults to the current working directory.
|
|
27
|
+
* @returns The absolute path of the file, or `undefined` when none is found
|
|
28
|
+
* @internal
|
|
29
|
+
* @private
|
|
30
|
+
* @category Resolve
|
|
31
|
+
*/
|
|
32
|
+
export function findBlueprintFile(path: string = cwd()): string | undefined {
|
|
33
|
+
let dir = resolve(path)
|
|
34
|
+
if (!existsSync(dir)) return undefined
|
|
35
|
+
if (statSync(dir).isFile()) return dir
|
|
36
|
+
|
|
37
|
+
while (true) {
|
|
38
|
+
for (const name of BLUEPRINT_FILE_NAMES) {
|
|
39
|
+
const candidate = join(dir, name)
|
|
40
|
+
if (existsSync(candidate)) return candidate
|
|
41
|
+
}
|
|
42
|
+
const parent = dirname(dir)
|
|
43
|
+
if (parent === dir) return undefined
|
|
44
|
+
dir = parent
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Load a blueprint file
|
|
50
|
+
*
|
|
51
|
+
* Parses a JSON file. Imports a JS or TS file and calls its default export.
|
|
52
|
+
* TypeScript that Node cannot run, such as an enum, is loaded with jiti when it is installed.
|
|
53
|
+
* Imported modules are cached, so a later call in the same process does not see changes to the file. Pass a `loader` that skips the cache to re-read it.
|
|
54
|
+
*
|
|
55
|
+
* @param path The blueprint file
|
|
56
|
+
* @throws When the file cannot be loaded or does not produce a blueprint object
|
|
57
|
+
* @internal
|
|
58
|
+
* @private
|
|
59
|
+
* @category Resolve
|
|
60
|
+
*/
|
|
61
|
+
export async function loadBlueprintFile(path: string, options: LoadBlueprintFileOptions = {}): Promise<LoadedBlueprintFile> {
|
|
62
|
+
const extension = extname(path)
|
|
63
|
+
|
|
64
|
+
if (extension === '.json') {
|
|
65
|
+
let blueprint: unknown
|
|
66
|
+
try {
|
|
67
|
+
blueprint = JSON.parse(readFileSync(path, 'utf8'))
|
|
68
|
+
} catch (error) {
|
|
69
|
+
throw new Error(`Unable to parse ${path}: ${errorText(error)}`, {cause: error})
|
|
70
|
+
}
|
|
71
|
+
return {blueprint: asBlueprint(blueprint, path)}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (!EXTENSIONS.includes(extension)) {
|
|
75
|
+
throw new Error(`Unsupported blueprint file extension "${extension}" for ${path}. Expected one of: ${EXTENSIONS.join(', ')}`)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const defaultExport = await importDefault(path, options.loader)
|
|
79
|
+
if (typeof defaultExport !== 'function') {
|
|
80
|
+
throw new Error(`${path} must export a default function. Wrap the blueprint in defineBlueprint().`)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const module = defaultExport as BlueprintModule
|
|
84
|
+
let blueprint: unknown
|
|
85
|
+
try {
|
|
86
|
+
blueprint = module()
|
|
87
|
+
} catch (error) {
|
|
88
|
+
throw new Error(`Error executing the default export of ${path}: ${errorText(error)}`, {cause: error})
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return {blueprint: asBlueprint(blueprint, path), module}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Read a local blueprint and the ids of the Stack it deploys to
|
|
96
|
+
*
|
|
97
|
+
* Ids come from `overrides`, the environment, `defineBlueprint`, then `.sanity/blueprint.config.json`.
|
|
98
|
+
* Resources are not validated. No network access.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* import {readBlueprint} from '@sanity/blueprints/resolve'
|
|
103
|
+
*
|
|
104
|
+
* const {resources, resourcesByName, stackId, sources} = await readBlueprint()
|
|
105
|
+
* resources.map((resource) => resource.name)
|
|
106
|
+
* resourcesByName['production-dataset']?.type // 'sanity.project.dataset'
|
|
107
|
+
* sources.stackId // 'config'
|
|
108
|
+
* ```
|
|
109
|
+
* @throws When no blueprint file is found, it cannot be loaded, or `resources` is not an array
|
|
110
|
+
* @category Resolve
|
|
111
|
+
*/
|
|
112
|
+
export async function readBlueprint(options: ReadBlueprintOptions = {}): Promise<BlueprintInfo> {
|
|
113
|
+
const path = findBlueprintFile(options.path)
|
|
114
|
+
if (!path) {
|
|
115
|
+
const searched = resolve(options.path ?? cwd())
|
|
116
|
+
throw new Error(`No blueprint file found in ${searched} or its parent directories. Expected one of: ${BLUEPRINT_FILE_NAMES.join(', ')}`)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const {blueprint, module} = await loadBlueprintFile(path, {loader: options.loader})
|
|
120
|
+
|
|
121
|
+
const resources = blueprint.resources ?? []
|
|
122
|
+
if (!Array.isArray(resources)) throw new Error(`Invalid blueprint in ${path}: \`resources\` must be an array`)
|
|
123
|
+
|
|
124
|
+
const file = readStackConfigFile(dirname(path))
|
|
125
|
+
const config = resolveStackConfig({
|
|
126
|
+
overrides: options.overrides,
|
|
127
|
+
env: options.env === undefined ? undefined : options.env && stackIdsFromEnv(options.env),
|
|
128
|
+
module,
|
|
129
|
+
config: file,
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
return {path, blueprint, module, resources, resourcesByName: byName(resources), ...config, configPath: file?.configPath}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function importDefault(path: string, loader?: BlueprintLoader): Promise<unknown> {
|
|
136
|
+
let error: unknown
|
|
137
|
+
try {
|
|
138
|
+
return await (loader ?? importNative)(path)
|
|
139
|
+
} catch (caught) {
|
|
140
|
+
error = caught
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (!loader && canRetryWithJiti(error)) {
|
|
144
|
+
const jiti = await findJiti(path)
|
|
145
|
+
if (!jiti) throw new Error(`Unable to import ${path}: ${errorText(error)} Install jiti to load it, or pass a loader.`, {cause: error})
|
|
146
|
+
try {
|
|
147
|
+
return await jiti(path)
|
|
148
|
+
} catch (caught) {
|
|
149
|
+
error = caught
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
throw new Error(`Unable to import ${path}: ${errorText(error)}`, {cause: error})
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function errorText(error: unknown): string {
|
|
157
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
158
|
+
return message.endsWith('.') ? message : `${message}.`
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function asBlueprint(value: unknown, path: string): Blueprint {
|
|
162
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
163
|
+
throw new Error(`${path} did not produce a blueprint object`)
|
|
164
|
+
}
|
|
165
|
+
return value as Blueprint
|
|
166
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import {existsSync, readFileSync} from 'node:fs'
|
|
2
|
+
import {resolve} from 'node:path'
|
|
3
|
+
import {cwd, env as processEnv} from 'node:process'
|
|
4
|
+
import type {BlueprintsApiConfig} from '../index.js'
|
|
5
|
+
import type {ConfigSource, StackConfig, StackConfigFile, StackIdSources, StackIds} from './types.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The directory next to the blueprint file that holds the Stack config
|
|
9
|
+
* @internal
|
|
10
|
+
* @private
|
|
11
|
+
* @category Resolve
|
|
12
|
+
*/
|
|
13
|
+
export const STACK_CONFIG_DIR = '.sanity'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The file in {@link STACK_CONFIG_DIR} that holds the Stack ids
|
|
17
|
+
* @internal
|
|
18
|
+
* @private
|
|
19
|
+
* @category Resolve
|
|
20
|
+
*/
|
|
21
|
+
export const STACK_CONFIG_FILE = 'blueprint.config.json'
|
|
22
|
+
|
|
23
|
+
const ID_KEYS: (keyof BlueprintsApiConfig)[] = ['organizationId', 'projectId', 'stackId']
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Read `.sanity/blueprint.config.json` from a blueprint directory
|
|
27
|
+
* @param dir The blueprint directory. Defaults to the current working directory.
|
|
28
|
+
* @returns The ids in the file and its path, or `undefined` when the file does not exist
|
|
29
|
+
* @throws When the file exists and is not valid JSON
|
|
30
|
+
* @internal
|
|
31
|
+
* @private
|
|
32
|
+
* @category Resolve
|
|
33
|
+
*/
|
|
34
|
+
export function readStackConfigFile(dir: string = cwd()): StackConfigFile | undefined {
|
|
35
|
+
const configPath = resolve(dir, STACK_CONFIG_DIR, STACK_CONFIG_FILE)
|
|
36
|
+
if (!existsSync(configPath)) return undefined
|
|
37
|
+
|
|
38
|
+
let parsed: Record<string, unknown>
|
|
39
|
+
try {
|
|
40
|
+
parsed = JSON.parse(readFileSync(configPath, 'utf8'))
|
|
41
|
+
} catch (error) {
|
|
42
|
+
throw new Error(`Unable to parse ${configPath}`, {cause: error})
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return {configPath, ...pickIds(parsed)}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Read the Stack ids from `SANITY_ORGANIZATION_ID`, `SANITY_PROJECT_ID`, and `SANITY_BLUEPRINT_STACK_ID`
|
|
50
|
+
* @param env The environment to read. Defaults to `process.env`.
|
|
51
|
+
* @internal
|
|
52
|
+
* @private
|
|
53
|
+
* @category Resolve
|
|
54
|
+
*/
|
|
55
|
+
export function stackIdsFromEnv(env: NodeJS.ProcessEnv = processEnv): StackIds {
|
|
56
|
+
return pickIds({
|
|
57
|
+
organizationId: env.SANITY_ORGANIZATION_ID,
|
|
58
|
+
projectId: env.SANITY_PROJECT_ID,
|
|
59
|
+
stackId: env.SANITY_BLUEPRINT_STACK_ID,
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Resolve the Stack ids and scope, and which source supplied each id
|
|
65
|
+
*
|
|
66
|
+
* Precedence: `overrides`, `env`, `module`, `config`. The scope is the project if known, else the organization.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* const config = resolveStackConfig({config: readStackConfigFile()})
|
|
71
|
+
* config.stackId // 'ST-abc123'
|
|
72
|
+
* config.sources.stackId // 'config'
|
|
73
|
+
* ```
|
|
74
|
+
* @internal
|
|
75
|
+
* @private
|
|
76
|
+
* @category Resolve
|
|
77
|
+
*/
|
|
78
|
+
export function resolveStackConfig(sources: StackIdSources = {}): StackConfig {
|
|
79
|
+
const ordered: [ConfigSource, StackIds | null | undefined][] = [
|
|
80
|
+
['overrides', sources.overrides],
|
|
81
|
+
['env', sources.env === undefined ? stackIdsFromEnv() : sources.env],
|
|
82
|
+
['module', sources.module],
|
|
83
|
+
['config', sources.config],
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
const config: StackConfig = {sources: {}}
|
|
87
|
+
for (const [source, values] of ordered) {
|
|
88
|
+
if (!values) continue
|
|
89
|
+
for (const key of ID_KEYS) {
|
|
90
|
+
const value = values[key]
|
|
91
|
+
if (!config[key] && value) {
|
|
92
|
+
config[key] = value
|
|
93
|
+
config.sources[key] = source
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (config.projectId) {
|
|
99
|
+
config.scopeType = 'project'
|
|
100
|
+
config.scopeId = config.projectId
|
|
101
|
+
} else if (config.organizationId) {
|
|
102
|
+
config.scopeType = 'organization'
|
|
103
|
+
config.scopeId = config.organizationId
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return config
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function pickIds(values: Record<string, unknown>): StackIds {
|
|
110
|
+
const ids: StackIds = {}
|
|
111
|
+
for (const key of ID_KEYS) {
|
|
112
|
+
const value = values[key]
|
|
113
|
+
if (typeof value === 'string' && value.length > 0) ids[key] = value
|
|
114
|
+
}
|
|
115
|
+
return ids
|
|
116
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import {env as processEnv} from 'node:process'
|
|
2
|
+
import {byName} from './by-name.js'
|
|
3
|
+
import {readBlueprint} from './load.js'
|
|
4
|
+
import type {DeployedStack, LiveResource, ReadStackOptions, StackInfo} from './types.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The Blueprints API version {@link readStack} uses when none is configured
|
|
8
|
+
* @category Resolve
|
|
9
|
+
*/
|
|
10
|
+
export const DEFAULT_BLUEPRINTS_API_VERSION = 'v2026-06-15'
|
|
11
|
+
|
|
12
|
+
const API_URLS: Record<string, string> = {
|
|
13
|
+
production: 'https://api.sanity.io',
|
|
14
|
+
staging: 'https://api.sanity.work',
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Read a local blueprint and its deployed Stack
|
|
19
|
+
*
|
|
20
|
+
* Adds each deployed resource's `externalId` and `live` values to the declared resource with the same type and name.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* import {readStack} from '@sanity/blueprints/resolve'
|
|
25
|
+
*
|
|
26
|
+
* const {values, resourcesByName} = await readStack({token: process.env.SANITY_AUTH_TOKEN})
|
|
27
|
+
* values['production-dataset']?.['name'] // the deployed dataset's name
|
|
28
|
+
* resourcesByName['my-function']?.externalId
|
|
29
|
+
* ```
|
|
30
|
+
* @throws When {@link readBlueprint} throws, the Stack id or scope is unknown, or the API responds with an error
|
|
31
|
+
* @category Resolve
|
|
32
|
+
*/
|
|
33
|
+
export async function readStack(options: ReadStackOptions): Promise<StackInfo> {
|
|
34
|
+
const blueprint = await readBlueprint(options)
|
|
35
|
+
const {stackId, scopeType, scopeId} = blueprint
|
|
36
|
+
|
|
37
|
+
if (!stackId || !scopeType || !scopeId) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
`No Stack to read for ${blueprint.path}. Set a Stack id and a project or organization id in ` +
|
|
40
|
+
'.sanity/blueprint.config.json, in defineBlueprint, or in the SANITY_BLUEPRINT_STACK_ID and ' +
|
|
41
|
+
'SANITY_PROJECT_ID or SANITY_ORGANIZATION_ID environment variables.',
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const env = options.env === undefined ? processEnv : options.env
|
|
46
|
+
const apiUrl = (options.apiUrl ?? apiUrlFromEnv(env)).replace(/\/$/, '')
|
|
47
|
+
const apiVersion = options.apiVersion ?? env?.SANITY_BLUEPRINTS_API_VERSION ?? DEFAULT_BLUEPRINTS_API_VERSION
|
|
48
|
+
const fetchFn = options.fetch ?? globalThis.fetch
|
|
49
|
+
|
|
50
|
+
const response = await fetchFn(`${apiUrl}/${apiVersion}/blueprints/stacks/${stackId}`, {
|
|
51
|
+
method: 'GET',
|
|
52
|
+
headers: {
|
|
53
|
+
Accept: 'application/json',
|
|
54
|
+
Authorization: `Bearer ${options.token}`,
|
|
55
|
+
'X-Sanity-Scope-Type': scopeType,
|
|
56
|
+
'X-Sanity-Scope-Id': scopeId,
|
|
57
|
+
'User-Agent': '@sanity/blueprints',
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
if (!response.ok) {
|
|
61
|
+
throw new Error(`Failed to read Stack ${stackId}: ${response.status} ${await errorMessage(response)}`)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const stack: DeployedStack = await response.json()
|
|
65
|
+
const deployed = new Map(stack.resources.map((resource) => [`${resource.type}:${resource.name}`, resource]))
|
|
66
|
+
|
|
67
|
+
const resources: LiveResource[] = blueprint.resources.map((resource) => {
|
|
68
|
+
const match = deployed.get(`${resource.type}:${resource.name}`)
|
|
69
|
+
if (!match) return resource
|
|
70
|
+
return {
|
|
71
|
+
...resource,
|
|
72
|
+
externalId: match.externalId ?? undefined,
|
|
73
|
+
live: match.resolvedParameters ?? match.parameters,
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
const values: StackInfo['values'] = {}
|
|
78
|
+
for (const resource of resources) {
|
|
79
|
+
if (resource.live) values[resource.name] = resource.live
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {...blueprint, stack, resources, resourcesByName: byName(resources), values}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function apiUrlFromEnv(env: NodeJS.ProcessEnv | null): string {
|
|
86
|
+
const sanityEnv = env?.SANITY_INTERNAL_ENV?.toLowerCase()
|
|
87
|
+
if (!sanityEnv) return API_URLS.production
|
|
88
|
+
// a value that is not a known environment is the origin itself
|
|
89
|
+
return API_URLS[sanityEnv] ?? sanityEnv
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function errorMessage(response: Response): Promise<string> {
|
|
93
|
+
try {
|
|
94
|
+
const body: {message?: unknown} = await response.json()
|
|
95
|
+
if (typeof body.message === 'string') return body.message
|
|
96
|
+
} catch {
|
|
97
|
+
// the body was not JSON
|
|
98
|
+
}
|
|
99
|
+
return response.statusText
|
|
100
|
+
}
|