@sanity/cli-core 3.5.1 → 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/SanityCommand.d.ts +2 -2
- package/dist/_exports/config.d.ts +1 -1
- package/dist/_exports/dates.d.ts +34 -0
- package/dist/_exports/dates.js +3 -0
- package/dist/_exports/dates.js.map +1 -0
- 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/{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/request/createRequester.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/dates.js +125 -0
- package/dist/util/dates.js.map +1 -0
- package/dist/util/importModule.js +1 -2
- package/dist/util/importModule.js.map +1 -1
- package/dist/ux/spinner.js +2 -2
- package/dist/ux/spinner.js.map +1 -1
- package/package.json +11 -9
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
|
|
package/dist/SanityCommand.d.ts
CHANGED
|
@@ -35,7 +35,7 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
|
|
|
35
35
|
*
|
|
36
36
|
* @deprecated use `getGlobalCliClient` function directly instead.
|
|
37
37
|
*/
|
|
38
|
-
protected getGlobalApiClient: (args: GlobalCliClientOptions) => Promise<import("
|
|
38
|
+
protected getGlobalApiClient: (args: GlobalCliClientOptions) => Promise<import("sanity").SanityClient>;
|
|
39
39
|
/**
|
|
40
40
|
* Get the project API client.
|
|
41
41
|
*
|
|
@@ -44,7 +44,7 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
|
|
|
44
44
|
*
|
|
45
45
|
* @deprecated use `getProjectCliClient` function directly instead.
|
|
46
46
|
*/
|
|
47
|
-
protected getProjectApiClient: (args: ProjectCliClientOptions) => Promise<import("
|
|
47
|
+
protected getProjectApiClient: (args: ProjectCliClientOptions) => Promise<import("sanity").SanityClient>;
|
|
48
48
|
/**
|
|
49
49
|
* Helper for outputting to the console.
|
|
50
50
|
*
|
|
@@ -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 };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formats a timestamp as `YYYY-MM-DD HH:mm:ss` in the local time zone. Unparseable
|
|
3
|
+
* timestamps are returned as-is, so a bad value from the API doesn't fail the command.
|
|
4
|
+
*
|
|
5
|
+
* @param timestamp - An ISO 8601 timestamp
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
declare function formatDateTime(timestamp: string): string;
|
|
9
|
+
/**
|
|
10
|
+
* Formats a duration in milliseconds as an approximate, human readable length of
|
|
11
|
+
* time, eg `less than a minute`, `5 minutes` or `2 days`.
|
|
12
|
+
*
|
|
13
|
+
* @param ms - The duration in milliseconds
|
|
14
|
+
* @internal
|
|
15
|
+
*/
|
|
16
|
+
declare function formatDuration(ms: number): string;
|
|
17
|
+
/**
|
|
18
|
+
* Formats a date relative to now, eg `2 days ago` or `in 3 hours`.
|
|
19
|
+
*
|
|
20
|
+
* @param date - The date to describe
|
|
21
|
+
* @param now - The reference point to compare against, defaults to the current time
|
|
22
|
+
* @internal
|
|
23
|
+
*/
|
|
24
|
+
declare function formatTimeAgo(date: Date, now?: number): string;
|
|
25
|
+
/**
|
|
26
|
+
* Parses a `YYYY-MM-DD` date into a `Date` at local midnight. Returns `undefined`
|
|
27
|
+
* for anything that isn't a real calendar date in that exact format.
|
|
28
|
+
*
|
|
29
|
+
* @param value - The date string to parse
|
|
30
|
+
* @internal
|
|
31
|
+
*/
|
|
32
|
+
declare function parseDateOnly(value: string): Date | undefined;
|
|
33
|
+
export { formatDateTime, formatDuration, formatTimeAgo, parseDateOnly };
|
|
34
|
+
//# sourceMappingURL=dates.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/dates.ts"],"sourcesContent":["export {formatDateTime, formatDuration, formatTimeAgo, parseDateOnly} from '../util/dates.js'\n"],"names":["formatDateTime","formatDuration","formatTimeAgo","parseDateOnly"],"mappings":"AAAA,SAAQA,cAAc,EAAEC,cAAc,EAAEC,aAAa,EAAEC,aAAa,QAAO,mBAAkB"}
|
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"}
|
|
@@ -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,IAA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;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","ssrT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MAAMC,aAAYpD,EAAE;YAClB,2EAA2E;YAC3E,6EAA6E;YAC7E,wEAAwE;YACxE,sCAAsC;YACtC,IAAID,WAAWC,KAAK;gBAClB,MAAM,EAACZ,MAAMiE,OAAO,EAAC,GAAG,MAAMrE,gBAAgBgB;gBAC9C,MAAMsD,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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,CAAC7F;AACtB,EAAE,OAAOqE,OAAO;IACd,yEAAyE;IACzE,wBAAwB;IACxB,IAAI,CAACL,WAAW;QACd,MAAMK;IACR;IAEA,0EAA0E;IAC1E,0EAA0E;IAC1E,6EAA6E;IAC7E,MAAML,UAAU8B,SAAS,CAACzB;AAC5B,SAAU;IACR,MAAML,WAAWG;AACnB"}
|
|
@@ -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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/request/createRequester.ts"],"sourcesContent":["import {readFileSync} from 'node:fs'\n\nimport {up as packageUp} from 'empathic/package'\nimport {\n createRequester as createGetItRequester,\n type FetchHeaders,\n type RequesterOptions,\n type RequestFunction,\n type TransformMiddleware,\n type WrappingMiddleware,\n} from 'get-it'\nimport {debug as debugMiddleware} from 'get-it/middleware'\nimport {createDebug} from 'obug'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\nlet cachedPkg: {name: string; version: string} | undefined\n\n/**\n * Options for creating a Sanity CLI requester.\n *\n * Extends get-it v9's {@link RequesterOptions} with Sanity CLI defaults for\n * User-Agent headers and debug logging.\n *\n * @public\n */\nexport type CreateRequesterOptions = Omit<RequesterOptions, 'headers'> & {\n /**\n * Debug logging middleware. Defaults to enabled with namespace `sanity:cli`.\n * Pass `false` to disable.\n */\n debug?: false | {namespace?: string; verbose?: boolean}\n /**\n * Default headers for all requests.\n * Omitting uses a lazy User-Agent of `@sanity/cli-core@<version>`.\n * Pass `false` to send no default headers.\n */\n headers?: false | Record<string, string>\n}\n\n/**\n * Creates a get-it requester with Sanity CLI defaults.\n *\n * Defaults:\n * - User-Agent header: `@sanity/cli-core@<version>` (lazy)\n * - Debug logging via `DEBUG=sanity:cli` (verbose)\n * - HTTP error throwing on (get-it default)\n *\n * @param options - Optional configuration to customize or disable defaults\n * @returns A configured get-it request function\n * @public\n */\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'json'},\n): RequestFunction<'json'>\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'text'},\n): RequestFunction<'text'>\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'stream'},\n): RequestFunction<'stream'>\nexport function createRequester(options?: CreateRequesterOptions): RequestFunction\nexport function createRequester(\n options?: CreateRequesterOptions,\n): RequestFunction<'json' | 'stream' | 'text' | undefined> {\n const {debug, headers, middleware = [], ...getItOptions} = options ?? {}\n\n // A programmatic invocation must not inherit the embedding process's DEBUG setting or write request/response bodies outside its output sinks.\n const resolvedMiddleware: Array<TransformMiddleware | WrappingMiddleware> = [...middleware]\n if (!getCliExecutionContext() && debug !== false) {\n const debugDefaults = {namespace: 'sanity:cli', verbose: true}\n const customDebug = typeof debug === 'object' ? debug : {}\n const {namespace, verbose} = {...debugDefaults, ...customDebug}\n resolvedMiddleware.push(debugMiddleware({log: createDebug(namespace), verbose}))\n }\n\n return createGetItRequester({\n ...getItOptions,\n headers: resolveDefaultHeaders(headers),\n middleware: resolvedMiddleware,\n })\n}\n\n/**\n * Builds default headers, including a lazy User-Agent unless overridden or disabled.\n *\n * @internal\n */\nfunction resolveDefaultHeaders(\n headers: false | Record<string, string> | undefined,\n): FetchHeaders | undefined {\n if (headers === false) {\n return undefined\n }\n\n const customHeaders = typeof headers === 'object' ? headers : {}\n if (Object.keys(customHeaders).some((header) => header.toLowerCase() === 'user-agent')) {\n return customHeaders\n }\n\n return {\n get ['User-Agent']() {\n const pkg = getPackageInfo()\n return `${pkg.name}@${pkg.version}`\n },\n ...customHeaders,\n }\n}\n\n/**\n * Reads the nearest `package.json` to determine the name and version of the `@sanity/cli-core` package.\n *\n * @returns The name and version of the package\n * @internal\n */\nfunction getPackageInfo(): {name: string; version: string} {\n if (cachedPkg) return cachedPkg\n\n const pkgPath = packageUp({cwd: import.meta.dirname})\n if (!pkgPath) {\n throw new Error('Unable to resolve @sanity/cli-core package root')\n }\n\n const packageJson = JSON.parse(readFileSync(pkgPath, 'utf8'))\n cachedPkg = {\n name: packageJson.name ?? '@sanity/cli-core',\n version: packageJson.version ?? '0.0.0',\n }\n return cachedPkg\n}\n"],"names":["readFileSync","up","packageUp","createRequester","createGetItRequester","debug","debugMiddleware","createDebug","getCliExecutionContext","cachedPkg","options","headers","middleware","getItOptions","resolvedMiddleware","debugDefaults","namespace","verbose","customDebug","push","log","resolveDefaultHeaders","undefined","customHeaders","Object","keys","some","header","toLowerCase","pkg","getPackageInfo","name","version","pkgPath","cwd","dirname","Error","packageJson","JSON","parse"],"mappings":"AAAA,SAAQA,YAAY,QAAO,UAAS;AAEpC,SAAQC,MAAMC,SAAS,QAAO,mBAAkB;AAChD,SACEC,mBAAmBC,oBAAoB,QAMlC,SAAQ;AACf,SAAQC,SAASC,eAAe,QAAO,oBAAmB;AAC1D,SAAQC,WAAW,QAAO,OAAM;AAEhC,SAAQC,sBAAsB,QAAO,yBAAwB;AAE7D,IAAIC;AA8CJ,OAAO,SAASN,gBACdO,OAAgC;IAEhC,MAAM,EAACL,KAAK,EAAEM,OAAO,EAAEC,aAAa,EAAE,EAAE,GAAGC,cAAa,GAAGH,WAAW,CAAC;IAEvE,8IAA8I;IAC9I,MAAMI,qBAAsE;WAAIF;KAAW;IAC3F,IAAI,CAACJ,4BAA4BH,UAAU,OAAO;QAChD,MAAMU,gBAAgB;YAACC,WAAW;YAAcC,SAAS;QAAI;QAC7D,MAAMC,cAAc,OAAOb,UAAU,WAAWA,QAAQ,CAAC;QACzD,MAAM,EAACW,SAAS,EAAEC,OAAO,EAAC,GAAG;YAAC,GAAGF,aAAa;YAAE,GAAGG,WAAW;QAAA;QAC9DJ,mBAAmBK,IAAI,CAACb,gBAAgB;YAACc,KAAKb,YAAYS;YAAYC;QAAO;IAC/E;IAEA,OAAOb,qBAAqB;QAC1B,GAAGS,YAAY;QACfF,SAASU,sBAAsBV;QAC/BC,YAAYE;IACd;AACF;AAEA;;;;CAIC,GACD,SAASO,sBACPV,OAAmD;IAEnD,IAAIA,YAAY,OAAO;QACrB,OAAOW;IACT;IAEA,MAAMC,gBAAgB,OAAOZ,YAAY,WAAWA,UAAU,CAAC;IAC/D,IAAIa,OAAOC,IAAI,CAACF,eAAeG,IAAI,CAAC,CAACC,SAAWA,OAAOC,WAAW,OAAO,eAAe;QACtF,OAAOL;IACT;IAEA,OAAO;QACL,IAAI,CAAC,aAAa
|
|
1
|
+
{"version":3,"sources":["../../src/request/createRequester.ts"],"sourcesContent":["import {readFileSync} from 'node:fs'\n\nimport {up as packageUp} from 'empathic/package'\nimport {\n createRequester as createGetItRequester,\n type FetchHeaders,\n type RequesterOptions,\n type RequestFunction,\n type TransformMiddleware,\n type WrappingMiddleware,\n} from 'get-it'\nimport {debug as debugMiddleware} from 'get-it/middleware'\nimport {createDebug} from 'obug'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\nlet cachedPkg: {name: string; version: string} | undefined\n\n/**\n * Options for creating a Sanity CLI requester.\n *\n * Extends get-it v9's {@link RequesterOptions} with Sanity CLI defaults for\n * User-Agent headers and debug logging.\n *\n * @public\n */\nexport type CreateRequesterOptions = Omit<RequesterOptions, 'headers'> & {\n /**\n * Debug logging middleware. Defaults to enabled with namespace `sanity:cli`.\n * Pass `false` to disable.\n */\n debug?: false | {namespace?: string; verbose?: boolean}\n /**\n * Default headers for all requests.\n * Omitting uses a lazy User-Agent of `@sanity/cli-core@<version>`.\n * Pass `false` to send no default headers.\n */\n headers?: false | Record<string, string>\n}\n\n/**\n * Creates a get-it requester with Sanity CLI defaults.\n *\n * Defaults:\n * - User-Agent header: `@sanity/cli-core@<version>` (lazy)\n * - Debug logging via `DEBUG=sanity:cli` (verbose)\n * - HTTP error throwing on (get-it default)\n *\n * @param options - Optional configuration to customize or disable defaults\n * @returns A configured get-it request function\n * @public\n */\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'json'},\n): RequestFunction<'json'>\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'text'},\n): RequestFunction<'text'>\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'stream'},\n): RequestFunction<'stream'>\nexport function createRequester(options?: CreateRequesterOptions): RequestFunction\nexport function createRequester(\n options?: CreateRequesterOptions,\n): RequestFunction<'json' | 'stream' | 'text' | undefined> {\n const {debug, headers, middleware = [], ...getItOptions} = options ?? {}\n\n // A programmatic invocation must not inherit the embedding process's DEBUG setting or write request/response bodies outside its output sinks.\n const resolvedMiddleware: Array<TransformMiddleware | WrappingMiddleware> = [...middleware]\n if (!getCliExecutionContext() && debug !== false) {\n const debugDefaults = {namespace: 'sanity:cli', verbose: true}\n const customDebug = typeof debug === 'object' ? debug : {}\n const {namespace, verbose} = {...debugDefaults, ...customDebug}\n resolvedMiddleware.push(debugMiddleware({log: createDebug(namespace), verbose}))\n }\n\n return createGetItRequester({\n ...getItOptions,\n headers: resolveDefaultHeaders(headers),\n middleware: resolvedMiddleware,\n })\n}\n\n/**\n * Builds default headers, including a lazy User-Agent unless overridden or disabled.\n *\n * @internal\n */\nfunction resolveDefaultHeaders(\n headers: false | Record<string, string> | undefined,\n): FetchHeaders | undefined {\n if (headers === false) {\n return undefined\n }\n\n const customHeaders = typeof headers === 'object' ? headers : {}\n if (Object.keys(customHeaders).some((header) => header.toLowerCase() === 'user-agent')) {\n return customHeaders\n }\n\n return {\n get ['User-Agent']() {\n const pkg = getPackageInfo()\n return `${pkg.name}@${pkg.version}`\n },\n ...customHeaders,\n }\n}\n\n/**\n * Reads the nearest `package.json` to determine the name and version of the `@sanity/cli-core` package.\n *\n * @returns The name and version of the package\n * @internal\n */\nfunction getPackageInfo(): {name: string; version: string} {\n if (cachedPkg) return cachedPkg\n\n const pkgPath = packageUp({cwd: import.meta.dirname})\n if (!pkgPath) {\n throw new Error('Unable to resolve @sanity/cli-core package root')\n }\n\n const packageJson = JSON.parse(readFileSync(pkgPath, 'utf8'))\n cachedPkg = {\n name: packageJson.name ?? '@sanity/cli-core',\n version: packageJson.version ?? '0.0.0',\n }\n return cachedPkg\n}\n"],"names":["readFileSync","up","packageUp","createRequester","createGetItRequester","debug","debugMiddleware","createDebug","getCliExecutionContext","cachedPkg","options","headers","middleware","getItOptions","resolvedMiddleware","debugDefaults","namespace","verbose","customDebug","push","log","resolveDefaultHeaders","undefined","customHeaders","Object","keys","some","header","toLowerCase","pkg","getPackageInfo","name","version","pkgPath","cwd","dirname","Error","packageJson","JSON","parse"],"mappings":"AAAA,SAAQA,YAAY,QAAO,UAAS;AAEpC,SAAQC,MAAMC,SAAS,QAAO,mBAAkB;AAChD,SACEC,mBAAmBC,oBAAoB,QAMlC,SAAQ;AACf,SAAQC,SAASC,eAAe,QAAO,oBAAmB;AAC1D,SAAQC,WAAW,QAAO,OAAM;AAEhC,SAAQC,sBAAsB,QAAO,yBAAwB;AAE7D,IAAIC;AA8CJ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DxB,YAAY;QACVsB,MAAMM,YAAYN,IAAI,IAAI;QAC1BC,SAASK,YAAYL,OAAO,IAAI;IAClC;IACA,OAAOvB;AACT"}
|
|
@@ -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
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
const MS_IN = {
|
|
2
|
+
day: 86_400_000,
|
|
3
|
+
hour: 3_600_000,
|
|
4
|
+
minute: 60_000,
|
|
5
|
+
month: 2_592_000_000,
|
|
6
|
+
second: 1000,
|
|
7
|
+
week: 604_800_000,
|
|
8
|
+
year: 31_536_000_000
|
|
9
|
+
};
|
|
10
|
+
/** Largest unit first, so the first unit the duration fills is the one we report. */ const UNITS = [
|
|
11
|
+
{
|
|
12
|
+
ms: MS_IN.year,
|
|
13
|
+
unit: 'year'
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
ms: MS_IN.month,
|
|
17
|
+
unit: 'month'
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
ms: MS_IN.week,
|
|
21
|
+
unit: 'week'
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
ms: MS_IN.day,
|
|
25
|
+
unit: 'day'
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
ms: MS_IN.hour,
|
|
29
|
+
unit: 'hour'
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
ms: MS_IN.minute,
|
|
33
|
+
unit: 'minute'
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
ms: MS_IN.second,
|
|
37
|
+
unit: 'second'
|
|
38
|
+
}
|
|
39
|
+
];
|
|
40
|
+
const relativeTime = new Intl.RelativeTimeFormat('en', {
|
|
41
|
+
numeric: 'always'
|
|
42
|
+
});
|
|
43
|
+
const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
44
|
+
function pad(value, length = 2) {
|
|
45
|
+
return String(value).padStart(length, '0');
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Returns the coarsest unit the elapsed time fills and the rounded number of those
|
|
49
|
+
* units, or `undefined` below a second.
|
|
50
|
+
*
|
|
51
|
+
* Rounding can land the value on the boundary of the next unit up, so we promote
|
|
52
|
+
* rather than report `60 minutes` where `1 hour` is meant. Units aren't all whole
|
|
53
|
+
* multiples of each other, so the boundary is the rounded count we'd display, which
|
|
54
|
+
* is why 25+ days reads as `1 month` rather than `4 weeks`.
|
|
55
|
+
*/ function selectUnit(elapsed) {
|
|
56
|
+
let index = UNITS.findIndex(({ ms })=>elapsed >= ms);
|
|
57
|
+
if (index === -1) return undefined;
|
|
58
|
+
while(index > 0 && Math.round(elapsed / UNITS[index].ms) >= Math.round(UNITS[index - 1].ms / UNITS[index].ms)){
|
|
59
|
+
index -= 1;
|
|
60
|
+
}
|
|
61
|
+
const { ms, unit } = UNITS[index];
|
|
62
|
+
return {
|
|
63
|
+
unit,
|
|
64
|
+
value: Math.round(elapsed / ms)
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Formats a timestamp as `YYYY-MM-DD HH:mm:ss` in the local time zone. Unparseable
|
|
69
|
+
* timestamps are returned as-is, so a bad value from the API doesn't fail the command.
|
|
70
|
+
*
|
|
71
|
+
* @param timestamp - An ISO 8601 timestamp
|
|
72
|
+
* @internal
|
|
73
|
+
*/ export function formatDateTime(timestamp) {
|
|
74
|
+
const date = new Date(timestamp);
|
|
75
|
+
if (!Number.isFinite(date.getTime())) return timestamp;
|
|
76
|
+
const day = `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
77
|
+
const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
78
|
+
return `${day} ${time}`;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Formats a duration in milliseconds as an approximate, human readable length of
|
|
82
|
+
* time, eg `less than a minute`, `5 minutes` or `2 days`.
|
|
83
|
+
*
|
|
84
|
+
* @param ms - The duration in milliseconds
|
|
85
|
+
* @internal
|
|
86
|
+
*/ export function formatDuration(ms) {
|
|
87
|
+
if (!Number.isFinite(ms)) return '';
|
|
88
|
+
const selected = selectUnit(Math.abs(ms));
|
|
89
|
+
if (!selected || selected.unit === 'second') return 'less than a minute';
|
|
90
|
+
const unit = selected.value === 1 ? selected.unit : `${selected.unit}s`;
|
|
91
|
+
return `${selected.value} ${unit}`;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Formats a date relative to now, eg `2 days ago` or `in 3 hours`.
|
|
95
|
+
*
|
|
96
|
+
* @param date - The date to describe
|
|
97
|
+
* @param now - The reference point to compare against, defaults to the current time
|
|
98
|
+
* @internal
|
|
99
|
+
*/ export function formatTimeAgo(date, now = Date.now()) {
|
|
100
|
+
const delta = date.getTime() - now;
|
|
101
|
+
if (!Number.isFinite(delta)) return '';
|
|
102
|
+
const selected = selectUnit(Math.abs(delta));
|
|
103
|
+
if (!selected) return 'just now';
|
|
104
|
+
return relativeTime.format(delta < 0 ? -selected.value : selected.value, selected.unit);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Parses a `YYYY-MM-DD` date into a `Date` at local midnight. Returns `undefined`
|
|
108
|
+
* for anything that isn't a real calendar date in that exact format.
|
|
109
|
+
*
|
|
110
|
+
* @param value - The date string to parse
|
|
111
|
+
* @internal
|
|
112
|
+
*/ export function parseDateOnly(value) {
|
|
113
|
+
const match = DATE_ONLY_PATTERN.exec(value);
|
|
114
|
+
if (!match) return undefined;
|
|
115
|
+
const year = Number(match[1]);
|
|
116
|
+
const month = Number(match[2]);
|
|
117
|
+
const day = Number(match[3]);
|
|
118
|
+
const date = new Date(year, month - 1, day);
|
|
119
|
+
// `new Date(2024, 1, 31)` silently rolls over into March, so reject anything
|
|
120
|
+
// that didn't survive the round trip
|
|
121
|
+
const isRoundTrip = date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
|
|
122
|
+
return isRoundTrip ? date : undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
//# sourceMappingURL=dates.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/util/dates.ts"],"sourcesContent":["const MS_IN = {\n day: 86_400_000,\n hour: 3_600_000,\n minute: 60_000,\n month: 2_592_000_000, // 30 days\n second: 1000,\n week: 604_800_000,\n year: 31_536_000_000, // 365 days\n} as const\n\n/** Largest unit first, so the first unit the duration fills is the one we report. */\nconst UNITS: {ms: number; unit: Intl.RelativeTimeFormatUnit}[] = [\n {ms: MS_IN.year, unit: 'year'},\n {ms: MS_IN.month, unit: 'month'},\n {ms: MS_IN.week, unit: 'week'},\n {ms: MS_IN.day, unit: 'day'},\n {ms: MS_IN.hour, unit: 'hour'},\n {ms: MS_IN.minute, unit: 'minute'},\n {ms: MS_IN.second, unit: 'second'},\n]\n\nconst relativeTime = new Intl.RelativeTimeFormat('en', {numeric: 'always'})\n\nconst DATE_ONLY_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/\n\nfunction pad(value: number, length = 2): string {\n return String(value).padStart(length, '0')\n}\n\n/**\n * Returns the coarsest unit the elapsed time fills and the rounded number of those\n * units, or `undefined` below a second.\n *\n * Rounding can land the value on the boundary of the next unit up, so we promote\n * rather than report `60 minutes` where `1 hour` is meant. Units aren't all whole\n * multiples of each other, so the boundary is the rounded count we'd display, which\n * is why 25+ days reads as `1 month` rather than `4 weeks`.\n */\nfunction selectUnit(\n elapsed: number,\n): {unit: Intl.RelativeTimeFormatUnit; value: number} | undefined {\n let index = UNITS.findIndex(({ms}) => elapsed >= ms)\n if (index === -1) return undefined\n\n while (\n index > 0 &&\n Math.round(elapsed / UNITS[index].ms) >= Math.round(UNITS[index - 1].ms / UNITS[index].ms)\n ) {\n index -= 1\n }\n\n const {ms, unit} = UNITS[index]\n return {unit, value: Math.round(elapsed / ms)}\n}\n\n/**\n * Formats a timestamp as `YYYY-MM-DD HH:mm:ss` in the local time zone. Unparseable\n * timestamps are returned as-is, so a bad value from the API doesn't fail the command.\n *\n * @param timestamp - An ISO 8601 timestamp\n * @internal\n */\nexport function formatDateTime(timestamp: string): string {\n const date = new Date(timestamp)\n if (!Number.isFinite(date.getTime())) return timestamp\n\n const day = `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`\n const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`\n return `${day} ${time}`\n}\n\n/**\n * Formats a duration in milliseconds as an approximate, human readable length of\n * time, eg `less than a minute`, `5 minutes` or `2 days`.\n *\n * @param ms - The duration in milliseconds\n * @internal\n */\nexport function formatDuration(ms: number): string {\n if (!Number.isFinite(ms)) return ''\n\n const selected = selectUnit(Math.abs(ms))\n if (!selected || selected.unit === 'second') return 'less than a minute'\n\n const unit = selected.value === 1 ? selected.unit : `${selected.unit}s`\n return `${selected.value} ${unit}`\n}\n\n/**\n * Formats a date relative to now, eg `2 days ago` or `in 3 hours`.\n *\n * @param date - The date to describe\n * @param now - The reference point to compare against, defaults to the current time\n * @internal\n */\nexport function formatTimeAgo(date: Date, now: number = Date.now()): string {\n const delta = date.getTime() - now\n if (!Number.isFinite(delta)) return ''\n\n const selected = selectUnit(Math.abs(delta))\n if (!selected) return 'just now'\n\n return relativeTime.format(delta < 0 ? -selected.value : selected.value, selected.unit)\n}\n\n/**\n * Parses a `YYYY-MM-DD` date into a `Date` at local midnight. Returns `undefined`\n * for anything that isn't a real calendar date in that exact format.\n *\n * @param value - The date string to parse\n * @internal\n */\nexport function parseDateOnly(value: string): Date | undefined {\n const match = DATE_ONLY_PATTERN.exec(value)\n if (!match) return undefined\n\n const year = Number(match[1])\n const month = Number(match[2])\n const day = Number(match[3])\n const date = new Date(year, month - 1, day)\n\n // `new Date(2024, 1, 31)` silently rolls over into March, so reject anything\n // that didn't survive the round trip\n const isRoundTrip =\n date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day\n\n return isRoundTrip ? date : undefined\n}\n"],"names":["MS_IN","day","hour","minute","month","second","week","year","UNITS","ms","unit","relativeTime","Intl","RelativeTimeFormat","numeric","DATE_ONLY_PATTERN","pad","value","length","String","padStart","selectUnit","elapsed","index","findIndex","undefined","Math","round","formatDateTime","timestamp","date","Date","Number","isFinite","getTime","getFullYear","getMonth","getDate","time","getHours","getMinutes","getSeconds","formatDuration","selected","abs","formatTimeAgo","now","delta","format","parseDateOnly","match","exec","isRoundTrip"],"mappings":"AAAA,MAAMA,QAAQ;IACZC,KAAK;IACLC,MAAM;IACNC,QAAQ;IACRC,OAAO;IACPC,QAAQ;IACRC,MAAM;IACNC,MAAM;AACR;AAEA,mFAAmF,GACnF,MAAMC,QAA2D;IAC/D;QAACC,IAAIT,MAAMO,IAAI;QAAEG,MAAM;IAAM;IAC7B;QAACD,IAAIT,MAAMI,KAAK;QAAEM,MAAM;IAAO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CAAC,EAAE;IAC7B,MAAMjD,MAAM+B,OAAOkB,KAAK,CAAC,EAAE;IAC3B,MAAMpB,OAAO,IAAIC,KAAKxB,MAAMH,QAAQ,GAAGH;IAEvC,6EAA6E;IAC7E,qCAAqC;IACrC,MAAMmD,cACJtB,KAAKK,WAAW,OAAO5B,QAAQuB,KAAKM,QAAQ,OAAOhC,QAAQ,KAAK0B,KAAKO,OAAO,OAAOpC;IAErF,OAAOmD,cAActB,OAAOL;AAC9B"}
|
|
@@ -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/dist/ux/spinner.js
CHANGED
|
@@ -10,8 +10,8 @@ import { getCliExecutionContext } from '../executionContext.js';
|
|
|
10
10
|
success: '✔',
|
|
11
11
|
warning: '⚠'
|
|
12
12
|
};
|
|
13
|
-
function resolveAffix(
|
|
14
|
-
const resolved = typeof
|
|
13
|
+
function resolveAffix(value) {
|
|
14
|
+
const resolved = typeof value === 'function' ? value() : value;
|
|
15
15
|
return typeof resolved === 'string' ? resolved : '';
|
|
16
16
|
}
|
|
17
17
|
/**
|
package/dist/ux/spinner.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ux/spinner.ts"],"sourcesContent":["import ora, {\n type Options,\n type Ora,\n oraPromise,\n type Spinner as OraSpinner,\n type PersistOptions,\n type PromiseOptions,\n} from 'ora'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\n/**\n * Uncolored counterparts of the `log-symbols` glyphs a real spinner persists\n * with. Lines forwarded to an execution context are handed to the embedding\n * host verbatim, so they should not carry ANSI codes the host has to strip.\n */\nconst persistSymbols = {\n error: '✖',\n info: 'ℹ',\n success: '✔',\n warning: '⚠',\n}\n\nfunction resolveAffix(value: Options['prefixText'] | Options['suffixText']): string {\n const resolved = typeof value === 'function' ? value() : value\n return typeof resolved === 'string' ? resolved : ''\n}\n\n/**\n * Stand-in for a real spinner, used when a CLI execution context is active.\n *\n * Frame animation and transient text updates have nowhere useful to go, so they\n * are dropped. The lines a spinner *persists* (`succeed`, `fail`, `warn`,\n * `info`, `stopAndPersist`) are the command's actual output rather than\n * progress, so they are forwarded to the context's sink instead of being\n * swallowed. Ora writes to `process.stderr` by default, so the `stderr` sink is\n * preferred, falling back to `stdout`.\n */\nfunction silentSpinner(options?: Options | string): Ora {\n const resolved = typeof options === 'string' ? {text: options} : (options ?? {})\n const context = getCliExecutionContext()\n const emit = resolved.isSilent ? undefined : (context?.stderr ?? context?.stdout)\n\n const prefixText = resolveAffix(resolved.prefixText)\n const suffixText = resolveAffix(resolved.suffixText)\n const state = {text: resolved.text ?? ''}\n\n const persist = (symbol: string, text?: string): void => {\n if (!emit) return\n\n // Mirrors ora's own line layout, minus the trailing whitespace it leaves\n // behind when only one of the symbol and the text is present.\n const body = text ?? state.text\n const line =\n (prefixText ? `${prefixText} ` : '') +\n symbol +\n (symbol && body ? ` ${body}` : body) +\n (suffixText ? ` ${suffixText}` : '')\n\n if (line.trim() !== '') emit(line)\n }\n\n const instance = {\n clear: () => instance,\n fail: (text?: string) => {\n persist(persistSymbols.error, text)\n return instance\n },\n frame: () => '',\n info: (text?: string) => {\n persist(persistSymbols.info, text)\n return instance\n },\n isSpinning: false,\n prefixText,\n render: () => instance,\n start: () => instance,\n stop: () => instance,\n stopAndPersist: (persistOptions: PersistOptions = {}) => {\n persist(persistOptions.symbol ?? '', persistOptions.text)\n return instance\n },\n succeed: (text?: string) => {\n persist(persistSymbols.success, text)\n return instance\n },\n suffixText,\n get text(): string {\n return state.text\n },\n set text(value: string) {\n state.text = value\n },\n warn: (text?: string) => {\n persist(persistSymbols.warning, text)\n return instance\n },\n }\n return instance as unknown as Ora\n}\n\n// Ora's default `discardStdin: true` puts stdin in raw mode, which stops the\n// kernel from turning Ctrl+C into SIGINT (and ora's userland re-signal\n// fallback never fires on a non-flowing stdin), hanging the process. Keep it\n// off by default; explicit caller options still win.\nfunction normalize<T extends Options>(options?: string | T): T {\n const resolved = typeof options === 'string' ? ({text: options} as T) : (options ?? ({} as T))\n return {discardStdin: false, ...resolved}\n}\n\nexport function spinner(options?: Options | string): Ora {\n return getCliExecutionContext() ? silentSpinner(options) : ora(normalize(options))\n}\n\nexport function spinnerPromise<T>(\n action: ((instance: Ora) => PromiseLike<T>) | PromiseLike<T>,\n options?: PromiseOptions<T> | string,\n): Promise<T> {\n if (!getCliExecutionContext()) return oraPromise(action, normalize(options))\n return Promise.resolve(typeof action === 'function' ? action(silentSpinner(options)) : action)\n}\n\nexport type Spinner = OraSpinner\nexport type SpinnerInstance = Ora\nexport type SpinnerOptions = Options\nexport type SpinnerPromiseOptions<T> = PromiseOptions<T>\n"],"names":["ora","oraPromise","getCliExecutionContext","persistSymbols","error","info","success","warning","resolveAffix","value","resolved","silentSpinner","options","text","context","emit","isSilent","undefined","stderr","stdout","prefixText","suffixText","state","persist","symbol","body","line","trim","instance","clear","fail","frame","isSpinning","render","start","stop","stopAndPersist","persistOptions","succeed","warn","normalize","discardStdin","spinner","spinnerPromise","action","Promise","resolve"],"mappings":"AAAA,OAAOA,OAGLC,UAAU,QAIL,MAAK;AAEZ,SAAQC,sBAAsB,QAAO,yBAAwB;AAE7D;;;;CAIC,GACD,MAAMC,iBAAiB;IACrBC,OAAO;IACPC,MAAM;IACNC,SAAS;IACTC,SAAS;AACX;AAEA,SAASC,aAAaC,
|
|
1
|
+
{"version":3,"sources":["../../src/ux/spinner.ts"],"sourcesContent":["import ora, {\n type Options,\n type Ora,\n oraPromise,\n type Spinner as OraSpinner,\n type PersistOptions,\n type PromiseOptions,\n} from 'ora'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\n/**\n * Uncolored counterparts of the `log-symbols` glyphs a real spinner persists\n * with. Lines forwarded to an execution context are handed to the embedding\n * host verbatim, so they should not carry ANSI codes the host has to strip.\n */\nconst persistSymbols = {\n error: '✖',\n info: 'ℹ',\n success: '✔',\n warning: '⚠',\n}\n\nfunction resolveAffix(value: Options['prefixText'] | Options['suffixText']): string {\n const resolved = typeof value === 'function' ? value() : value\n return typeof resolved === 'string' ? resolved : ''\n}\n\n/**\n * Stand-in for a real spinner, used when a CLI execution context is active.\n *\n * Frame animation and transient text updates have nowhere useful to go, so they\n * are dropped. The lines a spinner *persists* (`succeed`, `fail`, `warn`,\n * `info`, `stopAndPersist`) are the command's actual output rather than\n * progress, so they are forwarded to the context's sink instead of being\n * swallowed. Ora writes to `process.stderr` by default, so the `stderr` sink is\n * preferred, falling back to `stdout`.\n */\nfunction silentSpinner(options?: Options | string): Ora {\n const resolved = typeof options === 'string' ? {text: options} : (options ?? {})\n const context = getCliExecutionContext()\n const emit = resolved.isSilent ? undefined : (context?.stderr ?? context?.stdout)\n\n const prefixText = resolveAffix(resolved.prefixText)\n const suffixText = resolveAffix(resolved.suffixText)\n const state = {text: resolved.text ?? ''}\n\n const persist = (symbol: string, text?: string): void => {\n if (!emit) return\n\n // Mirrors ora's own line layout, minus the trailing whitespace it leaves\n // behind when only one of the symbol and the text is present.\n const body = text ?? state.text\n const line =\n (prefixText ? `${prefixText} ` : '') +\n symbol +\n (symbol && body ? ` ${body}` : body) +\n (suffixText ? ` ${suffixText}` : '')\n\n if (line.trim() !== '') emit(line)\n }\n\n const instance = {\n clear: () => instance,\n fail: (text?: string) => {\n persist(persistSymbols.error, text)\n return instance\n },\n frame: () => '',\n info: (text?: string) => {\n persist(persistSymbols.info, text)\n return instance\n },\n isSpinning: false,\n prefixText,\n render: () => instance,\n start: () => instance,\n stop: () => instance,\n stopAndPersist: (persistOptions: PersistOptions = {}) => {\n persist(persistOptions.symbol ?? '', persistOptions.text)\n return instance\n },\n succeed: (text?: string) => {\n persist(persistSymbols.success, text)\n return instance\n },\n suffixText,\n get text(): string {\n return state.text\n },\n set text(value: string) {\n state.text = value\n },\n warn: (text?: string) => {\n persist(persistSymbols.warning, text)\n return instance\n },\n }\n return instance as unknown as Ora\n}\n\n// Ora's default `discardStdin: true` puts stdin in raw mode, which stops the\n// kernel from turning Ctrl+C into SIGINT (and ora's userland re-signal\n// fallback never fires on a non-flowing stdin), hanging the process. Keep it\n// off by default; explicit caller options still win.\nfunction normalize<T extends Options>(options?: string | T): T {\n const resolved = typeof options === 'string' ? ({text: options} as T) : (options ?? ({} as T))\n return {discardStdin: false, ...resolved}\n}\n\nexport function spinner(options?: Options | string): Ora {\n return getCliExecutionContext() ? silentSpinner(options) : ora(normalize(options))\n}\n\nexport function spinnerPromise<T>(\n action: ((instance: Ora) => PromiseLike<T>) | PromiseLike<T>,\n options?: PromiseOptions<T> | string,\n): Promise<T> {\n if (!getCliExecutionContext()) return oraPromise(action, normalize(options))\n return Promise.resolve(typeof action === 'function' ? action(silentSpinner(options)) : action)\n}\n\nexport type Spinner = OraSpinner\nexport type SpinnerInstance = Ora\nexport type SpinnerOptions = Options\nexport type SpinnerPromiseOptions<T> = PromiseOptions<T>\n"],"names":["ora","oraPromise","getCliExecutionContext","persistSymbols","error","info","success","warning","resolveAffix","value","resolved","silentSpinner","options","text","context","emit","isSilent","undefined","stderr","stdout","prefixText","suffixText","state","persist","symbol","body","line","trim","instance","clear","fail","frame","isSpinning","render","start","stop","stopAndPersist","persistOptions","succeed","warn","normalize","discardStdin","spinner","spinnerPromise","action","Promise","resolve"],"mappings":"AAAA,OAAOA,OAGLC,UAAU,QAIL,MAAK;AAEZ,SAAQC,sBAAsB,QAAO,yBAAwB;AAE7D;;;;CAIC,GACD,MAAMC,iBAAiB;IACrBC,OAAO;IACPC,MAAM;IACNC,SAAS;IACTC,SAAS;AACX;AAEA,SAASC,aAAaC,KAAoD;IACxE,MAAMC,WAAW,OAAOD,UAAU,aAAaA,UAAUA;IACzD,OAAO,OAAOC,aAAa,WAAWA,WAAW;AACnD;AAEA;;;;;;;;;CASC,GACD,SAASC,cAAcC,OAA0B;IAC/C,MAAMF,WAAW,OAAOE,YAAY,WAAW;QAACC,MAAMD;IAAO,IAAKA,WAAW,CAAC;IAC9E,MAAME,UAAUZ;IAChB,MAAMa,OAAOL,SAASM,QAAQ,GAAGC,YAAaH,SAASI,UAAUJ,SAASK;IAE1E,MAAMC,aAAaZ,aAAaE,SAASU,UAAU;IACnD,MAAMC,aAAab,aAAaE,SAASW,UAAU;IACnD,MAAMC,QAAQ;QAACT,MAAMH,SAASG,IAAI,IAAI;IAAE;IAExC,MAAMU,UAA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AO;QAAC6B,cAAc;QAAO,GAAG/B,QAAQ;IAAA;AAC1C;AAEA,OAAO,SAASgC,QAAQ9B,OAA0B;IAChD,OAAOV,2BAA2BS,cAAcC,WAAWZ,IAAIwC,UAAU5B;AAC3E;AAEA,OAAO,SAAS+B,eACdC,MAA4D,EAC5DhC,OAAoC;IAEpC,IAAI,CAACV,0BAA0B,OAAOD,WAAW2C,QAAQJ,UAAU5B;IACnE,OAAOiC,QAAQC,OAAO,CAAC,OAAOF,WAAW,aAAaA,OAAOjC,cAAcC,YAAYgC;AACzF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli-core",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.6.1",
|
|
4
4
|
"description": "Sanity CLI core package",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -49,6 +49,10 @@
|
|
|
49
49
|
"source": "./src/_exports/debug.ts",
|
|
50
50
|
"default": "./dist/_exports/debug.js"
|
|
51
51
|
},
|
|
52
|
+
"./dates": {
|
|
53
|
+
"source": "./src/_exports/dates.ts",
|
|
54
|
+
"default": "./dist/_exports/dates.js"
|
|
55
|
+
},
|
|
52
56
|
"./errors": {
|
|
53
57
|
"source": "./src/_exports/errors.ts",
|
|
54
58
|
"default": "./dist/_exports/errors.js"
|
|
@@ -126,14 +130,15 @@
|
|
|
126
130
|
"obug": "^2.1.4",
|
|
127
131
|
"ora": "^9.0.0",
|
|
128
132
|
"rxjs": "^7.8.2",
|
|
129
|
-
"tsx": "^4.23.12",
|
|
130
133
|
"vite": "^8.2.2",
|
|
131
|
-
"vite-node": "^6.0.0",
|
|
132
134
|
"wrap-ansi": "^9.0.2",
|
|
133
|
-
"zod": "^4.
|
|
135
|
+
"zod": "^4.5.2"
|
|
134
136
|
},
|
|
135
137
|
"devDependencies": {
|
|
136
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",
|
|
137
142
|
"@sanity/pkg-utils": "^12.3.4",
|
|
138
143
|
"@sanity/telemetry": "^1.1.0",
|
|
139
144
|
"@swc/cli": "^0.8.1",
|
|
@@ -144,12 +149,9 @@
|
|
|
144
149
|
"eslint": "^10.7.0",
|
|
145
150
|
"oxc-transform-react": "^0.147.0",
|
|
146
151
|
"publint": "^0.3.21",
|
|
147
|
-
"sanity": "^6.
|
|
152
|
+
"sanity": "^6.11.0",
|
|
148
153
|
"typescript": "^6.0.3",
|
|
149
|
-
"vitest": "^4.1.11"
|
|
150
|
-
"@repo/package.config": "0.0.1",
|
|
151
|
-
"@repo/tsconfig": "3.70.0",
|
|
152
|
-
"@sanity/eslint-config-cli": "1.1.3"
|
|
154
|
+
"vitest": "^4.1.11"
|
|
153
155
|
},
|
|
154
156
|
"peerDependencies": {
|
|
155
157
|
"babel-plugin-react-compiler": "*",
|