@sanity/cli-core 0.1.0-alpha.8 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/SanityCommand.js +88 -5
- package/dist/SanityCommand.js.map +1 -1
- package/dist/_exports/request.d.ts +77 -0
- package/dist/_exports/request.js +7 -0
- package/dist/_exports/request.js.map +1 -0
- package/dist/_exports/ux.d.ts +75 -4
- package/dist/_exports/ux.js +2 -1
- package/dist/_exports/ux.js.map +1 -1
- package/dist/config/cli/getCliConfig.js +33 -33
- package/dist/config/cli/getCliConfig.js.map +1 -1
- package/dist/config/cli/getCliConfigSync.js +1 -1
- package/dist/config/cli/getCliConfigSync.js.map +1 -1
- package/dist/config/cli/schemas.js +7 -0
- package/dist/config/cli/schemas.js.map +1 -1
- package/dist/config/cli/types/cliConfig.js.map +1 -1
- package/dist/config/findProjectRoot.js +8 -4
- package/dist/config/findProjectRoot.js.map +1 -1
- package/dist/config/findProjectRootSync.js +7 -3
- package/dist/config/findProjectRootSync.js.map +1 -1
- package/dist/config/studio/getStudioConfig.js +0 -3
- package/dist/config/studio/getStudioConfig.js.map +1 -1
- package/dist/config/studio/getStudioWorkspaces.js +63 -0
- package/dist/config/studio/getStudioWorkspaces.js.map +1 -0
- package/dist/config/studio/isStudioConfig.js +19 -0
- package/dist/config/studio/isStudioConfig.js.map +1 -0
- package/dist/config/studio/readStudioConfig.worker.js +8 -34
- package/dist/config/studio/readStudioConfig.worker.js.map +1 -1
- package/dist/config/util/findStudioConfigPath.js +24 -3
- package/dist/config/util/findStudioConfigPath.js.map +1 -1
- package/dist/config/util/recursivelyResolveProjectRoot.js.map +1 -1
- package/dist/errors/NonInteractiveError.js +18 -0
- package/dist/errors/NonInteractiveError.js.map +1 -0
- package/dist/{util → errors}/NotFoundError.js +1 -1
- package/dist/errors/NotFoundError.js.map +1 -0
- package/dist/errors/ProjectRootNotFoundError.js +35 -0
- package/dist/errors/ProjectRootNotFoundError.js.map +1 -0
- package/dist/index.d.ts +1247 -36
- package/dist/index.js +14 -9
- package/dist/index.js.map +1 -1
- package/dist/loaders/studio/studioWorkerLoader.worker.js +102 -23
- package/dist/loaders/studio/studioWorkerLoader.worker.js.map +1 -1
- package/dist/loaders/studio/studioWorkerTask.js +55 -34
- package/dist/loaders/studio/studioWorkerTask.js.map +1 -1
- package/dist/loaders/tsx/tsxWorkerLoader.worker.js +3 -4
- package/dist/loaders/tsx/tsxWorkerLoader.worker.js.map +1 -1
- package/dist/loaders/tsx/tsxWorkerTask.js +4 -31
- package/dist/loaders/tsx/tsxWorkerTask.js.map +1 -1
- package/dist/request/createRequester.js +83 -0
- package/dist/request/createRequester.js.map +1 -0
- package/dist/services/apiClient.js +8 -4
- package/dist/services/apiClient.js.map +1 -1
- package/dist/services/cliUserConfig.js +5 -5
- package/dist/services/cliUserConfig.js.map +1 -1
- package/dist/services/getCliToken.js +2 -2
- package/dist/services/getCliToken.js.map +1 -1
- package/dist/telemetry/getTelemetryBaseInfo.js +33 -0
- package/dist/telemetry/getTelemetryBaseInfo.js.map +1 -0
- package/dist/telemetry/types.js +5 -0
- package/dist/telemetry/types.js.map +1 -0
- package/dist/util/doImport.js +2 -1
- package/dist/util/doImport.js.map +1 -1
- package/dist/util/environment/mockBrowserEnvironment.js +1 -0
- package/dist/util/environment/mockBrowserEnvironment.js.map +1 -1
- package/dist/util/getCliTelemetry.js +34 -0
- package/dist/util/getCliTelemetry.js.map +1 -0
- package/dist/util/getSanityUrl.js +4 -3
- package/dist/util/getSanityUrl.js.map +1 -1
- package/dist/util/importModule.js +32 -0
- package/dist/util/importModule.js.map +1 -0
- package/dist/util/isInteractive.js +1 -1
- package/dist/util/isInteractive.js.map +1 -1
- package/dist/util/isStaging.js +10 -0
- package/dist/util/isStaging.js.map +1 -0
- package/dist/util/normalizePath.js +12 -0
- package/dist/util/normalizePath.js.map +1 -0
- package/dist/util/promisifyWorker.js +72 -0
- package/dist/util/promisifyWorker.js.map +1 -0
- package/dist/util/readNDJSON.js +18 -0
- package/dist/util/readNDJSON.js.map +1 -0
- package/dist/util/readPackageJson.js +74 -0
- package/dist/util/readPackageJson.js.map +1 -0
- package/dist/ux/boxen.js +3 -0
- package/dist/ux/boxen.js.map +1 -0
- package/dist/ux/colorizeJson.js +6 -6
- package/dist/ux/colorizeJson.js.map +1 -1
- package/dist/ux/prompts.js +49 -1
- package/dist/ux/prompts.js.map +1 -1
- package/package.json +39 -31
- package/dist/SanityCommand.d.ts +0 -78
- package/dist/_exports/tree.d.ts +0 -1
- package/dist/_exports/tree.js +0 -3
- package/dist/_exports/tree.js.map +0 -1
- package/dist/config/cli/getCliConfig.d.ts +0 -16
- package/dist/config/cli/getCliConfig.worker.d.ts +0 -1
- package/dist/config/cli/getCliConfig.worker.js +0 -15
- package/dist/config/cli/getCliConfig.worker.js.map +0 -1
- package/dist/config/cli/getCliConfigSync.d.ts +0 -12
- package/dist/config/cli/schemas.d.ts +0 -104
- package/dist/config/cli/types/cliConfig.d.ts +0 -83
- package/dist/config/cli/types/userViteConfig.d.ts +0 -5
- package/dist/config/findProjectRoot.d.ts +0 -14
- package/dist/config/findProjectRootSync.d.ts +0 -27
- package/dist/config/studio/getStudioConfig.d.ts +0 -14
- package/dist/config/studio/readStudioConfig.d.ts +0 -96
- package/dist/config/studio/readStudioConfig.worker.d.ts +0 -1
- package/dist/config/util/configPathsSync.d.ts +0 -17
- package/dist/config/util/findAppConfigPath.d.ts +0 -8
- package/dist/config/util/findConfigsPaths.d.ts +0 -16
- package/dist/config/util/findStudioConfigPath.d.ts +0 -9
- package/dist/config/util/isSanityV2StudioRoot.d.ts +0 -8
- package/dist/config/util/recursivelyResolveProjectRoot.d.ts +0 -27
- package/dist/debug.d.ts +0 -15
- package/dist/loaders/studio/studioWorkerLoader.worker.d.ts +0 -1
- package/dist/loaders/studio/studioWorkerTask.d.ts +0 -40
- package/dist/loaders/tsx/tsxWorkerLoader.worker.d.ts +0 -1
- package/dist/loaders/tsx/tsxWorkerTask.d.ts +0 -28
- package/dist/services/apiClient.d.ts +0 -53
- package/dist/services/cliUserConfig.d.ts +0 -40
- package/dist/services/getCliToken.d.ts +0 -7
- package/dist/types.d.ts +0 -15
- package/dist/util/NotFoundError.d.ts +0 -20
- package/dist/util/NotFoundError.js.map +0 -1
- package/dist/util/createExpiringConfig.d.ts +0 -37
- package/dist/util/createExpiringConfig.js +0 -60
- package/dist/util/createExpiringConfig.js.map +0 -1
- package/dist/util/doImport.d.ts +0 -7
- package/dist/util/environment/getStudioEnvironmentVariables.d.ts +0 -12
- package/dist/util/environment/mockBrowserEnvironment.d.ts +0 -17
- package/dist/util/environment/setupBrowserStubs.d.ts +0 -10
- package/dist/util/environment/stubs.d.ts +0 -254
- package/dist/util/fileExists.d.ts +0 -9
- package/dist/util/generateHelpUrl.d.ts +0 -8
- package/dist/util/getEmptyAuth.d.ts +0 -5
- package/dist/util/getSanityEnvVar.d.ts +0 -19
- package/dist/util/getSanityUrl.d.ts +0 -5
- package/dist/util/getUserConfig.d.ts +0 -2
- package/dist/util/isCi.d.ts +0 -1
- package/dist/util/isInteractive.d.ts +0 -1
- package/dist/util/isRecord.d.ts +0 -8
- package/dist/util/isTrueish.d.ts +0 -1
- package/dist/util/parseStringFlag.d.ts +0 -10
- package/dist/util/parseStringFlag.js +0 -19
- package/dist/util/parseStringFlag.js.map +0 -1
- package/dist/util/readJsonFile.d.ts +0 -14
- package/dist/util/resolveLocalPackage.d.ts +0 -18
- package/dist/util/safeStructuredClone.d.ts +0 -8
- package/dist/util/tree.d.ts +0 -31
- package/dist/util/tree.js +0 -108
- package/dist/util/tree.js.map +0 -1
- package/dist/util/tryGetDefaultExport.d.ts +0 -5
- package/dist/util/writeJsonFile.d.ts +0 -9
- package/dist/ux/chalk.d.ts +0 -2
- package/dist/ux/chalk.js +0 -4
- package/dist/ux/chalk.js.map +0 -1
- package/dist/ux/colorizeJson.d.ts +0 -1
- package/dist/ux/formatObject.d.ts +0 -1
- package/dist/ux/formatObject.js +0 -9
- package/dist/ux/formatObject.js.map +0 -1
- package/dist/ux/logSymbols.d.ts +0 -1
- package/dist/ux/printKeyValue.d.ts +0 -1
- package/dist/ux/printKeyValue.js +0 -16
- package/dist/ux/printKeyValue.js.map +0 -1
- package/dist/ux/prompts.d.ts +0 -1
- package/dist/ux/spinner.d.ts +0 -1
- package/dist/ux/timer.d.ts +0 -12
package/dist/index.js
CHANGED
|
@@ -1,34 +1,39 @@
|
|
|
1
1
|
export * from './config/cli/getCliConfig.js';
|
|
2
2
|
export * from './config/cli/getCliConfigSync.js';
|
|
3
|
-
export { cliConfigSchema } from './config/cli/schemas.js';
|
|
4
3
|
export * from './config/findProjectRoot.js';
|
|
5
4
|
export * from './config/findProjectRootSync.js';
|
|
6
5
|
export * from './config/studio/getStudioConfig.js';
|
|
6
|
+
export * from './config/studio/getStudioWorkspaces.js';
|
|
7
|
+
export * from './config/studio/isStudioConfig.js';
|
|
7
8
|
export * from './config/util/findConfigsPaths.js';
|
|
8
9
|
export * from './config/util/findStudioConfigPath.js';
|
|
9
10
|
export * from './debug.js';
|
|
11
|
+
export * from './errors/NonInteractiveError.js';
|
|
12
|
+
export * from './errors/NotFoundError.js';
|
|
13
|
+
export * from './errors/ProjectRootNotFoundError.js';
|
|
14
|
+
export * from './loaders/studio/studioWorkerTask.js';
|
|
10
15
|
export * from './loaders/tsx/tsxWorkerTask.js';
|
|
11
16
|
export * from './SanityCommand.js';
|
|
12
17
|
export * from './services/apiClient.js';
|
|
13
18
|
export * from './services/cliUserConfig.js';
|
|
14
19
|
export * from './services/getCliToken.js';
|
|
15
|
-
export * from './
|
|
20
|
+
export * from './telemetry/getTelemetryBaseInfo.js';
|
|
16
21
|
export { doImport } from './util/doImport.js';
|
|
17
22
|
export * from './util/environment/mockBrowserEnvironment.js';
|
|
18
|
-
export
|
|
19
|
-
export * from './util/getEmptyAuth.js';
|
|
23
|
+
export { clearCliTelemetry, CLI_TELEMETRY_SYMBOL, getCliTelemetry, setCliTelemetry } from './util/getCliTelemetry.js';
|
|
20
24
|
export * from './util/getSanityEnvVar.js';
|
|
21
25
|
export * from './util/getSanityUrl.js';
|
|
22
26
|
export * from './util/getUserConfig.js';
|
|
27
|
+
export * from './util/importModule.js';
|
|
23
28
|
export * from './util/isCi.js';
|
|
24
29
|
export * from './util/isInteractive.js';
|
|
25
|
-
export * from './util/
|
|
26
|
-
export * from './util/
|
|
30
|
+
export * from './util/isStaging.js';
|
|
31
|
+
export * from './util/normalizePath.js';
|
|
32
|
+
export * from './util/promisifyWorker.js';
|
|
33
|
+
export * from './util/readPackageJson.js';
|
|
27
34
|
export * from './util/resolveLocalPackage.js';
|
|
28
|
-
export * from './util/
|
|
35
|
+
export * from './util/safeStructuredClone.js';
|
|
29
36
|
export * from './ux/colorizeJson.js';
|
|
30
|
-
export * from './ux/formatObject.js';
|
|
31
|
-
export * from './ux/printKeyValue.js';
|
|
32
37
|
export * from './ux/timer.js';
|
|
33
38
|
|
|
34
39
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './config/cli/getCliConfig.js'\nexport * from './config/cli/getCliConfigSync.js'\nexport {
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './config/cli/getCliConfig.js'\nexport * from './config/cli/getCliConfigSync.js'\nexport {type CliConfig} from './config/cli/types/cliConfig.js'\nexport {type UserViteConfig} from './config/cli/types/userViteConfig.js'\nexport * from './config/findProjectRoot.js'\nexport * from './config/findProjectRootSync.js'\nexport * from './config/studio/getStudioConfig.js'\nexport * from './config/studio/getStudioWorkspaces.js'\nexport * from './config/studio/isStudioConfig.js'\nexport * from './config/util/findConfigsPaths.js'\nexport * from './config/util/findStudioConfigPath.js'\nexport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nexport * from './debug.js'\nexport * from './errors/NonInteractiveError.js'\nexport * from './errors/NotFoundError.js'\nexport * from './errors/ProjectRootNotFoundError.js'\nexport * from './loaders/studio/studioWorkerTask.js'\nexport * from './loaders/tsx/tsxWorkerTask.js'\nexport * from './SanityCommand.js'\nexport * from './services/apiClient.js'\nexport * from './services/cliUserConfig.js'\nexport * from './services/getCliToken.js'\nexport * from './telemetry/getTelemetryBaseInfo.js'\nexport {\n type CLITelemetryStore,\n type ConsentInformation,\n type TelemetryUserProperties,\n} from './telemetry/types.js'\nexport {type Output, type SanityOrgUser} from './types.js'\nexport {doImport} from './util/doImport.js'\nexport * from './util/environment/mockBrowserEnvironment.js'\nexport {\n clearCliTelemetry,\n CLI_TELEMETRY_SYMBOL,\n getCliTelemetry,\n setCliTelemetry,\n} from './util/getCliTelemetry.js'\nexport * from './util/getSanityEnvVar.js'\nexport * from './util/getSanityUrl.js'\nexport * from './util/getUserConfig.js'\nexport * from './util/importModule.js'\nexport * from './util/isCi.js'\nexport * from './util/isInteractive.js'\nexport * from './util/isStaging.js'\nexport * from './util/normalizePath.js'\nexport * from './util/promisifyWorker.js'\nexport * from './util/readPackageJson.js'\nexport * from './util/resolveLocalPackage.js'\nexport * from './util/safeStructuredClone.js'\nexport * from './ux/colorizeJson.js'\nexport * from './ux/timer.js'\n"],"names":["doImport","clearCliTelemetry","CLI_TELEMETRY_SYMBOL","getCliTelemetry","setCliTelemetry"],"mappings":"AAAA,cAAc,+BAA8B;AAC5C,cAAc,mCAAkC;AAGhD,cAAc,8BAA6B;AAC3C,cAAc,kCAAiC;AAC/C,cAAc,qCAAoC;AAClD,cAAc,yCAAwC;AACtD,cAAc,oCAAmC;AACjD,cAAc,oCAAmC;AACjD,cAAc,wCAAuC;AAErD,cAAc,aAAY;AAC1B,cAAc,kCAAiC;AAC/C,cAAc,4BAA2B;AACzC,cAAc,uCAAsC;AACpD,cAAc,uCAAsC;AACpD,cAAc,iCAAgC;AAC9C,cAAc,qBAAoB;AAClC,cAAc,0BAAyB;AACvC,cAAc,8BAA6B;AAC3C,cAAc,4BAA2B;AACzC,cAAc,sCAAqC;AAOnD,SAAQA,QAAQ,QAAO,qBAAoB;AAC3C,cAAc,+CAA8C;AAC5D,SACEC,iBAAiB,EACjBC,oBAAoB,EACpBC,eAAe,EACfC,eAAe,QACV,4BAA2B;AAClC,cAAc,4BAA2B;AACzC,cAAc,yBAAwB;AACtC,cAAc,0BAAyB;AACvC,cAAc,yBAAwB;AACtC,cAAc,iBAAgB;AAC9B,cAAc,0BAAyB;AACvC,cAAc,sBAAqB;AACnC,cAAc,0BAAyB;AACvC,cAAc,4BAA2B;AACzC,cAAc,4BAA2B;AACzC,cAAc,gCAA+B;AAC7C,cAAc,gCAA+B;AAC7C,cAAc,uBAAsB;AACpC,cAAc,gBAAe"}
|
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import { isMainThread } from 'node:worker_threads';
|
|
2
|
-
import { createServer,
|
|
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
6
|
import { getCliConfig } from '../../config/cli/getCliConfig.js';
|
|
7
|
+
import { subdebug } from '../../debug.js';
|
|
8
|
+
import { isNotFoundError } from '../../errors/NotFoundError.js';
|
|
4
9
|
import { getStudioEnvironmentVariables } from '../../util/environment/getStudioEnvironmentVariables.js';
|
|
5
10
|
import { setupBrowserStubs } from '../../util/environment/setupBrowserStubs.js';
|
|
6
11
|
import { isRecord } from '../../util/isRecord.js';
|
|
7
|
-
import { isNotFoundError } from '../../util/NotFoundError.js';
|
|
8
12
|
if (isMainThread) {
|
|
9
13
|
throw new Error('Should be child of thread, not the main thread');
|
|
10
14
|
}
|
|
@@ -12,12 +16,51 @@ const rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH;
|
|
|
12
16
|
if (!rootPath) {
|
|
13
17
|
throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable');
|
|
14
18
|
}
|
|
19
|
+
const debug = subdebug('studio:worker');
|
|
15
20
|
const workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE;
|
|
16
21
|
if (!workerScriptPath) {
|
|
17
22
|
throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable');
|
|
18
23
|
}
|
|
19
24
|
await setupBrowserStubs();
|
|
20
25
|
const studioEnvVars = await getStudioEnvironmentVariables(rootPath);
|
|
26
|
+
// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can
|
|
27
|
+
// extend/modify the default vite configuration for the studio.
|
|
28
|
+
let cliConfig;
|
|
29
|
+
try {
|
|
30
|
+
cliConfig = await getCliConfig(rootPath);
|
|
31
|
+
} catch (err) {
|
|
32
|
+
debug('Failed to load CLI config: %o', err);
|
|
33
|
+
if (!isNotFoundError(err)) {
|
|
34
|
+
// eslint-disable-next-line no-console
|
|
35
|
+
console.warn('[warn] Failed to load CLI config:', err);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Fetches and caches modules from HTTP/HTTPS URLs.
|
|
40
|
+
* Vite's SSR transform treats `https://` imports as external and bypasses the plugin
|
|
41
|
+
* resolve pipeline entirely, so we intercept them at the ViteNodeRunner level instead.
|
|
42
|
+
*/ const httpModuleCache = new Map();
|
|
43
|
+
async function fetchHttpModule(url) {
|
|
44
|
+
const cached = httpModuleCache.get(url);
|
|
45
|
+
if (cached) return {
|
|
46
|
+
code: cached
|
|
47
|
+
};
|
|
48
|
+
debug('Fetching HTTP import: %s', url);
|
|
49
|
+
const response = await fetch(url, {
|
|
50
|
+
signal: AbortSignal.timeout(30_000)
|
|
51
|
+
});
|
|
52
|
+
if (!response.ok) {
|
|
53
|
+
throw new Error(`Failed to fetch module from ${url}: ${response.status} ${response.statusText}`);
|
|
54
|
+
}
|
|
55
|
+
const code = await response.text();
|
|
56
|
+
httpModuleCache.set(url, code);
|
|
57
|
+
return {
|
|
58
|
+
code
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function isHttpsUrl(id) {
|
|
62
|
+
return id.startsWith('https://');
|
|
63
|
+
}
|
|
21
64
|
const defaultViteConfig = {
|
|
22
65
|
build: {
|
|
23
66
|
target: 'node'
|
|
@@ -28,26 +71,28 @@ const defaultViteConfig = {
|
|
|
28
71
|
`process.env.${key}`,
|
|
29
72
|
JSON.stringify(value)
|
|
30
73
|
])),
|
|
74
|
+
envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',
|
|
75
|
+
esbuild: {
|
|
76
|
+
jsx: 'automatic'
|
|
77
|
+
},
|
|
31
78
|
logLevel: 'error',
|
|
32
79
|
optimizeDeps: {
|
|
33
|
-
|
|
80
|
+
include: undefined,
|
|
81
|
+
noDiscovery: true
|
|
34
82
|
},
|
|
35
83
|
root: rootPath,
|
|
36
84
|
server: {
|
|
37
85
|
hmr: false,
|
|
38
86
|
watch: null
|
|
87
|
+
},
|
|
88
|
+
ssr: {
|
|
89
|
+
/**
|
|
90
|
+
* We don't want to externalize any dependencies, we want everything to run thru vite.
|
|
91
|
+
* Especially for CJS compatibility, etc.
|
|
92
|
+
*/ noExternal: true
|
|
39
93
|
}
|
|
40
94
|
};
|
|
41
|
-
//
|
|
42
|
-
// extend/modify the default vite configuration for the studio.
|
|
43
|
-
let cliConfig;
|
|
44
|
-
try {
|
|
45
|
-
cliConfig = await getCliConfig(rootPath);
|
|
46
|
-
} catch (err) {
|
|
47
|
-
if (!isNotFoundError(err)) {
|
|
48
|
-
console.warn('[warn] Failed to load CLI config:', err);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
95
|
+
// Merge the CLI config's Vite config with the default Vite config
|
|
51
96
|
let viteConfig = defaultViteConfig;
|
|
52
97
|
if (typeof cliConfig?.vite === 'function') {
|
|
53
98
|
viteConfig = await cliConfig.vite(viteConfig, {
|
|
@@ -58,6 +103,7 @@ if (typeof cliConfig?.vite === 'function') {
|
|
|
58
103
|
} else if (isRecord(cliConfig?.vite)) {
|
|
59
104
|
viteConfig = mergeConfig(viteConfig, cliConfig.vite);
|
|
60
105
|
}
|
|
106
|
+
debug('Creating Vite server with config: %o', viteConfig);
|
|
61
107
|
// Vite will build the files we give it - targetting Node.js instead of the browser.
|
|
62
108
|
// We include the inject plugin in order to provide the stubs for the undefined global APIs.
|
|
63
109
|
const server = await createServer(viteConfig);
|
|
@@ -66,19 +112,52 @@ await server.pluginContainer.buildStart({});
|
|
|
66
112
|
// Load environment variables from `.env` files in the same way as Vite does.
|
|
67
113
|
// Note that Sanity also provides environment variables through `process.env.*` for compat reasons,
|
|
68
114
|
// and so we need to do the same here.
|
|
69
|
-
|
|
70
|
-
const env = loadEnv(server.config.mode, server.config.envDir, '');
|
|
115
|
+
const env = loadEnv(server.config.mode, server.config.envDir, viteConfig.envPrefix ?? '');
|
|
71
116
|
for(const key in env){
|
|
72
117
|
process.env[key] ??= env[key];
|
|
73
118
|
}
|
|
74
|
-
// Now we're
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
119
|
+
// Now we're providing the glue that ensures node-specific loading and execution works.
|
|
120
|
+
const node = new ViteNodeServer(server);
|
|
121
|
+
// Should make it easier to debug any crashes in the imported code…
|
|
122
|
+
installSourcemapsSupport({
|
|
123
|
+
getSourceMap: (source)=>node.getSourceMap(source)
|
|
124
|
+
});
|
|
125
|
+
const runner = new ViteNodeRunner({
|
|
126
|
+
base: server.config.base,
|
|
127
|
+
async fetchModule (id) {
|
|
128
|
+
// Vite's SSR transform externalizes https:// imports, so Node's ESM loader
|
|
129
|
+
// would reject them. We fetch the module over HTTP and run it through Vite's
|
|
130
|
+
// SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*
|
|
131
|
+
// format that ViteNodeRunner expects.
|
|
132
|
+
if (isHttpsUrl(id)) {
|
|
133
|
+
const { code: rawCode } = await fetchHttpModule(id);
|
|
134
|
+
const result = await server.ssrTransform(rawCode, null, id);
|
|
135
|
+
return {
|
|
136
|
+
code: result?.code || rawCode
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
return node.fetchModule(id);
|
|
140
|
+
},
|
|
141
|
+
resolveId (id, importer) {
|
|
142
|
+
// Prevent vite-node from trying to resolve HTTP URLs through Node's resolver
|
|
143
|
+
if (isHttpsUrl(id)) return {
|
|
144
|
+
id
|
|
145
|
+
};
|
|
146
|
+
// Resolve any import from an HTTP-fetched module against the remote origin
|
|
147
|
+
// (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)
|
|
148
|
+
if (importer && isHttpsUrl(importer)) {
|
|
149
|
+
return {
|
|
150
|
+
id: new URL(id, importer).href
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
return node.resolveId(id, importer);
|
|
154
|
+
},
|
|
155
|
+
root: server.config.root
|
|
78
156
|
});
|
|
79
|
-
//
|
|
80
|
-
|
|
81
|
-
//
|
|
82
|
-
await runner.
|
|
157
|
+
// Copied from `vite-node` - it appears that this applies the `define` config from
|
|
158
|
+
// vite, but it also takes a surprisingly long time to execute. Not clear at this
|
|
159
|
+
// point why this is, so we should investigate whether it's necessary or not.
|
|
160
|
+
await runner.executeId('/@vite/env');
|
|
161
|
+
await runner.executeId(workerScriptPath);
|
|
83
162
|
|
|
84
163
|
//# sourceMappingURL=studioWorkerLoader.worker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {isMainThread} from 'node:worker_threads'\n\nimport {createServer, createServerModuleRunner, type InlineConfig, loadEnv, mergeConfig} from 'vite'\n\nimport {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {getStudioEnvironmentVariables} from '../../util/environment/getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from '../../util/environment/setupBrowserStubs.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {isNotFoundError} from '../../util/NotFoundError.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 workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE\nif (!workerScriptPath) {\n throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable')\n}\n\nawait setupBrowserStubs()\n\nconst studioEnvVars = await getStudioEnvironmentVariables(rootPath)\n\nconst defaultViteConfig: InlineConfig = {\n build: {target: 'node'},\n configFile: false, // @todo Should use `vite` prop from `sanity.cli.ts` (if any)\n // Inject environment variables as compile-time constants for Vite\n define: Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\n ),\n logLevel: 'error',\n optimizeDeps: {disabled: true}, // @todo is this necessary? cant remember why was added\n root: rootPath,\n server: {\n hmr: false,\n watch: null,\n },\n}\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 if (!isNotFoundError(err)) {\n console.warn('[warn] Failed to load CLI config:', err)\n }\n}\n\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\n// Vite will build the files we give it - targetting Node.js instead of the browser.\n// We include the inject plugin in order to provide the stubs for the undefined global APIs.\nconst server = await createServer(viteConfig)\n\n// Bit of a hack, but seems necessary based on the `node-vite` binary implementation\nawait server.pluginContainer.buildStart({})\n\n// Load environment variables from `.env` files in the same way as Vite does.\n// Note that Sanity also provides environment variables through `process.env.*` for compat reasons,\n// and so we need to do the same here.\n// @todo is this in line with sanity?\nconst env = loadEnv(server.config.mode, server.config.envDir, '')\nfor (const key in env) {\n process.env[key] ??= env[key]\n}\n\n// Now we're using Vite's Module Runner (replaces vite-node in Vite 4+)\nconst runner = await createServerModuleRunner(server.environments.ssr, {\n hmr: false,\n sourcemapInterceptor: 'prepareStackTrace',\n})\n\n// Apply the `define` config from vite - imports environment variables\nawait runner.import('/@vite/env')\n\n// Execute the worker script\nawait runner.import(workerScriptPath)\n"],"names":["isMainThread","createServer","createServerModuleRunner","loadEnv","mergeConfig","getCliConfig","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","isNotFoundError","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","defaultViteConfig","build","target","configFile","define","Object","fromEntries","entries","map","key","value","JSON","stringify","logLevel","optimizeDeps","disabled","root","server","hmr","watch","cliConfig","err","console","warn","viteConfig","vite","command","isSsrBuild","mode","pluginContainer","buildStart","config","envDir","runner","environments","ssr","sourcemapInterceptor","import"],"mappings":"AAAA,SAAQA,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,YAAY,EAAEC,wBAAwB,EAAqBC,OAAO,EAAEC,WAAW,QAAO,OAAM;AAEpG,SAAQC,YAAY,QAAO,mCAAkC;AAE7D,SAAQC,6BAA6B,QAAO,0DAAyD;AACrG,SAAQC,iBAAiB,QAAO,8CAA6C;AAC7E,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,IAAIT,cAAc;IAChB,MAAM,IAAIU,MAAM;AAClB;AAEA,MAAMC,WAAWC,QAAQC,GAAG,CAACC,8BAA8B;AAC3D,IAAI,CAACH,UAAU;IACb,MAAM,IAAID,MAAM;AAClB;AAEA,MAAMK,mBAAmBH,QAAQC,GAAG,CAACG,uBAAuB;AAC5D,IAAI,CAACD,kBAAkB;IACrB,MAAM,IAAIL,MAAM;AAClB;AAEA,MAAMH;AAEN,MAAMU,gBAAgB,MAAMX,8BAA8BK;AAE1D,MAAMO,oBAAkC;IACtCC,OAAO;QAACC,QAAQ;IAAM;IACtBC,YAAY;IACZ,kEAAkE;IAClEC,QAAQC,OAAOC,WAAW,CACxBD,OAAOE,OAAO,CAACR,eAAeS,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;YAClD,CAAC,YAAY,EAAED,KAAK;YACpBE,KAAKC,SAAS,CAACF;SAChB;IAEHG,UAAU;IACVC,cAAc;QAACC,UAAU;IAAI;IAC7BC,MAAMvB;IACNwB,QAAQ;QACNC,KAAK;QACLC,OAAO;IACT;AACF;AAEA,oFAAoF;AACpF,+DAA+D;AAC/D,IAAIC;AACJ,IAAI;IACFA,YAAY,MAAMjC,aAAaM;AACjC,EAAE,OAAO4B,KAAK;IACZ,IAAI,CAAC9B,gBAAgB8B,MAAM;QACzBC,QAAQC,IAAI,CAAC,qCAAqCF;IACpD;AACF;AAEA,IAAIG,aAAaxB;AACjB,IAAI,OAAOoB,WAAWK,SAAS,YAAY;IACzCD,aAAc,MAAMJ,UAAUK,IAAI,CAACD,YAAY;QAC7CE,SAAS;QACTC,YAAY;QACZC,MAAM;IACR;AACF,OAAO,IAAItC,SAAS8B,WAAWK,OAAO;IACpCD,aAAatC,YAAYsC,YAAYJ,UAAUK,IAAI;AACrD;AAEA,oFAAoF;AACpF,4FAA4F;AAC5F,MAAMR,SAAS,MAAMlC,aAAayC;AAElC,oFAAoF;AACpF,MAAMP,OAAOY,eAAe,CAACC,UAAU,CAAC,CAAC;AAEzC,6EAA6E;AAC7E,mGAAmG;AACnG,sCAAsC;AACtC,qCAAqC;AACrC,MAAMnC,MAAMV,QAAQgC,OAAOc,MAAM,CAACH,IAAI,EAAEX,OAAOc,MAAM,CAACC,MAAM,EAAE;AAC9D,IAAK,MAAMvB,OAAOd,IAAK;IACrBD,QAAQC,GAAG,CAACc,IAAI,KAAKd,GAAG,CAACc,IAAI;AAC/B;AAEA,uEAAuE;AACvE,MAAMwB,SAAS,MAAMjD,yBAAyBiC,OAAOiB,YAAY,CAACC,GAAG,EAAE;IACrEjB,KAAK;IACLkB,sBAAsB;AACxB;AAEA,sEAAsE;AACtE,MAAMH,OAAOI,MAAM,CAAC;AAEpB,4BAA4B;AAC5B,MAAMJ,OAAOI,MAAM,CAACxC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {isMainThread} from 'node:worker_threads'\n\nimport {createServer, type InlineConfig, loadEnv, mergeConfig} from 'vite'\nimport {ViteNodeRunner} from 'vite-node/client'\nimport {ViteNodeServer} from 'vite-node/server'\nimport {installSourcemapsSupport} from 'vite-node/source-map'\n\nimport {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {subdebug} from '../../debug.js'\nimport {isNotFoundError} from '../../errors/NotFoundError.js'\nimport {getStudioEnvironmentVariables} from '../../util/environment/getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from '../../util/environment/setupBrowserStubs.js'\nimport {isRecord} from '../../util/isRecord.js'\n\nif (isMainThread) {\n throw new Error('Should be child of thread, not the main thread')\n}\n\nconst rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH\nif (!rootPath) {\n throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable')\n}\n\nconst debug = subdebug('studio:worker')\n\nconst workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE\nif (!workerScriptPath) {\n throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable')\n}\n\nawait setupBrowserStubs()\n\nconst studioEnvVars = await getStudioEnvironmentVariables(rootPath)\n\n// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can\n// extend/modify the default vite configuration for the studio.\nlet cliConfig: CliConfig | undefined\ntry {\n cliConfig = await getCliConfig(rootPath)\n} catch (err) {\n debug('Failed to load CLI config: %o', err)\n if (!isNotFoundError(err)) {\n // eslint-disable-next-line no-console\n console.warn('[warn] Failed to load CLI config:', err)\n }\n}\n\n/**\n * Fetches and caches modules from HTTP/HTTPS URLs.\n * Vite's SSR transform treats `https://` imports as external and bypasses the plugin\n * resolve pipeline entirely, so we intercept them at the ViteNodeRunner level instead.\n */\nconst httpModuleCache = new Map<string, string>()\nasync function fetchHttpModule(url: string): Promise<{code: string}> {\n const cached = httpModuleCache.get(url)\n if (cached) return {code: cached}\n\n debug('Fetching HTTP import: %s', url)\n const response = await fetch(url, {signal: AbortSignal.timeout(30_000)})\n if (!response.ok) {\n throw new Error(`Failed to fetch module from ${url}: ${response.status} ${response.statusText}`)\n }\n\n const code = await response.text()\n httpModuleCache.set(url, code)\n return {code}\n}\n\nfunction isHttpsUrl(id: string): boolean {\n return id.startsWith('https://')\n}\n\nconst defaultViteConfig: InlineConfig = {\n build: {target: 'node'},\n configFile: false,\n // Inject environment variables as compile-time constants for Vite\n define: Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\n ),\n envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n esbuild: {\n jsx: 'automatic',\n },\n logLevel: 'error',\n optimizeDeps: {\n include: undefined,\n noDiscovery: true,\n },\n root: rootPath,\n server: {\n hmr: false,\n watch: null,\n },\n ssr: {\n /**\n * We don't want to externalize any dependencies, we want everything to run thru vite.\n * Especially for CJS compatibility, etc.\n */\n noExternal: true,\n },\n}\n\n// Merge the CLI config's Vite config with the default Vite config\nlet viteConfig = defaultViteConfig\nif (typeof cliConfig?.vite === 'function') {\n viteConfig = (await cliConfig.vite(viteConfig, {\n command: 'build',\n isSsrBuild: true,\n mode: 'production',\n })) as InlineConfig\n} else if (isRecord(cliConfig?.vite)) {\n viteConfig = mergeConfig(viteConfig, cliConfig.vite)\n}\n\ndebug('Creating Vite server with config: %o', viteConfig)\n// Vite will build the files we give it - targetting Node.js instead of the browser.\n// We include the inject plugin in order to provide the stubs for the undefined global APIs.\nconst server = await createServer(viteConfig)\n\n// Bit of a hack, but seems necessary based on the `node-vite` binary implementation\nawait server.pluginContainer.buildStart({})\n\n// Load environment variables from `.env` files in the same way as Vite does.\n// Note that Sanity also provides environment variables through `process.env.*` for compat reasons,\n// and so we need to do the same here.\nconst env = loadEnv(server.config.mode, server.config.envDir, viteConfig.envPrefix ?? '')\nfor (const key in env) {\n process.env[key] ??= env[key]\n}\n\n// Now we're providing the glue that ensures node-specific loading and execution works.\nconst node = new ViteNodeServer(server)\n\n// Should make it easier to debug any crashes in the imported code…\ninstallSourcemapsSupport({\n getSourceMap: (source) => node.getSourceMap(source),\n})\n\nconst runner = new ViteNodeRunner({\n base: server.config.base,\n async fetchModule(id) {\n // Vite's SSR transform externalizes https:// imports, so Node's ESM loader\n // would reject them. We fetch the module over HTTP and run it through Vite's\n // SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*\n // format that ViteNodeRunner expects.\n if (isHttpsUrl(id)) {\n const {code: rawCode} = await fetchHttpModule(id)\n const result = await server.ssrTransform(rawCode, null, id)\n return {code: result?.code || rawCode}\n }\n return node.fetchModule(id)\n },\n resolveId(id, importer) {\n // Prevent vite-node from trying to resolve HTTP URLs through Node's resolver\n if (isHttpsUrl(id)) return {id}\n // Resolve any import from an HTTP-fetched module against the remote origin\n // (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)\n if (importer && isHttpsUrl(importer)) {\n return {id: new URL(id, importer).href}\n }\n return node.resolveId(id, importer)\n },\n root: server.config.root,\n})\n\n// Copied from `vite-node` - it appears that this applies the `define` config from\n// vite, but it also takes a surprisingly long time to execute. Not clear at this\n// point why this is, so we should investigate whether it's necessary or not.\nawait runner.executeId('/@vite/env')\n\nawait runner.executeId(workerScriptPath)\n"],"names":["isMainThread","createServer","loadEnv","mergeConfig","ViteNodeRunner","ViteNodeServer","installSourcemapsSupport","getCliConfig","subdebug","isNotFoundError","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","debug","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","cliConfig","err","console","warn","httpModuleCache","Map","fetchHttpModule","url","cached","get","code","response","fetch","signal","AbortSignal","timeout","ok","status","statusText","text","set","isHttpsUrl","id","startsWith","defaultViteConfig","build","target","configFile","define","Object","fromEntries","entries","map","key","value","JSON","stringify","envPrefix","esbuild","jsx","logLevel","optimizeDeps","include","undefined","noDiscovery","root","server","hmr","watch","ssr","noExternal","viteConfig","vite","command","isSsrBuild","mode","pluginContainer","buildStart","config","envDir","node","getSourceMap","source","runner","base","fetchModule","rawCode","result","ssrTransform","resolveId","importer","URL","href","executeId"],"mappings":"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"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
1
2
|
import { Worker } from 'node:worker_threads';
|
|
2
3
|
import { isRecord } from '../../util/isRecord.js';
|
|
4
|
+
import { promisifyWorker } from '../../util/promisifyWorker.js';
|
|
3
5
|
/**
|
|
4
6
|
* Executes a worker file in a Sanity Studio browser context.
|
|
5
7
|
*
|
|
@@ -28,40 +30,59 @@ import { isRecord } from '../../util/isRecord.js';
|
|
|
28
30
|
* @throws If the worker exits with a non-zero code
|
|
29
31
|
* @internal
|
|
30
32
|
*/ export function studioWorkerTask(filePath, options) {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
33
|
+
const normalizedFilePath = fileURLToPath(filePath);
|
|
34
|
+
if (!/\.worker\.(js|ts)$/.test(normalizedFilePath)) {
|
|
35
|
+
throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path');
|
|
36
|
+
}
|
|
37
|
+
const { studioRootPath, timeout, ...workerOptions } = options;
|
|
38
|
+
return promisifyWorker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
|
|
39
|
+
...workerOptions,
|
|
40
|
+
env: {
|
|
41
|
+
...isRecord(workerOptions.env) ? workerOptions.env : process.env,
|
|
42
|
+
STUDIO_WORKER_STUDIO_ROOT_PATH: studioRootPath,
|
|
43
|
+
STUDIO_WORKER_TASK_FILE: normalizedFilePath
|
|
44
|
+
},
|
|
45
|
+
timeout
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Creates a new worker for a studio worker task.
|
|
50
|
+
*
|
|
51
|
+
* This uses a combination of vite for "bundling" + jsdom for emulating a browser
|
|
52
|
+
* environment under the hood, which means that the same thing that will work in vite
|
|
53
|
+
* _should_ work in the worker - to a degree. If the user has defined any typescript
|
|
54
|
+
* path aliases, these will have to be added as aliases to the vite config - the same
|
|
55
|
+
* behavior as you would see with regular vite. Other things that are accounted for:
|
|
56
|
+
*
|
|
57
|
+
* - TypeScript support (+JSX, enums and other "compilation needed" features)
|
|
58
|
+
* - CSS, font and other file imports will resolve to a file path
|
|
59
|
+
* - CSS module imports will resolve to a javascript object of class names
|
|
60
|
+
* - Environment variables are available both as `import.meta.env` and `process.env`,
|
|
61
|
+
* and `.env` files are loaded in the same way that they would in a Sanity studio.
|
|
62
|
+
* - Browser globals not available in a Node.js environment but _are_ provided by JSDOM
|
|
63
|
+
* are defined directly to the Node environment as globals. While this polutes the
|
|
64
|
+
* global namespace, it is done only in the worker thread.
|
|
65
|
+
* - Certain browser globals that are _not_ available in JSDOM are also provided to the
|
|
66
|
+
* global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.
|
|
67
|
+
* These are provided with a minimal stub implementation to make them not crash.
|
|
68
|
+
*
|
|
69
|
+
* @param filePath - Path to the worker file (`.ts` works and is encouraged)
|
|
70
|
+
* @param options - Options to pass to the worker
|
|
71
|
+
* @returns A promise that resolves with the message from the worker
|
|
72
|
+
* @throws If the file does not exist
|
|
73
|
+
* @throws If the worker exits with a non-zero code
|
|
74
|
+
* @internal
|
|
75
|
+
*/ export function createStudioWorker(filePath, options) {
|
|
76
|
+
const normalizedFilePath = fileURLToPath(filePath);
|
|
77
|
+
if (!/\.worker\.(js|ts)$/.test(normalizedFilePath)) {
|
|
78
|
+
throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path');
|
|
79
|
+
}
|
|
80
|
+
return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
|
|
81
|
+
...options,
|
|
82
|
+
env: {
|
|
83
|
+
...isRecord(options.env) ? options.env : process.env,
|
|
84
|
+
STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,
|
|
85
|
+
STUDIO_WORKER_TASK_FILE: normalizedFilePath
|
|
65
86
|
}
|
|
66
87
|
});
|
|
67
88
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerTask.ts"],"sourcesContent":["import {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\n\n/**\n * Options for the studio worker task\n *\n * @internal\n */\ninterface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n studioRootPath: string\n}\n\n/**\n * Executes a worker file in a Sanity Studio browser context.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function studioWorkerTask(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerTask.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\n\n/**\n * Options for the studio worker task\n *\n * @internal\n */\ninterface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n studioRootPath: string\n\n /** Optional timeout in milliseconds. If the worker does not respond within this time, it will be terminated and the promise rejected. */\n timeout?: number\n}\n\n/**\n * Executes a worker file in a Sanity Studio browser context.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function studioWorkerTask<T = unknown>(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<T> {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n const {studioRootPath, timeout, ...workerOptions} = options\n return promisifyWorker<T>(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...workerOptions,\n env: {\n ...(isRecord(workerOptions.env) ? workerOptions.env : process.env),\n STUDIO_WORKER_STUDIO_ROOT_PATH: studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n timeout,\n })\n}\n\n/**\n * Creates a new worker for a studio worker task.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function createStudioWorker(filePath: URL, options: StudioWorkerTaskOptions) {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...options,\n env: {\n ...(isRecord(options.env) ? options.env : process.env),\n STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n })\n}\n"],"names":["fileURLToPath","Worker","isRecord","promisifyWorker","studioWorkerTask","filePath","options","normalizedFilePath","test","Error","studioRootPath","timeout","workerOptions","URL","url","env","process","STUDIO_WORKER_STUDIO_ROOT_PATH","STUDIO_WORKER_TASK_FILE","createStudioWorker"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AACtC,SAAQC,MAAM,QAA2B,sBAAqB;AAG9D,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,gCAA+B;AAc7D;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,iBACdC,QAAa,EACbC,OAAgC;IAEhC,MAAMC,qBAAqBP,cAAcK;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,MAAM,EAACC,cAAc,EAAEC,OAAO,EAAE,GAAGC,eAAc,GAAGN;IACpD,OAAOH,gBAAmB,IAAIU,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAClF,GAAGF,aAAa;QAChBG,KAAK;YACH,GAAIb,SAASU,cAAcG,GAAG,IAAIH,cAAcG,GAAG,GAAGC,QAAQD,GAAG;YACjEE,gCAAgCP;YAChCQ,yBAAyBX;QAC3B;QACAI;IACF;AACF;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASQ,mBAAmBd,QAAa,EAAEC,OAAgC;IAChF,MAAMC,qBAAqBP,cAAcK;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,OAAO,IAAIR,OAAO,IAAIY,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAC1E,GAAGR,OAAO;QACVS,KAAK;YACH,GAAIb,SAASI,QAAQS,GAAG,IAAIT,QAAQS,GAAG,GAAGC,QAAQD,GAAG;YACrDE,gCAAgCX,QAAQI,cAAc;YACtDQ,yBAAyBX;QAC3B;IACF;AACF"}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { importModule } from '../../util/importModule.js';
|
|
2
2
|
const workerScript = process.env.TSX_WORKER_TASK_SCRIPT;
|
|
3
3
|
if (workerScript) {
|
|
4
|
-
await
|
|
5
|
-
|
|
6
|
-
tsconfig: process.env.TSX_TSCONFIG_PATH
|
|
4
|
+
await importModule(workerScript, {
|
|
5
|
+
tsconfigPath: process.env.TSX_TSCONFIG_PATH
|
|
7
6
|
});
|
|
8
7
|
} else {
|
|
9
8
|
throw new Error('`TX_WORKER_TASK_SCRIPT` not defined');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerLoader.worker.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerLoader.worker.ts"],"sourcesContent":["import {importModule} from '../../util/importModule.js'\n\nconst workerScript = process.env.TSX_WORKER_TASK_SCRIPT\n\nif (workerScript) {\n await importModule(workerScript, {\n tsconfigPath: process.env.TSX_TSCONFIG_PATH,\n })\n} else {\n throw new Error('`TX_WORKER_TASK_SCRIPT` not defined')\n}\n"],"names":["importModule","workerScript","process","env","TSX_WORKER_TASK_SCRIPT","tsconfigPath","TSX_TSCONFIG_PATH","Error"],"mappings":"AAAA,SAAQA,YAAY,QAAO,6BAA4B;AAEvD,MAAMC,eAAeC,QAAQC,GAAG,CAACC,sBAAsB;AAEvD,IAAIH,cAAc;IAChB,MAAMD,aAAaC,cAAc;QAC/BI,cAAcH,QAAQC,GAAG,CAACG,iBAAiB;IAC7C;AACF,OAAO;IACL,MAAM,IAAIC,MAAM;AAClB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { URL } from 'node:url';
|
|
2
|
-
import { Worker } from 'node:worker_threads';
|
|
1
|
+
import { fileURLToPath, URL } from 'node:url';
|
|
3
2
|
import { getTsconfig } from 'get-tsconfig';
|
|
4
3
|
import { isRecord } from '../../util/isRecord.js';
|
|
4
|
+
import { promisifyWorker } from '../../util/promisifyWorker.js';
|
|
5
5
|
/**
|
|
6
6
|
* Executes a worker file with tsx registered. This means you can import other
|
|
7
7
|
* typescript with fairly rich syntax, and still have that only apply to the worker
|
|
@@ -23,39 +23,12 @@ import { isRecord } from '../../util/isRecord.js';
|
|
|
23
23
|
...tsconfig?.path ? {
|
|
24
24
|
TSX_TSCONFIG_PATH: tsconfig.path
|
|
25
25
|
} : {},
|
|
26
|
-
TSX_WORKER_TASK_SCRIPT: filePath
|
|
26
|
+
TSX_WORKER_TASK_SCRIPT: fileURLToPath(filePath)
|
|
27
27
|
};
|
|
28
|
-
|
|
28
|
+
return promisifyWorker(new URL('tsxWorkerLoader.worker.js', import.meta.url), {
|
|
29
29
|
...options,
|
|
30
30
|
env
|
|
31
31
|
});
|
|
32
|
-
return new Promise((resolve, reject)=>{
|
|
33
|
-
worker.addListener('error', function onWorkerError(err) {
|
|
34
|
-
reject(new Error(`Failed to load file through worker: ${err.message}`, {
|
|
35
|
-
cause: err
|
|
36
|
-
}));
|
|
37
|
-
cleanup();
|
|
38
|
-
});
|
|
39
|
-
worker.addListener('exit', function onWorkerExit(code) {
|
|
40
|
-
if (code > 0) {
|
|
41
|
-
reject(new Error(`Worker exited with code ${code}`));
|
|
42
|
-
}
|
|
43
|
-
});
|
|
44
|
-
worker.addListener('messageerror', function onWorkerMessageError(err) {
|
|
45
|
-
reject(new Error(`Fail to parse message from worker: ${err}`));
|
|
46
|
-
cleanup();
|
|
47
|
-
});
|
|
48
|
-
worker.addListener('message', function onWorkerMessage(message) {
|
|
49
|
-
resolve(message);
|
|
50
|
-
cleanup();
|
|
51
|
-
});
|
|
52
|
-
function cleanup() {
|
|
53
|
-
// Allow the worker a _bit_ of time to clean up, but ensure that we don't have
|
|
54
|
-
// lingering processes hanging around forever if the worker doesn't exit on its
|
|
55
|
-
// own.
|
|
56
|
-
setImmediate(()=>worker.terminate());
|
|
57
|
-
}
|
|
58
|
-
});
|
|
59
32
|
}
|
|
60
33
|
|
|
61
34
|
//# sourceMappingURL=tsxWorkerTask.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerTask.ts"],"sourcesContent":["import {URL} from 'node:url'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerTask.ts"],"sourcesContent":["import {fileURLToPath, URL} from 'node:url'\nimport {type WorkerOptions} from 'node:worker_threads'\n\nimport {getTsconfig} from 'get-tsconfig'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\n\n/**\n * Options for the tsx worker task\n *\n * @internal\n */\ninterface TsxWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n rootPath: string\n}\n\n/**\n * Executes a worker file with tsx registered. This means you can import other\n * typescript with fairly rich syntax, and still have that only apply to the worker\n * thread instead of the full parent process. The worker should emit a message when\n * complete using `parentPort`. Once it has received a single message will resolve the\n * returned promise with that message. If you are expecting multiple messages, you will\n * have to implement another method ;)\n *\n * @param filePath - Path to the worker file\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function tsxWorkerTask<T = unknown>(\n filePath: URL,\n options: TsxWorkerTaskOptions,\n): Promise<T> {\n const tsconfig = getTsconfig(options.rootPath)\n\n const env = {\n ...(isRecord(options.env) ? options.env : process.env),\n ...(tsconfig?.path ? {TSX_TSCONFIG_PATH: tsconfig.path} : {}),\n TSX_WORKER_TASK_SCRIPT: fileURLToPath(filePath),\n }\n\n return promisifyWorker<T>(new URL('tsxWorkerLoader.worker.js', import.meta.url), {\n ...options,\n env,\n })\n}\n"],"names":["fileURLToPath","URL","getTsconfig","isRecord","promisifyWorker","tsxWorkerTask","filePath","options","tsconfig","rootPath","env","process","path","TSX_TSCONFIG_PATH","TSX_WORKER_TASK_SCRIPT","url"],"mappings":"AAAA,SAAQA,aAAa,EAAEC,GAAG,QAAO,WAAU;AAG3C,SAAQC,WAAW,QAAO,eAAc;AAGxC,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,gCAA+B;AAW7D;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,cACdC,QAAa,EACbC,OAA6B;IAE7B,MAAMC,WAAWN,YAAYK,QAAQE,QAAQ;IAE7C,MAAMC,MAAM;QACV,GAAIP,SAASI,QAAQG,GAAG,IAAIH,QAAQG,GAAG,GAAGC,QAAQD,GAAG;QACrD,GAAIF,UAAUI,OAAO;YAACC,mBAAmBL,SAASI,IAAI;QAAA,IAAI,CAAC,CAAC;QAC5DE,wBAAwBd,cAAcM;IACxC;IAEA,OAAOF,gBAAmB,IAAIH,IAAI,6BAA6B,YAAYc,GAAG,GAAG;QAC/E,GAAGR,OAAO;QACVG;IACF;AACF"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { getIt } from 'get-it';
|
|
2
|
+
import { debug, headers, httpErrors, promise } from 'get-it/middleware';
|
|
3
|
+
import { readPackageUpSync } from 'read-package-up';
|
|
4
|
+
let cachedPkg;
|
|
5
|
+
/**
|
|
6
|
+
* Creates a `get-it` requester with a standard set of middleware.
|
|
7
|
+
*
|
|
8
|
+
* Default middleware (in order):
|
|
9
|
+
* 1. `httpErrors()` — throw on HTTP error status codes
|
|
10
|
+
* 2. `headers({'User-Agent': '@sanity/cli-core@<version>'})` — identify CLI requests
|
|
11
|
+
* 3. `debug({verbose: true, namespace: 'sanity:cli'})` — debug logging
|
|
12
|
+
* 4. `promise({onlyBody: true})` — return body directly (must be last)
|
|
13
|
+
*
|
|
14
|
+
* @param options - Optional configuration to disable or customize middleware
|
|
15
|
+
* @returns A configured `get-it` requester
|
|
16
|
+
* @public
|
|
17
|
+
*/ export function createRequester(options) {
|
|
18
|
+
const opts = options?.middleware;
|
|
19
|
+
const middleware = [];
|
|
20
|
+
// 1. httpErrors
|
|
21
|
+
if (opts?.httpErrors !== false) {
|
|
22
|
+
middleware.push(httpErrors());
|
|
23
|
+
}
|
|
24
|
+
// 2. headers
|
|
25
|
+
if (opts?.headers !== false) {
|
|
26
|
+
const customHeaders = typeof opts?.headers === 'object' ? opts.headers : {};
|
|
27
|
+
const allHeaders = customHeaders['User-Agent'] ? {
|
|
28
|
+
...customHeaders
|
|
29
|
+
} : {
|
|
30
|
+
get ['User-Agent'] () {
|
|
31
|
+
const pkg = getPackageInfo();
|
|
32
|
+
return `${pkg.name}@${pkg.version}`;
|
|
33
|
+
},
|
|
34
|
+
...customHeaders
|
|
35
|
+
};
|
|
36
|
+
middleware.push(headers(allHeaders));
|
|
37
|
+
}
|
|
38
|
+
// 3. debug
|
|
39
|
+
if (opts?.debug !== false) {
|
|
40
|
+
const debugDefaults = {
|
|
41
|
+
namespace: 'sanity:cli',
|
|
42
|
+
verbose: true
|
|
43
|
+
};
|
|
44
|
+
const customDebug = typeof opts?.debug === 'object' ? opts.debug : {};
|
|
45
|
+
middleware.push(debug({
|
|
46
|
+
...debugDefaults,
|
|
47
|
+
...customDebug
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
// 4. promise (must be last)
|
|
51
|
+
if (opts?.promise !== false) {
|
|
52
|
+
const promiseDefaults = {
|
|
53
|
+
onlyBody: true
|
|
54
|
+
};
|
|
55
|
+
const customPromise = typeof opts?.promise === 'object' ? opts.promise : {};
|
|
56
|
+
middleware.push(promise({
|
|
57
|
+
...promiseDefaults,
|
|
58
|
+
...customPromise
|
|
59
|
+
}));
|
|
60
|
+
}
|
|
61
|
+
return getIt(middleware);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Reads the nearest `package.json` to determine the name and version of the `@sanity/cli-core` package.
|
|
65
|
+
*
|
|
66
|
+
* @returns The name and version of the package
|
|
67
|
+
* @internal
|
|
68
|
+
*/ function getPackageInfo() {
|
|
69
|
+
if (cachedPkg) return cachedPkg;
|
|
70
|
+
const result = readPackageUpSync({
|
|
71
|
+
cwd: import.meta.dirname
|
|
72
|
+
});
|
|
73
|
+
if (!result) {
|
|
74
|
+
throw new Error('Unable to resolve @sanity/cli-core package root');
|
|
75
|
+
}
|
|
76
|
+
cachedPkg = {
|
|
77
|
+
name: result.packageJson.name ?? '@sanity/cli-core',
|
|
78
|
+
version: result.packageJson.version ?? '0.0.0'
|
|
79
|
+
};
|
|
80
|
+
return cachedPkg;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
//# sourceMappingURL=createRequester.js.map
|