@sanity/cli-core 3.6.0 → 3.6.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 +5 -5
- package/dist/_exports/config.d.ts +1 -1
- package/dist/_exports/index.d.ts +4 -4
- package/dist/_exports/schemas.d.ts +1 -1
- package/dist/_exports/tasks.d.ts +1 -1
- package/dist/_exports/types.d.ts +1 -1
- package/dist/_exports/util.d.ts +1 -1
- package/dist/config/cli/getCliConfigSync.js +13 -15
- package/dist/config/cli/getCliConfigSync.js.map +1 -1
- package/dist/config/studio/getStudioWorkspaces.js +0 -1
- package/dist/config/studio/getStudioWorkspaces.js.map +1 -1
- package/dist/{findStudioConfigPath-BV4DCesQ.d.ts → findStudioConfigPath-CeSHbV0N.d.ts} +2 -2
- package/dist/loaders/studio/studioModuleEvaluator.js +116 -0
- package/dist/loaders/studio/studioModuleEvaluator.js.map +1 -0
- package/dist/loaders/studio/studioWorkerLoader.worker.js +43 -45
- package/dist/loaders/studio/studioWorkerLoader.worker.js.map +1 -1
- package/dist/loaders/tsx/tsxWorkerTask.js +2 -2
- package/dist/loaders/tsx/tsxWorkerTask.js.map +1 -1
- package/dist/manifest.js +3 -3
- package/dist/manifest.js.map +1 -1
- package/dist/{safeStructuredClone-CWB0MXmH.d.ts → safeStructuredClone-DAFcnqtc.d.ts} +2 -3
- package/dist/{schemas-D1LxkXeZ.d.ts → schemas-BUfBJffI.d.ts} +4 -4
- package/dist/{tsxWorkerTask-MHWcAqb6.d.ts → tsxWorkerTask-cAuOb_uk.d.ts} +3 -3
- package/dist/util/importModule.js +1 -2
- package/dist/util/importModule.js.map +1 -1
- package/package.json +5 -7
package/README.md
CHANGED
|
@@ -125,11 +125,11 @@ Zod schemas for CLI configuration and app manifests.
|
|
|
125
125
|
|
|
126
126
|
Worker-based task runners.
|
|
127
127
|
|
|
128
|
-
| Export | Description
|
|
129
|
-
| ------------------------ |
|
|
130
|
-
| `studioWorkerTask(task)` | Run a task in the studio worker.
|
|
131
|
-
| `createStudioWorker()` | Create a studio worker instance.
|
|
132
|
-
| `tsxWorkerTask(task)` | Run a TypeScript task
|
|
128
|
+
| Export | Description |
|
|
129
|
+
| ------------------------ | ---------------------------------- |
|
|
130
|
+
| `studioWorkerTask(task)` | Run a task in the studio worker. |
|
|
131
|
+
| `createStudioWorker()` | Create a studio worker instance. |
|
|
132
|
+
| `tsxWorkerTask(task)` | Run a TypeScript task in a worker. |
|
|
133
133
|
|
|
134
134
|
## `@sanity/cli-core/telemetry`
|
|
135
135
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as ConfigStore, o as TypeGenConfig, r as CliConfig } from "../cliConfig-DUt8uaF6.js";
|
|
2
|
-
import { _ as CliTokenInfo, a as getStudioWorkspaces, c as findProjectRoot, d as getCliConfigUncached, f as getCliToken, g as setCliUserConfig, h as getUserConfig, i as isStudioConfig, l as getCliConfigSync, m as getCliUserConfig, n as tryFindStudioConfigPath, o as getStudioConfig, p as getCliTokenInfo, r as findPathForFiles, s as findProjectRootSync, t as findStudioConfigPath, u as getCliConfig, v as clearCliTokenCache } from "../findStudioConfigPath-
|
|
2
|
+
import { _ as CliTokenInfo, a as getStudioWorkspaces, c as findProjectRoot, d as getCliConfigUncached, f as getCliToken, g as setCliUserConfig, h as getUserConfig, i as isStudioConfig, l as getCliConfigSync, m as getCliUserConfig, n as tryFindStudioConfigPath, o as getStudioConfig, p as getCliTokenInfo, r as findPathForFiles, s as findProjectRootSync, t as findStudioConfigPath, u as getCliConfig, v as clearCliTokenCache } from "../findStudioConfigPath-CeSHbV0N.js";
|
|
3
3
|
import { n as isWorkbenchApp, r as parseWorkbenchCliConfig } from "../workbenchApp-DVKwpTyU.js";
|
|
4
4
|
import { a as getSanityDataDir, i as getSanityConfigDir, n as getSanityUrl, r as getSanityEnvVar, t as getWorkspace } from "../getWorkspace-CU32E6Uo.js";
|
|
5
5
|
export { type CliConfig, type CliTokenInfo, type ConfigStore, type TypeGenConfig, clearCliTokenCache, findPathForFiles, findProjectRoot, findProjectRootSync, findStudioConfigPath, getCliConfig, getCliConfigSync, getCliConfigUncached, getCliToken, getCliTokenInfo, getCliUserConfig, getSanityConfigDir, getSanityDataDir, getSanityEnvVar, getSanityUrl, getStudioConfig, getStudioWorkspaces, getUserConfig, getWorkspace, isStudioConfig, isWorkbenchApp, parseWorkbenchCliConfig, setCliUserConfig, tryFindStudioConfigPath };
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -5,20 +5,20 @@ import { n as ConsentInformation, r as TelemetryUserProperties, t as CLITelemetr
|
|
|
5
5
|
import { n as RequireProps, r as SanityOrgUser, t as Output } from "../types-CwJLTYDj.js";
|
|
6
6
|
import { SanityCommand, SanityCommandInterface } from "../SanityCommand.js";
|
|
7
7
|
import { t as mockBrowserEnvironment } from "../mockBrowserEnvironment-BjFQPb2W.js";
|
|
8
|
-
import { _ as CliTokenInfo, a as getStudioWorkspaces, c as findProjectRoot, d as getCliConfigUncached, f as getCliToken, g as setCliUserConfig, h as getUserConfig, i as isStudioConfig, l as getCliConfigSync, m as getCliUserConfig, n as tryFindStudioConfigPath, o as getStudioConfig, p as getCliTokenInfo, r as findPathForFiles, s as findProjectRootSync, t as findStudioConfigPath, u as getCliConfig, v as clearCliTokenCache } from "../findStudioConfigPath-
|
|
8
|
+
import { _ as CliTokenInfo, a as getStudioWorkspaces, c as findProjectRoot, d as getCliConfigUncached, f as getCliToken, g as setCliUserConfig, h as getUserConfig, i as isStudioConfig, l as getCliConfigSync, m as getCliUserConfig, n as tryFindStudioConfigPath, o as getStudioConfig, p as getCliTokenInfo, r as findPathForFiles, s as findProjectRootSync, t as findStudioConfigPath, u as getCliConfig, v as clearCliTokenCache } from "../findStudioConfigPath-CeSHbV0N.js";
|
|
9
9
|
import { n as isWorkbenchApp, t as ApplicationType } from "../workbenchApp-DVKwpTyU.js";
|
|
10
10
|
import { a as getSanityDataDir, i as getSanityConfigDir, n as getSanityUrl, r as getSanityEnvVar, t as getWorkspace } from "../getWorkspace-CU32E6Uo.js";
|
|
11
11
|
import { debug, subdebug } from "./debug.js";
|
|
12
12
|
import { t as NonInteractiveError } from "../NonInteractiveError-CSLT5y93.js";
|
|
13
13
|
import { i as isNotFoundError, n as isProjectRootNotFoundError, r as NotFoundError, t as ProjectRootNotFoundError } from "../ProjectRootNotFoundError-RgthN9uy.js";
|
|
14
14
|
import { exitCodes } from "../exitCodes.js";
|
|
15
|
-
import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-
|
|
15
|
+
import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-cAuOb_uk.js";
|
|
16
16
|
import { a as getCliTelemetry, i as clearCliTelemetry, n as getTelemetryBaseInfo, o as reportCliTraceError, r as CLI_TELEMETRY_SYMBOL, s as setCliTelemetry, t as noopLogger } from "../noopTelemetry-BJRIvASI.js";
|
|
17
|
-
import { a as isCi, i as isInteractive, n as normalizePath, o as importModule, r as isStaging, s as doImport, t as safeStructuredClone } from "../safeStructuredClone-
|
|
17
|
+
import { a as isCi, i as isInteractive, n as normalizePath, o as importModule, r as isStaging, s as doImport, t as safeStructuredClone } from "../safeStructuredClone-DAFcnqtc.js";
|
|
18
18
|
import { a as getLocalPackageVersion, i as getLocalPackageDir, n as resolveLocalPackageFrom, r as resolveLocalPackagePath, t as resolveLocalPackage } from "../resolveLocalPackage-Dr-TNTyk.js";
|
|
19
19
|
import { n as ReadPackageJsonOptions, r as readPackageJson, t as PackageJson } from "../readPackageJson-Cr_lbjVR.js";
|
|
20
20
|
import { n as colorizeJson, t as getTimer } from "../timer-Dwu2TIgB.js";
|
|
21
|
-
import { i as studioManifestSchema, n as StudioManifest, r as coreAppManifestSchema, t as CoreAppManifest } from "../schemas-
|
|
21
|
+
import { i as studioManifestSchema, n as StudioManifest, r as coreAppManifestSchema, t as CoreAppManifest } from "../schemas-BUfBJffI.js";
|
|
22
22
|
import { WorkerOptions } from "node:worker_threads";
|
|
23
23
|
interface PromisifyWorkerOptions extends WorkerOptions {
|
|
24
24
|
/**
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as cliConfigSchema, i as studioManifestSchema, n as StudioManifest, r as coreAppManifestSchema, t as CoreAppManifest } from "../schemas-
|
|
1
|
+
import { a as cliConfigSchema, i as studioManifestSchema, n as StudioManifest, r as coreAppManifestSchema, t as CoreAppManifest } from "../schemas-BUfBJffI.js";
|
|
2
2
|
export { type CoreAppManifest, type StudioManifest, cliConfigSchema, coreAppManifestSchema, studioManifestSchema };
|
package/dist/_exports/tasks.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-
|
|
1
|
+
import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-cAuOb_uk.js";
|
|
2
2
|
export { createStudioWorker, studioWorkerTask, tsxWorkerTask };
|
package/dist/_exports/types.d.ts
CHANGED
|
@@ -5,5 +5,5 @@ import { n as RequireProps, r as SanityOrgUser, t as Output } from "../types-CwJ
|
|
|
5
5
|
import { SanityCommandInterface } from "../SanityCommand.js";
|
|
6
6
|
import { t as ApplicationType } from "../workbenchApp-DVKwpTyU.js";
|
|
7
7
|
import { n as ReadPackageJsonOptions, t as PackageJson } from "../readPackageJson-Cr_lbjVR.js";
|
|
8
|
-
import { n as StudioManifest, t as CoreAppManifest } from "../schemas-
|
|
8
|
+
import { n as StudioManifest, t as CoreAppManifest } from "../schemas-BUfBJffI.js";
|
|
9
9
|
export type { ApplicationType, CLITelemetryStore, CliConfig, ConfigStore, ConsentInformation, CoreAppManifest, Output, PackageJson, ProjectRootResult, ReactCompilerConfig, ReadPackageJsonOptions, RequireProps, SanityCommandInterface, SanityOrgUser, StudioManifest, TelemetryUserProperties, TypeGenConfig, UserViteConfig };
|
package/dist/_exports/util.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as getSanityDataDir, i as getSanityConfigDir, n as getSanityUrl, r as getSanityEnvVar, t as getWorkspace } from "../getWorkspace-CU32E6Uo.js";
|
|
2
|
-
import { a as isCi, i as isInteractive$1, n as normalizePath, o as importModule, r as isStaging, s as doImport, t as safeStructuredClone } from "../safeStructuredClone-
|
|
2
|
+
import { a as isCi, i as isInteractive$1, n as normalizePath, o as importModule, r as isStaging, s as doImport, t as safeStructuredClone } from "../safeStructuredClone-DAFcnqtc.js";
|
|
3
3
|
declare function getCoreAppUrl(organizationId: string, appId: string): string;
|
|
4
4
|
/**
|
|
5
5
|
* Checks if the given value is a record (javascript objectish)
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { existsSync } from 'node:fs';
|
|
2
|
-
import { createRequire } from 'node:module';
|
|
3
2
|
import { join } from 'node:path';
|
|
4
|
-
import {
|
|
3
|
+
import { createJiti } from 'jiti';
|
|
5
4
|
import { NotFoundError } from '../../errors/NotFoundError.js';
|
|
6
5
|
import { tryGetDefaultExport } from '../../util/tryGetDefaultExport.js';
|
|
7
6
|
import { cliConfigSchema } from './schemas.js';
|
|
@@ -9,7 +8,7 @@ import { isWorkbenchApp, isWorkbenchConfig, parseWorkbenchCliConfig } from './wo
|
|
|
9
8
|
/**
|
|
10
9
|
* Get the CLI config for a project synchronously, given the root path.
|
|
11
10
|
*
|
|
12
|
-
* This loads the CLI config in the main thread using
|
|
11
|
+
* This loads the CLI config in the main thread using Jiti for TypeScript support.
|
|
13
12
|
* Note: This is a synchronous operation and does not use worker threads like the async version.
|
|
14
13
|
*
|
|
15
14
|
* @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.
|
|
@@ -28,18 +27,17 @@ import { isWorkbenchApp, isWorkbenchConfig, parseWorkbenchCliConfig } from './wo
|
|
|
28
27
|
throw new Error(`Multiple CLI config files found (${configPaths.join(', ')})`);
|
|
29
28
|
}
|
|
30
29
|
const configPath = configPaths[0];
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
30
|
+
const jiti = createJiti(import.meta.url, {
|
|
31
|
+
// Vite uses import.meta.require, which must be evaluated by Node instead of Jiti's CJS transform
|
|
32
|
+
// Sanity's dependency graph is large, so avoid transforming it as well
|
|
33
|
+
nativeModules: [
|
|
34
|
+
'sanity',
|
|
35
|
+
'vite'
|
|
36
|
+
],
|
|
37
|
+
tsconfigPaths: true
|
|
38
|
+
});
|
|
39
|
+
const loaded = jiti(configPath);
|
|
40
|
+
const cliConfig = tryGetDefaultExport(loaded);
|
|
43
41
|
// Branch as early as possible: a branded `defineApplication(...)` app or a
|
|
44
42
|
// branded `unstable_defineMediaLibrary(...)` config opts into workbench
|
|
45
43
|
// behavior, so its `app` skips the legacy `app` schema entirely.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/cli/getCliConfigSync.ts"],"sourcesContent":["import {existsSync} from 'node:fs'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/config/cli/getCliConfigSync.ts"],"sourcesContent":["import {existsSync} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {createJiti} from 'jiti'\n\nimport {NotFoundError} from '../../errors/NotFoundError.js'\nimport {tryGetDefaultExport} from '../../util/tryGetDefaultExport.js'\nimport {cliConfigSchema} from './schemas.js'\nimport {type CliConfig} from './types/cliConfig.js'\nimport {isWorkbenchApp, isWorkbenchConfig, parseWorkbenchCliConfig} from './workbenchApp.js'\n\n/**\n * Get the CLI config for a project synchronously, given the root path.\n *\n * This loads the CLI config in the main thread using Jiti for TypeScript support.\n * Note: This is a synchronous operation and does not use worker threads like the async version.\n *\n * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.\n * @returns The CLI config\n * @internal\n */\nexport function getCliConfigSync(rootPath: string): CliConfig {\n const possiblePaths = ['sanity.cli.ts', 'sanity.cli.js'].map((file) => join(rootPath, file))\n const configPaths = possiblePaths.filter((path) => existsSync(path))\n\n if (configPaths.length === 0) {\n throw new NotFoundError(`No CLI config found at ${rootPath}/sanity.cli.(ts|js)`)\n }\n\n if (configPaths.length > 1) {\n throw new Error(`Multiple CLI config files found (${configPaths.join(', ')})`)\n }\n\n const configPath = configPaths[0]\n\n const jiti = createJiti(import.meta.url, {\n // Vite uses import.meta.require, which must be evaluated by Node instead of Jiti's CJS transform\n // Sanity's dependency graph is large, so avoid transforming it as well\n nativeModules: ['sanity', 'vite'],\n tsconfigPaths: true,\n })\n const loaded = jiti(configPath)\n const cliConfig = tryGetDefaultExport(loaded) as CliConfig | undefined\n\n // Branch as early as possible: a branded `defineApplication(...)` app or a\n // branded `unstable_defineMediaLibrary(...)` config opts into workbench\n // behavior, so its `app` skips the legacy `app` schema entirely.\n if (isWorkbenchApp(cliConfig?.app) || isWorkbenchConfig(cliConfig?.app)) {\n return parseWorkbenchCliConfig(cliConfig, rootPath)\n }\n\n const {data, error, success} = cliConfigSchema.safeParse(cliConfig)\n if (!success) {\n throw new Error(`Invalid CLI config: ${error.message}`)\n }\n\n // There is a minor difference here because of the `vite` property and how the types\n // aren't as specific as our manually typed `CliConfig` type, thus the cast.\n return data as CliConfig\n}\n"],"names":["existsSync","join","createJiti","NotFoundError","tryGetDefaultExport","cliConfigSchema","isWorkbenchApp","isWorkbenchConfig","parseWorkbenchCliConfig","getCliConfigSync","rootPath","possiblePaths","map","file","configPaths","filter","path","length","Error","configPath","jiti","url","nativeModules","tsconfigPaths","loaded","cliConfig","app","data","error","success","safeParse","message"],"mappings":"AAAA,SAAQA,UAAU,QAAO,UAAS;AAClC,SAAQC,IAAI,QAAO,YAAW;AAE9B,SAAQC,UAAU,QAAO,OAAM;AAE/B,SAAQC,aAAa,QAAO,gCAA+B;AAC3D,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,eAAe,QAAO,eAAc;AAE5C,SAAQC,cAAc,EAAEC,iBAAiB,EAAEC,uBAAuB,QAAO,oBAAmB;AAE5F;;;;;;;;;CASC,GACD,OAAO,SAASC,iBAAiBC,QAAgB;IAC/C,MAAMC,gBAAgB;QAAC;QAAiB;KAAgB,CAACC,GAAG,CAAC,CAACC,OAASZ,KAAKS,UAAUG;IACtF,MAAMC,cAAcH,cAAcI,MAAM,CAAC,CAACC,OAAShB,WAAWgB;IAE9D,IAAIF,YAAYG,MAAM,KAAK,GAAG;QAC5B,MAAM,IAAId,cAAc,CAAC,uBAAuB,EAAEO,SAAS,mBAAmB,CAAC;IACjF;IAEA,IAAII,YAAYG,MAAM,GAAG,GAAG;QAC1B,MAAM,IAAIC,MAAM,CAAC,iCAAiC,EAAEJ,YAAYb,IAAI,CAAC,MAAM,CAAC,CAAC;IAC/E;IAEA,MAAMkB,aAAaL,WAAW,CAAC,EAAE;IAEjC,MAAMM,OAAOlB,WAAW,YAAYmB,GAAG,EAAE;QACvC,iGAAiG;QACjG,uEAAuE;QACvEC,eAAe;YAAC;YAAU;SAAO;QACjCC,eAAe;IACjB;IACA,MAAMC,SAASJ,KAAKD;IACpB,MAAMM,YAAYrB,oBAAoBoB;IAEtC,2EAA2E;IAC3E,wEAAwE;IACxE,iEAAiE;IACjE,IAAIlB,eAAemB,WAAWC,QAAQnB,kBAAkBkB,WAAWC,MAAM;QACvE,OAAOlB,wBAAwBiB,WAAWf;IAC5C;IAEA,MAAM,EAACiB,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGxB,gBAAgByB,SAAS,CAACL;IACzD,IAAI,CAACI,SAAS;QACZ,MAAM,IAAIX,MAAM,CAAC,oBAAoB,EAAEU,MAAMG,OAAO,EAAE;IACxD;IAEA,oFAAoF;IACpF,4EAA4E;IAC5E,OAAOJ;AACT"}
|
|
@@ -37,7 +37,6 @@ const debug = subdebug('worker:getStudioWorkspaces');
|
|
|
37
37
|
}
|
|
38
38
|
const workDir = dirname(configPath);
|
|
39
39
|
debug('Work dir %s', workDir);
|
|
40
|
-
// @ts-expect-error - resolveConfig is type-only in sanity@6.11.0; fixed in the next sanity release
|
|
41
40
|
const { resolveConfig } = await resolveLocalPackage('sanity', workDir);
|
|
42
41
|
if (typeof resolveConfig !== 'function') {
|
|
43
42
|
throw new TypeError('Expected `resolveConfig` from `sanity` to be a function');
|
|
@@ -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 {firstValueFrom, of} from 'rxjs'\nimport {type Workspace} from 'sanity'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {doImport} from '../../util/doImport.js'\nimport {getEmptyAuth} from '../../util/getEmptyAuth.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
|
|
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 {firstValueFrom, of} from 'rxjs'\nimport {type Workspace} from 'sanity'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {doImport} from '../../util/doImport.js'\nimport {getEmptyAuth} from '../../util/getEmptyAuth.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 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","firstValueFrom","of","subdebug","doImport","getEmptyAuth","resolveLocalPackage","findStudioConfigPath","isStudioConfig","debug","getStudioWorkspaces","configPath","Error","isDirectory","config","default","TypeError","workDir","resolveConfig","rawWorkspaces","Array","isArray","basePath","name","emptyAuth","state","unauthedWorkspaces","map","workspace","auth"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,OAAO,QAAO,YAAW;AACjC,SAAQC,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,cAAc,EAAEC,EAAE,QAAO,OAAM;AAGvC,SAAQC,QAAQ,QAAO,0BAAyB;AAChD,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,YAAY,QAAO,6BAA4B;AACvD,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,oBAAoB,QAAO,kCAAiC;AACpE,SAAQC,cAAc,QAAO,sBAAqB;AAElD,MAAMC,QAAQN,SAAS;AAEvB;;;;;;;;CAQC,GACD,OAAO,eAAeO,oBAAoBC,UAAkB;IAC1D,IAAIX,cAAc;QAChB,MAAM,IAAIY,MAAM;IAClB;IACA,MAAMC,cAAc,AAAC,CAAA,MAAMf,KAAKa,WAAU,EAAGE,WAAW;IACxD,IAAIA,aAAa;QACfF,aAAa,MAAMJ,qBAAqBI;IAC1C;IACAF,MAAM,iCAAiCE;IACvC,IAAIG,SAAS,MAAMV,SAASO;IAE5BF,MAAM,sBAAsBK;IAC5B,IAAI,CAACN,eAAeM,SAAS;QAC3B,IAAI,CAAE,CAAA,aAAaA,MAAK,KAAM,CAACN,eAAeM,OAAOC,OAAO,GAAG;YAC7DN,MAAM,wCAAwCE;YAC9C,MAAM,IAAIK,UAAU,CAAC,iCAAiC,EAAEL,WAAW,CAAC,CAAC;QACvE;QAEAG,SAASA,OAAOC,OAAO;IACzB;IAEA,MAAME,UAAUlB,QAAQY;IACxBF,MAAM,eAAeQ;IACrB,MAAM,EAACC,aAAa,EAAC,GAAG,MAAMZ,oBAA6C,UAAUW;IACrF,IAAI,OAAOC,kBAAkB,YAAY;QACvC,MAAM,IAAIF,UAAU;IACtB;IAEA,kFAAkF;IAClF,mFAAmF;IACnF,MAAMG,gBAAgBC,MAAMC,OAAO,CAACP,UAChCA,SACA;QAAC;YAAC,GAAGA,MAAM;YAAEQ,UAAUR,OAAOQ,QAAQ,IAAI;YAAKC,MAAMT,OAAOS,IAAI,IAAI;QAAS;KAAE;IAEnF,MAAMC,YAAY;QAACC,OAAOvB,GAAGG;IAAe;IAE5C,MAAMqB,qBAAqBP,cAAcQ,GAAG,CAAC,CAACC,YAAe,CAAA;YAC3D,GAAGA,SAAS;YACZC,MAAML;QACR,CAAA;IAEAf,MAAM,0BAA0BiB;IAEhC,OAAOzB,eAAeiB,cAAcQ;AACtC"}
|
|
@@ -109,7 +109,7 @@ declare function getCliConfigUncached(rootPath: string): Promise<CliConfig>;
|
|
|
109
109
|
/**
|
|
110
110
|
* Get the CLI config for a project synchronously, given the root path.
|
|
111
111
|
*
|
|
112
|
-
* This loads the CLI config in the main thread using
|
|
112
|
+
* This loads the CLI config in the main thread using Jiti for TypeScript support.
|
|
113
113
|
* Note: This is a synchronous operation and does not use worker threads like the async version.
|
|
114
114
|
*
|
|
115
115
|
* @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.
|
|
@@ -280,4 +280,4 @@ declare function findStudioConfigPath(basePath: string): Promise<string>;
|
|
|
280
280
|
*/
|
|
281
281
|
declare function tryFindStudioConfigPath(basePath: string): Promise<string | undefined>;
|
|
282
282
|
export { CliTokenInfo as _, getStudioWorkspaces as a, findProjectRoot as c, getCliConfigUncached as d, getCliToken as f, setCliUserConfig as g, getUserConfig as h, isStudioConfig as i, getCliConfigSync as l, getCliUserConfig as m, tryFindStudioConfigPath as n, getStudioConfig as o, getCliTokenInfo as p, findPathForFiles as r, findProjectRootSync as s, findStudioConfigPath as t, getCliConfig as u, clearCliTokenCache as v };
|
|
283
|
-
//# sourceMappingURL=findStudioConfigPath-
|
|
283
|
+
//# sourceMappingURL=findStudioConfigPath-CeSHbV0N.d.ts.map
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
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
|
+
function isPrimitive(value) {
|
|
9
|
+
return !value || typeof value !== 'object' && typeof value !== 'function';
|
|
10
|
+
}
|
|
11
|
+
function defineExport(exports, key, getter) {
|
|
12
|
+
Object.defineProperty(exports, key, {
|
|
13
|
+
configurable: true,
|
|
14
|
+
enumerable: true,
|
|
15
|
+
get: getter
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
function exportAll(exports, sourceModule) {
|
|
19
|
+
if (exports === sourceModule) return;
|
|
20
|
+
if (isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise) {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
for(const key in sourceModule){
|
|
24
|
+
if (key !== 'default' && !(key in exports)) {
|
|
25
|
+
try {
|
|
26
|
+
defineExport(exports, key, ()=>sourceModule[key]);
|
|
27
|
+
} catch {
|
|
28
|
+
// ignore non-configurable exports
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Module evaluator that can execute raw CommonJS modules in addition to
|
|
35
|
+
* Vite's SSR-transformed ESM. Matches vite-node's CJS execution behavior,
|
|
36
|
+
* which ModuleRunner's default ESModulesEvaluator does not support.
|
|
37
|
+
*/ export class StudioModuleEvaluator {
|
|
38
|
+
esmEvaluator = new ESModulesEvaluator();
|
|
39
|
+
startOffset = this.esmEvaluator.startOffset;
|
|
40
|
+
runExternalModule(filepath) {
|
|
41
|
+
return this.esmEvaluator.runExternalModule(filepath);
|
|
42
|
+
}
|
|
43
|
+
runInlinedModule(context, code, module) {
|
|
44
|
+
if (!isCommonJsCode(code)) {
|
|
45
|
+
return this.esmEvaluator.runInlinedModule(context, code, module);
|
|
46
|
+
}
|
|
47
|
+
return this.runCommonJsModule(context, code, module);
|
|
48
|
+
}
|
|
49
|
+
async runCommonJsModule(context, code, module) {
|
|
50
|
+
const modulePath = module.file || module.id;
|
|
51
|
+
const href = pathToFileURL(modulePath).href;
|
|
52
|
+
const __filename = fileURLToPath(href);
|
|
53
|
+
const __dirname = dirname(__filename);
|
|
54
|
+
const exports = context[ssrModuleExportsKey];
|
|
55
|
+
const moduleNotDefined = Symbol('not defined');
|
|
56
|
+
let moduleExports = moduleNotDefined;
|
|
57
|
+
const cjsExports = new Proxy(exports, {
|
|
58
|
+
get: (target, property, receiver)=>{
|
|
59
|
+
if (Reflect.has(target, property)) return Reflect.get(target, property, receiver);
|
|
60
|
+
return Reflect.get(Object.prototype, property, receiver);
|
|
61
|
+
},
|
|
62
|
+
getPrototypeOf: ()=>Object.prototype,
|
|
63
|
+
set: (_, property, value)=>{
|
|
64
|
+
if (property === 'default') {
|
|
65
|
+
exports.default = value;
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
if (!Reflect.has(exports, 'default')) {
|
|
69
|
+
exports.default = {};
|
|
70
|
+
}
|
|
71
|
+
if (moduleExports !== moduleNotDefined && isPrimitive(moduleExports)) {
|
|
72
|
+
defineExport(exports, String(property), ()=>{});
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
if (!isPrimitive(exports.default) && typeof exports.default === 'object') {
|
|
76
|
+
;
|
|
77
|
+
exports.default[String(property)] = value;
|
|
78
|
+
}
|
|
79
|
+
if (property !== 'default') {
|
|
80
|
+
defineExport(exports, String(property), ()=>value);
|
|
81
|
+
}
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
const moduleProxy = {
|
|
86
|
+
get exports () {
|
|
87
|
+
return cjsExports;
|
|
88
|
+
},
|
|
89
|
+
set exports (value){
|
|
90
|
+
exportAll(exports, value);
|
|
91
|
+
exports.default = value;
|
|
92
|
+
moduleExports = value;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
const cjsContext = {
|
|
96
|
+
...context,
|
|
97
|
+
__dirname,
|
|
98
|
+
__filename,
|
|
99
|
+
exports: cjsExports,
|
|
100
|
+
module: moduleProxy,
|
|
101
|
+
require: createRequire(href)
|
|
102
|
+
};
|
|
103
|
+
let normalizedCode = code;
|
|
104
|
+
if (normalizedCode[0] === '#') {
|
|
105
|
+
normalizedCode = normalizedCode.replace(/^#!.*/, (line)=>' '.repeat(line.length));
|
|
106
|
+
}
|
|
107
|
+
// Use AsyncFunction (same as ESModulesEvaluator) so the shared `startOffset`
|
|
108
|
+
// ModuleRunner applies to inlined sourcemaps matches this wrapper's padding.
|
|
109
|
+
const AsyncFunction = (async function() {}).constructor;
|
|
110
|
+
const parameterNames = Object.keys(cjsContext);
|
|
111
|
+
const runner = new AsyncFunction(...parameterNames, `"use strict";\n${normalizedCode}`);
|
|
112
|
+
await runner(...parameterNames.map((name)=>cjsContext[name]));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
//# sourceMappingURL=studioModuleEvaluator.js.map
|
|
@@ -0,0 +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 isCommonJsCode(code: string): boolean {\n return (\n /\\bmodule\\.exports\\b/.test(code) ||\n /\\bexports\\.[a-zA-Z_$]/.test(code) ||\n /(?:^|[;\\n])\\s*exports\\s=/.test(code) ||\n /(?:^|\\n|\\s)require\\s*\\(/.test(code)\n )\n}\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 if (!isCommonJsCode(code)) {\n return (this.esmEvaluator as ModuleEvaluator).runInlinedModule(context, code, module)\n }\n\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 if (property === 'default') {\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) && typeof exports.default === 'object') {\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 // Use AsyncFunction (same as ESModulesEvaluator) so the shared `startOffset`\n // ModuleRunner applies to inlined sourcemaps matches this wrapper's padding.\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 await runner(...parameterNames.map((name) => cjsContext[name]))\n }\n}\n"],"names":["createRequire","dirname","fileURLToPath","pathToFileURL","ESModulesEvaluator","ssrModuleExportsKey","isCommonJsCode","code","test","isPrimitive","value","defineExport","exports","key","getter","Object","defineProperty","configurable","enumerable","get","exportAll","sourceModule","Array","isArray","Promise","StudioModuleEvaluator","esmEvaluator","startOffset","runExternalModule","filepath","runInlinedModule","context","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,eAAeC,IAAY;IAClC,OACE,sBAAsBC,IAAI,CAACD,SAC3B,wBAAwBC,IAAI,CAACD,SAC7B,2BAA2BC,IAAI,CAACD,SAChC,0BAA0BC,IAAI,CAACD;AAEnC;AAEA,SAASE,YAAYC,KAAc;IACjC,OAAO,CAACA,SAAU,OAAOA,UAAU,YAAY,OAAOA,UAAU;AAClE;AAEA,SAASC,aAAaC,OAAgC,EAAEC,GAAW,EAAEC,MAAqB;IACxFC,OAAOC,cAAc,CAACJ,SAASC,KAAK;QAClCI,cAAc;QACdC,YAAY;QACZC,KAAKL;IACP;AACF;AAEA,SAASM,UAAUR,OAAgC,EAAES,YAAqB;IACxE,IAAIT,YAAYS,cAAc;IAC9B,IAAIZ,YAAYY,iBAAiBC,MAAMC,OAAO,CAACF,iBAAiBA,wBAAwBG,SAAS;QAC/F;IACF;IAEA,IAAK,MAAMX,OAAOQ,aAAyC;QACzD,IAAIR,QAAQ,aAAa,CAAEA,CAAAA,OAAOD,OAAM,GAAI;YAC1C,IAAI;gBACFD,aAAaC,SAASC,KAAK,IAAM,AAACQ,YAAwC,CAACR,IAAI;YACjF,EAAE,OAAM;YACN,kCAAkC;YACpC;QACF;IACF;AACF;AAEA;;;;CAIC,GACD,OAAO,MAAMY;IACMC,eAAe,IAAItB,qBAAoB;IAC/CuB,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oBACpE/B,aAAaC,SAAS2C,OAAOT,WAAW,KAAO;oBAC/C,OAAO;gBACT;gBACA,IAAI,CAACrC,YAAYG,QAAQ0C,OAAO,KAAK,OAAO1C,QAAQ0C,OAAO,KAAK,UAAU;;oBACtE1C,QAAQ0C,OAAO,AAA4B,CAACC,OAAOT,UAAU,GAAGpC;gBACpE;gBACA,IAAIoC,aAAa,WAAW;oBAC1BnC,aAAaC,SAAS2C,OAAOT,WAAW,IAAMpC;gBAChD;gBACA,OAAO;YACT;QACF;QAEA,MAAM8C,cAAc;YAClB,IAAI5C;gBACF,OAAO+B;YACT;YACA,IAAI/B,SAAQF,KAAc,CAAE;gBAC1BU,UAAUR,SAASF;gBACnBE,QAAQ0C,OAAO,GAAG5C;gBAClBgC,gBAAgBhC;YAClB;QACF;QAEA,MAAM+C,aAAsC;YAC1C,GAAG1B,OAAO;YACVQ;YACAD;YACA1B,SAAS+B;YACTX,QAAQwB;YACRE,SAAS1D,cAAcqC;QACzB;QAEA,IAAIsB,iBAAiBpD;QACrB,IAAIoD,cAAc,CAAC,EAAE,KAAK,KAAK;YAC7BA,iBAAiBA,eAAeC,OAAO,CAAC,SAAS,CAACC,OAAS,IAAIC,MAAM,CAACD,KAAKE,MAAM;QACnF;QAEA,6EAA6E;QAC7E,6EAA6E;QAC7E,MAAMC,gBAAgB,CAAA,kBAAmB,CAAA,EAAE,WAAW;QAGtD,MAAMC,iBAAiBlD,OAAOmD,IAAI,CAACT;QACnC,MAAMU,SAAS,IAAIH,iBAAiBC,gBAAgB,CAAC,eAAe,EAAEN,gBAAgB;QACtF,MAAMQ,UAAUF,eAAeG,GAAG,CAAC,CAACC,OAASZ,UAAU,CAACY,KAAK;IAC/D;AACF"}
|
|
@@ -1,14 +1,13 @@
|
|
|
1
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
1
2
|
import { isMainThread, parentPort } from 'node:worker_threads';
|
|
2
|
-
import { createServer, loadEnv, mergeConfig } from 'vite';
|
|
3
|
-
import { ViteNodeRunner } from 'vite-node/client';
|
|
4
|
-
import { ViteNodeServer } from 'vite-node/server';
|
|
5
|
-
import { installSourcemapsSupport } from 'vite-node/source-map';
|
|
3
|
+
import { createServer, createServerModuleRunner, isRunnableDevEnvironment, loadEnv, mergeConfig } from 'vite';
|
|
6
4
|
import { subdebug } from '../../_exports/debug.js';
|
|
7
5
|
import { getCliConfig } from '../../config/cli/getCliConfig.js';
|
|
8
6
|
import { isNotFoundError } from '../../errors/NotFoundError.js';
|
|
9
7
|
import { getStudioEnvironmentVariables } from '../../util/environment/getStudioEnvironmentVariables.js';
|
|
10
8
|
import { setupBrowserStubs } from '../../util/environment/setupBrowserStubs.js'; // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB
|
|
11
9
|
import { isRecord } from '../../util/isRecord.js';
|
|
10
|
+
import { StudioModuleEvaluator } from './studioModuleEvaluator.js';
|
|
12
11
|
import { createOneShotWorkerLifecycle } from './studioWorkerLifecycle.js';
|
|
13
12
|
if (isMainThread) {
|
|
14
13
|
throw new Error('Should be child of thread, not the main thread');
|
|
@@ -40,7 +39,7 @@ try {
|
|
|
40
39
|
/**
|
|
41
40
|
* Fetches and caches modules from HTTP/HTTPS URLs.
|
|
42
41
|
* Vite's SSR transform treats `https://` imports as external and bypasses the plugin
|
|
43
|
-
* resolve pipeline entirely, so we intercept them at the
|
|
42
|
+
* resolve pipeline entirely, so we intercept them at the module runner level instead.
|
|
44
43
|
*/ const httpModuleCache = new Map();
|
|
45
44
|
async function fetchHttpModule(url) {
|
|
46
45
|
const cached = httpModuleCache.get(url);
|
|
@@ -150,49 +149,48 @@ try {
|
|
|
150
149
|
for(const key in env){
|
|
151
150
|
process.env[key] ??= env[key];
|
|
152
151
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
},
|
|
175
|
-
resolveId (id, importer) {
|
|
176
|
-
// Prevent vite-node from trying to resolve HTTP URLs through Node's resolver
|
|
177
|
-
if (isHttpsUrl(id)) return {
|
|
178
|
-
id
|
|
152
|
+
const ssrEnvironment = server.environments.ssr;
|
|
153
|
+
if (!isRunnableDevEnvironment(ssrEnvironment)) {
|
|
154
|
+
throw new Error('Expected SSR environment to be a runnable dev environment');
|
|
155
|
+
}
|
|
156
|
+
await ssrEnvironment.init();
|
|
157
|
+
// Override fetchModule to support https:// imports and resolve relative imports from
|
|
158
|
+
// remote modules (e.g. esm.sh re-exports with absolute paths).
|
|
159
|
+
const defaultFetchModule = ssrEnvironment.fetchModule.bind(ssrEnvironment);
|
|
160
|
+
ssrEnvironment.fetchModule = async (id, importer, options)=>{
|
|
161
|
+
if (importer && isHttpsUrl(importer) && !isHttpsUrl(id)) {
|
|
162
|
+
id = new URL(id, importer).href;
|
|
163
|
+
}
|
|
164
|
+
if (isHttpsUrl(id)) {
|
|
165
|
+
const { code: rawCode } = await fetchHttpModule(id);
|
|
166
|
+
const result = await server.ssrTransform(rawCode, null, id);
|
|
167
|
+
return {
|
|
168
|
+
code: result?.code || rawCode,
|
|
169
|
+
file: null,
|
|
170
|
+
id,
|
|
171
|
+
invalidate: false,
|
|
172
|
+
url: id
|
|
179
173
|
};
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
174
|
+
}
|
|
175
|
+
// Module Runner's fetchModule skips Vite resolve for `file://` URLs, so TypeScript
|
|
176
|
+
// extension rewriting (`.js` → `.ts`/`.tsx`) never runs. vite-node always resolved
|
|
177
|
+
// through `resolveId` first; restore that for absolute file imports (e.g. lazy
|
|
178
|
+
// `doImport(new URL('iconResolver.js', import.meta.url))` in tests/source).
|
|
179
|
+
// Keep the result as `file://` — on Windows, bare `C:/...` paths are treated as
|
|
180
|
+
// package imports by Module Runner's fetchModule and fail to load.
|
|
181
|
+
if (id.startsWith('file://')) {
|
|
182
|
+
const resolved = await ssrEnvironment.pluginContainer.resolveId(fileURLToPath(id), importer ?? undefined);
|
|
183
|
+
if (resolved?.id && !resolved.id.startsWith('\0')) {
|
|
184
|
+
id = pathToFileURL(resolved.id).href;
|
|
186
185
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
186
|
+
}
|
|
187
|
+
return defaultFetchModule(id, importer, options);
|
|
188
|
+
};
|
|
189
|
+
const runner = createServerModuleRunner(ssrEnvironment, {
|
|
190
|
+
evaluator: new StudioModuleEvaluator(),
|
|
191
|
+
hmr: false
|
|
190
192
|
});
|
|
191
|
-
|
|
192
|
-
// vite, but it also takes a surprisingly long time to execute. Not clear at this
|
|
193
|
-
// point why this is, so we should investigate whether it's necessary or not.
|
|
194
|
-
await runner.executeId('/@vite/env');
|
|
195
|
-
await runner.executeId(workerScriptPath);
|
|
193
|
+
await runner.import(workerScriptPath);
|
|
196
194
|
} catch (error) {
|
|
197
195
|
// Long-lived workers keep the original behavior: the error surfaces as a
|
|
198
196
|
// Worker 'error' event.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {isMainThread, parentPort} from 'node:worker_threads'\n\nimport {createServer, type InlineConfig, loadEnv, mergeConfig} from 'vite'\nimport {ViteNodeRunner} from 'vite-node/client'\nimport {ViteNodeServer} from 'vite-node/server'\nimport {installSourcemapsSupport} from 'vite-node/source-map'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {isNotFoundError} from '../../errors/NotFoundError.js'\nimport {getStudioEnvironmentVariables} from '../../util/environment/getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from '../../util/environment/setupBrowserStubs.js' // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB\nimport {isRecord} from '../../util/isRecord.js'\nimport {createOneShotWorkerLifecycle} from './studioWorkerLifecycle.js'\n\nif (isMainThread) {\n throw new Error('Should be child of thread, not the main thread')\n}\n\nconst rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH\nif (!rootPath) {\n throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable')\n}\n\nconst debug = subdebug('studio:worker')\n\nconst workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE\nif (!workerScriptPath) {\n throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable')\n}\n\nawait setupBrowserStubs()\n\nconst studioEnvVars = await getStudioEnvironmentVariables(rootPath)\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 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: {\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 // Now we're providing the glue that ensures node-specific loading and execution works.\n const node = new ViteNodeServer(server)\n\n // Should make it easier to debug any crashes in the imported code…\n installSourcemapsSupport({\n getSourceMap: (source) => node.getSourceMap(source),\n })\n\n const runner = new ViteNodeRunner({\n base: server.config.base,\n async fetchModule(id) {\n // Vite's SSR transform externalizes https:// imports, so Node's ESM loader\n // would reject them. We fetch the module over HTTP and run it through Vite's\n // SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*\n // format that ViteNodeRunner expects.\n if (isHttpsUrl(id)) {\n const {code: rawCode} = await fetchHttpModule(id)\n const result = await server.ssrTransform(rawCode, null, id)\n return {code: result?.code || rawCode}\n }\n return node.fetchModule(id)\n },\n resolveId(id, importer) {\n // Prevent vite-node from trying to resolve HTTP URLs through Node's resolver\n if (isHttpsUrl(id)) return {id}\n // Resolve any import from an HTTP-fetched module against the remote origin\n // (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)\n if (importer && isHttpsUrl(importer)) {\n return {id: new URL(id, importer).href}\n }\n return node.resolveId(id, importer)\n },\n root: server.config.root,\n })\n\n // Copied from `vite-node` - it appears that this applies the `define` config from\n // vite, but it also takes a surprisingly long time to execute. Not clear at this\n // point why this is, so we should investigate whether it's necessary or not.\n await runner.executeId('/@vite/env')\n\n await runner.executeId(workerScriptPath)\n} catch (error) {\n // Long-lived workers keep the original behavior: the error surfaces as a\n // Worker 'error' event.\n if (!lifecycle) {\n throw error\n }\n\n // One-shot workers close the server first and post a serialized error the\n // main thread rethrows, so the worker exits cleanly (code 0) and the real\n // error (e.g. a broken `sanity.config.ts`) isn't masked by a teardown abort.\n await lifecycle.postError(error)\n} finally {\n await lifecycle?.close()\n}\n"],"names":["isMainThread","parentPort","createServer","loadEnv","mergeConfig","ViteNodeRunner","ViteNodeServer","installSourcemapsSupport","subdebug","getCliConfig","isNotFoundError","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","createOneShotWorkerLifecycle","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","debug","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","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","node","getSourceMap","source","runner","base","fetchModule","rawCode","result","ssrTransform","resolveId","importer","URL","href","executeId","postError"],"mappings":"AAAA,SAAQA,YAAY,EAAEC,UAAU,QAAO,sBAAqB;AAE5D,SAAQC,YAAY,EAAqBC,OAAO,EAAEC,WAAW,QAAO,OAAM;AAC1E,SAAQC,cAAc,QAAO,mBAAkB;AAC/C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AMsD,SAAS,MAAM3B,OAAO4B,YAAY,CAACF,SAAS,MAAMrD;gBACxD,OAAO;oBAACZ,MAAMkE,QAAQlE,QAAQiE;gBAAO;YACvC;YACA,OAAON,KAAKK,WAAW,CAACpD;QAC1B;QACAwD,WAAUxD,EAAE,EAAEyD,QAAQ;YACpB,6EAA6E;YAC7E,IAAI1D,WAAWC,KAAK,OAAO;gBAACA;YAAE;YAC9B,2EAA2E;YAC3E,kEAAkE;YAClE,IAAIyD,YAAY1D,WAAW0D,WAAW;gBACpC,OAAO;oBAACzD,IAAI,IAAI0D,IAAI1D,IAAIyD,UAAUE,IAAI;gBAAA;YACxC;YACA,OAAOZ,KAAKS,SAAS,CAACxD,IAAIyD;QAC5B;QACA/B,MAAMC,OAAOkB,MAAM,CAACnB,IAAI;IAC1B;IAEA,kFAAkF;IAClF,iFAAiF;IACjF,6EAA6E;IAC7E,MAAMwB,OAAOU,SAAS,CAAC;IAEvB,MAAMV,OAAOU,SAAS,CAACvF;AACzB,EAAE,OAAOqE,OAAO;IACd,yEAAyE;IACzE,wBAAwB;IACxB,IAAI,CAACL,WAAW;QACd,MAAMK;IACR;IAEA,0EAA0E;IAC1E,0EAA0E;IAC1E,6EAA6E;IAC7E,MAAML,UAAUwB,SAAS,CAACnB;AAC5B,SAAU;IACR,MAAML,WAAWG;AACnB"}
|
|
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;AAE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;AAC5B,SAAU;IACR,MAAML,WAAWG;AACnB"}
|
|
@@ -3,8 +3,8 @@ import { getTsconfig } from 'get-tsconfig';
|
|
|
3
3
|
import { isRecord } from '../../util/isRecord.js';
|
|
4
4
|
import { promisifyWorker } from '../../util/promisifyWorker.js';
|
|
5
5
|
/**
|
|
6
|
-
* Executes a worker file with
|
|
7
|
-
*
|
|
6
|
+
* Executes a worker file with TypeScript support. This means you can import other
|
|
7
|
+
* TypeScript with fairly rich syntax, and still have that only apply to the worker
|
|
8
8
|
* thread instead of the full parent process. The worker should emit a message when
|
|
9
9
|
* complete using `parentPort`. Once it has received a single message will resolve the
|
|
10
10
|
* returned promise with that message. If you are expecting multiple messages, you will
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerTask.ts"],"sourcesContent":["import {fileURLToPath, URL} from 'node:url'\nimport {type WorkerOptions} from 'node:worker_threads'\n\nimport {getTsconfig} from 'get-tsconfig'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\n\n/**\n * Options for the tsx worker task\n *\n * @internal\n */\ninterface TsxWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n rootPath: string\n}\n\n/**\n * Executes a worker file with
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerTask.ts"],"sourcesContent":["import {fileURLToPath, URL} from 'node:url'\nimport {type WorkerOptions} from 'node:worker_threads'\n\nimport {getTsconfig} from 'get-tsconfig'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\n\n/**\n * Options for the tsx worker task\n *\n * @internal\n */\ninterface TsxWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n rootPath: string\n}\n\n/**\n * Executes a worker file with TypeScript support. This means you can import other\n * TypeScript with fairly rich syntax, and still have that only apply to the worker\n * thread instead of the full parent process. The worker should emit a message when\n * complete using `parentPort`. Once it has received a single message will resolve the\n * returned promise with that message. If you are expecting multiple messages, you will\n * have to implement another method ;)\n *\n * @param filePath - Path to the worker file\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function tsxWorkerTask<T = unknown>(\n filePath: URL,\n options: TsxWorkerTaskOptions,\n): Promise<T> {\n const tsconfig = getTsconfig(options.rootPath)\n\n const env = {\n ...(isRecord(options.env) ? options.env : process.env),\n ...(tsconfig?.path ? {TSX_TSCONFIG_PATH: tsconfig.path} : {}),\n TSX_WORKER_TASK_SCRIPT: fileURLToPath(filePath),\n }\n\n return promisifyWorker<T>(new URL('tsxWorkerLoader.worker.js', import.meta.url), {\n ...options,\n env,\n })\n}\n"],"names":["fileURLToPath","URL","getTsconfig","isRecord","promisifyWorker","tsxWorkerTask","filePath","options","tsconfig","rootPath","env","process","path","TSX_TSCONFIG_PATH","TSX_WORKER_TASK_SCRIPT","url"],"mappings":"AAAA,SAAQA,aAAa,EAAEC,GAAG,QAAO,WAAU;AAG3C,SAAQC,WAAW,QAAO,eAAc;AAGxC,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,gCAA+B;AAW7D;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,cACdC,QAAa,EACbC,OAA6B;IAE7B,MAAMC,WAAWN,YAAYK,QAAQE,QAAQ;IAE7C,MAAMC,MAAM;QACV,GAAIP,SAASI,QAAQG,GAAG,IAAIH,QAAQG,GAAG,GAAGC,QAAQD,GAAG;QACrD,GAAIF,UAAUI,OAAO;YAACC,mBAAmBL,SAASI,IAAI;QAAA,IAAI,CAAC,CAAC;QAC5DE,wBAAwBd,cAAcM;IACxC;IAEA,OAAOF,gBAAmB,IAAIH,IAAI,6BAA6B,YAAYc,GAAG,GAAG;QAC/E,GAAGR,OAAO;QACVG;IACF;AACF"}
|
package/dist/manifest.js
CHANGED
|
@@ -12,9 +12,9 @@ import { z } from 'zod/mini';
|
|
|
12
12
|
*/ export const coreAppManifestSchema = z.object({
|
|
13
13
|
dock: z.optional(z.object({
|
|
14
14
|
group: z.optional(z.enum([
|
|
15
|
-
'
|
|
16
|
-
'
|
|
17
|
-
'
|
|
15
|
+
'system',
|
|
16
|
+
'applications',
|
|
17
|
+
'user'
|
|
18
18
|
])),
|
|
19
19
|
order: z.optional(z.number())
|
|
20
20
|
})),
|
package/dist/manifest.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/manifest.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n/**\n * Studio/app manifest schemas. They live in cli-core because more than one\n * package validates manifests: the CLI extracts and writes them, and the\n * workbench dev-server registry stores and rebroadcasts them. Keeping the\n * contract here lets both validate against the same schema without depending on\n * each other.\n */\n\n/**\n * Core-app application manifest. Mirrors the workbench's\n * `CoreAppUserApplicationManifest` schema. Strictly validated via zod since the\n * CLI produces the payload in full.\n */\nexport const coreAppManifestSchema = z.object({\n dock: z.optional(\n z.object({\n group: z.optional(z.enum(['
|
|
1
|
+
{"version":3,"sources":["../src/manifest.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n/**\n * Studio/app manifest schemas. They live in cli-core because more than one\n * package validates manifests: the CLI extracts and writes them, and the\n * workbench dev-server registry stores and rebroadcasts them. Keeping the\n * contract here lets both validate against the same schema without depending on\n * each other.\n */\n\n/**\n * Core-app application manifest. Mirrors the workbench's\n * `CoreAppUserApplicationManifest` schema. Strictly validated via zod since the\n * CLI produces the payload in full.\n */\nexport const coreAppManifestSchema = z.object({\n dock: z.optional(\n z.object({\n group: z.optional(z.enum(['system', 'applications', 'user'])),\n order: z.optional(z.number()),\n }),\n ),\n icon: z.optional(z.string()),\n slug: z.optional(z.string()),\n title: z.optional(z.string()),\n version: z.string(),\n})\n\nexport type CoreAppManifest = z.infer<typeof coreAppManifestSchema>\n\n/**\n * Studio application manifest (serialized `create-manifest.json`). Kept loose so\n * the CLI isn't coupled to the workbench's evolving client-side schema — the\n * workbench consumer is authoritative on the inner shape. See its\n * `ClientManifest` for the fields clients expect.\n */\nexport const studioManifestSchema = z.record(z.string(), z.unknown())\n\nexport type StudioManifest = z.infer<typeof studioManifestSchema>\n"],"names":["z","coreAppManifestSchema","object","dock","optional","group","enum","order","number","icon","string","slug","title","version","studioManifestSchema","record","unknown"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B;;;;;;CAMC,GAED;;;;CAIC,GACD,OAAO,MAAMC,wBAAwBD,EAAEE,MAAM,CAAC;IAC5CC,MAAMH,EAAEI,QAAQ,CACdJ,EAAEE,MAAM,CAAC;QACPG,OAAOL,EAAEI,QAAQ,CAACJ,EAAEM,IAAI,CAAC;YAAC;YAAU;YAAgB;SAAO;QAC3DC,OAAOP,EAAEI,QAAQ,CAACJ,EAAEQ,MAAM;IAC5B;IAEFC,MAAMT,EAAEI,QAAQ,CAACJ,EAAEU,MAAM;IACzBC,MAAMX,EAAEI,QAAQ,CAACJ,EAAEU,MAAM;IACzBE,OAAOZ,EAAEI,QAAQ,CAACJ,EAAEU,MAAM;IAC1BG,SAASb,EAAEU,MAAM;AACnB,GAAE;AAIF;;;;;CAKC,GACD,OAAO,MAAMI,uBAAuBd,EAAEe,MAAM,CAACf,EAAEU,MAAM,IAAIV,EAAEgB,OAAO,IAAG"}
|
|
@@ -18,8 +18,7 @@ interface ImportModuleOptions {
|
|
|
18
18
|
tsconfigPath?: string;
|
|
19
19
|
}
|
|
20
20
|
/**
|
|
21
|
-
* Imports a module using
|
|
22
|
-
* This is a thin wrapper around tsx to allow swapping out the underlying implementation in the future if needed.
|
|
21
|
+
* Imports a module using Jiti and returns its exports.
|
|
23
22
|
*
|
|
24
23
|
* @param filePath - Path to the module to import.
|
|
25
24
|
* @param options - Options for the importModule function.
|
|
@@ -55,4 +54,4 @@ declare function normalizePath(path: string): string;
|
|
|
55
54
|
*/
|
|
56
55
|
declare function safeStructuredClone<T>(obj: T): T;
|
|
57
56
|
export { isCi as a, isInteractive as i, normalizePath as n, importModule as o, isStaging as r, doImport as s, safeStructuredClone as t };
|
|
58
|
-
//# sourceMappingURL=safeStructuredClone-
|
|
57
|
+
//# sourceMappingURL=safeStructuredClone-DAFcnqtc.d.ts.map
|
|
@@ -82,9 +82,9 @@ declare const cliConfigSchema: z.ZodMiniObject<{
|
|
|
82
82
|
declare const coreAppManifestSchema: z.ZodMiniObject<{
|
|
83
83
|
dock: z.ZodMiniOptional<z.ZodMiniObject<{
|
|
84
84
|
group: z.ZodMiniOptional<z.ZodMiniEnum<{
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
85
|
+
system: "system";
|
|
86
|
+
applications: "applications";
|
|
87
|
+
user: "user";
|
|
88
88
|
}>>;
|
|
89
89
|
order: z.ZodMiniOptional<z.ZodMiniNumber<number>>;
|
|
90
90
|
}, z.core.$strip>>;
|
|
@@ -103,4 +103,4 @@ type CoreAppManifest = z.infer<typeof coreAppManifestSchema>;
|
|
|
103
103
|
declare const studioManifestSchema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
|
|
104
104
|
type StudioManifest = z.infer<typeof studioManifestSchema>;
|
|
105
105
|
export { cliConfigSchema as a, studioManifestSchema as i, StudioManifest as n, coreAppManifestSchema as r, CoreAppManifest as t };
|
|
106
|
-
//# sourceMappingURL=schemas-
|
|
106
|
+
//# sourceMappingURL=schemas-BUfBJffI.d.ts.map
|
|
@@ -79,8 +79,8 @@ interface TsxWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {
|
|
|
79
79
|
rootPath: string;
|
|
80
80
|
}
|
|
81
81
|
/**
|
|
82
|
-
* Executes a worker file with
|
|
83
|
-
*
|
|
82
|
+
* Executes a worker file with TypeScript support. This means you can import other
|
|
83
|
+
* TypeScript with fairly rich syntax, and still have that only apply to the worker
|
|
84
84
|
* thread instead of the full parent process. The worker should emit a message when
|
|
85
85
|
* complete using `parentPort`. Once it has received a single message will resolve the
|
|
86
86
|
* returned promise with that message. If you are expecting multiple messages, you will
|
|
@@ -95,4 +95,4 @@ interface TsxWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {
|
|
|
95
95
|
*/
|
|
96
96
|
declare function tsxWorkerTask<T = unknown>(filePath: URL$1, options: TsxWorkerTaskOptions): Promise<T>;
|
|
97
97
|
export { createStudioWorker as n, studioWorkerTask as r, tsxWorkerTask as t };
|
|
98
|
-
//# sourceMappingURL=tsxWorkerTask-
|
|
98
|
+
//# sourceMappingURL=tsxWorkerTask-cAuOb_uk.d.ts.map
|
|
@@ -3,8 +3,7 @@ import { createJiti } from 'jiti';
|
|
|
3
3
|
import { subdebug } from '../_exports/debug.js';
|
|
4
4
|
const debug = subdebug('importModule');
|
|
5
5
|
/**
|
|
6
|
-
* Imports a module using
|
|
7
|
-
* This is a thin wrapper around tsx to allow swapping out the underlying implementation in the future if needed.
|
|
6
|
+
* Imports a module using Jiti and returns its exports.
|
|
8
7
|
*
|
|
9
8
|
* @param filePath - Path to the module to import.
|
|
10
9
|
* @param options - Options for the importModule function.
|
|
@@ -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 '../_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
|
|
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 *\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;;;;;;;;CAQC,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli-core",
|
|
3
|
-
"version": "3.6.
|
|
3
|
+
"version": "3.6.1",
|
|
4
4
|
"description": "Sanity CLI core package",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -130,14 +130,15 @@
|
|
|
130
130
|
"obug": "^2.1.4",
|
|
131
131
|
"ora": "^9.0.0",
|
|
132
132
|
"rxjs": "^7.8.2",
|
|
133
|
-
"tsx": "^4.23.12",
|
|
134
133
|
"vite": "^8.2.2",
|
|
135
|
-
"vite-node": "^6.0.0",
|
|
136
134
|
"wrap-ansi": "^9.0.2",
|
|
137
135
|
"zod": "^4.5.2"
|
|
138
136
|
},
|
|
139
137
|
"devDependencies": {
|
|
140
138
|
"@eslint/compat": "^2.1.0",
|
|
139
|
+
"@repo/package.config": "0.0.1",
|
|
140
|
+
"@repo/tsconfig": "3.70.0",
|
|
141
|
+
"@sanity/eslint-config-cli": "1.1.3",
|
|
141
142
|
"@sanity/pkg-utils": "^12.3.4",
|
|
142
143
|
"@sanity/telemetry": "^1.1.0",
|
|
143
144
|
"@swc/cli": "^0.8.1",
|
|
@@ -150,10 +151,7 @@
|
|
|
150
151
|
"publint": "^0.3.21",
|
|
151
152
|
"sanity": "^6.11.0",
|
|
152
153
|
"typescript": "^6.0.3",
|
|
153
|
-
"vitest": "^4.1.11"
|
|
154
|
-
"@repo/package.config": "0.0.1",
|
|
155
|
-
"@repo/tsconfig": "3.70.0",
|
|
156
|
-
"@sanity/eslint-config-cli": "1.1.3"
|
|
154
|
+
"vitest": "^4.1.11"
|
|
157
155
|
},
|
|
158
156
|
"peerDependencies": {
|
|
159
157
|
"babel-plugin-react-compiler": "*",
|