@sanity/cli-core 3.8.0 → 3.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/studio/getStudioWorkspaces.js +8 -2
- package/dist/config/studio/getStudioWorkspaces.js.map +1 -1
- package/dist/loaders/studio/studioModuleEvaluator.js +5 -11
- package/dist/loaders/studio/studioModuleEvaluator.js.map +1 -1
- package/dist/loaders/studio/studioWorkerLoader.worker.js +1 -1
- package/dist/loaders/studio/studioWorkerLoader.worker.js.map +1 -1
- package/dist/util/environment/mockBrowserEnvironment.js +1 -2
- package/dist/util/environment/mockBrowserEnvironment.js.map +1 -1
- package/dist/util/environment/setupBrowserStubs.js +4 -1
- package/dist/util/environment/setupBrowserStubs.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { stat } from 'node:fs/promises';
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
3
|
import { isMainThread } from 'node:worker_threads';
|
|
4
|
-
import { firstValueFrom, of } from 'rxjs';
|
|
5
4
|
import { subdebug } from '../../_exports/debug.js';
|
|
6
5
|
import { doImport } from '../../util/doImport.js';
|
|
7
|
-
import { getEmptyAuth } from '../../util/getEmptyAuth.js';
|
|
8
6
|
import { resolveLocalPackage } from '../../util/resolveLocalPackage.js';
|
|
9
7
|
import { findStudioConfigPath } from '../util/findStudioConfigPath.js';
|
|
10
8
|
import { isStudioConfig } from './isStudioConfig.js';
|
|
@@ -50,6 +48,14 @@ const debug = subdebug('worker:getStudioWorkspaces');
|
|
|
50
48
|
name: config.name || 'default'
|
|
51
49
|
}
|
|
52
50
|
];
|
|
51
|
+
// Imported lazily: rxjs and `@sanity/client` are only needed here, but this
|
|
52
|
+
// module is reachable from the `@sanity/cli-core` barrel that every command loads.
|
|
53
|
+
const [{ firstValueFrom, of }, { getEmptyAuth }] = await Promise.all([
|
|
54
|
+
// eslint-disable-next-line no-restricted-syntax -- package import, not a file path
|
|
55
|
+
import('rxjs'),
|
|
56
|
+
// eslint-disable-next-line no-restricted-syntax -- static relative import, not a user file path
|
|
57
|
+
import('../../util/getEmptyAuth.js')
|
|
58
|
+
]);
|
|
53
59
|
const emptyAuth = {
|
|
54
60
|
state: of(getEmptyAuth())
|
|
55
61
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/studio/getStudioWorkspaces.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {dirname} from 'node:path'\nimport {isMainThread} from 'node:worker_threads'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/config/studio/getStudioWorkspaces.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {dirname} from 'node:path'\nimport {isMainThread} from 'node:worker_threads'\n\nimport {type Workspace} from 'sanity'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {doImport} from '../../util/doImport.js'\nimport {resolveLocalPackage} from '../../util/resolveLocalPackage.js'\nimport {findStudioConfigPath} from '../util/findStudioConfigPath.js'\nimport {isStudioConfig} from './isStudioConfig.js'\n\nconst debug = subdebug('worker:getStudioWorkspaces')\n\n/**\n * Resolves the workspaces from the studio config.\n *\n * NOTE: This function should only be called from a worker thread.\n *\n * @param configPath - The path to the studio config\n * @returns The workspaces\n * @internal\n */\nexport async function getStudioWorkspaces(configPath: string): Promise<Workspace[]> {\n if (isMainThread) {\n throw new Error('getStudioWorkspaces should only be called from a worker thread')\n }\n const isDirectory = (await stat(configPath)).isDirectory()\n if (isDirectory) {\n configPath = await findStudioConfigPath(configPath)\n }\n debug('Finding studio config path %s', configPath)\n let config = await doImport(configPath)\n\n debug('Imported config %o', config)\n if (!isStudioConfig(config)) {\n if (!('default' in config) || !isStudioConfig(config.default)) {\n debug('Invalid studio config format in \"%s\"', configPath)\n throw new TypeError(`Invalid studio config format in \"${configPath}\"`)\n }\n\n config = config.default\n }\n\n const workDir = dirname(configPath)\n debug('Work dir %s', workDir)\n const {resolveConfig} = await resolveLocalPackage<typeof import('sanity')>('sanity', workDir)\n if (typeof resolveConfig !== 'function') {\n throw new TypeError('Expected `resolveConfig` from `sanity` to be a function')\n }\n\n // We will also want to stub out some configuration - we don't need to resolve the\n // users' logged in state, for instance - so let's disable the auth implementation.\n const rawWorkspaces = Array.isArray(config)\n ? config\n : [{...config, basePath: config.basePath || '/', name: config.name || 'default'}]\n\n // Imported lazily: rxjs and `@sanity/client` are only needed here, but this\n // module is reachable from the `@sanity/cli-core` barrel that every command loads.\n const [{firstValueFrom, of}, {getEmptyAuth}] = await Promise.all([\n // eslint-disable-next-line no-restricted-syntax -- package import, not a file path\n import('rxjs'),\n // eslint-disable-next-line no-restricted-syntax -- static relative import, not a user file path\n import('../../util/getEmptyAuth.js'),\n ])\n const emptyAuth = {state: of(getEmptyAuth())}\n\n const unauthedWorkspaces = rawWorkspaces.map((workspace) => ({\n ...workspace,\n auth: emptyAuth,\n }))\n\n debug('Unauthed workspaces %o', unauthedWorkspaces)\n\n return firstValueFrom(resolveConfig(unauthedWorkspaces))\n}\n"],"names":["stat","dirname","isMainThread","subdebug","doImport","resolveLocalPackage","findStudioConfigPath","isStudioConfig","debug","getStudioWorkspaces","configPath","Error","isDirectory","config","default","TypeError","workDir","resolveConfig","rawWorkspaces","Array","isArray","basePath","name","firstValueFrom","of","getEmptyAuth","Promise","all","emptyAuth","state","unauthedWorkspaces","map","workspace","auth"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,OAAO,QAAO,YAAW;AACjC,SAAQC,YAAY,QAAO,sBAAqB;AAIhD,SAAQC,QAAQ,QAAO,0BAAyB;AAChD,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,oBAAoB,QAAO,kCAAiC;AACpE,SAAQC,cAAc,QAAO,sBAAqB;AAElD,MAAMC,QAAQL,SAAS;AAEvB;;;;;;;;CAQC,GACD,OAAO,eAAeM,oBAAoBC,UAAkB;IAC1D,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;IAEhC,OAAOP,eAAeN,cAAca;AACtC"}
|
|
@@ -2,9 +2,6 @@ import { createRequire } from 'node:module';
|
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
3
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
4
4
|
import { ESModulesEvaluator, ssrModuleExportsKey } from 'vite/module-runner';
|
|
5
|
-
function isCommonJsCode(code) {
|
|
6
|
-
return /\bmodule\.exports\b/.test(code) || /\bexports\.[a-zA-Z_$]/.test(code) || /(?:^|[;\n])\s*exports\s=/.test(code) || /(?:^|\n|\s)require\s*\(/.test(code);
|
|
7
|
-
}
|
|
8
5
|
function isPrimitive(value) {
|
|
9
6
|
return !value || typeof value !== 'object' && typeof value !== 'function';
|
|
10
7
|
}
|
|
@@ -41,9 +38,6 @@ function exportAll(exports, sourceModule) {
|
|
|
41
38
|
return this.esmEvaluator.runExternalModule(filepath);
|
|
42
39
|
}
|
|
43
40
|
runInlinedModule(context, code, module) {
|
|
44
|
-
if (!isCommonJsCode(code)) {
|
|
45
|
-
return this.esmEvaluator.runInlinedModule(context, code, module);
|
|
46
|
-
}
|
|
47
41
|
return this.runCommonJsModule(context, code, module);
|
|
48
42
|
}
|
|
49
43
|
async runCommonJsModule(context, code, module) {
|
|
@@ -61,7 +55,9 @@ function exportAll(exports, sourceModule) {
|
|
|
61
55
|
},
|
|
62
56
|
getPrototypeOf: ()=>Object.prototype,
|
|
63
57
|
set: (_, property, value)=>{
|
|
64
|
-
|
|
58
|
+
// Keep the module default when CommonJS aliases it back to `module.exports`.
|
|
59
|
+
if (property === 'default' && cjsExports !== value) {
|
|
60
|
+
exportAll(exports, value);
|
|
65
61
|
exports.default = value;
|
|
66
62
|
return true;
|
|
67
63
|
}
|
|
@@ -72,7 +68,7 @@ function exportAll(exports, sourceModule) {
|
|
|
72
68
|
defineExport(exports, String(property), ()=>{});
|
|
73
69
|
return true;
|
|
74
70
|
}
|
|
75
|
-
if (!isPrimitive(exports.default)
|
|
71
|
+
if (!isPrimitive(exports.default)) {
|
|
76
72
|
;
|
|
77
73
|
exports.default[String(property)] = value;
|
|
78
74
|
}
|
|
@@ -104,11 +100,9 @@ function exportAll(exports, sourceModule) {
|
|
|
104
100
|
if (normalizedCode[0] === '#') {
|
|
105
101
|
normalizedCode = normalizedCode.replace(/^#!.*/, (line)=>' '.repeat(line.length));
|
|
106
102
|
}
|
|
107
|
-
// Use AsyncFunction (same as ESModulesEvaluator) so the shared `startOffset`
|
|
108
|
-
// ModuleRunner applies to inlined sourcemaps matches this wrapper's padding.
|
|
109
103
|
const AsyncFunction = (async function() {}).constructor;
|
|
110
104
|
const parameterNames = Object.keys(cjsContext);
|
|
111
|
-
const runner = new AsyncFunction(...parameterNames, `"use strict"
|
|
105
|
+
const runner = new AsyncFunction(...parameterNames, `"use strict";{\n${normalizedCode}\n}`);
|
|
112
106
|
await runner(...parameterNames.map((name)=>cjsContext[name]));
|
|
113
107
|
}
|
|
114
108
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/studio/studioModuleEvaluator.ts"],"sourcesContent":["import {createRequire} from 'node:module'\nimport {dirname} from 'node:path'\nimport {fileURLToPath, pathToFileURL} from 'node:url'\n\nimport {\n ESModulesEvaluator,\n type EvaluatedModuleNode,\n type ModuleEvaluator,\n type ModuleRunnerContext,\n ssrModuleExportsKey,\n} from 'vite/module-runner'\n\nfunction
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioModuleEvaluator.ts"],"sourcesContent":["import {createRequire} from 'node:module'\nimport {dirname} from 'node:path'\nimport {fileURLToPath, pathToFileURL} from 'node:url'\n\nimport {\n ESModulesEvaluator,\n type EvaluatedModuleNode,\n type ModuleEvaluator,\n type ModuleRunnerContext,\n ssrModuleExportsKey,\n} from 'vite/module-runner'\n\nfunction isPrimitive(value: unknown): boolean {\n return !value || (typeof value !== 'object' && typeof value !== 'function')\n}\n\nfunction defineExport(exports: Record<string, unknown>, key: string, getter: () => unknown) {\n Object.defineProperty(exports, key, {\n configurable: true,\n enumerable: true,\n get: getter,\n })\n}\n\nfunction exportAll(exports: Record<string, unknown>, sourceModule: unknown) {\n if (exports === sourceModule) return\n if (isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise) {\n return\n }\n\n for (const key in sourceModule as Record<string, unknown>) {\n if (key !== 'default' && !(key in exports)) {\n try {\n defineExport(exports, key, () => (sourceModule as Record<string, unknown>)[key])\n } catch {\n // ignore non-configurable exports\n }\n }\n }\n}\n\n/**\n * Module evaluator that can execute raw CommonJS modules in addition to\n * Vite's SSR-transformed ESM. Matches vite-node's CJS execution behavior,\n * which ModuleRunner's default ESModulesEvaluator does not support.\n */\nexport class StudioModuleEvaluator implements ModuleEvaluator {\n private readonly esmEvaluator = new ESModulesEvaluator()\n readonly startOffset = this.esmEvaluator.startOffset\n\n runExternalModule(filepath: string): Promise<unknown> {\n return this.esmEvaluator.runExternalModule(filepath)\n }\n\n runInlinedModule(\n context: ModuleRunnerContext,\n code: string,\n module: Readonly<EvaluatedModuleNode>,\n ): Promise<void> {\n return this.runCommonJsModule(context, code, module)\n }\n\n private async runCommonJsModule(\n context: ModuleRunnerContext,\n code: string,\n module: Readonly<EvaluatedModuleNode>,\n ): Promise<void> {\n const modulePath = module.file || module.id\n const href = pathToFileURL(modulePath).href\n const __filename = fileURLToPath(href)\n const __dirname = dirname(__filename)\n\n const exports = context[ssrModuleExportsKey]\n const moduleNotDefined = Symbol('not defined')\n let moduleExports: unknown = moduleNotDefined\n\n const cjsExports = new Proxy(exports, {\n get: (target, property, receiver) => {\n if (Reflect.has(target, property)) return Reflect.get(target, property, receiver)\n return Reflect.get(Object.prototype, property, receiver)\n },\n getPrototypeOf: () => Object.prototype,\n set: (_, property, value) => {\n // Keep the module default when CommonJS aliases it back to `module.exports`.\n if (property === 'default' && cjsExports !== value) {\n exportAll(exports, value)\n exports.default = value\n return true\n }\n if (!Reflect.has(exports, 'default')) {\n exports.default = {}\n }\n if (moduleExports !== moduleNotDefined && isPrimitive(moduleExports)) {\n defineExport(exports, String(property), () => {})\n return true\n }\n if (!isPrimitive(exports.default)) {\n ;(exports.default as Record<string, unknown>)[String(property)] = value\n }\n if (property !== 'default') {\n defineExport(exports, String(property), () => value)\n }\n return true\n },\n })\n\n const moduleProxy = {\n get exports() {\n return cjsExports\n },\n set exports(value: unknown) {\n exportAll(exports, value)\n exports.default = value\n moduleExports = value\n },\n }\n\n const cjsContext: Record<string, unknown> = {\n ...context,\n __dirname,\n __filename,\n exports: cjsExports,\n module: moduleProxy,\n require: createRequire(href),\n }\n\n let normalizedCode = code\n if (normalizedCode[0] === '#') {\n normalizedCode = normalizedCode.replace(/^#!.*/, (line) => ' '.repeat(line.length))\n }\n\n const AsyncFunction = async function () {}.constructor as new (\n ...args: string[]\n ) => (...args: unknown[]) => Promise<unknown>\n const parameterNames = Object.keys(cjsContext)\n const runner = new AsyncFunction(...parameterNames, `\"use strict\";{\\n${normalizedCode}\\n}`)\n await runner(...parameterNames.map((name) => cjsContext[name]))\n }\n}\n"],"names":["createRequire","dirname","fileURLToPath","pathToFileURL","ESModulesEvaluator","ssrModuleExportsKey","isPrimitive","value","defineExport","exports","key","getter","Object","defineProperty","configurable","enumerable","get","exportAll","sourceModule","Array","isArray","Promise","StudioModuleEvaluator","esmEvaluator","startOffset","runExternalModule","filepath","runInlinedModule","context","code","module","runCommonJsModule","modulePath","file","id","href","__filename","__dirname","moduleNotDefined","Symbol","moduleExports","cjsExports","Proxy","target","property","receiver","Reflect","has","prototype","getPrototypeOf","set","_","default","String","moduleProxy","cjsContext","require","normalizedCode","replace","line","repeat","length","AsyncFunction","parameterNames","keys","runner","map","name"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AACzC,SAAQC,OAAO,QAAO,YAAW;AACjC,SAAQC,aAAa,EAAEC,aAAa,QAAO,WAAU;AAErD,SACEC,kBAAkB,EAIlBC,mBAAmB,QACd,qBAAoB;AAE3B,SAASC,YAAYC,KAAc;IACjC,O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C,OAAO,CAAC,SAAS,CAACC,OAAS,IAAIC,MAAM,CAACD,KAAKE,MAAM;QACnF;QAEA,MAAMC,gBAAgB,CAAA,kBAAmB,CAAA,EAAE,WAAW;QAGtD,MAAMC,iBAAiBnD,OAAOoD,IAAI,CAACT;QACnC,MAAMU,SAAS,IAAIH,iBAAiBC,gBAAgB,CAAC,gBAAgB,EAAEN,eAAe,GAAG,CAAC;QAC1F,MAAMQ,UAAUF,eAAeG,GAAG,CAAC,CAACC,OAASZ,UAAU,CAACY,KAAK;IAC/D;AACF"}
|
|
@@ -5,7 +5,7 @@ import { subdebug } from '../../_exports/debug.js';
|
|
|
5
5
|
import { getCliConfig } from '../../config/cli/getCliConfig.js';
|
|
6
6
|
import { isNotFoundError } from '../../errors/NotFoundError.js';
|
|
7
7
|
import { getStudioEnvironmentVariables } from '../../util/environment/getStudioEnvironmentVariables.js';
|
|
8
|
-
import { setupBrowserStubs } from '../../util/environment/setupBrowserStubs.js';
|
|
8
|
+
import { setupBrowserStubs } from '../../util/environment/setupBrowserStubs.js';
|
|
9
9
|
import { isRecord } from '../../util/isRecord.js';
|
|
10
10
|
import { StudioModuleEvaluator } from './studioModuleEvaluator.js';
|
|
11
11
|
import { createOneShotWorkerLifecycle } from './studioWorkerLifecycle.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {fileURLToPath, pathToFileURL} from 'node:url'\nimport {isMainThread, parentPort} from 'node:worker_threads'\n\nimport {\n createServer,\n createServerModuleRunner,\n type InlineConfig,\n isRunnableDevEnvironment,\n loadEnv,\n mergeConfig,\n} from 'vite'\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 {StudioModuleEvaluator} from './studioModuleEvaluator.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)\nconst applicationId = process.env.STUDIO_WORKER_APPLICATION_ID\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 module runner 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: {\n // Config imports must use the same bus identity as the surrounding app bundle.\n ...(applicationId ? {__SANITY_APP_ID__: JSON.stringify(applicationId)} : {}),\n ...Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\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 const ssrEnvironment = server.environments.ssr\n if (!isRunnableDevEnvironment(ssrEnvironment)) {\n throw new Error('Expected SSR environment to be a runnable dev environment')\n }\n\n await ssrEnvironment.init()\n\n // Override fetchModule to support https:// imports and resolve relative imports from\n // remote modules (e.g. esm.sh re-exports with absolute paths).\n const defaultFetchModule = ssrEnvironment.fetchModule.bind(ssrEnvironment)\n ssrEnvironment.fetchModule = async (id, importer, options) => {\n if (importer && isHttpsUrl(importer) && !isHttpsUrl(id)) {\n id = new URL(id, importer).href\n }\n if (isHttpsUrl(id)) {\n const {code: rawCode} = await fetchHttpModule(id)\n const result = await server.ssrTransform(rawCode, null, id)\n return {\n code: result?.code || rawCode,\n file: null,\n id,\n invalidate: false,\n url: id,\n }\n }\n\n // Module Runner's fetchModule skips Vite resolve for `file://` URLs, so TypeScript\n // extension rewriting (`.js` → `.ts`/`.tsx`) never runs. vite-node always resolved\n // through `resolveId` first; restore that for absolute file imports (e.g. lazy\n // `doImport(new URL('iconResolver.js', import.meta.url))` in tests/source).\n // Keep the result as `file://` — on Windows, bare `C:/...` paths are treated as\n // package imports by Module Runner's fetchModule and fail to load.\n if (id.startsWith('file://')) {\n const resolved = await ssrEnvironment.pluginContainer.resolveId(\n fileURLToPath(id),\n importer ?? undefined,\n )\n if (resolved?.id && !resolved.id.startsWith('\\0')) {\n id = pathToFileURL(resolved.id).href\n }\n }\n\n return defaultFetchModule(id, importer, options)\n }\n\n const runner = createServerModuleRunner(ssrEnvironment, {\n evaluator: new StudioModuleEvaluator(),\n hmr: false,\n })\n\n await runner.import(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":["fileURLToPath","pathToFileURL","isMainThread","parentPort","createServer","createServerModuleRunner","isRunnableDevEnvironment","loadEnv","mergeConfig","subdebug","getCliConfig","isNotFoundError","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","StudioModuleEvaluator","createOneShotWorkerLifecycle","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","debug","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","applicationId","STUDIO_WORKER_APPLICATION_ID","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","__SANITY_APP_ID__","JSON","stringify","Object","fromEntries","entries","map","key","value","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","ssrEnvironment","environments","init","defaultFetchModule","fetchModule","bind","importer","options","URL","href","rawCode","result","ssrTransform","file","invalidate","resolved","resolveId","runner","evaluator","import","postError"],"mappings":"AAAA,SAAQA,aAAa,EAAEC,aAAa,QAAO,WAAU;AACrD,SAAQC,YAAY,EAAEC,UAAU,QAAO,sBAAqB;AAE5D,SACEC,YAAY,EACZC,wBAAwB,EAExBC,wBAAwB,EACxBC,OAAO,EACPC,WAAW,QACN,OAAM;AAEb,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,qBAAqB,QAAO,6BAA4B;AAChE,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,QAAQb,SAAS;AAEvB,MAAMc,mBAAmBJ,QAAQC,GAAG,CAACI,uBAAuB;AAC5D,IAAI,CAACD,kBAAkB;IACrB,MAAM,IAAIN,MAAM;AAClB;AAEA,MAAMJ;AAEN,MAAMY,gBAAgB,MAAMb,8BAA8BM;AAC1D,MAAMQ,gBAAgBP,QAAQC,GAAG,CAACO,4BAA4B;AAE9D,oFAAoF;AACpF,+DAA+D;AAC/D,IAAIC;AACJ,IAAI;IACFA,YAAY,MAAMlB,aAAaQ;AACjC,EAAE,OAAOW,KAAK;IACZP,MAAM,iCAAiCO;IACvC,IAAI,CAAClB,gBAAgBkB,MAAM;QACzB,sCAAsC;QACtCC,QAAQC,IAAI,CAAC,qCAAqCF;IACpD;AACF;AAEA;;;;CAIC,GACD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ACR,MAAML,WAAWG;AACnB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {fileURLToPath, pathToFileURL} from 'node:url'\nimport {isMainThread, parentPort} from 'node:worker_threads'\n\nimport {\n createServer,\n createServerModuleRunner,\n type InlineConfig,\n isRunnableDevEnvironment,\n loadEnv,\n mergeConfig,\n} from 'vite'\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'\nimport {isRecord} from '../../util/isRecord.js'\nimport {StudioModuleEvaluator} from './studioModuleEvaluator.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)\nconst applicationId = process.env.STUDIO_WORKER_APPLICATION_ID\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 module runner 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: {\n // Config imports must use the same bus identity as the surrounding app bundle.\n ...(applicationId ? {__SANITY_APP_ID__: JSON.stringify(applicationId)} : {}),\n ...Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\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 const ssrEnvironment = server.environments.ssr\n if (!isRunnableDevEnvironment(ssrEnvironment)) {\n throw new Error('Expected SSR environment to be a runnable dev environment')\n }\n\n await ssrEnvironment.init()\n\n // Override fetchModule to support https:// imports and resolve relative imports from\n // remote modules (e.g. esm.sh re-exports with absolute paths).\n const defaultFetchModule = ssrEnvironment.fetchModule.bind(ssrEnvironment)\n ssrEnvironment.fetchModule = async (id, importer, options) => {\n if (importer && isHttpsUrl(importer) && !isHttpsUrl(id)) {\n id = new URL(id, importer).href\n }\n if (isHttpsUrl(id)) {\n const {code: rawCode} = await fetchHttpModule(id)\n const result = await server.ssrTransform(rawCode, null, id)\n return {\n code: result?.code || rawCode,\n file: null,\n id,\n invalidate: false,\n url: id,\n }\n }\n\n // Module Runner's fetchModule skips Vite resolve for `file://` URLs, so TypeScript\n // extension rewriting (`.js` → `.ts`/`.tsx`) never runs. vite-node always resolved\n // through `resolveId` first; restore that for absolute file imports (e.g. lazy\n // `doImport(new URL('iconResolver.js', import.meta.url))` in tests/source).\n // Keep the result as `file://` — on Windows, bare `C:/...` paths are treated as\n // package imports by Module Runner's fetchModule and fail to load.\n if (id.startsWith('file://')) {\n const resolved = await ssrEnvironment.pluginContainer.resolveId(\n fileURLToPath(id),\n importer ?? undefined,\n )\n if (resolved?.id && !resolved.id.startsWith('\\0')) {\n id = pathToFileURL(resolved.id).href\n }\n }\n\n return defaultFetchModule(id, importer, options)\n }\n\n const runner = createServerModuleRunner(ssrEnvironment, {\n evaluator: new StudioModuleEvaluator(),\n hmr: false,\n })\n\n await runner.import(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":["fileURLToPath","pathToFileURL","isMainThread","parentPort","createServer","createServerModuleRunner","isRunnableDevEnvironment","loadEnv","mergeConfig","subdebug","getCliConfig","isNotFoundError","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","StudioModuleEvaluator","createOneShotWorkerLifecycle","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","debug","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","applicationId","STUDIO_WORKER_APPLICATION_ID","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","__SANITY_APP_ID__","JSON","stringify","Object","fromEntries","entries","map","key","value","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","ssrEnvironment","environments","init","defaultFetchModule","fetchModule","bind","importer","options","URL","href","rawCode","result","ssrTransform","file","invalidate","resolved","resolveId","runner","evaluator","import","postError"],"mappings":"AAAA,SAAQA,aAAa,EAAEC,aAAa,QAAO,WAAU;AACrD,SAAQC,YAAY,EAAEC,UAAU,QAAO,sBAAqB;AAE5D,SACEC,YAAY,EACZC,wBAAwB,EAExBC,wBAAwB,EACxBC,OAAO,EACPC,WAAW,QACN,OAAM;AAEb,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;AAC7E,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,qBAAqB,QAAO,6BAA4B;AAChE,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,QAAQb,SAAS;AAEvB,MAAMc,mBAAmBJ,QAAQC,GAAG,CAACI,uBAAuB;AAC5D,IAAI,CAACD,kBAAkB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D,EAAE,EAAEwD,IAAI;YACtC;QACF;QAEA,OAAON,mBAAmBlD,IAAIqD,UAAUC;IAC1C;IAEA,MAAMU,SAAS7G,yBAAyB4F,gBAAgB;QACtDkB,WAAW,IAAIpG;QACf+D,KAAK;IACP;IAEA,MAAMoC,OAAOE,MAAM,CAAC7F;AACtB,EAAE,OAAOqE,OAAO;IACd,yEAAyE;IACzE,wBAAwB;IACxB,IAAI,CAACL,WAAW;QACd,MAAMK;IACR;IAEA,0EAA0E;IAC1E,0EAA0E;IAC1E,6EAA6E;IAC7E,MAAML,UAAU8B,SAAS,CAACzB;AAC5B,SAAU;IACR,MAAML,WAAWG;AACnB"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// TODO: Consider moving to @sanity/cli — only used there (SDK-983)
|
|
2
|
-
// this file pulls in JSDOM, which is a 46MB dep. we should isolate the impact of this on the import graph. SDK-983 should be addressed.
|
|
3
2
|
import { getStudioEnvironmentVariables } from './getStudioEnvironmentVariables.js';
|
|
4
|
-
import { setupBrowserStubs } from './setupBrowserStubs.js';
|
|
3
|
+
import { setupBrowserStubs } from './setupBrowserStubs.js';
|
|
5
4
|
/**
|
|
6
5
|
* Mocks a browser-like environment for processes in the main thread by:
|
|
7
6
|
* - Injecting browser globals (window, document, ResizeObserver, etc.)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/util/environment/mockBrowserEnvironment.ts"],"sourcesContent":["// TODO: Consider moving to @sanity/cli — only used there (SDK-983)\
|
|
1
|
+
{"version":3,"sources":["../../../src/util/environment/mockBrowserEnvironment.ts"],"sourcesContent":["// TODO: Consider moving to @sanity/cli — only used there (SDK-983)\nimport {getStudioEnvironmentVariables} from './getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from './setupBrowserStubs.js'\n\n/**\n * Mocks a browser-like environment for processes in the main thread by:\n * - Injecting browser globals (window, document, ResizeObserver, etc.)\n * - Loading studio environment variables from the project's sanity installation into process.env\n *\n * This is useful for commands like `sanity exec` that have to run user scripts\n * in the main thread of the process (but in a child process).\n *\n * Be cautious when using this, since it will pollute the global namespace with browser globals.\n *\n * If your code can run in a worker thread, you should use the `studioWorkerTask` function instead.\n *\n * @param basePath - The root path of the Sanity Studio project\n * @returns A cleanup function that removes the injected globals and environment variables\n * @internal\n */\nexport async function mockBrowserEnvironment(basePath: string): Promise<() => void> {\n // 1. Setup browser globals\n const cleanupBrowserStubs = await setupBrowserStubs()\n\n // 2. Load and set environment variables into process.env\n const envVars = await getStudioEnvironmentVariables(basePath)\n const setEnvKeys: string[] = []\n const originalEnvValues: Record<string, string | undefined> = {}\n\n for (const [key, value] of Object.entries(envVars)) {\n // Store original value (if any) so we can restore it\n originalEnvValues[key] = process.env[key]\n process.env[key] = value\n setEnvKeys.push(key)\n }\n\n // Return cleanup function\n return () => {\n // Restore or delete environment variables\n for (const key of setEnvKeys) {\n if (originalEnvValues[key] === undefined) {\n delete process.env[key]\n } else {\n process.env[key] = originalEnvValues[key]\n }\n }\n\n // Clean up browser stubs\n cleanupBrowserStubs()\n }\n}\n"],"names":["getStudioEnvironmentVariables","setupBrowserStubs","mockBrowserEnvironment","basePath","cleanupBrowserStubs","envVars","setEnvKeys","originalEnvValues","key","value","Object","entries","process","env","push","undefined"],"mappings":"AAAA,mEAAmE;AACnE,SAAQA,6BAA6B,QAAO,qCAAoC;AAChF,SAAQC,iBAAiB,QAAO,yBAAwB;AAExD;;;;;;;;;;;;;;;CAeC,GACD,OAAO,eAAeC,uBAAuBC,QAAgB;IAC3D,2BAA2B;IAC3B,MAAMC,sBAAsB,MAAMH;IAElC,yDAAyD;IACzD,MAAMI,UAAU,MAAML,8BAA8BG;IACpD,MAAMG,aAAuB,EAAE;IAC/B,MAAMC,oBAAwD,CAAC;IAE/D,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACN,SAAU;QAClD,qDAAqD;QACrDE,iBAAiB,CAACC,IAAI,GAAGI,QAAQC,GAAG,CAACL,IAAI;QACzCI,QAAQC,GAAG,CAACL,IAAI,GAAGC;QACnBH,WAAWQ,IAAI,CAACN;IAClB;IAEA,0BAA0B;IAC1B,OAAO;QACL,0CAA0C;QAC1C,KAAK,MAAMA,OAAOF,WAAY;YAC5B,IAAIC,iBAAiB,CAACC,IAAI,KAAKO,WAAW;gBACxC,OAAOH,QAAQC,GAAG,CAACL,IAAI;YACzB,OAAO;gBACLI,QAAQC,GAAG,CAACL,IAAI,GAAGD,iBAAiB,CAACC,IAAI;YAC3C;QACF;QAEA,yBAAyB;QACzBJ;IACF;AACF"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { getBrowserStubs } from './stubs.js'; // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB
|
|
2
1
|
/**
|
|
3
2
|
* Sets up browser globals (window, document, etc.) in the global scope.
|
|
4
3
|
*
|
|
@@ -17,6 +16,10 @@ import { getBrowserStubs } from './stubs.js'; // TODO: this imports jsdom!!! Unp
|
|
|
17
16
|
// decided what to inject — including a small set of keys (e.g.
|
|
18
17
|
// `localStorage`/`sessionStorage`/`Storage`) that we want to take from JSDOM
|
|
19
18
|
// even if Node provides them, so realm identity stays consistent.
|
|
19
|
+
// Imported lazily: `stubs.js` pulls in JSDOM (~600 modules), and this module
|
|
20
|
+
// is reachable from the `@sanity/cli-core` barrel that every command loads.
|
|
21
|
+
// eslint-disable-next-line no-restricted-syntax -- static relative import, not a user file path
|
|
22
|
+
const { getBrowserStubs } = await import('./stubs.js');
|
|
20
23
|
const stubs = getBrowserStubs();
|
|
21
24
|
const mockedGlobalThis = globalThis;
|
|
22
25
|
const stubbedKeys = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/util/environment/setupBrowserStubs.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"sources":["../../../src/util/environment/setupBrowserStubs.ts"],"sourcesContent":["/**\n * Sets up browser globals (window, document, etc.) in the global scope.\n *\n * This is used by both mockBrowserEnvironment (for child processes) and\n * studioWorkerLoader (for worker threads) to provide a browser-like environment.\n *\n * @returns A cleanup function that removes the injected globals\n * @internal\n */\nexport async function setupBrowserStubs(): Promise<() => void> {\n // Guard against double-registering\n if (globalThis.window && '__mockedBySanity' in globalThis.window) {\n return () => {\n /* intentional noop - already mocked */\n }\n }\n\n // Inject browser stubs into global scope. `getBrowserStubs()` has already\n // decided what to inject — including a small set of keys (e.g.\n // `localStorage`/`sessionStorage`/`Storage`) that we want to take from JSDOM\n // even if Node provides them, so realm identity stays consistent.\n // Imported lazily: `stubs.js` pulls in JSDOM (~600 modules), and this module\n // is reachable from the `@sanity/cli-core` barrel that every command loads.\n // eslint-disable-next-line no-restricted-syntax -- static relative import, not a user file path\n const {getBrowserStubs} = await import('./stubs.js')\n const stubs = getBrowserStubs()\n const mockedGlobalThis: Record<string, unknown> = globalThis\n const stubbedKeys: string[] = []\n const originalDescriptors = new Map<string, PropertyDescriptor>()\n\n for (const key of Object.keys(stubs)) {\n // Snapshot via descriptor to avoid triggering getters (e.g. Node 26's\n // `localStorage` getter logs an ExperimentalWarning on read).\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, key)\n if (descriptor) {\n originalDescriptors.set(key, descriptor)\n // Assignment would throw for getter-only accessors (e.g. Node 26's\n // `localStorage`/`sessionStorage`), so replace the property outright.\n Object.defineProperty(globalThis, key, {\n configurable: true,\n enumerable: descriptor.enumerable,\n value: stubs[key],\n writable: true,\n })\n } else {\n mockedGlobalThis[key] = stubs[key]\n }\n stubbedKeys.push(key)\n }\n\n // Add marker to window to detect double-mocking\n if (globalThis.window) {\n ;(globalThis.window as unknown as Record<string, unknown>).__mockedBySanity = true\n }\n\n // Return cleanup function\n return () => {\n // Remove marker before deleting window\n if (globalThis.window) {\n delete (globalThis.window as unknown as Record<string, unknown>).__mockedBySanity\n }\n\n for (const key of stubbedKeys) {\n const descriptor = originalDescriptors.get(key)\n if (descriptor) {\n Object.defineProperty(globalThis, key, descriptor)\n } else {\n delete mockedGlobalThis[key]\n }\n }\n }\n}\n"],"names":["setupBrowserStubs","globalThis","window","getBrowserStubs","stubs","mockedGlobalThis","stubbedKeys","originalDescriptors","Map","key","Object","keys","descriptor","getOwnPropertyDescriptor","set","defineProperty","configurable","enumerable","value","writable","push","__mockedBySanity","get"],"mappings":"AAAA;;;;;;;;CAQC,GACD,OAAO,eAAeA;IACpB,mCAAmC;IACnC,IAAIC,WAAWC,MAAM,IAAI,sBAAsBD,WAAWC,MAAM,EAAE;QAChE,OAAO;QACL,qCAAqC,GACvC;IACF;IAEA,0EAA0E;IAC1E,+DAA+D;IAC/D,6EAA6E;IAC7E,kEAAkE;IAClE,6EAA6E;IAC7E,4EAA4E;IAC5E,gGAAgG;IAChG,MAAM,EAACC,eAAe,EAAC,GAAG,MAAM,MAAM,CAAC;IACvC,MAAMC,QAAQD;IACd,MAAME,mBAA4CJ;IAClD,MAAMK,cAAwB,EAAE;IAChC,MAAMC,sBAAsB,IAAIC;IAEhC,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAACP,OAAQ;QACpC,sEAAsE;QACtE,8DAA8D;QAC9D,MAAMQ,aAAaF,OAAOG,wBAAwB,CAACZ,YAAYQ;QAC/D,IAAIG,YAAY;YACdL,oBAAoBO,GAAG,CAACL,KAAKG;YAC7B,mEAAmE;YACnE,sEAAsE;YACtEF,OAAOK,cAAc,CAACd,YAAYQ,KAAK;gBACrCO,cAAc;gBACdC,YAAYL,WAAWK,UAAU;gBACjCC,OAAOd,KAAK,CAACK,IAAI;gBACjBU,UAAU;YACZ;QACF,OAAO;YACLd,gBAAgB,CAACI,IAAI,GAAGL,KAAK,CAACK,IAAI;QACpC;QACAH,YAAYc,IAAI,CAACX;IACnB;IAEA,gDAAgD;IAChD,IAAIR,WAAWC,MAAM,EAAE;;QACnBD,WAAWC,MAAM,CAAwCmB,gBAAgB,GAAG;IAChF;IAEA,0BAA0B;IAC1B,OAAO;QACL,uCAAuC;QACvC,IAAIpB,WAAWC,MAAM,EAAE;YACr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