@sanity/runtime-cli 17.2.0 → 17.3.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 +35 -26
- package/dist/actions/blueprints/assets.js +15 -24
- package/dist/actions/blueprints/pre-deploy.d.ts +29 -0
- package/dist/actions/blueprints/pre-deploy.js +164 -0
- package/dist/commands/functions/env/add.d.ts +3 -0
- package/dist/commands/functions/env/add.js +6 -2
- package/dist/commands/functions/env/list.d.ts +3 -0
- package/dist/commands/functions/env/list.js +9 -3
- package/dist/commands/functions/env/remove.d.ts +3 -0
- package/dist/commands/functions/env/remove.js +9 -3
- package/dist/constants.d.ts +1 -0
- package/dist/constants.js +1 -0
- package/dist/cores/blueprints/deploy.js +16 -64
- package/dist/utils/functions/child-process-wrapper.js +13 -171
- package/dist/utils/functions/child-runtime/console.d.ts +1 -0
- package/dist/utils/functions/child-runtime/console.js +50 -0
- package/dist/utils/functions/child-runtime/invoke.d.ts +4 -0
- package/dist/utils/functions/child-runtime/invoke.js +47 -0
- package/dist/utils/functions/child-runtime/resources.d.ts +4 -0
- package/dist/utils/functions/child-runtime/resources.js +59 -0
- package/dist/utils/studios/prepare-asset.d.ts +6 -0
- package/dist/utils/studios/prepare-asset.js +139 -0
- package/dist/utils/types.d.ts +4 -7
- package/dist/utils/types.js +2 -3
- package/oclif.manifest.json +932 -932
- package/package.json +10 -4
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { dirname } from 'node:path';
|
|
2
|
-
import {
|
|
2
|
+
import { preDeploy } from '../../actions/blueprints/pre-deploy.js';
|
|
3
3
|
import { getStack, updateStack } from '../../actions/blueprints/stacks.js';
|
|
4
4
|
import { waitForOperation } from '../../actions/blueprints/wait-for-operation.js';
|
|
5
5
|
import { checkUserPermission } from '../../actions/sanity/access.js';
|
|
@@ -7,12 +7,7 @@ import { createHintCollector } from '../../utils/blueprints/hints.js';
|
|
|
7
7
|
import { niceId } from '../../utils/display/presenters.js';
|
|
8
8
|
import { CODE_OPERATION_UNCONFIRMED, EXIT_OPERATION_UNCONFIRMED } from '../../utils/exit-codes.js';
|
|
9
9
|
import { styleText } from '../../utils/style-text.js';
|
|
10
|
-
import { isAssetResource } from '../../utils/types.js';
|
|
11
10
|
import { getWarnings } from '../../utils/warnings.js';
|
|
12
|
-
const DEFAULT_ASSET_TIMEOUT = 60;
|
|
13
|
-
const assetTimeoutS = Number(process.env.SANITY_ASSET_TIMEOUT) || DEFAULT_ASSET_TIMEOUT;
|
|
14
|
-
const assetTimeoutMs = assetTimeoutS * 1000;
|
|
15
|
-
const warnTimeoutMs = assetTimeoutMs / 2;
|
|
16
11
|
export async function blueprintDeployCore(options) {
|
|
17
12
|
const { bin = 'sanity', log, auth, stackId, scopeType, scopeId, deployedStack, blueprint, flags, } = options;
|
|
18
13
|
const { verbose } = flags;
|
|
@@ -39,17 +34,21 @@ export async function blueprintDeployCore(options) {
|
|
|
39
34
|
};
|
|
40
35
|
}
|
|
41
36
|
const resources = [...blueprint.resources];
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
37
|
+
const preDeployResult = await preDeploy({
|
|
38
|
+
scopeType,
|
|
39
|
+
scopeId,
|
|
40
|
+
resources,
|
|
41
|
+
stackId,
|
|
42
|
+
stackName,
|
|
43
|
+
auth,
|
|
44
|
+
blueprintFileDir,
|
|
45
|
+
installer,
|
|
46
|
+
log,
|
|
47
|
+
bin,
|
|
48
|
+
verbose,
|
|
49
|
+
});
|
|
50
|
+
if (!preDeployResult?.success) {
|
|
51
|
+
return preDeployResult;
|
|
53
52
|
}
|
|
54
53
|
const spinner = log.ora('Deploying...').start();
|
|
55
54
|
const { ok: deployOk, stack, error: deployError, } = await updateStack({
|
|
@@ -152,53 +151,6 @@ export async function blueprintDeployCore(options) {
|
|
|
152
151
|
return { success: false, error: errorMessage };
|
|
153
152
|
}
|
|
154
153
|
}
|
|
155
|
-
async function preDeploy(resource, options) {
|
|
156
|
-
const { auth, blueprintFileDir, installer, log } = options;
|
|
157
|
-
const fnSpinner = log.ora({ text: `Processing ${resource.name}...`, prefixText: ' ' }).start();
|
|
158
|
-
const warnTimer = setTimeout(() => {
|
|
159
|
-
fnSpinner.text = `Still processing ${resource.name}, this can take a moment...`;
|
|
160
|
-
}, warnTimeoutMs);
|
|
161
|
-
let assetTimeoutTimer;
|
|
162
|
-
let result;
|
|
163
|
-
try {
|
|
164
|
-
result = await Promise.race([
|
|
165
|
-
stashAsset({ resource, blueprintFileDir, auth, logger: log, installer }),
|
|
166
|
-
new Promise((_, reject) => {
|
|
167
|
-
assetTimeoutTimer = setTimeout(() => {
|
|
168
|
-
reject(new Error(`Processing ${resource.name} timed out after ${assetTimeoutS}s`));
|
|
169
|
-
}, assetTimeoutMs);
|
|
170
|
-
}),
|
|
171
|
-
]);
|
|
172
|
-
}
|
|
173
|
-
catch (err) {
|
|
174
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
175
|
-
fnSpinner.fail(msg);
|
|
176
|
-
return { success: false, error: msg };
|
|
177
|
-
}
|
|
178
|
-
finally {
|
|
179
|
-
clearTimeout(warnTimer);
|
|
180
|
-
clearTimeout(assetTimeoutTimer);
|
|
181
|
-
}
|
|
182
|
-
if (result.success && result.assetId) {
|
|
183
|
-
const updatedResource = { ...resource, src: result.assetId };
|
|
184
|
-
fnSpinner.succeed(`${updatedResource.name} ${niceId(result.assetId)}`);
|
|
185
|
-
log(` Source: ${updatedResource.src}`);
|
|
186
|
-
if (result.hash) {
|
|
187
|
-
if (result.hash.length > 24) {
|
|
188
|
-
log.verbose(` Hash: ${result.hash.slice(0, 8)}...${result.hash.slice(-12)}`);
|
|
189
|
-
}
|
|
190
|
-
else {
|
|
191
|
-
log.verbose(` Hash: ${result.hash}`);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
if (result.exists)
|
|
195
|
-
log.verbose(' Asset unchanged');
|
|
196
|
-
return { success: true, resource: updatedResource };
|
|
197
|
-
}
|
|
198
|
-
const errorMsg = `Failed uploading ${resource.name} asset, deploy has stopped`;
|
|
199
|
-
fnSpinner.fail(errorMsg);
|
|
200
|
-
return { success: false, error: result.error || 'Failed to process asset' };
|
|
201
|
-
}
|
|
202
154
|
const CHECK_LEGACY_DEPLOY_PERMISSION = false;
|
|
203
155
|
const BLUEPRINTS_PERMISSION_ENFORCEMENT_DATE = 'July 1, 2026';
|
|
204
156
|
async function checkLegacyDeployPermission({ auth, scopeType, scopeId, log, }) {
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import {table as renderTable} from 'node:console'
|
|
2
1
|
import {existsSync, statSync} from 'node:fs'
|
|
3
2
|
import {isAbsolute, join} from 'node:path'
|
|
4
3
|
import process from 'node:process'
|
|
5
4
|
import {pathToFileURL} from 'node:url'
|
|
6
|
-
import {
|
|
5
|
+
import {installConsole} from './child-runtime/console.js'
|
|
6
|
+
import {createInvoker} from './child-runtime/invoke.js'
|
|
7
|
+
import {createResourcesApi} from './child-runtime/resources.js'
|
|
8
|
+
|
|
9
|
+
installConsole()
|
|
10
|
+
const invoker = createInvoker()
|
|
7
11
|
|
|
8
12
|
export function getFunctionSource(src) {
|
|
9
13
|
const pathToCheck = isAbsolute(src) ? src : join(process.cwd(), src)
|
|
@@ -18,91 +22,6 @@ export function getFunctionSource(src) {
|
|
|
18
22
|
return pathToFileURL(pathToCheck).href
|
|
19
23
|
}
|
|
20
24
|
|
|
21
|
-
// Monkey patch console menthods to have logs match server log format
|
|
22
|
-
function logPrefix(level, ...args) {
|
|
23
|
-
const date = new Date()
|
|
24
|
-
const shouldUseColors = process.env.FORCE_COLOR === '1'
|
|
25
|
-
const message = args
|
|
26
|
-
.map((arg) =>
|
|
27
|
-
typeof arg === 'string' ? arg : inspect(arg, {depth: null, colors: shouldUseColors}),
|
|
28
|
-
)
|
|
29
|
-
.join(' ')
|
|
30
|
-
return `${date.toLocaleDateString()} ${date.toLocaleTimeString()} ${level.toUpperCase()} ${message}`
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
console.log = (...args) => {
|
|
34
|
-
process.stdout.write(`${logPrefix('info', ...args)}\n`)
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
console.info = (...args) => {
|
|
38
|
-
process.stdout.write(`${logPrefix('info', ...args)}\n`)
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
console.dir = (obj, options) => {
|
|
42
|
-
const shouldUseColors = process.env.FORCE_COLOR === '1'
|
|
43
|
-
const inspectOptions = {...options, colors: shouldUseColors}
|
|
44
|
-
process.stdout.write(`${logPrefix('info', inspect(obj, inspectOptions))}\n`)
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
console.table = (data, columns) => {
|
|
48
|
-
const prefix = logPrefix('info')
|
|
49
|
-
|
|
50
|
-
// Capture table output
|
|
51
|
-
const originalWrite = process.stdout.write.bind(process.stdout)
|
|
52
|
-
let buffer = ''
|
|
53
|
-
|
|
54
|
-
process.stdout.write = (chunk, _encoding, callback) => {
|
|
55
|
-
buffer += chunk
|
|
56
|
-
if (typeof callback === 'function') callback()
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
renderTable(data, columns)
|
|
60
|
-
|
|
61
|
-
// Restore and print
|
|
62
|
-
process.stdout.write = originalWrite
|
|
63
|
-
for (const line of buffer.split('\n')) {
|
|
64
|
-
if (line.trim()) {
|
|
65
|
-
const message = `${!line.startsWith(prefix) ? `${prefix} ${line}` : line}`.trim()
|
|
66
|
-
process.stdout.write(`${message}\n`)
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
console.warn = (...args) => {
|
|
72
|
-
process.stdout.write(`${logPrefix('warn', ...args)}\n`)
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
console.error = (...args) => {
|
|
76
|
-
process.stdout.write(`${logPrefix('error', ...args)}\n`)
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Pending nested `context.invoke` calls, keyed by correlation id. Each entry
|
|
81
|
-
* holds the resolve/reject of the Promise returned to the user's handler; it is
|
|
82
|
-
* settled when the matching `invoke-response` arrives from the parent.
|
|
83
|
-
* @type {Map<string, {resolve: (value: unknown) => void, reject: (reason: Error) => void}>}
|
|
84
|
-
*/
|
|
85
|
-
const pendingInvokes = new Map()
|
|
86
|
-
let invokeSeq = 0
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* `context.invoke(name, payload)` — ask the parent to execute another blueprint
|
|
90
|
-
* function and resolve with its return value. Sent over IPC and correlated by id.
|
|
91
|
-
* @param {string} name
|
|
92
|
-
* @param {Record<string, unknown>} [payload]
|
|
93
|
-
* @returns {Promise<unknown>}
|
|
94
|
-
*/
|
|
95
|
-
function invokeFunction(name, payload = {}) {
|
|
96
|
-
if (typeof name !== 'string' || name.length === 0) {
|
|
97
|
-
return Promise.reject(new Error('context.invoke requires a function name'))
|
|
98
|
-
}
|
|
99
|
-
const id = String(++invokeSeq)
|
|
100
|
-
return new Promise((resolve, reject) => {
|
|
101
|
-
pendingInvokes.set(id, {resolve, reject})
|
|
102
|
-
process.send(JSON.stringify({type: 'invoke-request', id, name, payload}))
|
|
103
|
-
})
|
|
104
|
-
}
|
|
105
|
-
|
|
106
25
|
// Listen for IPC messages from the parent process.
|
|
107
26
|
process.on('message', async (data) => {
|
|
108
27
|
let jsonData = null
|
|
@@ -115,18 +34,7 @@ process.on('message', async (data) => {
|
|
|
115
34
|
|
|
116
35
|
// Response to a nested context.invoke() — route to the awaiting Promise and stop.
|
|
117
36
|
if (jsonData?.type === 'invoke-response') {
|
|
118
|
-
|
|
119
|
-
if (!pending) return
|
|
120
|
-
pendingInvokes.delete(jsonData.id)
|
|
121
|
-
if (jsonData.ok) {
|
|
122
|
-
pending.resolve(jsonData.result?.json)
|
|
123
|
-
} else {
|
|
124
|
-
const {message, stack, name} = jsonData.error ?? {}
|
|
125
|
-
const error = new Error(message ?? 'Nested invoke failed')
|
|
126
|
-
if (stack) error.stack = stack
|
|
127
|
-
if (name) error.name = name
|
|
128
|
-
pending.reject(error)
|
|
129
|
-
}
|
|
37
|
+
invoker.handleResponse(jsonData)
|
|
130
38
|
return
|
|
131
39
|
}
|
|
132
40
|
|
|
@@ -160,25 +68,20 @@ process.on('message', async (data) => {
|
|
|
160
68
|
try {
|
|
161
69
|
// Import the function code
|
|
162
70
|
const entry = await import(getFunctionSource(srcPath))
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
throw new Error(
|
|
167
|
-
'No valid handler found. Please provide a default export or a named export, "handler"',
|
|
168
|
-
)
|
|
71
|
+
const handler = entry.handler || entry.default
|
|
72
|
+
if (typeof handler !== 'function') {
|
|
73
|
+
throw new Error('No valid handler found. Provide a default export or a named "handler".')
|
|
169
74
|
}
|
|
170
75
|
|
|
171
76
|
// Replace resources JSON with Resources API
|
|
172
77
|
context.resources = createResourcesApi(context.resources)
|
|
173
78
|
|
|
174
79
|
// Allow the handler to invoke other blueprint functions by name.
|
|
175
|
-
context.invoke =
|
|
176
|
-
|
|
177
|
-
json = await eventHandler({
|
|
80
|
+
context.invoke = invoker.invoke
|
|
81
|
+
json = await handler({
|
|
178
82
|
context,
|
|
179
83
|
event,
|
|
180
|
-
|
|
181
|
-
done: async (_tags) => new Response(null, {status: 204}),
|
|
84
|
+
done: async () => new Response(null, {status: 204}),
|
|
182
85
|
})
|
|
183
86
|
|
|
184
87
|
// Restore streams
|
|
@@ -191,7 +94,6 @@ process.on('message', async (data) => {
|
|
|
191
94
|
// Restore streams on error
|
|
192
95
|
process.stdout.write = originalStdoutWrite
|
|
193
96
|
process.stderr.write = originalStderrWrite
|
|
194
|
-
|
|
195
97
|
const errorInfo = {
|
|
196
98
|
type: 'result',
|
|
197
99
|
json: null,
|
|
@@ -207,63 +109,3 @@ process.on('message', async (data) => {
|
|
|
207
109
|
process.exit(1)
|
|
208
110
|
}
|
|
209
111
|
})
|
|
210
|
-
|
|
211
|
-
/**
|
|
212
|
-
* The returned proxy wraps a function so the API itself is callable.
|
|
213
|
-
* @param {Record<string, ResourceEntry[]>} resources
|
|
214
|
-
* @returns {ResourcesApi}
|
|
215
|
-
*/
|
|
216
|
-
export function createResourcesApi(resources) {
|
|
217
|
-
const findByName = (name) => {
|
|
218
|
-
for (const group of Object.values(resources)) {
|
|
219
|
-
const found = group.find((r) => r.name === name)
|
|
220
|
-
if (found) return found
|
|
221
|
-
}
|
|
222
|
-
return undefined
|
|
223
|
-
}
|
|
224
|
-
let allCache
|
|
225
|
-
const all = () => (allCache ??= Object.values(resources).flat())
|
|
226
|
-
|
|
227
|
-
return /** @type {ResourcesApi} */ (
|
|
228
|
-
/** @type {unknown} */ (
|
|
229
|
-
/*
|
|
230
|
-
* The Proxy target is `findByName`, so invoking the API as a function —
|
|
231
|
-
* `context.resources('my-proj')` — bypasses the `get` trap entirely and
|
|
232
|
-
* calls `findByName` directly for a cross-type lookup by name.
|
|
233
|
-
*/
|
|
234
|
-
new Proxy(findByName, {
|
|
235
|
-
get: (_target, prop) => {
|
|
236
|
-
// context.resources.all() — flat array of every resource across types
|
|
237
|
-
if (prop === 'all') return all
|
|
238
|
-
// [...context.resources] / for (const r of context.resources) — iterate all
|
|
239
|
-
if (prop === Symbol.iterator) {
|
|
240
|
-
return function* () {
|
|
241
|
-
yield* all()
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/**
|
|
246
|
-
* Symbol property access (other than iterator above) and `then`
|
|
247
|
-
* lookups return undefined. The `then` guard prevents the API from
|
|
248
|
-
* looking like a thenable, so `await context.resources` resolves to
|
|
249
|
-
* the proxy itself rather than hanging or unwrapping unexpectedly.
|
|
250
|
-
*/
|
|
251
|
-
if (typeof prop !== 'string' || prop === 'then') {
|
|
252
|
-
return undefined
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
/**
|
|
256
|
-
* context.resources.<type>(name) — per-type lookup,
|
|
257
|
-
* e.g. context.resources.project('my-proj').
|
|
258
|
-
* Returns a function so the caller supplies the name;
|
|
259
|
-
* unknown types yield a function that always returns undefined.
|
|
260
|
-
*/
|
|
261
|
-
return (/** @type {string} */ name) =>
|
|
262
|
-
Object.hasOwn(resources, prop)
|
|
263
|
-
? resources[prop].find((r) => r.name === name)
|
|
264
|
-
: undefined
|
|
265
|
-
},
|
|
266
|
-
})
|
|
267
|
-
)
|
|
268
|
-
)
|
|
269
|
-
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function installConsole(): void
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import {table as renderTable} from 'node:console'
|
|
2
|
+
import process from 'node:process'
|
|
3
|
+
import {inspect} from 'node:util'
|
|
4
|
+
|
|
5
|
+
// Monkey patch console methods to have logs match server log format
|
|
6
|
+
function logPrefix(level, ...args) {
|
|
7
|
+
const date = new Date()
|
|
8
|
+
const shouldUseColors = process.env.FORCE_COLOR === '1'
|
|
9
|
+
const message = args
|
|
10
|
+
.map((arg) =>
|
|
11
|
+
typeof arg === 'string' ? arg : inspect(arg, {depth: null, colors: shouldUseColors}),
|
|
12
|
+
)
|
|
13
|
+
.join(' ')
|
|
14
|
+
return `${date.toLocaleDateString()} ${date.toLocaleTimeString()} ${level.toUpperCase()} ${message}`
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function installConsole() {
|
|
18
|
+
console.log = (...args) => process.stdout.write(`${logPrefix('info', ...args)}\n`)
|
|
19
|
+
console.info = (...args) => process.stdout.write(`${logPrefix('info', ...args)}\n`)
|
|
20
|
+
console.warn = (...args) => process.stdout.write(`${logPrefix('warn', ...args)}\n`)
|
|
21
|
+
console.error = (...args) => process.stdout.write(`${logPrefix('error', ...args)}\n`)
|
|
22
|
+
console.dir = (obj, options) => {
|
|
23
|
+
const shouldUseColors = process.env.FORCE_COLOR === '1'
|
|
24
|
+
const inspectOptions = {...options, colors: shouldUseColors}
|
|
25
|
+
process.stdout.write(`${logPrefix('info', inspect(obj, inspectOptions))}\n`)
|
|
26
|
+
}
|
|
27
|
+
console.table = (data, columns) => {
|
|
28
|
+
const prefix = logPrefix('info')
|
|
29
|
+
|
|
30
|
+
// Capture table output
|
|
31
|
+
const originalWrite = process.stdout.write.bind(process.stdout)
|
|
32
|
+
let buffer = ''
|
|
33
|
+
|
|
34
|
+
process.stdout.write = (chunk, _encoding, callback) => {
|
|
35
|
+
buffer += chunk
|
|
36
|
+
if (typeof callback === 'function') callback()
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
renderTable(data, columns)
|
|
40
|
+
|
|
41
|
+
// Restore and print
|
|
42
|
+
process.stdout.write = originalWrite
|
|
43
|
+
for (const line of buffer.split('\n')) {
|
|
44
|
+
if (line.trim()) {
|
|
45
|
+
const message = `${!line.startsWith(prefix) ? `${prefix} ${line}` : line}`.trim()
|
|
46
|
+
process.stdout.write(`${message}\n`)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import process from 'node:process'
|
|
2
|
+
|
|
3
|
+
export function createInvoker() {
|
|
4
|
+
/**
|
|
5
|
+
* Pending nested `context.invoke` calls, keyed by correlation id. Each entry
|
|
6
|
+
* holds the resolve/reject of the Promise returned to the user's handler; it is
|
|
7
|
+
* settled when the matching `invoke-response` arrives from the parent.
|
|
8
|
+
* @type {Map<string, {resolve: (value: unknown) => void, reject: (reason: Error) => void}>}
|
|
9
|
+
*/
|
|
10
|
+
const pending = new Map()
|
|
11
|
+
let invokeSeq = 0
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* `context.invoke(name, payload)` — ask the parent to execute another blueprint
|
|
15
|
+
* function and resolve with its return value. Sent over IPC and correlated by id.
|
|
16
|
+
* @param {string} name
|
|
17
|
+
* @param {Record<string, unknown>} [payload]
|
|
18
|
+
* @returns {Promise<unknown>}
|
|
19
|
+
*/
|
|
20
|
+
function invoke(name, payload = {}) {
|
|
21
|
+
if (typeof name !== 'string' || name.length === 0) {
|
|
22
|
+
return Promise.reject(new Error('context.invoke requires a function name'))
|
|
23
|
+
}
|
|
24
|
+
const id = String(++invokeSeq)
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
pending.set(id, {resolve, reject})
|
|
27
|
+
process.send(JSON.stringify({type: 'invoke-request', id, name, payload}))
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function handleResponse(msg) {
|
|
32
|
+
const pendingEntry = pending.get(msg.id)
|
|
33
|
+
if (!pendingEntry) return
|
|
34
|
+
pending.delete(msg.id)
|
|
35
|
+
if (msg.ok) {
|
|
36
|
+
pendingEntry.resolve(msg.result?.json)
|
|
37
|
+
} else {
|
|
38
|
+
const {message, stack, name} = msg.error ?? {}
|
|
39
|
+
const err = new Error(message ?? 'Nested invoke failed')
|
|
40
|
+
if (stack) err.stack = stack
|
|
41
|
+
if (name) err.name = name
|
|
42
|
+
pendingEntry.reject(err)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return {invoke, handleResponse}
|
|
47
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The returned proxy wraps a function so the API itself is callable.
|
|
3
|
+
* @param {Record<string, ResourceEntry[]>} resources
|
|
4
|
+
* @returns {ResourcesApi}
|
|
5
|
+
*/
|
|
6
|
+
export function createResourcesApi(resources) {
|
|
7
|
+
const findByName = (name) => {
|
|
8
|
+
for (const group of Object.values(resources)) {
|
|
9
|
+
const found = group.find((r) => r.name === name)
|
|
10
|
+
if (found) return found
|
|
11
|
+
}
|
|
12
|
+
return undefined
|
|
13
|
+
}
|
|
14
|
+
let allCache
|
|
15
|
+
const all = () => (allCache ??= Object.values(resources).flat())
|
|
16
|
+
|
|
17
|
+
return /** @type {ResourcesApi} */ (
|
|
18
|
+
/** @type {unknown} */ (
|
|
19
|
+
/*
|
|
20
|
+
* The Proxy target is `findByName`, so invoking the API as a function —
|
|
21
|
+
* `context.resources('my-proj')` — bypasses the `get` trap entirely and
|
|
22
|
+
* calls `findByName` directly for a cross-type lookup by name.
|
|
23
|
+
*/
|
|
24
|
+
new Proxy(findByName, {
|
|
25
|
+
get: (_target, prop) => {
|
|
26
|
+
// context.resources.all() — flat array of every resource across types
|
|
27
|
+
if (prop === 'all') return all
|
|
28
|
+
// [...context.resources] / for (const r of context.resources) — iterate all
|
|
29
|
+
if (prop === Symbol.iterator) {
|
|
30
|
+
return function* () {
|
|
31
|
+
yield* all()
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Symbol property access (other than iterator above) and `then`
|
|
37
|
+
* lookups return undefined. The `then` guard prevents the API from
|
|
38
|
+
* looking like a thenable, so `await context.resources` resolves to
|
|
39
|
+
* the proxy itself rather than hanging or unwrapping unexpectedly.
|
|
40
|
+
*/
|
|
41
|
+
if (typeof prop !== 'string' || prop === 'then') {
|
|
42
|
+
return undefined
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* context.resources.<type>(name) — per-type lookup,
|
|
47
|
+
* e.g. context.resources.project('my-proj').
|
|
48
|
+
* Returns a function so the caller supplies the name;
|
|
49
|
+
* unknown types yield a function that always returns undefined.
|
|
50
|
+
*/
|
|
51
|
+
return (/** @type {string} */ name) =>
|
|
52
|
+
Object.hasOwn(resources, prop)
|
|
53
|
+
? resources[prop].find((r) => r.name === name)
|
|
54
|
+
: undefined
|
|
55
|
+
},
|
|
56
|
+
})
|
|
57
|
+
)
|
|
58
|
+
)
|
|
59
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { BlueprintStudioResource } from '@sanity/blueprints';
|
|
2
|
+
import type { AssetPrepResult } from '../types.js';
|
|
3
|
+
export declare function prepareStudioAsset({ blueprintFileDir, resource, }: {
|
|
4
|
+
blueprintFileDir: string;
|
|
5
|
+
resource: BlueprintStudioResource;
|
|
6
|
+
}): Promise<AssetPrepResult>;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { createWriteStream } from 'node:fs';
|
|
2
|
+
import { mkdtemp, rm, stat } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path, { basename, dirname, join } from 'node:path';
|
|
5
|
+
import { pipeline } from 'node:stream/promises';
|
|
6
|
+
import { createGzip } from 'node:zlib';
|
|
7
|
+
import { buildStudio, compareDependencyVersions } from '@sanity/cli-build/_internal/build';
|
|
8
|
+
import { pack } from 'tar-fs';
|
|
9
|
+
export async function prepareStudioAsset({ blueprintFileDir, resource, }) {
|
|
10
|
+
// validate resource has an externalId
|
|
11
|
+
if (!('externalId' in resource) ||
|
|
12
|
+
typeof resource.externalId !== 'string' ||
|
|
13
|
+
!resource.externalId) {
|
|
14
|
+
return {
|
|
15
|
+
success: false,
|
|
16
|
+
async cleanup() {
|
|
17
|
+
// no op
|
|
18
|
+
},
|
|
19
|
+
error: `Unable to determine appId for sanity.studio resource '${resource.name}'`,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
let cleanup = async () => {
|
|
23
|
+
// no op
|
|
24
|
+
};
|
|
25
|
+
const studioPath = path.resolve(blueprintFileDir, resource.src);
|
|
26
|
+
try {
|
|
27
|
+
const studioPathStat = await stat(studioPath);
|
|
28
|
+
if (!studioPathStat.isDirectory()) {
|
|
29
|
+
return {
|
|
30
|
+
success: false,
|
|
31
|
+
cleanup,
|
|
32
|
+
error: `Property 'src' on resource with type '${resource.type}' must be a directory`,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
38
|
+
return {
|
|
39
|
+
success: false,
|
|
40
|
+
cleanup,
|
|
41
|
+
error: `Unable to read given 'src' on resource with type '${resource.type}': ${msg}`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
const outDir = await mkdtemp(join(tmpdir(), `studio-build-`));
|
|
46
|
+
const outFile = `${outDir}.tar.gz`;
|
|
47
|
+
cleanup = async () => {
|
|
48
|
+
await rm(outDir, { force: true, recursive: true });
|
|
49
|
+
await rm(outFile, { force: true });
|
|
50
|
+
};
|
|
51
|
+
const appId = resource.externalId;
|
|
52
|
+
try {
|
|
53
|
+
await buildStudio({
|
|
54
|
+
appId,
|
|
55
|
+
autoUpdatesEnabled: resource.autoUpdates.enabled,
|
|
56
|
+
checkAppId() { },
|
|
57
|
+
async compareDependencyVersions(packages) {
|
|
58
|
+
return compareDependencyVersions(packages, studioPath, { appId });
|
|
59
|
+
},
|
|
60
|
+
determineBasePath() {
|
|
61
|
+
return resource.basePath ?? '/';
|
|
62
|
+
},
|
|
63
|
+
isApp: false,
|
|
64
|
+
isWorkbenchApp: false,
|
|
65
|
+
minify: resource.minify ?? true,
|
|
66
|
+
outDir,
|
|
67
|
+
output: createSilentOutput(),
|
|
68
|
+
reactCompiler: resource.reactCompiler || false,
|
|
69
|
+
schemaExtraction: undefined,
|
|
70
|
+
sourceMap: resource.sourceMap ?? false,
|
|
71
|
+
stats: false,
|
|
72
|
+
unattendedMode: true,
|
|
73
|
+
// TODO pass in vite config from the studio resource
|
|
74
|
+
vite: undefined,
|
|
75
|
+
workDir: studioPath,
|
|
76
|
+
eventListener: {
|
|
77
|
+
onBuildFail({ message }) {
|
|
78
|
+
throw new Error(message);
|
|
79
|
+
},
|
|
80
|
+
onInvalidStyledComponentsVersionRange({ message }) {
|
|
81
|
+
throw new Error(message);
|
|
82
|
+
},
|
|
83
|
+
onNoDeclaredStyledComponentsVersion({ message }) {
|
|
84
|
+
throw new Error(message);
|
|
85
|
+
},
|
|
86
|
+
onNoInstalledSanityVersion({ message }) {
|
|
87
|
+
throw new Error(message);
|
|
88
|
+
},
|
|
89
|
+
onNoInstalledStyledComponentsVersion({ message }) {
|
|
90
|
+
throw new Error(message);
|
|
91
|
+
},
|
|
92
|
+
onPreReleaseInNonInteractiveAutoUpdate({ message }) {
|
|
93
|
+
throw new Error(message);
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
100
|
+
return {
|
|
101
|
+
success: false,
|
|
102
|
+
cleanup,
|
|
103
|
+
error: message,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
// tar/gzip/write the built output
|
|
107
|
+
await pipeline(pack(dirname(outDir), { entries: [basename(outDir)] }), createGzip(), createWriteStream(outFile));
|
|
108
|
+
return {
|
|
109
|
+
success: true,
|
|
110
|
+
cleanup,
|
|
111
|
+
// studio must be pre built (e.g. with `npm run build`) and tarred/gzipped
|
|
112
|
+
outputPath: outFile,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
return {
|
|
117
|
+
success: false,
|
|
118
|
+
cleanup,
|
|
119
|
+
error: error instanceof Error ? error.message : String(error),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function createSilentOutput() {
|
|
124
|
+
return {
|
|
125
|
+
error(input, options) {
|
|
126
|
+
if (typeof options?.exit === 'number') {
|
|
127
|
+
if (input instanceof Error) {
|
|
128
|
+
throw input;
|
|
129
|
+
}
|
|
130
|
+
throw new Error(input);
|
|
131
|
+
}
|
|
132
|
+
return undefined;
|
|
133
|
+
},
|
|
134
|
+
log() { },
|
|
135
|
+
warn(input) {
|
|
136
|
+
return input;
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|