@sanity/cli-core 0.1.0-alpha.9 → 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.
Files changed (103) hide show
  1. package/dist/SanityCommand.js +81 -5
  2. package/dist/SanityCommand.js.map +1 -1
  3. package/dist/_exports/request.d.ts +77 -0
  4. package/dist/_exports/request.js +7 -0
  5. package/dist/_exports/request.js.map +1 -0
  6. package/dist/_exports/ux.d.ts +37 -2
  7. package/dist/_exports/ux.js +1 -0
  8. package/dist/_exports/ux.js.map +1 -1
  9. package/dist/config/cli/getCliConfig.js +33 -33
  10. package/dist/config/cli/getCliConfig.js.map +1 -1
  11. package/dist/config/cli/getCliConfigSync.js +1 -1
  12. package/dist/config/cli/getCliConfigSync.js.map +1 -1
  13. package/dist/config/cli/schemas.js +7 -0
  14. package/dist/config/cli/schemas.js.map +1 -1
  15. package/dist/config/cli/types/cliConfig.js.map +1 -1
  16. package/dist/config/findProjectRoot.js +6 -2
  17. package/dist/config/findProjectRoot.js.map +1 -1
  18. package/dist/config/findProjectRootSync.js +7 -3
  19. package/dist/config/findProjectRootSync.js.map +1 -1
  20. package/dist/config/studio/getStudioWorkspaces.js +14 -1
  21. package/dist/config/studio/getStudioWorkspaces.js.map +1 -1
  22. package/dist/config/studio/readStudioConfig.worker.js +6 -5
  23. package/dist/config/studio/readStudioConfig.worker.js.map +1 -1
  24. package/dist/errors/NonInteractiveError.js +18 -0
  25. package/dist/errors/NonInteractiveError.js.map +1 -0
  26. package/dist/{util → errors}/NotFoundError.js +1 -1
  27. package/dist/errors/NotFoundError.js.map +1 -0
  28. package/dist/errors/ProjectRootNotFoundError.js +35 -0
  29. package/dist/errors/ProjectRootNotFoundError.js.map +1 -0
  30. package/dist/index.d.ts +869 -5649
  31. package/dist/index.js +8 -14
  32. package/dist/index.js.map +1 -1
  33. package/dist/loaders/studio/studioWorkerLoader.worker.js +102 -23
  34. package/dist/loaders/studio/studioWorkerLoader.worker.js.map +1 -1
  35. package/dist/loaders/studio/studioWorkerTask.js +18 -27
  36. package/dist/loaders/studio/studioWorkerTask.js.map +1 -1
  37. package/dist/loaders/tsx/tsxWorkerLoader.worker.js +3 -4
  38. package/dist/loaders/tsx/tsxWorkerLoader.worker.js.map +1 -1
  39. package/dist/loaders/tsx/tsxWorkerTask.js +4 -34
  40. package/dist/loaders/tsx/tsxWorkerTask.js.map +1 -1
  41. package/dist/request/createRequester.js +83 -0
  42. package/dist/request/createRequester.js.map +1 -0
  43. package/dist/services/apiClient.js +3 -3
  44. package/dist/services/apiClient.js.map +1 -1
  45. package/dist/services/cliUserConfig.js +5 -5
  46. package/dist/services/cliUserConfig.js.map +1 -1
  47. package/dist/services/getCliToken.js +2 -2
  48. package/dist/services/getCliToken.js.map +1 -1
  49. package/dist/util/doImport.js +2 -1
  50. package/dist/util/doImport.js.map +1 -1
  51. package/dist/util/environment/mockBrowserEnvironment.js +1 -0
  52. package/dist/util/environment/mockBrowserEnvironment.js.map +1 -1
  53. package/dist/util/getCliTelemetry.js +6 -8
  54. package/dist/util/getCliTelemetry.js.map +1 -1
  55. package/dist/util/getSanityUrl.js +4 -3
  56. package/dist/util/getSanityUrl.js.map +1 -1
  57. package/dist/util/importModule.js +32 -0
  58. package/dist/util/importModule.js.map +1 -0
  59. package/dist/util/isInteractive.js +1 -1
  60. package/dist/util/isInteractive.js.map +1 -1
  61. package/dist/util/promisifyWorker.js +72 -0
  62. package/dist/util/promisifyWorker.js.map +1 -0
  63. package/dist/util/readPackageJson.js +74 -0
  64. package/dist/util/readPackageJson.js.map +1 -0
  65. package/dist/ux/prompts.js +49 -1
  66. package/dist/ux/prompts.js.map +1 -1
  67. package/package.json +27 -26
  68. package/dist/_exports/tree.d.ts +0 -47
  69. package/dist/_exports/tree.js +0 -3
  70. package/dist/_exports/tree.js.map +0 -1
  71. package/dist/config/cli/getCliConfig.worker.js +0 -15
  72. package/dist/config/cli/getCliConfig.worker.js.map +0 -1
  73. package/dist/telemetry/cleanupOldTelemetryFiles.js +0 -30
  74. package/dist/telemetry/cleanupOldTelemetryFiles.js.map +0 -1
  75. package/dist/telemetry/createTelemetryStore.js +0 -95
  76. package/dist/telemetry/createTelemetryStore.js.map +0 -1
  77. package/dist/telemetry/createTraceId.js +0 -10
  78. package/dist/telemetry/createTraceId.js.map +0 -1
  79. package/dist/telemetry/findTelemetryFiles.js +0 -36
  80. package/dist/telemetry/findTelemetryFiles.js.map +0 -1
  81. package/dist/telemetry/flushTelemetryFiles.js +0 -107
  82. package/dist/telemetry/flushTelemetryFiles.js.map +0 -1
  83. package/dist/telemetry/generateTelemetryFilePath.js +0 -30
  84. package/dist/telemetry/generateTelemetryFilePath.js.map +0 -1
  85. package/dist/telemetry/logger.js +0 -54
  86. package/dist/telemetry/logger.js.map +0 -1
  87. package/dist/telemetry/telemetryStoreDebug.js +0 -7
  88. package/dist/telemetry/telemetryStoreDebug.js.map +0 -1
  89. package/dist/telemetry/trace.js +0 -150
  90. package/dist/telemetry/trace.js.map +0 -1
  91. package/dist/util/NotFoundError.js.map +0 -1
  92. package/dist/util/createExpiringConfig.js +0 -60
  93. package/dist/util/createExpiringConfig.js.map +0 -1
  94. package/dist/util/parseStringFlag.js +0 -19
  95. package/dist/util/parseStringFlag.js.map +0 -1
  96. package/dist/util/tree.js +0 -108
  97. package/dist/util/tree.js.map +0 -1
  98. package/dist/util/waitForAsync.js +0 -5
  99. package/dist/util/waitForAsync.js.map +0 -1
  100. package/dist/ux/formatObject.js +0 -9
  101. package/dist/ux/formatObject.js.map +0 -1
  102. package/dist/ux/printKeyValue.js +0 -16
  103. package/dist/ux/printKeyValue.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,45 +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';
7
6
  export * from './config/studio/getStudioWorkspaces.js';
7
+ export * from './config/studio/isStudioConfig.js';
8
8
  export * from './config/util/findConfigsPaths.js';
9
9
  export * from './config/util/findStudioConfigPath.js';
10
10
  export * from './debug.js';
11
+ export * from './errors/NonInteractiveError.js';
12
+ export * from './errors/NotFoundError.js';
13
+ export * from './errors/ProjectRootNotFoundError.js';
11
14
  export * from './loaders/studio/studioWorkerTask.js';
12
15
  export * from './loaders/tsx/tsxWorkerTask.js';
13
16
  export * from './SanityCommand.js';
14
17
  export * from './services/apiClient.js';
15
18
  export * from './services/cliUserConfig.js';
16
19
  export * from './services/getCliToken.js';
17
- export * from './telemetry/createTelemetryStore.js';
18
- export * from './telemetry/flushTelemetryFiles.js';
19
20
  export * from './telemetry/getTelemetryBaseInfo.js';
20
- export * from './telemetry/telemetryStoreDebug.js';
21
- export * from './util/createExpiringConfig.js';
22
21
  export { doImport } from './util/doImport.js';
23
22
  export * from './util/environment/mockBrowserEnvironment.js';
24
- export * from './util/fileExists.js';
25
23
  export { clearCliTelemetry, CLI_TELEMETRY_SYMBOL, getCliTelemetry, setCliTelemetry } from './util/getCliTelemetry.js';
26
- export * from './util/getEmptyAuth.js';
27
24
  export * from './util/getSanityEnvVar.js';
28
25
  export * from './util/getSanityUrl.js';
29
26
  export * from './util/getUserConfig.js';
27
+ export * from './util/importModule.js';
30
28
  export * from './util/isCi.js';
31
29
  export * from './util/isInteractive.js';
32
- export * from './util/isRecord.js';
33
30
  export * from './util/isStaging.js';
34
- export * from './util/isTrueish.js';
35
31
  export * from './util/normalizePath.js';
36
- export * from './util/parseStringFlag.js';
37
- export * from './util/readNDJSON.js';
32
+ export * from './util/promisifyWorker.js';
33
+ export * from './util/readPackageJson.js';
38
34
  export * from './util/resolveLocalPackage.js';
39
- export * from './util/tryGetDefaultExport.js';
35
+ export * from './util/safeStructuredClone.js';
40
36
  export * from './ux/colorizeJson.js';
41
- export * from './ux/formatObject.js';
42
- export * from './ux/printKeyValue.js';
43
37
  export * from './ux/timer.js';
44
38
 
45
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 {cliConfigSchema} from './config/cli/schemas.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/util/findConfigsPaths.js'\nexport * from './config/util/findStudioConfigPath.js'\nexport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nexport * from './debug.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/createTelemetryStore.js'\nexport * from './telemetry/flushTelemetryFiles.js'\nexport * from './telemetry/getTelemetryBaseInfo.js'\nexport * from './telemetry/telemetryStoreDebug.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 * from './util/createExpiringConfig.js'\nexport {doImport} from './util/doImport.js'\nexport * from './util/environment/mockBrowserEnvironment.js'\nexport * from './util/fileExists.js'\nexport {\n clearCliTelemetry,\n CLI_TELEMETRY_SYMBOL,\n getCliTelemetry,\n setCliTelemetry,\n} from './util/getCliTelemetry.js'\nexport * from './util/getEmptyAuth.js'\nexport * from './util/getSanityEnvVar.js'\nexport * from './util/getSanityUrl.js'\nexport * from './util/getUserConfig.js'\nexport * from './util/isCi.js'\nexport * from './util/isInteractive.js'\nexport * from './util/isRecord.js'\nexport * from './util/isStaging.js'\nexport * from './util/isTrueish.js'\nexport * from './util/normalizePath.js'\nexport * from './util/parseStringFlag.js'\nexport * from './util/readNDJSON.js'\nexport * from './util/resolveLocalPackage.js'\nexport * from './util/tryGetDefaultExport.js'\nexport * from './ux/colorizeJson.js'\nexport * from './ux/formatObject.js'\nexport * from './ux/printKeyValue.js'\nexport * from './ux/timer.js'\n"],"names":["cliConfigSchema","doImport","clearCliTelemetry","CLI_TELEMETRY_SYMBOL","getCliTelemetry","setCliTelemetry"],"mappings":"AAAA,cAAc,+BAA8B;AAC5C,cAAc,mCAAkC;AAChD,SAAQA,eAAe,QAAO,0BAAyB;AAGvD,cAAc,8BAA6B;AAC3C,cAAc,kCAAiC;AAC/C,cAAc,qCAAoC;AAClD,cAAc,yCAAwC;AACtD,cAAc,oCAAmC;AACjD,cAAc,wCAAuC;AAErD,cAAc,aAAY;AAC1B,cAAc,uCAAsC;AACpD,cAAc,iCAAgC;AAC9C,cAAc,qBAAoB;AAClC,cAAc,0BAAyB;AACvC,cAAc,8BAA6B;AAC3C,cAAc,4BAA2B;AACzC,cAAc,sCAAqC;AACnD,cAAc,qCAAoC;AAClD,cAAc,sCAAqC;AACnD,cAAc,qCAAoC;AAOlD,cAAc,iCAAgC;AAC9C,SAAQC,QAAQ,QAAO,qBAAoB;AAC3C,cAAc,+CAA8C;AAC5D,cAAc,uBAAsB;AACpC,SACEC,iBAAiB,EACjBC,oBAAoB,EACpBC,eAAe,EACfC,eAAe,QACV,4BAA2B;AAClC,cAAc,yBAAwB;AACtC,cAAc,4BAA2B;AACzC,cAAc,yBAAwB;AACtC,cAAc,0BAAyB;AACvC,cAAc,iBAAgB;AAC9B,cAAc,0BAAyB;AACvC,cAAc,qBAAoB;AAClC,cAAc,sBAAqB;AACnC,cAAc,sBAAqB;AACnC,cAAc,0BAAyB;AACvC,cAAc,4BAA2B;AACzC,cAAc,uBAAsB;AACpC,cAAc,gCAA+B;AAC7C,cAAc,gCAA+B;AAC7C,cAAc,uBAAsB;AACpC,cAAc,uBAAsB;AACpC,cAAc,wBAAuB;AACrC,cAAc,gBAAe"}
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, createServerModuleRunner, loadEnv, mergeConfig } from 'vite';
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
- disabled: true
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
- // Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can
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
- // @todo is this in line with sanity?
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 using Vite's Module Runner (replaces vite-node in Vite 4+)
75
- const runner = await createServerModuleRunner(server.environments.ssr, {
76
- hmr: false,
77
- sourcemapInterceptor: 'prepareStackTrace'
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
- // Apply the `define` config from vite - imports environment variables
80
- await runner.import('/@vite/env');
81
- // Execute the worker script
82
- await runner.import(workerScriptPath);
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,31 +30,19 @@ 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
- return new Promise((resolve, reject)=>{
32
- const worker = createStudioWorker(filePath, options);
33
- worker.addListener('error', function onWorkerError(err) {
34
- reject(new Error(`Fail to load file through worker: ${err.message}`));
35
- cleanup();
36
- });
37
- worker.addListener('exit', function onWorkerExit(code) {
38
- if (code > 0) {
39
- reject(new Error(`Worker exited with code ${code}`));
40
- }
41
- });
42
- worker.addListener('messageerror', function onWorkerMessageError(err) {
43
- reject(new Error(`Fail to parse message from worker: ${err}`));
44
- cleanup();
45
- });
46
- worker.addListener('message', function onWorkerMessage(message) {
47
- resolve(message);
48
- cleanup();
49
- });
50
- function cleanup() {
51
- // Allow the worker a _bit_ of time to clean up, but ensure that we don't have
52
- // lingering processes hanging around forever if the worker doesn't exit on its
53
- // own.
54
- setImmediate(()=>worker.terminate());
55
- }
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
56
46
  });
57
47
  }
58
48
  /**
@@ -83,7 +73,8 @@ import { isRecord } from '../../util/isRecord.js';
83
73
  * @throws If the worker exits with a non-zero code
84
74
  * @internal
85
75
  */ export function createStudioWorker(filePath, options) {
86
- if (!/\.worker\.(js|ts)$/.test(filePath.pathname)) {
76
+ const normalizedFilePath = fileURLToPath(filePath);
77
+ if (!/\.worker\.(js|ts)$/.test(normalizedFilePath)) {
87
78
  throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path');
88
79
  }
89
80
  return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
@@ -91,7 +82,7 @@ import { isRecord } from '../../util/isRecord.js';
91
82
  env: {
92
83
  ...isRecord(options.env) ? options.env : process.env,
93
84
  STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,
94
- STUDIO_WORKER_TASK_FILE: filePath.pathname
85
+ STUDIO_WORKER_TASK_FILE: normalizedFilePath
95
86
  }
96
87
  });
97
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<T = unknown>(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const worker = createStudioWorker(filePath, options)\n\n worker.addListener('error', function onWorkerError(err) {\n reject(new Error(`Fail to load file through worker: ${err.message}`))\n cleanup()\n })\n worker.addListener('exit', function onWorkerExit(code) {\n if (code > 0) {\n reject(new Error(`Worker exited with code ${code}`))\n }\n })\n worker.addListener('messageerror', function onWorkerMessageError(err) {\n reject(new Error(`Fail to parse message from worker: ${err}`))\n cleanup()\n })\n worker.addListener('message', function onWorkerMessage(message) {\n resolve(message)\n cleanup()\n })\n\n function cleanup() {\n // Allow the worker a _bit_ of time to clean up, but ensure that we don't have\n // lingering processes hanging around forever if the worker doesn't exit on its\n // own.\n setImmediate(() => worker.terminate())\n }\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 if (!/\\.worker\\.(js|ts)$/.test(filePath.pathname)) {\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: filePath.pathname,\n },\n })\n}\n"],"names":["Worker","isRecord","studioWorkerTask","filePath","options","Promise","resolve","reject","worker","createStudioWorker","addListener","onWorkerError","err","Error","message","cleanup","onWorkerExit","code","onWorkerMessageError","onWorkerMessage","setImmediate","terminate","test","pathname","URL","url","env","process","STUDIO_WORKER_STUDIO_ROOT_PATH","studioRootPath","STUDIO_WORKER_TASK_FILE"],"mappings":"AAAA,SAAQA,MAAM,QAA2B,sBAAqB;AAG9D,SAAQC,QAAQ,QAAO,yBAAwB;AAW/C;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,iBACdC,QAAa,EACbC,OAAgC;IAEhC,OAAO,IAAIC,QAAW,CAACC,SAASC;QAC9B,MAAMC,SAASC,mBAAmBN,UAAUC;QAE5CI,OAAOE,WAAW,CAAC,SAAS,SAASC,cAAcC,GAAG;YACpDL,OAAO,IAAIM,MAAM,CAAC,kCAAkC,EAAED,IAAIE,OAAO,EAAE;YACnEC;QACF;QACAP,OAAOE,WAAW,CAAC,QAAQ,SAASM,aAAaC,IAAI;YACnD,IAAIA,OAAO,GAAG;gBACZV,OAAO,IAAIM,MAAM,CAAC,wBAAwB,EAAEI,MAAM;YACpD;QACF;QACAT,OAAOE,WAAW,CAAC,gBAAgB,SAASQ,qBAAqBN,GAAG;YAClEL,OAAO,IAAIM,MAAM,CAAC,mCAAmC,EAAED,KAAK;YAC5DG;QACF;QACAP,OAAOE,WAAW,CAAC,WAAW,SAASS,gBAAgBL,OAAO;YAC5DR,QAAQQ;YACRC;QACF;QAEA,SAASA;YACP,8EAA8E;YAC9E,+EAA+E;YAC/E,OAAO;YACPK,aAAa,IAAMZ,OAAOa,SAAS;QACrC;IACF;AACF;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASZ,mBAAmBN,QAAa,EAAEC,OAAgC;IAChF,IAAI,CAAC,qBAAqBkB,IAAI,CAACnB,SAASoB,QAAQ,GAAG;QACjD,MAAM,IAAIV,MAAM;IAClB;IAEA,OAAO,IAAIb,OAAO,IAAIwB,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAC1E,GAAGrB,OAAO;QACVsB,KAAK;YACH,GAAIzB,SAASG,QAAQsB,GAAG,IAAItB,QAAQsB,GAAG,GAAGC,QAAQD,GAAG;YACrDE,gCAAgCxB,QAAQyB,cAAc;YACtDC,yBAAyB3B,SAASoB,QAAQ;QAC5C;IACF;AACF"}
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 { tsImport } from 'tsx/esm/api';
1
+ import { importModule } from '../../util/importModule.js';
2
2
  const workerScript = process.env.TSX_WORKER_TASK_SCRIPT;
3
3
  if (workerScript) {
4
- await tsImport(workerScript, {
5
- parentURL: import.meta.url,
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 {tsImport} from 'tsx/esm/api'\n\nconst workerScript = process.env.TSX_WORKER_TASK_SCRIPT\n\nif (workerScript) {\n await tsImport(workerScript, {\n parentURL: import.meta.url,\n tsconfig: process.env.TSX_TSCONFIG_PATH,\n })\n} else {\n throw new Error('`TX_WORKER_TASK_SCRIPT` not defined')\n}\n"],"names":["tsImport","workerScript","process","env","TSX_WORKER_TASK_SCRIPT","parentURL","url","tsconfig","TSX_TSCONFIG_PATH","Error"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,cAAa;AAEpC,MAAMC,eAAeC,QAAQC,GAAG,CAACC,sBAAsB;AAEvD,IAAIH,cAAc;IAChB,MAAMD,SAASC,cAAc;QAC3BI,WAAW,YAAYC,GAAG;QAC1BC,UAAUL,QAAQC,GAAG,CAACK,iBAAiB;IACzC;AACF,OAAO;IACL,MAAM,IAAIC,MAAM;AAClB"}
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,8 +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
- import { debug } from '../../debug.js';
5
3
  import { isRecord } from '../../util/isRecord.js';
4
+ import { promisifyWorker } from '../../util/promisifyWorker.js';
6
5
  /**
7
6
  * Executes a worker file with tsx registered. This means you can import other
8
7
  * typescript with fairly rich syntax, and still have that only apply to the worker
@@ -24,41 +23,12 @@ import { isRecord } from '../../util/isRecord.js';
24
23
  ...tsconfig?.path ? {
25
24
  TSX_TSCONFIG_PATH: tsconfig.path
26
25
  } : {},
27
- TSX_WORKER_TASK_SCRIPT: filePath.pathname
26
+ TSX_WORKER_TASK_SCRIPT: fileURLToPath(filePath)
28
27
  };
29
- const worker = new Worker(new URL('tsxWorkerLoader.worker.js', import.meta.url), {
28
+ return promisifyWorker(new URL('tsxWorkerLoader.worker.js', import.meta.url), {
30
29
  ...options,
31
30
  env
32
31
  });
33
- return new Promise((resolve, reject)=>{
34
- worker.addListener('error', function onWorkerError(err) {
35
- debug(`Failed to load file through worker for: ${filePath.pathname}`, err);
36
- reject(new Error(`Failed to load file through worker: ${err.message}`, {
37
- cause: err
38
- }));
39
- cleanup();
40
- });
41
- worker.addListener('exit', function onWorkerExit(code) {
42
- if (code > 0) {
43
- reject(new Error(`Worker exited with code ${code}`));
44
- }
45
- });
46
- worker.addListener('messageerror', function onWorkerMessageError(err) {
47
- debug(`Failed to parse message from worker for: ${filePath.pathname}`, err);
48
- reject(new Error(`Fail to parse message from worker: ${err}`));
49
- cleanup();
50
- });
51
- worker.addListener('message', function onWorkerMessage(message) {
52
- resolve(message);
53
- cleanup();
54
- });
55
- function cleanup() {
56
- // Allow the worker a _bit_ of time to clean up, but ensure that we don't have
57
- // lingering processes hanging around forever if the worker doesn't exit on its
58
- // own.
59
- setImmediate(()=>worker.terminate());
60
- }
61
- });
62
32
  }
63
33
 
64
34
  //# sourceMappingURL=tsxWorkerTask.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerTask.ts"],"sourcesContent":["import {URL} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {getTsconfig} from 'get-tsconfig'\n\nimport {debug} from '../../debug.js'\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.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: filePath.pathname,\n }\n\n const worker = new Worker(new URL('tsxWorkerLoader.worker.js', import.meta.url), {\n ...options,\n env,\n })\n\n return new Promise((resolve, reject) => {\n worker.addListener('error', function onWorkerError(err) {\n debug(`Failed to load file through worker for: ${filePath.pathname}`, err)\n reject(new Error(`Failed to load file through worker: ${err.message}`, {cause: err}))\n cleanup()\n })\n worker.addListener('exit', function onWorkerExit(code) {\n if (code > 0) {\n reject(new Error(`Worker exited with code ${code}`))\n }\n })\n worker.addListener('messageerror', function onWorkerMessageError(err) {\n debug(`Failed to parse message from worker for: ${filePath.pathname}`, err)\n reject(new Error(`Fail to parse message from worker: ${err}`))\n cleanup()\n })\n worker.addListener('message', function onWorkerMessage(message) {\n resolve(message)\n cleanup()\n })\n\n function cleanup() {\n // Allow the worker a _bit_ of time to clean up, but ensure that we don't have\n // lingering processes hanging around forever if the worker doesn't exit on its\n // own.\n setImmediate(() => worker.terminate())\n }\n })\n}\n"],"names":["URL","Worker","getTsconfig","debug","isRecord","tsxWorkerTask","filePath","options","tsconfig","rootPath","env","process","path","TSX_TSCONFIG_PATH","TSX_WORKER_TASK_SCRIPT","pathname","worker","url","Promise","resolve","reject","addListener","onWorkerError","err","Error","message","cause","cleanup","onWorkerExit","code","onWorkerMessageError","onWorkerMessage","setImmediate","terminate"],"mappings":"AAAA,SAAQA,GAAG,QAAO,WAAU;AAC5B,SAAQC,MAAM,QAA2B,sBAAqB;AAE9D,SAAQC,WAAW,QAAO,eAAc;AAExC,SAAQC,KAAK,QAAO,iBAAgB;AAEpC,SAAQC,QAAQ,QAAO,yBAAwB;AAW/C;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,cACdC,QAAa,EACbC,OAA6B;IAE7B,MAAMC,WAAWN,YAAYK,QAAQE,QAAQ;IAE7C,MAAMC,MAAM;QACV,GAAIN,SAASG,QAAQG,GAAG,IAAIH,QAAQG,GAAG,GAAGC,QAAQD,GAAG;QACrD,GAAIF,UAAUI,OAAO;YAACC,mBAAmBL,SAASI,IAAI;QAAA,IAAI,CAAC,CAAC;QAC5DE,wBAAwBR,SAASS,QAAQ;IAC3C;IAEA,MAAMC,SAAS,IAAIf,OAAO,IAAID,IAAI,6BAA6B,YAAYiB,GAAG,GAAG;QAC/E,GAAGV,OAAO;QACVG;IACF;IAEA,OAAO,IAAIQ,QAAQ,CAACC,SAASC;QAC3BJ,OAAOK,WAAW,CAAC,SAAS,SAASC,cAAcC,GAAG;YACpDpB,MAAM,CAAC,wCAAwC,EAAEG,SAASS,QAAQ,EAAE,EAAEQ;YACtEH,OAAO,IAAII,MAAM,CAAC,oCAAoC,EAAED,IAAIE,OAAO,EAAE,EAAE;gBAACC,OAAOH;YAAG;YAClFI;QACF;QACAX,OAAOK,WAAW,CAAC,QAAQ,SAASO,aAAaC,IAAI;YACnD,IAAIA,OAAO,GAAG;gBACZT,OAAO,IAAII,MAAM,CAAC,wBAAwB,EAAEK,MAAM;YACpD;QACF;QACAb,OAAOK,WAAW,CAAC,gBAAgB,SAASS,qBAAqBP,GAAG;YAClEpB,MAAM,CAAC,yCAAyC,EAAEG,SAASS,QAAQ,EAAE,EAAEQ;YACvEH,OAAO,IAAII,MAAM,CAAC,mCAAmC,EAAED,KAAK;YAC5DI;QACF;QACAX,OAAOK,WAAW,CAAC,WAAW,SAASU,gBAAgBN,OAAO;YAC5DN,QAAQM;YACRE;QACF;QAEA,SAASA;YACP,8EAA8E;YAC9E,+EAA+E;YAC/E,OAAO;YACPK,aAAa,IAAMhB,OAAOiB,SAAS;QACrC;IACF;AACF"}
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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/request/createRequester.ts"],"sourcesContent":["import {getIt, type Requester} from 'get-it'\nimport {debug, headers, httpErrors, promise} from 'get-it/middleware'\nimport {readPackageUpSync} from 'read-package-up'\n\nlet cachedPkg: {name: string; version: string} | undefined\n\n/**\n * Options for configuring individual middleware in {@link createRequester}.\n *\n * Each key corresponds to a middleware. Omitting a key uses the default,\n * `false` disables it, and an object merges with the defaults.\n *\n * @public\n */\nexport type MiddlewareOptions = {\n debug?: false | {namespace?: string; verbose?: boolean}\n headers?: false | Record<string, string>\n httpErrors?: false\n promise?: false | {onlyBody?: boolean}\n}\n\n/**\n * Creates a `get-it` requester with a standard set of middleware.\n *\n * Default middleware (in order):\n * 1. `httpErrors()` — throw on HTTP error status codes\n * 2. `headers({'User-Agent': '@sanity/cli-core@<version>'})` — identify CLI requests\n * 3. `debug({verbose: true, namespace: 'sanity:cli'})` — debug logging\n * 4. `promise({onlyBody: true})` — return body directly (must be last)\n *\n * @param options - Optional configuration to disable or customize middleware\n * @returns A configured `get-it` requester\n * @public\n */\nexport function createRequester(options?: {middleware?: MiddlewareOptions}): Requester {\n const opts = options?.middleware\n\n const middleware = []\n\n // 1. httpErrors\n if (opts?.httpErrors !== false) {\n middleware.push(httpErrors())\n }\n\n // 2. headers\n if (opts?.headers !== false) {\n const customHeaders = typeof opts?.headers === 'object' ? opts.headers : {}\n const allHeaders = customHeaders['User-Agent']\n ? {...customHeaders}\n : {\n get ['User-Agent']() {\n const pkg = getPackageInfo()\n return `${pkg.name}@${pkg.version}`\n },\n ...customHeaders,\n }\n middleware.push(headers(allHeaders))\n }\n\n // 3. debug\n if (opts?.debug !== false) {\n const debugDefaults = {namespace: 'sanity:cli', verbose: true}\n const customDebug = typeof opts?.debug === 'object' ? opts.debug : {}\n middleware.push(debug({...debugDefaults, ...customDebug}))\n }\n\n // 4. promise (must be last)\n if (opts?.promise !== false) {\n const promiseDefaults = {onlyBody: true}\n const customPromise = typeof opts?.promise === 'object' ? opts.promise : {}\n middleware.push(promise({...promiseDefaults, ...customPromise}))\n }\n\n return getIt(middleware)\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 result = readPackageUpSync({cwd: import.meta.dirname})\n if (!result) {\n throw new Error('Unable to resolve @sanity/cli-core package root')\n }\n\n cachedPkg = {\n name: result.packageJson.name ?? '@sanity/cli-core',\n version: result.packageJson.version ?? '0.0.0',\n }\n return cachedPkg\n}\n"],"names":["getIt","debug","headers","httpErrors","promise","readPackageUpSync","cachedPkg","createRequester","options","opts","middleware","push","customHeaders","allHeaders","pkg","getPackageInfo","name","version","debugDefaults","namespace","verbose","customDebug","promiseDefaults","onlyBody","customPromise","result","cwd","dirname","Error","packageJson"],"mappings":"AAAA,SAAQA,KAAK,QAAuB,SAAQ;AAC5C,SAAQC,KAAK,EAAEC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAAO,oBAAmB;AACrE,SAAQC,iBAAiB,QAAO,kBAAiB;AAEjD,IAAIC;AAiBJ;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,gBAAgBC,OAA0C;IACxE,MAAMC,OAAOD,SAASE;IAEtB,MAAMA,aAAa,EAAE;IAErB,gBAAgB;IAChB,IAAID,MAAMN,eAAe,OAAO;QAC9BO,WAAWC,IAAI,CAACR;IAClB;IAEA,aAAa;IACb,IAAIM,MAAMP,YAAY,OAAO;QAC3B,MAAMU,gBAAgB,OAAOH,MAAMP,YAAY,WAAWO,KAAKP,OAAO,GAAG,CAAC;QAC1E,MAAMW,aAAaD,aAAa,CAAC,aAAa,GAC1C;YAAC,GAAGA,aAAa;QAAA,IACjB;YACE,IAAI,CAAC,aAAa,IAAG;gBACnB,MAAME,MAAMC;gBACZ,OAAO,GAAGD,IAAIE,IAAI,CAAC,CAAC,EAAEF,IAAIG,OAAO,EAAE;YACrC;YACA,GAAGL,aAAa;QAClB;QACJF,WAAWC,IAAI,CAACT,QAAQW;IAC1B;IAEA,WAAW;IACX,IAAIJ,MAAMR,UAAU,OAAO;QACzB,MAAMiB,gBAAgB;YAACC,WAAW;YAAcC,SAAS;QAAI;QAC7D,MAAMC,cAAc,OAAOZ,MAAMR,UAAU,WAAWQ,KAAKR,KAAK,GAAG,CAAC;QACpES,WAAWC,IAAI,CAACV,MAAM;YAAC,GAAGiB,aAAa;YAAE,GAAGG,WAAW;QAAA;IACzD;IAEA,4BAA4B;IAC5B,IAAIZ,MAAML,YAAY,OAAO;QAC3B,MAAMkB,kBAAkB;YAACC,UAAU;QAAI;QACvC,MAAMC,gBAAgB,OAAOf,MAAML,YAAY,WAAWK,KAAKL,OAAO,GAAG,CAAC;QAC1EM,WAAWC,IAAI,CAACP,QAAQ;YAAC,GAAGkB,eAAe;YAAE,GAAGE,aAAa;QAAA;IAC/D;IAEA,OAAOxB,MAAMU;AACf;AAEA;;;;;CAKC,GACD,SAASK;IACP,IAAIT,WAAW,OAAOA;IAEtB,MAAMmB,SAASpB,kBAAkB;QAACqB,KAAK,YAAYC,OAAO;IAAA;IAC1D,IAAI,CAACF,QAAQ;QACX,MAAM,IAAIG,MAAM;IAClB;IAEAtB,YAAY;QACVU,MAAMS,OAAOI,WAAW,CAACb,IAAI,IAAI;QACjCC,SAASQ,OAAOI,WAAW,CAACZ,OAAO,IAAI;IACzC;IACA,OAAOX;AACT"}