@sanity/cli-core 2.3.0 → 2.5.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.
Files changed (33) hide show
  1. package/dist/SanityCommand.d.ts +13 -1
  2. package/dist/_exports/config.d.ts +13 -1
  3. package/dist/_exports/index.d.ts +35 -8
  4. package/dist/_exports/index.js +1 -0
  5. package/dist/_exports/index.js.map +1 -1
  6. package/dist/_exports/package-manager.d.ts +1 -2
  7. package/dist/_exports/schemas.d.ts +8 -0
  8. package/dist/_exports/tasks.d.ts +6 -6
  9. package/dist/_exports/types.d.ts +14 -1
  10. package/dist/_exports/undeploy.d.ts +74 -0
  11. package/dist/_exports/undeploy.js +13 -0
  12. package/dist/_exports/undeploy.js.map +1 -0
  13. package/dist/_exports/util.d.ts +5 -0
  14. package/dist/_exports/util.js +1 -0
  15. package/dist/_exports/util.js.map +1 -1
  16. package/dist/_exports/ux.d.ts +1 -2
  17. package/dist/config/cli/schemas.js +3 -1
  18. package/dist/config/cli/schemas.js.map +1 -1
  19. package/dist/config/cli/types/cliConfig.js +7 -5
  20. package/dist/config/cli/types/cliConfig.js.map +1 -1
  21. package/dist/loaders/studio/studioWorkerLifecycle.js +85 -0
  22. package/dist/loaders/studio/studioWorkerLifecycle.js.map +1 -0
  23. package/dist/loaders/studio/studioWorkerLoader.worker.js +86 -54
  24. package/dist/loaders/studio/studioWorkerLoader.worker.js.map +1 -1
  25. package/dist/loaders/studio/studioWorkerTask.js +17 -1
  26. package/dist/loaders/studio/studioWorkerTask.js.map +1 -1
  27. package/dist/manifest.js +1 -0
  28. package/dist/manifest.js.map +1 -1
  29. package/dist/util/getCoreAppUrl.js +6 -0
  30. package/dist/util/getCoreAppUrl.js.map +1 -0
  31. package/dist/util/promisifyWorker.js +21 -6
  32. package/dist/util/promisifyWorker.js.map +1 -1
  33. package/package.json +17 -13
@@ -0,0 +1,85 @@
1
+ const DEFAULT_STUDIO_WORKER_CLOSE_TIMEOUT = 5000;
2
+ const STUDIO_WORKER_ERROR_MARKER = 'sanity.studioWorker.error';
3
+ /**
4
+ * Defers messages from a one-shot studio worker until its Vite server has had
5
+ * a bounded opportunity to close. With Vite 8 the server hosts rolldown — a
6
+ * native addon whose threads talk to JS via napi threadsafe functions — and
7
+ * tearing the worker down while those threads are live aborts the whole
8
+ * process (silent SIGABRT / exit 134, reliably on macOS). Closing is
9
+ * single-flight so the task's final message and the loader's finalizer can
10
+ * safely request it at the same time.
11
+ */ export function createOneShotWorkerLifecycle(options) {
12
+ const { closeServer, onCloseError, parentPort, timeout = DEFAULT_STUDIO_WORKER_CLOSE_TIMEOUT } = options;
13
+ let closePromise;
14
+ const close = ()=>{
15
+ closePromise ??= closeServerWithTimeout(closeServer, timeout).catch((error)=>{
16
+ onCloseError(error);
17
+ });
18
+ return closePromise;
19
+ };
20
+ const originalPostMessage = parentPort.postMessage.bind(parentPort);
21
+ parentPort.postMessage = (...args)=>{
22
+ void close().then(()=>originalPostMessage(...args));
23
+ };
24
+ return {
25
+ close,
26
+ async postError (error) {
27
+ await close();
28
+ originalPostMessage(serializeStudioWorkerError(error));
29
+ }
30
+ };
31
+ }
32
+ export function deserializeStudioWorkerError(message) {
33
+ const cause = new Error(message.error.message);
34
+ cause.name = message.error.name;
35
+ if (message.error.stack) cause.stack = message.error.stack;
36
+ return new Error(`Worker error: ${message.error.message}`, {
37
+ cause
38
+ });
39
+ }
40
+ export function isStudioWorkerErrorMessage(value) {
41
+ if (typeof value !== 'object' || value === null || !('type' in value) || value.type !== STUDIO_WORKER_ERROR_MARKER || !('error' in value) || typeof value.error !== 'object' || value.error === null) {
42
+ return false;
43
+ }
44
+ const { error } = value;
45
+ return 'message' in error && typeof error.message === 'string' && 'name' in error && typeof error.name === 'string' && (!('stack' in error) || error.stack === undefined || typeof error.stack === 'string');
46
+ }
47
+ function closeServerWithTimeout(closeServer, timeout) {
48
+ return new Promise((resolve, reject)=>{
49
+ const timeoutId = setTimeout(()=>{
50
+ // Vite does not expose cancellation for close(); stop waiting while the
51
+ // unrefed worker lets the still-pending close finish with process teardown.
52
+ reject(new Error(`Vite server close timed out after ${timeout}ms`));
53
+ }, timeout);
54
+ void Promise.resolve().then(closeServer).then(()=>{
55
+ clearTimeout(timeoutId);
56
+ resolve();
57
+ }, (error)=>{
58
+ clearTimeout(timeoutId);
59
+ reject(error);
60
+ });
61
+ });
62
+ }
63
+ function serializeStudioWorkerError(error) {
64
+ if (error instanceof Error) {
65
+ return {
66
+ error: {
67
+ message: error.message,
68
+ name: error.name,
69
+ ...error.stack ? {
70
+ stack: error.stack
71
+ } : {}
72
+ },
73
+ type: STUDIO_WORKER_ERROR_MARKER
74
+ };
75
+ }
76
+ return {
77
+ error: {
78
+ message: String(error),
79
+ name: 'Error'
80
+ },
81
+ type: STUDIO_WORKER_ERROR_MARKER
82
+ };
83
+ }
84
+
85
+ //# sourceMappingURL=studioWorkerLifecycle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/loaders/studio/studioWorkerLifecycle.ts"],"sourcesContent":["import {type MessagePort} from 'node:worker_threads'\n\nconst DEFAULT_STUDIO_WORKER_CLOSE_TIMEOUT = 5000\n\nconst STUDIO_WORKER_ERROR_MARKER = 'sanity.studioWorker.error'\n\ninterface SerializedStudioWorkerError {\n message: string\n name: string\n\n stack?: string\n}\n\nexport interface StudioWorkerErrorMessage {\n error: SerializedStudioWorkerError\n type: typeof STUDIO_WORKER_ERROR_MARKER\n}\n\ninterface OneShotWorkerLifecycle {\n close: () => Promise<void>\n postError: (error: unknown) => Promise<void>\n}\n\ninterface OneShotWorkerLifecycleOptions {\n closeServer: () => Promise<void>\n onCloseError: (error: unknown) => void\n parentPort: MessagePort\n\n timeout?: number\n}\n\n/**\n * Defers messages from a one-shot studio worker until its Vite server has had\n * a bounded opportunity to close. With Vite 8 the server hosts rolldown — a\n * native addon whose threads talk to JS via napi threadsafe functions — and\n * tearing the worker down while those threads are live aborts the whole\n * process (silent SIGABRT / exit 134, reliably on macOS). Closing is\n * single-flight so the task's final message and the loader's finalizer can\n * safely request it at the same time.\n */\nexport function createOneShotWorkerLifecycle(\n options: OneShotWorkerLifecycleOptions,\n): OneShotWorkerLifecycle {\n const {\n closeServer,\n onCloseError,\n parentPort,\n timeout = DEFAULT_STUDIO_WORKER_CLOSE_TIMEOUT,\n } = options\n let closePromise: Promise<void> | undefined\n\n const close = () => {\n closePromise ??= closeServerWithTimeout(closeServer, timeout).catch((error) => {\n onCloseError(error)\n })\n return closePromise\n }\n\n const originalPostMessage = parentPort.postMessage.bind(parentPort)\n parentPort.postMessage = (...args: Parameters<MessagePort['postMessage']>) => {\n void close().then(() => originalPostMessage(...args))\n }\n\n return {\n close,\n async postError(error) {\n await close()\n originalPostMessage(serializeStudioWorkerError(error))\n },\n }\n}\n\nexport function deserializeStudioWorkerError(message: StudioWorkerErrorMessage): Error {\n const cause = new Error(message.error.message)\n cause.name = message.error.name\n if (message.error.stack) cause.stack = message.error.stack\n\n return new Error(`Worker error: ${message.error.message}`, {cause})\n}\n\nexport function isStudioWorkerErrorMessage(value: unknown): value is StudioWorkerErrorMessage {\n if (\n typeof value !== 'object' ||\n value === null ||\n !('type' in value) ||\n value.type !== STUDIO_WORKER_ERROR_MARKER ||\n !('error' in value) ||\n typeof value.error !== 'object' ||\n value.error === null\n ) {\n return false\n }\n\n const {error} = value\n return (\n 'message' in error &&\n typeof error.message === 'string' &&\n 'name' in error &&\n typeof error.name === 'string' &&\n (!('stack' in error) || error.stack === undefined || typeof error.stack === 'string')\n )\n}\n\nfunction closeServerWithTimeout(closeServer: () => Promise<void>, timeout: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n // Vite does not expose cancellation for close(); stop waiting while the\n // unrefed worker lets the still-pending close finish with process teardown.\n reject(new Error(`Vite server close timed out after ${timeout}ms`))\n }, timeout)\n\n void Promise.resolve()\n .then(closeServer)\n .then(\n () => {\n clearTimeout(timeoutId)\n resolve()\n },\n (error: unknown) => {\n clearTimeout(timeoutId)\n reject(error)\n },\n )\n })\n}\n\nfunction serializeStudioWorkerError(error: unknown): StudioWorkerErrorMessage {\n if (error instanceof Error) {\n return {\n error: {\n message: error.message,\n name: error.name,\n ...(error.stack ? {stack: error.stack} : {}),\n },\n type: STUDIO_WORKER_ERROR_MARKER,\n }\n }\n\n return {\n error: {\n message: String(error),\n name: 'Error',\n },\n type: STUDIO_WORKER_ERROR_MARKER,\n }\n}\n"],"names":["DEFAULT_STUDIO_WORKER_CLOSE_TIMEOUT","STUDIO_WORKER_ERROR_MARKER","createOneShotWorkerLifecycle","options","closeServer","onCloseError","parentPort","timeout","closePromise","close","closeServerWithTimeout","catch","error","originalPostMessage","postMessage","bind","args","then","postError","serializeStudioWorkerError","deserializeStudioWorkerError","message","cause","Error","name","stack","isStudioWorkerErrorMessage","value","type","undefined","Promise","resolve","reject","timeoutId","setTimeout","clearTimeout","String"],"mappings":"AAEA,MAAMA,sCAAsC;AAE5C,MAAMC,6BAA6B;AA2BnC;;;;;;;;CAQC,GACD,OAAO,SAASC,6BACdC,OAAsC;IAEtC,MAAM,EACJC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,UAAUP,mCAAmC,EAC9C,GAAGG;IACJ,IAAIK;IAEJ,MAAMC,QAAQ;QACZD,iBAAiBE,uBAAuBN,aAAaG,SAASI,KAAK,CAAC,CAACC;YACnEP,aAAaO;QACf;QACA,OAAOJ;IACT;IAEA,MAAMK,sBAAsBP,WAAWQ,WAAW,CAACC,IAAI,CAACT;IACxDA,WAAWQ,WAAW,GAAG,CAAC,GAAGE;QAC3B,KAAKP,QAAQQ,IAAI,CAAC,IAAMJ,uBAAuBG;IACjD;IAEA,OAAO;QACLP;QACA,MAAMS,WAAUN,KAAK;YACnB,MAAMH;YACNI,oBAAoBM,2BAA2BP;QACjD;IACF;AACF;AAEA,OAAO,SAASQ,6BAA6BC,OAAiC;IAC5E,MAAMC,QAAQ,IAAIC,MAAMF,QAAQT,KAAK,CAACS,O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MAAMY,IAAI;gBAChB,GAAIZ,MAAMa,KAAK,GAAG;oBAACA,OAAOb,MAAMa,KAAK;gBAAA,IAAI,CAAC,CAAC;YAC7C;YACAG,MAAM3B;QACR;IACF;IAEA,OAAO;QACLW,OAAO;YACLS,SAASe,OAAOxB;YAChBY,MAAM;QACR;QACAI,MAAM3B;IACR;AACF"}
@@ -1,4 +1,4 @@
1
- import { isMainThread } from 'node:worker_threads';
1
+ import { isMainThread, parentPort } from 'node:worker_threads';
2
2
  import { createServer, loadEnv, mergeConfig } from 'vite';
3
3
  import { ViteNodeRunner } from 'vite-node/client';
4
4
  import { ViteNodeServer } from 'vite-node/server';
@@ -9,6 +9,7 @@ import { isNotFoundError } from '../../errors/NotFoundError.js';
9
9
  import { getStudioEnvironmentVariables } from '../../util/environment/getStudioEnvironmentVariables.js';
10
10
  import { setupBrowserStubs } from '../../util/environment/setupBrowserStubs.js'; // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB
11
11
  import { isRecord } from '../../util/isRecord.js';
12
+ import { createOneShotWorkerLifecycle } from './studioWorkerLifecycle.js';
12
13
  if (isMainThread) {
13
14
  throw new Error('Should be child of thread, not the main thread');
14
15
  }
@@ -112,60 +113,91 @@ debug('Creating Vite server with config: %o', viteConfig);
112
113
  // Vite will build the files we give it - targetting Node.js instead of the browser.
113
114
  // We include the inject plugin in order to provide the stubs for the undefined global APIs.
114
115
  const server = await createServer(viteConfig);
115
- // Bit of a hack, but seems necessary based on the `node-vite` binary implementation
116
- await server.pluginContainer.buildStart({});
117
- // Load environment variables from `.env` files in the same way as Vite does.
118
- // Note that Sanity also provides environment variables through `process.env.*` for compat reasons,
119
- // and so we need to do the same here.
120
- // Load ALL env vars from .env files (not just studio-prefixed ones) so non-Sanity-prefixed
121
- // vars (e.g. NEXT_PUBLIC_*, VITE_*) are available via process.env at runtime.
122
- // The ??= on the next line prevents overwriting existing process.env values.
123
- const env = loadEnv(server.config.mode, server.config.envDir, '');
124
- for(const key in env){
125
- process.env[key] ??= env[key];
126
- }
127
- // Now we're providing the glue that ensures node-specific loading and execution works.
128
- const node = new ViteNodeServer(server);
129
- // Should make it easier to debug any crashes in the imported code…
130
- installSourcemapsSupport({
131
- getSourceMap: (source)=>node.getSourceMap(source)
132
- });
133
- const runner = new ViteNodeRunner({
134
- base: server.config.base,
135
- async fetchModule (id) {
136
- // Vite's SSR transform externalizes https:// imports, so Node's ESM loader
137
- // would reject them. We fetch the module over HTTP and run it through Vite's
138
- // SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*
139
- // format that ViteNodeRunner expects.
140
- if (isHttpsUrl(id)) {
141
- const { code: rawCode } = await fetchHttpModule(id);
142
- const result = await server.ssrTransform(rawCode, null, id);
143
- return {
144
- code: result?.code || rawCode
145
- };
146
- }
147
- return node.fetchModule(id);
116
+ // One-shot tasks (`studioWorkerTask`) resolve on their first message, and the
117
+ // main thread historically terminate()d the worker right after — destroying
118
+ // the worker's libuv loop while rolldown's native threads were still live.
119
+ // The next `napi_call_threadsafe_function` then locked a destroyed mutex and
120
+ // aborted the whole process (silent SIGABRT / exit code 134, reliably
121
+ // reproduced on macOS). The lifecycle closes the Vite server BEFORE any
122
+ // message reaches the main thread, and the main thread no longer terminates
123
+ // one-shot workers at all (see `terminateOnSettle` in promisifyWorker).
124
+ const lifecycle = process.env.STUDIO_WORKER_ONE_SHOT === '1' && parentPort ? createOneShotWorkerLifecycle({
125
+ closeServer: async ()=>{
126
+ debug('Closing Vite server');
127
+ await server.close();
128
+ debug('Vite server closed');
148
129
  },
149
- resolveId (id, importer) {
150
- // Prevent vite-node from trying to resolve HTTP URLs through Node's resolver
151
- if (isHttpsUrl(id)) return {
152
- id
153
- };
154
- // Resolve any import from an HTTP-fetched module against the remote origin
155
- // (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)
156
- if (importer && isHttpsUrl(importer)) {
157
- return {
158
- id: new URL(id, importer).href
130
+ onCloseError: (error)=>debug('Failed to close Vite server: %o', error),
131
+ parentPort
132
+ }) : undefined;
133
+ try {
134
+ // Bit of a hack, but seems necessary based on the `node-vite` binary implementation
135
+ await server.pluginContainer.buildStart({});
136
+ // Load environment variables from `.env` files in the same way as Vite does.
137
+ // Note that Sanity also provides environment variables through `process.env.*` for compat reasons,
138
+ // and so we need to do the same here.
139
+ // Load ALL env vars from .env files (not just studio-prefixed ones) so non-Sanity-prefixed
140
+ // vars (e.g. NEXT_PUBLIC_*, VITE_*) are available via process.env at runtime.
141
+ // The ??= on the next line prevents overwriting existing process.env values.
142
+ const env = loadEnv(server.config.mode, server.config.envDir, '');
143
+ for(const key in env){
144
+ process.env[key] ??= env[key];
145
+ }
146
+ // Now we're providing the glue that ensures node-specific loading and execution works.
147
+ const node = new ViteNodeServer(server);
148
+ // Should make it easier to debug any crashes in the imported code…
149
+ installSourcemapsSupport({
150
+ getSourceMap: (source)=>node.getSourceMap(source)
151
+ });
152
+ const runner = new ViteNodeRunner({
153
+ base: server.config.base,
154
+ async fetchModule (id) {
155
+ // Vite's SSR transform externalizes https:// imports, so Node's ESM loader
156
+ // would reject them. We fetch the module over HTTP and run it through Vite's
157
+ // SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*
158
+ // format that ViteNodeRunner expects.
159
+ if (isHttpsUrl(id)) {
160
+ const { code: rawCode } = await fetchHttpModule(id);
161
+ const result = await server.ssrTransform(rawCode, null, id);
162
+ return {
163
+ code: result?.code || rawCode
164
+ };
165
+ }
166
+ return node.fetchModule(id);
167
+ },
168
+ resolveId (id, importer) {
169
+ // Prevent vite-node from trying to resolve HTTP URLs through Node's resolver
170
+ if (isHttpsUrl(id)) return {
171
+ id
159
172
  };
160
- }
161
- return node.resolveId(id, importer);
162
- },
163
- root: server.config.root
164
- });
165
- // Copied from `vite-node` - it appears that this applies the `define` config from
166
- // vite, but it also takes a surprisingly long time to execute. Not clear at this
167
- // point why this is, so we should investigate whether it's necessary or not.
168
- await runner.executeId('/@vite/env');
169
- await runner.executeId(workerScriptPath);
173
+ // Resolve any import from an HTTP-fetched module against the remote origin
174
+ // (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)
175
+ if (importer && isHttpsUrl(importer)) {
176
+ return {
177
+ id: new URL(id, importer).href
178
+ };
179
+ }
180
+ return node.resolveId(id, importer);
181
+ },
182
+ root: server.config.root
183
+ });
184
+ // Copied from `vite-node` - it appears that this applies the `define` config from
185
+ // vite, but it also takes a surprisingly long time to execute. Not clear at this
186
+ // point why this is, so we should investigate whether it's necessary or not.
187
+ await runner.executeId('/@vite/env');
188
+ await runner.executeId(workerScriptPath);
189
+ } catch (error) {
190
+ // Long-lived workers keep the original behavior: the error surfaces as a
191
+ // Worker 'error' event.
192
+ if (!lifecycle) {
193
+ throw error;
194
+ }
195
+ // One-shot workers close the server first and post a serialized error the
196
+ // main thread rethrows, so the worker exits cleanly (code 0) and the real
197
+ // error (e.g. a broken `sanity.config.ts`) isn't masked by a teardown abort.
198
+ await lifecycle.postError(error);
199
+ } finally{
200
+ await lifecycle?.close();
201
+ }
170
202
 
171
203
  //# sourceMappingURL=studioWorkerLoader.worker.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {isMainThread} from 'node:worker_threads'\n\nimport {createServer, type InlineConfig, loadEnv, mergeConfig} from 'vite'\nimport {ViteNodeRunner} from 'vite-node/client'\nimport {ViteNodeServer} from 'vite-node/server'\nimport {installSourcemapsSupport} from 'vite-node/source-map'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {isNotFoundError} from '../../errors/NotFoundError.js'\nimport {getStudioEnvironmentVariables} from '../../util/environment/getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from '../../util/environment/setupBrowserStubs.js' // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB\nimport {isRecord} from '../../util/isRecord.js'\n\nif (isMainThread) {\n throw new Error('Should be child of thread, not the main thread')\n}\n\nconst rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH\nif (!rootPath) {\n throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable')\n}\n\nconst debug = subdebug('studio:worker')\n\nconst workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE\nif (!workerScriptPath) {\n throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable')\n}\n\nawait setupBrowserStubs()\n\nconst studioEnvVars = await getStudioEnvironmentVariables(rootPath)\n\n// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can\n// extend/modify the default vite configuration for the studio.\nlet cliConfig: CliConfig | undefined\ntry {\n cliConfig = await getCliConfig(rootPath)\n} catch (err) {\n debug('Failed to load CLI config: %o', err)\n if (!isNotFoundError(err)) {\n // eslint-disable-next-line no-console\n console.warn('[warn] Failed to load CLI config:', err)\n }\n}\n\n/**\n * Fetches and caches modules from HTTP/HTTPS URLs.\n * Vite's SSR transform treats `https://` imports as external and bypasses the plugin\n * resolve pipeline entirely, so we intercept them at the ViteNodeRunner level instead.\n */\nconst httpModuleCache = new Map<string, string>()\nasync function fetchHttpModule(url: string): Promise<{code: string}> {\n const cached = httpModuleCache.get(url)\n if (cached) return {code: cached}\n\n debug('Fetching HTTP import: %s', url)\n const response = await fetch(url, {signal: AbortSignal.timeout(30_000)})\n if (!response.ok) {\n throw new Error(`Failed to fetch module from ${url}: ${response.status} ${response.statusText}`)\n }\n\n const code = await response.text()\n httpModuleCache.set(url, code)\n return {code}\n}\n\nfunction isHttpsUrl(id: string): boolean {\n return id.startsWith('https://')\n}\n\nconst defaultViteConfig: InlineConfig = {\n build: {target: 'node'},\n configFile: false,\n // Inject environment variables as compile-time constants for Vite\n define: Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\n ),\n envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n esbuild: {\n jsx: 'automatic',\n },\n logLevel: 'error',\n optimizeDeps: {\n include: undefined,\n noDiscovery: true,\n },\n resolve: {\n // Resolve the studio's tsconfig `paths` natively (Vite 8+), replacing the\n // custom alias mapping and the need for a user-added `vite-tsconfig-paths`.\n tsconfigPaths: true,\n },\n root: rootPath,\n server: {\n hmr: false,\n watch: null,\n },\n ssr: {\n /**\n * We don't want to externalize any dependencies, we want everything to run thru vite.\n * Especially for CJS compatibility, etc.\n */\n noExternal: true,\n },\n}\n\n// Merge the CLI config's Vite config with the default Vite config\nlet viteConfig = defaultViteConfig\nif (typeof cliConfig?.vite === 'function') {\n viteConfig = (await cliConfig.vite(viteConfig, {\n command: 'build',\n isSsrBuild: true,\n mode: 'production',\n })) as InlineConfig\n} else if (isRecord(cliConfig?.vite)) {\n viteConfig = mergeConfig(viteConfig, cliConfig.vite)\n}\n\ndebug('Creating Vite server with config: %o', viteConfig)\n// Vite will build the files we give it - targetting Node.js instead of the browser.\n// We include the inject plugin in order to provide the stubs for the undefined global APIs.\nconst server = await createServer(viteConfig)\n\n// Bit of a hack, but seems necessary based on the `node-vite` binary implementation\nawait server.pluginContainer.buildStart({})\n\n// Load environment variables from `.env` files in the same way as Vite does.\n// Note that Sanity also provides environment variables through `process.env.*` for compat reasons,\n// and so we need to do the same here.\n// Load ALL env vars from .env files (not just studio-prefixed ones) so non-Sanity-prefixed\n// vars (e.g. NEXT_PUBLIC_*, VITE_*) are available via process.env at runtime.\n// The ??= on the next line prevents overwriting existing process.env values.\nconst env = loadEnv(server.config.mode, server.config.envDir, '')\nfor (const key in env) {\n process.env[key] ??= env[key]\n}\n\n// Now we're providing the glue that ensures node-specific loading and execution works.\nconst node = new ViteNodeServer(server)\n\n// Should make it easier to debug any crashes in the imported code…\ninstallSourcemapsSupport({\n getSourceMap: (source) => node.getSourceMap(source),\n})\n\nconst runner = new ViteNodeRunner({\n base: server.config.base,\n async fetchModule(id) {\n // Vite's SSR transform externalizes https:// imports, so Node's ESM loader\n // would reject them. We fetch the module over HTTP and run it through Vite's\n // SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*\n // format that ViteNodeRunner expects.\n if (isHttpsUrl(id)) {\n const {code: rawCode} = await fetchHttpModule(id)\n const result = await server.ssrTransform(rawCode, null, id)\n return {code: result?.code || rawCode}\n }\n return node.fetchModule(id)\n },\n resolveId(id, importer) {\n // Prevent vite-node from trying to resolve HTTP URLs through Node's resolver\n if (isHttpsUrl(id)) return {id}\n // Resolve any import from an HTTP-fetched module against the remote origin\n // (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)\n if (importer && isHttpsUrl(importer)) {\n return {id: new URL(id, importer).href}\n }\n return node.resolveId(id, importer)\n },\n root: server.config.root,\n})\n\n// Copied from `vite-node` - it appears that this applies the `define` config from\n// vite, but it also takes a surprisingly long time to execute. Not clear at this\n// point why this is, so we should investigate whether it's necessary or not.\nawait runner.executeId('/@vite/env')\n\nawait runner.executeId(workerScriptPath)\n"],"names":["isMainThread","createServer","loadEnv","mergeConfig","ViteNodeRunner","ViteNodeServer","installSourcemapsSupport","subdebug","getCliConfig","isNotFoundError","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","debug","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","cliConfig","err","console","warn","httpModuleCache","Map","fetchHttpModule","url","cached","get","code","response","fetch","signal","AbortSignal","timeout","ok","status","statusText","text","set","isHttpsUrl","id","startsWith","defaultViteConfig","build","target","configFile","define","Object","fromEntries","entries","map","key","value","JSON","stringify","envPrefix","esbuild","jsx","logLevel","optimizeDeps","include","undefined","noDiscovery","resolve","tsconfigPaths","root","server","hmr","watch","ssr","noExternal","viteConfig","vite","command","isSsrBuild","mode","pluginContainer","buildStart","config","envDir","node","getSourceMap","source","runner","base","fetchModule","rawCode","result","ssrTransform","resolveId","importer","URL","href","executeId"],"mappings":"AAA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MAAMC,OAAOY,MAAM,CAACb,IAAI;AAC1B;AAEA,kFAAkF;AAClF,iFAAiF;AACjF,6EAA6E;AAC7E,MAAMkB,OAAOU,SAAS,CAAC;AAEvB,MAAMV,OAAOU,SAAS,CAAC9E"}
1
+ {"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {isMainThread, parentPort} from 'node:worker_threads'\n\nimport {createServer, type InlineConfig, loadEnv, mergeConfig} from 'vite'\nimport {ViteNodeRunner} from 'vite-node/client'\nimport {ViteNodeServer} from 'vite-node/server'\nimport {installSourcemapsSupport} from 'vite-node/source-map'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {isNotFoundError} from '../../errors/NotFoundError.js'\nimport {getStudioEnvironmentVariables} from '../../util/environment/getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from '../../util/environment/setupBrowserStubs.js' // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB\nimport {isRecord} from '../../util/isRecord.js'\nimport {createOneShotWorkerLifecycle} from './studioWorkerLifecycle.js'\n\nif (isMainThread) {\n throw new Error('Should be child of thread, not the main thread')\n}\n\nconst rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH\nif (!rootPath) {\n throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable')\n}\n\nconst debug = subdebug('studio:worker')\n\nconst workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE\nif (!workerScriptPath) {\n throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable')\n}\n\nawait setupBrowserStubs()\n\nconst studioEnvVars = await getStudioEnvironmentVariables(rootPath)\n\n// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can\n// extend/modify the default vite configuration for the studio.\nlet cliConfig: CliConfig | undefined\ntry {\n cliConfig = await getCliConfig(rootPath)\n} catch (err) {\n debug('Failed to load CLI config: %o', err)\n if (!isNotFoundError(err)) {\n // eslint-disable-next-line no-console\n console.warn('[warn] Failed to load CLI config:', err)\n }\n}\n\n/**\n * Fetches and caches modules from HTTP/HTTPS URLs.\n * Vite's SSR transform treats `https://` imports as external and bypasses the plugin\n * resolve pipeline entirely, so we intercept them at the ViteNodeRunner level instead.\n */\nconst httpModuleCache = new Map<string, string>()\nasync function fetchHttpModule(url: string): Promise<{code: string}> {\n const cached = httpModuleCache.get(url)\n if (cached) return {code: cached}\n\n debug('Fetching HTTP import: %s', url)\n const response = await fetch(url, {signal: AbortSignal.timeout(30_000)})\n if (!response.ok) {\n throw new Error(`Failed to fetch module from ${url}: ${response.status} ${response.statusText}`)\n }\n\n const code = await response.text()\n httpModuleCache.set(url, code)\n return {code}\n}\n\nfunction isHttpsUrl(id: string): boolean {\n return id.startsWith('https://')\n}\n\nconst defaultViteConfig: InlineConfig = {\n build: {target: 'node'},\n configFile: false,\n // Inject environment variables as compile-time constants for Vite\n define: Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\n ),\n envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n esbuild: {\n jsx: 'automatic',\n },\n logLevel: 'error',\n optimizeDeps: {\n include: undefined,\n noDiscovery: true,\n },\n resolve: {\n // Resolve the studio's tsconfig `paths` natively (Vite 8+), replacing the\n // custom alias mapping and the need for a user-added `vite-tsconfig-paths`.\n tsconfigPaths: true,\n },\n root: rootPath,\n server: {\n hmr: false,\n watch: null,\n },\n ssr: {\n /**\n * We don't want to externalize any dependencies, we want everything to run thru vite.\n * Especially for CJS compatibility, etc.\n */\n noExternal: true,\n },\n}\n\n// Merge the CLI config's Vite config with the default Vite config\nlet viteConfig = defaultViteConfig\nif (typeof cliConfig?.vite === 'function') {\n viteConfig = (await cliConfig.vite(viteConfig, {\n command: 'build',\n isSsrBuild: true,\n mode: 'production',\n })) as InlineConfig\n} else if (isRecord(cliConfig?.vite)) {\n viteConfig = mergeConfig(viteConfig, cliConfig.vite)\n}\n\ndebug('Creating Vite server with config: %o', viteConfig)\n// Vite will build the files we give it - targetting Node.js instead of the browser.\n// We include the inject plugin in order to provide the stubs for the undefined global APIs.\nconst server = await createServer(viteConfig)\n\n// One-shot tasks (`studioWorkerTask`) resolve on their first message, and the\n// main thread historically terminate()d the worker right after — destroying\n// the worker's libuv loop while rolldown's native threads were still live.\n// The next `napi_call_threadsafe_function` then locked a destroyed mutex and\n// aborted the whole process (silent SIGABRT / exit code 134, reliably\n// reproduced on macOS). The lifecycle closes the Vite server BEFORE any\n// message reaches the main thread, and the main thread no longer terminates\n// one-shot workers at all (see `terminateOnSettle` in promisifyWorker).\nconst lifecycle =\n process.env.STUDIO_WORKER_ONE_SHOT === '1' && parentPort\n ? createOneShotWorkerLifecycle({\n closeServer: async () => {\n debug('Closing Vite server')\n await server.close()\n debug('Vite server closed')\n },\n onCloseError: (error) => debug('Failed to close Vite server: %o', error),\n parentPort,\n })\n : undefined\n\ntry {\n // Bit of a hack, but seems necessary based on the `node-vite` binary implementation\n await server.pluginContainer.buildStart({})\n\n // Load environment variables from `.env` files in the same way as Vite does.\n // Note that Sanity also provides environment variables through `process.env.*` for compat reasons,\n // and so we need to do the same here.\n // Load ALL env vars from .env files (not just studio-prefixed ones) so non-Sanity-prefixed\n // vars (e.g. NEXT_PUBLIC_*, VITE_*) are available via process.env at runtime.\n // The ??= on the next line prevents overwriting existing process.env values.\n const env = loadEnv(server.config.mode, server.config.envDir, '')\n for (const key in env) {\n process.env[key] ??= env[key]\n }\n\n // Now we're providing the glue that ensures node-specific loading and execution works.\n const node = new ViteNodeServer(server)\n\n // Should make it easier to debug any crashes in the imported code…\n installSourcemapsSupport({\n getSourceMap: (source) => node.getSourceMap(source),\n })\n\n const runner = new ViteNodeRunner({\n base: server.config.base,\n async fetchModule(id) {\n // Vite's SSR transform externalizes https:// imports, so Node's ESM loader\n // would reject them. We fetch the module over HTTP and run it through Vite's\n // SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*\n // format that ViteNodeRunner expects.\n if (isHttpsUrl(id)) {\n const {code: rawCode} = await fetchHttpModule(id)\n const result = await server.ssrTransform(rawCode, null, id)\n return {code: result?.code || rawCode}\n }\n return node.fetchModule(id)\n },\n resolveId(id, importer) {\n // Prevent vite-node from trying to resolve HTTP URLs through Node's resolver\n if (isHttpsUrl(id)) return {id}\n // Resolve any import from an HTTP-fetched module against the remote origin\n // (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)\n if (importer && isHttpsUrl(importer)) {\n return {id: new URL(id, importer).href}\n }\n return node.resolveId(id, importer)\n },\n root: server.config.root,\n })\n\n // Copied from `vite-node` - it appears that this applies the `define` config from\n // vite, but it also takes a surprisingly long time to execute. Not clear at this\n // point why this is, so we should investigate whether it's necessary or not.\n await runner.executeId('/@vite/env')\n\n await runner.executeId(workerScriptPath)\n} catch (error) {\n // Long-lived workers keep the original behavior: the error surfaces as a\n // Worker 'error' event.\n if (!lifecycle) {\n throw error\n }\n\n // One-shot workers close the server first and post a serialized error the\n // main thread rethrows, so the worker exits cleanly (code 0) and the real\n // error (e.g. a broken `sanity.config.ts`) isn't masked by a teardown abort.\n await lifecycle.postError(error)\n} finally {\n await lifecycle?.close()\n}\n"],"names":["isMainThread","parentPort","createServer","loadEnv","mergeConfig","ViteNodeRunner","ViteNodeServer","installSourcemapsSupport","subdebug","getCliConfig","isNotFoundError","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","createOneShotWorkerLifecycle","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","debug","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","cliConfig","err","console","warn","httpModuleCache","Map","fetchHttpModule","url","cached","get","code","response","fetch","signal","AbortSignal","timeout","ok","status","statusText","text","set","isHttpsUrl","id","startsWith","defaultViteConfig","build","target","configFile","define","Object","fromEntries","entries","map","key","value","JSON","stringify","envPrefix","esbuild","jsx","logLevel","optimizeDeps","include","undefined","noDiscovery","resolve","tsconfigPaths","root","server","hmr","watch","ssr","noExternal","viteConfig","vite","command","isSsrBuild","mode","lifecycle","STUDIO_WORKER_ONE_SHOT","closeServer","close","onCloseError","error","pluginContainer","buildStart","config","envDir","node","getSourceMap","source","runner","base","fetchModule","rawCode","result","ssrTransform","resolveId","importer","URL","href","executeId","postError"],"mappings":"AAAA,SAAQA,YAAY,EAAEC,UAAU,QAAO,sBAAqB;AAE5D,SAAQC,YAAY,EAAqBC,OAAO,EAAEC,WAAW,QAAO,OAAM;AAC1E,SAAQC,cAAc,QAAO,mBAAkB;AAC/C,SAAQC,cAAc,QAAO,mBAAkB;AAC/C,SAAQC,wBAAwB,QAAO,uBAAsB;AAE7D,SAAQC,QAAQ,QAAO,0BAAyB;AAChD,SAAQC,YAAY,QAAO,mCAAkC;AAE7D,SAAQC,eAAe,QAAO,gCAA+B;AAC7D,SAAQC,6BAA6B,QAAO,0DAAyD;AACrG,SAAQC,iBAAiB,QAAO,8CAA6C,CAAC,2EAA2E;AACzJ,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,4BAA4B,QAAO,6BAA4B;AAEvE,IAAId,cAAc;IAChB,MAAM,IAAIe,MAAM;AAClB;AAEA,MAAMC,WAAWC,QAAQC,GAAG,CAACC,8BAA8B;AAC3D,IAAI,CAACH,UAAU;IACb,MAAM,IAAID,MAAM;AAClB;AAEA,MAAMK,QAAQZ,SAAS;AAEvB,MAAMa,mBAAmBJ,QAAQC,GAAG,CAACI,uBAAuB;AAC5D,IAAI,CAACD,kBAAkB;IACrB,MAAM,IAAIN,MAAM;AAClB;AAEA,MAAMH;AAEN,MAAMW,gBAAgB,MAAMZ,8BAA8BK;AAE1D,oFAAoF;AACpF,+DAA+D;AAC/D,IAAIQ;AACJ,IAAI;IACFA,YAAY,MAAMf,aAAaO;AACjC,EAAE,OAAOS,KAAK;IACZL,MAAM,iCAAiCK;IACvC,IAAI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F,MAAMxB,OAAOkB,MAAM,CAACM,IAAI;QACxB,MAAMC,aAAYnD,EAAE;YAClB,2EAA2E;YAC3E,6EAA6E;YAC7E,wEAAwE;YACxE,sCAAsC;YACtC,IAAID,WAAWC,KAAK;gBAClB,MAAM,EAACZ,MAAMgE,OAAO,EAAC,GAAG,MAAMpE,gBAAgBgB;gBAC9C,MAAMqD,SAAS,MAAM3B,OAAO4B,YAAY,CAACF,SAAS,MAAMpD;gBACxD,OAAO;oBAACZ,MAAMiE,QAAQjE,QAAQgE;gBAAO;YACvC;YACA,OAAON,KAAKK,WAAW,CAACnD;QAC1B;QACAuD,WAAUvD,EAAE,EAAEwD,QAAQ;YACpB,6EAA6E;YAC7E,IAAIzD,WAAWC,KAAK,OAAO;gBAACA;YAAE;YAC9B,2EAA2E;YAC3E,kEAAkE;YAClE,IAAIwD,YAAYzD,WAAWyD,WAAW;gBACpC,OAAO;oBAACxD,IAAI,IAAIyD,IAAIzD,IAAIwD,UAAUE,IAAI;gBAAA;YACxC;YACA,OAAOZ,KAAKS,SAAS,CAACvD,IAAIwD;QAC5B;QACA/B,MAAMC,OAAOkB,MAAM,CAACnB,IAAI;IAC1B;IAEA,kFAAkF;IAClF,iFAAiF;IACjF,6EAA6E;IAC7E,MAAMwB,OAAOU,SAAS,CAAC;IAEvB,MAAMV,OAAOU,SAAS,CAACpF;AACzB,EAAE,OAAOkE,OAAO;IACd,yEAAyE;IACzE,wBAAwB;IACxB,IAAI,CAACL,WAAW;QACd,MAAMK;IACR;IAEA,0EAA0E;IAC1E,0EAA0E;IAC1E,6EAA6E;IAC7E,MAAML,UAAUwB,SAAS,CAACnB;AAC5B,SAAU;IACR,MAAML,WAAWG;AACnB"}
@@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url';
2
2
  import { Worker } from 'node:worker_threads';
3
3
  import { isRecord } from '../../util/isRecord.js';
4
4
  import { promisifyWorker } from '../../util/promisifyWorker.js';
5
+ import { deserializeStudioWorkerError, isStudioWorkerErrorMessage } from './studioWorkerLifecycle.js';
5
6
  /**
6
7
  * Executes a worker file in a Sanity Studio browser context.
7
8
  *
@@ -35,15 +36,30 @@ import { promisifyWorker } from '../../util/promisifyWorker.js';
35
36
  throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path');
36
37
  }
37
38
  const { studioRootPath, timeout, ...workerOptions } = options;
38
- return promisifyWorker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
39
+ const workerPromise = promisifyWorker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
39
40
  ...workerOptions,
40
41
  env: {
41
42
  ...isRecord(workerOptions.env) ? workerOptions.env : process.env,
43
+ // Tasks spawned here are one-shot: the loader closes its Vite
44
+ // (rolldown) server before any message reaches the main thread, so
45
+ // teardown can never race rolldown's native threads (SIGABRT on
46
+ // macOS). Long-lived workers (`createStudioWorker`) must NOT set it.
47
+ STUDIO_WORKER_ONE_SHOT: '1',
42
48
  STUDIO_WORKER_STUDIO_ROOT_PATH: studioRootPath,
43
49
  STUDIO_WORKER_TASK_FILE: normalizedFilePath
44
50
  },
51
+ // Never terminate() a worker hosting rolldown's native threads — let it
52
+ // exit on its own (it closes its server first) or tear down with the
53
+ // process.
54
+ terminateOnSettle: false,
45
55
  timeout
46
56
  });
57
+ return workerPromise.then((result)=>{
58
+ if (isStudioWorkerErrorMessage(result)) {
59
+ throw deserializeStudioWorkerError(result);
60
+ }
61
+ return result;
62
+ });
47
63
  }
48
64
  /**
49
65
  * Creates a new worker for a studio worker task.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/loaders/studio/studioWorkerTask.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\n\n/**\n * Options for the studio worker task\n *\n * @internal\n */\ninterface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n studioRootPath: string\n\n /** Optional timeout in milliseconds. If the worker does not respond within this time, it will be terminated and the promise rejected. */\n timeout?: number\n}\n\n/**\n * Executes a worker file in a Sanity Studio browser context.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function studioWorkerTask<T = unknown>(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<T> {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n const {studioRootPath, timeout, ...workerOptions} = options\n return promisifyWorker<T>(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...workerOptions,\n env: {\n ...(isRecord(workerOptions.env) ? workerOptions.env : process.env),\n STUDIO_WORKER_STUDIO_ROOT_PATH: studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n timeout,\n })\n}\n\n/**\n * Creates a new worker for a studio worker task.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function createStudioWorker(filePath: URL, options: StudioWorkerTaskOptions) {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...options,\n env: {\n ...(isRecord(options.env) ? options.env : process.env),\n STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n })\n}\n"],"names":["fileURLToPath","Worker","isRecord","promisifyWorker","studioWorkerTask","filePath","options","normalizedFilePath","test","Error","studioRootPath","timeout","workerOptions","URL","url","env","process","STUDIO_WORKER_STUDIO_ROOT_PATH","STUDIO_WORKER_TASK_FILE","createStudioWorker"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AACtC,SAAQC,MAAM,QAA2B,sBAAqB;AAG9D,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,gCAA+B;AAc7D;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,iBACdC,QAAa,EACbC,OAAgC;IAEhC,MAAMC,qBAAqBP,cAAcK;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,MAAM,EAACC,cAAc,EAAEC,OAAO,EAAE,GAAGC,eAAc,GAAGN;IACpD,OAAOH,gBAAmB,IAAIU,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAClF,GAAGF,aAAa;QAChBG,KAAK;YACH,GAAIb,SAASU,cAAcG,GAAG,IAAIH,cAAcG,GAAG,GAAGC,QAAQD,GAAG;YACjEE,gCAAgCP;YAChCQ,yBAAyBX;QAC3B;QACAI;IACF;AACF;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASQ,mBAAmBd,QAAa,EAAEC,OAAgC;IAChF,MAAMC,qBAAqBP,cAAcK;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,OAAO,IAAIR,OAAO,IAAIY,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAC1E,GAAGR,OAAO;QACVS,KAAK;YACH,GAAIb,SAASI,QAAQS,GAAG,IAAIT,QAAQS,GAAG,GAAGC,QAAQD,GAAG;YACrDE,gCAAgCX,QAAQI,cAAc;YACtDQ,yBAAyBX;QAC3B;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/loaders/studio/studioWorkerTask.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\nimport {\n deserializeStudioWorkerError,\n isStudioWorkerErrorMessage,\n type StudioWorkerErrorMessage,\n} from './studioWorkerLifecycle.js'\n\n/**\n * Options for the studio worker task\n *\n * @internal\n */\ninterface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n studioRootPath: string\n\n /** Optional timeout in milliseconds. If the worker does not respond within this time, the promise is rejected. */\n timeout?: number\n}\n\n/**\n * Executes a worker file in a Sanity Studio browser context.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function studioWorkerTask<T = unknown>(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<T> {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n const {studioRootPath, timeout, ...workerOptions} = options\n const workerPromise = promisifyWorker<StudioWorkerErrorMessage | T>(\n new URL('studioWorkerLoader.worker.js', import.meta.url),\n {\n ...workerOptions,\n env: {\n ...(isRecord(workerOptions.env) ? workerOptions.env : process.env),\n // Tasks spawned here are one-shot: the loader closes its Vite\n // (rolldown) server before any message reaches the main thread, so\n // teardown can never race rolldown's native threads (SIGABRT on\n // macOS). Long-lived workers (`createStudioWorker`) must NOT set it.\n STUDIO_WORKER_ONE_SHOT: '1',\n STUDIO_WORKER_STUDIO_ROOT_PATH: studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n // Never terminate() a worker hosting rolldown's native threads — let it\n // exit on its own (it closes its server first) or tear down with the\n // process.\n terminateOnSettle: false,\n timeout,\n },\n )\n\n return workerPromise.then((result) => {\n if (isStudioWorkerErrorMessage(result)) {\n throw deserializeStudioWorkerError(result)\n }\n\n return result\n })\n}\n\n/**\n * Creates a new worker for a studio worker task.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function createStudioWorker(filePath: URL, options: StudioWorkerTaskOptions) {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...options,\n env: {\n ...(isRecord(options.env) ? options.env : process.env),\n STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n })\n}\n"],"names":["fileURLToPath","Worker","isRecord","promisifyWorker","deserializeStudioWorkerError","isStudioWorkerErrorMessage","studioWorkerTask","filePath","options","normalizedFilePath","test","Error","studioRootPath","timeout","workerOptions","workerPromise","URL","url","env","process","STUDIO_WORKER_ONE_SHOT","STUDIO_WORKER_STUDIO_ROOT_PATH","STUDIO_WORKER_TASK_FILE","terminateOnSettle","then","result","createStudioWorker"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AACtC,SAAQC,MAAM,QAA2B,sBAAqB;AAG9D,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,gCAA+B;AAC7D,SACEC,4BAA4B,EAC5BC,0BAA0B,QAErB,6BAA4B;AAcnC;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,iBACdC,QAAa,EACbC,OAAgC;IAEhC,MAAMC,qBAAqBT,cAAcO;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,MAAM,EAACC,cAAc,EAAEC,OAAO,EAAE,GAAGC,eAAc,GAAGN;IACpD,MAAMO,gBAAgBZ,gBACpB,IAAIa,IAAI,gCAAgC,YAAYC,GAAG,GACvD;QACE,GAAGH,aAAa;QAChBI,KAAK;YACH,GAAIhB,SAASY,cAAcI,GAAG,IAAIJ,cAAcI,GAAG,GAAGC,QAAQD,GAAG;YACjE,8DAA8D;YAC9D,mEAAmE;YACnE,gEAAgE;YAChE,qEAAqE;YACrEE,wBAAwB;YACxBC,gCAAgCT;YAChCU,yBAAyBb;QAC3B;QACA,wEAAwE;QACxE,qEAAqE;QACrE,WAAW;QACXc,mBAAmB;QACnBV;IACF;IAGF,OAAOE,cAAcS,IAAI,CAAC,CAACC;QACzB,IAAIpB,2BAA2BoB,SAAS;YACtC,MAAMrB,6BAA6BqB;QACrC;QAEA,OAAOA;IACT;AACF;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,mBAAmBnB,QAAa,EAAEC,OAAgC;IAChF,MAAMC,qBAAqBT,cAAcO;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,OAAO,IAAIV,OAAO,IAAIe,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAC1E,GAAGT,OAAO;QACVU,KAAK;YACH,GAAIhB,SAASM,QAAQU,GAAG,IAAIV,QAAQU,GAAG,GAAGC,QAAQD,GAAG;YACrDG,gCAAgCb,QAAQI,cAAc;YACtDU,yBAAyBb;QAC3B;IACF;AACF"}
package/dist/manifest.js CHANGED
@@ -13,6 +13,7 @@ import { z } from 'zod/mini';
13
13
  group: z.optional(z.string()),
14
14
  icon: z.optional(z.string()),
15
15
  priority: z.optional(z.number()),
16
+ slug: z.optional(z.string()),
16
17
  title: z.optional(z.string()),
17
18
  version: z.string()
18
19
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/manifest.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n/**\n * Studio/app manifest schemas. They live in cli-core because more than one\n * package validates manifests: the CLI extracts and writes them, and the\n * workbench dev-server registry stores and rebroadcasts them. Keeping the\n * contract here lets both validate against the same schema without depending on\n * each other.\n */\n\n/**\n * Core-app application manifest. Mirrors the workbench's\n * `CoreAppUserApplicationManifest` schema. Strictly validated via zod since the\n * CLI produces the payload in full.\n */\nexport const coreAppManifestSchema = z.object({\n group: z.optional(z.string()),\n icon: z.optional(z.string()),\n priority: z.optional(z.number()),\n title: z.optional(z.string()),\n version: z.string(),\n})\n\nexport type CoreAppManifest = z.infer<typeof coreAppManifestSchema>\n\n/**\n * Studio application manifest (serialized `create-manifest.json`). Kept loose so\n * the CLI isn't coupled to the workbench's evolving client-side schema — the\n * workbench consumer is authoritative on the inner shape. See its\n * `ClientManifest` for the fields clients expect.\n */\nexport const studioManifestSchema = z.record(z.string(), z.unknown())\n\nexport type StudioManifest = z.infer<typeof studioManifestSchema>\n"],"names":["z","coreAppManifestSchema","object","group","optional","string","icon","priority","number","title","version","studioManifestSchema","record","unknown"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B;;;;;;CAMC,GAED;;;;CAIC,GACD,OAAO,MAAMC,wBAAwBD,EAAEE,MAAM,CAAC;IAC5CC,OAAOH,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IAC1BC,MAAMN,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IACzBE,UAAUP,EAAEI,QAAQ,CAACJ,EAAEQ,MAAM;IAC7BC,OAAOT,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IAC1BK,SAASV,EAAEK,MAAM;AACnB,GAAE;AAIF;;;;;CAKC,GACD,OAAO,MAAMM,uBAAuBX,EAAEY,MAAM,CAACZ,EAAEK,MAAM,IAAIL,EAAEa,OAAO,IAAG"}
1
+ {"version":3,"sources":["../src/manifest.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n/**\n * Studio/app manifest schemas. They live in cli-core because more than one\n * package validates manifests: the CLI extracts and writes them, and the\n * workbench dev-server registry stores and rebroadcasts them. Keeping the\n * contract here lets both validate against the same schema without depending on\n * each other.\n */\n\n/**\n * Core-app application manifest. Mirrors the workbench's\n * `CoreAppUserApplicationManifest` schema. Strictly validated via zod since the\n * CLI produces the payload in full.\n */\nexport const coreAppManifestSchema = z.object({\n group: z.optional(z.string()),\n icon: z.optional(z.string()),\n priority: z.optional(z.number()),\n slug: z.optional(z.string()),\n title: z.optional(z.string()),\n version: z.string(),\n})\n\nexport type CoreAppManifest = z.infer<typeof coreAppManifestSchema>\n\n/**\n * Studio application manifest (serialized `create-manifest.json`). Kept loose so\n * the CLI isn't coupled to the workbench's evolving client-side schema — the\n * workbench consumer is authoritative on the inner shape. See its\n * `ClientManifest` for the fields clients expect.\n */\nexport const studioManifestSchema = z.record(z.string(), z.unknown())\n\nexport type StudioManifest = z.infer<typeof studioManifestSchema>\n"],"names":["z","coreAppManifestSchema","object","group","optional","string","icon","priority","number","slug","title","version","studioManifestSchema","record","unknown"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B;;;;;;CAMC,GAED;;;;CAIC,GACD,OAAO,MAAMC,wBAAwBD,EAAEE,MAAM,CAAC;IAC5CC,OAAOH,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IAC1BC,MAAMN,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IACzBE,UAAUP,EAAEI,QAAQ,CAACJ,EAAEQ,MAAM;IAC7BC,MAAMT,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IACzBK,OAAOV,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IAC1BM,SAASX,EAAEK,MAAM;AACnB,GAAE;AAIF;;;;;CAKC,GACD,OAAO,MAAMO,uBAAuBZ,EAAEa,MAAM,CAACb,EAAEK,MAAM,IAAIL,EAAEc,OAAO,IAAG"}
@@ -0,0 +1,6 @@
1
+ import { getSanityUrl } from './getSanityUrl.js';
2
+ export function getCoreAppUrl(organizationId, appId) {
3
+ return getSanityUrl(`/@${organizationId}/application/${appId}`);
4
+ }
5
+
6
+ //# sourceMappingURL=getCoreAppUrl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/getCoreAppUrl.ts"],"sourcesContent":["import {getSanityUrl} from './getSanityUrl.js'\n\nexport function getCoreAppUrl(organizationId: string, appId: string): string {\n return getSanityUrl(`/@${organizationId}/application/${appId}`)\n}\n"],"names":["getSanityUrl","getCoreAppUrl","organizationId","appId"],"mappings":"AAAA,SAAQA,YAAY,QAAO,oBAAmB;AAE9C,OAAO,SAASC,cAAcC,cAAsB,EAAEC,KAAa;IACjE,OAAOH,aAAa,CAAC,EAAE,EAAEE,eAAe,aAAa,EAAEC,OAAO;AAChE"}
@@ -1,11 +1,15 @@
1
1
  import { Worker } from 'node:worker_threads';
2
2
  import { subdebug } from '../_exports/debug.js';
3
3
  const debug = subdebug('promisifyWorker');
4
+ function onDetachedWorkerError(err) {
5
+ debug(`Detached worker error: ${err.message}`, err);
6
+ }
4
7
  /**
5
8
  * Creates a Node.js Worker from the given file path and options, and wraps it
6
9
  * in a Promise that resolves with the first message the worker sends, and
7
10
  * rejects on error, message deserialization failure, or non-zero exit code.
8
- * The worker is terminated after a message or error is received.
11
+ * By default, the worker is terminated after a message or error is received.
12
+ * Callers can instead unref it and allow natural process teardown.
9
13
  *
10
14
  * @param filePath - URL to the worker file
11
15
  * @param options - Options to pass to the Worker constructor
@@ -13,7 +17,7 @@ const debug = subdebug('promisifyWorker');
13
17
  * @throws If the worker emits an error, a message deserialization error, or exits with a non-zero code
14
18
  * @internal
15
19
  */ export function promisifyWorker(filePath, options) {
16
- const { timeout, ...workerOptions } = options ?? {};
20
+ const { terminateOnSettle = true, timeout, ...workerOptions } = options ?? {};
17
21
  const worker = new Worker(filePath, workerOptions);
18
22
  const fileName = `[${filePath.pathname}]`;
19
23
  return new Promise((resolve, reject)=>{
@@ -23,8 +27,7 @@ const debug = subdebug('promisifyWorker');
23
27
  timeoutId = setTimeout(()=>{
24
28
  settled = true;
25
29
  reject(new Error(`Worker timed out after ${timeout}ms`));
26
- void worker.terminate();
27
- worker.removeAllListeners();
30
+ cleanup(false);
28
31
  }, timeout);
29
32
  }
30
33
  worker.addListener('error', function onWorkerError(err) {
@@ -62,9 +65,21 @@ const debug = subdebug('promisifyWorker');
62
65
  resolve(message);
63
66
  cleanup();
64
67
  });
65
- function cleanup() {
66
- setImmediate(()=>worker.terminate());
68
+ function cleanup(deferTermination = true) {
69
+ if (terminateOnSettle) {
70
+ if (deferTermination) {
71
+ setImmediate(()=>void worker.terminate());
72
+ } else {
73
+ void worker.terminate();
74
+ }
75
+ worker.removeAllListeners();
76
+ return;
77
+ }
78
+ worker.unref();
67
79
  worker.removeAllListeners();
80
+ // A detached worker may still fail before process teardown. Keep an error
81
+ // listener so EventEmitter does not rethrow it in the parent process.
82
+ worker.addListener('error', onDetachedWorkerError);
68
83
  }
69
84
  });
70
85
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/promisifyWorker.ts"],"sourcesContent":["import {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {subdebug} from '../_exports/debug.js'\n\nconst debug = subdebug('promisifyWorker')\n\ninterface PromisifyWorkerOptions extends WorkerOptions {\n /** Optional timeout in milliseconds. If the worker does not respond within this time, it will be terminated and the promise rejected. */\n timeout?: number\n}\n\n/**\n * Creates a Node.js Worker from the given file path and options, and wraps it\n * in a Promise that resolves with the first message the worker sends, and\n * rejects on error, message deserialization failure, or non-zero exit code.\n * The worker is terminated after a message or error is received.\n *\n * @param filePath - URL to the worker file\n * @param options - Options to pass to the Worker constructor\n * @returns A promise that resolves with the first message from the worker\n * @throws If the worker emits an error, a message deserialization error, or exits with a non-zero code\n * @internal\n */\nexport function promisifyWorker<T = unknown>(\n filePath: URL,\n options?: PromisifyWorkerOptions,\n): Promise<T> {\n const {timeout, ...workerOptions} = options ?? {}\n const worker = new Worker(filePath, workerOptions)\n\n const fileName = `[${filePath.pathname}]`\n\n return new Promise<T>((resolve, reject) => {\n let settled = false\n let timeoutId: ReturnType<typeof setTimeout> | undefined\n\n if (timeout !== undefined && timeout > 0) {\n timeoutId = setTimeout(() => {\n settled = true\n reject(new Error(`Worker timed out after ${timeout}ms`))\n void worker.terminate()\n worker.removeAllListeners()\n }, timeout)\n }\n\n worker.addListener('error', function onWorkerError(err) {\n settled = true\n clearTimeout(timeoutId)\n debug(`Worker error: ${err.message}`, err)\n reject(new Error(`Worker error: ${err.message}`, {cause: err}))\n cleanup()\n })\n // No cleanup() here — the worker is already dead after exiting,\n // so there is nothing to terminate or remove listeners from.\n worker.addListener('exit', function onWorkerExit(code) {\n clearTimeout(timeoutId)\n if (code > 0) {\n debug(`${fileName} exited with code ${code}`)\n reject(new Error(`Worker exited with code ${code}`))\n } else if (!settled) {\n debug(`${fileName} exited with code 0 without sending a message`)\n reject(new Error('Worker exited without sending a message'))\n }\n })\n worker.addListener('messageerror', function onWorkerMessageError(err) {\n settled = true\n clearTimeout(timeoutId)\n debug(`${fileName} message error: ${err.message}`, err)\n reject(new Error(`Failed to deserialize worker message: ${err}`))\n cleanup()\n })\n worker.addListener('message', function onWorkerMessage(message) {\n settled = true\n clearTimeout(timeoutId)\n debug(`${fileName} message %o`, message)\n resolve(message)\n cleanup()\n })\n\n function cleanup() {\n setImmediate(() => worker.terminate())\n worker.removeAllListeners()\n }\n })\n}\n"],"names":["Worker","subdebug","debug","promisifyWorker","filePath","options","timeout","workerOptions","worker","fileName","pathname","Promise","resolve","reject","settled","timeoutId","undefined","setTimeout","Error","terminate","removeAllListeners","addListener","onWorkerError","err","clearTimeout","message","cause","cleanup","onWorkerExit","code","onWorkerMessageError","onWorkerMessage","setImmediate"],"mappings":"AAAA,SAAQA,MAAM,QAA2B,sBAAqB;AAE9D,SAAQC,QAAQ,QAAO,uBAAsB;AAE7C,MAAMC,QAAQD,SAAS;AAOvB;;;;;;;;;;;CAWC,GACD,OAAO,SAASE,gBACdC,QAAa,EACbC,OAAgC;IAEhC,MAAM,EAACC,OAAO,EAAE,GAAGC,eAAc,GAAGF,WAAW,CAAC;IAChD,MAAMG,SAAS,IAAIR,OAAOI,UAAUG;IAEpC,MAAME,WAAW,CAAC,CAAC,EAAEL,SAASM,QAAQ,CAAC,CAAC,CAAC;IAEzC,OAAO,IAAIC,QAAW,CAACC,SAASC;QAC9B,IAAIC,UAAU;QACd,IAAIC;QAEJ,IAAIT,YAAYU,aAAaV,UAAU,GAAG;YACxCS,YAAYE,WAAW;gBACrBH,UAAU;gBACVD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type WorkerOptions} from 'node:worker_threads'\n\nimport {subdebug} from '../_exports/debug.js'\n\nconst debug = subdebug('promisifyWorker')\n\nfunction onDetachedWorkerError(err: Error) {\n debug(`Detached worker error: ${err.message}`, err)\n}\n\ninterface PromisifyWorkerOptions extends WorkerOptions {\n /**\n * Whether to forcibly terminate the worker after settling. Disable this for\n * workers that host native addons (e.g. rolldown via Vite 8) whose threads\n * must tear down with the process: terminating such a worker while native\n * threads are live can abort the whole process with a silent SIGABRT. A\n * disabled worker is unrefed and may continue running until the process\n * exits, including after a timeout.\n */\n terminateOnSettle?: boolean\n\n /** Optional timeout in milliseconds. If the worker does not respond within this time, the promise is rejected. */\n timeout?: number\n}\n\n/**\n * Creates a Node.js Worker from the given file path and options, and wraps it\n * in a Promise that resolves with the first message the worker sends, and\n * rejects on error, message deserialization failure, or non-zero exit code.\n * By default, the worker is terminated after a message or error is received.\n * Callers can instead unref it and allow natural process teardown.\n *\n * @param filePath - URL to the worker file\n * @param options - Options to pass to the Worker constructor\n * @returns A promise that resolves with the first message from the worker\n * @throws If the worker emits an error, a message deserialization error, or exits with a non-zero code\n * @internal\n */\nexport function promisifyWorker<T = unknown>(\n filePath: URL,\n options?: PromisifyWorkerOptions,\n): Promise<T> {\n const {terminateOnSettle = true, timeout, ...workerOptions} = options ?? {}\n const worker = new Worker(filePath, workerOptions)\n\n const fileName = `[${filePath.pathname}]`\n\n return new Promise<T>((resolve, reject) => {\n let settled = false\n let timeoutId: ReturnType<typeof setTimeout> | undefined\n\n if (timeout !== undefined && timeout > 0) {\n timeoutId = setTimeout(() => {\n settled = true\n reject(new Error(`Worker timed out after ${timeout}ms`))\n cleanup(false)\n }, timeout)\n }\n\n worker.addListener('error', function onWorkerError(err) {\n settled = true\n clearTimeout(timeoutId)\n debug(`Worker error: ${err.message}`, err)\n reject(new Error(`Worker error: ${err.message}`, {cause: err}))\n cleanup()\n })\n // No cleanup() here — the worker is already dead after exiting,\n // so there is nothing to terminate or remove listeners from.\n worker.addListener('exit', function onWorkerExit(code) {\n clearTimeout(timeoutId)\n if (code > 0) {\n debug(`${fileName} exited with code ${code}`)\n reject(new Error(`Worker exited with code ${code}`))\n } else if (!settled) {\n debug(`${fileName} exited with code 0 without sending a message`)\n reject(new Error('Worker exited without sending a message'))\n }\n })\n worker.addListener('messageerror', function onWorkerMessageError(err) {\n settled = true\n clearTimeout(timeoutId)\n debug(`${fileName} message error: ${err.message}`, err)\n reject(new Error(`Failed to deserialize worker message: ${err}`))\n cleanup()\n })\n worker.addListener('message', function onWorkerMessage(message) {\n settled = true\n clearTimeout(timeoutId)\n debug(`${fileName} message %o`, message)\n resolve(message)\n cleanup()\n })\n\n function cleanup(deferTermination = true) {\n if (terminateOnSettle) {\n if (deferTermination) {\n setImmediate(() => void worker.terminate())\n } else {\n void worker.terminate()\n }\n worker.removeAllListeners()\n return\n }\n\n worker.unref()\n worker.removeAllListeners()\n // A detached worker may still fail before process teardown. Keep an error\n // listener so EventEmitter does not rethrow it in the parent process.\n worker.addListener('error', onDetachedWorkerError)\n }\n })\n}\n"],"names":["Worker","subdebug","debug","onDetachedWorkerError","err","message","promisifyWorker","filePath","options","terminateOnSettle","timeout","workerOptions","worker","fileName","pathname","Promise","resolve","reject","settled","timeoutId","undefined","setTimeout","Error","cleanup","addListener","onWorkerError","clearTimeout","cause","onWorkerExit","code","onWorkerMessageError","onWorkerMessage","deferTermination","setImmediate","terminate","removeAllListeners","unref"],"mappings":"AAAA,SAAQA,MAAM,QAA2B,sBAAqB;AAE9D,SAAQC,QAAQ,QAAO,uBAAsB;AAE7C,MAAMC,QAAQD,SAAS;AAEvB,SAASE,sBAAsBC,GAAU;IACvCF,MAAM,CAAC,uBAAuB,EAAEE,IAAIC,OAAO,EAAE,EAAED;AACjD;AAiBA;;;;;;;;;;;;CAYC,GACD,OAAO,SAASE,gBACdC,QAAa,EACbC,OAAgC;IAEhC,MAAM,EAACC,oBAAoB,IAAI,EAAEC,OAAO,EAAE,GAAGC,eAAc,GAAGH,WAA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AC5Da,UAAU;YACVQ,aAAaP;YACbjB,MAAM,GAAGW,SAAS,WAAW,CAAC,EAAER;YAChCW,QAAQX;YACRkB;QACF;QAEA,SAASA,QAAQS,mBAAmB,IAAI;YACtC,IAAIvB,mBAAmB;gBACrB,IAAIuB,kBAAkB;oBACpBC,aAAa,IAAM,KAAKrB,OAAOsB,SAAS;gBAC1C,OAAO;oBACL,KAAKtB,OAAOsB,SAAS;gBACvB;gBACAtB,OAAOuB,kBAAkB;gBACzB;YACF;YAEAvB,OAAOwB,KAAK;YACZxB,OAAOuB,kBAAkB;YACzB,0EAA0E;YAC1E,sEAAsE;YACtEvB,OAAOY,WAAW,CAAC,SAASrB;QAC9B;IACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-core",
3
- "version": "2.3.0",
3
+ "version": "2.5.0",
4
4
  "description": "Sanity CLI core package",
5
5
  "keywords": [
6
6
  "cli",
@@ -77,6 +77,10 @@
77
77
  "source": "./src/_exports/types.ts",
78
78
  "default": "./dist/_exports/types.js"
79
79
  },
80
+ "./undeploy": {
81
+ "source": "./src/_exports/undeploy.ts",
82
+ "default": "./dist/_exports/undeploy.js"
83
+ },
80
84
  "./util": {
81
85
  "source": "./src/_exports/util.ts",
82
86
  "default": "./dist/_exports/util.js"
@@ -100,8 +104,8 @@
100
104
  },
101
105
  "dependencies": {
102
106
  "@inquirer/prompts": "^8.5.2",
103
- "@oclif/core": "^4.11.7",
104
- "@sanity/client": "^7.23.0",
107
+ "@oclif/core": "^4.11.14",
108
+ "@sanity/client": "^7.23.2",
105
109
  "boxen": "^8.0.1",
106
110
  "debug": "^4.4.3",
107
111
  "empathic": "^2.0.1",
@@ -114,29 +118,29 @@
114
118
  "log-symbols": "^7.0.1",
115
119
  "ora": "^9.0.0",
116
120
  "rxjs": "^7.8.2",
117
- "tsx": "^4.22.4",
118
- "vite": "^8.1.3",
121
+ "tsx": "^4.23.1",
122
+ "vite": "^8.1.5",
119
123
  "vite-node": "^6.0.0",
120
124
  "zod": "^4.4.3"
121
125
  },
122
126
  "devDependencies": {
123
127
  "@eslint/compat": "^2.1.0",
124
- "@sanity/pkg-utils": "^10.8.1",
128
+ "@sanity/pkg-utils": "^11.0.9",
125
129
  "@sanity/telemetry": "^1.1.0",
126
130
  "@swc/cli": "^0.8.1",
127
- "@swc/core": "^1.15.41",
131
+ "@swc/core": "^1.15.43",
128
132
  "@types/debug": "^4.1.13",
129
133
  "@types/jsdom": "^28.0.3",
130
134
  "@types/node": "^22.20.0",
131
135
  "babel-plugin-react-compiler": "^1.0.0",
132
- "eslint": "^10.4.1",
136
+ "eslint": "^10.7.0",
133
137
  "publint": "^0.3.21",
134
- "sanity": "^6.1.0",
135
- "typescript": "^5.9.3",
136
- "vitest": "^4.1.9",
138
+ "sanity": "^6.5.0",
139
+ "typescript": "^6.0.3",
140
+ "vitest": "^4.1.10",
137
141
  "@repo/package.config": "0.0.1",
138
142
  "@repo/tsconfig": "3.70.0",
139
- "@sanity/eslint-config-cli": "1.1.2"
143
+ "@sanity/eslint-config-cli": "1.1.3"
140
144
  },
141
145
  "peerDependencies": {
142
146
  "babel-plugin-react-compiler": "*"
@@ -150,7 +154,7 @@
150
154
  "node": ">=22.12"
151
155
  },
152
156
  "scripts": {
153
- "build": "swc --delete-dir-on-start --strip-leading-paths --out-dir dist/ src --ignore '**/*.test.ts' --ignore '**/__tests__/**'",
157
+ "build": "swc --delete-dir-on-start --strip-leading-paths --out-dir dist/ src",
154
158
  "build:types": "pkg-utils build --emitDeclarationOnly",
155
159
  "check:types": "tsc --noEmit",
156
160
  "lint": "eslint .",