@sanity/cli-build 5.3.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/_exports/_internal/build.d.ts +2 -2
  2. package/dist/_exports/_internal/extract.d.ts +13 -7
  3. package/dist/_exports/_internal/extract.js +1 -0
  4. package/dist/_exports/_internal/extract.js.map +1 -1
  5. package/dist/_exports/_internal/manifest.d.ts +179 -0
  6. package/dist/_exports/_internal/manifest.js +7 -0
  7. package/dist/_exports/_internal/manifest.js.map +1 -0
  8. package/dist/actions/build/buildStaticFiles.js.map +1 -1
  9. package/dist/actions/build/getViteConfig.js.map +1 -1
  10. package/dist/actions/build/renderDocumentWorker/getDocumentHtml.js +2 -1
  11. package/dist/actions/build/renderDocumentWorker/getDocumentHtml.js.map +1 -1
  12. package/dist/actions/build/writeSanityRuntime.js +1 -1
  13. package/dist/actions/build/writeSanityRuntime.js.map +1 -1
  14. package/dist/actions/manifest/blockTypeTransformer.js +67 -0
  15. package/dist/actions/manifest/blockTypeTransformer.js.map +1 -0
  16. package/dist/actions/manifest/debug.js +4 -0
  17. package/dist/actions/manifest/debug.js.map +1 -0
  18. package/dist/actions/manifest/extractCoreAppManifest.js +108 -0
  19. package/dist/actions/manifest/extractCoreAppManifest.js.map +1 -0
  20. package/dist/actions/manifest/extractManifest.js +42 -0
  21. package/dist/actions/manifest/extractManifest.js.map +1 -0
  22. package/dist/actions/manifest/extractManifest.worker.js +30 -0
  23. package/dist/actions/manifest/extractManifest.worker.js.map +1 -0
  24. package/dist/actions/manifest/extractWorkspaceManifest.js +72 -0
  25. package/dist/actions/manifest/extractWorkspaceManifest.js.map +1 -0
  26. package/dist/actions/manifest/iconResolver.js +36 -0
  27. package/dist/actions/manifest/iconResolver.js.map +1 -0
  28. package/dist/actions/manifest/purifyConfig.js +307 -0
  29. package/dist/actions/manifest/purifyConfig.js.map +1 -0
  30. package/dist/actions/manifest/referenceTransformer.js +51 -0
  31. package/dist/actions/manifest/referenceTransformer.js.map +1 -0
  32. package/dist/actions/manifest/resolveSchemaIcon.js +43 -0
  33. package/dist/actions/manifest/resolveSchemaIcon.js.map +1 -0
  34. package/dist/actions/manifest/sanitizeIcon.js +13 -0
  35. package/dist/actions/manifest/sanitizeIcon.js.map +1 -0
  36. package/dist/actions/manifest/schemaTypeHelpers.js +110 -0
  37. package/dist/actions/manifest/schemaTypeHelpers.js.map +1 -0
  38. package/dist/actions/manifest/schemaTypeTransformer.js +169 -0
  39. package/dist/actions/manifest/schemaTypeTransformer.js.map +1 -0
  40. package/dist/actions/manifest/transformerUtils.js +40 -0
  41. package/dist/actions/manifest/transformerUtils.js.map +1 -0
  42. package/dist/actions/manifest/types.js +13 -0
  43. package/dist/actions/manifest/types.js.map +1 -0
  44. package/dist/actions/manifest/validationTransformer.js +84 -0
  45. package/dist/actions/manifest/validationTransformer.js.map +1 -0
  46. package/dist/actions/manifest/writeManifestFile.js +29 -0
  47. package/dist/actions/manifest/writeManifestFile.js.map +1 -0
  48. package/dist/actions/manifest/writeWorkspaceFiles.js +30 -0
  49. package/dist/actions/manifest/writeWorkspaceFiles.js.map +1 -0
  50. package/dist/actions/schema/uploadSchemaToLexicon.js +91 -0
  51. package/dist/actions/schema/uploadSchemaToLexicon.js.map +1 -0
  52. package/package.json +17 -6
@@ -143,7 +143,7 @@ interface StaticBuildOptions {
143
143
  entry?: string;
144
144
  exposes?: WorkbenchExposes;
145
145
  isApp?: boolean;
146
- /** Workbench app (opted in via `unstable_defineApp`) — drives the federation build. */
146
+ /** Workbench app (opted in via `defineApplication`) — drives the federation build. */
147
147
  isWorkbenchApp?: boolean;
148
148
  minify?: boolean;
149
149
  profile?: boolean;
@@ -289,7 +289,7 @@ interface ViteOptions {
289
289
  exposes?: WorkbenchExposes;
290
290
  isApp?: boolean;
291
291
  /**
292
- * Whether this is a workbench app (opted in via `unstable_defineApp`). Drives
292
+ * Whether this is a workbench app (opted in via `defineApplication`). Drives
293
293
  * the module-federation build.
294
294
  */
295
295
  isWorkbenchApp?: boolean;
@@ -1,7 +1,7 @@
1
1
  import { ProjectRootResult } from "@sanity/cli-core/types";
2
2
  import { SchemaValidationProblemGroup } from "@sanity/types";
3
3
  import { extractSchema } from "@sanity/schema/_internal";
4
- import "zod/mini";
4
+ import { StudioManifest, Workspace } from "sanity";
5
5
  declare function getAggregatedSeverity(groupOrGroups: SchemaValidationProblemGroup | SchemaValidationProblemGroup[]): 'error' | 'warning';
6
6
  declare function formatSchemaValidation(validation: SchemaValidationProblemGroup[]): string;
7
7
  interface ExtractOptions {
@@ -38,12 +38,18 @@ declare function createSchemaPatternMatcher(patterns: string[]): {
38
38
  * Throws SchemaExtractionError on failure.
39
39
  */
40
40
  declare function runSchemaExtraction(extractOptions: Omit<ExtractOptions, 'watchPatterns'>): Promise<ReturnType<typeof extractSchema>>;
41
- /** @internal */
42
- interface ExtractSchemaWorkerError {
43
- error: string;
44
- type: 'error';
45
- validation?: SchemaValidationProblemGroup[];
41
+ interface UploadSchemaToLexiconOptions {
42
+ projectId: string;
43
+ workDir: string;
44
+ workspaces: Workspace[];
45
+ verbose?: boolean;
46
46
  }
47
+ /**
48
+ * Uploads the schemas to Lexicon and returns the studio manifest
49
+ * @param options - The options for the uploadSchemaToLexicon function
50
+ * @returns The studio manifest
51
+ */
52
+ declare function uploadSchemaToLexicon(options: UploadSchemaToLexiconOptions): Promise<StudioManifest | null>;
47
53
  /**
48
54
  * Extracts validation problem groups from a SchemaError.
49
55
  */
@@ -78,5 +84,5 @@ interface SchemaDeployTraceData {
78
84
  declare const SchemaExtractedTrace: import("@sanity/telemetry").DefinedTelemetryTrace<SchemaExtractedTraceAttributes, void>;
79
85
  declare const SchemaExtractionWatchModeTrace: import("@sanity/telemetry").DefinedTelemetryTrace<SchemaExtractionWatchModeAttributes, void>;
80
86
  declare const SchemaDeploy: import("@sanity/telemetry").DefinedTelemetryTrace<SchemaDeployTraceData, void>;
81
- export { type ExtractOptions, type ExtractSchemaWorkerError, SchemaDeploy, SchemaExtractedTrace, SchemaExtractionError, SchemaExtractionWatchModeTrace, createSchemaPatternMatcher, extractValidationFromSchemaError, formatSchemaValidation, getAggregatedSeverity, getExtractOptions, runSchemaExtraction };
87
+ export { type ExtractOptions, SchemaDeploy, SchemaExtractedTrace, SchemaExtractionError, SchemaExtractionWatchModeTrace, createSchemaPatternMatcher, extractValidationFromSchemaError, formatSchemaValidation, getAggregatedSeverity, getExtractOptions, runSchemaExtraction, uploadSchemaToLexicon };
82
88
  //# sourceMappingURL=extract.d.ts.map
@@ -2,6 +2,7 @@ export { formatSchemaValidation, getAggregatedSeverity } from '../../actions/sch
2
2
  export { getExtractOptions } from '../../actions/schema/getExtractOptions.js';
3
3
  export { createSchemaPatternMatcher } from '../../actions/schema/matchSchemaPattern.js';
4
4
  export { runSchemaExtraction } from '../../actions/schema/runSchemaExtraction.js';
5
+ export { uploadSchemaToLexicon } from '../../actions/schema/uploadSchemaToLexicon.js';
5
6
  export { extractValidationFromSchemaError } from '../../actions/schema/utils/extractValidationFromSchemaError.js';
6
7
  export { SchemaExtractionError } from '../../actions/schema/utils/SchemaExtractionError.js';
7
8
  export { SchemaDeploy, SchemaExtractedTrace, SchemaExtractionWatchModeTrace } from '../../telemetry/extractSchema.telemetry.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/_exports/_internal/extract.ts"],"sourcesContent":["export {\n formatSchemaValidation,\n getAggregatedSeverity,\n} from '../../actions/schema/formatSchemaValidation.js'\nexport {type ExtractOptions, getExtractOptions} from '../../actions/schema/getExtractOptions.js'\nexport {createSchemaPatternMatcher} from '../../actions/schema/matchSchemaPattern.js'\nexport {runSchemaExtraction} from '../../actions/schema/runSchemaExtraction.js'\nexport {type ExtractSchemaWorkerError} from '../../actions/schema/types.js'\nexport {extractValidationFromSchemaError} from '../../actions/schema/utils/extractValidationFromSchemaError.js'\nexport {SchemaExtractionError} from '../../actions/schema/utils/SchemaExtractionError.js'\nexport {\n SchemaDeploy,\n SchemaExtractedTrace,\n SchemaExtractionWatchModeTrace,\n} from '../../telemetry/extractSchema.telemetry.js'\n"],"names":["formatSchemaValidation","getAggregatedSeverity","getExtractOptions","createSchemaPatternMatcher","runSchemaExtraction","extractValidationFromSchemaError","SchemaExtractionError","SchemaDeploy","SchemaExtractedTrace","SchemaExtractionWatchModeTrace"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,qBAAqB,QAChB,iDAAgD;AACvD,SAA6BC,iBAAiB,QAAO,4CAA2C;AAChG,SAAQC,0BAA0B,QAAO,6CAA4C;AACrF,SAAQC,mBAAmB,QAAO,8CAA6C;AAE/E,SAAQC,gCAAgC,QAAO,iEAAgE;AAC/G,SAAQC,qBAAqB,QAAO,sDAAqD;AACzF,SACEC,YAAY,EACZC,oBAAoB,EACpBC,8BAA8B,QACzB,6CAA4C"}
1
+ {"version":3,"sources":["../../../src/_exports/_internal/extract.ts"],"sourcesContent":["export {\n formatSchemaValidation,\n getAggregatedSeverity,\n} from '../../actions/schema/formatSchemaValidation.js'\nexport {type ExtractOptions, getExtractOptions} from '../../actions/schema/getExtractOptions.js'\nexport {createSchemaPatternMatcher} from '../../actions/schema/matchSchemaPattern.js'\nexport {runSchemaExtraction} from '../../actions/schema/runSchemaExtraction.js'\nexport {uploadSchemaToLexicon} from '../../actions/schema/uploadSchemaToLexicon.js'\nexport {extractValidationFromSchemaError} from '../../actions/schema/utils/extractValidationFromSchemaError.js'\nexport {SchemaExtractionError} from '../../actions/schema/utils/SchemaExtractionError.js'\nexport {\n SchemaDeploy,\n SchemaExtractedTrace,\n SchemaExtractionWatchModeTrace,\n} from '../../telemetry/extractSchema.telemetry.js'\n"],"names":["formatSchemaValidation","getAggregatedSeverity","getExtractOptions","createSchemaPatternMatcher","runSchemaExtraction","uploadSchemaToLexicon","extractValidationFromSchemaError","SchemaExtractionError","SchemaDeploy","SchemaExtractedTrace","SchemaExtractionWatchModeTrace"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,qBAAqB,QAChB,iDAAgD;AACvD,SAA6BC,iBAAiB,QAAO,4CAA2C;AAChG,SAAQC,0BAA0B,QAAO,6CAA4C;AACrF,SAAQC,mBAAmB,QAAO,8CAA6C;AAC/E,SAAQC,qBAAqB,QAAO,gDAA+C;AACnF,SAAQC,gCAAgC,QAAO,iEAAgE;AAC/G,SAAQC,qBAAqB,QAAO,sDAAqD;AACzF,SACEC,YAAY,EACZC,oBAAoB,EACpBC,8BAA8B,QACzB,6CAA4C"}
@@ -0,0 +1,179 @@
1
+ import { SanityDocumentLike, Schema } from "@sanity/types";
2
+ import { MediaLibraryConfig, Workspace } from "sanity";
3
+ import "zod/mini";
4
+ import { CoreAppManifest, StudioManifest } from "@sanity/cli-core";
5
+ declare const SANITY_WORKSPACE_SCHEMA_ID_PREFIX = "_.schemas";
6
+ declare const CURRENT_WORKSPACE_SCHEMA_VERSION = "2025-05-01";
7
+ type ManifestSerializable = boolean | ManifestSerializable[] | number | string | {
8
+ [k: string]: ManifestSerializable;
9
+ };
10
+ interface CreateManifest {
11
+ createdAt: string;
12
+ studioVersion: string | null;
13
+ version: number;
14
+ workspaces: ManifestWorkspaceFile[];
15
+ }
16
+ interface ManifestWorkspaceFile extends Omit<CreateWorkspaceManifest, 'schema' | 'tools'> {
17
+ schema: string;
18
+ tools: string;
19
+ }
20
+ interface CreateWorkspaceManifest {
21
+ basePath: string;
22
+ dataset: string;
23
+ /**
24
+ * returns null in the case of the icon not being able to be stringified
25
+ */
26
+ icon: string | null;
27
+ name: string;
28
+ projectId: string;
29
+ schema: ManifestSchemaType[];
30
+ tools: ManifestTool[];
31
+ mediaLibrary?: MediaLibraryConfig;
32
+ subtitle?: string;
33
+ title?: string;
34
+ }
35
+ interface ManifestSchemaType {
36
+ name: string;
37
+ type: string;
38
+ deprecated?: {
39
+ reason: string;
40
+ };
41
+ fields?: ManifestField[];
42
+ fieldsets?: ManifestFieldset[];
43
+ hidden?: 'conditional' | boolean;
44
+ lists?: ManifestTitledValue[];
45
+ marks?: {
46
+ annotations?: ManifestArrayMember[];
47
+ decorators?: ManifestTitledValue[];
48
+ };
49
+ of?: ManifestArrayMember[];
50
+ options?: Record<string, ManifestSerializable>;
51
+ preview?: {
52
+ select: Record<string, string>;
53
+ };
54
+ readOnly?: 'conditional' | boolean;
55
+ styles?: ManifestTitledValue[];
56
+ title?: string;
57
+ to?: ManifestReferenceMember[];
58
+ validation?: ManifestValidationGroup[];
59
+ }
60
+ interface ManifestFieldset {
61
+ [index: string]: ManifestSerializable | undefined;
62
+ name: string;
63
+ title?: string;
64
+ }
65
+ interface ManifestTitledValue {
66
+ value: string;
67
+ title?: string;
68
+ }
69
+ type ManifestArrayMember = Omit<ManifestSchemaType, 'name'> & {
70
+ name?: string;
71
+ };
72
+ type ManifestReferenceMember = Omit<ManifestSchemaType, 'name'> & {
73
+ name?: string;
74
+ };
75
+ type ManifestField = ManifestSchemaType & {
76
+ fieldset?: string;
77
+ };
78
+ interface ManifestValidationGroup {
79
+ rules: ManifestValidationRule[];
80
+ level?: 'error' | 'info' | 'warning';
81
+ message?: string;
82
+ }
83
+ type ManifestValidationRule = {
84
+ [index: string]: ManifestSerializable | undefined;
85
+ constraint?: ManifestSerializable;
86
+ flag: string;
87
+ };
88
+ interface ManifestTool {
89
+ /**
90
+ * returns null in the case of the icon not being able to be stringified
91
+ */
92
+ icon: string | null;
93
+ name: string;
94
+ title: string;
95
+ type: string | null;
96
+ }
97
+ type DefaultWorkspaceSchemaId = `${typeof SANITY_WORKSPACE_SCHEMA_ID_PREFIX}.${string}`;
98
+ type PrefixedWorkspaceSchemaId = `${DefaultWorkspaceSchemaId}.${string}`;
99
+ type WorkspaceSchemaId = DefaultWorkspaceSchemaId | PrefixedWorkspaceSchemaId;
100
+ interface StoredWorkspaceSchema extends SanityDocumentLike {
101
+ _id: WorkspaceSchemaId;
102
+ _type: 'system.schema';
103
+ /**
104
+ * The API expects JSON coming in, but will store a string to save on attribute paths.
105
+ * Consumers must use JSON.parse on the value, but we deploy to the API using ManifestSchemaType[]
106
+ */
107
+ schema: ManifestSchemaType[] | string;
108
+ version: typeof CURRENT_WORKSPACE_SCHEMA_VERSION | undefined;
109
+ workspace: {
110
+ name: string;
111
+ title?: string;
112
+ };
113
+ tag?: string;
114
+ }
115
+ interface ExtractCoreAppManifestOptions {
116
+ workDir: string;
117
+ }
118
+ /**
119
+ * The title change a deploy would sync from the manifest to the user
120
+ * application, or null when the titles already match (or none is set).
121
+ *
122
+ * @internal
123
+ */
124
+ declare function resolveTitleUpdate(manifest: CoreAppManifest | undefined, application: {
125
+ title: string | null;
126
+ }): {
127
+ from: string | null;
128
+ to: string;
129
+ } | null;
130
+ /**
131
+ * Resolves app.icon from config (a file path) to a sanitized SVG string. Used
132
+ * both for the manifest and, on deploy, for the icon shipped to Brett — the
133
+ * manifest expects the SVG inline, not a path.
134
+ *
135
+ * The file is sanitized through the same allowlist as the studio manifest's
136
+ * icon resolver (see {@link lazySanitizeIcon}) so both manifest paths inline the
137
+ * same trusted subset of SVG markup.
138
+ * @internal
139
+ */
140
+ declare function readIconFromPath(workDir: string, iconPath: string): Promise<string>;
141
+ /**
142
+ * Unlike studio manifest extraction, skips schema/tool parsing. The config's
143
+ * `app.icon` is a file path; its content is read and inlined in the manifest.
144
+ */
145
+ declare function extractCoreAppManifest(options: ExtractCoreAppManifestOptions): Promise<CoreAppManifest | undefined>;
146
+ declare const MANIFEST_FILENAME = "create-manifest.json";
147
+ interface WriteManifestFileOptions {
148
+ /**
149
+ * Target directory for the manifest files. May be absolute or relative — relative
150
+ * paths are resolved against `workDir`.
151
+ */
152
+ outPath: string;
153
+ /**
154
+ * Studio root directory. Used to resolve a relative `outPath` and to look up the
155
+ * local `sanity` package version that gets stamped onto the manifest.
156
+ */
157
+ workDir: string;
158
+ /** Extracted workspace manifests to serialize alongside the top-level manifest. */
159
+ workspaceManifests: CreateWorkspaceManifest[];
160
+ }
161
+ declare function writeManifestFile({ outPath, workDir, workspaceManifests }: WriteManifestFileOptions): Promise<void>;
162
+ interface ExtractManifestOptions extends Pick<WriteManifestFileOptions, 'outPath' | 'workDir'> {
163
+ /** Absolute path to the studio's `sanity.config.(ts|js)` entry file. */
164
+ path: string;
165
+ }
166
+ declare function extractManifest({ outPath, path, workDir }: ExtractManifestOptions): Promise<void>;
167
+ /**
168
+ * Extracts manifest data from an array of workspaces
169
+ */
170
+ declare function extractWorkspaceManifest(workspaces: Workspace[], workDir: string): Promise<CreateWorkspaceManifest[]>;
171
+ /**
172
+ * Extracts all serializable properties from userland schema types,
173
+ * so they best-effort can be used as definitions for Schema.compile.
174
+ *
175
+ * @internal
176
+ */
177
+ declare function extractManifestSchemaTypes(schema: Schema, workDir: string): Promise<ManifestSchemaType[]>;
178
+ export { CURRENT_WORKSPACE_SCHEMA_VERSION, type CoreAppManifest, type CreateManifest, type CreateWorkspaceManifest, type DefaultWorkspaceSchemaId, MANIFEST_FILENAME, type ManifestSchemaType, SANITY_WORKSPACE_SCHEMA_ID_PREFIX, type StoredWorkspaceSchema, type StudioManifest, type WorkspaceSchemaId, extractCoreAppManifest, extractManifest, extractManifestSchemaTypes, extractWorkspaceManifest, readIconFromPath, resolveTitleUpdate, writeManifestFile };
179
+ //# sourceMappingURL=manifest.d.ts.map
@@ -0,0 +1,7 @@
1
+ export { extractCoreAppManifest, readIconFromPath, resolveTitleUpdate } from '../../actions/manifest/extractCoreAppManifest.js';
2
+ export { extractManifest } from '../../actions/manifest/extractManifest.js';
3
+ export { extractManifestSchemaTypes, extractWorkspaceManifest } from '../../actions/manifest/extractWorkspaceManifest.js';
4
+ export { CURRENT_WORKSPACE_SCHEMA_VERSION, SANITY_WORKSPACE_SCHEMA_ID_PREFIX } from '../../actions/manifest/types.js';
5
+ export { MANIFEST_FILENAME, writeManifestFile } from '../../actions/manifest/writeManifestFile.js';
6
+
7
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/_exports/_internal/manifest.ts"],"sourcesContent":["export {\n extractCoreAppManifest,\n readIconFromPath,\n resolveTitleUpdate,\n} from '../../actions/manifest/extractCoreAppManifest.js'\nexport {extractManifest} from '../../actions/manifest/extractManifest.js'\nexport {\n extractManifestSchemaTypes,\n extractWorkspaceManifest,\n} from '../../actions/manifest/extractWorkspaceManifest.js'\nexport {\n type CoreAppManifest,\n type CreateManifest,\n type CreateWorkspaceManifest,\n CURRENT_WORKSPACE_SCHEMA_VERSION,\n type DefaultWorkspaceSchemaId,\n type ManifestSchemaType,\n SANITY_WORKSPACE_SCHEMA_ID_PREFIX,\n type StoredWorkspaceSchema,\n type StudioManifest,\n type WorkspaceSchemaId,\n} from '../../actions/manifest/types.js'\nexport {MANIFEST_FILENAME, writeManifestFile} from '../../actions/manifest/writeManifestFile.js'\n"],"names":["extractCoreAppManifest","readIconFromPath","resolveTitleUpdate","extractManifest","extractManifestSchemaTypes","extractWorkspaceManifest","CURRENT_WORKSPACE_SCHEMA_VERSION","SANITY_WORKSPACE_SCHEMA_ID_PREFIX","MANIFEST_FILENAME","writeManifestFile"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,gBAAgB,EAChBC,kBAAkB,QACb,mDAAkD;AACzD,SAAQC,eAAe,QAAO,4CAA2C;AACzE,SACEC,0BAA0B,EAC1BC,wBAAwB,QACnB,qDAAoD;AAC3D,SAIEC,gCAAgC,EAGhCC,iCAAiC,QAI5B,kCAAiC;AACxC,SAAQC,iBAAiB,EAAEC,iBAAiB,QAAO,8CAA6C"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/buildStaticFiles.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {build, createBuilder} from 'vite'\n\nimport {copyDir} from '../../util/copyDir.js'\nimport {type AutoUpdatesBuildConfig} from './autoUpdates.js'\nimport {buildDebug} from './buildDebug.js'\nimport {\n getAppEnvironmentVariables,\n getStudioEnvironmentVariables,\n} from './getEnvironmentVariables.js'\nimport {extendViteConfigWithUserConfig, finalizeViteConfig, getViteConfig} from './getViteConfig.js'\nimport {writeFavicons} from './writeFavicons.js'\nimport {resolveEntries, writeSanityRuntime} from './writeSanityRuntime.js'\n\nexport interface ChunkModule {\n name: string\n renderedLength: number\n}\n\nexport interface ChunkStats {\n modules: ChunkModule[]\n name: string\n}\n\ninterface StaticBuildOptions {\n basePath: string\n cwd: string\n outputDir: string\n\n appTitle?: string\n autoUpdates?: AutoUpdatesBuildConfig\n entry?: string\n exposes?: WorkbenchExposes\n isApp?: boolean\n /** Workbench app (opted in via `unstable_defineApp`) — drives the federation build. */\n isWorkbenchApp?: boolean\n minify?: boolean\n profile?: boolean\n reactCompiler?: CliConfig['reactCompiler']\n schemaExtraction?: CliConfig['schemaExtraction']\n sourceMap?: boolean\n vite?: UserViteConfig\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Builds static files\n *\n * @internal\n */\nexport async function buildStaticFiles(\n options: StaticBuildOptions,\n): Promise<{chunks: ChunkStats[]}> {\n const {\n appTitle,\n autoUpdates,\n basePath,\n cwd,\n entry,\n exposes,\n isApp,\n isWorkbenchApp,\n minify = true,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap = false,\n vite: extendViteConfig,\n workbenchAppId,\n } = options\n\n const mode = 'production'\n\n /* Federation builds only produce the federation environment\n * (remote-entry, mf-manifest) — skip client-specific steps like\n * runtime generation, static file copies, and favicons.\n */\n if (isWorkbenchApp) {\n // A workbench remote can also serve itself standalone. When\n // `SANITY_INTERNAL_IS_WORKBENCH_REMOTE` is set, emit an SPA (index.html +\n // bootstrap + favicons) into the same `dist` as the federation output via a\n // dedicated `client` environment (see plugin-sanity-environment). Skipped for\n // a dock-only app (no `./App` to mount), matching `exposesApp` in plugin.ts.\n const emitSpa = process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true' && !(isApp && !entry)\n\n let entries: Awaited<ReturnType<typeof resolveEntries>>\n if (emitSpa) {\n buildDebug('Writing Sanity runtime files (workbench remote SPA)')\n ;({entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n reactStrictMode: false,\n watch: false,\n }))\n } else {\n buildDebug('Resolving entries for federation build')\n entries = await resolveEntries({cwd, entry, isApp, isWorkbenchApp})\n }\n\n buildDebug('Resolving vite config (federation)')\n let viteConfig = await getViteConfig({\n basePath,\n cwd,\n entries,\n exposes,\n getEnvironmentVariables,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n // Schema extraction is a build-time artifact, not a client-specific step,\n // so a federated studio extracts its schema like the legacy studio build.\n schemaExtraction,\n sourceMap,\n workbenchAppId,\n })\n\n // Apply the user's Vite config so plugins like `@vanilla-extract/vite-plugin`\n // transform source files before the federation environment is bundled.\n // `finalizeViteConfig` is intentionally skipped: the federation environment\n // has its own entry and does not use `.sanity/runtime/app.js`.\n if (extendViteConfig) {\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n }\n\n if (emitSpa) {\n const fromPath = path.join(cwd, 'static')\n const staticPath = path.join(outputDir, 'static')\n buildDebug(`Copying static files from ${fromPath} to output dir`)\n await copyDir(fromPath, staticPath)\n buildDebug('Writing favicons to output dir')\n const faviconBasePath = `${basePath.replace(/\\/+$/, '')}/static`\n await writeFavicons(faviconBasePath, staticPath)\n }\n\n buildDebug('Bundling federation environment')\n const builder = await createBuilder(viteConfig)\n await builder.buildApp()\n buildDebug('Bundling complete')\n // TODO: add stats here\n return {chunks: []}\n }\n\n buildDebug('Writing Sanity runtime files')\n const {entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n reactStrictMode: false,\n watch: false,\n })\n\n function getEnvironmentVariables() {\n return isApp\n ? getAppEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n : getStudioEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n }\n\n buildDebug('Resolving vite config')\n let viteConfig = await getViteConfig({\n autoUpdates,\n basePath,\n cwd,\n entries,\n getEnvironmentVariables,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n })\n\n if (extendViteConfig) {\n const defaultViteConfig = viteConfig\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n viteConfig = await finalizeViteConfig(viteConfig, defaultViteConfig)\n }\n\n const fromPath = path.join(cwd, 'static')\n // Copy files placed in /static to the built /static\n buildDebug(`Copying static files from ${fromPath} to output dir`)\n const staticPath = path.join(outputDir, 'static')\n await copyDir(fromPath, staticPath)\n\n // Write favicons, not overwriting ones that already exist, to static folder\n buildDebug('Writing favicons to output dir')\n const faviconBasePath = `${basePath.replace(/\\/+$/, '')}/static`\n await writeFavicons(faviconBasePath, staticPath)\n\n buildDebug('Bundling using vite')\n const bundle = await build(viteConfig)\n buildDebug('Bundling complete')\n\n // For typescript only - this shouldn't ever be the case given we're not watching\n if (Array.isArray(bundle) || !('output' in bundle)) {\n return {chunks: []}\n }\n\n const stats: ChunkStats[] = []\n for (const chunk of bundle.output) {\n if (chunk.type !== 'chunk') {\n continue\n }\n\n stats.push({\n modules: Object.entries(chunk.modules).map(([rawFilePath, chunkModule]) => {\n const filePath = rawFilePath.startsWith('\\u0000')\n ? rawFilePath.slice('\\u0000'.length)\n : rawFilePath\n\n return {\n name: path.isAbsolute(filePath) ? path.relative(cwd, filePath) : filePath,\n renderedLength: chunkModule.renderedLength,\n }\n }),\n name: chunk.name,\n })\n }\n\n return {chunks: stats}\n}\n"],"names":["path","build","createBuilder","copyDir","buildDebug","getAppEnvironmentVariables","getStudioEnvironmentVariables","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","writeFavicons","resolveEntries","writeSanityRuntime","buildStaticFiles","options","appTitle","autoUpdates","basePath","cwd","entry","exposes","isApp","isWorkbenchApp","minify","outputDir","reactCompiler","schemaExtraction","sourceMap","vite","extendViteConfig","workbenchAppId","mode","emitSpa","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","entries","reactStrictMode","watch","viteConfig","getEnvironmentVariables","command","fromPath","join","staticPath","faviconBasePath","replace","builder","buildApp","chunks","jsonEncode","prefix","defaultViteConfig","bundle","Array","isArray","stats","chunk","output","type","push","modules","Object","map","rawFilePath","chunkModule","filePath","startsWith","slice","length","name","isAbsolute","relative","renderedLength"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAI5B,SAAQC,KAAK,EAAEC,aAAa,QAAO,OAAM;AAEzC,SAAQC,OAAO,QAAO,wBAAuB;AAE7C,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SACEC,0BAA0B,EAC1BC,6BAA6B,QACxB,+BAA8B;AACrC,SAAQC,8BAA8B,EAAEC,kBAAkB,EAAEC,aAAa,QAAO,qBAAoB;AACpG,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,cAAc,EAAEC,kBAAkB,QAAO,0BAAyB;AAkC1E;;;;CAIC,GACD,OAAO,eAAeC,iBACpBC,OAA2B;IAE3B,MAAM,EACJC,QAAQ,EACRC,WAAW,EACXC,QAAQ,EACRC,GAAG,EACHC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,cAAc,EACdC,SAAS,IAAI,EACbC,SAAS,EACTC,aAAa,EACbC,gBAAgB,EAChBC,YAAY,KAAK,EACjBC,MAAMC,gBAAgB,EACtBC,cAAc,EACf,GAAGhB;IAEJ,MAAMiB,OAAO;IAEb;;;GAGC,GACD,IAAIT,gBAAgB;QAClB,4DAA4D;QAC5D,0EAA0E;QAC1E,4EAA4E;QAC5E,8EAA8E;QAC9E,6EAA6E;QAC7E,MAAMU,UAAUC,QAAQC,GAAG,CAACC,mCAAmC,KAAK,UAAU,CAAEd,CAAAA,SAAS,CAACF,KAAI;QAE9F,IAAIiB;QACJ,IAA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,YAAYI,KAAK,CAAC,SAASC,MAAM,IACjCL;gBAEJ,OAAO;oBACLM,MAAMtE,KAAKuE,UAAU,CAACL,YAAYlE,KAAKwE,QAAQ,CAACtD,KAAKgD,YAAYA;oBACjEO,gBAAgBR,YAAYQ,cAAc;gBAC5C;YACF;YACAH,MAAMb,MAAMa,IAAI;QAClB;IACF;IAEA,OAAO;QAACrB,QAAQO;IAAK;AACvB"}
1
+ {"version":3,"sources":["../../../src/actions/build/buildStaticFiles.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {type WorkbenchExposes} from '@sanity/workbench-cli/build'\nimport {build, createBuilder} from 'vite'\n\nimport {copyDir} from '../../util/copyDir.js'\nimport {type AutoUpdatesBuildConfig} from './autoUpdates.js'\nimport {buildDebug} from './buildDebug.js'\nimport {\n getAppEnvironmentVariables,\n getStudioEnvironmentVariables,\n} from './getEnvironmentVariables.js'\nimport {extendViteConfigWithUserConfig, finalizeViteConfig, getViteConfig} from './getViteConfig.js'\nimport {writeFavicons} from './writeFavicons.js'\nimport {resolveEntries, writeSanityRuntime} from './writeSanityRuntime.js'\n\nexport interface ChunkModule {\n name: string\n renderedLength: number\n}\n\nexport interface ChunkStats {\n modules: ChunkModule[]\n name: string\n}\n\ninterface StaticBuildOptions {\n basePath: string\n cwd: string\n outputDir: string\n\n appTitle?: string\n autoUpdates?: AutoUpdatesBuildConfig\n entry?: string\n exposes?: WorkbenchExposes\n isApp?: boolean\n /** Workbench app (opted in via `defineApplication`) — drives the federation build. */\n isWorkbenchApp?: boolean\n minify?: boolean\n profile?: boolean\n reactCompiler?: CliConfig['reactCompiler']\n schemaExtraction?: CliConfig['schemaExtraction']\n sourceMap?: boolean\n vite?: UserViteConfig\n /** The workbench app's bus identity (`__SANITY_APP_ID__`). */\n workbenchAppId?: string\n}\n\n/**\n * Builds static files\n *\n * @internal\n */\nexport async function buildStaticFiles(\n options: StaticBuildOptions,\n): Promise<{chunks: ChunkStats[]}> {\n const {\n appTitle,\n autoUpdates,\n basePath,\n cwd,\n entry,\n exposes,\n isApp,\n isWorkbenchApp,\n minify = true,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap = false,\n vite: extendViteConfig,\n workbenchAppId,\n } = options\n\n const mode = 'production'\n\n /* Federation builds only produce the federation environment\n * (remote-entry, mf-manifest) — skip client-specific steps like\n * runtime generation, static file copies, and favicons.\n */\n if (isWorkbenchApp) {\n // A workbench remote can also serve itself standalone. When\n // `SANITY_INTERNAL_IS_WORKBENCH_REMOTE` is set, emit an SPA (index.html +\n // bootstrap + favicons) into the same `dist` as the federation output via a\n // dedicated `client` environment (see plugin-sanity-environment). Skipped for\n // a dock-only app (no `./App` to mount), matching `exposesApp` in plugin.ts.\n const emitSpa = process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true' && !(isApp && !entry)\n\n let entries: Awaited<ReturnType<typeof resolveEntries>>\n if (emitSpa) {\n buildDebug('Writing Sanity runtime files (workbench remote SPA)')\n ;({entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n reactStrictMode: false,\n watch: false,\n }))\n } else {\n buildDebug('Resolving entries for federation build')\n entries = await resolveEntries({cwd, entry, isApp, isWorkbenchApp})\n }\n\n buildDebug('Resolving vite config (federation)')\n let viteConfig = await getViteConfig({\n basePath,\n cwd,\n entries,\n exposes,\n getEnvironmentVariables,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n // Schema extraction is a build-time artifact, not a client-specific step,\n // so a federated studio extracts its schema like the legacy studio build.\n schemaExtraction,\n sourceMap,\n workbenchAppId,\n })\n\n // Apply the user's Vite config so plugins like `@vanilla-extract/vite-plugin`\n // transform source files before the federation environment is bundled.\n // `finalizeViteConfig` is intentionally skipped: the federation environment\n // has its own entry and does not use `.sanity/runtime/app.js`.\n if (extendViteConfig) {\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n }\n\n if (emitSpa) {\n const fromPath = path.join(cwd, 'static')\n const staticPath = path.join(outputDir, 'static')\n buildDebug(`Copying static files from ${fromPath} to output dir`)\n await copyDir(fromPath, staticPath)\n buildDebug('Writing favicons to output dir')\n const faviconBasePath = `${basePath.replace(/\\/+$/, '')}/static`\n await writeFavicons(faviconBasePath, staticPath)\n }\n\n buildDebug('Bundling federation environment')\n const builder = await createBuilder(viteConfig)\n await builder.buildApp()\n buildDebug('Bundling complete')\n // TODO: add stats here\n return {chunks: []}\n }\n\n buildDebug('Writing Sanity runtime files')\n const {entries} = await writeSanityRuntime({\n appTitle,\n basePath,\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n reactStrictMode: false,\n watch: false,\n })\n\n function getEnvironmentVariables() {\n return isApp\n ? getAppEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n : getStudioEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n }\n\n buildDebug('Resolving vite config')\n let viteConfig = await getViteConfig({\n autoUpdates,\n basePath,\n cwd,\n entries,\n getEnvironmentVariables,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n sourceMap,\n })\n\n if (extendViteConfig) {\n const defaultViteConfig = viteConfig\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'build', mode},\n viteConfig,\n extendViteConfig,\n )\n viteConfig = await finalizeViteConfig(viteConfig, defaultViteConfig)\n }\n\n const fromPath = path.join(cwd, 'static')\n // Copy files placed in /static to the built /static\n buildDebug(`Copying static files from ${fromPath} to output dir`)\n const staticPath = path.join(outputDir, 'static')\n await copyDir(fromPath, staticPath)\n\n // Write favicons, not overwriting ones that already exist, to static folder\n buildDebug('Writing favicons to output dir')\n const faviconBasePath = `${basePath.replace(/\\/+$/, '')}/static`\n await writeFavicons(faviconBasePath, staticPath)\n\n buildDebug('Bundling using vite')\n const bundle = await build(viteConfig)\n buildDebug('Bundling complete')\n\n // For typescript only - this shouldn't ever be the case given we're not watching\n if (Array.isArray(bundle) || !('output' in bundle)) {\n return {chunks: []}\n }\n\n const stats: ChunkStats[] = []\n for (const chunk of bundle.output) {\n if (chunk.type !== 'chunk') {\n continue\n }\n\n stats.push({\n modules: Object.entries(chunk.modules).map(([rawFilePath, chunkModule]) => {\n const filePath = rawFilePath.startsWith('\\u0000')\n ? rawFilePath.slice('\\u0000'.length)\n : rawFilePath\n\n return {\n name: path.isAbsolute(filePath) ? path.relative(cwd, filePath) : filePath,\n renderedLength: chunkModule.renderedLength,\n }\n }),\n name: chunk.name,\n })\n }\n\n return {chunks: stats}\n}\n"],"names":["path","build","createBuilder","copyDir","buildDebug","getAppEnvironmentVariables","getStudioEnvironmentVariables","extendViteConfigWithUserConfig","finalizeViteConfig","getViteConfig","writeFavicons","resolveEntries","writeSanityRuntime","buildStaticFiles","options","appTitle","autoUpdates","basePath","cwd","entry","exposes","isApp","isWorkbenchApp","minify","outputDir","reactCompiler","schemaExtraction","sourceMap","vite","extendViteConfig","workbenchAppId","mode","emitSpa","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","entries","reactStrictMode","watch","viteConfig","getEnvironmentVariables","command","fromPath","join","staticPath","faviconBasePath","replace","builder","buildApp","chunks","jsonEncode","prefix","defaultViteConfig","bundle","Array","isArray","stats","chunk","output","type","push","modules","Object","map","rawFilePath","chunkModule","filePath","startsWith","slice","length","name","isAbsolute","relative","renderedLength"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAI5B,SAAQC,KAAK,EAAEC,aAAa,QAAO,OAAM;AAEzC,SAAQC,OAAO,QAAO,wBAAuB;AAE7C,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SACEC,0BAA0B,EAC1BC,6BAA6B,QACxB,+BAA8B;AACrC,SAAQC,8BAA8B,EAAEC,kBAAkB,EAAEC,aAAa,QAAO,qBAAoB;AACpG,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,cAAc,E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,GAAG5B,SAAS6B,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC;IAChE,MAAMpC,cAAcmC,iBAAiBD;IAErCxC,WAAW;IACX,MAAMiD,SAAS,MAAMpD,MAAMsC;IAC3BnC,WAAW;IAEX,iFAAiF;IACjF,IAAIkD,MAAMC,OAAO,CAACF,WAAW,CAAE,CAAA,YAAYA,MAAK,GAAI;QAClD,OAAO;YAACJ,QAAQ,EAAE;QAAA;IACpB;IAEA,MAAMO,QAAsB,EAAE;IAC9B,KAAK,MAAMC,SAASJ,OAAOK,MAAM,CAAE;QACjC,IAAID,MAAME,IAAI,KAAK,SAAS;YAC1B;QACF;QAEAH,MAAMI,IAAI,CAAC;YACTC,SAASC,OAAO1B,OAAO,CAACqB,MAAMI,OAAO,EAAEE,GAAG,CAAC,CAAC,CAACC,aAAaC,YAAY;gBACpE,MAAMC,WAAWF,YAAYG,UAAU,CAAC,YACpCH,YAAYI,KAAK,CAAC,SAASC,MAAM,IACjCL;gBAEJ,OAAO;oBACLM,MAAMtE,KAAKuE,UAAU,CAACL,YAAYlE,KAAKwE,QAAQ,CAACtD,KAAKgD,YAAYA;oBACjEO,gBAAgBR,YAAYQ,cAAc;gBAC5C;YACF;YACAH,MAAMb,MAAMa,IAAI;QAClB;IACF;IAEA,OAAO;QAACrB,QAAQO;IAAK;AACvB"}
@@ -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 ReactCompilerConfig, 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 {\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 {buildDebug} from './buildDebug.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: CliConfig['reactCompiler']\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 ...getReactPlugins(reactCompiler),\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\n/**\n * The React plugin(s) for the given `reactCompiler` configuration.\n *\n * With the (default) babel transform the compiler runs as a babel preset\n * next to a plain `viteReact()`. With the experimental oxc transform,\n * `viteReact`'s `compiler` option lets `oxc-transform-react` own the React\n * Compiler, TypeScript/JSX and Fast Refresh transforms in one pass. The\n * `transform` discriminator is stripped so neither compiler receives an\n * option it does not know.\n */\nfunction getReactPlugins(reactCompiler: CliConfig['reactCompiler']): PluginOption[] {\n const config: ReactCompilerConfig | undefined =\n reactCompiler === true ? {} : reactCompiler || undefined\n\n if (!config) {\n return [viteReact()]\n }\n\n if (config.transform === 'oxc') {\n const {transform, ...compilerOptions} = config\n return [viteReact({compiler: compilerOptions})]\n }\n\n const {transform, ...compilerOptions} = config\n return [viteReact(), babel({presets: [reactCompilerPreset(compilerOptions)]})]\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 buildDebug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n buildDebug('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","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","buildDebug","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","getReactPlugins","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","config","undefined","transform","compilerOptions","compiler","presets","warning","warn","suppressUnusedImport","code","names","includes","n","length","ids","every","id","finalizeViteConfig","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;AACnE,SAEEC,wBAAwB,EAExBC,WAAW,QAIN,OAAM;AAEb,SAAQC,gBAAgB,QAAO,qBAAoB;AACnD,SAAQC,4BAA4B,QAAO,6CAA4C;AAEvF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,UAAU,QAAO,iBAAgB;AACzC,SAAQC,2BAA2B,QAAO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5E,IAAIA,QAAQG,IAAI,KAAK,0BAA0B,OAAO;IAEtD,YAAY;IACZ,MAAM;IACN,4DAA4D;IAC5D,MAAM;IACN,IAAIH,QAAQI,KAAK,EAAEC,SAAS,kBAAkB;QAC5CL,QAAQI,KAAK,GAAGJ,QAAQI,KAAK,CAAC1C,MAAM,CAAC,CAAC4C,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,mBACpBjB,MAAoB,EACpBkB,aAA2B;IAE3B,IAAI,OAAOlB,OAAOpE,KAAK,EAAEuD,iBAAiBC,UAAU,UAAU;QAC5D,MAAM,IAAI+B,UACR;IAEJ;IAEA,IAAI,CAACnB,OAAO1C,IAAI,EAAE;QAChB,MAAM,IAAI8D,MACR;IAEJ;IAEA,OAAO3I,YAAYuH,QAAQ;QACzBpE,OAAO;YACLuD,iBAAiB+B,cAActF,KAAK,EAAEuD,mBAAmB,CAAC;QAC5D;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAekC,+BACpB3E,GAAc,EACdwE,aAA2B,EAC3BI,UAA0B;IAE1B,IAAItB,SAASkB;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpC1I,WAAW;QACXoH,SAAS,MAAMsB,WAAWtB,QAAQtD;IACpC,OAAO,IAAI,OAAO4E,eAAe,UAAU;QACzC1I,WAAW;QACXoH,SAASvH,YAAYuH,QAAQsB;IAC/B;IAEA,OAAOtB;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 ReactCompilerConfig, 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 {\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 {buildDebug} from './buildDebug.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: CliConfig['reactCompiler']\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 `defineApplication`). 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 ...getReactPlugins(reactCompiler),\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\n/**\n * The React plugin(s) for the given `reactCompiler` configuration.\n *\n * With the (default) babel transform the compiler runs as a babel preset\n * next to a plain `viteReact()`. With the experimental oxc transform,\n * `viteReact`'s `compiler` option lets `oxc-transform-react` own the React\n * Compiler, TypeScript/JSX and Fast Refresh transforms in one pass. The\n * `transform` discriminator is stripped so neither compiler receives an\n * option it does not know.\n */\nfunction getReactPlugins(reactCompiler: CliConfig['reactCompiler']): PluginOption[] {\n const config: ReactCompilerConfig | undefined =\n reactCompiler === true ? {} : reactCompiler || undefined\n\n if (!config) {\n return [viteReact()]\n }\n\n if (config.transform === 'oxc') {\n const {transform, ...compilerOptions} = config\n return [viteReact({compiler: compilerOptions})]\n }\n\n const {transform, ...compilerOptions} = config\n return [viteReact(), babel({presets: [reactCompilerPreset(compilerOptions)]})]\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 buildDebug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n buildDebug('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","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","buildDebug","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","getReactPlugins","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","config","undefined","transform","compilerOptions","compiler","presets","warning","warn","suppressUnusedImport","code","names","includes","n","length","ids","every","id","finalizeViteConfig","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,8B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,SAAS,MAAMsB,WAAWtB,QAAQtD;IACpC,OAAO,IAAI,OAAO4E,eAAe,UAAU;QACzC1I,WAAW;QACXoH,SAASvH,YAAYuH,QAAQsB;IAC/B;IAEA,OAAOtB;AACT"}
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { renderToStaticMarkup } from 'react-dom/server';
2
+ import { resolveLocalPackage } from '@sanity/cli-core/package-manager';
3
3
  import { buildDebug } from '../buildDebug.js';
4
4
  import { addTimestampedImportMapScriptToHtml } from './addTimestampImportMapScriptToHtml.js';
5
5
  import { getDocumentComponent } from './getDocumentComponent.js';
@@ -29,6 +29,7 @@ import { getDocumentComponent } from './getDocumentComponent.js';
29
29
  * @internal
30
30
  */ export async function getDocumentHtml(parent, studioRootPath, props, importMap, isApp, autoUpdatesCssUrls) {
31
31
  const Document = await getDocumentComponent(parent, studioRootPath, isApp);
32
+ const { renderToStaticMarkup } = await resolveLocalPackage('react-dom/server', studioRootPath);
32
33
  const defaultProps = {
33
34
  entryPath: './.sanity/runtime/app.js'
34
35
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/renderDocumentWorker/getDocumentHtml.tsx"],"sourcesContent":["import {type MessagePort} from 'node:worker_threads'\n\nimport {renderToStaticMarkup} from 'react-dom/server'\n\nimport {buildDebug} from '../buildDebug.js'\nimport {addTimestampedImportMapScriptToHtml} from './addTimestampImportMapScriptToHtml.js'\nimport {getDocumentComponent} from './getDocumentComponent.js'\nimport {type DocumentProps} from './types.js'\n\n/**\n * Adds a base path to a URL if necessary, and returns the resulting URL.\n * @param url - The URL to prefix with a base path.\n * @param basePath - The base path to prefix the URL with. Default value is `/`.\n * @returns The resulting URL with the base path.\n * @internal\n */\nfunction _prefixUrlWithBasePath(url: string, basePath: string): string {\n // Normalize basePath by adding a leading slash if it's missing.\n const normalizedBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`\n\n // If the URL starts with a slash, append it to the basePath, removing any trailing slash if present.\n if (url.startsWith('/')) {\n if (normalizedBasePath.endsWith('/')) {\n return `${normalizedBasePath.slice(0, -1)}${url}`\n }\n return `${normalizedBasePath}${url}`\n }\n\n // If the URL doesn't start with a slash, append it to the basePath with a slash in between.\n if (normalizedBasePath.endsWith('/')) {\n return `${normalizedBasePath}${url}`\n }\n return `${normalizedBasePath}/${url}`\n}\n\n/**\n * @internal\n */\nexport async function getDocumentHtml(\n parent: MessagePort,\n studioRootPath: string,\n props?: DocumentProps,\n importMap?: {imports?: Record<string, string>},\n isApp?: boolean,\n autoUpdatesCssUrls?: string[],\n): Promise<string> {\n const Document = await getDocumentComponent(parent, studioRootPath, isApp)\n\n const defaultProps = {\n entryPath: './.sanity/runtime/app.js',\n }\n\n // NOTE: Validate the list of CSS paths so implementers of `_document.tsx` don't have to\n // - If the path is not a full URL, check if it starts with `/`\n // - If not, then prepend a `/` to the string\n const css = props?.css?.map((url) => {\n try {\n // If the URL is absolute, we don't need to prefix it\n return new URL(url).toString()\n } catch {\n return _prefixUrlWithBasePath(url, props.basePath)\n }\n })\n\n buildDebug('Rendering document component using React')\n const result = addTimestampedImportMapScriptToHtml(\n renderToStaticMarkup(<Document {...defaultProps} {...props} css={css} />),\n importMap,\n autoUpdatesCssUrls,\n )\n\n return `<!DOCTYPE html>${result}`\n}\n"],"names":["renderToStaticMarkup","buildDebug","addTimestampedImportMapScriptToHtml","getDocumentComponent","_prefixUrlWithBasePath","url","basePath","normalizedBasePath","startsWith","endsWith","slice","getDocumentHtml","parent","studioRootPath","props","importMap","isApp","autoUpdatesCssUrls","Document","defaultProps","entryPath","css","map","URL","toString","result"],"mappings":";AAEA,SAAQA,oBAAoB,QAAO,mBAAkB;AAErD,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,mCAAmC,QAAO,yCAAwC;AAC1F,SAAQC,oBAAoB,QAAO,4BAA2B;AAG9D;;;;;;CAMC,GACD,SAASC,uBAAuBC,GAAW,EAAEC,QAAgB;IAC3D,gEAAgE;IAChE,MAAMC,qBAAqBD,SAASE,UAAU,CAAC,OAAOF,WAAW,CAAC,CAAC,EAAEA,UAAU;IAE/E,qGAAqG;IACrG,IAAID,IAAIG,UAAU,CAAC,MAAM;QACvB,IAAID,mBAAmBE,QAAQ,CAAC,MAAM;YACpC,OAAO,GAAGF,mBAAmBG,KAAK,CAAC,GAAG,CAAC,KAAKL,KAAK;QACnD;QACA,OAAO,GAAGE,qBAAqBF,KAAK;IACtC;IAEA,4FAA4F;IAC5F,IAAIE,mBAAmBE,QAAQ,CAAC,MAAM;QACpC,OAAO,GAAGF,qBAAqBF,KAAK;IACtC;IACA,OAAO,GAAGE,mBAAmB,CAAC,EAAEF,KAAK;AACvC;AAEA;;CAEC,GACD,OAAO,eAAeM,gBACpBC,MAAmB,EACnBC,cAAsB,EACtBC,KAAqB,EACrBC,SAA8C,EAC9CC,KAAe,EACfC,kBAA6B;IAE7B,MAAMC,WAAW,MAAMf,qBAAqBS,QAAQC,gBAAgBG;IAEpE,MAAMG,eAAe;QACnBC,WAAW;IACb;IAEA,wFAAwF;IACxF,+DAA+D;IAC/D,+CAA+C;IAC/C,MAAMC,MAAMP,OAAOO,KAAKC,IAAI,CAACjB;QAC3B,IAAI;YACF,qDAAqD;YACrD,OAAO,IAAIkB,IAAIlB,KAAKmB,QAAQ;QAC9B,EAAE,OAAM;YACN,OAAOpB,uBAAuBC,KAAKS,MAAMR,QAAQ;QACnD;IACF;IAEAL,WAAW;IACX,MAAMwB,SAASvB,oCACbF,mCAAqB,KAACkB;QAAU,GAAGC,YAAY;QAAG,GAAGL,KAAK;QAAEO,KAAKA;SACjEN,WACAE;IAGF,OAAO,CAAC,eAAe,EAAEQ,QAAQ;AACnC"}
1
+ {"version":3,"sources":["../../../../src/actions/build/renderDocumentWorker/getDocumentHtml.tsx"],"sourcesContent":["import {type MessagePort} from 'node:worker_threads'\n\nimport {resolveLocalPackage} from '@sanity/cli-core/package-manager'\n\nimport {buildDebug} from '../buildDebug.js'\nimport {addTimestampedImportMapScriptToHtml} from './addTimestampImportMapScriptToHtml.js'\nimport {getDocumentComponent} from './getDocumentComponent.js'\nimport {type DocumentProps} from './types.js'\n\n/**\n * Adds a base path to a URL if necessary, and returns the resulting URL.\n * @param url - The URL to prefix with a base path.\n * @param basePath - The base path to prefix the URL with. Default value is `/`.\n * @returns The resulting URL with the base path.\n * @internal\n */\nfunction _prefixUrlWithBasePath(url: string, basePath: string): string {\n // Normalize basePath by adding a leading slash if it's missing.\n const normalizedBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`\n\n // If the URL starts with a slash, append it to the basePath, removing any trailing slash if present.\n if (url.startsWith('/')) {\n if (normalizedBasePath.endsWith('/')) {\n return `${normalizedBasePath.slice(0, -1)}${url}`\n }\n return `${normalizedBasePath}${url}`\n }\n\n // If the URL doesn't start with a slash, append it to the basePath with a slash in between.\n if (normalizedBasePath.endsWith('/')) {\n return `${normalizedBasePath}${url}`\n }\n return `${normalizedBasePath}/${url}`\n}\n\n/**\n * @internal\n */\nexport async function getDocumentHtml(\n parent: MessagePort,\n studioRootPath: string,\n props?: DocumentProps,\n importMap?: {imports?: Record<string, string>},\n isApp?: boolean,\n autoUpdatesCssUrls?: string[],\n): Promise<string> {\n const Document = await getDocumentComponent(parent, studioRootPath, isApp)\n const {renderToStaticMarkup} = await resolveLocalPackage<typeof import('react-dom/server')>(\n 'react-dom/server',\n studioRootPath,\n )\n\n const defaultProps = {\n entryPath: './.sanity/runtime/app.js',\n }\n\n // NOTE: Validate the list of CSS paths so implementers of `_document.tsx` don't have to\n // - If the path is not a full URL, check if it starts with `/`\n // - If not, then prepend a `/` to the string\n const css = props?.css?.map((url) => {\n try {\n // If the URL is absolute, we don't need to prefix it\n return new URL(url).toString()\n } catch {\n return _prefixUrlWithBasePath(url, props.basePath)\n }\n })\n\n buildDebug('Rendering document component using React')\n const result = addTimestampedImportMapScriptToHtml(\n renderToStaticMarkup(<Document {...defaultProps} {...props} css={css} />),\n importMap,\n autoUpdatesCssUrls,\n )\n\n return `<!DOCTYPE html>${result}`\n}\n"],"names":["resolveLocalPackage","buildDebug","addTimestampedImportMapScriptToHtml","getDocumentComponent","_prefixUrlWithBasePath","url","basePath","normalizedBasePath","startsWith","endsWith","slice","getDocumentHtml","parent","studioRootPath","props","importMap","isApp","autoUpdatesCssUrls","Document","renderToStaticMarkup","defaultProps","entryPath","css","map","URL","toString","result"],"mappings":";AAEA,SAAQA,mBAAmB,QAAO,mCAAkC;AAEpE,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,mCAAmC,QAAO,yCAAwC;AAC1F,SAAQC,oBAAoB,QAAO,4BAA2B;AAG9D;;;;;;CAMC,GACD,SAASC,uBAAuBC,GAAW,EAAEC,QAAgB;IAC3D,gEAAgE;IAChE,MAAMC,qBAAqBD,SAASE,UAAU,CAAC,OAAOF,WAAW,CAAC,CAAC,EAAEA,UAAU;IAE/E,qGAAqG;IACrG,IAAID,IAAIG,UAAU,CAAC,MAAM;QACvB,IAAID,mBAAmBE,QAAQ,CAAC,MAAM;YACpC,OAAO,GAAGF,mBAAmBG,KAAK,CAAC,GAAG,CAAC,KAAKL,KAAK;QACnD;QACA,OAAO,GAAGE,qBAAqBF,KAAK;IACtC;IAEA,4FAA4F;IAC5F,IAAIE,mBAAmBE,QAAQ,CAAC,MAAM;QACpC,OAAO,GAAGF,qBAAqBF,KAAK;IACtC;IACA,OAAO,GAAGE,mBAAmB,CAAC,EAAEF,KAAK;AACvC;AAEA;;CAEC,GACD,OAAO,eAAeM,gBACpBC,MAAmB,EACnBC,cAAsB,EACtBC,KAAqB,EACrBC,SAA8C,EAC9CC,KAAe,EACfC,kBAA6B;IAE7B,MAAMC,WAAW,MAAMf,qBAAqBS,QAAQC,gBAAgBG;IACpE,MAAM,EAACG,oBAAoB,EAAC,GAAG,MAAMnB,oBACnC,oBACAa;IAGF,MAAMO,eAAe;QACnBC,WAAW;IACb;IAEA,wFAAwF;IACxF,+DAA+D;IAC/D,+CAA+C;IAC/C,MAAMC,MAAMR,OAAOQ,KAAKC,IAAI,CAAClB;QAC3B,IAAI;YACF,qDAAqD;YACrD,OAAO,IAAImB,IAAInB,KAAKoB,QAAQ;QAC9B,EAAE,OAAM;YACN,OAAOrB,uBAAuBC,KAAKS,MAAMR,QAAQ;QACnD;IACF;IAEAL,WAAW;IACX,MAAMyB,SAASxB,oCACbiB,mCAAqB,KAACD;QAAU,GAAGE,YAAY;QAAG,GAAGN,KAAK;QAAEQ,KAAKA;SACjEP,WACAE;IAGF,OAAO,CAAC,eAAe,EAAES,QAAQ;AACnC"}
@@ -81,7 +81,7 @@ import { renderDocument } from './renderDocument.js';
81
81
  const studioConfigPath = await tryFindStudioConfigPath(cwd);
82
82
  relativeConfigLocation = studioConfigPath ? toForwardSlashes(path.relative(runtimeDir, studioConfigPath)) : null;
83
83
  }
84
- // Only a *branded* app (`unstable_defineApp`) that declares no `entry` has no
84
+ // Only a *branded* app (`defineApplication`) that declares no `entry` has no
85
85
  // navigable app view (sanity-io/workbench spec 002-workbench-extension-api,
86
86
  // US5): `null` entry tells the runtime/federation to skip the `./App` render
87
87
  // path. Non-branded (legacy SDK) apps keep the historical `./src/App` default,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/writeSanityRuntime.ts"],"sourcesContent":["import {mkdir, writeFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {tryFindStudioConfigPath} from '@sanity/cli-core/config'\nimport {watch as chokidarWatch, type FSWatcher} from 'chokidar'\n\nimport {buildDebug} from './buildDebug.js'\nimport {decorateIndexWithAutoGeneratedWarning} from './decorateIndexWithAutoGeneratedWarning.js'\nimport {decorateIndexWithBridgeScript} from './decorateIndexWithBridgeScript.js'\nimport {decorateIndexWithStagingScript} from './decorateIndexWithStagingScript.js'\nimport {getEntryModule} from './getEntryModule.js'\nimport {getPossibleDocumentComponentLocations} from './getPossibleDocumentComponentLocations.js'\nimport {renderDocument} from './renderDocument.js'\n\ninterface RuntimeOptions {\n cwd: string\n reactStrictMode: boolean | undefined\n watch: boolean\n\n appTitle?: string\n basePath?: string\n entry?: string\n isApp?: boolean\n isWorkbenchApp?: boolean\n}\n\n/**\n * Generates the `.sanity/runtime` directory, and optionally watches for custom\n * document files, rebuilding when they change\n *\n * @param options - Current working directory (Sanity root dir), and whether or not to watch\n * @returns A watcher instance if watch is enabled, undefined otherwise\n * @internal\n */\nexport async function writeSanityRuntime(options: RuntimeOptions): Promise<{\n entries: {relativeConfigLocation: string | null; relativeEntry: string | null}\n watcher: FSWatcher | undefined\n}> {\n const {appTitle, basePath, cwd, entry, isApp, isWorkbenchApp, reactStrictMode, watch} = options\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n\n buildDebug('Making runtime directory')\n await mkdir(runtimeDir, {recursive: true})\n\n async function renderAndWriteDocument() {\n buildDebug('Rendering document template')\n const indexHtml = decorateIndexWithStagingScript(\n decorateIndexWithBridgeScript(\n decorateIndexWithAutoGeneratedWarning(\n await renderDocument({\n isApp,\n props: {\n basePath: basePath || '/',\n entryPath: `/${toForwardSlashes(path.relative(cwd, path.join(runtimeDir, 'app.js')))}`,\n title: appTitle,\n },\n studioRootPath: cwd,\n }),\n ),\n ),\n )\n\n buildDebug('Writing index.html to runtime directory')\n await writeFile(path.join(runtimeDir, 'index.html'), indexHtml)\n }\n\n let watcher: FSWatcher | undefined\n\n if (watch) {\n // Skip the initial scan; the explicit renderAndWriteDocument() below handles first generation.\n watcher = chokidarWatch(getPossibleDocumentComponentLocations(cwd), {ignoreInitial: true}).on(\n 'all',\n () => renderAndWriteDocument(),\n )\n }\n\n await renderAndWriteDocument()\n\n buildDebug('Writing app.js to runtime directory')\n const {relativeConfigLocation, relativeEntry} = await resolveEntries({\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n runtimeDir,\n })\n const appJsContent = getEntryModule({\n basePath,\n entry: relativeEntry ?? undefined,\n isApp,\n reactStrictMode,\n relativeConfigLocation,\n })\n await writeFile(path.join(runtimeDir, 'app.js'), appJsContent)\n\n return {\n entries: {\n relativeConfigLocation,\n relativeEntry,\n },\n watcher,\n }\n}\n\n/**\n * Resolves the relative entry paths for a Sanity project without writing any\n * runtime files to disk. Used by federation builds that skip the full runtime\n * generation but still need entry metadata for the vite plugin.\n */\nexport async function resolveEntries(options: {\n cwd: string\n entry?: string\n isApp?: boolean\n isWorkbenchApp?: boolean\n runtimeDir?: string\n}): Promise<{relativeConfigLocation: string | null; relativeEntry: string | null}> {\n const {cwd, entry, isApp, isWorkbenchApp} = options\n const runtimeDir = options.runtimeDir ?? path.join(cwd, '.sanity', 'runtime')\n\n let relativeConfigLocation: string | null = null\n if (!isApp) {\n const studioConfigPath = await tryFindStudioConfigPath(cwd)\n relativeConfigLocation = studioConfigPath\n ? toForwardSlashes(path.relative(runtimeDir, studioConfigPath))\n : null\n }\n\n // Only a *branded* app (`unstable_defineApp`) that declares no `entry` has no\n // navigable app view (sanity-io/workbench spec 002-workbench-extension-api,\n // US5): `null` entry tells the runtime/federation to skip the `./App` render\n // path. Non-branded (legacy SDK) apps keep the historical `./src/App` default,\n // and studios ignore `relativeEntry` — so gating on `isApp` here would regress\n // non-opted-in apps to the dock-only stub.\n const relativeEntry =\n isWorkbenchApp && !entry\n ? null\n : toForwardSlashes(path.relative(runtimeDir, path.resolve(cwd, entry || './src/App')))\n\n return {relativeConfigLocation, relativeEntry}\n}\n\nfunction toForwardSlashes(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n"],"names":["mkdir","writeFile","path","tryFindStudioConfigPath","watch","chokidarWatch","buildDebug","decorateIndexWithAutoGeneratedWarning","decorateIndexWithBridgeScript","decorateIndexWithStagingScript","getEntryModule","getPossibleDocumentComponentLocations","renderDocument","writeSanityRuntime","options","appTitle","basePath","cwd","entry","isApp","isWorkbenchApp","reactStrictMode","runtimeDir","join","recursive","renderAndWriteDocument","indexHtml","props","entryPath","toForwardSlashes","relative","title","studioRootPath","watcher","ignoreInitial","on","relativeConfigLocation","relativeEntry","resolveEntries","appJsContent","undefined","entries","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AAMA;IAENnB,WAAW;IACX,MAAM,EAAC8B,sBAAsB,EAAEC,aAAa,EAAC,GAAG,MAAMC,eAAe;QACnErB;QACAC;QACAC;QACAC;QACAE;IACF;IACA,MAAMiB,eAAe7B,eAAe;QAClCM;QACAE,OAAOmB,iBAAiBG;QACxBrB;QACAE;QACAe;IACF;IACA,MAAMnC,UAAUC,KAAKqB,IAAI,CAACD,YAAY,WAAWiB;IAEjD,OAAO;QACLE,SAAS;YACPL;YACAC;QACF;QACAJ;IACF;AACF;AAEA;;;;CAIC,GACD,OAAO,eAAeK,eAAexB,OAMpC;IACC,MAAM,EAACG,GAAG,EAAEC,KAAK,EAAEC,KAAK,EAAEC,cAAc,EAAC,GAAGN;IAC5C,MAAMQ,aAAaR,QAAQQ,UAAU,IAAIpB,KAAKqB,IAAI,CAACN,KAAK,WAAW;IAEnE,IAAImB,yBAAwC;IAC5C,IAAI,CAACjB,OAAO;QACV,MAAMuB,mBAAmB,MAAMvC,wBAAwBc;QACvDmB,yBAAyBM,mBACrBb,iBAAiB3B,KAAK4B,QAAQ,CAACR,YAAYoB,qBAC3C;IACN;IAEA,8EAA8E;IAC9E,4EAA4E;IAC5E,6EAA6E;IAC7E,+EAA+E;IAC/E,+EAA+E;IAC/E,2CAA2C;IAC3C,MAAML,gBACJjB,kBAAkB,CAACF,QACf,OACAW,iBAAiB3B,KAAK4B,QAAQ,CAACR,YAAYpB,KAAKyC,OAAO,CAAC1B,KAAKC,SAAS;IAE5E,OAAO;QAACkB;QAAwBC;IAAa;AAC/C;AAEA,SAASR,iBAAiBe,QAAgB;IACxC,OAAOA,SAASC,UAAU,CAAC,MAAM;AACnC"}
1
+ {"version":3,"sources":["../../../src/actions/build/writeSanityRuntime.ts"],"sourcesContent":["import {mkdir, writeFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {tryFindStudioConfigPath} from '@sanity/cli-core/config'\nimport {watch as chokidarWatch, type FSWatcher} from 'chokidar'\n\nimport {buildDebug} from './buildDebug.js'\nimport {decorateIndexWithAutoGeneratedWarning} from './decorateIndexWithAutoGeneratedWarning.js'\nimport {decorateIndexWithBridgeScript} from './decorateIndexWithBridgeScript.js'\nimport {decorateIndexWithStagingScript} from './decorateIndexWithStagingScript.js'\nimport {getEntryModule} from './getEntryModule.js'\nimport {getPossibleDocumentComponentLocations} from './getPossibleDocumentComponentLocations.js'\nimport {renderDocument} from './renderDocument.js'\n\ninterface RuntimeOptions {\n cwd: string\n reactStrictMode: boolean | undefined\n watch: boolean\n\n appTitle?: string\n basePath?: string\n entry?: string\n isApp?: boolean\n isWorkbenchApp?: boolean\n}\n\n/**\n * Generates the `.sanity/runtime` directory, and optionally watches for custom\n * document files, rebuilding when they change\n *\n * @param options - Current working directory (Sanity root dir), and whether or not to watch\n * @returns A watcher instance if watch is enabled, undefined otherwise\n * @internal\n */\nexport async function writeSanityRuntime(options: RuntimeOptions): Promise<{\n entries: {relativeConfigLocation: string | null; relativeEntry: string | null}\n watcher: FSWatcher | undefined\n}> {\n const {appTitle, basePath, cwd, entry, isApp, isWorkbenchApp, reactStrictMode, watch} = options\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n\n buildDebug('Making runtime directory')\n await mkdir(runtimeDir, {recursive: true})\n\n async function renderAndWriteDocument() {\n buildDebug('Rendering document template')\n const indexHtml = decorateIndexWithStagingScript(\n decorateIndexWithBridgeScript(\n decorateIndexWithAutoGeneratedWarning(\n await renderDocument({\n isApp,\n props: {\n basePath: basePath || '/',\n entryPath: `/${toForwardSlashes(path.relative(cwd, path.join(runtimeDir, 'app.js')))}`,\n title: appTitle,\n },\n studioRootPath: cwd,\n }),\n ),\n ),\n )\n\n buildDebug('Writing index.html to runtime directory')\n await writeFile(path.join(runtimeDir, 'index.html'), indexHtml)\n }\n\n let watcher: FSWatcher | undefined\n\n if (watch) {\n // Skip the initial scan; the explicit renderAndWriteDocument() below handles first generation.\n watcher = chokidarWatch(getPossibleDocumentComponentLocations(cwd), {ignoreInitial: true}).on(\n 'all',\n () => renderAndWriteDocument(),\n )\n }\n\n await renderAndWriteDocument()\n\n buildDebug('Writing app.js to runtime directory')\n const {relativeConfigLocation, relativeEntry} = await resolveEntries({\n cwd,\n entry,\n isApp,\n isWorkbenchApp,\n runtimeDir,\n })\n const appJsContent = getEntryModule({\n basePath,\n entry: relativeEntry ?? undefined,\n isApp,\n reactStrictMode,\n relativeConfigLocation,\n })\n await writeFile(path.join(runtimeDir, 'app.js'), appJsContent)\n\n return {\n entries: {\n relativeConfigLocation,\n relativeEntry,\n },\n watcher,\n }\n}\n\n/**\n * Resolves the relative entry paths for a Sanity project without writing any\n * runtime files to disk. Used by federation builds that skip the full runtime\n * generation but still need entry metadata for the vite plugin.\n */\nexport async function resolveEntries(options: {\n cwd: string\n entry?: string\n isApp?: boolean\n isWorkbenchApp?: boolean\n runtimeDir?: string\n}): Promise<{relativeConfigLocation: string | null; relativeEntry: string | null}> {\n const {cwd, entry, isApp, isWorkbenchApp} = options\n const runtimeDir = options.runtimeDir ?? path.join(cwd, '.sanity', 'runtime')\n\n let relativeConfigLocation: string | null = null\n if (!isApp) {\n const studioConfigPath = await tryFindStudioConfigPath(cwd)\n relativeConfigLocation = studioConfigPath\n ? toForwardSlashes(path.relative(runtimeDir, studioConfigPath))\n : null\n }\n\n // Only a *branded* app (`defineApplication`) that declares no `entry` has no\n // navigable app view (sanity-io/workbench spec 002-workbench-extension-api,\n // US5): `null` entry tells the runtime/federation to skip the `./App` render\n // path. Non-branded (legacy SDK) apps keep the historical `./src/App` default,\n // and studios ignore `relativeEntry` — so gating on `isApp` here would regress\n // non-opted-in apps to the dock-only stub.\n const relativeEntry =\n isWorkbenchApp && !entry\n ? null\n : toForwardSlashes(path.relative(runtimeDir, path.resolve(cwd, entry || './src/App')))\n\n return {relativeConfigLocation, relativeEntry}\n}\n\nfunction toForwardSlashes(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n"],"names":["mkdir","writeFile","path","tryFindStudioConfigPath","watch","chokidarWatch","buildDebug","decorateIndexWithAutoGeneratedWarning","decorateIndexWithBridgeScript","decorateIndexWithStagingScript","getEntryModule","getPossibleDocumentComponentLocations","renderDocument","writeSanityRuntime","options","appTitle","basePath","cwd","entry","isApp","isWorkbenchApp","reactStrictMode","runtimeDir","join","recursive","renderAndWriteDocument","indexHtml","props","entryPath","toForwardSlashes","relative","title","studioRootPath","watcher","ignoreInitial","on","relativeConfigLocation","relativeEntry","resolveEntries","appJsContent","undefined","entries","studioConfigPath","resolve","filePath","replaceAll"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,SAAS,QAAO,mBAAkB;AACjD,OAAOC,UAAU,YAAW;AAE5B,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SAAQC,SAASC,aAAa,QAAuB,WAAU;AAE/D,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,qCAAqC,QAAO,6CAA4C;AAChG,SAAQC,6BAA6B,QAAO,qCAAoC;AAChF,SAAQC,8BAA8B,QAAO,sCAAqC;AAClF,SAAQC,cAAc,QAAO,sBAAqB;AAClD,SAAQC,qCAAqC,QAAO,6CAA4C;AAChG,SAAQC,cAAc,QAAO,sBAAqB;AAclD;;;;;;;CAOC,GACD,OAAO,eAAeC,mBAAmBC,OAAuB;IAI9D,MAAM,EAACC,QAAQ,EAAEC,QAAQ,EAAEC,GAAG,EAAEC,KAAK,EAAEC,KAAK,EAAEC,cAAc,EAAEC,eAAe,EAAEjB,KAAK,EAAC,GAAGU;IACxF,MAAMQ,aAAapB,KAAKqB,IAAI,CAACN,KAAK,WAAW;IAE7CX,WAAW;IACX,MAAMN,MAAMsB,YAAY;QAACE,WAAW;IAAI;IAExC,eAAeC;QACbnB,WAAW;QACX,MAAMoB,YAAYjB,+BAChBD,8BACED,sCACE,MAAMK,eAAe;YACnBO;YACAQ,OAAO;gBACLX,UAAUA,YAAY;gBACtBY,WAAW,CAAC,CAAC,EAAEC,iBAAiB3B,KAAK4B,QAAQ,CAACb,KAAKf,KAAKqB,IAAI,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