@sanity/cli-build 4.1.1 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,6 +34,15 @@ declare interface AutoUpdatesBuildConfig {
34
34
  */
35
35
  export declare function buildApp(options: BuildOptions): Promise<void>;
36
36
 
37
+ export declare type BuildAppEventListener = BuildEventListener;
38
+
39
+ declare interface BuildEventListener {
40
+ onPreReleaseInInteractiveAutoUpdate(params: {
41
+ prereleaseMessage: string;
42
+ }): Promise<void>;
43
+ onPreReleaseInNonInteractiveAutoUpdate: MessageFunc;
44
+ }
45
+
37
46
  declare interface BuildOptions {
38
47
  appId: string | undefined;
39
48
  appTitle: string | undefined;
@@ -47,6 +56,7 @@ declare interface BuildOptions {
47
56
  ) => Promise<CompareDependencyVersionsResult>;
48
57
  determineBasePath: () => string;
49
58
  entry: string | undefined;
59
+ eventListener: Partial<BuildAppEventListener>;
50
60
  isWorkbenchApp: boolean;
51
61
  minify: boolean;
52
62
  outDir: string | undefined;
@@ -74,6 +84,7 @@ declare interface BuildOptions_2 {
74
84
  }[],
75
85
  ) => Promise<CompareDependencyVersionsResult>;
76
86
  determineBasePath: () => string;
87
+ eventListener: Partial<BuildStudioEventListener>;
77
88
  isApp: boolean;
78
89
  isWorkbenchApp: boolean;
79
90
  minify: boolean;
@@ -84,9 +95,6 @@ declare interface BuildOptions_2 {
84
95
  sourceMap: boolean;
85
96
  stats: boolean;
86
97
  unattendedMode: boolean;
87
- upgradePackages(options: {
88
- packages: [name: string, version: string][];
89
- }): Promise<void>;
90
98
  vite: UserViteConfig | undefined;
91
99
  workDir: string;
92
100
  exposes?: WorkbenchExposes;
@@ -109,6 +117,32 @@ export declare function buildStaticFiles(options: StaticBuildOptions): Promise<{
109
117
  */
110
118
  export declare function buildStudio(options: BuildOptions_2): Promise<void>;
111
119
 
120
+ export declare interface BuildStudioEventListener extends BuildEventListener {
121
+ onBuildEnd: MessageFunc;
122
+ onBuildFail: MessageFunc;
123
+ onBuildStart: MessageFunc;
124
+ onCleanOutputDirEnd: MessageFunc;
125
+ onCleanOutputDirStart: MessageFunc;
126
+ onIncompatibleDeclaredStyledComponentsVersionRange: MessageFunc;
127
+ onIncompatibleInstalledStyledComponentsVersionRange: MessageFunc;
128
+ onInteractiveNonDefaultOutputDir({ message }: { message: string }): Promise<{
129
+ shouldClean: boolean;
130
+ }>;
131
+ onInvalidStyledComponentsVersionRange: MessageFunc;
132
+ onNoDeclaredStyledComponentsVersion: MessageFunc;
133
+ onNoInstalledSanityVersion: MessageFunc;
134
+ onNoInstalledStyledComponentsVersion: MessageFunc;
135
+ onVersionMismatchInInteractiveAutoUpdate(params: {
136
+ mismatched: CompareDependencyVersions[];
137
+ versionMismatchWarning: string;
138
+ }): Promise<{
139
+ stopBuild: boolean;
140
+ }>;
141
+ onVersionMismatchInNonInteractiveAutoUpdate(params: {
142
+ versionMismatchWarning: string;
143
+ }): void;
144
+ }
145
+
112
146
  /**
113
147
  * Checks that the studio has declared and installed the required dependencies
114
148
  * needed by the Sanity modules. While we generally use regular, explicit
@@ -126,8 +160,13 @@ export declare function checkRequiredDependencies(
126
160
 
127
161
  declare interface CheckRequiredDependenciesOptions {
128
162
  isApp: boolean;
129
- output: Output;
130
163
  workDir: string;
164
+ onIncompatibleDeclaredStyledComponentsVersionRange?: BuildStudioEventListener["onIncompatibleDeclaredStyledComponentsVersionRange"];
165
+ onIncompatibleInstalledStyledComponentsVersionRange?: BuildStudioEventListener["onIncompatibleInstalledStyledComponentsVersionRange"];
166
+ onInvalidStyledComponentsVersionRange?: BuildStudioEventListener["onInvalidStyledComponentsVersionRange"];
167
+ onNoDeclaredStyledComponentsVersion?: BuildStudioEventListener["onNoDeclaredStyledComponentsVersion"];
168
+ onNoInstalledSanityVersion?: BuildStudioEventListener["onNoInstalledSanityVersion"];
169
+ onNoInstalledStyledComponentsVersion?: BuildStudioEventListener["onNoInstalledStyledComponentsVersion"];
131
170
  }
132
171
 
133
172
  declare interface CheckResult {
@@ -224,6 +263,8 @@ export declare function getViteConfig(
224
263
  options: ViteOptions,
225
264
  ): Promise<InlineConfig>;
226
265
 
266
+ declare type MessageFunc = ({ message }: { message: string }) => void;
267
+
227
268
  /**
228
269
  * Resolves vendor package entry points and metadata for a combined studio/app build.
229
270
  * Does not run a build — callers add `entries` to the main Vite/Rolldown input and
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/_exports/_internal/build.ts"],"sourcesContent":["export {buildApp} from '../../actions/build/buildApp.js'\nexport {buildStaticFiles} from '../../actions/build/buildStaticFiles.js'\nexport {buildStudio} from '../../actions/build/buildStudio.js'\nexport {checkRequiredDependencies} from '../../actions/build/checkRequiredDependencies.js'\nexport {checkStudioDependencyVersions} from '../../actions/build/checkStudioDependencyVersions.js'\nexport {extendViteConfigWithUserConfig, getViteConfig} from '../../actions/build/getViteConfig.js'\nexport {resolveVendorBuildConfig} from '../../actions/build/resolveVendorBuildConfig.js'\nexport {writeSanityRuntime} from '../../actions/build/writeSanityRuntime.js'\nexport {SANITY_CACHE_DIR} from '../../constants.js'\nexport {\n compareDependencyVersions,\n type CompareDependencyVersions,\n type CompareDependencyVersionsResult,\n type UnresolvedPrerelease,\n} from '../../util/compareDependencyVersions.js'\n"],"names":["buildApp","buildStaticFiles","buildStudio","checkRequiredDependencies","checkStudioDependencyVersions","extendViteConfigWithUserConfig","getViteConfig","resolveVendorBuildConfig","writeSanityRuntime","SANITY_CACHE_DIR","compareDependencyVersions"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,kCAAiC;AACxD,SAAQC,gBAAgB,QAAO,0CAAyC;AACxE,SAAQC,WAAW,QAAO,qCAAoC;AAC9D,SAAQC,yBAAyB,QAAO,mDAAkD;AAC1F,SAAQC,6BAA6B,QAAO,uDAAsD;AAClG,SAAQC,8BAA8B,EAAEC,aAAa,QAAO,uCAAsC;AAClG,SAAQC,wBAAwB,QAAO,kDAAiD;AACxF,SAAQC,kBAAkB,QAAO,4CAA2C;AAC5E,SAAQC,gBAAgB,QAAO,qBAAoB;AACnD,SACEC,yBAAyB,QAIpB,0CAAyC"}
1
+ {"version":3,"sources":["../../../src/_exports/_internal/build.ts"],"sourcesContent":["export {buildApp, type BuildAppEventListener} from '../../actions/build/buildApp.js'\nexport {buildStaticFiles} from '../../actions/build/buildStaticFiles.js'\nexport {buildStudio, type BuildStudioEventListener} from '../../actions/build/buildStudio.js'\nexport {checkRequiredDependencies} from '../../actions/build/checkRequiredDependencies.js'\nexport {checkStudioDependencyVersions} from '../../actions/build/checkStudioDependencyVersions.js'\nexport {extendViteConfigWithUserConfig, getViteConfig} from '../../actions/build/getViteConfig.js'\nexport {resolveVendorBuildConfig} from '../../actions/build/resolveVendorBuildConfig.js'\nexport {writeSanityRuntime} from '../../actions/build/writeSanityRuntime.js'\nexport {SANITY_CACHE_DIR} from '../../constants.js'\nexport {\n compareDependencyVersions,\n type CompareDependencyVersions,\n type CompareDependencyVersionsResult,\n type UnresolvedPrerelease,\n} from '../../util/compareDependencyVersions.js'\n"],"names":["buildApp","buildStaticFiles","buildStudio","checkRequiredDependencies","checkStudioDependencyVersions","extendViteConfigWithUserConfig","getViteConfig","resolveVendorBuildConfig","writeSanityRuntime","SANITY_CACHE_DIR","compareDependencyVersions"],"mappings":"AAAA,SAAQA,QAAQ,QAAmC,kCAAiC;AACpF,SAAQC,gBAAgB,QAAO,0CAAyC;AACxE,SAAQC,WAAW,QAAsC,qCAAoC;AAC7F,SAAQC,yBAAyB,QAAO,mDAAkD;AAC1F,SAAQC,6BAA6B,QAAO,uDAAsD;AAClG,SAAQC,8BAA8B,EAAEC,aAAa,QAAO,uCAAsC;AAClG,SAAQC,wBAAwB,QAAO,kDAAiD;AACxF,SAAQC,kBAAkB,QAAO,4CAA2C;AAC5E,SAAQC,gBAAgB,QAAO,qBAAoB;AACnD,SACEC,yBAAyB,QAIpB,0CAAyC"}
@@ -19,7 +19,7 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
19
19
  * @param options - options for the build
20
20
  */ export async function buildApp(options) {
21
21
  buildDebug(`Building app`);
22
- const { appId, determineBasePath, outDir, output, workDir } = options;
22
+ const { appId, determineBasePath, eventListener, outDir, output, workDir } = options;
23
23
  let { autoUpdatesEnabled } = options;
24
24
  const unattendedMode = options.unattendedMode;
25
25
  const timer = getTimer();
@@ -76,7 +76,8 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
76
76
  const { mismatched, unresolvedPrerelease } = await options.compareDependencyVersions(autoUpdatedPackages);
77
77
  if (unresolvedPrerelease.length > 0) {
78
78
  await handlePrereleaseVersions({
79
- output,
79
+ onPreReleaseInInteractiveAutoUpdate: eventListener.onPreReleaseInInteractiveAutoUpdate,
80
+ onPreReleaseInNonInteractiveAutoUpdate: eventListener.onPreReleaseInNonInteractiveAutoUpdate,
80
81
  unattendedMode,
81
82
  unresolvedPrerelease
82
83
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/buildApp.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {getLocalPackageVersion} from '@sanity/cli-core/package-manager'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type Output, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isInteractive} from '@sanity/cli-core/util'\nimport {confirm, getTimer, logSymbols, spinner, type SpinnerInstance} from '@sanity/cli-core/ux'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {parse as semverParse} from 'semver'\n\nimport {AppBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {CompareDependencyVersionsResult} from '../../util/compareDependencyVersions.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getAppEnvironmentVariables} from './getEnvironmentVariables.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {resolveVendorBuildConfig} from './resolveVendorBuildConfig.js'\n\nexport interface BuildOptions {\n appId: string | undefined\n appTitle: string | undefined\n autoUpdatesEnabled: boolean\n checkAppId: () => void\n compareDependencyVersions: (\n packages: {name: string; version: string}[],\n ) => Promise<CompareDependencyVersionsResult>\n determineBasePath: () => string\n entry: string | undefined\n isWorkbenchApp: boolean\n minify: boolean\n outDir: string | undefined\n output: Output\n reactCompiler: CliConfig['reactCompiler']\n schemaExtraction: CliConfig['schemaExtraction']\n sourceMap: boolean\n stats: boolean\n unattendedMode: boolean\n vite: UserViteConfig | undefined\n workDir: string\n\n exposes?: WorkbenchExposes\n\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Internal build app that avoids depending on flags for CLI config.\n * @param options - options for the build\n */\nexport async function buildApp(options: BuildOptions): Promise<void> {\n buildDebug(`Building app`)\n\n const {appId, determineBasePath, outDir, output, workDir} = options\n let {autoUpdatesEnabled} = options\n const unattendedMode = options.unattendedMode\n\n const timer = getTimer()\n\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n const installedSdkVersion = await getLocalPackageVersion('@sanity/sdk-react', workDir)\n const installedSanityVersion = await getLocalPackageVersion('sanity', workDir)\n\n if (!installedSdkVersion) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {exit: 1})\n return\n }\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSDKVersion = semverParse(installedSdkVersion)?.version\n if (!cleanSDKVersion) {\n output.error(`Failed to parse installed SDK version: ${installedSdkVersion}`, {exit: 1})\n return\n }\n\n // Sanity might not be installed, but if it is, we want to auto update it.\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n\n const autoUpdatedPackages = [\n {name: '@sanity/sdk', version: cleanSDKVersion},\n {name: '@sanity/sdk-react', version: cleanSDKVersion},\n ...(cleanSanityVersion\n ? [{cssFile: 'index.css', name: 'sanity' as const, version: cleanSanityVersion}]\n : []),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(autoUpdatedPackages, {appId})\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(autoUpdatedPackages, {appId})\n\n output.log(`${logSymbols.info} Building with auto-updates enabled`)\n\n // Warn if auto updates enabled but no appId configured.\n options.checkAppId()\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} =\n await options.compareDependencyVersions(autoUpdatedPackages)\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({output, unattendedMode, unresolvedPrerelease})\n autoUpdatesImports = {}\n autoUpdatesCssUrls = []\n autoUpdatesEnabled = false\n }\n\n if (mismatched.length > 0 && autoUpdatesEnabled) {\n const versionMismatchWarning =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you test locally with the same versions before deploying. \\n\\n` +\n `${mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}`\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const shouldContinue = await confirm({\n default: false,\n message: styleText('yellow', `${versionMismatchWarning} \\n\\nContinue anyway?`),\n })\n\n if (!shouldContinue) {\n output.error('Declined to continue with build', {exit: 1})\n return\n }\n } else {\n // if non-interactive or unattended, just show the warning\n output.warn(versionMismatchWarning)\n }\n }\n }\n\n const envVarKeys = Object.keys(getAppEnvironmentVariables())\n if (envVarKeys.length > 0) {\n output.log('\\nIncluding the following environment variables as part of the JavaScript bundle:')\n for (const key of envVarKeys) output.log(`- ${key}`)\n output.log('')\n }\n\n let shouldClean = true\n if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {\n shouldClean = await confirm({\n default: true,\n message: `Do you want to delete the existing directory (${outputDir}) first?`,\n })\n }\n\n const basePath = determineBasePath()\n\n let spin: SpinnerInstance\n if (shouldClean) {\n timer.start('cleanOutputFolder')\n spin = spinner('Clean output folder').start()\n await rm(outputDir, {force: true, recursive: true})\n const cleanDuration = timer.end('cleanOutputFolder')\n spin.text = `Clean output folder (${cleanDuration.toFixed(0)}ms)`\n spin.succeed()\n }\n\n spin = spinner(`Building Sanity application`).start()\n\n const trace = getCliTelemetry().trace(AppBuildTrace)\n trace.start()\n\n let autoUpdates\n if (autoUpdatesEnabled && !options.isWorkbenchApp) {\n autoUpdates = {\n cssUrls: autoUpdatesCssUrls,\n imports: autoUpdatesImports,\n vendor: await resolveVendorBuildConfig({cwd: workDir, isApp: true}),\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n appTitle: options.appTitle,\n autoUpdates,\n basePath,\n cwd: workDir,\n entry: options.entry,\n exposes: options.exposes,\n isApp: true,\n isWorkbenchApp: options.isWorkbenchApp,\n minify: options.minify,\n outputDir,\n reactCompiler: options.reactCompiler,\n schemaExtraction: options.schemaExtraction,\n sourceMap: options.sourceMap,\n vite: options.vite,\n workbenchAppId: options.workbenchAppId,\n })\n\n trace.log({\n outputSize: bundle.chunks\n .flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength))\n .reduce((sum, n) => sum + n, 0),\n })\n const buildDuration = timer.end('bundleStudio')\n\n spin.text = `Build Sanity application (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n if (options.stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n\n trace.complete()\n } catch (error) {\n spin.fail()\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity application`, {error})\n output.error(`Failed to build Sanity application: ${message}`, {exit: 1})\n }\n}\n"],"names":["rm","path","styleText","getLocalPackageVersion","getCliTelemetry","isInteractive","confirm","getTimer","logSymbols","spinner","parse","semverParse","AppBuildTrace","formatModuleSizes","sortModulesBySize","buildDebug","buildStaticFiles","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getAppEnvironmentVariables","handlePrereleaseVersions","resolveVendorBuildConfig","buildApp","options","appId","determineBasePath","outDir","output","workDir","autoUpdatesEnabled","unattendedMode","timer","defaultOutputDir","resolve","join","outputDir","installedSdkVersion","installedSanityVersion","error","exit","autoUpdatesImports","autoUpdatesCssUrls","cleanSDKVersion","version","cleanSanityVersion","autoUpdatedPackages","name","cssFile","log","info","checkAppId","mismatched","unresolvedPrerelease","compareDependencyVersions","length","versionMismatchWarning","map","mod","pkg","installed","remote","shouldContinue","default","message","warn","envVarKeys","Object","keys","key","shouldClean","basePath","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","autoUpdates","isWorkbenchApp","cssUrls","imports","vendor","cwd","isApp","bundle","appTitle","entry","exposes","minify","reactCompiler","schemaExtraction","sourceMap","vite","workbenchAppId","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","stats","slice","complete","fail","Error","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,sBAAsB,QAAO,mCAAkC;AACvE,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,aAAa,QAAO,wBAAuB;AACnD,SAAQC,OAAO,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,OAAO,QAA6B,sBAAqB;AAEhG,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,aAAa,QAAO,qCAAoC;AAEhE,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,qBAAqB,EAAEC,uBAAuB,QAAO,+BAA8B;AAC3F,SAAQC,0BAA0B,QAAO,+BAA8B;AACvE,SAAQC,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QsE,aAAa;YACpCC,kBAAkBvE,QAAQuE,gBAAgB;YAC1CC,WAAWxE,QAAQwE,SAAS;YAC5BC,MAAMzE,QAAQyE,IAAI;YAClBC,gBAAgB1E,QAAQ0E,cAAc;QACxC;QAEAjB,MAAMhC,GAAG,CAAC;YACRkD,YAAYV,OAAOW,MAAM,CACtBC,OAAO,CAAC,CAACC,QAAUA,MAAMC,OAAO,CAACF,OAAO,CAAC,CAAC3C,MAAQA,IAAI8C,cAAc,GACpEC,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,GAAG;QACjC;QACA,MAAMC,gBAAgB5E,MAAM6C,GAAG,CAAC;QAEhCL,KAAKM,IAAI,GAAG,CAAC,0BAA0B,EAAE8B,cAAc7B,OAAO,CAAC,GAAG,GAAG,CAAC;QACtEP,KAAKQ,OAAO;QAEZ,IAAIxD,QAAQqF,KAAK,EAAE;YACjBjF,OAAOqB,GAAG,CAAC;YACXrB,OAAOqB,GAAG,CAACnC,kBAAkBC,kBAAkB0E,OAAOW,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;QAEA7B,MAAM8B,QAAQ;IAChB,EAAE,OAAOxE,OAAO;QACdiC,KAAKwC,IAAI;QACT/B,MAAM1C,KAAK,CAACA;QACZ,MAAMyB,UAAUzB,iBAAiB0E,QAAQ1E,MAAMyB,OAAO,GAAGkD,OAAO3E;QAChEvB,WAAW,CAAC,kCAAkC,CAAC,EAAE;YAACuB;QAAK;QACvDX,OAAOW,KAAK,CAAC,CAAC,oCAAoC,EAAEyB,SAAS,EAAE;YAACxB,MAAM;QAAC;IACzE;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/build/buildApp.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {getLocalPackageVersion} from '@sanity/cli-core/package-manager'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type Output, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isInteractive} from '@sanity/cli-core/util'\nimport {confirm, getTimer, logSymbols, spinner, type SpinnerInstance} from '@sanity/cli-core/ux'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {parse as semverParse} from 'semver'\n\nimport {AppBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {CompareDependencyVersionsResult} from '../../util/compareDependencyVersions.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {BuildEventListener} from './eventListener.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getAppEnvironmentVariables} from './getEnvironmentVariables.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {resolveVendorBuildConfig} from './resolveVendorBuildConfig.js'\n\nexport type BuildAppEventListener = BuildEventListener\nexport interface BuildOptions {\n appId: string | undefined\n appTitle: string | undefined\n autoUpdatesEnabled: boolean\n checkAppId: () => void\n compareDependencyVersions: (\n packages: {name: string; version: string}[],\n ) => Promise<CompareDependencyVersionsResult>\n determineBasePath: () => string\n entry: string | undefined\n eventListener: Partial<BuildAppEventListener>\n isWorkbenchApp: boolean\n minify: boolean\n outDir: string | undefined\n output: Output\n reactCompiler: CliConfig['reactCompiler']\n schemaExtraction: CliConfig['schemaExtraction']\n sourceMap: boolean\n stats: boolean\n unattendedMode: boolean\n vite: UserViteConfig | undefined\n workDir: string\n\n exposes?: WorkbenchExposes\n\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Internal build app that avoids depending on flags for CLI config.\n * @param options - options for the build\n */\nexport async function buildApp(options: BuildOptions): Promise<void> {\n buildDebug(`Building app`)\n\n const {appId, determineBasePath, eventListener, outDir, output, workDir} = options\n let {autoUpdatesEnabled} = options\n const unattendedMode = options.unattendedMode\n\n const timer = getTimer()\n\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n const installedSdkVersion = await getLocalPackageVersion('@sanity/sdk-react', workDir)\n const installedSanityVersion = await getLocalPackageVersion('sanity', workDir)\n\n if (!installedSdkVersion) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {exit: 1})\n return\n }\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSDKVersion = semverParse(installedSdkVersion)?.version\n if (!cleanSDKVersion) {\n output.error(`Failed to parse installed SDK version: ${installedSdkVersion}`, {exit: 1})\n return\n }\n\n // Sanity might not be installed, but if it is, we want to auto update it.\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n\n const autoUpdatedPackages = [\n {name: '@sanity/sdk', version: cleanSDKVersion},\n {name: '@sanity/sdk-react', version: cleanSDKVersion},\n ...(cleanSanityVersion\n ? [{cssFile: 'index.css', name: 'sanity' as const, version: cleanSanityVersion}]\n : []),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(autoUpdatedPackages, {appId})\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(autoUpdatedPackages, {appId})\n\n output.log(`${logSymbols.info} Building with auto-updates enabled`)\n\n // Warn if auto updates enabled but no appId configured.\n options.checkAppId()\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} =\n await options.compareDependencyVersions(autoUpdatedPackages)\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({\n onPreReleaseInInteractiveAutoUpdate: eventListener.onPreReleaseInInteractiveAutoUpdate,\n onPreReleaseInNonInteractiveAutoUpdate:\n eventListener.onPreReleaseInNonInteractiveAutoUpdate,\n unattendedMode,\n unresolvedPrerelease,\n })\n autoUpdatesImports = {}\n autoUpdatesCssUrls = []\n autoUpdatesEnabled = false\n }\n\n if (mismatched.length > 0 && autoUpdatesEnabled) {\n const versionMismatchWarning =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you test locally with the same versions before deploying. \\n\\n` +\n `${mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}`\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const shouldContinue = await confirm({\n default: false,\n message: styleText('yellow', `${versionMismatchWarning} \\n\\nContinue anyway?`),\n })\n\n if (!shouldContinue) {\n output.error('Declined to continue with build', {exit: 1})\n return\n }\n } else {\n // if non-interactive or unattended, just show the warning\n output.warn(versionMismatchWarning)\n }\n }\n }\n\n const envVarKeys = Object.keys(getAppEnvironmentVariables())\n if (envVarKeys.length > 0) {\n output.log('\\nIncluding the following environment variables as part of the JavaScript bundle:')\n for (const key of envVarKeys) output.log(`- ${key}`)\n output.log('')\n }\n\n let shouldClean = true\n if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {\n shouldClean = await confirm({\n default: true,\n message: `Do you want to delete the existing directory (${outputDir}) first?`,\n })\n }\n\n const basePath = determineBasePath()\n\n let spin: SpinnerInstance\n if (shouldClean) {\n timer.start('cleanOutputFolder')\n spin = spinner('Clean output folder').start()\n await rm(outputDir, {force: true, recursive: true})\n const cleanDuration = timer.end('cleanOutputFolder')\n spin.text = `Clean output folder (${cleanDuration.toFixed(0)}ms)`\n spin.succeed()\n }\n\n spin = spinner(`Building Sanity application`).start()\n\n const trace = getCliTelemetry().trace(AppBuildTrace)\n trace.start()\n\n let autoUpdates\n if (autoUpdatesEnabled && !options.isWorkbenchApp) {\n autoUpdates = {\n cssUrls: autoUpdatesCssUrls,\n imports: autoUpdatesImports,\n vendor: await resolveVendorBuildConfig({cwd: workDir, isApp: true}),\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n appTitle: options.appTitle,\n autoUpdates,\n basePath,\n cwd: workDir,\n entry: options.entry,\n exposes: options.exposes,\n isApp: true,\n isWorkbenchApp: options.isWorkbenchApp,\n minify: options.minify,\n outputDir,\n reactCompiler: options.reactCompiler,\n schemaExtraction: options.schemaExtraction,\n sourceMap: options.sourceMap,\n vite: options.vite,\n workbenchAppId: options.workbenchAppId,\n })\n\n trace.log({\n outputSize: bundle.chunks\n .flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength))\n .reduce((sum, n) => sum + n, 0),\n })\n const buildDuration = timer.end('bundleStudio')\n\n spin.text = `Build Sanity application (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n if (options.stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n\n trace.complete()\n } catch (error) {\n spin.fail()\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity application`, {error})\n output.error(`Failed to build Sanity application: ${message}`, {exit: 1})\n }\n}\n"],"names":["rm","path","styleText","getLocalPackageVersion","getCliTelemetry","isInteractive","confirm","getTimer","logSymbols","spinner","parse","semverParse","AppBuildTrace","formatModuleSizes","sortModulesBySize","buildDebug","buildStaticFiles","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getAppEnvironmentVariables","handlePrereleaseVersions","resolveVendorBuildConfig","buildApp","options","appId","determineBasePath","eventListener","outDir","output","workDir","autoUpdatesEnabled","unattendedMode","timer","defaultOutputDir","resolve","join","outputDir","installedSdkVersion","installedSanityVersion","error","exit","autoUpdatesImports","autoUpdatesCssUrls","cleanSDKVersion","version","cleanSanityVersion","autoUpdatedPackages","name","cssFile","log","info","checkAppId","mismatched","unresolvedPrerelease","compareDependencyVersions","length","onPreReleaseInInteractiveAutoUpdate","onPreReleaseInNonInteractiveAutoUpdate","versionMismatchWarning","map","mod","pkg","installed","remote","shouldContinue","default","message","warn","envVarKeys","Object","keys","key","shouldClean","basePath","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","autoUpdates","isWorkbenchApp","cssUrls","imports","vendor","cwd","isApp","bundle","appTitle","entry","exposes","minify","reactCompiler","schemaExtraction","sourceMap","vite","workbenchAppId","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","stats","slice","complete","fail","Error","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,sBAAsB,QAAO,mCAAkC;AACvE,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,aAAa,QAAO,wBAAuB;AACnD,SAAQC,OAAO,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,OAAO,QAA6B,sBAAqB;AAEhG,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,aAAa,QAAO,qCAAoC;AAEhE,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AAEtD,SAAQC,qBAAqB,EAAEC,uBAAuB,QAAO,+BAA8B;AAC3F,SAAQC,0BAA0B,QAAO,+BAA8B;AACvE,SAAQC,wBAAwB,QAAO,gCAA+B;AACtE,SAAQC,wBAAwB,QAAO,gCAA+B;AAgCtE;;;CAGC,GACD,OAAO,eAAeC,SAASC,OAAqB;IAClDR,WAAW,CAAC,YAAY,CAAC;IAEzB,MAAM,EAACS,KAAK,EAAEC,iBAAiB,EAAEC,aAAa,EAAEC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAC,GAAGN;IAC3E,IAAI,EAACO,kBAAkB,EAAC,GAAGP;IAC3B,MAAMQ,iBAAiBR,QAAQQ,cAAc;IAE7C,MAAMC,QAAQzB;IAEd,MAAM0B,mBAAmBhC,KAAKiC,OAAO,CAACjC,KAAKkC,IAAI,CAACN,SAAS;IACzD,MAAMO,YAAYnC,KAAKiC,OAAO,CAACP,UAAUM;IAEzC,MAAMI,sBAAsB,MAAMlC,uBAAuB,qBAAqB0B;IAC9E,MAA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c7B,OAAO,CAAC,GAAG,GAAG,CAAC;QACtEP,KAAKQ,OAAO;QAEZ,IAAI3D,QAAQwF,KAAK,EAAE;YACjBnF,OAAOqB,GAAG,CAAC;YACXrB,OAAOqB,GAAG,CAACpC,kBAAkBC,kBAAkB6E,OAAOW,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;QAEA7B,MAAM8B,QAAQ;IAChB,EAAE,OAAO1E,OAAO;QACdmC,KAAKwC,IAAI;QACT/B,MAAM5C,KAAK,CAACA;QACZ,MAAM2B,UAAU3B,iBAAiB4E,QAAQ5E,MAAM2B,OAAO,GAAGkD,OAAO7E;QAChExB,WAAW,CAAC,kCAAkC,CAAC,EAAE;YAACwB;QAAK;QACvDX,OAAOW,KAAK,CAAC,CAAC,oCAAoC,EAAE2B,SAAS,EAAE;YAAC1B,MAAM;QAAC;IACzE;AACF"}
@@ -1,10 +1,9 @@
1
1
  import { rm } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { styleText } from 'node:util';
4
3
  import { getLocalPackageVersion } from '@sanity/cli-core/package-manager';
5
4
  import { getCliTelemetry } from '@sanity/cli-core/telemetry';
6
5
  import { isInteractive } from '@sanity/cli-core/util';
7
- import { confirm, getTimer, logSymbols, select, spinner } from '@sanity/cli-core/ux';
6
+ import { getTimer, logSymbols } from '@sanity/cli-core/ux';
8
7
  import { parse as semverParse } from 'semver';
9
8
  import { StudioBuildTrace } from '../../telemetry/build.telemetry.js';
10
9
  import { formatModuleSizes, sortModulesBySize } from '../../util/moduleFormatUtils.js';
@@ -22,7 +21,7 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
22
21
  */ export async function buildStudio(options) {
23
22
  buildDebug(`Building studio`);
24
23
  const timer = getTimer();
25
- const { appId, determineBasePath, exposes, isApp, minify, outDir, output, reactCompiler, schemaExtraction, sourceMap, stats, unattendedMode, upgradePackages, vite, workDir } = options;
24
+ const { appId, determineBasePath, eventListener, exposes, isApp, minify, outDir, output, reactCompiler, schemaExtraction, sourceMap, stats, unattendedMode, vite, workDir } = options;
26
25
  const defaultOutputDir = path.resolve(path.join(workDir, 'dist'));
27
26
  const outputDir = path.resolve(outDir || defaultOutputDir);
28
27
  await checkStudioDependencyVersions(workDir, output);
@@ -30,8 +29,8 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
30
29
  // thus we want to exit early
31
30
  const { installedSanityVersion } = await checkRequiredDependencies({
32
31
  isApp,
33
- output,
34
- workDir
32
+ workDir,
33
+ ...eventListener
35
34
  });
36
35
  let autoUpdatesEnabled = options.autoUpdatesEnabled;
37
36
  let autoUpdatesImports = {};
@@ -76,9 +75,9 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
76
75
  const { mismatched, unresolvedPrerelease } = await options.compareDependencyVersions(sanityDependencies);
77
76
  if (unresolvedPrerelease.length > 0) {
78
77
  await handlePrereleaseVersions({
79
- output,
80
78
  unattendedMode,
81
- unresolvedPrerelease
79
+ unresolvedPrerelease,
80
+ ...eventListener
82
81
  });
83
82
  autoUpdatesImports = {};
84
83
  autoUpdatesCssUrls = [];
@@ -86,50 +85,21 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
86
85
  }
87
86
  if (mismatched.length > 0 && autoUpdatesEnabled) {
88
87
  const versionMismatchWarning = `The following local package versions are different from the versions currently served at runtime.\n` + `When using auto updates, we recommend that you test locally with the same versions before deploying. \n\n` + `${mismatched.map((mod)=>` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\n')}`;
88
+ const { onVersionMismatchInInteractiveAutoUpdate = ()=>({
89
+ stopBuild: true
90
+ }), onVersionMismatchInNonInteractiveAutoUpdate = ()=>{} } = eventListener;
89
91
  // If it is non-interactive or in unattended mode, we don't want to prompt
90
92
  if (isInteractive() && !unattendedMode) {
91
- const choice = await select({
92
- choices: [
93
- {
94
- name: `Upgrade local versions (recommended). You will need to run the build command again`,
95
- value: 'upgrade'
96
- },
97
- {
98
- name: `Upgrade and proceed with build`,
99
- value: 'upgrade-and-proceed'
100
- },
101
- {
102
- name: `Continue anyway`,
103
- value: 'continue'
104
- },
105
- {
106
- name: 'Cancel',
107
- value: 'cancel'
108
- }
109
- ],
110
- default: 'upgrade',
111
- message: styleText('yellow', `${logSymbols.warning} ${versionMismatchWarning}\n\nDo you want to upgrade local versions before deploying?`)
93
+ const { stopBuild } = await onVersionMismatchInInteractiveAutoUpdate({
94
+ mismatched,
95
+ versionMismatchWarning
112
96
  });
113
- if (choice === 'cancel') {
114
- output.error('Declined to continue with build', {
115
- exit: 1
116
- });
117
- return;
118
- }
119
- if (choice === 'upgrade' || choice === 'upgrade-and-proceed') {
120
- await upgradePackages({
121
- packages: mismatched.map((res)=>[
122
- res.pkg,
123
- res.remote
124
- ])
125
- });
126
- if (choice === 'upgrade') {
127
- return;
128
- }
129
- }
97
+ if (stopBuild) return;
130
98
  } else {
131
99
  // if non-interactive or unattended, just show the warning
132
- output.warn(versionMismatchWarning);
100
+ onVersionMismatchInNonInteractiveAutoUpdate({
101
+ versionMismatchWarning
102
+ });
133
103
  }
134
104
  }
135
105
  }
@@ -143,29 +113,37 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
143
113
  }
144
114
  let shouldClean = true;
145
115
  if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {
146
- shouldClean = await confirm({
147
- default: true,
116
+ const { onInteractiveNonDefaultOutputDir = ()=>({
117
+ shouldClean: true
118
+ }) } = eventListener;
119
+ ({ shouldClean } = await onInteractiveNonDefaultOutputDir({
148
120
  message: `Do you want to delete the existing directory (${outputDir}) first?`
149
- });
121
+ }));
150
122
  }
151
123
  // Determine base path for built studio
152
124
  const basePath = determineBasePath();
153
125
  if (schemaExtraction?.enabled) {
154
126
  output.log(`${logSymbols.info} Building with schema extraction enabled`);
155
127
  }
156
- let spin;
157
128
  if (shouldClean) {
129
+ const { onCleanOutputDirEnd = ()=>{}, onCleanOutputDirStart = ()=>{} } = eventListener;
158
130
  timer.start('cleanOutputFolder');
159
- spin = spinner('Clean output folder').start();
131
+ onCleanOutputDirStart({
132
+ message: 'Clean output folder'
133
+ });
160
134
  await rm(outputDir, {
161
135
  force: true,
162
136
  recursive: true
163
137
  });
164
138
  const cleanDuration = timer.end('cleanOutputFolder');
165
- spin.text = `Clean output folder (${cleanDuration.toFixed(0)}ms)`;
166
- spin.succeed();
139
+ onCleanOutputDirEnd({
140
+ message: `Clean output folder (${cleanDuration.toFixed(0)}ms)`
141
+ });
167
142
  }
168
- spin = spinner(`Build Sanity Studio`).start();
143
+ const { onBuildEnd = ()=>{}, onBuildFail = ()=>{}, onBuildStart = ()=>{} } = eventListener;
144
+ onBuildStart({
145
+ message: `Build Sanity Studio`
146
+ });
169
147
  const trace = getCliTelemetry().trace(StudioBuildTrace);
170
148
  trace.start();
171
149
  let autoUpdates;
@@ -199,23 +177,24 @@ import { resolveVendorBuildConfig } from './resolveVendorBuildConfig.js';
199
177
  outputSize: bundle.chunks.flatMap((chunk)=>chunk.modules.flatMap((mod)=>mod.renderedLength)).reduce((sum, n)=>sum + n, 0)
200
178
  });
201
179
  const buildDuration = timer.end('bundleStudio');
202
- spin.text = `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`;
203
- spin.succeed();
180
+ onBuildEnd({
181
+ message: `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`
182
+ });
204
183
  trace.complete();
205
184
  if (stats) {
206
185
  output.log('\nLargest module files:');
207
186
  output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)));
208
187
  }
209
188
  } catch (error) {
210
- spin.fail();
211
189
  trace.error(error);
212
190
  const message = error instanceof Error ? error.message : String(error);
213
191
  buildDebug(`Failed to build Sanity Studio`, {
214
192
  error
215
193
  });
216
- output.error(`Failed to build Sanity Studio: ${message}`, {
217
- exit: 1
194
+ onBuildFail({
195
+ message: `Failed to build Sanity Studio: ${message}`
218
196
  });
197
+ return;
219
198
  }
220
199
  }
221
200
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/buildStudio.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {getLocalPackageVersion} from '@sanity/cli-core/package-manager'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type Output, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isInteractive} from '@sanity/cli-core/util'\nimport {\n confirm,\n getTimer,\n logSymbols,\n select,\n spinner,\n type SpinnerInstance,\n} from '@sanity/cli-core/ux'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {parse as semverParse} from 'semver'\n\nimport {StudioBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {CompareDependencyVersionsResult} from '../../util/compareDependencyVersions.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {checkRequiredDependencies} from './checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from './checkStudioDependencyVersions.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getStudioEnvironmentVariables} from './getEnvironmentVariables.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {resolveVendorBuildConfig} from './resolveVendorBuildConfig.js'\n\nexport interface BuildOptions {\n appId: string | undefined\n autoUpdatesEnabled: boolean\n checkAppId: () => void\n compareDependencyVersions: (\n packages: {name: string; version: string}[],\n ) => Promise<CompareDependencyVersionsResult>\n determineBasePath: () => string\n isApp: boolean\n isWorkbenchApp: boolean\n minify: boolean\n outDir: string | undefined\n output: Output\n reactCompiler: boolean | CliConfig['reactCompiler'] | undefined\n schemaExtraction: CliConfig['schemaExtraction']\n sourceMap: boolean\n stats: boolean\n unattendedMode: boolean\n upgradePackages(options: {packages: [name: string, version: string][]}): Promise<void>\n vite: UserViteConfig | undefined\n workDir: string\n\n exposes?: WorkbenchExposes\n\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Internal build studio that avoids depending on flags for CLI config.\n * @param options - options for the build\n */\nexport async function buildStudio(options: BuildOptions): Promise<void> {\n buildDebug(`Building studio`)\n\n const timer = getTimer()\n const {\n appId,\n determineBasePath,\n exposes,\n isApp,\n minify,\n outDir,\n output,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n stats,\n unattendedMode,\n upgradePackages,\n vite,\n workDir,\n } = options\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n await checkStudioDependencyVersions(workDir, output)\n\n // If the check resulted in a dependency install, the CLI command will be re-run,\n // thus we want to exit early\n const {installedSanityVersion} = await checkRequiredDependencies({\n isApp,\n output,\n workDir,\n })\n\n let autoUpdatesEnabled = options.autoUpdatesEnabled\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n if (!cleanSanityVersion) {\n throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`)\n }\n\n output.log(`${logSymbols.info} Building with auto-updates enabled`)\n\n // Warn if auto updates enabled but no appId configured\n options.checkAppId()\n\n const installedVisionVersion = await getLocalPackageVersion('@sanity/vision', workDir)\n const cleanVisionVersion = installedVisionVersion\n ? semverParse(installedVisionVersion)?.version\n : undefined\n\n const sanityDependencies = [\n {cssFile: 'index.css', name: 'sanity', version: cleanSanityVersion},\n ...(cleanVisionVersion\n ? [{cssFile: 'index.css', name: '@sanity/vision' as const, version: cleanVisionVersion}]\n : [{name: '@sanity/vision' as const, version: cleanSanityVersion}]),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(sanityDependencies, {appId})\n\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(sanityDependencies, {appId})\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} =\n await options.compareDependencyVersions(sanityDependencies)\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({output, unattendedMode, unresolvedPrerelease})\n autoUpdatesImports = {}\n autoUpdatesCssUrls = []\n autoUpdatesEnabled = false\n }\n\n if (mismatched.length > 0 && autoUpdatesEnabled) {\n const versionMismatchWarning =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you test locally with the same versions before deploying. \\n\\n` +\n `${mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}`\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const choice = await select({\n choices: [\n {\n name: `Upgrade local versions (recommended). You will need to run the build command again`,\n value: 'upgrade',\n },\n {\n name: `Upgrade and proceed with build`,\n value: 'upgrade-and-proceed',\n },\n {\n name: `Continue anyway`,\n value: 'continue',\n },\n {name: 'Cancel', value: 'cancel'},\n ],\n default: 'upgrade',\n message: styleText(\n 'yellow',\n `${logSymbols.warning} ${versionMismatchWarning}\\n\\nDo you want to upgrade local versions before deploying?`,\n ),\n })\n\n if (choice === 'cancel') {\n output.error('Declined to continue with build', {exit: 1})\n return\n }\n\n if (choice === 'upgrade' || choice === 'upgrade-and-proceed') {\n await upgradePackages({\n packages: mismatched.map((res) => [res.pkg, res.remote]),\n })\n\n if (choice === 'upgrade') {\n return\n }\n }\n } else {\n // if non-interactive or unattended, just show the warning\n output.warn(versionMismatchWarning)\n }\n }\n }\n\n const envVarKeys = Object.keys(getStudioEnvironmentVariables())\n if (envVarKeys.length > 0) {\n output.log('\\nIncluding the following environment variables as part of the JavaScript bundle:')\n for (const key of envVarKeys) {\n output.log(`- ${key}`)\n }\n output.log('')\n }\n\n let shouldClean = true\n if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {\n shouldClean = await confirm({\n default: true,\n message: `Do you want to delete the existing directory (${outputDir}) first?`,\n })\n }\n\n // Determine base path for built studio\n const basePath = determineBasePath()\n\n if (schemaExtraction?.enabled) {\n output.log(`${logSymbols.info} Building with schema extraction enabled`)\n }\n\n let spin: SpinnerInstance\n if (shouldClean) {\n timer.start('cleanOutputFolder')\n spin = spinner('Clean output folder').start()\n await rm(outputDir, {force: true, recursive: true})\n const cleanDuration = timer.end('cleanOutputFolder')\n spin.text = `Clean output folder (${cleanDuration.toFixed(0)}ms)`\n spin.succeed()\n }\n\n spin = spinner(`Build Sanity Studio`).start()\n\n const trace = getCliTelemetry().trace(StudioBuildTrace)\n trace.start()\n\n let autoUpdates\n if (autoUpdatesEnabled && !options.isWorkbenchApp) {\n autoUpdates = {\n cssUrls: autoUpdatesCssUrls,\n imports: autoUpdatesImports,\n vendor: await resolveVendorBuildConfig({cwd: workDir, isApp: false}),\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n autoUpdates,\n basePath,\n cwd: workDir,\n exposes,\n isWorkbenchApp: options.isWorkbenchApp,\n minify,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n vite,\n workbenchAppId: options.workbenchAppId,\n })\n\n trace.log({\n outputSize: bundle.chunks\n .flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength))\n .reduce((sum, n) => sum + n, 0),\n })\n const buildDuration = timer.end('bundleStudio')\n\n spin.text = `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`\n spin.succeed()\n\n trace.complete()\n if (stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n } catch (error) {\n spin.fail()\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity Studio`, {error})\n output.error(`Failed to build Sanity Studio: ${message}`, {exit: 1})\n }\n}\n"],"names":["rm","path","styleText","getLocalPackageVersion","getCliTelemetry","isInteractive","confirm","getTimer","logSymbols","select","spinner","parse","semverParse","StudioBuildTrace","formatModuleSizes","sortModulesBySize","buildDebug","buildStaticFiles","checkRequiredDependencies","checkStudioDependencyVersions","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getStudioEnvironmentVariables","handlePrereleaseVersions","resolveVendorBuildConfig","buildStudio","options","timer","appId","determineBasePath","exposes","isApp","minify","outDir","output","reactCompiler","schemaExtraction","sourceMap","stats","unattendedMode","upgradePackages","vite","workDir","defaultOutputDir","resolve","join","outputDir","installedSanityVersion","autoUpdatesEnabled","autoUpdatesImports","autoUpdatesCssUrls","cleanSanityVersion","version","Error","log","info","checkAppId","installedVisionVersion","cleanVisionVersion","undefined","sanityDependencies","cssFile","name","mismatched","unresolvedPrerelease","compareDependencyVersions","length","versionMismatchWarning","map","mod","pkg","installed","remote","choice","choices","value","default","message","warning","error","exit","packages","res","warn","envVarKeys","Object","keys","key","shouldClean","basePath","enabled","spin","start","force","recursive","cleanDuration","end","text","toFixed","succeed","trace","autoUpdates","isWorkbenchApp","cssUrls","imports","vendor","cwd","bundle","workbenchAppId","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","complete","slice","fail","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,sBAAsB,QAAO,mCAAkC;AACvE,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,aAAa,QAAO,wBAAuB;AACnD,SACEC,OAAO,EACPC,QAAQ,EACRC,UAAU,EACVC,MAAM,EACNC,OAAO,QAEF,sBAAqB;AAE5B,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,gBAAgB,QAAO,qCAAoC;AAEnE,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,yBAAyB,QAAO,iCAAgC;AACxE,SAAQC,6B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AAK,CAAC,GAAG;QACzE;IACF,EAAE,OAAOzC,OAAO;QACdY,KAAK8B,IAAI;QACTrB,MAAMrB,KAAK,CAACA;QACZ,MAAMF,UAAUE,iBAAiB1B,QAAQ0B,MAAMF,OAAO,GAAG6C,OAAO3C;QAChE/D,WAAW,CAAC,6BAA6B,CAAC,EAAE;YAAC+D;QAAK;QAClD7C,OAAO6C,KAAK,CAAC,CAAC,+BAA+B,EAAEF,SAAS,EAAE;YAACG,MAAM;QAAC;IACpE;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/build/buildStudio.ts"],"sourcesContent":["import {rm} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {getLocalPackageVersion} from '@sanity/cli-core/package-manager'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type Output, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isInteractive} from '@sanity/cli-core/util'\nimport {getTimer, logSymbols} from '@sanity/cli-core/ux'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {parse as semverParse} from 'semver'\n\nimport {StudioBuildTrace} from '../../telemetry/build.telemetry.js'\nimport {\n CompareDependencyVersions,\n CompareDependencyVersionsResult,\n} from '../../util/compareDependencyVersions.js'\nimport {formatModuleSizes, sortModulesBySize} from '../../util/moduleFormatUtils.js'\nimport {buildDebug} from './buildDebug.js'\nimport {buildStaticFiles} from './buildStaticFiles.js'\nimport {checkRequiredDependencies} from './checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from './checkStudioDependencyVersions.js'\nimport {type BuildEventListener, type MessageFunc} from './eventListener.js'\nimport {getAutoUpdatesCssUrls, getAutoUpdatesImportMap} from './getAutoUpdatesImportMap.js'\nimport {getStudioEnvironmentVariables} from './getEnvironmentVariables.js'\nimport {handlePrereleaseVersions} from './handlePrereleaseVersions.js'\nimport {resolveVendorBuildConfig} from './resolveVendorBuildConfig.js'\n\nexport interface BuildStudioEventListener extends BuildEventListener {\n onBuildEnd: MessageFunc\n onBuildFail: MessageFunc\n onBuildStart: MessageFunc\n onCleanOutputDirEnd: MessageFunc\n onCleanOutputDirStart: MessageFunc\n onIncompatibleDeclaredStyledComponentsVersionRange: MessageFunc\n onIncompatibleInstalledStyledComponentsVersionRange: MessageFunc\n onInteractiveNonDefaultOutputDir({message}: {message: string}): Promise<{shouldClean: boolean}>\n onInvalidStyledComponentsVersionRange: MessageFunc\n onNoDeclaredStyledComponentsVersion: MessageFunc\n onNoInstalledSanityVersion: MessageFunc\n onNoInstalledStyledComponentsVersion: MessageFunc\n onVersionMismatchInInteractiveAutoUpdate(params: {\n mismatched: CompareDependencyVersions[]\n versionMismatchWarning: string\n }): Promise<{stopBuild: boolean}>\n onVersionMismatchInNonInteractiveAutoUpdate(params: {versionMismatchWarning: string}): void\n}\n\nexport interface BuildOptions {\n appId: string | undefined\n autoUpdatesEnabled: boolean\n checkAppId: () => void\n compareDependencyVersions: (\n packages: {name: string; version: string}[],\n ) => Promise<CompareDependencyVersionsResult>\n determineBasePath: () => string\n eventListener: Partial<BuildStudioEventListener>\n isApp: boolean\n isWorkbenchApp: boolean\n minify: boolean\n outDir: string | undefined\n output: Output\n reactCompiler: boolean | CliConfig['reactCompiler'] | undefined\n schemaExtraction: CliConfig['schemaExtraction']\n sourceMap: boolean\n stats: boolean\n unattendedMode: boolean\n vite: UserViteConfig | undefined\n workDir: string\n\n exposes?: WorkbenchExposes\n\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Internal build studio that avoids depending on flags for CLI config.\n * @param options - options for the build\n */\nexport async function buildStudio(options: BuildOptions): Promise<void> {\n buildDebug(`Building studio`)\n\n const timer = getTimer()\n const {\n appId,\n determineBasePath,\n eventListener,\n exposes,\n isApp,\n minify,\n outDir,\n output,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n stats,\n unattendedMode,\n vite,\n workDir,\n } = options\n const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))\n const outputDir = path.resolve(outDir || defaultOutputDir)\n\n await checkStudioDependencyVersions(workDir, output)\n\n // If the check resulted in a dependency install, the CLI command will be re-run,\n // thus we want to exit early\n const {installedSanityVersion} = await checkRequiredDependencies({\n isApp,\n workDir,\n\n ...eventListener,\n })\n\n let autoUpdatesEnabled = options.autoUpdatesEnabled\n\n let autoUpdatesImports = {}\n let autoUpdatesCssUrls: string[] = []\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semverParse(installedSanityVersion)?.version\n if (!cleanSanityVersion) {\n throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`)\n }\n\n output.log(`${logSymbols.info} Building with auto-updates enabled`)\n\n // Warn if auto updates enabled but no appId configured\n options.checkAppId()\n\n const installedVisionVersion = await getLocalPackageVersion('@sanity/vision', workDir)\n const cleanVisionVersion = installedVisionVersion\n ? semverParse(installedVisionVersion)?.version\n : undefined\n\n const sanityDependencies = [\n {cssFile: 'index.css', name: 'sanity', version: cleanSanityVersion},\n ...(cleanVisionVersion\n ? [{cssFile: 'index.css', name: '@sanity/vision' as const, version: cleanVisionVersion}]\n : [{name: '@sanity/vision' as const, version: cleanSanityVersion}]),\n ]\n autoUpdatesImports = getAutoUpdatesImportMap(sanityDependencies, {appId})\n\n autoUpdatesCssUrls = getAutoUpdatesCssUrls(sanityDependencies, {appId})\n\n // Check the versions\n const {mismatched, unresolvedPrerelease} =\n await options.compareDependencyVersions(sanityDependencies)\n\n if (unresolvedPrerelease.length > 0) {\n await handlePrereleaseVersions({\n unattendedMode,\n unresolvedPrerelease,\n\n ...eventListener,\n })\n autoUpdatesImports = {}\n autoUpdatesCssUrls = []\n autoUpdatesEnabled = false\n }\n\n if (mismatched.length > 0 && autoUpdatesEnabled) {\n const versionMismatchWarning =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you test locally with the same versions before deploying. \\n\\n` +\n `${mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}`\n\n const {\n onVersionMismatchInInteractiveAutoUpdate = () => ({stopBuild: true}),\n onVersionMismatchInNonInteractiveAutoUpdate = () => {},\n } = eventListener\n\n // If it is non-interactive or in unattended mode, we don't want to prompt\n if (isInteractive() && !unattendedMode) {\n const {stopBuild} = await onVersionMismatchInInteractiveAutoUpdate({\n mismatched,\n versionMismatchWarning,\n })\n if (stopBuild) return\n } else {\n // if non-interactive or unattended, just show the warning\n onVersionMismatchInNonInteractiveAutoUpdate({versionMismatchWarning})\n }\n }\n }\n\n const envVarKeys = Object.keys(getStudioEnvironmentVariables())\n if (envVarKeys.length > 0) {\n output.log('\\nIncluding the following environment variables as part of the JavaScript bundle:')\n for (const key of envVarKeys) {\n output.log(`- ${key}`)\n }\n output.log('')\n }\n\n let shouldClean = true\n if (outputDir !== defaultOutputDir && !unattendedMode && isInteractive()) {\n const {onInteractiveNonDefaultOutputDir = () => ({shouldClean: true})} = eventListener\n ;({shouldClean} = await onInteractiveNonDefaultOutputDir({\n message: `Do you want to delete the existing directory (${outputDir}) first?`,\n }))\n }\n\n // Determine base path for built studio\n const basePath = determineBasePath()\n\n if (schemaExtraction?.enabled) {\n output.log(`${logSymbols.info} Building with schema extraction enabled`)\n }\n\n if (shouldClean) {\n const {onCleanOutputDirEnd = () => {}, onCleanOutputDirStart = () => {}} = eventListener\n timer.start('cleanOutputFolder')\n onCleanOutputDirStart({message: 'Clean output folder'})\n\n await rm(outputDir, {force: true, recursive: true})\n const cleanDuration = timer.end('cleanOutputFolder')\n\n onCleanOutputDirEnd({\n message: `Clean output folder (${cleanDuration.toFixed(0)}ms)`,\n })\n }\n\n const {onBuildEnd = () => {}, onBuildFail = () => {}, onBuildStart = () => {}} = eventListener\n\n onBuildStart({message: `Build Sanity Studio`})\n\n const trace = getCliTelemetry().trace(StudioBuildTrace)\n trace.start()\n\n let autoUpdates\n if (autoUpdatesEnabled && !options.isWorkbenchApp) {\n autoUpdates = {\n cssUrls: autoUpdatesCssUrls,\n imports: autoUpdatesImports,\n vendor: await resolveVendorBuildConfig({cwd: workDir, isApp: false}),\n }\n }\n\n try {\n timer.start('bundleStudio')\n\n const bundle = await buildStaticFiles({\n autoUpdates,\n basePath,\n cwd: workDir,\n exposes,\n isWorkbenchApp: options.isWorkbenchApp,\n minify,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n vite,\n workbenchAppId: options.workbenchAppId,\n })\n\n trace.log({\n outputSize: bundle.chunks\n .flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength))\n .reduce((sum, n) => sum + n, 0),\n })\n const buildDuration = timer.end('bundleStudio')\n\n onBuildEnd({message: `Build Sanity Studio (${buildDuration.toFixed(0)}ms)`})\n\n trace.complete()\n if (stats) {\n output.log('\\nLargest module files:')\n output.log(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))\n }\n } catch (error) {\n trace.error(error)\n const message = error instanceof Error ? error.message : String(error)\n buildDebug(`Failed to build Sanity Studio`, {error})\n onBuildFail({message: `Failed to build Sanity Studio: ${message}`})\n return\n }\n}\n"],"names":["rm","path","getLocalPackageVersion","getCliTelemetry","isInteractive","getTimer","logSymbols","parse","semverParse","StudioBuildTrace","formatModuleSizes","sortModulesBySize","buildDebug","buildStaticFiles","checkRequiredDependencies","checkStudioDependencyVersions","getAutoUpdatesCssUrls","getAutoUpdatesImportMap","getStudioEnvironmentVariables","handlePrereleaseVersions","resolveVendorBuildConfig","buildStudio","options","timer","appId","determineBasePath","eventListener","exposes","isApp","minify","outDir","output","reactCompiler","schemaExtraction","sourceMap","stats","unattendedMode","vite","workDir","defaultOutputDir","resolve","join","outputDir","installedSanityVersion","autoUpdatesEnabled","autoUpdatesImports","autoUpdatesCssUrls","cleanSanityVersion","version","Error","log","info","checkAppId","installedVisionVersion","cleanVisionVersion","undefined","sanityDependencies","cssFile","name","mismatched","unresolvedPrerelease","compareDependencyVersions","length","versionMismatchWarning","map","mod","pkg","installed","remote","onVersionMismatchInInteractiveAutoUpdate","stopBuild","onVersionMismatchInNonInteractiveAutoUpdate","envVarKeys","Object","keys","key","shouldClean","onInteractiveNonDefaultOutputDir","message","basePath","enabled","onCleanOutputDirEnd","onCleanOutputDirStart","start","force","recursive","cleanDuration","end","toFixed","onBuildEnd","onBuildFail","onBuildStart","trace","autoUpdates","isWorkbenchApp","cssUrls","imports","vendor","cwd","bundle","workbenchAppId","outputSize","chunks","flatMap","chunk","modules","renderedLength","reduce","sum","n","buildDuration","complete","slice","error","String"],"mappings":"AAAA,SAAQA,EAAE,QAAO,mBAAkB;AACnC,OAAOC,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,QAAO,mCAAkC;AACvE,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,aAAa,QAAO,wBAAuB;AACnD,SAAQC,QAAQ,EAAEC,UAAU,QAAO,sBAAqB;AAExD,SAAQC,SAASC,WAAW,QAAO,SAAQ;AAE3C,SAAQC,gBAAgB,QAAO,qCAAoC;AAKnE,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,kCAAiC;AACpF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,yBAAyB,QAAO,iCAAgC;AACxE,SAAQC,6BAA6B,QAAO,qCAAoC;AAEhF,SAAQC,qBAAqB,EAAEC,uBAAuB,QAAO,+BAA8B;AAC3F,SAAQC,6BAA6B,QAAO,+BAA8B;AAC1E,SAAQC,wBAAwB,QAAO,gCAA+B;AACtE,SAAQC,wBAAwB,QAAO,gCAA+B;AAkDtE;;;CAGC,GACD,OAAO,eAAeC,YAAYC,OAAqB;IACrDV,WAAW,CAAC,eAAe,CAAC;IAE5B,MAAMW,QAAQlB;IACd,MAAM,EACJmB,KAAK,EACLC,iBAAiB,EACjBC,aAAa,EACbC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,gBAAgB,EAChBC,SAAS,E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AV;YACAC;YACAC;YACAG;YACA+D,gBAAgB9E,QAAQ8E,cAAc;QACxC;QAEAR,MAAM1C,GAAG,CAAC;YACRmD,YAAYF,OAAOG,MAAM,CACtBC,OAAO,CAAC,CAACC,QAAUA,MAAMC,OAAO,CAACF,OAAO,CAAC,CAACtC,MAAQA,IAAIyC,cAAc,GACpEC,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,GAAG;QACjC;QACA,MAAMC,gBAAgBvF,MAAMgE,GAAG,CAAC;QAEhCE,WAAW;YAACX,SAAS,CAAC,qBAAqB,EAAEgC,cAActB,OAAO,CAAC,GAAG,GAAG,CAAC;QAAA;QAE1EI,MAAMmB,QAAQ;QACd,IAAI5E,OAAO;YACTJ,OAAOmB,GAAG,CAAC;YACXnB,OAAOmB,GAAG,CAACxC,kBAAkBC,kBAAkBwF,OAAOG,MAAM,EAAEU,KAAK,CAAC,GAAG;QACzE;IACF,EAAE,OAAOC,OAAO;QACdrB,MAAMqB,KAAK,CAACA;QACZ,MAAMnC,UAAUmC,iBAAiBhE,QAAQgE,MAAMnC,OAAO,GAAGoC,OAAOD;QAChErG,WAAW,CAAC,6BAA6B,CAAC,EAAE;YAACqG;QAAK;QAClDvB,YAAY;YAACZ,SAAS,CAAC,+BAA+B,EAAEA,SAAS;QAAA;QACjE;IACF;AACF"}
@@ -7,6 +7,7 @@ const defaultStudioManifestProps = {
7
7
  version: '1.0.0'
8
8
  };
9
9
  const styledComponentsVersionRange = '^6.1.15';
10
+ const noop = async ()=>{};
10
11
  /**
11
12
  * Checks that the studio has declared and installed the required dependencies
12
13
  * needed by the Sanity modules. While we generally use regular, explicit
@@ -18,7 +19,7 @@ const styledComponentsVersionRange = '^6.1.15';
18
19
  *
19
20
  * Additionally, returns the version of the 'sanity' dependency from the package.json.
20
21
  */ export async function checkRequiredDependencies(options) {
21
- const { isApp, output, workDir: studioPath } = options;
22
+ const { isApp, workDir: studioPath } = options;
22
23
  // currently there's no check needed for core apps,
23
24
  // but this should be removed once they are more mature
24
25
  if (isApp) {
@@ -26,6 +27,7 @@ const styledComponentsVersionRange = '^6.1.15';
26
27
  installedSanityVersion: ''
27
28
  };
28
29
  }
30
+ const { onIncompatibleDeclaredStyledComponentsVersionRange = noop, onIncompatibleInstalledStyledComponentsVersionRange = noop, onInvalidStyledComponentsVersionRange = noop, onNoDeclaredStyledComponentsVersion = noop, onNoInstalledSanityVersion = noop, onNoInstalledStyledComponentsVersion = noop } = options;
29
31
  const [studioPackageManifest, installedStyledComponentsVersion, installedSanityVersion] = await Promise.all([
30
32
  readPackageJson(path.join(studioPath, 'package.json'), {
31
33
  defaults: defaultStudioManifestProps,
@@ -37,8 +39,8 @@ const styledComponentsVersionRange = '^6.1.15';
37
39
  const wantedStyledComponentsVersionRange = styledComponentsVersionRange;
38
40
  // Retrieve the version of the 'sanity' dependency
39
41
  if (!installedSanityVersion) {
40
- output.error('Failed to read the installed sanity version.', {
41
- exit: 1
42
+ onNoInstalledSanityVersion({
43
+ message: 'Failed to read the installed sanity version.'
42
44
  });
43
45
  return {
44
46
  installedSanityVersion: ''
@@ -49,11 +51,11 @@ const styledComponentsVersionRange = '^6.1.15';
49
51
  // dependencies before running whatever command was being run
50
52
  const declaredStyledComponentsVersion = studioPackageManifest.dependencies?.['styled-components'] || studioPackageManifest?.devDependencies?.['styled-components'];
51
53
  if (!declaredStyledComponentsVersion) {
52
- output.error(oneline`
54
+ onNoDeclaredStyledComponentsVersion({
55
+ message: oneline`
53
56
  Declared dependency \`styled-components\` is not installed - run
54
57
  \`npm install\`, \`yarn install\` or \`pnpm install\` to install it before re-running this command.
55
- `, {
56
- exit: 1
58
+ `
57
59
  });
58
60
  return {
59
61
  installedSanityVersion
@@ -69,11 +71,11 @@ const styledComponentsVersionRange = '^6.1.15';
69
71
  // Intentional fall-through (variable will be left as null, throwing below)
70
72
  }
71
73
  if (!minDeclaredStyledComponentsVersion && !isStyledComponentsVersionRangeInCatalog) {
72
- output.error(oneline`
74
+ onInvalidStyledComponentsVersionRange({
75
+ message: oneline`
73
76
  Declared dependency \`styled-components\` has an invalid version range:
74
77
  \`${declaredStyledComponentsVersion}\`.
75
- `, {
76
- exit: 1
78
+ `
77
79
  });
78
80
  return {
79
81
  installedSanityVersion
@@ -86,19 +88,21 @@ const styledComponentsVersionRange = '^6.1.15';
86
88
  // to anything is going to be challenging, so only compare "simple" ranges/versions
87
89
  // (^x.x.x / ~x.x.x / x.x.x)
88
90
  if (!isStyledComponentsVersionRangeInCatalog && isComparableRange(declaredStyledComponentsVersion) && !satisfies(minDeclaredStyledComponentsVersion, wantedStyledComponentsVersionRange)) {
89
- output.warn(oneline`
91
+ onIncompatibleDeclaredStyledComponentsVersionRange({
92
+ message: oneline`
90
93
  Declared version of styled-components (${declaredStyledComponentsVersion})
91
94
  is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).
92
95
  This might cause problems!
93
- `);
96
+ `
97
+ });
94
98
  }
95
99
  // Ensure the studio has _installed_ a version of `styled-components`
96
100
  if (!installedStyledComponentsVersion) {
97
- output.error(oneline`
101
+ onNoInstalledStyledComponentsVersion({
102
+ message: oneline`
98
103
  Declared dependency \`styled-components\` is not installed - run
99
104
  \`npm install\`, \`yarn install\` or \`pnpm install\` to install it before re-running this command.
100
- `, {
101
- exit: 1
105
+ `
102
106
  });
103
107
  return {
104
108
  installedSanityVersion
@@ -107,11 +111,13 @@ const styledComponentsVersionRange = '^6.1.15';
107
111
  // The studio should have an _installed_ version of `styled-components`, and it should
108
112
  // be semver compatible with the version specified in `sanity` peer dependencies.
109
113
  if (!satisfies(installedStyledComponentsVersion, wantedStyledComponentsVersionRange)) {
110
- output.warn(oneline`
114
+ onIncompatibleInstalledStyledComponentsVersionRange({
115
+ message: oneline`
111
116
  Installed version of styled-components (${installedStyledComponentsVersion})
112
117
  is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).
113
118
  This might cause problems!
114
- `);
119
+ `
120
+ });
115
121
  }
116
122
  return {
117
123
  installedSanityVersion
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/checkRequiredDependencies.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {getLocalPackageVersion, readPackageJson} from '@sanity/cli-core/package-manager'\nimport {type Output, type PackageJson} from '@sanity/cli-core/types'\nimport {oneline} from 'oneline'\nimport {minVersion, satisfies, type SemVer} from 'semver'\n\nconst defaultStudioManifestProps: Partial<PackageJson> = {\n name: 'studio',\n version: '1.0.0',\n}\n\ninterface CheckResult {\n installedSanityVersion: string\n}\n\ninterface CheckRequiredDependenciesOptions {\n isApp: boolean\n output: Output\n workDir: string\n}\n\nconst styledComponentsVersionRange = '^6.1.15'\n\n/**\n * Checks that the studio has declared and installed the required dependencies\n * needed by the Sanity modules. While we generally use regular, explicit\n * dependencies in modules, there are certain dependencies that are better\n * served being peer dependencies, such as react and styled-components.\n *\n * If these dependencies are not installed/declared, we report an error\n * and instruct the user to install them manually.\n *\n * Additionally, returns the version of the 'sanity' dependency from the package.json.\n */\nexport async function checkRequiredDependencies(\n options: CheckRequiredDependenciesOptions,\n): Promise<CheckResult> {\n const {isApp, output, workDir: studioPath} = options\n // currently there's no check needed for core apps,\n // but this should be removed once they are more mature\n if (isApp) {\n return {installedSanityVersion: ''}\n }\n\n const [studioPackageManifest, installedStyledComponentsVersion, installedSanityVersion] =\n await Promise.all([\n readPackageJson(path.join(studioPath, 'package.json'), {\n defaults: defaultStudioManifestProps,\n skipSchemaValidation: true,\n }),\n getLocalPackageVersion('styled-components', studioPath),\n getLocalPackageVersion('sanity', studioPath),\n ])\n\n const wantedStyledComponentsVersionRange = styledComponentsVersionRange\n\n // Retrieve the version of the 'sanity' dependency\n if (!installedSanityVersion) {\n output.error('Failed to read the installed sanity version.', {exit: 1})\n return {installedSanityVersion: ''}\n }\n\n // The studio _must_ now declare `styled-components` as a dependency. If it's not there,\n // we'll want to automatically _add it_ to the manifest and tell the user to reinstall\n // dependencies before running whatever command was being run\n const declaredStyledComponentsVersion =\n studioPackageManifest.dependencies?.['styled-components'] ||\n studioPackageManifest?.devDependencies?.['styled-components']\n\n if (!declaredStyledComponentsVersion) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // We ignore catalog identifiers since we check the actual version anyway\n const isStyledComponentsVersionRangeInCatalog =\n declaredStyledComponentsVersion.startsWith('catalog:')\n // Theoretically the version specified in package.json could be incorrect, eg `foo`\n let minDeclaredStyledComponentsVersion: SemVer | null = null\n try {\n minDeclaredStyledComponentsVersion = minVersion(declaredStyledComponentsVersion)\n } catch {\n // Intentional fall-through (variable will be left as null, throwing below)\n }\n\n if (!minDeclaredStyledComponentsVersion && !isStyledComponentsVersionRangeInCatalog) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` has an invalid version range:\n \\`${declaredStyledComponentsVersion}\\`.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // The declared version should be semver-compatible with the version specified as a\n // peer dependency in `sanity`. If not, we should tell the user to change it.\n //\n // Exception: Ranges are hard to compare. `>=5.0.0 && <=5.3.2 || ^6`... Comparing this\n // to anything is going to be challenging, so only compare \"simple\" ranges/versions\n // (^x.x.x / ~x.x.x / x.x.x)\n if (\n !isStyledComponentsVersionRangeInCatalog &&\n isComparableRange(declaredStyledComponentsVersion) &&\n !satisfies(minDeclaredStyledComponentsVersion!, wantedStyledComponentsVersionRange)\n ) {\n output.warn(oneline`\n Declared version of styled-components (${declaredStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `)\n }\n\n // Ensure the studio has _installed_ a version of `styled-components`\n if (!installedStyledComponentsVersion) {\n output.error(\n oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n {exit: 1},\n )\n return {installedSanityVersion}\n }\n\n // The studio should have an _installed_ version of `styled-components`, and it should\n // be semver compatible with the version specified in `sanity` peer dependencies.\n if (!satisfies(installedStyledComponentsVersion, wantedStyledComponentsVersionRange)) {\n output.warn(oneline`\n Installed version of styled-components (${installedStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `)\n }\n\n return {installedSanityVersion}\n}\n\nfunction isComparableRange(range: string): boolean {\n return /^[\\^~]?\\d+(\\.\\d+)?(\\.\\d+)?$/.test(range)\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","oneline","minVersion","satisfies","defaultStudioManifestProps","name","version","styledComponentsVersionRange","checkRequiredDependencies","options","isApp","output","workDir","studioPath","installedSanityVersion","studioPackageManifest","installedStyledComponentsVersion","Promise","all","join","defaults","skipSchemaValidation","wantedStyledComponentsVersionRange","error","exit","declaredStyledComponentsVersion","dependencies","devDependencies","isStyledComponentsVersionRangeInCatalog","startsWith","minDeclaredStyledComponentsVersion","isComparableRange","warn","range","test"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,EAAEC,eAAe,QAAO,mCAAkC;AAExF,SAAQC,OAAO,QAAO,UAAS;AAC/B,SAAQC,UAAU,EAAEC,SAAS,QAAoB,SAAQ;AAEzD,MAAMC,6BAAmD;IACvDC,MAAM;IACNC,SAAS;AACX;AAYA,MAAMC,+BAA+B;AAErC;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,0BACpBC,OAAyC;IAEzC,MAAM,EAACC,KAAK,EAAEC,MAAM,EAAEC,SAASC,UAAU,EAAC,GAAGJ;IAC7C,mDAAmD;IACnD,uDAAuD;IACvD,IAAIC,OAAO;QACT,OAAO;YAACI,wBAAwB;QAAE;IACpC;IAEA,MAAM,CAACC,uBAAuBC,kCAAkCF,uBAAuB,GACrF,MAAMG,QAAQC,GAAG,CAAC;QAChBlB,gBAAgBF,KAAKqB,IAAI,CAACN,YAAY,iBAAiB;YACrDO,UAAUhB;YACViB,sBAAs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,OAAO;YAACV;QAAsB;IAChC;IAEA,sFAAsF;IACtF,iFAAiF;IACjF,IAAI,CAACX,UAAUa,kCAAkCM,qCAAqC;QACpFX,OAAOqB,IAAI,CAAC/B,OAAO,CAAC;8CACsB,EAAEe,iCAAiC;6DACpB,EAAEM,mCAAmC;;IAE9F,CAAC;IACH;IAEA,OAAO;QAACR;IAAsB;AAChC;AAEA,SAASiB,kBAAkBE,KAAa;IACtC,OAAO,8BAA8BC,IAAI,CAACD;AAC5C"}
1
+ {"version":3,"sources":["../../../src/actions/build/checkRequiredDependencies.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {getLocalPackageVersion, readPackageJson} from '@sanity/cli-core/package-manager'\nimport {type PackageJson} from '@sanity/cli-core/types'\nimport {oneline} from 'oneline'\nimport {minVersion, satisfies, type SemVer} from 'semver'\n\nimport {type BuildStudioEventListener} from './buildStudio'\n\nconst defaultStudioManifestProps: Partial<PackageJson> = {\n name: 'studio',\n version: '1.0.0',\n}\n\ninterface CheckResult {\n installedSanityVersion: string\n}\n\nexport interface CheckRequiredDependenciesOptions {\n isApp: boolean\n workDir: string\n\n onIncompatibleDeclaredStyledComponentsVersionRange?: BuildStudioEventListener['onIncompatibleDeclaredStyledComponentsVersionRange']\n onIncompatibleInstalledStyledComponentsVersionRange?: BuildStudioEventListener['onIncompatibleInstalledStyledComponentsVersionRange']\n onInvalidStyledComponentsVersionRange?: BuildStudioEventListener['onInvalidStyledComponentsVersionRange']\n onNoDeclaredStyledComponentsVersion?: BuildStudioEventListener['onNoDeclaredStyledComponentsVersion']\n onNoInstalledSanityVersion?: BuildStudioEventListener['onNoInstalledSanityVersion']\n onNoInstalledStyledComponentsVersion?: BuildStudioEventListener['onNoInstalledStyledComponentsVersion']\n}\n\nconst styledComponentsVersionRange = '^6.1.15'\n\nconst noop = async () => {}\n\n/**\n * Checks that the studio has declared and installed the required dependencies\n * needed by the Sanity modules. While we generally use regular, explicit\n * dependencies in modules, there are certain dependencies that are better\n * served being peer dependencies, such as react and styled-components.\n *\n * If these dependencies are not installed/declared, we report an error\n * and instruct the user to install them manually.\n *\n * Additionally, returns the version of the 'sanity' dependency from the package.json.\n */\nexport async function checkRequiredDependencies(\n options: CheckRequiredDependenciesOptions,\n): Promise<CheckResult> {\n const {isApp, workDir: studioPath} = options\n // currently there's no check needed for core apps,\n // but this should be removed once they are more mature\n if (isApp) {\n return {installedSanityVersion: ''}\n }\n\n const {\n onIncompatibleDeclaredStyledComponentsVersionRange = noop,\n onIncompatibleInstalledStyledComponentsVersionRange = noop,\n onInvalidStyledComponentsVersionRange = noop,\n onNoDeclaredStyledComponentsVersion = noop,\n onNoInstalledSanityVersion = noop,\n onNoInstalledStyledComponentsVersion = noop,\n } = options\n\n const [studioPackageManifest, installedStyledComponentsVersion, installedSanityVersion] =\n await Promise.all([\n readPackageJson(path.join(studioPath, 'package.json'), {\n defaults: defaultStudioManifestProps,\n skipSchemaValidation: true,\n }),\n getLocalPackageVersion('styled-components', studioPath),\n getLocalPackageVersion('sanity', studioPath),\n ])\n\n const wantedStyledComponentsVersionRange = styledComponentsVersionRange\n\n // Retrieve the version of the 'sanity' dependency\n if (!installedSanityVersion) {\n onNoInstalledSanityVersion({message: 'Failed to read the installed sanity version.'})\n return {installedSanityVersion: ''}\n }\n\n // The studio _must_ now declare `styled-components` as a dependency. If it's not there,\n // we'll want to automatically _add it_ to the manifest and tell the user to reinstall\n // dependencies before running whatever command was being run\n const declaredStyledComponentsVersion =\n studioPackageManifest.dependencies?.['styled-components'] ||\n studioPackageManifest?.devDependencies?.['styled-components']\n\n if (!declaredStyledComponentsVersion) {\n onNoDeclaredStyledComponentsVersion({\n message: oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n })\n return {installedSanityVersion}\n }\n\n // We ignore catalog identifiers since we check the actual version anyway\n const isStyledComponentsVersionRangeInCatalog =\n declaredStyledComponentsVersion.startsWith('catalog:')\n // Theoretically the version specified in package.json could be incorrect, eg `foo`\n let minDeclaredStyledComponentsVersion: SemVer | null = null\n try {\n minDeclaredStyledComponentsVersion = minVersion(declaredStyledComponentsVersion)\n } catch {\n // Intentional fall-through (variable will be left as null, throwing below)\n }\n\n if (!minDeclaredStyledComponentsVersion && !isStyledComponentsVersionRangeInCatalog) {\n onInvalidStyledComponentsVersionRange({\n message: oneline`\n Declared dependency \\`styled-components\\` has an invalid version range:\n \\`${declaredStyledComponentsVersion}\\`.\n `,\n })\n return {installedSanityVersion}\n }\n\n // The declared version should be semver-compatible with the version specified as a\n // peer dependency in `sanity`. If not, we should tell the user to change it.\n //\n // Exception: Ranges are hard to compare. `>=5.0.0 && <=5.3.2 || ^6`... Comparing this\n // to anything is going to be challenging, so only compare \"simple\" ranges/versions\n // (^x.x.x / ~x.x.x / x.x.x)\n if (\n !isStyledComponentsVersionRangeInCatalog &&\n isComparableRange(declaredStyledComponentsVersion) &&\n !satisfies(minDeclaredStyledComponentsVersion!, wantedStyledComponentsVersionRange)\n ) {\n onIncompatibleDeclaredStyledComponentsVersionRange({\n message: oneline`\n Declared version of styled-components (${declaredStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `,\n })\n }\n\n // Ensure the studio has _installed_ a version of `styled-components`\n if (!installedStyledComponentsVersion) {\n onNoInstalledStyledComponentsVersion({\n message: oneline`\n Declared dependency \\`styled-components\\` is not installed - run\n \\`npm install\\`, \\`yarn install\\` or \\`pnpm install\\` to install it before re-running this command.\n `,\n })\n return {installedSanityVersion}\n }\n\n // The studio should have an _installed_ version of `styled-components`, and it should\n // be semver compatible with the version specified in `sanity` peer dependencies.\n if (!satisfies(installedStyledComponentsVersion, wantedStyledComponentsVersionRange)) {\n onIncompatibleInstalledStyledComponentsVersionRange({\n message: oneline`\n Installed version of styled-components (${installedStyledComponentsVersion})\n is not compatible with the version required by sanity (${wantedStyledComponentsVersionRange}).\n This might cause problems!\n `,\n })\n }\n\n return {installedSanityVersion}\n}\n\nfunction isComparableRange(range: string): boolean {\n return /^[\\^~]?\\d+(\\.\\d+)?(\\.\\d+)?$/.test(range)\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","oneline","minVersion","satisfies","defaultStudioManifestProps","name","version","styledComponentsVersionRange","noop","checkRequiredDependencies","options","isApp","workDir","studioPath","installedSanityVersion","onIncompatibleDeclaredStyledComponentsVersionRange","onIncompatibleInstalledStyledComponentsVersionRange","onInvalidStyledComponentsVersionRange","onNoDeclaredStyledComponentsVersion","onNoInstalledSanityVersion","onNoInstalledStyledComponentsVersion","studioPackageManifest","installedStyledComponentsVersion","Promise","all","join","defaults","skipSchemaValidation","wantedStyledComponentsVersionRange","message","declaredStyledComponentsVersion","dependencies","devDependencies","isStyledComponentsVersionRangeInCatalog","startsWith","minDeclaredStyledComponentsVersion","isComparableRange","range","test"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,EAAEC,eAAe,QAAO,mCAAkC;AAExF,SAAQC,OAAO,QAAO,UAAS;AAC/B,SAAQC,UAAU,EAAEC,SAAS,QAAoB,SAAQ;AAIzD,MAAMC,6BAAmD;IACvDC,MAAM;IACNC,SAAS;AACX;AAkBA,MAAMC,+BAA+B;AAErC,MAAMC,OAAO,WAAa;AAE1B;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,0BACpBC,OAAyC;IAEzC,MAAM,EAACC,KAAK,EAAEC,SAASC,UAAU,EAAC,GAAGH;IACrC,mDAAmD;IACnD,uDAAuD;IACvD,IAAIC,OAAO;QACT,OAAO;YAACG,wBAAwB;QAAE;IACpC;IAEA,MAAM,EACJC,qDAAqDP,IAAI,EACzDQ,sDAAsDR,IAAI,EAC1DS,wCAAwCT,IAAI,EAC5CU,sCAAsCV,IAAI,EAC1CW,6BAA6BX,IAAI,EACjCY,uCAAuCZ,IAAI,EAC5C,GAAGE;IAEJ,MAAM,CAACW,uBAAuBC,kCAAkCR,uBAAuB,GACrF,MAA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qC;YACnCS,SAAS5B,OAAO,CAAC;;;IAGnB,CAAC;QACD;QACA,OAAO;YAACa;QAAsB;IAChC;IAEA,sFAAsF;IACtF,iFAAiF;IACjF,IAAI,CAACX,UAAUmB,kCAAkCM,qCAAqC;QACpFZ,oDAAoD;YAClDa,SAAS5B,OAAO,CAAC;8CACuB,EAAEqB,iCAAiC;6DACpB,EAAEM,mCAAmC;;IAE9F,CAAC;QACD;IACF;IAEA,OAAO;QAACd;IAAsB;AAChC;AAEA,SAASsB,kBAAkBC,KAAa;IACtC,OAAO,8BAA8BC,IAAI,CAACD;AAC5C"}
@@ -1,3 +1,4 @@
1
+ import { isStaging } from '@sanity/cli-core/util';
1
2
  /**
2
3
  * Decorates the given HTML template with a script
3
4
  * tag that loads the bridge component to communicate
@@ -5,12 +6,11 @@
5
6
  *
6
7
  * @internal
7
8
  */ export function decorateIndexWithBridgeScript(template) {
8
- const sanityEnv = process.env.SANITY_INTERNAL_ENV || 'production';
9
9
  /**
10
- * The URL to the bridge script is determined by the
11
- * `SANITY_INTERNAL_ENV` environment variable. So if you deploy
12
- * a studio to the staging ENV then you'll get the correct script.
13
- */ const scriptURL = sanityEnv === 'production' ? 'https://core.sanity-cdn.com/bridge.js' : 'https://core.sanity-cdn.work/bridge.js';
10
+ * The URL to the bridge script is determined by the active Sanity
11
+ * environment. So if you deploy a studio to the staging environment,
12
+ * then you'll get the correct script.
13
+ */ const scriptURL = isStaging() ? 'https://core.sanity-cdn.work/bridge.js' : 'https://core.sanity-cdn.com/bridge.js';
14
14
  return template.replace('</head>', `<script src="${scriptURL}" async type="module" data-sanity-core></script>\n</head>`);
15
15
  }
16
16
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/decorateIndexWithBridgeScript.ts"],"sourcesContent":["/**\n * Decorates the given HTML template with a script\n * tag that loads the bridge component to communicate\n * with core-ui.\n *\n * @internal\n */\nexport function decorateIndexWithBridgeScript(template: string): string {\n const sanityEnv = process.env.SANITY_INTERNAL_ENV || 'production'\n\n /**\n * The URL to the bridge script is determined by the\n * `SANITY_INTERNAL_ENV` environment variable. So if you deploy\n * a studio to the staging ENV then you'll get the correct script.\n */\n const scriptURL =\n sanityEnv === 'production'\n ? 'https://core.sanity-cdn.com/bridge.js'\n : 'https://core.sanity-cdn.work/bridge.js'\n\n return template.replace(\n '</head>',\n `<script src=\"${scriptURL}\" async type=\"module\" data-sanity-core></script>\\n</head>`,\n )\n}\n"],"names":["decorateIndexWithBridgeScript","template","sanityEnv","process","env","SANITY_INTERNAL_ENV","scriptURL","replace"],"mappings":"AAAA;;;;;;CAMC,GACD,OAAO,SAASA,8BAA8BC,QAAgB;IAC5D,MAAMC,YAAYC,QAAQC,GAAG,CAACC,mBAAmB,IAAI;IAErD;;;;GAIC,GACD,MAAMC,YACJJ,cAAc,eACV,0CACA;IAEN,OAAOD,SAASM,OAAO,CACrB,WACA,CAAC,aAAa,EAAED,UAAU,yDAAyD,CAAC;AAExF"}
1
+ {"version":3,"sources":["../../../src/actions/build/decorateIndexWithBridgeScript.ts"],"sourcesContent":["import {isStaging} from '@sanity/cli-core/util'\n\n/**\n * Decorates the given HTML template with a script\n * tag that loads the bridge component to communicate\n * with core-ui.\n *\n * @internal\n */\nexport function decorateIndexWithBridgeScript(template: string): string {\n /**\n * The URL to the bridge script is determined by the active Sanity\n * environment. So if you deploy a studio to the staging environment,\n * then you'll get the correct script.\n */\n const scriptURL = isStaging()\n ? 'https://core.sanity-cdn.work/bridge.js'\n : 'https://core.sanity-cdn.com/bridge.js'\n\n return template.replace(\n '</head>',\n `<script src=\"${scriptURL}\" async type=\"module\" data-sanity-core></script>\\n</head>`,\n )\n}\n"],"names":["isStaging","decorateIndexWithBridgeScript","template","scriptURL","replace"],"mappings":"AAAA,SAAQA,SAAS,QAAO,wBAAuB;AAE/C;;;;;;CAMC,GACD,OAAO,SAASC,8BAA8BC,QAAgB;IAC5D;;;;GAIC,GACD,MAAMC,YAAYH,cACd,2CACA;IAEJ,OAAOE,SAASE,OAAO,CACrB,WACA,CAAC,aAAa,EAAED,UAAU,yDAAyD,CAAC;AAExF"}
@@ -0,0 +1,3 @@
1
+ export { };
2
+
3
+ //# sourceMappingURL=eventListener.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/build/eventListener.ts"],"sourcesContent":["export type MessageFunc = ({message}: {message: string}) => void\n\nexport interface BuildEventListener {\n onPreReleaseInInteractiveAutoUpdate(params: {prereleaseMessage: string}): Promise<void>\n onPreReleaseInNonInteractiveAutoUpdate: MessageFunc\n}\n"],"names":[],"mappings":"AAEA,WAGC"}
@@ -1,4 +1,7 @@
1
- const MODULES_HOST = process.env.SANITY_MODULES_HOST || (process.env.SANITY_INTERNAL_ENV === 'staging' ? 'https://sanity-cdn.work' : 'https://sanity-cdn.com');
1
+ import { isStaging } from '@sanity/cli-core/util';
2
+ function getModulesHost() {
3
+ return process.env.SANITY_MODULES_HOST || (isStaging() ? 'https://sanity-cdn.work' : 'https://sanity-cdn.com');
4
+ }
2
5
  function currentUnixTime() {
3
6
  return Math.floor(Date.now() / 1000);
4
7
  }
@@ -37,11 +40,11 @@ function currentUnixTime() {
37
40
  }
38
41
  function getLegacyModuleUrl(pkg, options) {
39
42
  const encodedMinVer = encodeURIComponent(`^${pkg.version}`);
40
- return `${options.baseUrl || MODULES_HOST}/v1/modules/${rewriteScopedPackage(pkg.name)}/default/${encodedMinVer}/t${options.timestamp}`;
43
+ return `${options.baseUrl || getModulesHost()}/v1/modules/${rewriteScopedPackage(pkg.name)}/default/${encodedMinVer}/t${options.timestamp}`;
41
44
  }
42
45
  function getByAppModuleUrl(pkg, options) {
43
46
  const encodedMinVer = encodeURIComponent(`^${pkg.version}`);
44
- return `${options.baseUrl || MODULES_HOST}/v1/modules/by-app/${options.appId}/t${options.timestamp}/${encodedMinVer}/${rewriteScopedPackage(pkg.name)}`;
47
+ return `${options.baseUrl || getModulesHost()}/v1/modules/by-app/${options.appId}/t${options.timestamp}/${encodedMinVer}/${rewriteScopedPackage(pkg.name)}`;
45
48
  }
46
49
  /**
47
50
  * replaces '/' with '__' similar to how eg `@types/scope__pkg` are rewritten
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/getAutoUpdatesImportMap.ts"],"sourcesContent":["const MODULES_HOST =\n process.env.SANITY_MODULES_HOST ||\n (process.env.SANITY_INTERNAL_ENV === 'staging'\n ? 'https://sanity-cdn.work'\n : 'https://sanity-cdn.com')\n\nfunction currentUnixTime(): number {\n return Math.floor(Date.now() / 1000)\n}\n\ntype Package = {name: string; version: string}\n/**\n * @internal\n */\nexport function getAutoUpdatesImportMap<const Pkg extends Package>(\n packages: Pkg[],\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n) {\n return Object.fromEntries(\n packages.flatMap((pkg) => getAppAutoUpdateImportMapForPackage(pkg, options)),\n ) as {[K in `${Pkg['name']}/` | Pkg['name']]: string}\n}\n\n/**\n * @internal\n */\nfunction getAppAutoUpdateImportMapForPackage<const Pkg extends Package>(\n pkg: Pkg,\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n): [[Pkg['name'], string], [`${Pkg['name']}/`, string]] {\n const moduleUrl = getModuleUrl(pkg, options)\n\n return [\n [pkg.name, moduleUrl],\n [`${pkg.name}/`, `${moduleUrl}/`],\n ]\n}\n\n/**\n * @internal\n */\nexport function getModuleUrl(\n pkg: Package,\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n) {\n const {timestamp = currentUnixTime()} = options\n return options.appId\n ? getByAppModuleUrl(pkg, {appId: options.appId, baseUrl: options.baseUrl, timestamp})\n : getLegacyModuleUrl(pkg, {baseUrl: options.baseUrl, timestamp})\n}\n\nfunction getLegacyModuleUrl(pkg: Package, options: {baseUrl?: string; timestamp: number}) {\n const encodedMinVer = encodeURIComponent(`^${pkg.version}`)\n return `${options.baseUrl || MODULES_HOST}/v1/modules/${rewriteScopedPackage(pkg.name)}/default/${encodedMinVer}/t${options.timestamp}`\n}\n\nfunction getByAppModuleUrl(\n pkg: Package,\n options: {appId: string; baseUrl?: string; timestamp: number},\n) {\n const encodedMinVer = encodeURIComponent(`^${pkg.version}`)\n return `${options.baseUrl || MODULES_HOST}/v1/modules/by-app/${options.appId}/t${options.timestamp}/${encodedMinVer}/${rewriteScopedPackage(pkg.name)}`\n}\n\n/**\n * replaces '/' with '__' similar to how eg `@types/scope__pkg` are rewritten\n * scoped packages are stored this way both in the manifest and in the cloud storage bucket\n */\nfunction rewriteScopedPackage(pkgName: string) {\n if (!pkgName.includes('@')) {\n return pkgName\n }\n const [scope, ...pkg] = pkgName.split('/')\n return `${scope}__${pkg.join('')}`\n}\n\ntype PackageWithCss = Package & {cssFile?: string}\n\n/**\n * Generate CDN CSS URLs for auto-updated packages.\n * Uses the same URL pattern as JS module URLs so the module server\n * resolves CSS and JS to the same version.\n *\n * @internal\n */\nexport function getAutoUpdatesCssUrls<const Pkg extends PackageWithCss>(\n packages: Pkg[],\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n): string[] {\n return packages\n .filter((pkg) => Boolean(pkg.cssFile))\n .map((pkg) => `${getModuleUrl(pkg, options)}/${pkg.cssFile}`)\n}\n"],"names":["MODULES_HOST","process","env","SANITY_MODULES_HOST","SANITY_INTERNAL_ENV","currentUnixTime","Math","floor","Date","now","getAutoUpdatesImportMap","packages","options","Object","fromEntries","flatMap","pkg","getAppAutoUpdateImportMapForPackage","moduleUrl","getModuleUrl","name","timestamp","appId","getByAppModuleUrl","baseUrl","getLegacyModuleUrl","encodedMinVer","encodeURIComponent","version","rewriteScopedPackage","pkgName","includes","scope","split","join","getAutoUpdatesCssUrls","filter","Boolean","cssFile","map"],"mappings":"AAAA,MAAMA,eACJC,QAAQC,GAAG,CAACC,mBAAmB,IAC9BF,CAAAA,QAAQC,GAAG,CAACE,mBAAmB,KAAK,YACjC,4BACA,wBAAuB;AAE7B,SAASC;IACP,OAAOC,KAAKC,KAAK,CAACC,KAAKC,GAAG,KAAK;AACjC;AAGA;;CAEC,GACD,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,IAAI,GAAG;AACzJ;AAEA;;;CAGC,GACD,SAASS,qBAAqBC,OAAe;IAC3C,IAAI,CAACA,QAAQC,QAAQ,CAAC,MAAM;QAC1B,OAAOD;IACT;IACA,MAAM,CAACE,OAAO,GAAGhB,IAAI,GAAGc,QAAQG,KAAK,CAAC;IACtC,OAAO,GAAGD,MAAM,EAAE,EAAEhB,IAAIkB,IAAI,CAAC,KAAK;AACpC;AAIA;;;;;;CAMC,GACD,OAAO,SAASC,sBACdxB,QAAe,EACfC,UAAkE,CAAC,CAAC;IAEpE,OAAOD,SACJyB,MAAM,CAAC,CAACpB,MAAQqB,QAAQrB,IAAIsB,OAAO,GACnCC,GAAG,CAAC,CAACvB,MAAQ,GAAGG,aAAaH,KAAKJ,SAAS,CAAC,EAAEI,IAAIsB,OAAO,EAAE;AAChE"}
1
+ {"version":3,"sources":["../../../src/actions/build/getAutoUpdatesImportMap.ts"],"sourcesContent":["import {isStaging} from '@sanity/cli-core/util'\n\nfunction getModulesHost() {\n return (\n process.env.SANITY_MODULES_HOST ||\n (isStaging() ? 'https://sanity-cdn.work' : 'https://sanity-cdn.com')\n )\n}\n\nfunction currentUnixTime(): number {\n return Math.floor(Date.now() / 1000)\n}\n\ntype Package = {name: string; version: string}\n/**\n * @internal\n */\nexport function getAutoUpdatesImportMap<const Pkg extends Package>(\n packages: Pkg[],\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n) {\n return Object.fromEntries(\n packages.flatMap((pkg) => getAppAutoUpdateImportMapForPackage(pkg, options)),\n ) as {[K in `${Pkg['name']}/` | Pkg['name']]: string}\n}\n\n/**\n * @internal\n */\nfunction getAppAutoUpdateImportMapForPackage<const Pkg extends Package>(\n pkg: Pkg,\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n): [[Pkg['name'], string], [`${Pkg['name']}/`, string]] {\n const moduleUrl = getModuleUrl(pkg, options)\n\n return [\n [pkg.name, moduleUrl],\n [`${pkg.name}/`, `${moduleUrl}/`],\n ]\n}\n\n/**\n * @internal\n */\nexport function getModuleUrl(\n pkg: Package,\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n) {\n const {timestamp = currentUnixTime()} = options\n return options.appId\n ? getByAppModuleUrl(pkg, {appId: options.appId, baseUrl: options.baseUrl, timestamp})\n : getLegacyModuleUrl(pkg, {baseUrl: options.baseUrl, timestamp})\n}\n\nfunction getLegacyModuleUrl(pkg: Package, options: {baseUrl?: string; timestamp: number}) {\n const encodedMinVer = encodeURIComponent(`^${pkg.version}`)\n return `${options.baseUrl || getModulesHost()}/v1/modules/${rewriteScopedPackage(pkg.name)}/default/${encodedMinVer}/t${options.timestamp}`\n}\n\nfunction getByAppModuleUrl(\n pkg: Package,\n options: {appId: string; baseUrl?: string; timestamp: number},\n) {\n const encodedMinVer = encodeURIComponent(`^${pkg.version}`)\n return `${options.baseUrl || getModulesHost()}/v1/modules/by-app/${options.appId}/t${options.timestamp}/${encodedMinVer}/${rewriteScopedPackage(pkg.name)}`\n}\n\n/**\n * replaces '/' with '__' similar to how eg `@types/scope__pkg` are rewritten\n * scoped packages are stored this way both in the manifest and in the cloud storage bucket\n */\nfunction rewriteScopedPackage(pkgName: string) {\n if (!pkgName.includes('@')) {\n return pkgName\n }\n const [scope, ...pkg] = pkgName.split('/')\n return `${scope}__${pkg.join('')}`\n}\n\ntype PackageWithCss = Package & {cssFile?: string}\n\n/**\n * Generate CDN CSS URLs for auto-updated packages.\n * Uses the same URL pattern as JS module URLs so the module server\n * resolves CSS and JS to the same version.\n *\n * @internal\n */\nexport function getAutoUpdatesCssUrls<const Pkg extends PackageWithCss>(\n packages: Pkg[],\n options: {appId?: string; baseUrl?: string; timestamp?: number} = {},\n): string[] {\n return packages\n .filter((pkg) => Boolean(pkg.cssFile))\n .map((pkg) => `${getModuleUrl(pkg, options)}/${pkg.cssFile}`)\n}\n"],"names":["isStaging","getModulesHost","process","env","SANITY_MODULES_HOST","currentUnixTime","Math","floor","Date","now","getAutoUpdatesImportMap","packages","options","Object","fromEntries","flatMap","pkg","getAppAutoUpdateImportMapForPackage","moduleUrl","getModuleUrl","name","timestamp","appId","getByAppModuleUrl","baseUrl","getLegacyModuleUrl","encodedMinVer","encodeURIComponent","version","rewriteScopedPackage","pkgName","includes","scope","split","join","getAutoUpdatesCssUrls","filter","Boolean","cssFile","map"],"mappings":"AAAA,SAAQA,SAAS,QAAO,wBAAuB;AAE/C,SAASC;IACP,OACEC,QAAQC,GAAG,CAACC,mBAAmB,IAC9BJ,CAAAA,cAAc,4BAA4B,wBAAuB;AAEtE;AAEA,SAASK;IACP,OAAOC,KAAKC,KAAK,CAACC,KAAKC,GAAG,KAAK;AACjC;AAGA;;CAEC,GACD,OAAO,SAASC,wBACdC,QAAe,EACfC,UAAkE,CAAC,CAAC;IAEpE,OAAOC,OAAOC,WAAW,CACvBH,SAASI,OAAO,CAAC,CAACC,MAAQC,oCAAoCD,KAAKJ;AAEvE;AAEA;;CAEC,GACD,SAASK,oCACPD,GAAQ,EACRJ,UAAkE,CAAC,CAAC;IAEpE,MAAMM,YAAYC,aAAaH,KAAKJ;IAEpC,OAAO;QACL;YAACI,IAAII,IAAI;YAAEF;SAAU;QACrB;YAAC,GAAGF,IAAII,IAAI,CAAC,CAAC,CAAC;YAAE,GAAGF,UAAU,CAAC,CAAC;SAAC;KAClC;AACH;AAEA;;CAEC,GACD,OAAO,SAASC,aACdH,GAAY,EACZJ,UAAkE,CAAC,CAAC;IAEpE,MAAM,EAACS,YAAYhB,iBAAiB,EAAC,GAAGO;IACxC,OAAOA,QAAQU,KAAK,GAChBC,kBAAkBP,KAAK;QAACM,OAAOV,QAAQU,KAAK;QAAEE,SAASZ,QAAQY,OAAO;QAAEH;IAAS,KACjFI,mBAAmBT,KAAK;QAACQ,SAASZ,QAAQY,OAAO;QAAEH;IAAS;AAClE;AAEA,SAASI,mBAAmBT,GAAY,EAAEJ,OAA8C;IACtF,MAAMc,gBAAgBC,mBAAmB,CAAC,CAAC,EAAEX,IAAIY,OAAO,EAAE;IAC1D,OAAO,GAAGhB,QAAQY,OAAO,IAAIvB,iBAAiB,YAAY,EAAE4B,qBAAqBb,IAAII,IAAI,EAAE,SAAS,EAAEM,cAAc,EAAE,EAAEd,QAAQS,SAAS,EAAE;AAC7I;AAEA,SAASE,kBACPP,GAAY,EACZJ,OAA6D;IAE7D,MAAMc,gBAAgBC,mBAAmB,CAAC,CAAC,EAAEX,IAAIY,OAAO,EAAE;IAC1D,OAAO,GAAGhB,QAAQY,OAAO,IAAIvB,iBAAiB,mBAAmB,EAAEW,QAAQU,KAAK,CAAC,EAAE,EAAEV,QAAQS,SAAS,CAAC,CAAC,EAAEK,cAAc,CAAC,EAAEG,qBAAqBb,IAAII,IAAI,GAAG;AAC7J;AAEA;;;CAGC,GACD,SAASS,qBAAqBC,OAAe;IAC3C,IAAI,CAACA,QAAQC,QAAQ,CAAC,MAAM;QAC1B,OAAOD;IACT;IACA,MAAM,CAACE,OAAO,GAAGhB,IAAI,GAAGc,QAAQG,KAAK,CAAC;IACtC,OAAO,GAAGD,MAAM,EAAE,EAAEhB,IAAIkB,IAAI,CAAC,KAAK;AACpC;AAIA;;;;;;CAMC,GACD,OAAO,SAASC,sBACdxB,QAAe,EACfC,UAAkE,CAAC,CAAC;IAEpE,OAAOD,SACJyB,MAAM,CAAC,CAACpB,MAAQqB,QAAQrB,IAAIsB,OAAO,GACnCC,GAAG,CAAC,CAACvB,MAAQ,GAAGG,aAAaH,KAAKJ,SAAS,CAAC,EAAEI,IAAIsB,OAAO,EAAE;AAChE"}
@@ -2,6 +2,7 @@ import path from 'node:path';
2
2
  import babel from '@rolldown/plugin-babel';
3
3
  import { findProjectRoot } from '@sanity/cli-core/config';
4
4
  import { getCliTelemetry } from '@sanity/cli-core/telemetry';
5
+ import { isStaging } from '@sanity/cli-core/util';
5
6
  import { workbenchOptimizeDeps, workbenchVitePlugins } from '@sanity/workbench-cli/build';
6
7
  import viteReact, { reactCompilerPreset } from '@vitejs/plugin-react';
7
8
  import debug from 'debug';
@@ -62,7 +63,7 @@ import { getDefaultFaviconsPath } from './writeFavicons.js';
62
63
  configFile: false,
63
64
  define: {
64
65
  __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),
65
- __SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',
66
+ __SANITY_STAGING__: isStaging(),
66
67
  'process.env.MODE': JSON.stringify(mode),
67
68
  'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),
68
69
  /**
@@ -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 {findProjectRoot} from '@sanity/cli-core/config'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {\n type WorkbenchExposes,\n workbenchOptimizeDeps,\n workbenchVitePlugins,\n} from '@sanity/workbench-cli/build'\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 PluginOption,\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 entries: {\n relativeConfigLocation: string | null\n // `null` when a branded app declares no `entry` (sanity-io/workbench spec 002-workbench-extension-api, US5) — no app view.\n relativeEntry: string | null\n }\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: boolean | 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 exposes?: WorkbenchExposes\n\n isApp?: boolean\n\n /**\n * Whether this is a workbench app (opted in via `unstable_defineApp`). Drives\n * the module-federation build.\n */\n isWorkbenchApp?: 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 /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n\n /**\n * The workbench app's bus identity, stamped into its modules as\n * `__SANITY_APP_ID__` for `@sanity/runtime`. Only read for workbench apps.\n */\n workbenchAppId?: string\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 entries,\n exposes,\n isApp,\n isWorkbenchApp,\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 workbenchAppId,\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 sharedPlugins: PluginOption = [\n viteReact(),\n ...(reactCompiler\n ? [babel({presets: [reactCompilerPreset(reactCompiler === true ? {} : reactCompiler)]})]\n : []),\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 ]\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 // Federation builds skip the serve-only client plugins (favicons, runtime\n // rewrite) — they no-op at build. `sanityBuildEntries` is scoped to the\n // `client` environment so it emits the standalone SPA `index.html`\n // (bridge-free) when the workbench remote SPA is enabled, and no-ops in the\n // federation env / when no client env exists (see plugin-sanity-environment).\n ...(isWorkbenchApp\n ? [\n ...sharedPlugins,\n await workbenchVitePlugins({appId: workbenchAppId, cwd, entries, exposes, isApp}),\n {\n ...sanityBuildEntries({basePath, bridge: false, cwd, isApp}),\n applyToEnvironment: (env) => env.name === 'client',\n } satisfies Plugin,\n ]\n : [\n ...sharedPlugins,\n sanityFaviconsPlugin({\n customFaviconsPath,\n defaultFaviconsPath,\n staticUrlPath: staticPath,\n }),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({autoUpdates, basePath, cwd, isApp}),\n ]),\n // Caller-provided plugins (e.g. typegen in dev) aren't client-specific,\n // so they apply to federation builds too.\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 // Apps drift to a free port (the reported URL embeds whichever port was\n // claimed), and workbench runs stack servers on adjacent ports — both\n // need the fallback. Studios fail fast on a busy port.\n strictPort: !isApp && !isWorkbenchApp,\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 // Front-load the deps the federation `exposes` reach only via the host's\n // dynamic imports, which Vite's dep scanner (crawling from the HTML entry)\n // otherwise misses — see `workbenchOptimizeDeps`. Dev-server only; Vite\n // ignores `optimizeDeps` at build. Set before the userland `vite` hook so an\n // app can still extend the list.\n if (isWorkbenchApp && mode === 'development') {\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n const appSources = [entries.relativeEntry, entries.relativeConfigLocation]\n .filter((relativePath): relativePath is string => relativePath !== null)\n .map((relativePath) => path.resolve(runtimeDir, relativePath))\n viteConfig.optimizeDeps = workbenchOptimizeDeps({appSources, cwd, exposes})\n }\n\n // Federation builds don't produce a client bundle — the federation\n // plugin configures its own environment and build entry point.\n if (mode === 'production' && !isWorkbenchApp) {\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","workbenchOptimizeDeps","workbenchVitePlugins","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","entries","exposes","isApp","isWorkbenchApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","workbenchAppId","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","getEnvironmentVariables","sharedPlugins","presets","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","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","appId","bridge","applyToEnvironment","name","staticUrlPath","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","runtimeDir","appSources","relativeEntry","relativeConfigLocation","filter","relativePath","map","optimizeDeps","push","vendor","namesByChunkName","external","imports","Object","fromEntries","values","specifiersByChunkName","specifier","vendorChunkNames","Set","keys","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","experimental","nativeMagicString","output","entryFileNames","chunk","has","exports","preserveEntrySignatures","warning","warn","suppressUnusedImport","code","names","includes","n","length","ids","every","id","finalizeViteConfig","config","defaultConfig","TypeError","Error","extendViteConfigWithUserConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,OAAOC,WAAW,yBAAwB;AAC1C,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAEEC,qBAAqB,EACrBC,oBAAoB,QACf,8BAA6B;AACpC,OAAOC,aAAYC,mBAAmB,QAAO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,QAAQI,KAAK,EAAEC,SAAS,kBAAkB;QAC5CL,QAAQI,KAAK,GAAGJ,QAAQI,KAAK,CAACpC,MAAM,CAAC,CAACsC,IAAMA,MAAM;QAClD,IAAIN,QAAQI,KAAK,CAACG,MAAM,KAAK,GAAG,OAAO;IACzC;IAEA,mFAAmF;IACnF,IAAIP,QAAQQ,GAAG,EAAEC,MAAM,CAACC,KAAOA,GAAGL,QAAQ,CAAC,qBAAqBK,GAAGL,QAAQ,CAAC,sBAC1E,OAAO;IAET,OAAO;AACT;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,eAAeM,mBACpBC,MAAoB,EACpBC,aAA2B;IAE3B,IAAI,OAAOD,OAAOjF,KAAK,EAAEwD,iBAAiBC,UAAU,UAAU;QAC5D,MAAM,IAAI0B,UACR;IAEJ;IAEA,IAAI,CAACF,OAAOtD,IAAI,EAAE;QAChB,MAAM,IAAIyD,MACR;IAEJ;IAEA,OAAOtI,YAAYmI,QAAQ;QACzBjF,OAAO;YACLwD,iBAAiB0B,cAAclF,KAAK,EAAEwD,mBAAmB,CAAC;QAC5D;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAe6B,+BACpBvE,GAAc,EACdoE,aAA2B,EAC3BI,UAA0B;IAE1B,IAAIL,SAASC;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpC1I,MAAM;QACNqI,SAAS,MAAMK,WAAWL,QAAQnE;IACpC,OAAO,IAAI,OAAOwE,eAAe,UAAU;QACzC1I,MAAM;QACNqI,SAASnI,YAAYmI,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 {findProjectRoot} from '@sanity/cli-core/config'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isStaging} from '@sanity/cli-core/util'\nimport {\n type WorkbenchExposes,\n workbenchOptimizeDeps,\n workbenchVitePlugins,\n} from '@sanity/workbench-cli/build'\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 PluginOption,\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 entries: {\n relativeConfigLocation: string | null\n // `null` when a branded app declares no `entry` (sanity-io/workbench spec 002-workbench-extension-api, US5) — no app view.\n relativeEntry: string | null\n }\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: boolean | 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 exposes?: WorkbenchExposes\n\n isApp?: boolean\n\n /**\n * Whether this is a workbench app (opted in via `unstable_defineApp`). Drives\n * the module-federation build.\n */\n isWorkbenchApp?: 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 /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n\n /**\n * The workbench app's bus identity, stamped into its modules as\n * `__SANITY_APP_ID__` for `@sanity/runtime`. Only read for workbench apps.\n */\n workbenchAppId?: string\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 entries,\n exposes,\n isApp,\n isWorkbenchApp,\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 workbenchAppId,\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 sharedPlugins: PluginOption = [\n viteReact(),\n ...(reactCompiler\n ? [babel({presets: [reactCompilerPreset(reactCompiler === true ? {} : reactCompiler)]})]\n : []),\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 ]\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__: isStaging(),\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 // Federation builds skip the serve-only client plugins (favicons, runtime\n // rewrite) — they no-op at build. `sanityBuildEntries` is scoped to the\n // `client` environment so it emits the standalone SPA `index.html`\n // (bridge-free) when the workbench remote SPA is enabled, and no-ops in the\n // federation env / when no client env exists (see plugin-sanity-environment).\n ...(isWorkbenchApp\n ? [\n ...sharedPlugins,\n await workbenchVitePlugins({appId: workbenchAppId, cwd, entries, exposes, isApp}),\n {\n ...sanityBuildEntries({basePath, bridge: false, cwd, isApp}),\n applyToEnvironment: (env) => env.name === 'client',\n } satisfies Plugin,\n ]\n : [\n ...sharedPlugins,\n sanityFaviconsPlugin({\n customFaviconsPath,\n defaultFaviconsPath,\n staticUrlPath: staticPath,\n }),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({autoUpdates, basePath, cwd, isApp}),\n ]),\n // Caller-provided plugins (e.g. typegen in dev) aren't client-specific,\n // so they apply to federation builds too.\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 // Apps drift to a free port (the reported URL embeds whichever port was\n // claimed), and workbench runs stack servers on adjacent ports — both\n // need the fallback. Studios fail fast on a busy port.\n strictPort: !isApp && !isWorkbenchApp,\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 // Front-load the deps the federation `exposes` reach only via the host's\n // dynamic imports, which Vite's dep scanner (crawling from the HTML entry)\n // otherwise misses — see `workbenchOptimizeDeps`. Dev-server only; Vite\n // ignores `optimizeDeps` at build. Set before the userland `vite` hook so an\n // app can still extend the list.\n if (isWorkbenchApp && mode === 'development') {\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n const appSources = [entries.relativeEntry, entries.relativeConfigLocation]\n .filter((relativePath): relativePath is string => relativePath !== null)\n .map((relativePath) => path.resolve(runtimeDir, relativePath))\n viteConfig.optimizeDeps = workbenchOptimizeDeps({appSources, cwd, exposes})\n }\n\n // Federation builds don't produce a client bundle — the federation\n // plugin configures its own environment and build entry point.\n if (mode === 'production' && !isWorkbenchApp) {\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","isStaging","workbenchOptimizeDeps","workbenchVitePlugins","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","entries","exposes","isApp","isWorkbenchApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","workbenchAppId","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","getEnvironmentVariables","sharedPlugins","presets","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","appId","bridge","applyToEnvironment","name","staticUrlPath","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","runtimeDir","appSources","relativeEntry","relativeConfigLocation","filter","relativePath","map","optimizeDeps","push","vendor","namesByChunkName","external","imports","Object","fromEntries","values","specifiersByChunkName","specifier","vendorChunkNames","Set","keys","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","experimental","nativeMagicString","output","entryFileNames","chunk","has","exports","preserveEntrySignatures","warning","warn","suppressUnusedImport","code","names","includes","n","length","ids","every","id","finalizeViteConfig","config","defaultConfig","TypeError","Error","extendViteConfigWithUserConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,OAAOC,WAAW,yBAAwB;AAC1C,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,SAEEC,qBAAqB,EACrBC,oBAAoB,QACf,8BAA6B;AACpC,OAAOC,aAAYC,mBAAmB,QAAO,uBAAsB;AAEnE,OAAOC,WAAW,QAAO;AACzB,SAEEC,wBAAwB,EAExBC,WAAW,QAIN,OAAM;AAEb,SAAQC,gBAAgB,QAAO,qBAAoB;AACnD,SAAQC,4BAA4B,QAAO,6CAA4C;AAEvF,SAAQC,UAAU,QAAO,iBAAgB;AACzC,SAAQC,2BAA2B,QAAO,mCAAkC;AAC5E,SAAQC,iBAAiB,QAAO,yBAAwB;AACxD,SAAQC,kBAAkB,QAAO,wCAAuC;AACxE,SAAQC,oBAAoB,QAAO,mCAAkC;AACrE,SAAQC,0BAA0B,QAAO,0CAAyC;AAClF,SAAQC,8BAA8B,QAAO,+CAA8C;AAC3F,SAAQC,sBAAsB,QAAO,qBAAoB;AAsFzD;;;;CAIC,GACD,OAAO,eAAeC,cAAcC,OAAoB;IACtD,MAAM,EACJC,iBAAiB,EACjBC,W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AIyD,MACR;IAEJ;IAEA,OAAOrI,YAAYkI,QAAQ;QACzBhF,OAAO;YACLuD,iBAAiB0B,cAAcjF,KAAK,EAAEuD,mBAAmB,CAAC;QAC5D;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAe6B,+BACpBtE,GAAc,EACdmE,aAA2B,EAC3BI,UAA0B;IAE1B,IAAIL,SAASC;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpCzI,MAAM;QACNoI,SAAS,MAAMK,WAAWL,QAAQlE;IACpC,OAAO,IAAI,OAAOuE,eAAe,UAAU;QACzCzI,MAAM;QACNoI,SAASlI,YAAYkI,QAAQK;IAC/B;IAEA,OAAOL;AACT"}
@@ -1,6 +1,5 @@
1
- import { styleText } from 'node:util';
2
1
  import { isInteractive } from '@sanity/cli-core/util';
3
- import { select } from '@sanity/cli-core/ux';
2
+ const noop = async ()=>{};
4
3
  /**
5
4
  * Handle prerelease versions that cannot be resolved by the auto-updates CDN.
6
5
  *
@@ -8,37 +7,19 @@ import { select } from '@sanity/cli-core/ux';
8
7
  * prompts the user to either disable auto-updates for this build or cancel.
9
8
  *
10
9
  * Does not return if the build should be cancelled (exits via `output.error`).
11
- */ export async function handlePrereleaseVersions({ output, unattendedMode, unresolvedPrerelease }) {
10
+ */ export async function handlePrereleaseVersions({ onPreReleaseInInteractiveAutoUpdate, onPreReleaseInNonInteractiveAutoUpdate, unattendedMode, unresolvedPrerelease }) {
11
+ onPreReleaseInInteractiveAutoUpdate ??= noop;
12
+ onPreReleaseInNonInteractiveAutoUpdate ??= noop;
12
13
  const prereleaseMessage = `The following packages are using prerelease versions not yet available on the auto-updates CDN:\n\n` + `${unresolvedPrerelease.map((mod)=>` - ${mod.pkg} (${mod.version})`).join('\n')}\n\n` + `Auto-updates cannot be used with prerelease versions. To re-enable auto-updates later, ` + `switch to a non-prerelease version locally and deploy again.`;
13
14
  if (unattendedMode || !isInteractive()) {
14
- output.error(`${prereleaseMessage}\n\n` + `Cannot build with auto-updates in unattended mode when using prerelease versions. ` + `Either switch to a non-prerelease version, or use --no-auto-updates to build without auto-updates.`, {
15
- exit: 1
15
+ onPreReleaseInNonInteractiveAutoUpdate({
16
+ message: `${prereleaseMessage}\n\n` + `Cannot build with auto-updates in unattended mode when using prerelease versions. ` + `Either switch to a non-prerelease version, or use --no-auto-updates to build without auto-updates.`
16
17
  });
17
- // output.error with exit: 1 throws, but TypeScript doesn't know that
18
18
  return;
19
19
  }
20
- const choice = await select({
21
- choices: [
22
- {
23
- name: 'Disable auto-updates for this build and continue',
24
- value: 'disable-auto-updates'
25
- },
26
- {
27
- name: 'Cancel build',
28
- value: 'cancel'
29
- }
30
- ],
31
- default: 'disable-auto-updates',
32
- message: styleText('yellow', prereleaseMessage)
20
+ await onPreReleaseInInteractiveAutoUpdate({
21
+ prereleaseMessage
33
22
  });
34
- if (choice === 'cancel') {
35
- output.error('Declined to continue with build', {
36
- exit: 1
37
- });
38
- // output.error with exit: 1 throws, but TypeScript doesn't know that
39
- return;
40
- }
41
- output.warn('Auto-updates disabled for this build');
42
23
  }
43
24
 
44
25
  //# sourceMappingURL=handlePrereleaseVersions.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/handlePrereleaseVersions.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type Output} from '@sanity/cli-core/types'\nimport {isInteractive} from '@sanity/cli-core/util'\nimport {select} from '@sanity/cli-core/ux'\n\nimport {type UnresolvedPrerelease} from '../../util/compareDependencyVersions.js'\n\n/**\n * Handle prerelease versions that cannot be resolved by the auto-updates CDN.\n *\n * In unattended or non-interactive mode, exits with an error. In interactive mode,\n * prompts the user to either disable auto-updates for this build or cancel.\n *\n * Does not return if the build should be cancelled (exits via `output.error`).\n */\nexport async function handlePrereleaseVersions({\n output,\n unattendedMode,\n unresolvedPrerelease,\n}: {\n output: Output\n unattendedMode: boolean\n unresolvedPrerelease: UnresolvedPrerelease[]\n}): Promise<void> {\n const prereleaseMessage =\n `The following packages are using prerelease versions not yet available on the auto-updates CDN:\\n\\n` +\n `${unresolvedPrerelease.map((mod) => ` - ${mod.pkg} (${mod.version})`).join('\\n')}\\n\\n` +\n `Auto-updates cannot be used with prerelease versions. To re-enable auto-updates later, ` +\n `switch to a non-prerelease version locally and deploy again.`\n\n if (unattendedMode || !isInteractive()) {\n output.error(\n `${prereleaseMessage}\\n\\n` +\n `Cannot build with auto-updates in unattended mode when using prerelease versions. ` +\n `Either switch to a non-prerelease version, or use --no-auto-updates to build without auto-updates.`,\n {exit: 1},\n )\n // output.error with exit: 1 throws, but TypeScript doesn't know that\n return\n }\n\n const choice = await select({\n choices: [\n {\n name: 'Disable auto-updates for this build and continue',\n value: 'disable-auto-updates',\n },\n {name: 'Cancel build', value: 'cancel'},\n ],\n default: 'disable-auto-updates',\n message: styleText('yellow', prereleaseMessage),\n })\n\n if (choice === 'cancel') {\n output.error('Declined to continue with build', {exit: 1})\n // output.error with exit: 1 throws, but TypeScript doesn't know that\n return\n }\n\n output.warn('Auto-updates disabled for this build')\n}\n"],"names":["styleText","isInteractive","select","handlePrereleaseVersions","output","unattendedMode","unresolvedPrerelease","prereleaseMessage","map","mod","pkg","version","join","error","exit","choice","choices","name","value","default","message","warn"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAGnC,SAAQC,aAAa,QAAO,wBAAuB;AACnD,SAAQC,MAAM,QAAO,sBAAqB;AAI1C;;;;;;;CAOC,GACD,OAAO,eAAeC,yBAAyB,EAC7CC,MAAM,EACNC,cAAc,EACdC,oBAAoB,EAKrB;IACC,MAAMC,oBACJ,CAAC,mGAAmG,CAAC,GACrG,GAAGD,qBAAqBE,GAAG,CAAC,CAACC,MAAQ,CAAC,GAAG,EAAEA,IAAIC,GAAG,CAAC,EAAE,EAAED,IAAIE,OAAO,CAAC,CAAC,CAAC,EAAEC,IAAI,CAAC,MAAM,IAAI,CAAC,GACvF,CAAC,uFAAuF,CAAC,GACzF,CAAC,4DAA4D,CAAC;IAEhE,IAAIP,kBAAkB,CAACJ,iBAAiB;QACtCG,OAAOS,KAAK,CACV,GAAGN,kBAAkB,IAAI,CAAC,GACxB,CAAC,kFAAkF,CAAC,GACpF,CAAC,kGAAkG,CAAC,EACtG;YAACO,MAAM;QAAC;QAEV,qEAAqE;QACrE;IACF;IAEA,MAAMC,SAAS,MAAMb,OAAO;QAC1Bc,SAAS;YACP;gBACEC,MAAM;gBACNC,OAAO;YACT;YACA;gBAACD,MAAM;gBAAgBC,OAAO;YAAQ;SACvC;QACDC,SAAS;QACTC,SAASpB,UAAU,UAAUO;IAC/B;IAEA,IAAIQ,WAAW,UAAU;QACvBX,OAAOS,KAAK,CAAC,mCAAmC;YAACC,MAAM;QAAC;QACxD,qEAAqE;QACrE;IACF;IAEAV,OAAOiB,IAAI,CAAC;AACd"}
1
+ {"version":3,"sources":["../../../src/actions/build/handlePrereleaseVersions.ts"],"sourcesContent":["import {isInteractive} from '@sanity/cli-core/util'\n\nimport {type UnresolvedPrerelease} from '../../util/compareDependencyVersions.js'\nimport {type BuildStudioEventListener} from './buildStudio.js'\n\nconst noop = async () => {}\n\n/**\n * Handle prerelease versions that cannot be resolved by the auto-updates CDN.\n *\n * In unattended or non-interactive mode, exits with an error. In interactive mode,\n * prompts the user to either disable auto-updates for this build or cancel.\n *\n * Does not return if the build should be cancelled (exits via `output.error`).\n */\nexport async function handlePrereleaseVersions({\n onPreReleaseInInteractiveAutoUpdate,\n onPreReleaseInNonInteractiveAutoUpdate,\n unattendedMode,\n unresolvedPrerelease,\n}: {\n onPreReleaseInInteractiveAutoUpdate?: BuildStudioEventListener['onPreReleaseInInteractiveAutoUpdate']\n onPreReleaseInNonInteractiveAutoUpdate?: BuildStudioEventListener['onPreReleaseInNonInteractiveAutoUpdate']\n unattendedMode: boolean\n unresolvedPrerelease: UnresolvedPrerelease[]\n}): Promise<void> {\n onPreReleaseInInteractiveAutoUpdate ??= noop\n onPreReleaseInNonInteractiveAutoUpdate ??= noop\n\n const prereleaseMessage =\n `The following packages are using prerelease versions not yet available on the auto-updates CDN:\\n\\n` +\n `${unresolvedPrerelease.map((mod) => ` - ${mod.pkg} (${mod.version})`).join('\\n')}\\n\\n` +\n `Auto-updates cannot be used with prerelease versions. To re-enable auto-updates later, ` +\n `switch to a non-prerelease version locally and deploy again.`\n\n if (unattendedMode || !isInteractive()) {\n onPreReleaseInNonInteractiveAutoUpdate({\n message:\n `${prereleaseMessage}\\n\\n` +\n `Cannot build with auto-updates in unattended mode when using prerelease versions. ` +\n `Either switch to a non-prerelease version, or use --no-auto-updates to build without auto-updates.`,\n })\n return\n }\n\n await onPreReleaseInInteractiveAutoUpdate({prereleaseMessage})\n}\n"],"names":["isInteractive","noop","handlePrereleaseVersions","onPreReleaseInInteractiveAutoUpdate","onPreReleaseInNonInteractiveAutoUpdate","unattendedMode","unresolvedPrerelease","prereleaseMessage","map","mod","pkg","version","join","message"],"mappings":"AAAA,SAAQA,aAAa,QAAO,wBAAuB;AAKnD,MAAMC,OAAO,WAAa;AAE1B;;;;;;;CAOC,GACD,OAAO,eAAeC,yBAAyB,EAC7CC,mCAAmC,EACnCC,sCAAsC,EACtCC,cAAc,EACdC,oBAAoB,EAMrB;IACCH,wCAAwCF;IACxCG,2CAA2CH;IAE3C,MAAMM,oBACJ,CAAC,mGAAmG,CAAC,GACrG,GAAGD,qBAAqBE,GAAG,CAAC,CAACC,MAAQ,CAAC,GAAG,EAAEA,IAAIC,GAAG,CAAC,EAAE,EAAED,IAAIE,OAAO,CAAC,CAAC,CAAC,EAAEC,IAAI,CAAC,MAAM,IAAI,CAAC,GACvF,CAAC,uFAAuF,CAAC,GACzF,CAAC,4DAA4D,CAAC;IAEhE,IAAIP,kBAAkB,CAACL,iBAAiB;QACtCI,uCAAuC;YACrCS,SACE,GAAGN,kBAAkB,IAAI,CAAC,GAC1B,CAAC,kFAAkF,CAAC,GACpF,CAAC,kGAAkG,CAAC;QACxG;QACA;IACF;IAEA,MAAMJ,oCAAoC;QAACI;IAAiB;AAC9D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-build",
3
- "version": "4.1.1",
3
+ "version": "5.1.0",
4
4
  "description": "Internal Sanity package for building studios and apps",
5
5
  "keywords": [
6
6
  "cli",
@@ -49,9 +49,9 @@
49
49
  "@oclif/core": "^4.11.14",
50
50
  "@rolldown/plugin-babel": "^0.2.3",
51
51
  "@sanity/generate-help-url": "^4.0.0",
52
- "@sanity/schema": "^6.5.0",
52
+ "@sanity/schema": "^6.7.0",
53
53
  "@sanity/telemetry": "^1.1.0",
54
- "@sanity/types": "^6.5.0",
54
+ "@sanity/types": "^6.7.0",
55
55
  "@vitejs/plugin-react": "^6.0.3",
56
56
  "chokidar": "^5.0.0",
57
57
  "cjs-module-lexer": "^2.2.0",
@@ -66,8 +66,8 @@
66
66
  "semver": "^7.8.1",
67
67
  "vite": "^8.1.5",
68
68
  "zod": "^4.4.3",
69
- "@sanity/cli-core": "^2.5.1",
70
- "@sanity/workbench-cli": "^1.6.0"
69
+ "@sanity/cli-core": "^2.7.0",
70
+ "@sanity/workbench-cli": "^1.8.0"
71
71
  },
72
72
  "devDependencies": {
73
73
  "@eslint/compat": "^2.1.0",
@@ -86,13 +86,13 @@
86
86
  "eslint": "^10.7.0",
87
87
  "magic-string": "^0.30.21",
88
88
  "publint": "^0.3.21",
89
- "sanity": "^6.5.0",
89
+ "sanity": "^6.7.0",
90
90
  "styled-components": "^6.4.3",
91
91
  "typescript": "^6.0.3",
92
92
  "vitest": "^4.1.10",
93
93
  "@repo/package.config": "0.0.1",
94
94
  "@repo/tsconfig": "3.70.0",
95
- "@sanity/cli-test": "6.0.1",
95
+ "@sanity/cli-test": "8.0.0",
96
96
  "@sanity/eslint-config-cli": "^1.1.3"
97
97
  },
98
98
  "peerDependencies": {