@sanity/cli-build 1.0.3 → 1.0.5

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.
@@ -16,18 +16,27 @@ export declare const AppBuildTrace: DefinedTelemetryTrace<
16
16
  void
17
17
  >;
18
18
 
19
- export declare const buildDebug: Debugger;
20
-
21
19
  /**
22
- * Builds the ESM browser compatible versions of the vendor packages
23
- * specified in VENDOR_IMPORTS. Returns the `imports` object of an import map.
20
+ * Everything the production build needs to produce an auto-updating studio/app.
21
+ *
22
+ * Auto-updating deployments load `sanity` (and friends) from Sanity's module
23
+ * CDN via an import map, and load `react`/`react-dom`/`styled-components` from
24
+ * hashed vendor chunks emitted by the build itself. These concerns always come
25
+ * together: when auto-updates are disabled none of this applies and everything
26
+ * is bundled as usual.
27
+ *
28
+ * @internal
24
29
  */
25
- export declare function buildVendorDependencies({
26
- basePath,
27
- cwd,
28
- isApp,
29
- outputDir,
30
- }: VendorBuildOptions): Promise<Record<string, string>>;
30
+ export declare interface AutoUpdatesBuildConfig {
31
+ /** Import map entries for the packages served from Sanity's module CDN. */
32
+ imports: Record<string, string>;
33
+ /** Vendor packages to emit as hashed browser-loadable ESM chunks. */
34
+ vendor: VendorBuildConfig;
35
+ /** Stylesheets served from the module CDN, loaded via `<link>` tags. */
36
+ cssUrls?: string[];
37
+ }
38
+
39
+ export declare const buildDebug: Debugger;
31
40
 
32
41
  export declare function checkStudioDependencyVersions(
33
42
  workDir: string,
@@ -69,14 +78,27 @@ export declare function extendViteConfigWithUserConfig(
69
78
  ): Promise<InlineConfig>;
70
79
 
71
80
  /**
72
- * Ensure Sanity entry chunk is always loaded
81
+ * Re-asserts the critical parts of the default config after a userland vite
82
+ * config (`vite` in `sanity.cli.ts`) has been applied.
83
+ *
84
+ * Everything `getViteConfig` sets under `build.rolldownOptions` is load-bearing:
85
+ * the `input` entries (the studio entry plus, for auto-updating studios/apps,
86
+ * the vendor entries), `preserveEntrySignatures`, the `experimental` flags the
87
+ * vendor plugins rely on, and the `output` chunk naming. A userland config that
88
+ * returns a brand-new object for any of these would silently break the build
89
+ * (e.g. vendor chunks never emitted while the bundle still treats them as
90
+ * external), so the default `rolldownOptions` are deep-merged back over the
91
+ * userland config: userland additions survive, replacements of critical
92
+ * options are healed.
73
93
  *
74
94
  * @param config - User-modified configuration
95
+ * @param defaultConfig - The configuration produced by `getViteConfig`, before the userland config was applied
75
96
  * @returns Merged configuration
76
97
  * @internal
77
98
  */
78
99
  export declare function finalizeViteConfig(
79
100
  config: InlineConfig,
101
+ defaultConfig: InlineConfig,
80
102
  ): Promise<InlineConfig>;
81
103
 
82
104
  /**
@@ -88,6 +110,23 @@ export declare function getViteConfig(
88
110
  options: ViteOptions,
89
111
  ): Promise<InlineConfig>;
90
112
 
113
+ /**
114
+ * Resolves vendor package entry points and metadata for a combined studio/app build.
115
+ * Does not run a build — callers add `entries` to the main Vite/Rolldown input and
116
+ * derive the import map from emitted vendor chunks after the single `vite.build`.
117
+ *
118
+ * @internal
119
+ */
120
+ export declare function resolveVendorBuildConfig({
121
+ cwd,
122
+ isApp,
123
+ }: ResolveVendorBuildConfigOptions): Promise<VendorBuildConfig>;
124
+
125
+ declare interface ResolveVendorBuildConfigOptions {
126
+ cwd: string;
127
+ isApp: boolean;
128
+ }
129
+
91
130
  declare interface RuntimeOptions {
92
131
  cwd: string;
93
132
  reactStrictMode: boolean | undefined;
@@ -111,11 +150,13 @@ declare interface TrackedPackage {
111
150
  supported: string[];
112
151
  }
113
152
 
114
- declare interface VendorBuildOptions {
115
- basePath: string;
116
- cwd: string;
117
- isApp: boolean;
118
- outputDir: string;
153
+ export declare interface VendorBuildConfig {
154
+ /** Rolldown entry name -\> absolute path to the package entry file. */
155
+ entries: Record<string, string>;
156
+ /** Named exports each CommonJS entry must re-expose as ESM, keyed by chunk name. */
157
+ namesByChunkName: Record<string, readonly string[]>;
158
+ /** Rolldown entry chunk name -\> bare import specifier (e.g. `react`, `react-dom/client`). */
159
+ specifiersByChunkName: Record<string, string>;
119
160
  }
120
161
 
121
162
  declare interface ViteOptions {
@@ -137,17 +178,16 @@ declare interface ViteOptions {
137
178
  */
138
179
  additionalPlugins?: Plugin_2[];
139
180
  /**
140
- * CSS URLs for auto-updated packages (loaded via module server)
181
+ * Auto-updates configuration (production builds only). When set, vendor
182
+ * packages are emitted as hashed ESM chunks by this build and the import map
183
+ * in `index.html` is derived from the build output.
141
184
  */
142
- autoUpdatesCssUrls?: string[];
185
+ autoUpdates?: AutoUpdatesBuildConfig;
143
186
  /**
144
187
  * Base path (eg under where to serve the app - `/studio` or similar)
145
188
  * Will be normalized to ensure it starts and ends with a `/`
146
189
  */
147
190
  basePath?: string;
148
- importMap?: {
149
- imports?: Record<string, string>;
150
- };
151
191
  isApp?: boolean;
152
192
  /**
153
193
  * Whether or not to minify the output (only used in `mode: 'production'`)
@@ -1,7 +1,7 @@
1
1
  export { buildDebug } from '../../actions/build/buildDebug.js';
2
- export { buildVendorDependencies } from '../../actions/build/buildVendorDependencies.js';
3
2
  export { checkStudioDependencyVersions } from '../../actions/build/checkStudioDependencyVersions.js';
4
3
  export { extendViteConfigWithUserConfig, finalizeViteConfig, getViteConfig } from '../../actions/build/getViteConfig.js';
4
+ export { resolveVendorBuildConfig } from '../../actions/build/resolveVendorBuildConfig.js';
5
5
  export { writeFavicons } from '../../actions/build/writeFavicons.js';
6
6
  export { writeSanityRuntime } from '../../actions/build/writeSanityRuntime.js';
7
7
  export { AppBuildTrace, StudioBuildTrace } from '../../telemetry/build.telemetry.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/_exports/_internal/build.ts"],"sourcesContent":["export {buildDebug} from '../../actions/build/buildDebug.js'\nexport {buildVendorDependencies} from '../../actions/build/buildVendorDependencies.js'\nexport {checkStudioDependencyVersions} from '../../actions/build/checkStudioDependencyVersions.js'\nexport {\n extendViteConfigWithUserConfig,\n finalizeViteConfig,\n getViteConfig,\n} from '../../actions/build/getViteConfig.js'\nexport {writeFavicons} from '../../actions/build/writeFavicons.js'\nexport {writeSanityRuntime} from '../../actions/build/writeSanityRuntime.js'\nexport {AppBuildTrace, StudioBuildTrace} from '../../telemetry/build.telemetry.js'\nexport {copyDir} from '../../util/copyDir.js'\n"],"names":["buildDebug","buildVendorDependencies","checkStudioDependencyVersions","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","writeFavicons","writeSanityRuntime","AppBuildTrace","StudioBuildTrace","copyDir"],"mappings":"AAAA,SAAQA,UAAU,QAAO,oCAAmC;AAC5D,SAAQC,uBAAuB,QAAO,iDAAgD;AACtF,SAAQC,6BAA6B,QAAO,uDAAsD;AAClG,SACEC,8BAA8B,EAC9BC,kBAAkB,EAClBC,aAAa,QACR,uCAAsC;AAC7C,SAAQC,aAAa,QAAO,uCAAsC;AAClE,SAAQC,kBAAkB,QAAO,4CAA2C;AAC5E,SAAQC,aAAa,EAAEC,gBAAgB,QAAO,qCAAoC;AAClF,SAAQC,OAAO,QAAO,wBAAuB"}
1
+ {"version":3,"sources":["../../../src/_exports/_internal/build.ts"],"sourcesContent":["export {type AutoUpdatesBuildConfig} from '../../actions/build/autoUpdates.js'\nexport {buildDebug} from '../../actions/build/buildDebug.js'\nexport {checkStudioDependencyVersions} from '../../actions/build/checkStudioDependencyVersions.js'\nexport {\n extendViteConfigWithUserConfig,\n finalizeViteConfig,\n getViteConfig,\n} from '../../actions/build/getViteConfig.js'\nexport {\n resolveVendorBuildConfig,\n type VendorBuildConfig,\n} from '../../actions/build/resolveVendorBuildConfig.js'\nexport {writeFavicons} from '../../actions/build/writeFavicons.js'\nexport {writeSanityRuntime} from '../../actions/build/writeSanityRuntime.js'\nexport {AppBuildTrace, StudioBuildTrace} from '../../telemetry/build.telemetry.js'\nexport {copyDir} from '../../util/copyDir.js'\n"],"names":["buildDebug","checkStudioDependencyVersions","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","resolveVendorBuildConfig","writeFavicons","writeSanityRuntime","AppBuildTrace","StudioBuildTrace","copyDir"],"mappings":"AACA,SAAQA,UAAU,QAAO,oCAAmC;AAC5D,SAAQC,6BAA6B,QAAO,uDAAsD;AAClG,SACEC,8BAA8B,EAC9BC,kBAAkB,EAClBC,aAAa,QACR,uCAAsC;AAC7C,SACEC,wBAAwB,QAEnB,kDAAiD;AACxD,SAAQC,aAAa,QAAO,uCAAsC;AAClE,SAAQC,kBAAkB,QAAO,4CAA2C;AAC5E,SAAQC,aAAa,EAAEC,gBAAgB,QAAO,qCAAoC;AAClF,SAAQC,OAAO,QAAO,wBAAuB"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Everything the production build needs to produce an auto-updating studio/app.
3
+ *
4
+ * Auto-updating deployments load `sanity` (and friends) from Sanity's module
5
+ * CDN via an import map, and load `react`/`react-dom`/`styled-components` from
6
+ * hashed vendor chunks emitted by the build itself. These concerns always come
7
+ * together: when auto-updates are disabled none of this applies and everything
8
+ * is bundled as usual.
9
+ *
10
+ * @internal
11
+ */ export { };
12
+
13
+ //# sourceMappingURL=autoUpdates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/build/autoUpdates.ts"],"sourcesContent":["import {type VendorBuildConfig} from './resolveVendorBuildConfig.js'\n\n/**\n * Everything the production build needs to produce an auto-updating studio/app.\n *\n * Auto-updating deployments load `sanity` (and friends) from Sanity's module\n * CDN via an import map, and load `react`/`react-dom`/`styled-components` from\n * hashed vendor chunks emitted by the build itself. These concerns always come\n * together: when auto-updates are disabled none of this applies and everything\n * is bundled as usual.\n *\n * @internal\n */\nexport interface AutoUpdatesBuildConfig {\n /** Import map entries for the packages served from Sanity's module CDN. */\n imports: Record<string, string>\n /** Vendor packages to emit as hashed browser-loadable ESM chunks. */\n vendor: VendorBuildConfig\n\n /** Stylesheets served from the module CDN, loaded via `<link>` tags. */\n cssUrls?: string[]\n}\n"],"names":[],"mappings":"AAEA;;;;;;;;;;CAUC,GACD,WAQC"}
@@ -0,0 +1,3 @@
1
+ /** Subdirectory under the build output where vendored ESM chunks are emitted. */ export const VENDOR_DIR = 'vendor';
2
+
3
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/build/constants.ts"],"sourcesContent":["/** Subdirectory under the build output where vendored ESM chunks are emitted. */\nexport const VENDOR_DIR = 'vendor'\n"],"names":["VENDOR_DIR"],"mappings":"AAAA,+EAA+E,GAC/E,OAAO,MAAMA,aAAa,SAAQ"}
@@ -0,0 +1,21 @@
1
+ import path from 'node:path';
2
+ /**
3
+ * Builds the vendor portion of an import map from emitted Rolldown chunks.
4
+ *
5
+ * The returned paths are absolute (rooted at the served `basePath`) so the
6
+ * browser can resolve the bare specifiers in the emitted import map regardless
7
+ * of the document's location.
8
+ *
9
+ * @internal
10
+ */ export function createVendorImportMapFromBundle(outputBundle, specifiersByChunkName, basePath) {
11
+ const imports = {};
12
+ for (const file of Object.values(outputBundle)){
13
+ if (file.type !== 'chunk' || !file.isEntry) continue;
14
+ const specifier = specifiersByChunkName[file.name];
15
+ if (!specifier) continue;
16
+ imports[specifier] = path.posix.join('/', basePath, file.fileName);
17
+ }
18
+ return imports;
19
+ }
20
+
21
+ //# sourceMappingURL=createVendorImportMapFromBundle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/build/createVendorImportMapFromBundle.ts"],"sourcesContent":["import path from 'node:path'\n\ninterface OutputChunk {\n fileName: string\n isEntry: boolean\n name: string\n type: 'chunk'\n}\n\ninterface OutputBundle {\n [fileName: string]: OutputChunk | {type: 'asset'}\n}\n\n/**\n * Builds the vendor portion of an import map from emitted Rolldown chunks.\n *\n * The returned paths are absolute (rooted at the served `basePath`) so the\n * browser can resolve the bare specifiers in the emitted import map regardless\n * of the document's location.\n *\n * @internal\n */\nexport function createVendorImportMapFromBundle(\n outputBundle: OutputBundle,\n specifiersByChunkName: Record<string, string>,\n basePath: string,\n): Record<string, string> {\n const imports: Record<string, string> = {}\n\n for (const file of Object.values(outputBundle)) {\n if (file.type !== 'chunk' || !file.isEntry) continue\n\n const specifier = specifiersByChunkName[file.name]\n if (!specifier) continue\n\n imports[specifier] = path.posix.join('/', basePath, file.fileName)\n }\n\n return imports\n}\n"],"names":["path","createVendorImportMapFromBundle","outputBundle","specifiersByChunkName","basePath","imports","file","Object","values","type","isEntry","specifier","name","posix","join","fileName"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAa5B;;;;;;;;CAQC,GACD,OAAO,SAASC,gCACdC,YAA0B,EAC1BC,qBAA6C,EAC7CC,QAAgB;IAEhB,MAAMC,UAAkC,CAAC;IAEzC,KAAK,MAAMC,QAAQC,OAAOC,MAAM,CAACN,cAAe;QAC9C,IAAII,KAAKG,IAAI,KAAK,WAAW,CAACH,KAAKI,OAAO,EAAE;QAE5C,MAAMC,YAAYR,qBAAqB,CAACG,KAAKM,IAAI,CAAC;QAClD,IAAI,CAACD,WAAW;QAEhBN,OAAO,CAACM,UAAU,GAAGX,KAAKa,KAAK,CAACC,IAAI,CAAC,KAAKV,UAAUE,KAAKS,QAAQ;IACnE;IAEA,OAAOV;AACT"}
@@ -6,18 +6,20 @@ import debug from 'debug';
6
6
  import { esmExternalRequirePlugin, mergeConfig } from 'vite';
7
7
  import { SANITY_CACHE_DIR } from '../../constants.js';
8
8
  import { sanitySchemaExtractionPlugin } from '../schema/vite/plugin-schema-extraction.js';
9
+ import { VENDOR_DIR } from './constants.js';
9
10
  import { createExternalFromImportMap } from './createExternalFromImportMap.js';
10
11
  import { normalizeBasePath } from './normalizeBasePath.js';
11
12
  import { sanityBuildEntries } from './vite/plugin-sanity-build-entries.js';
12
13
  import { sanityFaviconsPlugin } from './vite/plugin-sanity-favicons.js';
13
14
  import { sanityRuntimeRewritePlugin } from './vite/plugin-sanity-runtime-rewrite.js';
15
+ import { createVendorNamedExportsPlugin } from './vite/plugin-sanity-vendor-named-exports.js';
14
16
  import { getDefaultFaviconsPath } from './writeFavicons.js';
15
17
  /**
16
18
  * Get a configuration object for Vite based on the passed options
17
19
  *
18
20
  * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally
19
21
  */ export async function getViteConfig(options) {
20
- const { additionalPlugins, autoUpdatesCssUrls, basePath: rawBasePath = '/', cwd, importMap, isApp, minify, mode, outputDir, reactCompiler, schemaExtraction, server, // default to `true` when `mode=development`
22
+ const { additionalPlugins, autoUpdates, basePath: rawBasePath = '/', cwd, isApp, minify, mode, outputDir, reactCompiler, schemaExtraction, server, // default to `true` when `mode=development`
21
23
  sourceMap = options.mode === 'development' } = options;
22
24
  const basePath = normalizeBasePath(rawBasePath);
23
25
  const configPath = (await findProjectRoot(cwd)).path;
@@ -70,10 +72,9 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
70
72
  }),
71
73
  sanityRuntimeRewritePlugin(),
72
74
  sanityBuildEntries({
73
- autoUpdatesCssUrls,
75
+ autoUpdates,
74
76
  basePath,
75
77
  cwd,
76
- importMap,
77
78
  isApp
78
79
  }),
79
80
  // Add schema extraction when enabled
@@ -121,17 +122,30 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
121
122
  }
122
123
  };
123
124
  if (mode === 'production') {
124
- // For auto-updating studios the import map externalizes react/react-dom/etc.
125
- // Hand those externals to `esmExternalRequirePlugin` rather than
126
- // `rolldownOptions.external`, so any bundled CommonJS `require()` of an external
127
- // is rewritten to an ESM import instead of a runtime `require` shim that throws
128
- // in the browser. The plugin both marks them external AND converts the requires;
129
- // also setting `rolldownOptions.external` would short-circuit that conversion.
130
- // With no import map (auto-updates off) the external list is empty and this is a
131
- // no-op (everything is bundled, so requires resolve internally).
132
- viteConfig.plugins.push(esmExternalRequirePlugin({
133
- external: createExternalFromImportMap(importMap)
134
- }));
125
+ if (autoUpdates) {
126
+ viteConfig.plugins.push(// Re-expose CommonJS named exports (react, react-dom) as real ESM exports
127
+ // on the emitted vendor chunks; Rolldown only emits `export default` for a
128
+ // CommonJS entry.
129
+ createVendorNamedExportsPlugin(autoUpdates.vendor.namesByChunkName), // The import map and vendor specifiers are externals of the studio/app
130
+ // bundle, resolved by the browser at runtime. They are handed to
131
+ // `esmExternalRequirePlugin` rather than `rolldownOptions.external`: the
132
+ // plugin both marks them external AND rewrites bundled CommonJS
133
+ // `require()` calls of an external (e.g. react-dom requiring react) into
134
+ // ESM imports, while `rolldownOptions.external` would short-circuit that
135
+ // rewrite and leave a runtime `require` shim that throws in the browser.
136
+ esmExternalRequirePlugin({
137
+ external: createExternalFromImportMap({
138
+ imports: {
139
+ ...autoUpdates.imports,
140
+ ...Object.fromEntries(Object.values(autoUpdates.vendor.specifiersByChunkName).map((specifier)=>[
141
+ specifier,
142
+ ''
143
+ ]))
144
+ }
145
+ })
146
+ }));
147
+ }
148
+ const vendorChunkNames = autoUpdates ? new Set(Object.keys(autoUpdates.vendor.specifiersByChunkName)) : null;
135
149
  viteConfig.build = {
136
150
  ...viteConfig.build,
137
151
  assetsDir: 'static',
@@ -139,9 +153,29 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
139
153
  minify: minify ? 'oxc' : false,
140
154
  rolldownOptions: {
141
155
  input: {
142
- sanity: path.join(cwd, '.sanity', 'runtime', 'app.js')
156
+ sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),
157
+ ...autoUpdates?.vendor.entries
143
158
  },
144
- onwarn: onRolldownWarn
159
+ onwarn: onRolldownWarn,
160
+ ...autoUpdates ? {
161
+ // Expose Rolldown's native MagicString on `renderChunk`'s `meta` so
162
+ // the vendor named-exports plugin can edit chunks without a JS
163
+ // dependency.
164
+ experimental: {
165
+ nativeMagicString: true
166
+ },
167
+ output: {
168
+ entryFileNames: (chunk)=>vendorChunkNames.has(chunk.name) ? `${VENDOR_DIR}/[name]-[hash].mjs` : 'static/[name]-[hash].js',
169
+ exports: 'named'
170
+ },
171
+ // App-style builds default to `preserveEntrySignatures: false`, which
172
+ // treeshakes the exports off entry chunks. Vendor chunks are loaded by
173
+ // the browser via the import map, so their exports must survive (e.g.
174
+ // styled-components' native ESM exports). `exports-only` keeps exports
175
+ // for entries that have them, while the export-less `sanity` app entry
176
+ // still bundles as before.
177
+ preserveEntrySignatures: 'exports-only'
178
+ } : {}
145
179
  }
146
180
  };
147
181
  }
@@ -168,12 +202,24 @@ function suppressUnusedImport(warning) {
168
202
  return false;
169
203
  }
170
204
  /**
171
- * Ensure Sanity entry chunk is always loaded
205
+ * Re-asserts the critical parts of the default config after a userland vite
206
+ * config (`vite` in `sanity.cli.ts`) has been applied.
207
+ *
208
+ * Everything `getViteConfig` sets under `build.rolldownOptions` is load-bearing:
209
+ * the `input` entries (the studio entry plus, for auto-updating studios/apps,
210
+ * the vendor entries), `preserveEntrySignatures`, the `experimental` flags the
211
+ * vendor plugins rely on, and the `output` chunk naming. A userland config that
212
+ * returns a brand-new object for any of these would silently break the build
213
+ * (e.g. vendor chunks never emitted while the bundle still treats them as
214
+ * external), so the default `rolldownOptions` are deep-merged back over the
215
+ * userland config: userland additions survive, replacements of critical
216
+ * options are healed.
172
217
  *
173
218
  * @param config - User-modified configuration
219
+ * @param defaultConfig - The configuration produced by `getViteConfig`, before the userland config was applied
174
220
  * @returns Merged configuration
175
221
  * @internal
176
- */ export async function finalizeViteConfig(config) {
222
+ */ export async function finalizeViteConfig(config, defaultConfig) {
177
223
  if (typeof config.build?.rolldownOptions?.input !== 'object') {
178
224
  throw new TypeError('Vite config must contain `build.rolldownOptions.input`, and it must be an object');
179
225
  }
@@ -182,11 +228,7 @@ function suppressUnusedImport(warning) {
182
228
  }
183
229
  return mergeConfig(config, {
184
230
  build: {
185
- rolldownOptions: {
186
- input: {
187
- sanity: path.join(config.root, '.sanity', 'runtime', 'app.js')
188
- }
189
- }
231
+ rolldownOptions: defaultConfig.build?.rolldownOptions ?? {}
190
232
  }
191
233
  });
192
234
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport babel from '@rolldown/plugin-babel'\nimport {\n type CliConfig,\n findProjectRoot,\n getCliTelemetry,\n type UserViteConfig,\n} from '@sanity/cli-core'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport debug from 'debug'\nimport {\n type ConfigEnv,\n esmExternalRequirePlugin,\n type InlineConfig,\n mergeConfig,\n type Plugin,\n type Rolldown,\n} from 'vite'\n\nimport {SANITY_CACHE_DIR} from '../../constants.js'\nimport {sanitySchemaExtractionPlugin} from '../schema/vite/plugin-schema-extraction.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\nimport {sanityBuildEntries} from './vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from './vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from './vite/plugin-sanity-runtime-rewrite.js'\nimport {getDefaultFaviconsPath} from './writeFavicons.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n /**\n * Returns the environment variables to be injected into the config.\n */\n getEnvironmentVariables(): Record<string, string>\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: ReactCompilerConfig | undefined\n\n /**\n * Additional plugins when configured, eg. typegen\n */\n additionalPlugins?: Plugin[]\n\n /**\n * CSS URLs for auto-updated packages (loaded via module server)\n */\n autoUpdatesCssUrls?: string[]\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n importMap?: {imports?: Record<string, string>}\n\n isApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n /**\n * Schema extraction configuration\n */\n schemaExtraction?: CliConfig['schemaExtraction']\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n additionalPlugins,\n autoUpdatesCssUrls,\n basePath: rawBasePath = '/',\n cwd,\n importMap,\n isApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n server,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const configPath = (await findProjectRoot(cwd)).path\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = await getDefaultFaviconsPath()\n const staticPath = `${basePath}static`\n\n const envVars = options.getEnvironmentVariables()\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n configFile: false,\n define: {\n __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),\n __SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\n 'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n viteReact(),\n ...(reactCompiler ? [babel({presets: [reactCompilerPreset(reactCompiler)]})] : []),\n sanityFaviconsPlugin({customFaviconsPath, defaultFaviconsPath, staticUrlPath: staticPath}),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({autoUpdatesCssUrls, basePath, cwd, importMap, isApp}),\n // Add schema extraction when enabled\n ...(schemaExtraction?.enabled\n ? [\n sanitySchemaExtractionPlugin({\n additionalPatterns: schemaExtraction.watchPatterns,\n configPath,\n enforceRequiredFields: schemaExtraction.enforceRequiredFields,\n outputPath: schemaExtraction.path,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n workspaceName: schemaExtraction.workspace,\n }),\n ]\n : []),\n ...(additionalPlugins || []),\n ],\n resolve: {\n dedupe: ['react', 'react-dom', 'sanity', 'styled-components'],\n // Honor the studio's tsconfig `paths`, consistent with studioWorkerLoader.worker.ts.\n tsconfigPaths: true,\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Only enable strict port for studio,\n // since apps can run on any port\n strictPort: isApp ? false : true,\n\n /**\n * Significantly speed up startup time,\n * and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`\n * types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.\n * This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,\n * and thus avoids frustrating reload loops.\n */\n warmup: {\n clientFiles: ['./.sanity/runtime/app.js'],\n },\n },\n }\n\n if (mode === 'production') {\n // For auto-updating studios the import map externalizes react/react-dom/etc.\n // Hand those externals to `esmExternalRequirePlugin` rather than\n // `rolldownOptions.external`, so any bundled CommonJS `require()` of an external\n // is rewritten to an ESM import instead of a runtime `require` shim that throws\n // in the browser. The plugin both marks them external AND converts the requires;\n // also setting `rolldownOptions.external` would short-circuit that conversion.\n // With no import map (auto-updates off) the external list is empty and this is a\n // no-op (everything is bundled, so requires resolve internally).\n viteConfig.plugins!.push(\n esmExternalRequirePlugin({external: createExternalFromImportMap(importMap)}),\n )\n\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'oxc' : false,\n\n rolldownOptions: {\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n },\n onwarn: onRolldownWarn,\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRolldownWarn(warning: Rolldown.RolldownLog, warn: Rolldown.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rolldown.RolldownLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Ensure Sanity entry chunk is always loaded\n *\n * @param config - User-modified configuration\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(config: InlineConfig): Promise<InlineConfig> {\n if (typeof config.build?.rolldownOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rolldownOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rolldownOptions: {\n input: {\n sanity: path.join(config.root, '.sanity', 'runtime', 'app.js'),\n },\n },\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n debug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n debug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","babel","findProjectRoot","getCliTelemetry","viteReact","reactCompilerPreset","debug","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","createExternalFromImportMap","normalizeBasePath","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","getDefaultFaviconsPath","getViteConfig","options","additionalPlugins","autoUpdatesCssUrls","basePath","rawBasePath","cwd","importMap","isApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","getEnvironmentVariables","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","SANITY_INTERNAL_ENV","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","presets","staticUrlPath","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","push","external","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","warning","warn","suppressUnusedImport","code","names","includes","filter","n","length","ids","every","id","finalizeViteConfig","config","TypeError","Error","extendVi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A,OAAO7D,KAAK,EAAE2C,iBAAiBC,UAAU,UAAU;QAC5D,MAAM,IAAIkB,UACR;IAEJ;IAEA,IAAI,CAACD,OAAO5B,IAAI,EAAE;QAChB,MAAM,IAAI8B,MACR;IAEJ;IAEA,OAAOjG,YAAY+F,QAAQ;QACzB7D,OAAO;YACL2C,iBAAiB;gBACfC,OAAO;oBACLC,QAAQvF,KAAKmC,IAAI,CAACoE,OAAO5B,IAAI,EAAE,WAAW,WAAW;gBACvD;YACF;QACF;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAe+B,+BACpBlD,GAAc,EACdmD,aAA2B,EAC3BC,UAA0B;IAE1B,IAAIL,SAASI;IAEb,IAAI,OAAOC,eAAe,YAAY;QACpCtG,MAAM;QACNiG,SAAS,MAAMK,WAAWL,QAAQ/C;IACpC,OAAO,IAAI,OAAOoD,eAAe,UAAU;QACzCtG,MAAM;QACNiG,SAAS/F,YAAY+F,QAAQK;IAC/B;IAEA,OAAOL;AACT"}
1
+ {"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport babel from '@rolldown/plugin-babel'\nimport {\n type CliConfig,\n findProjectRoot,\n getCliTelemetry,\n type UserViteConfig,\n} from '@sanity/cli-core'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport debug from 'debug'\nimport {\n type ConfigEnv,\n esmExternalRequirePlugin,\n type InlineConfig,\n mergeConfig,\n type Plugin,\n type Rolldown,\n} from 'vite'\n\nimport {SANITY_CACHE_DIR} from '../../constants.js'\nimport {sanitySchemaExtractionPlugin} from '../schema/vite/plugin-schema-extraction.js'\nimport {type AutoUpdatesBuildConfig} from './autoUpdates.js'\nimport {VENDOR_DIR} from './constants.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\nimport {sanityBuildEntries} from './vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from './vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from './vite/plugin-sanity-runtime-rewrite.js'\nimport {createVendorNamedExportsPlugin} from './vite/plugin-sanity-vendor-named-exports.js'\nimport {getDefaultFaviconsPath} from './writeFavicons.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n /**\n * Returns the environment variables to be injected into the config.\n */\n getEnvironmentVariables(): Record<string, string>\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: ReactCompilerConfig | undefined\n\n /**\n * Additional plugins when configured, eg. typegen\n */\n additionalPlugins?: Plugin[]\n\n /**\n * Auto-updates configuration (production builds only). When set, vendor\n * packages are emitted as hashed ESM chunks by this build and the import map\n * in `index.html` is derived from the build output.\n */\n autoUpdates?: AutoUpdatesBuildConfig\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n isApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n\n /**\n * Schema extraction configuration\n */\n schemaExtraction?: CliConfig['schemaExtraction']\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n additionalPlugins,\n autoUpdates,\n basePath: rawBasePath = '/',\n cwd,\n isApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n server,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const configPath = (await findProjectRoot(cwd)).path\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = await getDefaultFaviconsPath()\n const staticPath = `${basePath}static`\n\n const envVars = options.getEnvironmentVariables()\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n configFile: false,\n define: {\n __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),\n __SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\n 'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n viteReact(),\n ...(reactCompiler ? [babel({presets: [reactCompilerPreset(reactCompiler)]})] : []),\n sanityFaviconsPlugin({customFaviconsPath, defaultFaviconsPath, staticUrlPath: staticPath}),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({autoUpdates, basePath, cwd, isApp}),\n // Add schema extraction when enabled\n ...(schemaExtraction?.enabled\n ? [\n sanitySchemaExtractionPlugin({\n additionalPatterns: schemaExtraction.watchPatterns,\n configPath,\n enforceRequiredFields: schemaExtraction.enforceRequiredFields,\n outputPath: schemaExtraction.path,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n workspaceName: schemaExtraction.workspace,\n }),\n ]\n : []),\n ...(additionalPlugins || []),\n ],\n resolve: {\n dedupe: ['react', 'react-dom', 'sanity', 'styled-components'],\n // Honor the studio's tsconfig `paths`, consistent with studioWorkerLoader.worker.ts.\n tsconfigPaths: true,\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Only enable strict port for studio,\n // since apps can run on any port\n strictPort: isApp ? false : true,\n\n /**\n * Significantly speed up startup time,\n * and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`\n * types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.\n * This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,\n * and thus avoids frustrating reload loops.\n */\n warmup: {\n clientFiles: ['./.sanity/runtime/app.js'],\n },\n },\n }\n\n if (mode === 'production') {\n if (autoUpdates) {\n viteConfig.plugins!.push(\n // Re-expose CommonJS named exports (react, react-dom) as real ESM exports\n // on the emitted vendor chunks; Rolldown only emits `export default` for a\n // CommonJS entry.\n createVendorNamedExportsPlugin(autoUpdates.vendor.namesByChunkName),\n // The import map and vendor specifiers are externals of the studio/app\n // bundle, resolved by the browser at runtime. They are handed to\n // `esmExternalRequirePlugin` rather than `rolldownOptions.external`: the\n // plugin both marks them external AND rewrites bundled CommonJS\n // `require()` calls of an external (e.g. react-dom requiring react) into\n // ESM imports, while `rolldownOptions.external` would short-circuit that\n // rewrite and leave a runtime `require` shim that throws in the browser.\n esmExternalRequirePlugin({\n external: createExternalFromImportMap({\n imports: {\n ...autoUpdates.imports,\n ...Object.fromEntries(\n Object.values(autoUpdates.vendor.specifiersByChunkName).map((specifier) => [\n specifier,\n '',\n ]),\n ),\n },\n }),\n }),\n )\n }\n\n const vendorChunkNames = autoUpdates\n ? new Set(Object.keys(autoUpdates.vendor.specifiersByChunkName))\n : null\n\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'oxc' : false,\n\n rolldownOptions: {\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n ...autoUpdates?.vendor.entries,\n },\n onwarn: onRolldownWarn,\n ...(autoUpdates\n ? {\n // Expose Rolldown's native MagicString on `renderChunk`'s `meta` so\n // the vendor named-exports plugin can edit chunks without a JS\n // dependency.\n experimental: {nativeMagicString: true},\n output: {\n entryFileNames: (chunk) =>\n vendorChunkNames!.has(chunk.name)\n ? `${VENDOR_DIR}/[name]-[hash].mjs`\n : 'static/[name]-[hash].js',\n exports: 'named',\n },\n // App-style builds default to `preserveEntrySignatures: false`, which\n // treeshakes the exports off entry chunks. Vendor chunks are loaded by\n // the browser via the import map, so their exports must survive (e.g.\n // styled-components' native ESM exports). `exports-only` keeps exports\n // for entries that have them, while the export-less `sanity` app entry\n // still bundles as before.\n preserveEntrySignatures: 'exports-only',\n }\n : {}),\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRolldownWarn(warning: Rolldown.RolldownLog, warn: Rolldown.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rolldown.RolldownLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Re-asserts the critical parts of the default config after a userland vite\n * config (`vite` in `sanity.cli.ts`) has been applied.\n *\n * Everything `getViteConfig` sets under `build.rolldownOptions` is load-bearing:\n * the `input` entries (the studio entry plus, for auto-updating studios/apps,\n * the vendor entries), `preserveEntrySignatures`, the `experimental` flags the\n * vendor plugins rely on, and the `output` chunk naming. A userland config that\n * returns a brand-new object for any of these would silently break the build\n * (e.g. vendor chunks never emitted while the bundle still treats them as\n * external), so the default `rolldownOptions` are deep-merged back over the\n * userland config: userland additions survive, replacements of critical\n * options are healed.\n *\n * @param config - User-modified configuration\n * @param defaultConfig - The configuration produced by `getViteConfig`, before the userland config was applied\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(\n config: InlineConfig,\n defaultConfig: InlineConfig,\n): Promise<InlineConfig> {\n if (typeof config.build?.rolldownOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rolldownOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rolldownOptions: defaultConfig.build?.rolldownOptions ?? {},\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n debug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n debug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","babel","findProjectRoot","getCliTelemetry","viteReact","reactCompilerPreset","debug","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","VENDOR_DIR","createExternalFromImportMap","normalizeBasePath","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","createVendorNamedExportsPlugin","getDefaultFaviconsPath","getViteConfig","options","additionalPlugins","autoUpdates","basePath","rawBasePath","cwd","isApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","getEnvironmentVariables","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","SANITY_INTERNAL_ENV","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","presets","staticUrlPath","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","push","vendor","namesByChunkName","external","imports","Object","fromEntries","values","specifiersByChunkName","map","specifier","vendorChunkNames","Set","keys","assetsDir","emptyOutDir","rolldownOptions","input","sanity","entries","onwarn","onRolldownWarn","experimental","nativeMagicString","output","entryFileNames","chunk","has","name","exports","preserveEntrySignatures","warning","warn","suppressUnusedImport","code","names","includes","filter","n","length","ids","every","id","finalizeViteConfig","config","defaultConfig","TypeError","Error","extendViteConfigWithUserConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,OAAOC,WAAW,yBAAwB;AAC1C,SAEEC,eAAe,EACfC,eAAe,QAEV,mBAAkB;AACzB,OAAOC,aAAYC,mBAAmB,QAAO,uBAAsB;AAEnE,OAAOC,WAAW,QAAO;AACzB,SAEEC,wBAAwB,EAExBC,WAAW,QAGN,OAAM;AAEb,SAAQC,gBAAgB,QAAO,qBAAoB;AACnD,SAAQC,4BAA4B,QAA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AACP;AAEA,SAASE,qBAAqBF,OAAgD;IAC5E,IAAIA,QAAQG,IAAI,KAAK,0BAA0B,OAAO;IAEtD,YAAY;IACZ,MAAM;IACN,4DAA4D;IAC5D,MAAM;IACN,IAAIH,QAAQI,KAAK,EAAEC,SAAS,kBAAkB;QAC5CL,QAAQI,KAAK,GAAGJ,QAAQI,KAAK,CAACE,MAAM,CAAC,CAACC,IAAMA,MAAM;QAClD,IAAIP,QAAQI,KAAK,CAACI,MAAM,KAAK,GAAG,OAAO;IACzC;IAEA,mFAAmF;IACnF,IAAIR,QAAQS,GAAG,EAAEC,MAAM,CAACC,KAAOA,GAAGN,QAAQ,CAAC,qBAAqBM,GAAGN,QAAQ,CAAC,sBAC1E,OAAO;IAET,OAAO;AACT;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,eAAeO,mBACpBC,MAAoB,EACpBC,aAA2B;IAE3B,IAAI,OAAOD,OAAOnF,KAAK,EAAEuD,iBAAiBC,UAAU,UAAU;QAC5D,MAAM,IAAI6B,UACR;IAEJ;IAEA,IAAI,CAACF,OAAOlD,IAAI,EAAE;QAChB,MAAM,IAAIqD,MACR;IAEJ;IAEA,OAAOzH,YAAYsH,QAAQ;QACzBnF,OAAO;YACLuD,iBAAiB6B,cAAcpF,KAAK,EAAEuD,mBAAmB,CAAC;QAC5D;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAegC,+BACpBzE,GAAc,EACdsE,aAA2B,EAC3BI,UAA0B;IAE1B,IAAIL,SAASC;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpC7H,MAAM;QACNwH,SAAS,MAAMK,WAAWL,QAAQrE;IACpC,OAAO,IAAI,OAAO0E,eAAe,UAAU;QACzC7H,MAAM;QACNwH,SAAStH,YAAYsH,QAAQK;IAC/B;IAEA,OAAOL;AACT"}
@@ -0,0 +1,95 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { getLocalPackageDir, getLocalPackageVersion } from '@sanity/cli-core';
4
+ import { gt, minVersion, rcompare, satisfies } from 'semver';
5
+ import { getCjsNamedExports } from './getCjsNamedExports.js';
6
+ // Define the vendor packages and their corresponding versions and entry points
7
+ const VENDOR_IMPORTS = {
8
+ react: {
9
+ '^19.2.0': {
10
+ '.': './cjs/react.production.js',
11
+ './compiler-runtime': './cjs/react-compiler-runtime.production.js',
12
+ './jsx-dev-runtime': './cjs/react-jsx-dev-runtime.production.js',
13
+ './jsx-runtime': './cjs/react-jsx-runtime.production.js',
14
+ './package.json': './package.json'
15
+ }
16
+ },
17
+ 'react-dom': {
18
+ '^19.2.0': {
19
+ '.': './cjs/react-dom.production.js',
20
+ './client': './cjs/react-dom-client.production.js',
21
+ './package.json': './package.json',
22
+ './server': './cjs/react-dom-server-legacy.browser.production.js',
23
+ './server.browser': './cjs/react-dom-server-legacy.browser.production.js',
24
+ './static': './cjs/react-dom-server.browser.production.js',
25
+ './static.browser': './cjs/react-dom-server.browser.production.js'
26
+ }
27
+ }
28
+ };
29
+ const STYLED_COMPONENTS_IMPORTS = {
30
+ 'styled-components': {
31
+ '^6.1.0': {
32
+ '.': './dist/styled-components.browser.esm.js',
33
+ './package.json': './package.json'
34
+ }
35
+ }
36
+ };
37
+ /**
38
+ * Resolves vendor package entry points and metadata for a combined studio/app build.
39
+ * Does not run a build — callers add `entries` to the main Vite/Rolldown input and
40
+ * derive the import map from emitted vendor chunks after the single `vite.build`.
41
+ *
42
+ * @internal
43
+ */ export async function resolveVendorBuildConfig({ cwd, isApp }) {
44
+ const entries = {};
45
+ const namesByChunkName = {};
46
+ const specifiersByChunkName = {};
47
+ const vendorImports = isApp ? VENDOR_IMPORTS : {
48
+ ...VENDOR_IMPORTS,
49
+ ...STYLED_COMPONENTS_IMPORTS
50
+ };
51
+ for (const [packageName, ranges] of Object.entries(vendorImports)){
52
+ const version = await getLocalPackageVersion(packageName, cwd);
53
+ if (!version) {
54
+ throw new Error(`Could not get version for '${packageName}'`);
55
+ }
56
+ const sortedRanges = Object.keys(ranges).toSorted((range1, range2)=>{
57
+ const min1 = minVersion(range1);
58
+ const min2 = minVersion(range2);
59
+ if (!min1) throw new Error(`Could not parse range '${range1}'`);
60
+ if (!min2) throw new Error(`Could not parse range '${range2}'`);
61
+ return rcompare(min1.version, min2.version);
62
+ });
63
+ const matchedRange = sortedRanges.find((range)=>satisfies(version, range));
64
+ if (!matchedRange) {
65
+ const min = minVersion(sortedRanges.at(-1));
66
+ if (!min) {
67
+ throw new Error(`Could not find a minimum version for package '${packageName}'`);
68
+ }
69
+ if (gt(min.version, version)) {
70
+ throw new Error(`Package '${packageName}' requires at least ${min.version}.`);
71
+ }
72
+ throw new Error(`Version '${version}' of package '${packageName}' is not supported yet.`);
73
+ }
74
+ const subpaths = ranges[matchedRange];
75
+ const packageDir = getLocalPackageDir(packageName, cwd);
76
+ for (const [subpath, relativeEntryPoint] of Object.entries(subpaths)){
77
+ const specifier = path.posix.join(packageName, subpath);
78
+ const chunkName = path.posix.join(packageName, path.relative(packageName, specifier) || 'index');
79
+ const entryPath = path.join(packageDir, relativeEntryPoint);
80
+ entries[chunkName] = entryPath;
81
+ specifiersByChunkName[chunkName] = specifier;
82
+ if (packageName in VENDOR_IMPORTS && subpath !== './package.json') {
83
+ const source = await readFile(entryPath, 'utf8');
84
+ namesByChunkName[chunkName] = await getCjsNamedExports(source, chunkName);
85
+ }
86
+ }
87
+ }
88
+ return {
89
+ entries,
90
+ namesByChunkName,
91
+ specifiersByChunkName
92
+ };
93
+ }
94
+
95
+ //# sourceMappingURL=resolveVendorBuildConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/build/resolveVendorBuildConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {getLocalPackageDir, getLocalPackageVersion} from '@sanity/cli-core'\nimport {gt, minVersion, rcompare, satisfies} from 'semver'\n\nimport {getCjsNamedExports} from './getCjsNamedExports.js'\n\n/**\n * A type representing the imports of vendor packages, defining specific entry\n * points for various versions and subpaths of the packages.\n */\ntype VendorImports = {\n [packageName: string]: {\n [versionRange: string]: {\n [subpath: string]: string\n }\n }\n}\n\n// Define the vendor packages and their corresponding versions and entry points\nconst VENDOR_IMPORTS: VendorImports = {\n react: {\n '^19.2.0': {\n '.': './cjs/react.production.js',\n './compiler-runtime': './cjs/react-compiler-runtime.production.js',\n './jsx-dev-runtime': './cjs/react-jsx-dev-runtime.production.js',\n './jsx-runtime': './cjs/react-jsx-runtime.production.js',\n './package.json': './package.json',\n },\n },\n 'react-dom': {\n '^19.2.0': {\n '.': './cjs/react-dom.production.js',\n './client': './cjs/react-dom-client.production.js',\n './package.json': './package.json',\n './server': './cjs/react-dom-server-legacy.browser.production.js',\n './server.browser': './cjs/react-dom-server-legacy.browser.production.js',\n './static': './cjs/react-dom-server.browser.production.js',\n './static.browser': './cjs/react-dom-server.browser.production.js',\n },\n },\n}\n\nconst STYLED_COMPONENTS_IMPORTS = {\n 'styled-components': {\n '^6.1.0': {\n '.': './dist/styled-components.browser.esm.js',\n './package.json': './package.json',\n },\n },\n}\n\nexport interface VendorBuildConfig {\n /** Rolldown entry name -\\> absolute path to the package entry file. */\n entries: Record<string, string>\n /** Named exports each CommonJS entry must re-expose as ESM, keyed by chunk name. */\n namesByChunkName: Record<string, readonly string[]>\n /** Rolldown entry chunk name -\\> bare import specifier (e.g. `react`, `react-dom/client`). */\n specifiersByChunkName: Record<string, string>\n}\n\ninterface ResolveVendorBuildConfigOptions {\n cwd: string\n isApp: boolean\n}\n\n/**\n * Resolves vendor package entry points and metadata for a combined studio/app build.\n * Does not run a build — callers add `entries` to the main Vite/Rolldown input and\n * derive the import map from emitted vendor chunks after the single `vite.build`.\n *\n * @internal\n */\nexport async function resolveVendorBuildConfig({\n cwd,\n isApp,\n}: ResolveVendorBuildConfigOptions): Promise<VendorBuildConfig> {\n const entries: Record<string, string> = {}\n const namesByChunkName: Record<string, readonly string[]> = {}\n const specifiersByChunkName: Record<string, string> = {}\n\n const vendorImports = isApp ? VENDOR_IMPORTS : {...VENDOR_IMPORTS, ...STYLED_COMPONENTS_IMPORTS}\n\n for (const [packageName, ranges] of Object.entries(vendorImports)) {\n const version = await getLocalPackageVersion(packageName, cwd)\n if (!version) {\n throw new Error(`Could not get version for '${packageName}'`)\n }\n\n const sortedRanges = Object.keys(ranges).toSorted((range1, range2) => {\n const min1 = minVersion(range1)\n const min2 = minVersion(range2)\n\n if (!min1) throw new Error(`Could not parse range '${range1}'`)\n if (!min2) throw new Error(`Could not parse range '${range2}'`)\n\n return rcompare(min1.version, min2.version)\n })\n\n const matchedRange = sortedRanges.find((range) => satisfies(version, range))\n\n if (!matchedRange) {\n const min = minVersion(sortedRanges.at(-1)!)\n if (!min) {\n throw new Error(`Could not find a minimum version for package '${packageName}'`)\n }\n\n if (gt(min.version, version)) {\n throw new Error(`Package '${packageName}' requires at least ${min.version}.`)\n }\n\n throw new Error(`Version '${version}' of package '${packageName}' is not supported yet.`)\n }\n\n const subpaths = ranges[matchedRange]\n const packageDir = getLocalPackageDir(packageName, cwd)\n\n for (const [subpath, relativeEntryPoint] of Object.entries(subpaths)) {\n const specifier = path.posix.join(packageName, subpath)\n const chunkName = path.posix.join(\n packageName,\n path.relative(packageName, specifier) || 'index',\n )\n\n const entryPath = path.join(packageDir, relativeEntryPoint)\n entries[chunkName] = entryPath\n specifiersByChunkName[chunkName] = specifier\n\n if (packageName in VENDOR_IMPORTS && subpath !== './package.json') {\n const source = await readFile(entryPath, 'utf8')\n namesByChunkName[chunkName] = await getCjsNamedExports(source, chunkName)\n }\n }\n }\n\n return {entries, namesByChunkName, specifiersByChunkName}\n}\n"],"names":["readFile","path","getLocalPackageDir","getLocalPackageVersion","gt","minVersion","rcompare","satisfies","getCjsNamedExports","VENDOR_IMPORTS","react","STYLED_COMPONENTS_IMPORTS","resolveVendorBuildConfig","cwd","isApp","entries","namesByChunkName","specifiersByChunkName","vendorImports","packageName","ranges","Object","version","Error","sortedRanges","keys","toSorted","range1","range2","min1","min2","matchedRange","find","range","min","at","subpaths","packageDir","subpath","relativeEntryPoint","specifier","posix","join","chunkName","relative","entryPath","source"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,OAAOC,UAAU,YAAW;AAE5B,SAAQC,kBAAkB,EAAEC,sBAAsB,QAAO,mBAAkB;AAC3E,SAAQC,EAAE,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,SAAS,QAAO,SAAQ;AAE1D,SAAQC,kBAAkB,QAAO,0BAAyB;AAc1D,+EAA+E;AAC/E,MAAMC,iBAAgC;IACpCC,OAAO;QACL,WAAW;YACT,KAAK;YACL,sBAAsB;YACtB,qBAAqB;YACrB,iBAAiB;YACjB,kBAAkB;QACpB;IACF;IACA,aAAa;QACX,WAAW;YACT,KAAK;YACL,YAAY;YACZ,kBAAkB;YAClB,YAAY;YACZ,oBAAoB;YACpB,YAAY;YACZ,oBAAoB;QACtB;IACF;AACF;AAEA,MAAMC,4BAA4B;IAChC,qBAAqB;QACnB,UAAU;YACR,KAAK;YACL,kBAAkB;QACpB;IACF;AACF;AAgBA;;;;;;CAMC,GACD,OAAO,eAAeC,yBAAyB,EAC7CC,GAAG,EACHC,KAAK,EAC2B;IAChC,MAAMC,UAAkC,CAAC;IACzC,MAAMC,mBAAsD,CAAC;IAC7D,MAAMC,wBAAgD,CAAC;IAEvD,MAAMC,gBAAgBJ,QAAQL,iBAAiB;QAAC,GAAGA,cAAc;QAAE,GAAGE,yBAAyB;IAAA;IAE/F,KAAK,MAAM,CAACQ,aAAaC,OAAO,IAAIC,OAAON,OAAO,CAACG,eAAgB;QACjE,MAAMI,UAAU,MAAMnB,uBAAuBgB,aAAaN;QAC1D,IAAI,CAACS,SAAS;YACZ,MAAM,IAAIC,MAAM,CAAC,2BAA2B,EAAEJ,YAAY,CAAC,CAAC;QAC9D;QAEA,MAAMK,eAAeH,OAAOI,IAAI,CAACL,QAAQM,QAAQ,CAAC,CAACC,QAAQC;YACzD,MAAMC,OAA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AAeV,kBAAkB6B,YAAY,kBAAkB;gBACjE,MAAMQ,SAAS,MAAM9C,SAAS6C,WAAW;gBACzC7B,gBAAgB,CAAC2B,UAAU,GAAG,MAAMnC,mBAAmBsC,QAAQH;YACjE;QACF;IACF;IAEA,OAAO;QAAC5B;QAASC;QAAkBC;IAAqB;AAC1D"}
@@ -1,9 +1,10 @@
1
+ import { createVendorImportMapFromBundle } from '../createVendorImportMapFromBundle.js';
1
2
  import { decorateIndexWithBridgeScript } from '../decorateIndexWithBridgeScript.js';
2
3
  import { decorateIndexWithStagingScript } from '../decorateIndexWithStagingScript.js';
3
4
  import { renderDocument } from '../renderDocument.js';
4
5
  const entryChunkId = '.sanity/runtime/app.js';
5
6
  export function sanityBuildEntries(options) {
6
- const { autoUpdatesCssUrls, basePath, cwd, importMap, isApp } = options;
7
+ const { autoUpdates, basePath, cwd, isApp } = options;
7
8
  return {
8
9
  apply: 'build',
9
10
  name: 'sanity/server/build-entries',
@@ -45,10 +46,19 @@ export function sanityBuildEntries(options) {
45
46
  }
46
47
  }
47
48
  }
49
+ // For auto-updating studios/apps the import map combines the vendor
50
+ // chunks emitted by this very build (hashed filenames, resolved from the
51
+ // bundle) with the module-CDN imports for auto-updated packages.
52
+ const importMap = autoUpdates ? {
53
+ imports: {
54
+ ...createVendorImportMapFromBundle(bundle, autoUpdates.vendor.specifiersByChunkName, basePath),
55
+ ...autoUpdates.imports
56
+ }
57
+ } : undefined;
48
58
  this.emitFile({
49
59
  fileName: 'index.html',
50
60
  source: decorateIndexWithStagingScript(decorateIndexWithBridgeScript(await renderDocument({
51
- autoUpdatesCssUrls,
61
+ autoUpdatesCssUrls: autoUpdates?.cssUrls,
52
62
  importMap,
53
63
  isApp,
54
64
  props: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/vite/plugin-sanity-build-entries.ts"],"sourcesContent":["import {type ChunkMetadata, type Plugin} from 'vite'\n\nimport {decorateIndexWithBridgeScript} from '../decorateIndexWithBridgeScript.js'\nimport {decorateIndexWithStagingScript} from '../decorateIndexWithStagingScript.js'\nimport {renderDocument} from '../renderDocument.js'\n\ninterface ViteOutputBundle {\n [fileName: string]: ViteRenderedAsset | ViteRenderedChunk\n}\n\ninterface ViteRenderedAsset {\n type: 'asset'\n}\n\ninterface ViteRenderedChunk {\n code: string\n facadeModuleId: string | null\n fileName: string\n imports: string[]\n isEntry: boolean\n name: string\n type: 'chunk'\n viteMetadata: ChunkMetadata\n}\n\nconst entryChunkId = '.sanity/runtime/app.js'\n\nexport function sanityBuildEntries(options: {\n autoUpdatesCssUrls?: string[]\n basePath: string\n cwd: string\n importMap?: {imports?: Record<string, string>}\n isApp?: boolean\n}): Plugin {\n const {autoUpdatesCssUrls, basePath, cwd, importMap, isApp} = options\n\n return {\n apply: 'build',\n name: 'sanity/server/build-entries',\n\n buildStart() {\n this.emitFile({\n id: entryChunkId,\n name: 'sanity',\n type: 'chunk',\n })\n },\n\n async generateBundle(_options, outputBundle) {\n const bundle = outputBundle as unknown as ViteOutputBundle\n const entryFile = Object.values(bundle).find(\n (file) =>\n file.type === 'chunk' &&\n file.name === 'sanity' &&\n file.facadeModuleId?.endsWith(entryChunkId),\n )\n\n if (!entryFile) {\n throw new Error(`Failed to find entry file in bundle (${entryChunkId})`)\n }\n\n if (entryFile.type !== 'chunk') {\n throw new Error('Entry file is not a chunk')\n }\n\n const entryFileName = entryFile.fileName\n const entryPath = [basePath.replace(/\\/+$/, ''), entryFileName].join('/')\n\n let css: string[] = []\n if (entryFile.viteMetadata?.importedCss) {\n // Check all the top-level imports of the entryPoint to see if they have\n // static CSS assets that need loading\n css = [...entryFile.viteMetadata.importedCss]\n for (const key of entryFile.imports) {\n // Traverse all CSS assets that isn't loaded by the runtime and\n // need <link> tags in the HTML template\n const entry = bundle[key]\n const importedCss =\n entry && entry.type === 'chunk' ? entry.viteMetadata.importedCss : undefined\n\n if (importedCss) {\n css.push(...importedCss)\n }\n }\n }\n\n this.emitFile({\n fileName: 'index.html',\n source: decorateIndexWithStagingScript(\n decorateIndexWithBridgeScript(\n await renderDocument({\n autoUpdatesCssUrls,\n importMap,\n isApp,\n props: {\n basePath,\n css,\n entryPath,\n },\n studioRootPath: cwd,\n }),\n ),\n ),\n type: 'asset',\n })\n },\n }\n}\n"],"names":["decorateIndexWithBridgeScript","decorateIndexWithStagingScript","renderDocument","entryChunkId","sanityBuildEntries","options","autoUpdatesCssUrls","basePath","cwd","importMap","isApp","apply","name","buildStart","emitFile","id","type","generateBundle","_options","outputBundle","bundle","entryFile","Object","values","find","file","facadeModuleId","endsWith","Error","entryFileName","fileName","entryPath","replace","join","css","viteMetadata","importedCss","key","imports","entry","undefined","push","source","props","studioRootPath"],"mappings":"AAEA,SAAQA,6BAA6B,QAAO,sCAAqC;AACjF,SAAQC,8BAA8B,QAAO,uCAAsC;AACnF,SAAQC,cAAc,QAAO,uBAAsB;AAqBnD,MAAMC,eAAe;AAErB,OAAO,SAASC,mBAAmBC,OAMlC;IACC,MAAM,EAACC,kBAAkB,EAAEC,QAAQ,EAAEC,GAAG,EAAEC,SAAS,EAAEC,KAAK,EAAC,GAAGL;IAE9D,OAAO;QACLM,OAAO;QACPC,MAAM;QAENC;YACE,IAAI,CAACC,QAAQ,CAAC;gBACZC,IAAIZ;gBACJS,MAAM;gBACNI,MAAM;YACR;QACF;QAEA,MAAMC,gBAAeC,QAAQ,EAAEC,YAAY;YACzC,MAAMC,SAASD;YACf,MAAME,YAAYC,OAAOC,MAAM,CAACH,QAAQI,IAAI,CAC1C,CAACC,OACCA,KAAKT,IAAI,KAAK,WACdS,KAAKb,IAAI,KAAK,YACda,KAAKC,cAAc,EAAEC,SAASxB;YAGlC,IAAI,CAACkB,WAAW;gBACd,MAAM,IAAIO,MAAM,CAAC,qCAAqC,EAAEzB,aAAa,CAAC,CAAC;YACzE;YAEA,IAAIkB,UAAUL,IAAI,KAAK,SAAS;gBAC9B,MAAM,IAAIY,MAAM;YAClB;YAEA,MAAMC,gBAAgBR,UAAUS,QAAQ;YACxC,MAAMC,YAAY;gBAACxB,SAASyB,OAAO,CAAC,QAAQ;gBAAKH;aAAc,CAACI,IAAI,CAAC;YAErE,IAAIC,MAAgB,EAAE;YACtB,IAAIb,UAAUc,YAAY,EAAEC,aAAa;gBACvC,wEAAwE;gBACxE,sCAAsC;gBACtCF,MAAM;uBAAIb,UAAUc,YAAY,CAACC,WAAW;iBAAC;gBAC7C,KAAK,MAAMC,OAAOhB,UAAUiB,OAAO,CAAE;oBACnC,+DAA+D;oBAC/D,wCAAwC;oBACxC,MAAMC,QAAQnB,MAAM,CAACiB,IAAI;oBACzB,MAAMD,cACJG,SAASA,MAAMvB,IAAI,KAAK,UAAUuB,MAAMJ,YAAY,CAACC,WAAW,GAAGI;oBAErE,IAAIJ,aAAa;wBACfF,IAAIO,IAAI,IAAIL;oBACd;gBACF;YACF;YAEA,IAAI,CAACtB,QAAQ,CAAC;gBACZgB,UAAU;gBACVY,QAAQzC,+BACND,8BACE,MAAME,eAAe;oBACnBI;oBACAG;oBACAC;oBACAiC,OAAO;wBACLpC;wBACA2B;wBACAH;oBACF;oBACAa,gBAAgBpC;gBAClB;gBAGJQ,MAAM;YACR;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../src/actions/build/vite/plugin-sanity-build-entries.ts"],"sourcesContent":["import {type ChunkMetadata, type Plugin} from 'vite'\n\nimport {type AutoUpdatesBuildConfig} from '../autoUpdates.js'\nimport {createVendorImportMapFromBundle} from '../createVendorImportMapFromBundle.js'\nimport {decorateIndexWithBridgeScript} from '../decorateIndexWithBridgeScript.js'\nimport {decorateIndexWithStagingScript} from '../decorateIndexWithStagingScript.js'\nimport {renderDocument} from '../renderDocument.js'\n\ninterface ViteOutputBundle {\n [fileName: string]: ViteRenderedAsset | ViteRenderedChunk\n}\n\ninterface ViteRenderedAsset {\n type: 'asset'\n}\n\ninterface ViteRenderedChunk {\n code: string\n facadeModuleId: string | null\n fileName: string\n imports: string[]\n isEntry: boolean\n name: string\n type: 'chunk'\n viteMetadata: ChunkMetadata\n}\n\nconst entryChunkId = '.sanity/runtime/app.js'\n\nexport function sanityBuildEntries(options: {\n autoUpdates?: AutoUpdatesBuildConfig\n basePath: string\n cwd: string\n isApp?: boolean\n}): Plugin {\n const {autoUpdates, basePath, cwd, isApp} = options\n\n return {\n apply: 'build',\n name: 'sanity/server/build-entries',\n\n buildStart() {\n this.emitFile({\n id: entryChunkId,\n name: 'sanity',\n type: 'chunk',\n })\n },\n\n async generateBundle(_options, outputBundle) {\n const bundle = outputBundle as unknown as ViteOutputBundle\n const entryFile = Object.values(bundle).find(\n (file) =>\n file.type === 'chunk' &&\n file.name === 'sanity' &&\n file.facadeModuleId?.endsWith(entryChunkId),\n )\n\n if (!entryFile) {\n throw new Error(`Failed to find entry file in bundle (${entryChunkId})`)\n }\n\n if (entryFile.type !== 'chunk') {\n throw new Error('Entry file is not a chunk')\n }\n\n const entryFileName = entryFile.fileName\n const entryPath = [basePath.replace(/\\/+$/, ''), entryFileName].join('/')\n\n let css: string[] = []\n if (entryFile.viteMetadata?.importedCss) {\n // Check all the top-level imports of the entryPoint to see if they have\n // static CSS assets that need loading\n css = [...entryFile.viteMetadata.importedCss]\n for (const key of entryFile.imports) {\n // Traverse all CSS assets that isn't loaded by the runtime and\n // need <link> tags in the HTML template\n const entry = bundle[key]\n const importedCss =\n entry && entry.type === 'chunk' ? entry.viteMetadata.importedCss : undefined\n\n if (importedCss) {\n css.push(...importedCss)\n }\n }\n }\n\n // For auto-updating studios/apps the import map combines the vendor\n // chunks emitted by this very build (hashed filenames, resolved from the\n // bundle) with the module-CDN imports for auto-updated packages.\n const importMap = autoUpdates\n ? {\n imports: {\n ...createVendorImportMapFromBundle(\n bundle,\n autoUpdates.vendor.specifiersByChunkName,\n basePath,\n ),\n ...autoUpdates.imports,\n },\n }\n : undefined\n\n this.emitFile({\n fileName: 'index.html',\n source: decorateIndexWithStagingScript(\n decorateIndexWithBridgeScript(\n await renderDocument({\n autoUpdatesCssUrls: autoUpdates?.cssUrls,\n importMap,\n isApp,\n props: {\n basePath,\n css,\n entryPath,\n },\n studioRootPath: cwd,\n }),\n ),\n ),\n type: 'asset',\n })\n },\n }\n}\n"],"names":["createVendorImportMapFromBundle","decorateIndexWithBridgeScript","decorateIndexWithStagingScript","renderDocument","entryChunkId","sanityBuildEntries","options","autoUpdates","basePath","cwd","isApp","apply","name","buildStart","emitFile","id","type","generateBundle","_options","outputBundle","bundle","entryFile","Object","values","find","file","facadeModuleId","endsWith","Error","entryFileName","fileName","entryPath","replace","join","css","viteMetadata","importedCss","key","imports","entry","undefined","push","importMap","vendor","specifiersByChunkName","source","autoUpdatesCssUrls","cssUrls","props","studioRootPath"],"mappings":"AAGA,SAAQA,+BAA+B,QAAO,wCAAuC;AACrF,SAAQC,6BAA6B,QAAO,sCAAqC;AACjF,SAAQC,8BAA8B,QAAO,uCAAsC;AACnF,SAAQC,cAAc,QAAO,uBAAsB;AAqBnD,MAAMC,eAAe;AAErB,OAAO,SAASC,mBAAmBC,OAKlC;IACC,MAAM,EAACC,WAAW,EAAEC,QAAQ,EAAEC,GAAG,EAAEC,KAAK,EAAC,GAAGJ;IAE5C,OAAO;QACLK,OAAO;QACPC,MAAM;QAENC;YACE,IAAI,CAACC,QAAQ,CAAC;gBACZC,IAAIX;gBACJQ,MAAM;gBACNI,MAAM;YACR;QACF;QAEA,MAAMC,gBAAeC,QAAQ,EAAEC,YAAY;YACzC,MAAMC,SAASD;YACf,MAAME,YAAYC,OAAOC,MAAM,CAACH,QAAQI,IAAI,CAC1C,CAACC,OACCA,KAAKT,IAAI,KAAK,WACdS,KAAKb,IAAI,KAAK,YACda,KAAKC,cAAc,EAAEC,SAASvB;YAGlC,IAAI,CAACiB,WAAW;gBACd,MAAM,IAAIO,MAAM,CAAC,qCAAqC,EAAExB,aAAa,CAAC,CAAC;YACzE;YAEA,IAAIiB,UAAUL,IAAI,KAAK,SAAS;gBAC9B,MAAM,IAAIY,MAAM;YAClB;YAEA,MAAMC,gBAAgBR,UAAUS,QAAQ;YACxC,MAAMC,YAAY;gBAACvB,SAASwB,OAAO,CAAC,QAAQ;gBAAKH;aAAc,CAACI,IAAI,CAAC;YAErE,IAAIC,MAAgB,EAAE;YACtB,IAAIb,UAAUc,YAAY,EAAEC,aAAa;gBACvC,wEAAwE;gBACxE,sCAAsC;gBACtCF,MAAM;uBAAIb,UAAUc,YAAY,CAACC,WAAW;iBAAC;gBAC7C,KAAK,MAAMC,OAAOhB,UAAUiB,OAAO,CAAE;oBACnC,+DAA+D;oBAC/D,wCAAwC;oBACxC,MAAMC,QAAQnB,MAAM,CAACiB,IAAI;oBACzB,MAAMD,cACJG,SAASA,MAAMvB,IAAI,KAAK,UAAUuB,MAAMJ,YAAY,CAACC,WAAW,GAAGI;oBAErE,IAAIJ,aAAa;wBACfF,IAAIO,IAAI,IAAIL;oBACd;gBACF;YACF;YAEA,oEAAoE;YACpE,yEAAyE;YACzE,iEAAiE;YACjE,MAAMM,YAAYnC,cACd;gBACE+B,SAAS;oBACP,GAAGtC,gCACDoB,QACAb,YAAYoC,MAAM,CAACC,qBAAqB,EACxCpC,SACD;oBACD,GAAGD,YAAY+B,OAAO;gBACxB;YACF,IACAE;YAEJ,IAAI,CAAC1B,QAAQ,CAAC;gBACZgB,UAAU;gBACVe,QAAQ3C,+BACND,8BACE,MAAME,eAAe;oBACnB2C,oBAAoBvC,aAAawC;oBACjCL;oBACAhC;oBACAsC,OAAO;wBACLxC;wBACA0B;wBACAH;oBACF;oBACAkB,gBAAgBxC;gBAClB;gBAGJO,MAAM;YACR;QACF;IACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-build",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "Internal Sanity package for building studios and apps",
5
5
  "keywords": [
6
6
  "cli",
@@ -45,9 +45,9 @@
45
45
  "@oclif/core": "^4.11.4",
46
46
  "@rolldown/plugin-babel": "^0.2.3",
47
47
  "@sanity/generate-help-url": "^4.0.0",
48
- "@sanity/schema": "^5.31.1",
48
+ "@sanity/schema": "^6.0.0",
49
49
  "@sanity/telemetry": "^1.1.0",
50
- "@sanity/types": "^5.31.1",
50
+ "@sanity/types": "^6.0.0",
51
51
  "@vitejs/plugin-react": "^6.0.2",
52
52
  "chokidar": "^5.0.0",
53
53
  "cjs-module-lexer": "^2.2.0",
@@ -71,7 +71,7 @@
71
71
  "@types/debug": "^4.1.13",
72
72
  "@types/jsdom": "^28.0.3",
73
73
  "@types/lodash-es": "^4.17.12",
74
- "@types/node": "^20.19.41",
74
+ "@types/node": "^20.19.43",
75
75
  "@types/picomatch": "^4.0.3",
76
76
  "@types/react": "^19.2.16",
77
77
  "@types/react-dom": "^19.2.3",
@@ -82,7 +82,7 @@
82
82
  "jsdom": "^29.1.1",
83
83
  "magic-string": "^0.30.21",
84
84
  "publint": "^0.3.21",
85
- "sanity": "^5.31.1",
85
+ "sanity": "^6.0.0",
86
86
  "styled-components": "^6.4.2",
87
87
  "typescript": "^5.9.3",
88
88
  "vitest": "^4.1.8",
@@ -1,179 +0,0 @@
1
- import { readFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { getLocalPackageDir, getLocalPackageVersion } from '@sanity/cli-core';
4
- import { gt, minVersion, rcompare, satisfies } from 'semver';
5
- import { build, esmExternalRequirePlugin } from 'vite';
6
- import { SANITY_CACHE_DIR } from '../../constants.js';
7
- import { createExternalFromImportMap } from './createExternalFromImportMap.js';
8
- import { getCjsNamedExports } from './getCjsNamedExports.js';
9
- import { createVendorNamedExportsPlugin } from './vite/plugin-sanity-vendor-named-exports.js';
10
- // Directory where vendor packages will be stored
11
- const VENDOR_DIR = 'vendor';
12
- // Define the vendor packages and their corresponding versions and entry points
13
- const VENDOR_IMPORTS = {
14
- react: {
15
- '^19.2.0': {
16
- '.': './cjs/react.production.js',
17
- './compiler-runtime': './cjs/react-compiler-runtime.production.js',
18
- './jsx-dev-runtime': './cjs/react-jsx-dev-runtime.production.js',
19
- './jsx-runtime': './cjs/react-jsx-runtime.production.js',
20
- './package.json': './package.json'
21
- }
22
- },
23
- 'react-dom': {
24
- '^19.2.0': {
25
- '.': './cjs/react-dom.production.js',
26
- './client': './cjs/react-dom-client.production.js',
27
- './package.json': './package.json',
28
- './server': './cjs/react-dom-server-legacy.browser.production.js',
29
- './server.browser': './cjs/react-dom-server-legacy.browser.production.js',
30
- './static': './cjs/react-dom-server.browser.production.js',
31
- './static.browser': './cjs/react-dom-server.browser.production.js'
32
- }
33
- }
34
- };
35
- const STYLED_COMPONENTS_IMPORTS = {
36
- 'styled-components': {
37
- '^6.1.0': {
38
- '.': './dist/styled-components.browser.esm.js',
39
- './package.json': './package.json'
40
- }
41
- }
42
- };
43
- /**
44
- * Builds the ESM browser compatible versions of the vendor packages
45
- * specified in VENDOR_IMPORTS. Returns the `imports` object of an import map.
46
- */ export async function buildVendorDependencies({ basePath, cwd, isApp, outputDir }) {
47
- const entry = {};
48
- const imports = {};
49
- // Named exports each CommonJS entry must re-expose as ESM, keyed by chunk name.
50
- const namesByChunkName = {};
51
- // If we're building an app, we don't need to build the styled-components package
52
- const vendorImports = isApp ? VENDOR_IMPORTS : {
53
- ...VENDOR_IMPORTS,
54
- ...STYLED_COMPONENTS_IMPORTS
55
- };
56
- // Iterate over each package and its version ranges in VENDOR_IMPORTS
57
- for (const [packageName, ranges] of Object.entries(vendorImports)){
58
- const version = await getLocalPackageVersion(packageName, cwd);
59
- if (!version) {
60
- throw new Error(`Could not get version for '${packageName}'`);
61
- }
62
- // Sort version ranges in descending order
63
- const sortedRanges = Object.keys(ranges).toSorted((range1, range2)=>{
64
- const min1 = minVersion(range1);
65
- const min2 = minVersion(range2);
66
- if (!min1) throw new Error(`Could not parse range '${range1}'`);
67
- if (!min2) throw new Error(`Could not parse range '${range2}'`);
68
- // sort them in reverse so we can rely on array `.find` below
69
- return rcompare(min1.version, min2.version);
70
- });
71
- // Find the first version range that satisfies the package version
72
- const matchedRange = sortedRanges.find((range)=>satisfies(version, range));
73
- if (!matchedRange) {
74
- const min = minVersion(sortedRanges.at(-1));
75
- if (!min) {
76
- throw new Error(`Could not find a minimum version for package '${packageName}'`);
77
- }
78
- if (gt(min.version, version)) {
79
- throw new Error(`Package '${packageName}' requires at least ${min.version}.`);
80
- }
81
- throw new Error(`Version '${version}' of package '${packageName}' is not supported yet.`);
82
- }
83
- const subpaths = ranges[matchedRange];
84
- // Resolve the actual package directory using Node module resolution,
85
- // so that hoisted packages in monorepos/workspaces are found correctly
86
- const packageDir = getLocalPackageDir(packageName, cwd);
87
- // Iterate over each subpath and its corresponding entry point
88
- for (const [subpath, relativeEntryPoint] of Object.entries(subpaths)){
89
- const specifier = path.posix.join(packageName, subpath);
90
- const chunkName = path.posix.join(packageName, path.relative(packageName, specifier) || 'index');
91
- const entryPath = path.join(packageDir, relativeEntryPoint);
92
- entry[chunkName] = entryPath;
93
- imports[specifier] = path.posix.join('/', basePath, VENDOR_DIR, `${chunkName}.mjs`);
94
- // React and React-DOM ship CommonJS. Rolldown lowers a CJS entry to an ESM
95
- // chunk that only emits `export default`, so collect the named exports it
96
- // must additionally re-expose (see `createVendorNamedExportsPlugin`).
97
- // `styled-components` is native ESM and `package.json` is JSON, so both are
98
- // skipped here.
99
- if (packageName in VENDOR_IMPORTS && subpath !== './package.json') {
100
- const source = await readFile(entryPath, 'utf8');
101
- namesByChunkName[chunkName] = await getCjsNamedExports(source, chunkName);
102
- }
103
- }
104
- }
105
- // Externals are handled by `esmExternalRequirePlugin` (below) rather than
106
- // `rolldownOptions.external`: the plugin both marks them external AND rewrites
107
- // CommonJS `require('react')` calls (e.g. in react-dom) into ESM imports.
108
- // Also setting `rolldownOptions.external` short-circuits that rewrite, leaving a
109
- // runtime `require` shim that throws in the browser.
110
- const external = createExternalFromImportMap({
111
- imports
112
- });
113
- // Use Vite to build the packages into the output directory
114
- let buildResult = await build({
115
- appType: 'custom',
116
- build: {
117
- emptyOutDir: false,
118
- lib: {
119
- entry,
120
- formats: [
121
- 'es'
122
- ]
123
- },
124
- minify: true,
125
- outDir: path.join(outputDir, VENDOR_DIR),
126
- rolldownOptions: {
127
- // Expose Rolldown's native MagicString on `renderChunk`'s `meta` so the
128
- // vendor named-exports plugin can edit chunks without a JS dependency.
129
- experimental: {
130
- nativeMagicString: true
131
- },
132
- output: {
133
- chunkFileNames: '[name]-[hash].mjs',
134
- entryFileNames: '[name]-[hash].mjs',
135
- exports: 'named',
136
- format: 'es'
137
- },
138
- treeshake: true
139
- }
140
- },
141
- // Define a custom cache directory so that sanity's vite cache
142
- // does not conflict with any potential local vite projects
143
- cacheDir: `${SANITY_CACHE_DIR}/vite-vendor`,
144
- configFile: false,
145
- define: {
146
- 'process.env.NODE_ENV': JSON.stringify('production')
147
- },
148
- logLevel: 'silent',
149
- mode: 'production',
150
- plugins: [
151
- // Re-expose CommonJS named exports (react, react-dom) as real ESM exports;
152
- // Rolldown only emits `export default` for a CommonJS entry.
153
- createVendorNamedExportsPlugin(namesByChunkName),
154
- // Rewrite external `require(...)` (e.g. react-dom requiring react) into ESM
155
- // imports so the vendored output runs in the browser without `require`.
156
- esmExternalRequirePlugin({
157
- external
158
- })
159
- ],
160
- root: cwd
161
- });
162
- buildResult = Array.isArray(buildResult) ? buildResult : [
163
- buildResult
164
- ];
165
- // Create a map of the original import specifiers to their hashed filenames
166
- const hashedImports = {};
167
- const output = buildResult.flatMap((i)=>i.output);
168
- for (const chunk of output){
169
- if (chunk.type === 'asset') continue;
170
- for (const [specifier, originalPath] of Object.entries(imports)){
171
- if (originalPath.endsWith(`${chunk.name}.mjs`)) {
172
- hashedImports[specifier] = path.posix.join('/', basePath, VENDOR_DIR, chunk.fileName);
173
- }
174
- }
175
- }
176
- return hashedImports;
177
- }
178
-
179
- //# sourceMappingURL=buildVendorDependencies.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/actions/build/buildVendorDependencies.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {getLocalPackageDir, getLocalPackageVersion} from '@sanity/cli-core'\nimport {gt, minVersion, rcompare, satisfies} from 'semver'\nimport {build, esmExternalRequirePlugin} from 'vite'\n\nimport {SANITY_CACHE_DIR} from '../../constants.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {getCjsNamedExports} from './getCjsNamedExports.js'\nimport {createVendorNamedExportsPlugin} from './vite/plugin-sanity-vendor-named-exports.js'\n\n// Directory where vendor packages will be stored\nconst VENDOR_DIR = 'vendor'\n\n/**\n * A type representing the imports of vendor packages, defining specific entry\n * points for various versions and subpaths of the packages.\n *\n * The `VendorImports` object is used to build ESM browser-compatible versions\n * of the specified packages. This approach ensures that the appropriate version\n * and entry points are used for each package, enabling compatibility and proper\n * functionality in the browser environment.\n *\n * ## Rationale\n *\n * The rationale for this structure is to handle different versions of the\n * packages carefully, especially major versions. Major version bumps often\n * introduce breaking changes, so the module scheme for the package needs to be\n * checked when there is a major version update. However, minor and patch\n * versions are generally backward compatible, so they are handled more\n * leniently. By assuming that new minor versions are compatible, we avoid\n * unnecessary warnings and streamline the update process.\n *\n * If a new minor version introduces an additional subpath export within the\n * package of this version range, the corresponding package can add a more\n * specific version range that includes the new subpath. This design allows for\n * flexibility and ease of maintenance, ensuring that the latest features and\n * fixes are incorporated without extensive manual intervention.\n *\n * An additional subpath export within the package of this version range that\n * could cause the build to break if that new export is used, can be treated as\n * a bug fix. It might make more sense to our users that this new subpath isn't\n * supported yet until we address it as a bug fix. This approach helps maintain\n * stability and prevents unexpected issues during the build process.\n *\n * ## Structure\n * The `VendorImports` type is a nested object where:\n * - The keys at the first level represent the package names.\n * - The keys at the second level represent the version ranges (e.g., `^19.0.0`).\n * - The keys at the third level represent the subpaths within the package (e.g., `.` for the main entry point).\n * - The values at the third level are the relative paths to the corresponding entry points within the package.\n *\n * This structure allows for precise specification of the entry points for\n * different versions and subpaths, ensuring that the correct files are used\n * during the build process.\n */\ntype VendorImports = {\n [packageName: string]: {\n [versionRange: string]: {\n [subpath: string]: string\n }\n }\n}\n\n// Define the vendor packages and their corresponding versions and entry points\nconst VENDOR_IMPORTS: VendorImports = {\n react: {\n '^19.2.0': {\n '.': './cjs/react.production.js',\n './compiler-runtime': './cjs/react-compiler-runtime.production.js',\n './jsx-dev-runtime': './cjs/react-jsx-dev-runtime.production.js',\n './jsx-runtime': './cjs/react-jsx-runtime.production.js',\n './package.json': './package.json',\n },\n },\n 'react-dom': {\n '^19.2.0': {\n '.': './cjs/react-dom.production.js',\n './client': './cjs/react-dom-client.production.js',\n './package.json': './package.json',\n './server': './cjs/react-dom-server-legacy.browser.production.js',\n './server.browser': './cjs/react-dom-server-legacy.browser.production.js',\n './static': './cjs/react-dom-server.browser.production.js',\n './static.browser': './cjs/react-dom-server.browser.production.js',\n },\n },\n}\n\nconst STYLED_COMPONENTS_IMPORTS = {\n 'styled-components': {\n '^6.1.0': {\n '.': './dist/styled-components.browser.esm.js',\n './package.json': './package.json',\n },\n },\n}\n\ninterface VendorBuildOptions {\n basePath: string\n cwd: string\n isApp: boolean\n outputDir: string\n}\n\n/**\n * Builds the ESM browser compatible versions of the vendor packages\n * specified in VENDOR_IMPORTS. Returns the `imports` object of an import map.\n */\nexport async function buildVendorDependencies({\n basePath,\n cwd,\n isApp,\n outputDir,\n}: VendorBuildOptions): Promise<Record<string, string>> {\n const entry: Record<string, string> = {}\n const imports: Record<string, string> = {}\n\n // Named exports each CommonJS entry must re-expose as ESM, keyed by chunk name.\n const namesByChunkName: Record<string, readonly string[]> = {}\n\n // If we're building an app, we don't need to build the styled-components package\n const vendorImports = isApp ? VENDOR_IMPORTS : {...VENDOR_IMPORTS, ...STYLED_COMPONENTS_IMPORTS}\n\n // Iterate over each package and its version ranges in VENDOR_IMPORTS\n for (const [packageName, ranges] of Object.entries(vendorImports)) {\n const version = await getLocalPackageVersion(packageName, cwd)\n if (!version) {\n throw new Error(`Could not get version for '${packageName}'`)\n }\n\n // Sort version ranges in descending order\n const sortedRanges = Object.keys(ranges).toSorted((range1, range2) => {\n const min1 = minVersion(range1)\n const min2 = minVersion(range2)\n\n if (!min1) throw new Error(`Could not parse range '${range1}'`)\n if (!min2) throw new Error(`Could not parse range '${range2}'`)\n\n // sort them in reverse so we can rely on array `.find` below\n return rcompare(min1.version, min2.version)\n })\n\n // Find the first version range that satisfies the package version\n const matchedRange = sortedRanges.find((range) => satisfies(version, range))\n\n if (!matchedRange) {\n const min = minVersion(sortedRanges.at(-1)!)\n if (!min) {\n throw new Error(`Could not find a minimum version for package '${packageName}'`)\n }\n\n if (gt(min.version, version)) {\n throw new Error(`Package '${packageName}' requires at least ${min.version}.`)\n }\n\n throw new Error(`Version '${version}' of package '${packageName}' is not supported yet.`)\n }\n\n const subpaths = ranges[matchedRange]\n\n // Resolve the actual package directory using Node module resolution,\n // so that hoisted packages in monorepos/workspaces are found correctly\n const packageDir = getLocalPackageDir(packageName, cwd)\n\n // Iterate over each subpath and its corresponding entry point\n for (const [subpath, relativeEntryPoint] of Object.entries(subpaths)) {\n const specifier = path.posix.join(packageName, subpath)\n const chunkName = path.posix.join(\n packageName,\n path.relative(packageName, specifier) || 'index',\n )\n\n const entryPath = path.join(packageDir, relativeEntryPoint)\n entry[chunkName] = entryPath\n imports[specifier] = path.posix.join('/', basePath, VENDOR_DIR, `${chunkName}.mjs`)\n\n // React and React-DOM ship CommonJS. Rolldown lowers a CJS entry to an ESM\n // chunk that only emits `export default`, so collect the named exports it\n // must additionally re-expose (see `createVendorNamedExportsPlugin`).\n // `styled-components` is native ESM and `package.json` is JSON, so both are\n // skipped here.\n if (packageName in VENDOR_IMPORTS && subpath !== './package.json') {\n const source = await readFile(entryPath, 'utf8')\n namesByChunkName[chunkName] = await getCjsNamedExports(source, chunkName)\n }\n }\n }\n\n // Externals are handled by `esmExternalRequirePlugin` (below) rather than\n // `rolldownOptions.external`: the plugin both marks them external AND rewrites\n // CommonJS `require('react')` calls (e.g. in react-dom) into ESM imports.\n // Also setting `rolldownOptions.external` short-circuits that rewrite, leaving a\n // runtime `require` shim that throws in the browser.\n const external = createExternalFromImportMap({imports})\n\n // removes the `RolldownWatcher` type\n type BuildResult = Exclude<Awaited<ReturnType<typeof build>>, {close: unknown}>\n\n // Use Vite to build the packages into the output directory\n let buildResult = (await build({\n appType: 'custom',\n build: {\n emptyOutDir: false, // Rely on CLI to do this\n lib: {entry, formats: ['es']},\n minify: true,\n outDir: path.join(outputDir, VENDOR_DIR),\n rolldownOptions: {\n // Expose Rolldown's native MagicString on `renderChunk`'s `meta` so the\n // vendor named-exports plugin can edit chunks without a JS dependency.\n experimental: {nativeMagicString: true},\n output: {\n chunkFileNames: '[name]-[hash].mjs',\n entryFileNames: '[name]-[hash].mjs',\n exports: 'named',\n format: 'es',\n },\n treeshake: true,\n },\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: `${SANITY_CACHE_DIR}/vite-vendor`,\n configFile: false,\n define: {'process.env.NODE_ENV': JSON.stringify('production')},\n logLevel: 'silent',\n mode: 'production',\n plugins: [\n // Re-expose CommonJS named exports (react, react-dom) as real ESM exports;\n // Rolldown only emits `export default` for a CommonJS entry.\n createVendorNamedExportsPlugin(namesByChunkName),\n // Rewrite external `require(...)` (e.g. react-dom requiring react) into ESM\n // imports so the vendored output runs in the browser without `require`.\n esmExternalRequirePlugin({external}),\n ],\n root: cwd,\n })) as BuildResult\n\n buildResult = Array.isArray(buildResult) ? buildResult : [buildResult]\n\n // Create a map of the original import specifiers to their hashed filenames\n const hashedImports: Record<string, string> = {}\n const output = buildResult.flatMap((i) => i.output)\n\n for (const chunk of output) {\n if (chunk.type === 'asset') continue\n\n for (const [specifier, originalPath] of Object.entries(imports)) {\n if (originalPath.endsWith(`${chunk.name}.mjs`)) {\n hashedImports[specifier] = path.posix.join('/', basePath, VENDOR_DIR, chunk.fileName)\n }\n }\n }\n\n return hashedImports\n}\n"],"names":["readFile","path","getLocalPackageDir","getLocalPackageVersion","gt","minVersion","rcompare","satisfies","build","esmExternalRequirePlugin","SANITY_CACHE_DIR","createExternalFromImportMap","getCjsNamedExports","createVendorNamedExportsPlugin","VENDOR_DIR","VENDOR_IMPORTS","react","STYLED_COMPONENTS_IMPORTS","buildVendorDependencies","basePath","cwd","isApp","outputDir","entry","imports","namesByChunkName","vendorImports","packageName","ranges","Object","entries","version","Error","sortedRanges","keys","toSorted","range1","range2","min1","min2","matchedRange","find","range","min","at","subpaths","packageDir","subpath","relativeEntryPoint","specifier","posix","join","chunkName","relative","entryPath","source","external","buildResult","appType","emptyOutDir","lib","formats","minify","outDir","rolldownOptions","experimental","nativeMagicString","output","chunkFileNames","entryFileNames","exports","format","treeshake","cacheDir","configFile","define","JSON","stringify","logLevel","mode","plugins","root","Array","isArray","hashedImports","flatMap","i","chunk","type","originalPath","endsWith","name","fileName"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,OAAOC,UAAU,YAAW;AAE5B,SAAQC,kBAAkB,EAAEC,sBAAsB,QAAO,mBAAkB;AAC3E,SAAQC,EAAE,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,SAAS,QAAO,SAAQ;AAC1D,SAAQC,KAAK,EAAEC,wBAAwB,QAAO,OAAM;AAEpD,SAAQC,gBAAgB,QAAO,qBAAoB;AACnD,SAAQC,2BAA2B,QAAO,mCAAkC;AAC5E,SAAQC,kBAAkB,QAAO,0BAAyB;AAC1D,SAAQC,8BAA8B,QAAO,+CAA8C;AAE3F,iDAAiD;AACjD,MAAMC,aAAa;AAoDnB,+EAA+E;AAC/E,MAAMC,iBAAgC;IACpCC,OAAO;QACL,WAAW;YACT,KAAK;YACL,sBAAsB;YACtB,qBAAqB;YACrB,iBAAiB;YACjB,kBAAkB;QACpB;IACF;IACA,aAAa;QACX,WAAW;YACT,KAAK;YACL,YAAY;YACZ,kBAAkB;YAClB,YAAY;YACZ,oBAAoB;YACpB,YAAY;YACZ,oBAAoB;QACtB;IACF;AACF;AAEA,MAAMC,4BAA4B;IAChC,qBAAqB;QACnB,UAAU;YACR,K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