@sanity/cli-core 2.1.3 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +224 -1
- package/dist/SanityCommand.d.ts +454 -0
- package/dist/SanityCommand.js +5 -4
- package/dist/SanityCommand.js.map +1 -1
- package/dist/_exports/browser.d.ts +21 -0
- package/dist/_exports/browser.js +5 -0
- package/dist/_exports/browser.js.map +1 -0
- package/dist/_exports/config.d.ts +653 -0
- package/dist/_exports/config.js +18 -0
- package/dist/_exports/config.js.map +1 -0
- package/dist/_exports/debug.d.ts +20 -0
- package/dist/_exports/debug.js.map +1 -0
- package/dist/_exports/errors.d.ts +67 -0
- package/dist/_exports/errors.js +5 -0
- package/dist/_exports/errors.js.map +1 -0
- package/dist/_exports/index.d.ts +30 -33
- package/dist/_exports/index.js +42 -39
- package/dist/_exports/index.js.map +1 -1
- package/dist/_exports/package-manager.d.ts +191 -0
- package/dist/_exports/package-manager.js +3 -0
- package/dist/_exports/package-manager.js.map +1 -1
- package/dist/_exports/schemas.d.ts +227 -0
- package/dist/_exports/schemas.js +4 -0
- package/dist/_exports/schemas.js.map +1 -0
- package/dist/_exports/tasks.d.ts +120 -0
- package/dist/_exports/tasks.js +4 -0
- package/dist/_exports/tasks.js.map +1 -0
- package/dist/_exports/telemetry.d.ts +156 -0
- package/dist/_exports/telemetry.js +7 -0
- package/dist/_exports/telemetry.js.map +1 -0
- package/dist/_exports/types.d.ts +460 -0
- package/dist/_exports/types.js +3 -0
- package/dist/_exports/types.js.map +1 -0
- package/dist/_exports/util.d.ts +132 -0
- package/dist/_exports/util.js +16 -0
- package/dist/_exports/util.js.map +1 -0
- package/dist/_exports/ux.d.ts +15 -0
- package/dist/_exports/ux.js +6 -4
- package/dist/_exports/ux.js.map +1 -1
- package/dist/apiClient.d.ts +79 -0
- package/dist/{services/apiClient.js → apiClient.js} +2 -2
- package/dist/{services/apiClient.js.map → apiClient.js.map} +1 -1
- package/dist/config/cli/cliTokenCache.js.map +1 -0
- package/dist/{services → config/cli}/cliUserConfig.js +31 -6
- package/dist/config/cli/cliUserConfig.js.map +1 -0
- package/dist/config/cli/getCliConfig.js +1 -1
- package/dist/config/cli/getCliConfig.js.map +1 -1
- package/dist/config/cli/schemas.js +1 -0
- package/dist/config/cli/schemas.js.map +1 -1
- package/dist/config/cli/types/cliConfig.js +4 -0
- package/dist/config/cli/types/cliConfig.js.map +1 -1
- package/dist/config/cli/workbenchApp.js +19 -38
- package/dist/config/cli/workbenchApp.js.map +1 -1
- package/dist/config/studio/getStudioWorkspaces.js +1 -1
- package/dist/config/studio/getStudioWorkspaces.js.map +1 -1
- package/dist/config/studio/readStudioConfig.worker.js +1 -1
- package/dist/config/studio/readStudioConfig.worker.js.map +1 -1
- package/dist/exitCodes.d.ts +23 -0
- package/dist/loaders/studio/studioWorkerLoader.worker.js +2 -2
- package/dist/loaders/studio/studioWorkerLoader.worker.js.map +1 -1
- package/dist/telemetry/getCliTelemetry.js +3 -2
- package/dist/telemetry/getCliTelemetry.js.map +1 -1
- package/dist/telemetry/getTelemetryBaseInfo.js +1 -1
- package/dist/telemetry/getTelemetryBaseInfo.js.map +1 -1
- package/dist/util/environment/mockBrowserEnvironment.js +3 -2
- package/dist/util/environment/mockBrowserEnvironment.js.map +1 -1
- package/dist/util/environment/setupBrowserStubs.js +1 -1
- package/dist/util/environment/setupBrowserStubs.js.map +1 -1
- package/dist/util/getSanityConfigDir.js +1 -0
- package/dist/util/getSanityConfigDir.js.map +1 -1
- package/dist/util/getSanityEnvVar.js +1 -0
- package/dist/util/getSanityEnvVar.js.map +1 -1
- package/dist/util/getSanityUrl.js +1 -0
- package/dist/util/getSanityUrl.js.map +1 -1
- package/dist/util/getWorkspace.js +1 -0
- package/dist/util/getWorkspace.js.map +1 -1
- package/dist/util/importModule.js +1 -1
- package/dist/util/importModule.js.map +1 -1
- package/dist/util/promisifyWorker.js +1 -1
- package/dist/util/promisifyWorker.js.map +1 -1
- package/package.json +56 -8
- package/dist/debug.js.map +0 -1
- package/dist/services/cliTokenCache.js.map +0 -1
- package/dist/services/cliUserConfig.js.map +0 -1
- package/dist/services/getCliToken.js +0 -26
- package/dist/services/getCliToken.js.map +0 -1
- /package/dist/{debug.js → _exports/debug.js} +0 -0
- /package/dist/{services → config/cli}/cliTokenCache.js +0 -0
|
@@ -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 {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {subdebug} from '../../debug.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'\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","getCliConfig","subdebug","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":"AAAA,SAAQA,YAAY,QAAO,sBAAqB;AAEhD,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,YAAY,QAAO,mCAAkC;AAE7D,SAAQC,QAAQ,QAAO,iBAAgB;AACvC,SAAQC,eAAe,QAAO,gCAA+B;AAC7D,SAAQC,6BAA6B,QAAO,0DAAyD;AACrG,SAAQC,iBAAiB,QAAO,8CAA6C;AAC7E,SAAQC,QAAQ,QAAO,yBAAwB;AAE/C,IAAIZ,cAAc;IAChB,MAAM,IAAIa,MAAM;AAClB;AAEA,MAAMC,WAAWC,QAAQC,GAAG,CAAC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;AAEA,MAAMC,SAAS,IAAInF,eAAe;IAChCoF,MAAMlB,OAAOY,MAAM,CAACM,IAAI;IACxB,MAAMC,aAAY7C,EAAE;QAClB,2EAA2E;QAC3E,6EAA6E;QAC7E,wEAAwE;QACxE,sCAAsC;QACtC,IAAID,WAAWC,KAAK;YAClB,MAAM,EAACZ,MAAM0D,OAAO,EAAC,GAAG,MAAM9D,gBAAgBgB;YAC9C,MAAM+C,SAAS,MAAMrB,OAAOsB,YAAY,CAACF,SAAS,MAAM9C;YACxD,OAAO;gBAACZ,MAAM2D,QAAQ3D,QAAQ0D;YAAO;QACvC;QACA,OAAON,KAAKK,WAAW,CAAC7C;IAC1B;IACAiD,WAAUjD,EAAE,EAAEkD,QAAQ;QACpB,6EAA6E;QAC7E,IAAInD,WAAWC,KAAK,OAAO;YAACA;QAAE;QAC9B,2EAA2E;QAC3E,kEAAkE;QAClE,IAAIkD,YAAYnD,WAAWmD,WAAW;YACpC,OAAO;gBAAClD,IAAI,IAAImD,IAAInD,IAAIkD,UAAUE,IAAI;YAAA;QACxC;QACA,OAAOZ,KAAKS,SAAS,CAACjD,IAAIkD;IAC5B;IACAzB,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} 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":"AAAA,SAAQA,YAAY,QAAO,sBAAqB;AAEhD,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;AAE/C,IAAIZ,cAAc;IAChB,MAAM,IAAIa,MAAM;AAClB;AAEA,MAAMC,WAAWC,QAAQC,GAAG,CAACC,8BAA8B;AAC3D,IAAI,CAACH,UAAU;IACb,MAAM,IAAID,MAAM;AAClB;AAEA,MAAMK,QAAQX,SAAS;AAEvB,MAAMY,mBAAmBJ,QAAQC,GAAG,CAACI,uBAAuB;AAC5D,IAAI,CAACD,kBAAkB;IACrB,MAAM,IAAIN,MAAM;AAClB;AAEA,MAAMF;AAEN,MAAMU,gBAAgB,MAAMX,8BAA8BI;AAE1D,oFAAoF;AACpF,+DAA+D;AAC/D,IAAIQ;AACJ,IAAI;IACFA,YAAY,MAAMd,aAAaM;AACjC,EAAE,OAAOS,KAAK;IACZL,MAAM,iCAAiCK;IACvC,IAAI,CAACd,gBAAgBc,MAAM;QACzB,sCAAsC;QACtCC,QAAQC,IAAI,CAAC,qCAAqCF;IACpD;AACF;AAEA;;;;CAIC,GACD,MAAMG,kBAAkB,IAAIC;AAC5B,eA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C3E,kEAAkE;QAClE,IAAIkD,YAAYnD,WAAWmD,WAAW;YACpC,OAAO;gBAAClD,IAAI,IAAImD,IAAInD,IAAIkD,UAAUE,IAAI;YAAA;QACxC;QACA,OAAOZ,KAAKS,SAAS,CAACjD,IAAIkD;IAC5B;IACAzB,MAAMC,OAAOY,MAAM,CAACb,IAAI;AAC1B;AAEA,kFAAkF;AAClF,iFAAiF;AACjF,6EAA6E;AAC7E,MAAMkB,OAAOU,SAAS,CAAC;AAEvB,MAAMV,OAAOU,SAAS,CAAC9E"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ux } from '@oclif/core';
|
|
1
|
+
import { ux } from '@oclif/core'; // TODO: should telemetry helpers be importing oclif? cli-build imports this... we should remove this.
|
|
2
2
|
import { noopLogger } from './noopTelemetry.js';
|
|
3
3
|
/**
|
|
4
4
|
* @public
|
|
@@ -10,7 +10,8 @@ function getState() {
|
|
|
10
10
|
}
|
|
11
11
|
/**
|
|
12
12
|
* @public
|
|
13
|
-
*/
|
|
13
|
+
*/ // TODO: change this API so that it accepts a channel for passing warnings through, otherwise this is pumped through OCLIF UX via singleton
|
|
14
|
+
export function getCliTelemetry() {
|
|
14
15
|
const state = getState();
|
|
15
16
|
// This should never happen, but if it does, we return a noop logger to avoid errors.
|
|
16
17
|
if (!state) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/telemetry/getCliTelemetry.ts"],"sourcesContent":["import {ux} from '@oclif/core'
|
|
1
|
+
{"version":3,"sources":["../../src/telemetry/getCliTelemetry.ts"],"sourcesContent":["import {ux} from '@oclif/core' // TODO: should telemetry helpers be importing oclif? cli-build imports this... we should remove this.\n\nimport {noopLogger} from './noopTelemetry.js'\nimport {type CLITelemetryStore} from './types.js'\n\n/**\n * @public\n * Symbol used to store CLI telemetry state on globalThis.\n * Use the accessor functions instead of accessing this directly.\n */\nexport const CLI_TELEMETRY_SYMBOL = Symbol.for('sanity.cli.telemetry')\n\ntype TraceErrorReporter = (error: Error) => void\n\ninterface CliTelemetryState {\n logger: CLITelemetryStore\n\n reportTraceError?: TraceErrorReporter\n}\n\ntype GlobalWithTelemetry = typeof globalThis & {\n [CLI_TELEMETRY_SYMBOL]?: CliTelemetryState\n}\n\nfunction getState(): CliTelemetryState | undefined {\n return (globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL]\n}\n\n/**\n * @public\n */\n// TODO: change this API so that it accepts a channel for passing warnings through, otherwise this is pumped through OCLIF UX via singleton\nexport function getCliTelemetry(): CLITelemetryStore {\n const state = getState()\n // This should never happen, but if it does, we return a noop logger to avoid errors.\n if (!state) {\n ux.warn('CLI telemetry not initialized, returning noop logger')\n return noopLogger\n }\n\n return state.logger\n}\n\n/**\n * Sets the global CLI telemetry state.\n * @internal\n */\nexport function setCliTelemetry(\n telemetry: CLITelemetryStore,\n options?: {reportTraceError?: TraceErrorReporter},\n): void {\n ;(globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL] = {\n logger: telemetry,\n reportTraceError: options?.reportTraceError,\n }\n}\n\n/**\n * Reports an error to the CLI command trace. Called from SanityCommand.catch()\n * for real command errors (not user aborts).\n * @internal\n */\nexport function reportCliTraceError(error: Error): void {\n getState()?.reportTraceError?.(error)\n}\n\n/**\n * Clears the global CLI telemetry store.\n * @internal\n */\nexport function clearCliTelemetry(): void {\n const global = globalThis as GlobalWithTelemetry\n delete global[CLI_TELEMETRY_SYMBOL]\n}\n"],"names":["ux","noopLogger","CLI_TELEMETRY_SYMBOL","Symbol","for","getState","globalThis","getCliTelemetry","state","warn","logger","setCliTelemetry","telemetry","options","reportTraceError","reportCliTraceError","error","clearCliTelemetry","global"],"mappings":"AAAA,SAAQA,EAAE,QAAO,cAAa,CAAC,sGAAsG;AAErI,SAAQC,UAAU,QAAO,qBAAoB;AAG7C;;;;CAIC,GACD,OAAO,MAAMC,uBAAuBC,OAAOC,GAAG,CAAC,wBAAuB;AActE,SAASC;IACP,OAAO,AAACC,UAAkC,CAACJ,qBAAqB;AAClE;AAEA;;CAEC,GACD,2IAA2I;AAC3I,OAAO,SAASK;IACd,MAAMC,QAAQH;IACd,qFAAqF;IACrF,IAAI,CAACG,OAAO;QACVR,GAAGS,IAAI,CAAC;QACR,OAAOR;IACT;IAEA,OAAOO,MAAME,MAAM;AACrB;AAEA;;;CAGC,GACD,OAAO,SAASC,gBACdC,SAA4B,EAC5BC,OAAiD;;IAE/CP,UAAkC,CAACJ,qBAAqB,GAAG;QAC3DQ,QAAQE;QACRE,kBAAkBD,SAASC;IAC7B;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,KAAY;IAC9CX,YAAYS,mBAAmBE;AACjC;AAEA;;;CAGC,GACD,OAAO,SAASC;IACd,MAAMC,SAASZ;IACf,OAAOY,MAAM,CAAChB,qBAAqB;AACrC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { tmpdir } from 'node:os';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
|
-
import { getCliToken } from '../
|
|
4
|
+
import { getCliToken } from '../config/cli/cliUserConfig.js';
|
|
5
5
|
import { isStaging } from '../util/isStaging.js';
|
|
6
6
|
/**
|
|
7
7
|
* Gets the base telemetry information needed for file operations.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/telemetry/getTelemetryBaseInfo.ts"],"sourcesContent":["import {createHash} from 'node:crypto'\nimport {tmpdir} from 'node:os'\nimport {join} from 'node:path'\n\nimport {getCliToken} from '../
|
|
1
|
+
{"version":3,"sources":["../../src/telemetry/getTelemetryBaseInfo.ts"],"sourcesContent":["import {createHash} from 'node:crypto'\nimport {tmpdir} from 'node:os'\nimport {join} from 'node:path'\n\nimport {getCliToken} from '../config/cli/cliUserConfig.js'\nimport {isStaging} from '../util/isStaging.js'\n\n/**\n * Base information needed for telemetry file operations.\n * Contains common data used by both file path generation and pattern matching.\n */\ninterface TelemetryBaseInfo {\n /** Base filename pattern without sessionId suffix */\n basePattern: string\n /** Base directory where telemetry files are stored */\n directory: string\n /** Environment: 'staging' or 'production' */\n environment: string\n /** Hashed token (first 8 chars of SHA256) for privacy */\n hashedToken: string\n}\n\n/**\n * Gets the base telemetry information needed for file operations.\n *\n * This shared utility extracts common logic used by:\n * - `generateTelemetryFilePath` - for generating session-specific file paths\n * - `findTelemetryFiles` - for discovering all telemetry files via glob patterns\n *\n * @returns Promise resolving to base telemetry information\n * @throws Error if no auth token is found\n * @internal\n */\nexport async function getTelemetryBaseInfo(): Promise<TelemetryBaseInfo> {\n const token = await getCliToken()\n if (!token) {\n throw new Error('No auth token found - user must be logged in for telemetry')\n }\n\n const hashedToken = createHash('sha256').update(token).digest('hex').slice(0, 8)\n const environment = isStaging() ? 'staging' : 'production'\n const directory = join(tmpdir(), '.config', 'sanity')\n const basePattern = `telemetry-${hashedToken}-${environment}`\n\n return {\n basePattern,\n directory,\n environment,\n hashedToken,\n }\n}\n"],"names":["createHash","tmpdir","join","getCliToken","isStaging","getTelemetryBaseInfo","token","Error","hashedToken","update","digest","slice","environment","directory","basePattern"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AACtC,SAAQC,MAAM,QAAO,UAAS;AAC9B,SAAQC,IAAI,QAAO,YAAW;AAE9B,SAAQC,WAAW,QAAO,iCAAgC;AAC1D,SAAQC,SAAS,QAAO,uBAAsB;AAiB9C;;;;;;;;;;CAUC,GACD,OAAO,eAAeC;IACpB,MAAMC,QAAQ,MAAMH;IACpB,IAAI,CAACG,OAAO;QACV,MAAM,IAAIC,MAAM;IAClB;IAEA,MAAMC,cAAcR,WAAW,UAAUS,MAAM,CAACH,OAAOI,MAAM,CAAC,OAAOC,KAAK,CAAC,GAAG;IAC9E,MAAMC,cAAcR,cAAc,YAAY;IAC9C,MAAMS,YAAYX,KAAKD,UAAU,WAAW;IAC5C,MAAMa,cAAc,CAAC,UAAU,EAAEN,YAAY,CAAC,EAAEI,aAAa;IAE7D,OAAO;QACLE;QACAD;QACAD;QACAJ;IACF;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
// TODO
|
|
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.
|
|
2
3
|
import { getStudioEnvironmentVariables } from './getStudioEnvironmentVariables.js';
|
|
3
|
-
import { setupBrowserStubs } from './setupBrowserStubs.js';
|
|
4
|
+
import { setupBrowserStubs } from './setupBrowserStubs.js'; // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB
|
|
4
5
|
/**
|
|
5
6
|
* Mocks a browser-like environment for processes in the main thread by:
|
|
6
7
|
* - Injecting browser globals (window, document, ResizeObserver, etc.)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/util/environment/mockBrowserEnvironment.ts"],"sourcesContent":["// TODO
|
|
1
|
+
{"version":3,"sources":["../../../src/util/environment/mockBrowserEnvironment.ts"],"sourcesContent":["// TODO: Consider moving to @sanity/cli — only used there (SDK-983)\n// 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.\nimport {getStudioEnvironmentVariables} from './getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from './setupBrowserStubs.js' // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB\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,wIAAwI;AACxI,SAAQA,6BAA6B,QAAO,qCAAoC;AAChF,SAAQC,iBAAiB,QAAO,yBAAwB,CAAC,2EAA2E;AAEpI;;;;;;;;;;;;;;;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 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/util/environment/setupBrowserStubs.ts"],"sourcesContent":["import {getBrowserStubs} from './stubs.js'\n\n/**\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 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":["getBrowserStubs","setupBrowserStubs","globalThis","window","stubs","mockedGlobalThis","stubbedKeys","originalDescriptors","Map","key","Object","keys","descriptor","getOwnPropertyDescriptor","set","defineProperty","configurable","enumerable","value","writable","push","__mockedBySanity","get"],"mappings":"AAAA,SAAQA,eAAe,QAAO,aAAY;
|
|
1
|
+
{"version":3,"sources":["../../../src/util/environment/setupBrowserStubs.ts"],"sourcesContent":["import {getBrowserStubs} from './stubs.js' // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB\n\n/**\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 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":["getBrowserStubs","setupBrowserStubs","globalThis","window","stubs","mockedGlobalThis","stubbedKeys","originalDescriptors","Map","key","Object","keys","descriptor","getOwnPropertyDescriptor","set","defineProperty","configurable","enumerable","value","writable","push","__mockedBySanity","get"],"mappings":"AAAA,SAAQA,eAAe,QAAO,aAAY,CAAC,2EAA2E;AAEtH;;;;;;;;CAQC,GACD,OAAO,eAAeC;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,MAAMC,QAAQJ;IACd,MAAMK,mBAA4CH;IAClD,MAAMI,cAAwB,EAAE;IAChC,MAAMC,sBAAsB,IAAIC;IAEhC,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAACP,OAAQ;QACpC,sEAAsE;QACtE,8DAA8D;QAC9D,MAAMQ,aAAaF,OAAOG,wBAAwB,CAACX,YAAYO;QAC/D,IAAIG,YAAY;YACdL,oBAAoBO,GAAG,CAACL,KAAKG;YAC7B,mEAAmE;YACnE,sEAAsE;YACtEF,OAAOK,cAAc,CAACb,YAAYO,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,IAAIP,WAAWC,MAAM,EAAE;;QACnBD,WAAWC,MAAM,CAAwCkB,gBAAgB,GAAG;IAChF;IAEA,0BAA0B;IAC1B,OAAO;QACL,uCAAuC;QACvC,IAAInB,WAAWC,MAAM,EAAE;YACrB,OAAO,AAACD,WAAWC,MAAM,CAAwCkB,gBAAgB;QACnF;QAEA,KAAK,MAAMZ,OAAOH,YAAa;YAC7B,MAAMM,aAAaL,oBAAoBe,GAAG,CAACb;YAC3C,IAAIG,YAAY;gBACdF,OAAOK,cAAc,CAACb,YAAYO,KAAKG;YACzC,OAAO;gBACL,OAAOP,gBAAgB,CAACI,IAAI;YAC9B;QACF;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/util/getSanityConfigDir.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"sources":["../../src/util/getSanityConfigDir.ts"],"sourcesContent":["// Pure in memory implementation, widely exported. Please keep it that way.\nimport {homedir} from 'node:os'\nimport {join as joinPath} from 'node:path'\n\nimport {isStaging} from './isStaging.js'\n\nfunction envSuffix(): string {\n return isStaging() ? '-staging' : ''\n}\n\n/**\n * Returns the base Sanity configuration directory for the current user.\n * For persistent user settings (auth tokens, preferences, etc.).\n * Respects `SANITY_INTERNAL_ENV=staging` to isolate staging instances.\n *\n * Layout: `~/.config/sanity{-staging}/`\n *\n * @returns Absolute path to the config directory\n * @internal\n */\nexport function getSanityConfigDir(): string {\n return joinPath(homedir(), '.config', `sanity${envSuffix()}`)\n}\n\n/**\n * Returns the base Sanity data directory for the current user.\n * For ephemeral runtime state (dev-server registries, caches, etc.).\n * Respects `SANITY_INTERNAL_ENV=staging` to isolate staging instances.\n *\n * Layout: `~/.sanity{-staging}/`\n *\n * @returns Absolute path to the data directory\n * @internal\n */\nexport function getSanityDataDir(): string {\n return joinPath(homedir(), `.sanity${envSuffix()}`)\n}\n"],"names":["homedir","join","joinPath","isStaging","envSuffix","getSanityConfigDir","getSanityDataDir"],"mappings":"AAAA,2EAA2E;AAC3E,SAAQA,OAAO,QAAO,UAAS;AAC/B,SAAQC,QAAQC,QAAQ,QAAO,YAAW;AAE1C,SAAQC,SAAS,QAAO,iBAAgB;AAExC,SAASC;IACP,OAAOD,cAAc,aAAa;AACpC;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASE;IACd,OAAOH,SAASF,WAAW,WAAW,CAAC,MAAM,EAAEI,aAAa;AAC9D;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASE;IACd,OAAOJ,SAASF,WAAW,CAAC,OAAO,EAAEI,aAAa;AACpD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/util/getSanityEnvVar.ts"],"sourcesContent":["/**\n * Gets an environment variable with the appropriate Sanity prefix based on whether it's an app or studio.\n *\n * @param suffix - The suffix for the environment variable (e.g., 'SERVER_HOSTNAME')\n * @param isApp - Whether to use the app prefix (SANITY_APP_) or studio prefix (SANITY_STUDIO_)\n * @returns The value of the environment variable, or undefined if not set\n *\n * @example\n * ```ts\n * // For studio: SANITY_STUDIO_SERVER_HOSTNAME\n * const studioHostname = getSanityEnvVar('SERVER_HOSTNAME', false)\n *\n * // For app: SANITY_APP_SERVER_HOSTNAME\n * const appHostname = getSanityEnvVar('SERVER_HOSTNAME', true)\n * ```\n *\n * @internal\n */\nexport function getSanityEnvVar(suffix: string, isApp: boolean): string | undefined {\n const prefix = isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_'\n const envVarName = `${prefix}${suffix}`\n return process.env[envVarName]\n}\n"],"names":["getSanityEnvVar","suffix","isApp","prefix","envVarName","process","env"],"mappings":"AAAA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASA,gBAAgBC,MAAc,EAAEC,KAAc;IAC5D,MAAMC,SAASD,QAAQ,gBAAgB;IACvC,MAAME,aAAa,GAAGD,SAASF,QAAQ;IACvC,OAAOI,QAAQC,GAAG,CAACF,WAAW;AAChC"}
|
|
1
|
+
{"version":3,"sources":["../../src/util/getSanityEnvVar.ts"],"sourcesContent":["// Pure in-memory implementation. Widely exported.\n/**\n * Gets an environment variable with the appropriate Sanity prefix based on whether it's an app or studio.\n *\n * @param suffix - The suffix for the environment variable (e.g., 'SERVER_HOSTNAME')\n * @param isApp - Whether to use the app prefix (SANITY_APP_) or studio prefix (SANITY_STUDIO_)\n * @returns The value of the environment variable, or undefined if not set\n *\n * @example\n * ```ts\n * // For studio: SANITY_STUDIO_SERVER_HOSTNAME\n * const studioHostname = getSanityEnvVar('SERVER_HOSTNAME', false)\n *\n * // For app: SANITY_APP_SERVER_HOSTNAME\n * const appHostname = getSanityEnvVar('SERVER_HOSTNAME', true)\n * ```\n *\n * @internal\n */\nexport function getSanityEnvVar(suffix: string, isApp: boolean): string | undefined {\n const prefix = isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_'\n const envVarName = `${prefix}${suffix}`\n return process.env[envVarName]\n}\n"],"names":["getSanityEnvVar","suffix","isApp","prefix","envVarName","process","env"],"mappings":"AAAA,kDAAkD;AAClD;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASA,gBAAgBC,MAAc,EAAEC,KAAc;IAC5D,MAAMC,SAASD,QAAQ,gBAAgB;IACvC,MAAME,aAAa,GAAGD,SAASF,QAAQ;IACvC,OAAOI,QAAQC,GAAG,CAACF,WAAW;AAChC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/util/getSanityUrl.ts"],"sourcesContent":["/**\n * @internal\n * @returns The Sanity URL for the given path, using the correct domain based on the environment\n */\nexport function getSanityUrl(path = '/') {\n const domain =\n process.env.SANITY_INTERNAL_ENV === 'staging'\n ? 'https://www.sanity.work'\n : 'https://www.sanity.io'\n return `${domain}${path.startsWith('/') ? path : `/${path}`}`\n}\n"],"names":["getSanityUrl","path","domain","process","env","SANITY_INTERNAL_ENV","startsWith"],"mappings":"AAAA;;;CAGC,GACD,OAAO,SAASA,aAAaC,OAAO,GAAG;IACrC,MAAMC,SACJC,QAAQC,GAAG,CAACC,mBAAmB,KAAK,YAChC,4BACA;IACN,OAAO,GAAGH,SAASD,KAAKK,UAAU,CAAC,OAAOL,OAAO,CAAC,CAAC,EAAEA,MAAM,EAAE;AAC/D"}
|
|
1
|
+
{"version":3,"sources":["../../src/util/getSanityUrl.ts"],"sourcesContent":["// Pure in-memory implementation. Widely exported.\n/**\n * @internal\n * @returns The Sanity URL for the given path, using the correct domain based on the environment\n */\nexport function getSanityUrl(path = '/') {\n const domain =\n process.env.SANITY_INTERNAL_ENV === 'staging'\n ? 'https://www.sanity.work'\n : 'https://www.sanity.io'\n return `${domain}${path.startsWith('/') ? path : `/${path}`}`\n}\n"],"names":["getSanityUrl","path","domain","process","env","SANITY_INTERNAL_ENV","startsWith"],"mappings":"AAAA,kDAAkD;AAClD;;;CAGC,GACD,OAAO,SAASA,aAAaC,OAAO,GAAG;IACrC,MAAMC,SACJC,QAAQC,GAAG,CAACC,mBAAmB,KAAK,YAChC,4BACA;IACN,OAAO,GAAGH,SAASD,KAAKK,UAAU,CAAC,OAAOL,OAAO,CAAC,CAAC,EAAEA,MAAM,EAAE;AAC/D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/util/getWorkspace.ts"],"sourcesContent":["/**\n * @internal\n */\nexport function getWorkspace<T extends {name: string}>(workspaces: T[], workspaceName?: string) {\n if (workspaces.length === 0) {\n throw new Error('No workspaces found')\n }\n\n if (workspaces.length === 1) {\n return workspaces[0]\n }\n\n if (!workspaceName) {\n throw new Error(\n `Multiple workspaces found. Please specify which workspace to use with '--workspace' or with the schemaExtraction.workspace config prop. Available workspaces: ${workspaces.map((w) => w.name).join(', ')}`,\n )\n }\n\n const workspace = workspaces.find((w) => w.name === workspaceName)\n\n if (!workspace) {\n throw new Error(\n `Could not find \"${workspaceName}\" workspace. Available workspaces: ${workspaces.map((w) => w.name).join(', ')}`,\n )\n }\n\n return workspace\n}\n"],"names":["getWorkspace","workspaces","workspaceName","length","Error","map","w","name","join","workspace","find"],"mappings":"AAAA;;CAEC,GACD,OAAO,SAASA,aAAuCC,UAAe,EAAEC,aAAsB;IAC5F,IAAID,WAAWE,MAAM,KAAK,GAAG;QAC3B,MAAM,IAAIC,MAAM;IAClB;IAEA,IAAIH,WAAWE,MAAM,KAAK,GAAG;QAC3B,OAAOF,UAAU,CAAC,EAAE;IACtB;IAEA,IAAI,CAACC,eAAe;QAClB,MAAM,IAAIE,MACR,CAAC,8JAA8J,EAAEH,WAAWI,GAAG,CAAC,CAACC,IAAMA,EAAEC,IAAI,EAAEC,IAAI,CAAC,OAAO;IAE/M;IAEA,MAAMC,YAAYR,WAAWS,IAAI,CAAC,CAACJ,IAAMA,EAAEC,IAAI,KAAKL;IAEpD,IAAI,CAACO,WAAW;QACd,MAAM,IAAIL,MACR,CAAC,gBAAgB,EAAEF,cAAc,mCAAmC,EAAED,WAAWI,GAAG,CAAC,CAACC,IAAMA,EAAEC,IAAI,EAAEC,IAAI,CAAC,OAAO;IAEpH;IAEA,OAAOC;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../src/util/getWorkspace.ts"],"sourcesContent":["// Pure in-memory implementation. Widely exported.\n/**\n * @internal\n */\nexport function getWorkspace<T extends {name: string}>(workspaces: T[], workspaceName?: string) {\n if (workspaces.length === 0) {\n throw new Error('No workspaces found')\n }\n\n if (workspaces.length === 1) {\n return workspaces[0]\n }\n\n if (!workspaceName) {\n throw new Error(\n `Multiple workspaces found. Please specify which workspace to use with '--workspace' or with the schemaExtraction.workspace config prop. Available workspaces: ${workspaces.map((w) => w.name).join(', ')}`,\n )\n }\n\n const workspace = workspaces.find((w) => w.name === workspaceName)\n\n if (!workspace) {\n throw new Error(\n `Could not find \"${workspaceName}\" workspace. Available workspaces: ${workspaces.map((w) => w.name).join(', ')}`,\n )\n }\n\n return workspace\n}\n"],"names":["getWorkspace","workspaces","workspaceName","length","Error","map","w","name","join","workspace","find"],"mappings":"AAAA,kDAAkD;AAClD;;CAEC,GACD,OAAO,SAASA,aAAuCC,UAAe,EAAEC,aAAsB;IAC5F,IAAID,WAAWE,MAAM,KAAK,GAAG;QAC3B,MAAM,IAAIC,MAAM;IAClB;IAEA,IAAIH,WAAWE,MAAM,KAAK,GAAG;QAC3B,OAAOF,UAAU,CAAC,EAAE;IACtB;IAEA,IAAI,CAACC,eAAe;QAClB,MAAM,IAAIE,MACR,CAAC,8JAA8J,EAAEH,WAAWI,GAAG,CAAC,CAACC,IAAMA,EAAEC,IAAI,EAAEC,IAAI,CAAC,OAAO;IAE/M;IAEA,MAAMC,YAAYR,WAAWS,IAAI,CAAC,CAACJ,IAAMA,EAAEC,IAAI,KAAKL;IAEpD,IAAI,CAACO,WAAW;QACd,MAAM,IAAIL,MACR,CAAC,gBAAgB,EAAEF,cAAc,mCAAmC,EAAED,WAAWI,GAAG,CAAC,CAACC,IAAMA,EAAEC,IAAI,EAAEC,IAAI,CAAC,OAAO;IAEpH;IAEA,OAAOC;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
2
2
|
import { createJiti } from 'jiti';
|
|
3
|
-
import { subdebug } from '../debug.js';
|
|
3
|
+
import { subdebug } from '../_exports/debug.js';
|
|
4
4
|
const debug = subdebug('importModule');
|
|
5
5
|
/**
|
|
6
6
|
* Imports a module using jiti and returns its exports.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/util/importModule.ts"],"sourcesContent":["import {fileURLToPath, pathToFileURL} from 'node:url'\n\nimport {createJiti, type JitiResolveOptions} from 'jiti'\n\nimport {subdebug} from '../debug.js'\n\ninterface ImportModuleOptions {\n /**\n * Whether to return the default export of the module.\n * Default: true\n */\n default?: boolean\n\n /**\n * Path to the tsconfig file to use for the import. If not provided, the tsconfig\n * will be inferred from the nearest `tsconfig.json` file.\n */\n tsconfigPath?: string\n}\n\nconst debug = subdebug('importModule')\n\n/**\n * Imports a module using jiti and returns its exports.\n * This is a thin wrapper around tsx to allow swapping out the underlying implementation in the future if needed.\n *\n * @param filePath - Path to the module to import.\n * @param options - Options for the importModule function.\n * @returns The exported module.\n *\n * @internal\n */\nexport async function importModule<T = unknown>(\n filePath: string | URL,\n options: ImportModuleOptions = {},\n): Promise<T> {\n const {default: returnDefault = true, tsconfigPath} = options\n\n const jiti = createJiti(import.meta.url, {\n debug: debug.enabled,\n tsconfigPaths: typeof tsconfigPath === 'string' ? tsconfigPath : true,\n })\n\n const fileURL = typeof filePath === 'string' ? pathToFileURL(filePath) : filePath\n\n debug(`Loading module: ${fileURLToPath(fileURL)}`, {tsconfigPath})\n\n const jitiOptions: JitiResolveOptions & {default?: true} = {}\n\n // If the default option is true, add it to the jiti options\n if (returnDefault) {\n jitiOptions.default = true\n }\n\n return jiti.import<T>(fileURLToPath(fileURL), jitiOptions)\n}\n"],"names":["fileURLToPath","pathToFileURL","createJiti","subdebug","debug","importModule","filePath","options","default","returnDefault","tsconfigPath","jiti","url","enabled","tsconfigPaths","fileURL","jitiOptions","import"],"mappings":"AAAA,SAAQA,aAAa,EAAEC,aAAa,QAAO,WAAU;AAErD,SAAQC,UAAU,QAAgC,OAAM;AAExD,SAAQC,QAAQ,QAAO,
|
|
1
|
+
{"version":3,"sources":["../../src/util/importModule.ts"],"sourcesContent":["import {fileURLToPath, pathToFileURL} from 'node:url'\n\nimport {createJiti, type JitiResolveOptions} from 'jiti'\n\nimport {subdebug} from '../_exports/debug.js'\n\ninterface ImportModuleOptions {\n /**\n * Whether to return the default export of the module.\n * Default: true\n */\n default?: boolean\n\n /**\n * Path to the tsconfig file to use for the import. If not provided, the tsconfig\n * will be inferred from the nearest `tsconfig.json` file.\n */\n tsconfigPath?: string\n}\n\nconst debug = subdebug('importModule')\n\n/**\n * Imports a module using jiti and returns its exports.\n * This is a thin wrapper around tsx to allow swapping out the underlying implementation in the future if needed.\n *\n * @param filePath - Path to the module to import.\n * @param options - Options for the importModule function.\n * @returns The exported module.\n *\n * @internal\n */\nexport async function importModule<T = unknown>(\n filePath: string | URL,\n options: ImportModuleOptions = {},\n): Promise<T> {\n const {default: returnDefault = true, tsconfigPath} = options\n\n const jiti = createJiti(import.meta.url, {\n debug: debug.enabled,\n tsconfigPaths: typeof tsconfigPath === 'string' ? tsconfigPath : true,\n })\n\n const fileURL = typeof filePath === 'string' ? pathToFileURL(filePath) : filePath\n\n debug(`Loading module: ${fileURLToPath(fileURL)}`, {tsconfigPath})\n\n const jitiOptions: JitiResolveOptions & {default?: true} = {}\n\n // If the default option is true, add it to the jiti options\n if (returnDefault) {\n jitiOptions.default = true\n }\n\n return jiti.import<T>(fileURLToPath(fileURL), jitiOptions)\n}\n"],"names":["fileURLToPath","pathToFileURL","createJiti","subdebug","debug","importModule","filePath","options","default","returnDefault","tsconfigPath","jiti","url","enabled","tsconfigPaths","fileURL","jitiOptions","import"],"mappings":"AAAA,SAAQA,aAAa,EAAEC,aAAa,QAAO,WAAU;AAErD,SAAQC,UAAU,QAAgC,OAAM;AAExD,SAAQC,QAAQ,QAAO,uBAAsB;AAgB7C,MAAMC,QAAQD,SAAS;AAEvB;;;;;;;;;CASC,GACD,OAAO,eAAeE,aACpBC,QAAsB,EACtBC,UAA+B,CAAC,CAAC;IAEjC,MAAM,EAACC,SAASC,gBAAgB,IAAI,EAAEC,YAAY,EAAC,GAAGH;IAEtD,MAAMI,OAAOT,WAAW,YAAYU,GAAG,EAAE;QACvCR,OAAOA,MAAMS,OAAO;QACpBC,eAAe,OAAOJ,iBAAiB,WAAWA,eAAe;IACnE;IAEA,MAAMK,UAAU,OAAOT,aAAa,WAAWL,cAAcK,YAAYA;IAEzEF,MAAM,CAAC,gBAAgB,EAAEJ,cAAce,UAAU,EAAE;QAACL;IAAY;IAEhE,MAAMM,cAAqD,CAAC;IAE5D,4DAA4D;IAC5D,IAAIP,eAAe;QACjBO,YAAYR,OAAO,GAAG;IACxB;IAEA,OAAOG,KAAKM,MAAM,CAAIjB,cAAce,UAAUC;AAChD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/util/promisifyWorker.ts"],"sourcesContent":["import {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {subdebug} from '../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,
|
|
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,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,SAASS,qBAAqBP,GAAG;YAClET,UAAU;YACVU,aAAaT;YACbb,MAAM,GAAGO,SAAS,gBAAgB,EAAEc,IAAIE,OAAO,EAAE,EAAEF;YACnDV,OAAO,IAAIK,MAAM,CAAC,sCAAsC,EAAEK,KAAK;YAC/DI;QACF;QACAnB,OAAOa,WAAW,CAAC,WAAW,SAASU,gBAAgBN,OAAO;YAC5DX,UAAU;YACVU,aAAaT;YACbb,MAAM,GAAGO,SAAS,WAAW,CAAC,EAAEgB;YAChCb,QAAQa;YACRE;QACF;QAEA,SAASA;YACPK,aAAa,IAAMxB,OAAOW,SAAS;YACnCX,OAAOY,kBAAkB;QAC3B;IACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli-core",
|
|
3
|
-
"version": "2.1
|
|
3
|
+
"version": "2.2.1",
|
|
4
4
|
"description": "Sanity CLI core package",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -33,18 +33,66 @@
|
|
|
33
33
|
"source": "./src/_exports/index.ts",
|
|
34
34
|
"default": "./dist/_exports/index.js"
|
|
35
35
|
},
|
|
36
|
-
"./
|
|
37
|
-
"source": "./src/
|
|
38
|
-
"default": "./dist/
|
|
36
|
+
"./apiClient": {
|
|
37
|
+
"source": "./src/apiClient.ts",
|
|
38
|
+
"default": "./dist/apiClient.js"
|
|
39
39
|
},
|
|
40
|
-
"./
|
|
41
|
-
"source": "./src/_exports/
|
|
42
|
-
"default": "./dist/_exports/
|
|
40
|
+
"./browser": {
|
|
41
|
+
"source": "./src/_exports/browser.ts",
|
|
42
|
+
"default": "./dist/_exports/browser.js"
|
|
43
|
+
},
|
|
44
|
+
"./config": {
|
|
45
|
+
"source": "./src/_exports/config.ts",
|
|
46
|
+
"default": "./dist/_exports/config.js"
|
|
47
|
+
},
|
|
48
|
+
"./debug": {
|
|
49
|
+
"source": "./src/_exports/debug.ts",
|
|
50
|
+
"default": "./dist/_exports/debug.js"
|
|
51
|
+
},
|
|
52
|
+
"./errors": {
|
|
53
|
+
"source": "./src/_exports/errors.ts",
|
|
54
|
+
"default": "./dist/_exports/errors.js"
|
|
43
55
|
},
|
|
44
56
|
"./package-manager": {
|
|
45
57
|
"source": "./src/_exports/package-manager.ts",
|
|
46
58
|
"default": "./dist/_exports/package-manager.js"
|
|
47
59
|
},
|
|
60
|
+
"./request": {
|
|
61
|
+
"source": "./src/_exports/request.ts",
|
|
62
|
+
"default": "./dist/_exports/request.js"
|
|
63
|
+
},
|
|
64
|
+
"./schemas": {
|
|
65
|
+
"source": "./src/_exports/schemas.ts",
|
|
66
|
+
"default": "./dist/_exports/schemas.js"
|
|
67
|
+
},
|
|
68
|
+
"./tasks": {
|
|
69
|
+
"source": "./src/_exports/tasks.ts",
|
|
70
|
+
"default": "./dist/_exports/tasks.js"
|
|
71
|
+
},
|
|
72
|
+
"./telemetry": {
|
|
73
|
+
"source": "./src/_exports/telemetry.ts",
|
|
74
|
+
"default": "./dist/_exports/telemetry.js"
|
|
75
|
+
},
|
|
76
|
+
"./types": {
|
|
77
|
+
"source": "./src/_exports/types.ts",
|
|
78
|
+
"default": "./dist/_exports/types.js"
|
|
79
|
+
},
|
|
80
|
+
"./util": {
|
|
81
|
+
"source": "./src/_exports/util.ts",
|
|
82
|
+
"default": "./dist/_exports/util.js"
|
|
83
|
+
},
|
|
84
|
+
"./ux": {
|
|
85
|
+
"source": "./src/_exports/ux.ts",
|
|
86
|
+
"default": "./dist/_exports/ux.js"
|
|
87
|
+
},
|
|
88
|
+
"./SanityCommand": {
|
|
89
|
+
"source": "./src/SanityCommand.ts",
|
|
90
|
+
"default": "./dist/SanityCommand.js"
|
|
91
|
+
},
|
|
92
|
+
"./ExitCodes": {
|
|
93
|
+
"source": "./src/exitCodes.ts",
|
|
94
|
+
"default": "./dist/exitCodes.js"
|
|
95
|
+
},
|
|
48
96
|
"./package.json": "./package.json"
|
|
49
97
|
},
|
|
50
98
|
"publishConfig": {
|
|
@@ -67,7 +115,7 @@
|
|
|
67
115
|
"read-package-up": "^12.0.0",
|
|
68
116
|
"rxjs": "^7.8.2",
|
|
69
117
|
"tsx": "^4.22.4",
|
|
70
|
-
"vite": "^8.1.
|
|
118
|
+
"vite": "^8.1.3",
|
|
71
119
|
"vite-node": "^6.0.0",
|
|
72
120
|
"zod": "^4.4.3"
|
|
73
121
|
},
|
package/dist/debug.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/debug.ts"],"sourcesContent":["import debugIt from 'debug'\n\n/**\n * `debug` instance for the CLI\n *\n * @internal\n */\nexport const debug = debugIt('sanity:cli')\n\n/**\n * Get a `debug` instance which extends the CLI debug instance with the given namespace,\n * eg namespace would be `sanity:cli:<providedNamespace>`\n *\n * @param namespace - The namespace to extend the CLI debug instance with\n * @returns The extended `debug` instance\n */\nexport const subdebug = (namespace: string) => debug.extend(namespace)\n"],"names":["debugIt","debug","subdebug","namespace","extend"],"mappings":"AAAA,OAAOA,aAAa,QAAO;AAE3B;;;;CAIC,GACD,OAAO,MAAMC,QAAQD,QAAQ,cAAa;AAE1C;;;;;;CAMC,GACD,OAAO,MAAME,WAAW,CAACC,YAAsBF,MAAMG,MAAM,CAACD,WAAU"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/cliTokenCache.ts"],"sourcesContent":["/**\n * Module-level cache for the CLI auth token, shared between\n * `getCliToken` (reads/writes) and `setCliUserConfig` (invalidates).\n *\n * Extracted into its own module to avoid a circular dependency\n * between `cliUserConfig.ts` and `getCliToken.ts`.\n */\nlet cachedToken: string | undefined\n\nexport function getCachedToken(): string | undefined {\n return cachedToken\n}\n\nexport function setCachedToken(token: string | undefined): void {\n cachedToken = token\n}\n\n/**\n * Clear the in-process token cache so the next `getCliToken()` call\n * re-reads from disk or the environment.\n *\n * Called automatically by `setCliUserConfig('authToken', ...)`.\n *\n * @internal\n */\nexport function clearCliTokenCache(): void {\n cachedToken = undefined\n}\n"],"names":["cachedToken","getCachedToken","setCachedToken","token","clearCliTokenCache","undefined"],"mappings":"AAAA;;;;;;CAMC,GACD,IAAIA;AAEJ,OAAO,SAASC;IACd,OAAOD;AACT;AAEA,OAAO,SAASE,eAAeC,KAAyB;IACtDH,cAAcG;AAChB;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC;IACdJ,cAAcK;AAChB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/cliUserConfig.ts"],"sourcesContent":["import {mkdirSync} from 'node:fs'\nimport {dirname, join as joinPath} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {debug} from '../debug.js'\nimport {getSanityConfigDir} from '../util/getSanityConfigDir.js'\nimport {readJsonFileSync} from '../util/readJsonFileSync.js'\nimport {writeJsonFileSync} from '../util/writeJsonFileSync.js'\nimport {clearCliTokenCache} from './cliTokenCache.js'\n\nconst cliUserConfigSchema = {\n authToken: z.optional(z.string()),\n}\n\n/**\n * Set the config value for the given property.\n * Validates that the passed value adheres to the defined CLI config schema.\n *\n * @param prop - The property to set the value for\n * @param value - The value to set\n * @internal\n */\nexport function setCliUserConfig(prop: 'authToken', value: string | undefined): void {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(value)\n if (!result.success) {\n const message = result.error.issues\n .map(({message, path}) => `[${path.join('.')}] ${message}`)\n .join('\\n')\n\n throw new Error(`Invalid value for config property \"${prop}\": ${message}`)\n }\n\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n\n // When value is undefined, explicitly delete the key rather than relying\n // on JSON.stringify silently dropping undefined values.\n if (value === undefined) {\n const {[prop]: _, ...rest} = config\n writeJsonFileSync(configPath, rest, {pretty: true})\n } else {\n writeJsonFileSync(configPath, {...config, [prop]: value}, {pretty: true})\n }\n\n // Invalidate the in-process token cache so subsequent getCliToken() calls\n // pick up the new value from disk.\n clearCliTokenCache()\n}\n\n/**\n * Get the config value for the given property\n *\n * @param prop - The property to get the value for\n * @returns The value of the given property\n * @internal\n */\nexport function getCliUserConfig(prop: 'authToken'): string | undefined {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(config[prop])\n if (!result.success) {\n debug('Ignoring invalid stored value for \"%s\", returning undefined', prop)\n return undefined\n }\n\n return result.data\n}\n\n/**\n * A raw key-value store for CLI user configuration.\n * Unlike the typed `getCliUserConfig`/`setCliUserConfig`, this operates on\n * arbitrary keys without schema validation.\n *\n * @public\n */\nexport interface ConfigStore {\n /** Remove a key from the config file. */\n delete: (key: string) => void\n /** Read a value by key. Returns `undefined` if the key does not exist. */\n get: (key: string) => unknown\n /** Write a value by key, merging it into the existing config. */\n set: (key: string, value: unknown) => void\n}\n\n/**\n * Get a key-value store backed by the CLI user configuration file\n * (`~/.config/sanity/config.json`).\n *\n * Each call to `get`, `set`, or `delete` performs a full synchronous\n * read-modify-write cycle. This is intentional: sync I/O prevents\n * intra-process race conditions that occurred with the previous async\n * (configstore-backed) implementation.\n *\n * Note: there is no file-level locking, so concurrent writes from\n * separate CLI processes could still conflict. In practice this is\n * unlikely since CLI config writes are rare and user-initiated.\n *\n * @returns A {@link ConfigStore} for the CLI config file\n * @public\n */\nexport function getUserConfig(): ConfigStore {\n return {\n get(key: string): unknown {\n const config = readConfig()\n return config[key]\n },\n\n set(key: string, value: unknown): void {\n const config = readConfig()\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n writeJsonFileSync(configPath, {...config, [key]: value}, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n\n // No mkdirSync needed: if readConfig() succeeded the directory already exists.\n delete(key: string): void {\n const config = readConfig()\n if (!(key in config)) return\n const {[key]: _, ...rest} = config\n writeJsonFileSync(getCliUserConfigPath(), rest, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n }\n}\n\n/**\n * Read the whole configuration from file system. If the file does not exist,\n * is corrupt, or otherwise unreadable, an empty object is returned. This is\n * intentional: the config only holds recoverable data (auth tokens, telemetry\n * consent) so silently resetting is preferable to blocking the user.\n *\n * @returns The whole CLI configuration.\n * @internal\n */\nfunction readConfig(): Record<string, unknown> {\n try {\n const config = readJsonFileSync(getCliUserConfigPath())\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error('Invalid config file - expected an object')\n }\n return config\n } catch (err: unknown) {\n debug('Failed to read CLI config file: %s', err instanceof Error ? err.message : `${err}`)\n return {}\n }\n}\n\n/**\n * Get the file system location for the CLI user configuration file.\n * Takes into account the active environment (staging vs production).\n * The file is located in the user's home directory under the `.config` directory.\n *\n * @returns The path to the CLI configuration file.\n * @internal\n */\nfunction getCliUserConfigPath() {\n return process.env.SANITY_CLI_CONFIG_PATH || joinPath(getSanityConfigDir(), 'config.json')\n}\n"],"names":["mkdirSync","dirname","join","joinPath","z","debug","getSanityConfigDir","readJsonFileSync","writeJsonFileSync","clearCliTokenCache","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","config","readConfig","result","safeParse","success","message","error","issues","map","path","Error","configPath","getCliUserConfigPath","recursive","undefined","_","rest","pretty","getCliUserConfig","data","getUserConfig","get","key","set","delete","Array","isArray","err","process","env","SANITY_CLI_CONFIG_PATH"],"mappings":"AAAA,SAAQA,SAAS,QAAO,UAAS;AACjC,SAAQC,OAAO,EAAEC,QAAQC,QAAQ,QAAO,YAAW;AAEnD,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,kBAAkB,QAAO,gCAA+B;AAChE,SAAQC,gBAAgB,QAAO,8BAA6B;AAC5D,SAAQC,iBAAiB,QAAO,+BAA8B;AAC9D,SAAQC,kBAAkB,QAAO,qBAAoB;AAErD,MAAMC,sBAAsB;IAC1BC,WAAWP,EAAEQ,QAAQ,CAACR,EAAES,MAAM;AAChC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,iBAAiBC,IAAiB,EAAEC,KAAyB;IAC3E,MAAMC,SAASC;I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C;YACf,MAAMU,aAAaC;YACnB7B,UAAUC,QAAQ2B,aAAa;gBAACE,WAAW;YAAI;YAC/CtB,kBAAkBoB,YAAY;gBAAC,GAAGX,MAAM;gBAAE,CAACsB,IAAI,EAAEvB;YAAK,GAAG;gBAACkB,QAAQ;YAAI;YACtE,IAAIK,QAAQ,aAAa9B;QAC3B;QAEA,+EAA+E;QAC/EgC,QAAOF,GAAW;YAChB,MAAMtB,SAASC;YACf,IAAI,CAAEqB,CAAAA,OAAOtB,MAAK,GAAI;YACtB,MAAM,EAAC,CAACsB,IAAI,EAAEP,CAAC,EAAE,GAAGC,MAAK,GAAGhB;YAC5BT,kBAAkBqB,wBAAwBI,MAAM;gBAACC,QAAQ;YAAI;YAC7D,IAAIK,QAAQ,aAAa9B;QAC3B;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,SAASS;IACP,IAAI;QACF,MAAMD,SAASV,iBAAiBsB;QAChC,IAAI,CAACZ,UAAU,OAAOA,WAAW,YAAYyB,MAAMC,OAAO,CAAC1B,SAAS;YAClE,MAAM,IAAIU,MAAM;QAClB;QACA,OAAOV;IACT,EAAE,OAAO2B,KAAc;QACrBvC,MAAM,sCAAsCuC,eAAejB,QAAQiB,IAAItB,OAAO,GAAG,GAAGsB,KAAK;QACzF,OAAO,CAAC;IACV;AACF;AAEA;;;;;;;CAOC,GACD,SAASf;IACP,OAAOgB,QAAQC,GAAG,CAACC,sBAAsB,IAAI5C,SAASG,sBAAsB;AAC9E"}
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { getCachedToken, setCachedToken } from './cliTokenCache.js';
|
|
2
|
-
import { getCliUserConfig } from './cliUserConfig.js';
|
|
3
|
-
// Re-export so existing consumers don't break
|
|
4
|
-
export { clearCliTokenCache } from './cliTokenCache.js';
|
|
5
|
-
/**
|
|
6
|
-
* Get the CLI authentication token from the environment or the config file
|
|
7
|
-
*
|
|
8
|
-
* @returns A promise that resolves to a CLI token, or undefined if no token is found
|
|
9
|
-
* @internal
|
|
10
|
-
*/ export async function getCliToken() {
|
|
11
|
-
const cached = getCachedToken();
|
|
12
|
-
if (cached !== undefined) {
|
|
13
|
-
return cached;
|
|
14
|
-
}
|
|
15
|
-
const token = process.env.SANITY_AUTH_TOKEN;
|
|
16
|
-
if (token) {
|
|
17
|
-
const trimmed = token.trim();
|
|
18
|
-
setCachedToken(trimmed);
|
|
19
|
-
return trimmed;
|
|
20
|
-
}
|
|
21
|
-
const configToken = getCliUserConfig('authToken');
|
|
22
|
-
setCachedToken(configToken);
|
|
23
|
-
return configToken;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
//# sourceMappingURL=getCliToken.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/getCliToken.ts"],"sourcesContent":["import {getCachedToken, setCachedToken} from './cliTokenCache.js'\nimport {getCliUserConfig} from './cliUserConfig.js'\n\n// Re-export so existing consumers don't break\nexport {clearCliTokenCache} from './cliTokenCache.js'\n\n/**\n * Get the CLI authentication token from the environment or the config file\n *\n * @returns A promise that resolves to a CLI token, or undefined if no token is found\n * @internal\n */\nexport async function getCliToken(): Promise<string | undefined> {\n const cached = getCachedToken()\n if (cached !== undefined) {\n return cached\n }\n\n const token = process.env.SANITY_AUTH_TOKEN\n if (token) {\n const trimmed = token.trim()\n setCachedToken(trimmed)\n return trimmed\n }\n\n const configToken = getCliUserConfig('authToken')\n setCachedToken(configToken)\n return configToken\n}\n"],"names":["getCachedToken","setCachedToken","getCliUserConfig","clearCliTokenCache","getCliToken","cached","undefined","token","process","env","SANITY_AUTH_TOKEN","trimmed","trim","configToken"],"mappings":"AAAA,SAAQA,cAAc,EAAEC,cAAc,QAAO,qBAAoB;AACjE,SAAQC,gBAAgB,QAAO,qBAAoB;AAEnD,8CAA8C;AAC9C,SAAQC,kBAAkB,QAAO,qBAAoB;AAErD;;;;;CAKC,GACD,OAAO,eAAeC;IACpB,MAAMC,SAASL;IACf,IAAIK,WAAWC,WAAW;QACxB,OAAOD;IACT;IAEA,MAAME,QAAQC,QAAQC,GAAG,CAACC,iBAAiB;IAC3C,IAAIH,OAAO;QACT,MAAMI,UAAUJ,MAAMK,IAAI;QAC1BX,eAAeU;QACf,OAAOA;IACT;IAEA,MAAME,cAAcX,iBAAiB;IACrCD,eAAeY;IACf,OAAOA;AACT"}
|
|
File without changes
|
|
File without changes
|