@sanity/cli-core 0.0.0-20260410130107
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/LICENSE +21 -0
- package/README.md +3 -0
- package/dist/SanityCommand.js +196 -0
- package/dist/SanityCommand.js.map +1 -0
- package/dist/_exports/index.d.ts +1391 -0
- package/dist/_exports/index.js +39 -0
- package/dist/_exports/index.js.map +1 -0
- package/dist/_exports/package-manager.d.ts +33 -0
- package/dist/_exports/package-manager.js +3 -0
- package/dist/_exports/package-manager.js.map +1 -0
- package/dist/_exports/request.d.ts +79 -0
- package/dist/_exports/request.js +7 -0
- package/dist/_exports/request.js.map +1 -0
- package/dist/_exports/ux.d.ts +75 -0
- package/dist/_exports/ux.js +7 -0
- package/dist/_exports/ux.js.map +1 -0
- package/dist/config/cli/getCliConfig.js +68 -0
- package/dist/config/cli/getCliConfig.js.map +1 -0
- package/dist/config/cli/getCliConfigSync.js +51 -0
- package/dist/config/cli/getCliConfigSync.js.map +1 -0
- package/dist/config/cli/schemas.js +62 -0
- package/dist/config/cli/schemas.js.map +1 -0
- package/dist/config/cli/types/cliConfig.js +5 -0
- package/dist/config/cli/types/cliConfig.js.map +1 -0
- package/dist/config/cli/types/userViteConfig.js +5 -0
- package/dist/config/cli/types/userViteConfig.js.map +1 -0
- package/dist/config/findProjectRoot.js +62 -0
- package/dist/config/findProjectRoot.js.map +1 -0
- package/dist/config/findProjectRootSync.js +88 -0
- package/dist/config/findProjectRootSync.js.map +1 -0
- package/dist/config/studio/getStudioConfig.js +13 -0
- package/dist/config/studio/getStudioConfig.js.map +1 -0
- package/dist/config/studio/getStudioWorkspaces.js +63 -0
- package/dist/config/studio/getStudioWorkspaces.js.map +1 -0
- package/dist/config/studio/isStudioConfig.js +19 -0
- package/dist/config/studio/isStudioConfig.js.map +1 -0
- package/dist/config/studio/readStudioConfig.js +82 -0
- package/dist/config/studio/readStudioConfig.js.map +1 -0
- package/dist/config/studio/readStudioConfig.worker.js +25 -0
- package/dist/config/studio/readStudioConfig.worker.js.map +1 -0
- package/dist/config/util/configPathsSync.js +85 -0
- package/dist/config/util/configPathsSync.js.map +1 -0
- package/dist/config/util/findAppConfigPath.js +22 -0
- package/dist/config/util/findAppConfigPath.js.map +1 -0
- package/dist/config/util/findConfigsPaths.js +21 -0
- package/dist/config/util/findConfigsPaths.js.map +1 -0
- package/dist/config/util/findStudioConfigPath.js +52 -0
- package/dist/config/util/findStudioConfigPath.js.map +1 -0
- package/dist/config/util/isSanityV2StudioRoot.js +22 -0
- package/dist/config/util/isSanityV2StudioRoot.js.map +1 -0
- package/dist/config/util/recursivelyResolveProjectRoot.js +28 -0
- package/dist/config/util/recursivelyResolveProjectRoot.js.map +1 -0
- package/dist/debug.js +15 -0
- package/dist/debug.js.map +1 -0
- package/dist/errors/NonInteractiveError.js +18 -0
- package/dist/errors/NonInteractiveError.js.map +1 -0
- package/dist/errors/NotFoundError.js +27 -0
- package/dist/errors/NotFoundError.js.map +1 -0
- package/dist/errors/ProjectRootNotFoundError.js +35 -0
- package/dist/errors/ProjectRootNotFoundError.js.map +1 -0
- package/dist/exitCodes.js +17 -0
- package/dist/exitCodes.js.map +1 -0
- package/dist/loaders/studio/studioWorkerLoader.worker.js +205 -0
- package/dist/loaders/studio/studioWorkerLoader.worker.js.map +1 -0
- package/dist/loaders/studio/studioWorkerTask.js +90 -0
- package/dist/loaders/studio/studioWorkerTask.js.map +1 -0
- package/dist/loaders/tsx/tsxWorkerLoader.worker.js +11 -0
- package/dist/loaders/tsx/tsxWorkerLoader.worker.js.map +1 -0
- package/dist/loaders/tsx/tsxWorkerTask.js +34 -0
- package/dist/loaders/tsx/tsxWorkerTask.js.map +1 -0
- package/dist/request/createRequester.js +83 -0
- package/dist/request/createRequester.js.map +1 -0
- package/dist/services/apiClient.js +97 -0
- package/dist/services/apiClient.js.map +1 -0
- package/dist/services/cliTokenCache.js +25 -0
- package/dist/services/cliTokenCache.js.map +1 -0
- package/dist/services/cliUserConfig.js +144 -0
- package/dist/services/cliUserConfig.js.map +1 -0
- package/dist/services/getCliToken.js +26 -0
- package/dist/services/getCliToken.js.map +1 -0
- package/dist/telemetry/getCliTelemetry.js +47 -0
- package/dist/telemetry/getCliTelemetry.js.map +1 -0
- package/dist/telemetry/getTelemetryBaseInfo.js +33 -0
- package/dist/telemetry/getTelemetryBaseInfo.js.map +1 -0
- package/dist/telemetry/readNDJSON.js +18 -0
- package/dist/telemetry/readNDJSON.js.map +1 -0
- package/dist/telemetry/types.js +5 -0
- package/dist/telemetry/types.js.map +1 -0
- package/dist/types.js +5 -0
- package/dist/types.js.map +1 -0
- package/dist/util/doImport.js +17 -0
- package/dist/util/doImport.js.map +1 -0
- package/dist/util/environment/getStudioEnvironmentVariables.js +36 -0
- package/dist/util/environment/getStudioEnvironmentVariables.js.map +1 -0
- package/dist/util/environment/mockBrowserEnvironment.js +47 -0
- package/dist/util/environment/mockBrowserEnvironment.js.map +1 -0
- package/dist/util/environment/setupBrowserStubs.js +42 -0
- package/dist/util/environment/setupBrowserStubs.js.map +1 -0
- package/dist/util/environment/stubs.js +142 -0
- package/dist/util/environment/stubs.js.map +1 -0
- package/dist/util/fileExists.js +13 -0
- package/dist/util/fileExists.js.map +1 -0
- package/dist/util/generateHelpUrl.js +11 -0
- package/dist/util/generateHelpUrl.js.map +1 -0
- package/dist/util/getEmptyAuth.js +16 -0
- package/dist/util/getEmptyAuth.js.map +1 -0
- package/dist/util/getSanityEnvVar.js +24 -0
- package/dist/util/getSanityEnvVar.js.map +1 -0
- package/dist/util/getSanityUrl.js +9 -0
- package/dist/util/getSanityUrl.js.map +1 -0
- package/dist/util/importModule.js +32 -0
- package/dist/util/importModule.js.map +1 -0
- package/dist/util/isCi.js +7 -0
- package/dist/util/isCi.js.map +1 -0
- package/dist/util/isInteractive.js +5 -0
- package/dist/util/isInteractive.js.map +1 -0
- package/dist/util/isRecord.js +11 -0
- package/dist/util/isRecord.js.map +1 -0
- package/dist/util/isStaging.js +10 -0
- package/dist/util/isStaging.js.map +1 -0
- package/dist/util/isTrueish.js +10 -0
- package/dist/util/isTrueish.js.map +1 -0
- package/dist/util/normalizePath.js +12 -0
- package/dist/util/normalizePath.js.map +1 -0
- package/dist/util/packageManager.js +55 -0
- package/dist/util/packageManager.js.map +1 -0
- package/dist/util/promisifyWorker.js +72 -0
- package/dist/util/promisifyWorker.js.map +1 -0
- package/dist/util/readJsonFile.js +26 -0
- package/dist/util/readJsonFile.js.map +1 -0
- package/dist/util/readJsonFileSync.js +26 -0
- package/dist/util/readJsonFileSync.js.map +1 -0
- package/dist/util/readPackageJson.js +74 -0
- package/dist/util/readPackageJson.js.map +1 -0
- package/dist/util/resolveLocalPackage.js +82 -0
- package/dist/util/resolveLocalPackage.js.map +1 -0
- package/dist/util/safeStructuredClone.js +43 -0
- package/dist/util/safeStructuredClone.js.map +1 -0
- package/dist/util/tryGetDefaultExport.js +18 -0
- package/dist/util/tryGetDefaultExport.js.map +1 -0
- package/dist/util/writeJsonFileSync.js +19 -0
- package/dist/util/writeJsonFileSync.js.map +1 -0
- package/dist/ux/boxen.js +3 -0
- package/dist/ux/boxen.js.map +1 -0
- package/dist/ux/colorizeJson.js +32 -0
- package/dist/ux/colorizeJson.js.map +1 -0
- package/dist/ux/logSymbols.js +3 -0
- package/dist/ux/logSymbols.js.map +1 -0
- package/dist/ux/prompts.js +51 -0
- package/dist/ux/prompts.js.map +1 -0
- package/dist/ux/spinner.js +3 -0
- package/dist/ux/spinner.js.map +1 -0
- package/dist/ux/timer.js +29 -0
- package/dist/ux/timer.js.map +1 -0
- package/package.json +111 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/config/util/recursivelyResolveProjectRoot.ts"],"sourcesContent":["import {dirname, resolve} from 'node:path'\n\n/**\n * Result of finding a project configuration\n *\n * @public\n */\nexport interface ProjectRootResult {\n directory: string\n /**\n * Path to the project configuration file, if found.\n */\n path: string\n /**\n * Type of project root.\n */\n type: 'app' | 'studio'\n}\n\n/**\n * Generic recursive search function for project configuration files.\n *\n * @param basePath - The base path to start searching from\n * @param findConfigFn - Function that looks for config files in a given directory\n * @param projectType - The type of project ('app' | 'studio')\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion\n * @returns A promise that resolves to an object if config is found, false otherwise\n * @internal\n */\nexport async function recursivelyResolveProjectRoot(\n basePath: string,\n findConfigFn: (path: string) => Promise<string | undefined>,\n projectType: 'app' | 'studio',\n iterations = 0,\n): Promise<false | ProjectRootResult> {\n const configPath = await findConfigFn(basePath)\n\n if (configPath) {\n return {\n directory: dirname(configPath),\n path: configPath,\n type: projectType,\n }\n }\n\n const parentDir = resolve(basePath, '..')\n if (parentDir === basePath || iterations > 50) {\n // Reached root (or max depth), give up\n return false\n }\n\n return recursivelyResolveProjectRoot(parentDir, findConfigFn, projectType, iterations + 1)\n}\n"],"names":["dirname","resolve","recursivelyResolveProjectRoot","basePath","findConfigFn","projectType","iterations","configPath","directory","path","type","parentDir"],"mappings":"AAAA,SAAQA,OAAO,EAAEC,OAAO,QAAO,YAAW;AAmB1C;;;;;;;;;CASC,GACD,OAAO,eAAeC,8BACpBC,QAAgB,EAChBC,YAA2D,EAC3DC,WAA6B,EAC7BC,aAAa,CAAC;IAEd,MAAMC,aAAa,MAAMH,aAAaD;IAEtC,IAAII,YAAY;QACd,OAAO;YACLC,WAAWR,QAAQO;YACnBE,MAAMF;YACNG,MAAML;QACR;IACF;IAEA,MAAMM,YAAYV,QAAQE,UAAU;IACpC,IAAIQ,cAAcR,YAAYG,aAAa,IAAI;QAC7C,uCAAuC;QACvC,OAAO;IACT;IAEA,OAAOJ,8BAA8BS,WAAWP,cAAcC,aAAaC,aAAa;AAC1F"}
|
package/dist/debug.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import debugIt from 'debug';
|
|
2
|
+
/**
|
|
3
|
+
* `debug` instance for the CLI
|
|
4
|
+
*
|
|
5
|
+
* @internal
|
|
6
|
+
*/ export const debug = debugIt('sanity:cli');
|
|
7
|
+
/**
|
|
8
|
+
* Get a `debug` instance which extends the CLI debug instance with the given namespace,
|
|
9
|
+
* eg namespace would be `sanity:cli:<providedNamespace>`
|
|
10
|
+
*
|
|
11
|
+
* @param namespace - The namespace to extend the CLI debug instance with
|
|
12
|
+
* @returns The extended `debug` instance
|
|
13
|
+
*/ export const subdebug = (namespace)=>debug.extend(namespace);
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=debug.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { CLIError } from '@oclif/core/errors';
|
|
2
|
+
/**
|
|
3
|
+
* Error thrown when a prompt is attempted in a non-interactive environment
|
|
4
|
+
* (e.g., CI, non-TTY, piped stdin). Callers can catch this specific error
|
|
5
|
+
* to provide appropriate fallback behavior.
|
|
6
|
+
*
|
|
7
|
+
* Extends `CLIError` to suppress stack traces in user-facing output.
|
|
8
|
+
*/ export class NonInteractiveError extends CLIError {
|
|
9
|
+
constructor(promptName){
|
|
10
|
+
super(`Cannot run "${promptName}" prompt in a non-interactive environment. ` + 'Provide the required value via flags or environment variables, or run in an interactive terminal.', {
|
|
11
|
+
code: 'NON_INTERACTIVE',
|
|
12
|
+
exit: 1
|
|
13
|
+
});
|
|
14
|
+
this.name = 'NonInteractiveError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=NonInteractiveError.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/errors/NonInteractiveError.ts"],"sourcesContent":["import {CLIError} from '@oclif/core/errors'\n\n/**\n * Error thrown when a prompt is attempted in a non-interactive environment\n * (e.g., CI, non-TTY, piped stdin). Callers can catch this specific error\n * to provide appropriate fallback behavior.\n *\n * Extends `CLIError` to suppress stack traces in user-facing output.\n */\nexport class NonInteractiveError extends CLIError {\n constructor(promptName: string) {\n super(\n `Cannot run \"${promptName}\" prompt in a non-interactive environment. ` +\n 'Provide the required value via flags or environment variables, or run in an interactive terminal.',\n {code: 'NON_INTERACTIVE', exit: 1},\n )\n this.name = 'NonInteractiveError'\n }\n}\n"],"names":["CLIError","NonInteractiveError","promptName","code","exit","name"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,qBAAoB;AAE3C;;;;;;CAMC,GACD,OAAO,MAAMC,4BAA4BD;IACvC,YAAYE,UAAkB,CAAE;QAC9B,KAAK,CACH,CAAC,YAAY,EAAEA,WAAW,2CAA2C,CAAC,GACpE,qGACF;YAACC,MAAM;YAAmBC,MAAM;QAAC;QAEnC,IAAI,CAACC,IAAI,GAAG;IACd;AACF"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { isRecord } from '../util/isRecord.js';
|
|
2
|
+
/**
|
|
3
|
+
* Error thrown when a file or directory is not found
|
|
4
|
+
*
|
|
5
|
+
* `code` is always `ENOENT` to mirror Node.js behavior when a file is not found
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/ export class NotFoundError extends Error {
|
|
9
|
+
code = 'ENOENT';
|
|
10
|
+
path;
|
|
11
|
+
constructor(message, path){
|
|
12
|
+
super(message);
|
|
13
|
+
this.path = path;
|
|
14
|
+
this.name = 'NotFoundError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Returns whether or not the given error is a `NotFoundError`
|
|
19
|
+
*
|
|
20
|
+
* @param err - The error to check
|
|
21
|
+
* @returns `true` if the error is a `NotFoundError`, `false` otherwise
|
|
22
|
+
* @internal
|
|
23
|
+
*/ export function isNotFoundError(err) {
|
|
24
|
+
return isRecord(err) && 'name' in err && err.name === 'NotFoundError' && 'code' in err && err.code === 'ENOENT' && 'message' in err && typeof err.message === 'string';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=NotFoundError.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/errors/NotFoundError.ts"],"sourcesContent":["import {isRecord} from '../util/isRecord.js'\n\n/**\n * Error thrown when a file or directory is not found\n *\n * `code` is always `ENOENT` to mirror Node.js behavior when a file is not found\n *\n * @internal\n */\nexport class NotFoundError extends Error {\n code = 'ENOENT'\n path?: string\n\n constructor(message: string, path?: string) {\n super(message)\n this.path = path\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Returns whether or not the given error is a `NotFoundError`\n *\n * @param err - The error to check\n * @returns `true` if the error is a `NotFoundError`, `false` otherwise\n * @internal\n */\nexport function isNotFoundError(err: unknown): err is NotFoundError {\n return (\n isRecord(err) &&\n 'name' in err &&\n err.name === 'NotFoundError' &&\n 'code' in err &&\n err.code === 'ENOENT' &&\n 'message' in err &&\n typeof err.message === 'string'\n )\n}\n"],"names":["isRecord","NotFoundError","Error","code","path","message","name","isNotFoundError","err"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,sBAAqB;AAE5C;;;;;;CAMC,GACD,OAAO,MAAMC,sBAAsBC;IACjCC,OAAO,SAAQ;IACfC,KAAa;IAEb,YAAYC,OAAe,EAAED,IAAa,CAAE;QAC1C,KAAK,CAACC;QACN,IAAI,CAACD,IAAI,GAAGA;QACZ,IAAI,CAACE,IAAI,GAAG;IACd;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,gBAAgBC,GAAY;IAC1C,OACER,SAASQ,QACT,UAAUA,OACVA,IAAIF,IAAI,KAAK,mBACb,UAAUE,OACVA,IAAIL,IAAI,KAAK,YACb,aAAaK,OACb,OAAOA,IAAIH,OAAO,KAAK;AAE3B"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { CLIError } from '@oclif/core/errors';
|
|
2
|
+
import { isRecord } from '../util/isRecord.js';
|
|
3
|
+
/**
|
|
4
|
+
* Error thrown when a project root directory cannot be found.
|
|
5
|
+
*
|
|
6
|
+
* This occurs when the CLI is run outside a Sanity project directory
|
|
7
|
+
* (one containing `sanity.config.(ts|js)` or `sanity.cli.(ts|js)`).
|
|
8
|
+
*
|
|
9
|
+
* Extends `CLIError` to suppress stack traces in user-facing output.
|
|
10
|
+
*
|
|
11
|
+
* @internal
|
|
12
|
+
*/ export class ProjectRootNotFoundError extends CLIError {
|
|
13
|
+
constructor(message, options){
|
|
14
|
+
super(message, {
|
|
15
|
+
code: 'PROJECT_ROOT_NOT_FOUND',
|
|
16
|
+
exit: 1,
|
|
17
|
+
suggestions: options?.suggestions
|
|
18
|
+
});
|
|
19
|
+
this.name = 'ProjectRootNotFoundError';
|
|
20
|
+
if (options?.cause) {
|
|
21
|
+
this.cause = options.cause;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Returns whether or not the given error is a `ProjectRootNotFoundError`
|
|
27
|
+
*
|
|
28
|
+
* @param err - The error to check
|
|
29
|
+
* @returns `true` if the error is a `ProjectRootNotFoundError`, `false` otherwise
|
|
30
|
+
* @internal
|
|
31
|
+
*/ export function isProjectRootNotFoundError(err) {
|
|
32
|
+
return isRecord(err) && 'name' in err && err.name === 'ProjectRootNotFoundError' && 'code' in err && err.code === 'PROJECT_ROOT_NOT_FOUND' && 'message' in err && typeof err.message === 'string';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=ProjectRootNotFoundError.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/errors/ProjectRootNotFoundError.ts"],"sourcesContent":["import {CLIError} from '@oclif/core/errors'\n\nimport {isRecord} from '../util/isRecord.js'\n\n/**\n * Error thrown when a project root directory cannot be found.\n *\n * This occurs when the CLI is run outside a Sanity project directory\n * (one containing `sanity.config.(ts|js)` or `sanity.cli.(ts|js)`).\n *\n * Extends `CLIError` to suppress stack traces in user-facing output.\n *\n * @internal\n */\nexport class ProjectRootNotFoundError extends CLIError {\n constructor(message: string, options?: {cause?: Error; suggestions?: string[]}) {\n super(message, {code: 'PROJECT_ROOT_NOT_FOUND', exit: 1, suggestions: options?.suggestions})\n this.name = 'ProjectRootNotFoundError'\n if (options?.cause) {\n this.cause = options.cause\n }\n }\n}\n\n/**\n * Returns whether or not the given error is a `ProjectRootNotFoundError`\n *\n * @param err - The error to check\n * @returns `true` if the error is a `ProjectRootNotFoundError`, `false` otherwise\n * @internal\n */\nexport function isProjectRootNotFoundError(err: unknown): err is ProjectRootNotFoundError {\n return (\n isRecord(err) &&\n 'name' in err &&\n err.name === 'ProjectRootNotFoundError' &&\n 'code' in err &&\n err.code === 'PROJECT_ROOT_NOT_FOUND' &&\n 'message' in err &&\n typeof err.message === 'string'\n )\n}\n"],"names":["CLIError","isRecord","ProjectRootNotFoundError","message","options","code","exit","suggestions","name","cause","isProjectRootNotFoundError","err"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,qBAAoB;AAE3C,SAAQC,QAAQ,QAAO,sBAAqB;AAE5C;;;;;;;;;CASC,GACD,OAAO,MAAMC,iCAAiCF;IAC5C,YAAYG,OAAe,EAAEC,OAAiD,CAAE;QAC9E,KAAK,CAACD,SAAS;YAACE,MAAM;YAA0BC,MAAM;YAAGC,aAAaH,SAASG;QAAW;QAC1F,IAAI,CAACC,IAAI,GAAG;QACZ,IAAIJ,SAASK,OAAO;YAClB,IAAI,CAACA,KAAK,GAAGL,QAAQK,KAAK;QAC5B;IACF;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,2BAA2BC,GAAY;IACrD,OACEV,SAASU,QACT,UAAUA,OACVA,IAAIH,IAAI,KAAK,8BACb,UAAUG,OACVA,IAAIN,IAAI,KAAK,4BACb,aAAaM,OACb,OAAOA,IAAIR,OAAO,KAAK;AAE3B"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard exit codes for CLI commands.
|
|
3
|
+
*
|
|
4
|
+
* - 0, 1, 2 align with oclif defaults and Unix convention.
|
|
5
|
+
* - 3 is application-defined (oclif does not use it).
|
|
6
|
+
* - 130 follows the Unix convention of 128 + signal number (SIGINT = 2).
|
|
7
|
+
*
|
|
8
|
+
* @see CLAUDE.md "Exit Code Convention" for usage guidance and examples.
|
|
9
|
+
*/ export const exitCodes = {
|
|
10
|
+
/** Something went wrong that is not the user's fault (API errors, network, missing config, etc.). */ RUNTIME_ERROR: 1,
|
|
11
|
+
/** The user interrupted via Ctrl+C (128 + SIGINT). Handled by SanityCommand.catch(). */ SIGINT: 130,
|
|
12
|
+
/** Command completed normally. */ SUCCESS: 0,
|
|
13
|
+
/** The user provided invalid input (bad args, unknown flags, validation failures). */ USAGE_ERROR: 2,
|
|
14
|
+
/** The user declined a confirmation or chose not to proceed. */ USER_ABORT: 3
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=exitCodes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/exitCodes.ts"],"sourcesContent":["/**\n * Standard exit codes for CLI commands.\n *\n * - 0, 1, 2 align with oclif defaults and Unix convention.\n * - 3 is application-defined (oclif does not use it).\n * - 130 follows the Unix convention of 128 + signal number (SIGINT = 2).\n *\n * @see CLAUDE.md \"Exit Code Convention\" for usage guidance and examples.\n */\nexport const exitCodes = {\n /** Something went wrong that is not the user's fault (API errors, network, missing config, etc.). */\n RUNTIME_ERROR: 1,\n /** The user interrupted via Ctrl+C (128 + SIGINT). Handled by SanityCommand.catch(). */\n SIGINT: 130,\n /** Command completed normally. */\n SUCCESS: 0,\n /** The user provided invalid input (bad args, unknown flags, validation failures). */\n USAGE_ERROR: 2,\n /** The user declined a confirmation or chose not to proceed. */\n USER_ABORT: 3,\n} as const\n"],"names":["exitCodes","RUNTIME_ERROR","SIGINT","SUCCESS","USAGE_ERROR","USER_ABORT"],"mappings":"AAAA;;;;;;;;CAQC,GACD,OAAO,MAAMA,YAAY;IACvB,mGAAmG,GACnGC,eAAe;IACf,sFAAsF,GACtFC,QAAQ;IACR,gCAAgC,GAChCC,SAAS;IACT,oFAAoF,GACpFC,aAAa;IACb,8DAA8D,GAC9DC,YAAY;AACd,EAAU"}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { dirname, resolve as resolvePath } from 'node:path';
|
|
2
|
+
import { isMainThread } from 'node:worker_threads';
|
|
3
|
+
import { getTsconfig } from 'get-tsconfig';
|
|
4
|
+
import { createServer, loadEnv, mergeConfig } from 'vite';
|
|
5
|
+
import { ViteNodeRunner } from 'vite-node/client';
|
|
6
|
+
import { ViteNodeServer } from 'vite-node/server';
|
|
7
|
+
import { installSourcemapsSupport } from 'vite-node/source-map';
|
|
8
|
+
import { getCliConfig } from '../../config/cli/getCliConfig.js';
|
|
9
|
+
import { subdebug } from '../../debug.js';
|
|
10
|
+
import { isNotFoundError } from '../../errors/NotFoundError.js';
|
|
11
|
+
import { getStudioEnvironmentVariables } from '../../util/environment/getStudioEnvironmentVariables.js';
|
|
12
|
+
import { setupBrowserStubs } from '../../util/environment/setupBrowserStubs.js';
|
|
13
|
+
import { isRecord } from '../../util/isRecord.js';
|
|
14
|
+
if (isMainThread) {
|
|
15
|
+
throw new Error('Should be child of thread, not the main thread');
|
|
16
|
+
}
|
|
17
|
+
const rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH;
|
|
18
|
+
if (!rootPath) {
|
|
19
|
+
throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable');
|
|
20
|
+
}
|
|
21
|
+
const debug = subdebug('studio:worker');
|
|
22
|
+
const workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE;
|
|
23
|
+
if (!workerScriptPath) {
|
|
24
|
+
throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable');
|
|
25
|
+
}
|
|
26
|
+
await setupBrowserStubs();
|
|
27
|
+
const studioEnvVars = await getStudioEnvironmentVariables(rootPath);
|
|
28
|
+
// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can
|
|
29
|
+
// extend/modify the default vite configuration for the studio.
|
|
30
|
+
let cliConfig;
|
|
31
|
+
try {
|
|
32
|
+
cliConfig = await getCliConfig(rootPath);
|
|
33
|
+
} catch (err) {
|
|
34
|
+
debug('Failed to load CLI config: %o', err);
|
|
35
|
+
if (!isNotFoundError(err)) {
|
|
36
|
+
// eslint-disable-next-line no-console
|
|
37
|
+
console.warn('[warn] Failed to load CLI config:', err);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Reads tsconfig.json `paths` and converts them to Vite `resolve.alias` entries.
|
|
42
|
+
* This allows studio projects using path aliases (e.g. `"@/*": ["./src/*"]`) to work
|
|
43
|
+
* with CLI worker commands without requiring the user to manually add `vite-tsconfig-paths`.
|
|
44
|
+
*/ function getTsconfigPathAliases(studioRootPath) {
|
|
45
|
+
const tsconfig = getTsconfig(studioRootPath);
|
|
46
|
+
if (!tsconfig) return {};
|
|
47
|
+
const { baseUrl, paths } = tsconfig.config.compilerOptions ?? {};
|
|
48
|
+
if (!paths) return {};
|
|
49
|
+
const tsconfigDir = dirname(tsconfig.path);
|
|
50
|
+
const base = baseUrl ? resolvePath(tsconfigDir, baseUrl) : tsconfigDir;
|
|
51
|
+
const aliases = {};
|
|
52
|
+
for (const [pattern, targets] of Object.entries(paths)){
|
|
53
|
+
if (!targets || targets.length === 0) continue;
|
|
54
|
+
// Only the first target is used — multiple fallback targets are not supported
|
|
55
|
+
const target = targets[0];
|
|
56
|
+
if (pattern.endsWith('/*') && target.endsWith('/*')) {
|
|
57
|
+
// Wildcard: "@/*" => "./src/*" becomes "@" => "/abs/path/src"
|
|
58
|
+
aliases[pattern.slice(0, -2)] = resolvePath(base, target.slice(0, -2));
|
|
59
|
+
} else {
|
|
60
|
+
// Exact: "@utils" => "./src/utils/index"
|
|
61
|
+
aliases[pattern] = resolvePath(base, target);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// Sort by key length descending so more-specific aliases take precedence
|
|
65
|
+
// (e.g. "@lib" is matched before "@" when both exist)
|
|
66
|
+
return Object.fromEntries(Object.entries(aliases).toSorted(([a], [b])=>b.length - a.length));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Fetches and caches modules from HTTP/HTTPS URLs.
|
|
70
|
+
* Vite's SSR transform treats `https://` imports as external and bypasses the plugin
|
|
71
|
+
* resolve pipeline entirely, so we intercept them at the ViteNodeRunner level instead.
|
|
72
|
+
*/ const httpModuleCache = new Map();
|
|
73
|
+
async function fetchHttpModule(url) {
|
|
74
|
+
const cached = httpModuleCache.get(url);
|
|
75
|
+
if (cached) return {
|
|
76
|
+
code: cached
|
|
77
|
+
};
|
|
78
|
+
debug('Fetching HTTP import: %s', url);
|
|
79
|
+
const response = await fetch(url, {
|
|
80
|
+
signal: AbortSignal.timeout(30_000)
|
|
81
|
+
});
|
|
82
|
+
if (!response.ok) {
|
|
83
|
+
throw new Error(`Failed to fetch module from ${url}: ${response.status} ${response.statusText}`);
|
|
84
|
+
}
|
|
85
|
+
const code = await response.text();
|
|
86
|
+
httpModuleCache.set(url, code);
|
|
87
|
+
return {
|
|
88
|
+
code
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
function isHttpsUrl(id) {
|
|
92
|
+
return id.startsWith('https://');
|
|
93
|
+
}
|
|
94
|
+
let tsconfigAliases = {};
|
|
95
|
+
try {
|
|
96
|
+
tsconfigAliases = getTsconfigPathAliases(rootPath);
|
|
97
|
+
} catch (err) {
|
|
98
|
+
debug('Failed to read tsconfig paths: %o', err);
|
|
99
|
+
}
|
|
100
|
+
const defaultViteConfig = {
|
|
101
|
+
build: {
|
|
102
|
+
target: 'node'
|
|
103
|
+
},
|
|
104
|
+
configFile: false,
|
|
105
|
+
// Inject environment variables as compile-time constants for Vite
|
|
106
|
+
define: Object.fromEntries(Object.entries(studioEnvVars).map(([key, value])=>[
|
|
107
|
+
`process.env.${key}`,
|
|
108
|
+
JSON.stringify(value)
|
|
109
|
+
])),
|
|
110
|
+
envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',
|
|
111
|
+
esbuild: {
|
|
112
|
+
jsx: 'automatic'
|
|
113
|
+
},
|
|
114
|
+
logLevel: 'error',
|
|
115
|
+
optimizeDeps: {
|
|
116
|
+
include: undefined,
|
|
117
|
+
noDiscovery: true
|
|
118
|
+
},
|
|
119
|
+
resolve: {
|
|
120
|
+
alias: tsconfigAliases
|
|
121
|
+
},
|
|
122
|
+
root: rootPath,
|
|
123
|
+
server: {
|
|
124
|
+
hmr: false,
|
|
125
|
+
watch: null
|
|
126
|
+
},
|
|
127
|
+
ssr: {
|
|
128
|
+
/**
|
|
129
|
+
* We don't want to externalize any dependencies, we want everything to run thru vite.
|
|
130
|
+
* Especially for CJS compatibility, etc.
|
|
131
|
+
*/ noExternal: true
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
// Merge the CLI config's Vite config with the default Vite config
|
|
135
|
+
let viteConfig = defaultViteConfig;
|
|
136
|
+
if (typeof cliConfig?.vite === 'function') {
|
|
137
|
+
viteConfig = await cliConfig.vite(viteConfig, {
|
|
138
|
+
command: 'build',
|
|
139
|
+
isSsrBuild: true,
|
|
140
|
+
mode: 'production'
|
|
141
|
+
});
|
|
142
|
+
} else if (isRecord(cliConfig?.vite)) {
|
|
143
|
+
viteConfig = mergeConfig(viteConfig, cliConfig.vite);
|
|
144
|
+
}
|
|
145
|
+
debug('Creating Vite server with config: %o', viteConfig);
|
|
146
|
+
// Vite will build the files we give it - targetting Node.js instead of the browser.
|
|
147
|
+
// We include the inject plugin in order to provide the stubs for the undefined global APIs.
|
|
148
|
+
const server = await createServer(viteConfig);
|
|
149
|
+
// Bit of a hack, but seems necessary based on the `node-vite` binary implementation
|
|
150
|
+
await server.pluginContainer.buildStart({});
|
|
151
|
+
// Load environment variables from `.env` files in the same way as Vite does.
|
|
152
|
+
// Note that Sanity also provides environment variables through `process.env.*` for compat reasons,
|
|
153
|
+
// and so we need to do the same here.
|
|
154
|
+
// Load ALL env vars from .env files (not just studio-prefixed ones) so non-Sanity-prefixed
|
|
155
|
+
// vars (e.g. NEXT_PUBLIC_*, VITE_*) are available via process.env at runtime.
|
|
156
|
+
// The ??= on the next line prevents overwriting existing process.env values.
|
|
157
|
+
const env = loadEnv(server.config.mode, server.config.envDir, '');
|
|
158
|
+
for(const key in env){
|
|
159
|
+
process.env[key] ??= env[key];
|
|
160
|
+
}
|
|
161
|
+
// Now we're providing the glue that ensures node-specific loading and execution works.
|
|
162
|
+
const node = new ViteNodeServer(server);
|
|
163
|
+
// Should make it easier to debug any crashes in the imported code…
|
|
164
|
+
installSourcemapsSupport({
|
|
165
|
+
getSourceMap: (source)=>node.getSourceMap(source)
|
|
166
|
+
});
|
|
167
|
+
const runner = new ViteNodeRunner({
|
|
168
|
+
base: server.config.base,
|
|
169
|
+
async fetchModule (id) {
|
|
170
|
+
// Vite's SSR transform externalizes https:// imports, so Node's ESM loader
|
|
171
|
+
// would reject them. We fetch the module over HTTP and run it through Vite's
|
|
172
|
+
// SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*
|
|
173
|
+
// format that ViteNodeRunner expects.
|
|
174
|
+
if (isHttpsUrl(id)) {
|
|
175
|
+
const { code: rawCode } = await fetchHttpModule(id);
|
|
176
|
+
const result = await server.ssrTransform(rawCode, null, id);
|
|
177
|
+
return {
|
|
178
|
+
code: result?.code || rawCode
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
return node.fetchModule(id);
|
|
182
|
+
},
|
|
183
|
+
resolveId (id, importer) {
|
|
184
|
+
// Prevent vite-node from trying to resolve HTTP URLs through Node's resolver
|
|
185
|
+
if (isHttpsUrl(id)) return {
|
|
186
|
+
id
|
|
187
|
+
};
|
|
188
|
+
// Resolve any import from an HTTP-fetched module against the remote origin
|
|
189
|
+
// (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)
|
|
190
|
+
if (importer && isHttpsUrl(importer)) {
|
|
191
|
+
return {
|
|
192
|
+
id: new URL(id, importer).href
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
return node.resolveId(id, importer);
|
|
196
|
+
},
|
|
197
|
+
root: server.config.root
|
|
198
|
+
});
|
|
199
|
+
// Copied from `vite-node` - it appears that this applies the `define` config from
|
|
200
|
+
// vite, but it also takes a surprisingly long time to execute. Not clear at this
|
|
201
|
+
// point why this is, so we should investigate whether it's necessary or not.
|
|
202
|
+
await runner.executeId('/@vite/env');
|
|
203
|
+
await runner.executeId(workerScriptPath);
|
|
204
|
+
|
|
205
|
+
//# sourceMappingURL=studioWorkerLoader.worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {dirname, resolve as resolvePath} from 'node:path'\nimport {isMainThread} from 'node:worker_threads'\n\nimport {getTsconfig} from 'get-tsconfig'\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 * Reads tsconfig.json `paths` and converts them to Vite `resolve.alias` entries.\n * This allows studio projects using path aliases (e.g. `\"@/*\": [\"./src/*\"]`) to work\n * with CLI worker commands without requiring the user to manually add `vite-tsconfig-paths`.\n */\nfunction getTsconfigPathAliases(studioRootPath: string): Record<string, string> {\n const tsconfig = getTsconfig(studioRootPath)\n if (!tsconfig) return {}\n\n const {baseUrl, paths} = tsconfig.config.compilerOptions ?? {}\n if (!paths) return {}\n\n const tsconfigDir = dirname(tsconfig.path)\n const base = baseUrl ? resolvePath(tsconfigDir, baseUrl) : tsconfigDir\n\n const aliases: Record<string, string> = {}\n for (const [pattern, targets] of Object.entries(paths)) {\n if (!targets || targets.length === 0) continue\n // Only the first target is used — multiple fallback targets are not supported\n const target = targets[0]\n\n if (pattern.endsWith('/*') && target.endsWith('/*')) {\n // Wildcard: \"@/*\" => \"./src/*\" becomes \"@\" => \"/abs/path/src\"\n aliases[pattern.slice(0, -2)] = resolvePath(base, target.slice(0, -2))\n } else {\n // Exact: \"@utils\" => \"./src/utils/index\"\n aliases[pattern] = resolvePath(base, target)\n }\n }\n // Sort by key length descending so more-specific aliases take precedence\n // (e.g. \"@lib\" is matched before \"@\" when both exist)\n return Object.fromEntries(Object.entries(aliases).toSorted(([a], [b]) => b.length - a.length))\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\nlet tsconfigAliases: Record<string, string> = {}\ntry {\n tsconfigAliases = getTsconfigPathAliases(rootPath)\n} catch (err) {\n debug('Failed to read tsconfig paths: %o', err)\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 alias: tsconfigAliases,\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":["dirname","resolve","resolvePath","isMainThread","getTsconfig","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","getTsconfigPathAliases","studioRootPath","tsconfig","baseUrl","paths","config","compilerOptions","tsconfigDir","path","base","aliases","pattern","targets","Object","entries","length","target","endsWith","slice","fromEntries","toSorted","a","b","httpModuleCache","Map","fetchHttpModule","url","cached","get","code","response","fetch","signal","AbortSignal","timeout","ok","status","statusText","text","set","isHttpsUrl","id","startsWith","tsconfigAliases","defaultViteConfig","build","configFile","define","map","key","value","JSON","stringify","envPrefix","esbuild","jsx","logLevel","optimizeDeps","include","undefined","noDiscovery","alias","root","server","hmr","watch","ssr","noExternal","viteConfig","vite","command","isSsrBuild","mode","pluginContainer","buildStart","envDir","node","getSourceMap","source","runner","fetchModule","rawCode","result","ssrTransform","resolveId","importer","URL","href","executeId"],"mappings":"AAAA,SAAQA,OAAO,EAAEC,WAAWC,WAAW,QAAO,YAAW;AACzD,SAAQC,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,WAAW,QAAO,eAAc;AACxC,SAAQC,YAAY,EAAqB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
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { Worker } from 'node:worker_threads';
|
|
3
|
+
import { isRecord } from '../../util/isRecord.js';
|
|
4
|
+
import { promisifyWorker } from '../../util/promisifyWorker.js';
|
|
5
|
+
/**
|
|
6
|
+
* Executes a worker file in a Sanity Studio browser context.
|
|
7
|
+
*
|
|
8
|
+
* This uses a combination of vite for "bundling" + jsdom for emulating a browser
|
|
9
|
+
* environment under the hood, which means that the same thing that will work in vite
|
|
10
|
+
* _should_ work in the worker - to a degree. If the user has defined any typescript
|
|
11
|
+
* path aliases, these will have to be added as aliases to the vite config - the same
|
|
12
|
+
* behavior as you would see with regular vite. Other things that are accounted for:
|
|
13
|
+
*
|
|
14
|
+
* - TypeScript support (+JSX, enums and other "compilation needed" features)
|
|
15
|
+
* - CSS, font and other file imports will resolve to a file path
|
|
16
|
+
* - CSS module imports will resolve to a javascript object of class names
|
|
17
|
+
* - Environment variables are available both as `import.meta.env` and `process.env`,
|
|
18
|
+
* and `.env` files are loaded in the same way that they would in a Sanity studio.
|
|
19
|
+
* - Browser globals not available in a Node.js environment but _are_ provided by JSDOM
|
|
20
|
+
* are defined directly to the Node environment as globals. While this polutes the
|
|
21
|
+
* global namespace, it is done only in the worker thread.
|
|
22
|
+
* - Certain browser globals that are _not_ available in JSDOM are also provided to the
|
|
23
|
+
* global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.
|
|
24
|
+
* These are provided with a minimal stub implementation to make them not crash.
|
|
25
|
+
*
|
|
26
|
+
* @param filePath - Path to the worker file (`.ts` works and is encouraged)
|
|
27
|
+
* @param options - Options to pass to the worker
|
|
28
|
+
* @returns A promise that resolves with the message from the worker
|
|
29
|
+
* @throws If the file does not exist
|
|
30
|
+
* @throws If the worker exits with a non-zero code
|
|
31
|
+
* @internal
|
|
32
|
+
*/ export function studioWorkerTask(filePath, options) {
|
|
33
|
+
const normalizedFilePath = fileURLToPath(filePath);
|
|
34
|
+
if (!/\.worker\.(js|ts)$/.test(normalizedFilePath)) {
|
|
35
|
+
throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path');
|
|
36
|
+
}
|
|
37
|
+
const { studioRootPath, timeout, ...workerOptions } = options;
|
|
38
|
+
return promisifyWorker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
|
|
39
|
+
...workerOptions,
|
|
40
|
+
env: {
|
|
41
|
+
...isRecord(workerOptions.env) ? workerOptions.env : process.env,
|
|
42
|
+
STUDIO_WORKER_STUDIO_ROOT_PATH: studioRootPath,
|
|
43
|
+
STUDIO_WORKER_TASK_FILE: normalizedFilePath
|
|
44
|
+
},
|
|
45
|
+
timeout
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Creates a new worker for a studio worker task.
|
|
50
|
+
*
|
|
51
|
+
* This uses a combination of vite for "bundling" + jsdom for emulating a browser
|
|
52
|
+
* environment under the hood, which means that the same thing that will work in vite
|
|
53
|
+
* _should_ work in the worker - to a degree. If the user has defined any typescript
|
|
54
|
+
* path aliases, these will have to be added as aliases to the vite config - the same
|
|
55
|
+
* behavior as you would see with regular vite. Other things that are accounted for:
|
|
56
|
+
*
|
|
57
|
+
* - TypeScript support (+JSX, enums and other "compilation needed" features)
|
|
58
|
+
* - CSS, font and other file imports will resolve to a file path
|
|
59
|
+
* - CSS module imports will resolve to a javascript object of class names
|
|
60
|
+
* - Environment variables are available both as `import.meta.env` and `process.env`,
|
|
61
|
+
* and `.env` files are loaded in the same way that they would in a Sanity studio.
|
|
62
|
+
* - Browser globals not available in a Node.js environment but _are_ provided by JSDOM
|
|
63
|
+
* are defined directly to the Node environment as globals. While this polutes the
|
|
64
|
+
* global namespace, it is done only in the worker thread.
|
|
65
|
+
* - Certain browser globals that are _not_ available in JSDOM are also provided to the
|
|
66
|
+
* global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.
|
|
67
|
+
* These are provided with a minimal stub implementation to make them not crash.
|
|
68
|
+
*
|
|
69
|
+
* @param filePath - Path to the worker file (`.ts` works and is encouraged)
|
|
70
|
+
* @param options - Options to pass to the worker
|
|
71
|
+
* @returns A promise that resolves with the message from the worker
|
|
72
|
+
* @throws If the file does not exist
|
|
73
|
+
* @throws If the worker exits with a non-zero code
|
|
74
|
+
* @internal
|
|
75
|
+
*/ export function createStudioWorker(filePath, options) {
|
|
76
|
+
const normalizedFilePath = fileURLToPath(filePath);
|
|
77
|
+
if (!/\.worker\.(js|ts)$/.test(normalizedFilePath)) {
|
|
78
|
+
throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path');
|
|
79
|
+
}
|
|
80
|
+
return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
|
|
81
|
+
...options,
|
|
82
|
+
env: {
|
|
83
|
+
...isRecord(options.env) ? options.env : process.env,
|
|
84
|
+
STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,
|
|
85
|
+
STUDIO_WORKER_TASK_FILE: normalizedFilePath
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=studioWorkerTask.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerTask.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\n\n/**\n * Options for the studio worker task\n *\n * @internal\n */\ninterface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n studioRootPath: string\n\n /** Optional timeout in milliseconds. If the worker does not respond within this time, it will be terminated and the promise rejected. */\n timeout?: number\n}\n\n/**\n * Executes a worker file in a Sanity Studio browser context.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function studioWorkerTask<T = unknown>(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<T> {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n const {studioRootPath, timeout, ...workerOptions} = options\n return promisifyWorker<T>(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...workerOptions,\n env: {\n ...(isRecord(workerOptions.env) ? workerOptions.env : process.env),\n STUDIO_WORKER_STUDIO_ROOT_PATH: studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n timeout,\n })\n}\n\n/**\n * Creates a new worker for a studio worker task.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function createStudioWorker(filePath: URL, options: StudioWorkerTaskOptions) {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...options,\n env: {\n ...(isRecord(options.env) ? options.env : process.env),\n STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n })\n}\n"],"names":["fileURLToPath","Worker","isRecord","promisifyWorker","studioWorkerTask","filePath","options","normalizedFilePath","test","Error","studioRootPath","timeout","workerOptions","URL","url","env","process","STUDIO_WORKER_STUDIO_ROOT_PATH","STUDIO_WORKER_TASK_FILE","createStudioWorker"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AACtC,SAAQC,MAAM,QAA2B,sBAAqB;AAG9D,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,gCAA+B;AAc7D;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,iBACdC,QAAa,EACbC,OAAgC;IAEhC,MAAMC,qBAAqBP,cAAcK;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,MAAM,EAACC,cAAc,EAAEC,OAAO,EAAE,GAAGC,eAAc,GAAGN;IACpD,OAAOH,gBAAmB,IAAIU,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAClF,GAAGF,aAAa;QAChBG,KAAK;YACH,GAAIb,SAASU,cAAcG,GAAG,IAAIH,cAAcG,GAAG,GAAGC,QAAQD,GAAG;YACjEE,gCAAgCP;YAChCQ,yBAAyBX;QAC3B;QACAI;IACF;AACF;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASQ,mBAAmBd,QAAa,EAAEC,OAAgC;IAChF,MAAMC,qBAAqBP,cAAcK;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,OAAO,IAAIR,OAAO,IAAIY,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAC1E,GAAGR,OAAO;QACVS,KAAK;YACH,GAAIb,SAASI,QAAQS,GAAG,IAAIT,QAAQS,GAAG,GAAGC,QAAQD,GAAG;YACrDE,gCAAgCX,QAAQI,cAAc;YACtDQ,yBAAyBX;QAC3B;IACF;AACF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { importModule } from '../../util/importModule.js';
|
|
2
|
+
const workerScript = process.env.TSX_WORKER_TASK_SCRIPT;
|
|
3
|
+
if (workerScript) {
|
|
4
|
+
await importModule(workerScript, {
|
|
5
|
+
tsconfigPath: process.env.TSX_TSCONFIG_PATH
|
|
6
|
+
});
|
|
7
|
+
} else {
|
|
8
|
+
throw new Error('`TX_WORKER_TASK_SCRIPT` not defined');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=tsxWorkerLoader.worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerLoader.worker.ts"],"sourcesContent":["import {importModule} from '../../util/importModule.js'\n\nconst workerScript = process.env.TSX_WORKER_TASK_SCRIPT\n\nif (workerScript) {\n await importModule(workerScript, {\n tsconfigPath: process.env.TSX_TSCONFIG_PATH,\n })\n} else {\n throw new Error('`TX_WORKER_TASK_SCRIPT` not defined')\n}\n"],"names":["importModule","workerScript","process","env","TSX_WORKER_TASK_SCRIPT","tsconfigPath","TSX_TSCONFIG_PATH","Error"],"mappings":"AAAA,SAAQA,YAAY,QAAO,6BAA4B;AAEvD,MAAMC,eAAeC,QAAQC,GAAG,CAACC,sBAAsB;AAEvD,IAAIH,cAAc;IAChB,MAAMD,aAAaC,cAAc;QAC/BI,cAAcH,QAAQC,GAAG,CAACG,iBAAiB;IAC7C;AACF,OAAO;IACL,MAAM,IAAIC,MAAM;AAClB"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { fileURLToPath, URL } from 'node:url';
|
|
2
|
+
import { getTsconfig } from 'get-tsconfig';
|
|
3
|
+
import { isRecord } from '../../util/isRecord.js';
|
|
4
|
+
import { promisifyWorker } from '../../util/promisifyWorker.js';
|
|
5
|
+
/**
|
|
6
|
+
* Executes a worker file with tsx registered. This means you can import other
|
|
7
|
+
* typescript with fairly rich syntax, and still have that only apply to the worker
|
|
8
|
+
* thread instead of the full parent process. The worker should emit a message when
|
|
9
|
+
* complete using `parentPort`. Once it has received a single message will resolve the
|
|
10
|
+
* returned promise with that message. If you are expecting multiple messages, you will
|
|
11
|
+
* have to implement another method ;)
|
|
12
|
+
*
|
|
13
|
+
* @param filePath - Path to the worker file
|
|
14
|
+
* @param options - Options to pass to the worker
|
|
15
|
+
* @returns A promise that resolves with the message from the worker
|
|
16
|
+
* @throws If the file does not exist
|
|
17
|
+
* @throws If the worker exits with a non-zero code
|
|
18
|
+
* @internal
|
|
19
|
+
*/ export function tsxWorkerTask(filePath, options) {
|
|
20
|
+
const tsconfig = getTsconfig(options.rootPath);
|
|
21
|
+
const env = {
|
|
22
|
+
...isRecord(options.env) ? options.env : process.env,
|
|
23
|
+
...tsconfig?.path ? {
|
|
24
|
+
TSX_TSCONFIG_PATH: tsconfig.path
|
|
25
|
+
} : {},
|
|
26
|
+
TSX_WORKER_TASK_SCRIPT: fileURLToPath(filePath)
|
|
27
|
+
};
|
|
28
|
+
return promisifyWorker(new URL('tsxWorkerLoader.worker.js', import.meta.url), {
|
|
29
|
+
...options,
|
|
30
|
+
env
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=tsxWorkerTask.js.map
|
|
@@ -0,0 +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 tsx registered. 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"}
|