@sanity/runtime-cli 17.1.0 → 17.2.0-blueprinit.gd1553d6

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 (104) hide show
  1. package/README.md +38 -28
  2. package/dist/actions/blueprinit/manifest.d.ts +13 -0
  3. package/dist/actions/blueprinit/manifest.js +57 -0
  4. package/dist/actions/blueprinit/studio.d.ts +6 -0
  5. package/dist/actions/blueprinit/studio.js +43 -0
  6. package/dist/actions/blueprinit/templates.d.ts +34 -0
  7. package/dist/actions/blueprinit/templates.js +83 -0
  8. package/dist/actions/blueprinit/workspace.d.ts +15 -0
  9. package/dist/actions/blueprinit/workspace.js +142 -0
  10. package/dist/actions/blueprints/assets.d.ts +2 -1
  11. package/dist/actions/blueprints/assets.js +17 -26
  12. package/dist/actions/blueprints/blueprint.d.ts +1 -1
  13. package/dist/actions/blueprints/pre-deploy.d.ts +29 -0
  14. package/dist/actions/blueprints/pre-deploy.js +164 -0
  15. package/dist/actions/blueprints/wait-for-operation.js +4 -0
  16. package/dist/actions/sanity/datasets.d.ts +15 -0
  17. package/dist/actions/sanity/datasets.js +26 -0
  18. package/dist/actions/sanity/examples.d.ts +4 -4
  19. package/dist/baseCommands.d.ts +4 -4
  20. package/dist/commands/blueprinit.d.ts +13 -0
  21. package/dist/commands/blueprinit.js +44 -0
  22. package/dist/commands/blueprints/add.d.ts +1 -1
  23. package/dist/commands/blueprints/config.d.ts +1 -1
  24. package/dist/commands/blueprints/deploy.d.ts +1 -1
  25. package/dist/commands/blueprints/destroy.d.ts +1 -1
  26. package/dist/commands/blueprints/doctor.d.ts +0 -1
  27. package/dist/commands/blueprints/doctor.js +3 -7
  28. package/dist/commands/blueprints/info.d.ts +1 -1
  29. package/dist/commands/blueprints/logs.d.ts +1 -1
  30. package/dist/commands/blueprints/mint-deploy-token.d.ts +1 -1
  31. package/dist/commands/blueprints/plan.d.ts +1 -1
  32. package/dist/commands/blueprints/promote.d.ts +1 -1
  33. package/dist/commands/blueprints/stacks.d.ts +1 -1
  34. package/dist/commands/functions/add.d.ts +1 -1
  35. package/dist/commands/functions/build.d.ts +1 -1
  36. package/dist/commands/functions/dev.d.ts +1 -1
  37. package/dist/commands/functions/env/add.d.ts +4 -1
  38. package/dist/commands/functions/env/add.js +6 -2
  39. package/dist/commands/functions/env/list.d.ts +4 -1
  40. package/dist/commands/functions/env/list.js +9 -3
  41. package/dist/commands/functions/env/remove.d.ts +4 -1
  42. package/dist/commands/functions/env/remove.js +9 -3
  43. package/dist/commands/functions/logs.d.ts +1 -1
  44. package/dist/commands/functions/test.d.ts +1 -1
  45. package/dist/constants.d.ts +1 -0
  46. package/dist/constants.js +1 -0
  47. package/dist/cores/blueprinit/adopt.d.ts +6 -0
  48. package/dist/cores/blueprinit/adopt.js +90 -0
  49. package/dist/cores/blueprinit/finish.d.ts +14 -0
  50. package/dist/cores/blueprinit/finish.js +36 -0
  51. package/dist/cores/blueprinit/fresh.d.ts +3 -0
  52. package/dist/cores/blueprinit/fresh.js +88 -0
  53. package/dist/cores/blueprinit/prompts.d.ts +4 -0
  54. package/dist/cores/blueprinit/prompts.js +14 -0
  55. package/dist/cores/blueprinit/selection.d.ts +15 -0
  56. package/dist/cores/blueprinit/selection.js +63 -0
  57. package/dist/cores/blueprinit/types.d.ts +13 -0
  58. package/dist/cores/blueprinit/types.js +1 -0
  59. package/dist/cores/blueprinit.d.ts +7 -0
  60. package/dist/cores/blueprinit.js +39 -0
  61. package/dist/cores/blueprints/deploy.js +18 -65
  62. package/dist/cores/blueprints/doctor.js +15 -12
  63. package/dist/cores/functions/build.js +3 -2
  64. package/dist/cores/functions/test.js +4 -2
  65. package/dist/server/app.js +8 -2
  66. package/dist/server/static/favicon-dark.svg +1 -0
  67. package/dist/server/static/favicon.svg +1 -0
  68. package/dist/server/static/index.html +1 -1
  69. package/dist/server/static/vendor/vendor.bundle.js +5 -0
  70. package/dist/utils/functions/child-process-wrapper.js +13 -171
  71. package/dist/utils/functions/child-runtime/console.d.ts +1 -0
  72. package/dist/utils/functions/child-runtime/console.js +50 -0
  73. package/dist/utils/functions/child-runtime/invoke.d.ts +4 -0
  74. package/dist/utils/functions/child-runtime/invoke.js +47 -0
  75. package/dist/utils/functions/child-runtime/resources.d.ts +4 -0
  76. package/dist/utils/functions/child-runtime/resources.js +59 -0
  77. package/dist/utils/functions/find-entry-point.d.ts +1 -1
  78. package/dist/utils/functions/find-entry-point.js +10 -12
  79. package/dist/utils/functions/invoke/local.js +1 -1
  80. package/dist/utils/functions/invoke/prepare.d.ts +1 -1
  81. package/dist/utils/functions/invoke/prepare.js +19 -8
  82. package/dist/utils/functions/package-json.d.ts +1 -2
  83. package/dist/utils/functions/package-json.js +4 -6
  84. package/dist/utils/functions/prepare-asset.d.ts +2 -2
  85. package/dist/utils/functions/prepare-asset.js +18 -7
  86. package/dist/utils/functions/resolve-dependencies.d.ts +4 -1
  87. package/dist/utils/functions/resolve-dependencies.js +5 -6
  88. package/dist/utils/functions/resource-to-arc.d.ts +1 -1
  89. package/dist/utils/functions/resource-to-arc.js +4 -5
  90. package/dist/utils/functions/should-transpile.d.ts +7 -1
  91. package/dist/utils/functions/should-transpile.js +10 -10
  92. package/dist/utils/functions/transpile/function.d.ts +4 -1
  93. package/dist/utils/functions/transpile/function.js +9 -14
  94. package/dist/utils/functions/transpile/verify-handler.js +1 -1
  95. package/dist/utils/logger.d.ts +7 -5
  96. package/dist/utils/logger.js +33 -1
  97. package/dist/utils/progress.d.ts +5 -0
  98. package/dist/utils/progress.js +40 -0
  99. package/dist/utils/studios/prepare-asset.d.ts +6 -0
  100. package/dist/utils/studios/prepare-asset.js +139 -0
  101. package/dist/utils/types.d.ts +9 -8
  102. package/dist/utils/types.js +2 -3
  103. package/oclif.manifest.json +1049 -951
  104. package/package.json +30 -23
@@ -1,5 +1,5 @@
1
1
  import { dirname } from 'node:path';
2
- import { stashAsset } from '../../actions/blueprints/assets.js';
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,19 +7,15 @@ 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;
19
14
  const noWait = flags['no-wait'] || false;
20
15
  const stackName = flags['new-stack-name'] ?? deployedStack.name;
21
16
  const installer = flags['fn-installer'] || undefined;
22
- const workspaceWarnings = getWarnings({ dir: dirname(blueprint.fileInfo.blueprintFilePath) });
17
+ const blueprintFileDir = dirname(blueprint.fileInfo.blueprintFilePath);
18
+ const workspaceWarnings = getWarnings({ dir: blueprintFileDir });
23
19
  log(`Deploying "${stackName}" ${niceId(deployedStack.id)}...`);
24
20
  try {
25
21
  const { ok: checkOk, stack: currentStack } = await getStack({ stackId, auth, logger: log });
@@ -38,17 +34,21 @@ export async function blueprintDeployCore(options) {
38
34
  };
39
35
  }
40
36
  const resources = [...blueprint.resources];
41
- const assetResources = resources.filter(isAssetResource);
42
- if (assetResources.length > 0) {
43
- log('Processing assets...');
44
- for (const resource of assetResources) {
45
- const preDeployResult = await preDeploy(resource, { auth, installer, log });
46
- if (!preDeployResult.success)
47
- return preDeployResult;
48
- const idx = resources.indexOf(resource);
49
- if (idx !== -1)
50
- resources[idx] = preDeployResult.resource;
51
- }
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;
52
52
  }
53
53
  const spinner = log.ora('Deploying...').start();
54
54
  const { ok: deployOk, stack, error: deployError, } = await updateStack({
@@ -151,53 +151,6 @@ export async function blueprintDeployCore(options) {
151
151
  return { success: false, error: errorMessage };
152
152
  }
153
153
  }
154
- async function preDeploy(resource, options) {
155
- const { auth, installer, log } = options;
156
- const fnSpinner = log.ora({ text: `Processing ${resource.name}...`, prefixText: ' ' }).start();
157
- const warnTimer = setTimeout(() => {
158
- fnSpinner.text = `Still processing ${resource.name}, this can take a moment...`;
159
- }, warnTimeoutMs);
160
- let assetTimeoutTimer;
161
- let result;
162
- try {
163
- result = await Promise.race([
164
- stashAsset({ resource, auth, logger: log, installer }),
165
- new Promise((_, reject) => {
166
- assetTimeoutTimer = setTimeout(() => {
167
- reject(new Error(`Processing ${resource.name} timed out after ${assetTimeoutS}s`));
168
- }, assetTimeoutMs);
169
- }),
170
- ]);
171
- }
172
- catch (err) {
173
- const msg = err instanceof Error ? err.message : String(err);
174
- fnSpinner.fail(msg);
175
- return { success: false, error: msg };
176
- }
177
- finally {
178
- clearTimeout(warnTimer);
179
- clearTimeout(assetTimeoutTimer);
180
- }
181
- if (result.success && result.assetId) {
182
- const updatedResource = { ...resource, src: result.assetId };
183
- fnSpinner.succeed(`${updatedResource.name} ${niceId(result.assetId)}`);
184
- log(` Source: ${updatedResource.src}`);
185
- if (result.hash) {
186
- if (result.hash.length > 24) {
187
- log.verbose(` Hash: ${result.hash.slice(0, 8)}...${result.hash.slice(-12)}`);
188
- }
189
- else {
190
- log.verbose(` Hash: ${result.hash}`);
191
- }
192
- }
193
- if (result.exists)
194
- log.verbose(' Asset unchanged');
195
- return { success: true, resource: updatedResource };
196
- }
197
- const errorMsg = `Failed uploading ${resource.name} asset, deploy has stopped`;
198
- fnSpinner.fail(errorMsg);
199
- return { success: false, error: result.error || 'Failed to process asset' };
200
- }
201
154
  const CHECK_LEGACY_DEPLOY_PERMISSION = false;
202
155
  const BLUEPRINTS_PERMISSION_ENFORCEMENT_DATE = 'July 1, 2026';
203
156
  async function checkLegacyDeployPermission({ auth, scopeType, scopeId, log, }) {
@@ -2,13 +2,13 @@ import { readFileSync } from 'node:fs';
2
2
  import { dirname } from 'node:path';
3
3
  import { arch, cwd, env, version as nodeVersion, platform } from 'node:process';
4
4
  import * as resolve from 'empathic/resolve';
5
- import ora from 'ora';
6
5
  import { loadAndParseBlueprint, } from '../../actions/blueprints/blueprint.js';
7
6
  import { readConfigFile } from '../../actions/blueprints/config.js';
8
7
  import { resolveIds } from '../../actions/blueprints/resolve.js';
9
8
  import { getStack } from '../../actions/blueprints/stacks.js';
10
9
  import config, { RUNTIME_CLI_VERSION } from '../../config.js';
11
10
  import { formatDateTime } from '../../utils/display/dates.js';
11
+ import { presentBlueprintParserErrors } from '../../utils/display/errors.js';
12
12
  import { advise, check, filePathRelativeToCwd, niceId, renderSection, severe, unsure, } from '../../utils/display/presenters.js';
13
13
  import { styleText } from '../../utils/style-text.js';
14
14
  import { createTracedFetch } from '../../utils/traced-fetch.js';
@@ -55,7 +55,7 @@ export async function blueprintDoctorCore(options) {
55
55
  envRows.push(['CLI', bin]);
56
56
  const configRows = [];
57
57
  const stackRows = [];
58
- const spinner = ora('Running diagnostics...').start();
58
+ const spinner = log.ora('Running diagnostics...').start();
59
59
  // --- ONLINE ---
60
60
  const fetchFn = createTracedFetch(log);
61
61
  try {
@@ -109,6 +109,7 @@ export async function blueprintDoctorCore(options) {
109
109
  status: false,
110
110
  detail: `${blueprint.errors.length} error(s)`,
111
111
  };
112
+ log.verbose(presentBlueprintParserErrors(blueprint.errors));
112
113
  }
113
114
  }
114
115
  catch {
@@ -186,6 +187,8 @@ export async function blueprintDoctorCore(options) {
186
187
  stackRows.push(['Operation', `${op.status}${timestamp}`]);
187
188
  if (op.userMessage)
188
189
  stackRows.push([' Message', `"${op.userMessage}"`]);
190
+ if (v && op.systemMessage)
191
+ stackRows.push([' System', `"${op.systemMessage}"`]);
189
192
  }
190
193
  if (stack.resources) {
191
194
  stackRows.push(['Resources', `${stack.resources.length}`]);
@@ -275,20 +278,20 @@ export async function blueprintDoctorCore(options) {
275
278
  }
276
279
  // --- RENDER REPORT ---
277
280
  spinner.stop();
278
- // Environment (verbose)
279
- log.verbose(renderSection('Environment', envRows));
280
- log.verbose('');
281
- // Configuration (verbose)
281
+ // Environment
282
+ log(renderSection('Environment', envRows));
283
+ log('');
284
+ // Configuration
282
285
  if (configRows.length > 0) {
283
- log.verbose(renderSection('Configuration', configRows));
284
- log.verbose('');
286
+ log(renderSection('Configuration', configRows));
287
+ log('');
285
288
  }
286
- // Deployment (verbose)
289
+ // Deployment
287
290
  if (stackRows.length > 0) {
288
- log.verbose(renderSection('Deployment', stackRows));
289
- log.verbose('');
291
+ log(renderSection('Deployment', stackRows));
292
+ log('');
290
293
  }
291
- // Checks (always visible)
294
+ // Checks
292
295
  const maxLabel = Math.max(...Object.values(diagLookup).map((l) => l.length));
293
296
  log(styleText('bold', 'Checks'));
294
297
  let allGood = true;
@@ -18,13 +18,14 @@ export async function functionBuildCore(options) {
18
18
  functions = allFunctions;
19
19
  }
20
20
  const installer = flags['fn-installer'] || undefined;
21
- const outDir = flags['out-dir'] || path.join(path.dirname(blueprint.fileInfo.blueprintFilePath), '.build');
21
+ const blueprintFileDir = path.dirname(blueprint.fileInfo.blueprintFilePath);
22
+ const outDir = flags['out-dir'] || path.join(blueprintFileDir, '.build');
22
23
  await fs.promises.mkdir(outDir, { recursive: true });
23
24
  const errors = [];
24
25
  const built = [];
25
26
  for (const resource of functions) {
26
27
  const spinner = log.ora(`Building ${resource.name}...`).start();
27
- const prepResult = await prepareAsset({ resource }, { installer });
28
+ const prepResult = await prepareAsset({ resource, blueprintFileDir, installer });
28
29
  if (prepResult.success === false) {
29
30
  spinner.fail(`Failed to build ${resource.name}`);
30
31
  errors.push({ name: resource.name, error: prepResult.error ?? 'Unknown error' });
@@ -1,5 +1,5 @@
1
1
  import { readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { dirname, join } from 'node:path';
3
3
  import { cwd } from 'node:process';
4
4
  import { testAction } from '../../actions/functions/test.js';
5
5
  import config from '../../config.js';
@@ -50,6 +50,7 @@ export async function functionTestCore(options) {
50
50
  : undefined,
51
51
  logger: log,
52
52
  });
53
+ const blueprintFileDir = dirname(blueprint.fileInfo.blueprintFilePath);
53
54
  const contextOptions = docFunction || mediaFunction
54
55
  ? {
55
56
  clientOptions: {
@@ -63,8 +64,9 @@ export async function functionTestCore(options) {
63
64
  functionResourceType: 'project',
64
65
  functionResourceId: projectId || '',
65
66
  resources: resolvedResources,
67
+ blueprintFileDir,
66
68
  }
67
- : { clientOptions: {}, resources: resolvedResources };
69
+ : { clientOptions: {}, resources: resolvedResources, blueprintFileDir };
68
70
  // If the user sets the flag to use the real token set it in our options
69
71
  if (withUserToken) {
70
72
  contextOptions.clientOptions.token = config.token || undefined;
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync, watchFile } from 'node:fs';
2
2
  import * as http from 'node:http';
3
+ import { dirname } from 'node:path';
3
4
  import { default as mime } from 'mime-types';
4
5
  import { WebSocket, WebSocketServer } from 'ws';
5
6
  import { findBlueprintFile, loadAndParseBlueprint } from '../actions/blueprints/blueprint.js';
@@ -68,7 +69,11 @@ const app = (host, port, validateResources, executionOptions) => {
68
69
  req.on('end', async () => {
69
70
  res.setHeader('Content-Type', 'application/json');
70
71
  try {
71
- const { data, func: functionName, metadata } = parseInvokeRequest(Buffer.concat(body));
72
+ const fileInfo = findBlueprintFile();
73
+ if (!fileInfo) {
74
+ throw Error('Could not find a Blueprint manifest (sanity.blueprint.ts, .js, or .json). Run `blueprints init` to create one.');
75
+ }
76
+ const { data, func: functionName, metadata, } = parseInvokeRequest(Buffer.concat(body), dirname(fileInfo.blueprintFilePath));
72
77
  const { context, event } = data;
73
78
  // replace user token if required
74
79
  if (isGroqContextOptions(context)) {
@@ -312,7 +317,7 @@ function buildApiUrl(projectId, dataset, docId, apiUrl) {
312
317
  function buildAssetUrl(mediaLibraryId, docId, apiUrl) {
313
318
  return `${apiUrl}/v2025-03-24/media-libraries/${mediaLibraryId}/doc/${docId}`;
314
319
  }
315
- function parseInvokeRequest(body) {
320
+ function parseInvokeRequest(body, blueprintFileDir) {
316
321
  let json;
317
322
  try {
318
323
  json = JSON.parse(body.toString('utf8'));
@@ -404,6 +409,7 @@ function parseInvokeRequest(body) {
404
409
  context: {
405
410
  ...context,
406
411
  clientOptions,
412
+ blueprintFileDir,
407
413
  // Provide default values for required properties if not present
408
414
  eventResourceType: typeof context.eventResourceType === 'string' ? context.eventResourceType : '',
409
415
  eventResourceId: typeof context.eventResourceId === 'string' ? context.eventResourceId : '',
@@ -1,4 +1,5 @@
1
1
  <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
2
+ <title>Sanity.io logo</title>
2
3
  <g clip-path="url(#clip0_2_1533)">
3
4
  <rect width="32" height="32" fill="#FFFFFF"/>
4
5
  <rect width="32" height="32" fill="#FFFFFF"/>
@@ -1,4 +1,5 @@
1
1
  <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
2
+ <title>Sanity.io logo</title>
2
3
  <g clip-path="url(#clip0_2_1533)">
3
4
  <rect width="32" height="32" fill="#0B0B0B"/>
4
5
  <rect width="32" height="32" fill="#0B0B0B"/>
@@ -33,7 +33,7 @@
33
33
  <filters-component></filters-component>
34
34
  <input type="checkbox" id="nav-toggle" class="hidden">
35
35
  <nav id="sidebar" class="relative y-scroll max-h-100 pad-t-5 border-right overflow-auto nav-min-width">
36
- <label for="nav-toggle" id="nav-toggle-label" title="Toggle Functions list" class="z-10 nav-label"></label>
36
+ <label for="nav-toggle" id="nav-toggle-label" aria-label="Toggle Functions list" title="Toggle Functions list" class="z-10 nav-label"></label>
37
37
  <h4 class="config-label mar-t-0 mar-b-3 pad-l-3">Functions</h4>
38
38
  <function-list></function-list>
39
39
  </nav>
@@ -6203,6 +6203,7 @@ class FacetProvider {
6203
6203
  }
6204
6204
  };
6205
6205
  }
6206
+ get extension() { return this; }
6206
6207
  }
6207
6208
  function compareArray(a, b, compare) {
6208
6209
  if (a.length != b.length)
@@ -6400,6 +6401,7 @@ class PrecExtension {
6400
6401
  this.inner = inner;
6401
6402
  this.prec = prec;
6402
6403
  }
6404
+ get extension() { return this; }
6403
6405
  }
6404
6406
  /**
6405
6407
  Extension compartments can be used to make a configuration
@@ -6434,6 +6436,7 @@ class CompartmentInstance {
6434
6436
  this.compartment = compartment;
6435
6437
  this.inner = inner;
6436
6438
  }
6439
+ get extension() { return this; }
6437
6440
  }
6438
6441
  class Configuration {
6439
6442
  constructor(base, compartments, dynamicSlots, address, staticValues, facets) {
@@ -6543,6 +6546,8 @@ function flatten(extension, compartments, newCompartments) {
6543
6546
  else {
6544
6547
  let content = ext.extension;
6545
6548
  if (!content)
6549
+ throw new Error(`Unrecognized extension value in extension set (${ext}).`);
6550
+ if (content == ext)
6546
6551
  throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
6547
6552
  inner(content, prec);
6548
6553
  }
@@ -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 {inspect} from 'node:util'
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
- const pending = pendingInvokes.get(jsonData.id)
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 eventHandler = entry.handler || entry.default
164
-
165
- if (typeof eventHandler !== 'function') {
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 = invokeFunction
176
-
177
- json = await eventHandler({
80
+ context.invoke = invoker.invoke
81
+ json = await handler({
178
82
  context,
179
83
  event,
180
- // mock sync-tag-invalidate done callback
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,4 @@
1
+ export function createInvoker(): {
2
+ invoke: (name: string, payload?: Record<string, unknown>) => Promise<unknown>
3
+ handleResponse: (msg: unknown) => void
4
+ }
@@ -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,4 @@
1
+ import type {ResourcesApi} from '@sanity/functions'
2
+ import type {GroupedBlueprintResources} from '../../blueprints/group-resources.js'
3
+
4
+ export function createResourcesApi(resources: GroupedBlueprintResources): ResourcesApi