@sanity/workbench-cli 2.5.2 → 2.6.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 (28) hide show
  1. package/dist/_exports/build.d.ts +5 -2
  2. package/dist/_exports/build.js +1 -0
  3. package/dist/_exports/build.js.map +1 -1
  4. package/dist/_exports/dev.d.ts +1 -1
  5. package/dist/actions/build/artifact.js.map +1 -1
  6. package/dist/actions/build/render-remote.js +23 -4
  7. package/dist/actions/build/render-remote.js.map +1 -1
  8. package/dist/actions/build/views/artifact.js +2 -1
  9. package/dist/actions/build/views/artifact.js.map +1 -1
  10. package/dist/actions/build/vite/discover-shared-dependencies.js +206 -0
  11. package/dist/actions/build/vite/discover-shared-dependencies.js.map +1 -0
  12. package/dist/actions/build/vite/plugins/plugin-module-federation.js +45 -23
  13. package/dist/actions/build/vite/plugins/plugin-module-federation.js.map +1 -1
  14. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js +8 -2
  15. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js.map +1 -1
  16. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js +20 -13
  17. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js.map +1 -1
  18. package/dist/actions/build/vite/shared-dependencies.js +116 -0
  19. package/dist/actions/build/vite/shared-dependencies.js.map +1 -0
  20. package/dist/actions/dev/startWorkbenchDev.js +0 -1
  21. package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
  22. package/dist/actions/dev/startWorkbenchDevServer.js +3 -7
  23. package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
  24. package/dist/actions/preview/startWorkbenchPreview.js +0 -1
  25. package/dist/actions/preview/startWorkbenchPreview.js.map +1 -1
  26. package/dist/services/applications.js +1 -1
  27. package/dist/services/applications.js.map +1 -1
  28. package/package.json +5 -2
@@ -1,5 +1,5 @@
1
1
  import { a as resolveWorkbenchApp, i as WorkbenchExposes, n as resolveWorkbenchConfig, r as ResolvedWorkbenchApp, t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-1CV651GT.js";
2
- import { PluginOption } from "vite";
2
+ import { InlineConfig, PluginOption } from "vite";
3
3
  /**
4
4
  * Resource bindings ride in a dedicated module in the app's bundle rather than an
5
5
  * index.html script tag, so both standalone studios and federated apps resolve
@@ -50,6 +50,9 @@ declare const resourceBindingsCodeSplittingGroup: {
50
50
  * or `undefined` for any other chunk so the caller can apply its own default.
51
51
  */
52
52
  declare function resourceBindingsChunkFileName(chunkName: string): string | undefined;
53
+ declare function buildFederatedApp(config: InlineConfig, { reuseStandaloneBuild }?: {
54
+ reuseStandaloneBuild?: boolean;
55
+ }): Promise<void>;
53
56
  /**
54
57
  * Dep pre-bundling inputs for a workbench app's dev server.
55
58
  *
@@ -111,5 +114,5 @@ declare function workbenchVitePlugins(options: WorkbenchViteOptions): Promise<Pl
111
114
  * its own id from the applications API.
112
115
  */
113
116
  declare function buildAppId(app: ResolvedWorkbenchApp): Promise<string>;
114
- export { RESOURCE_BINDINGS_CHUNK_NAME, RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE, RESOURCE_BINDINGS_TOKEN, type ResolvedMediaLibraryConfig, type WorkbenchExposes, buildAppId, resolveWorkbenchApp, resolveWorkbenchConfig, resourceBindingsChunkFileName, resourceBindingsCodeSplittingGroup, workbenchOptimizeDeps, workbenchVitePlugins };
117
+ export { RESOURCE_BINDINGS_CHUNK_NAME, RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE, RESOURCE_BINDINGS_TOKEN, type ResolvedMediaLibraryConfig, type WorkbenchExposes, buildAppId, buildFederatedApp, resolveWorkbenchApp, resolveWorkbenchConfig, resourceBindingsChunkFileName, resourceBindingsCodeSplittingGroup, workbenchOptimizeDeps, workbenchVitePlugins };
115
118
  //# sourceMappingURL=build.d.ts.map
@@ -4,6 +4,7 @@
4
4
  // deploy-time guards, so it takes the bare `resolveWorkbenchApp` — the guarded
5
5
  // view (`getWorkbench`) is the deploy entry's export.
6
6
  export { RESOURCE_BINDINGS_CHUNK_NAME, RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE, RESOURCE_BINDINGS_TOKEN, resourceBindingsChunkFileName, resourceBindingsCodeSplittingGroup } from '../actions/build/resource-bindings.js';
7
+ export { buildFederatedApp } from '../actions/build/vite/discover-shared-dependencies.js';
7
8
  export { workbenchOptimizeDeps } from '../actions/build/vite/optimize-deps.js';
8
9
  export { workbenchVitePlugins } from '../actions/build/vite/workbench-vite-plugins.js';
9
10
  export { buildAppId } from '../appId.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/build.ts"],"sourcesContent":["// Node-only build entry: the module-federation Vite plugins that\n// `@sanity/cli-build`'s `getViteConfig` swaps in for a workbench app, plus the\n// resolver the build reads declared views/web workers from. The build needs no\n// deploy-time guards, so it takes the bare `resolveWorkbenchApp` — the guarded\n// view (`getWorkbench`) is the deploy entry's export.\n\nexport {\n RESOURCE_BINDINGS_CHUNK_NAME,\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n RESOURCE_BINDINGS_TOKEN,\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../actions/build/resource-bindings.js'\nexport {workbenchOptimizeDeps} from '../actions/build/vite/optimize-deps.js'\nexport {workbenchVitePlugins} from '../actions/build/vite/workbench-vite-plugins.js'\nexport {buildAppId} from '../appId.js'\nexport {resolveWorkbenchApp, type WorkbenchExposes} from '../resolveWorkbenchApp.js'\nexport {type ResolvedMediaLibraryConfig, resolveWorkbenchConfig} from '../resolveWorkbenchConfig.js'\n"],"names":["RESOURCE_BINDINGS_CHUNK_NAME","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","RESOURCE_BINDINGS_TOKEN","resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","workbenchOptimizeDeps","workbenchVitePlugins","buildAppId","resolveWorkbenchApp","resolveWorkbenchConfig"],"mappings":"AAAA,iEAAiE;AACjE,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,sDAAsD;AAEtD,SACEA,4BAA4B,EAC5BC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,EAC/BC,uBAAuB,EACvBC,6BAA6B,EAC7BC,kCAAkC,QAC7B,wCAAuC;AAC9C,SAAQC,qBAAqB,QAAO,yCAAwC;AAC5E,SAAQC,oBAAoB,QAAO,kDAAiD;AACpF,SAAQC,UAAU,QAAO,cAAa;AACtC,SAAQC,mBAAmB,QAA8B,4BAA2B;AACpF,SAAyCC,sBAAsB,QAAO,+BAA8B"}
1
+ {"version":3,"sources":["../../src/_exports/build.ts"],"sourcesContent":["// Node-only build entry: the module-federation Vite plugins that\n// `@sanity/cli-build`'s `getViteConfig` swaps in for a workbench app, plus the\n// resolver the build reads declared views/web workers from. The build needs no\n// deploy-time guards, so it takes the bare `resolveWorkbenchApp` — the guarded\n// view (`getWorkbench`) is the deploy entry's export.\n\nexport {\n RESOURCE_BINDINGS_CHUNK_NAME,\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n RESOURCE_BINDINGS_TOKEN,\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../actions/build/resource-bindings.js'\nexport {buildFederatedApp} from '../actions/build/vite/discover-shared-dependencies.js'\nexport {workbenchOptimizeDeps} from '../actions/build/vite/optimize-deps.js'\nexport {workbenchVitePlugins} from '../actions/build/vite/workbench-vite-plugins.js'\nexport {buildAppId} from '../appId.js'\nexport {resolveWorkbenchApp, type WorkbenchExposes} from '../resolveWorkbenchApp.js'\nexport {type ResolvedMediaLibraryConfig, resolveWorkbenchConfig} from '../resolveWorkbenchConfig.js'\n"],"names":["RESOURCE_BINDINGS_CHUNK_NAME","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","RESOURCE_BINDINGS_TOKEN","resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","buildFederatedApp","workbenchOptimizeDeps","workbenchVitePlugins","buildAppId","resolveWorkbenchApp","resolveWorkbenchConfig"],"mappings":"AAAA,iEAAiE;AACjE,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,sDAAsD;AAEtD,SACEA,4BAA4B,EAC5BC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,EAC/BC,uBAAuB,EACvBC,6BAA6B,EAC7BC,kCAAkC,QAC7B,wCAAuC;AAC9C,SAAQC,iBAAiB,QAAO,wDAAuD;AACvF,SAAQC,qBAAqB,QAAO,yCAAwC;AAC5E,SAAQC,oBAAoB,QAAO,kDAAiD;AACpF,SAAQC,UAAU,QAAO,cAAa;AACtC,SAAQC,mBAAmB,QAA8B,4BAA2B;AACpF,SAAyCC,sBAAsB,QAAO,+BAA8B"}
@@ -1,6 +1,6 @@
1
1
  import { t as DevServerManifest } from "./registry-CIoKFIDw.js";
2
- import { CliConfig, Output } from "@sanity/cli-core";
3
2
  import { ViteDevServer } from "vite";
3
+ import { CliConfig, Output } from "@sanity/cli-core";
4
4
  /**
5
5
  * Minimal shape the supervisor needs back from a started app/studio dev server.
6
6
  * The not-started arm is reserved for expected early exits the server already
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/artifact.ts"],"sourcesContent":["import {type WorkbenchExposes} from '../../resolveWorkbenchApp.js'\nimport {configArtifacts} from './configs/artifact.js'\nimport {serviceArtifacts} from './services/artifact.js'\nimport {viewArtifacts} from './views/artifact.js'\n\n/**\n * What a {@link GeneratedArtifact.source} builder receives from the build — the\n * one thing it can't compute on its own, since only the build knows where the\n * runtime dir sits relative to the app's `src`.\n */\ninterface ArtifactContext {\n /** Import specifier for an app `src` file, relative to this artifact. */\n resolveImport: (src: string) => string\n}\n\n/**\n * One file the federation build generates into the runtime dir for a declared\n * interface. Each interface type — views, web workers — expands its declarations\n * into a flat list of these; the build then writes them and maps the ones the\n * host loads directly into the module-federation manifest.\n *\n * Adding an interface type is adding a builder that returns\n * `GeneratedArtifact[]` — the write loop and the expose mapping never change.\n */\nexport interface GeneratedArtifact {\n /** Path relative to the federation runtime dir, e.g. `views/feed/panel.js`. */\n path: string\n /** Build the file's contents. */\n source: (context: ArtifactContext) => string\n\n /**\n * Module-federation expose key when the host loads this artifact directly —\n * a view component `./views/feed/panel`, a service loader `./services/unread`.\n * Omitted for a file the host never loads on its own, like a worker bundle\n * (reached through its sibling loader).\n */\n expose?: string\n}\n\n/**\n * Map the artifacts the host loads directly (those with an `expose`) to their\n * runtime-dir paths, for the module-federation `exposes` field. `toExposePath`\n * turns a runtime-relative artifact path into the value federation wants — the\n * caller owns the runtime-dir location and any entry resolution.\n */\nexport function artifactExposes(\n artifacts: readonly GeneratedArtifact[],\n toExposePath: (artifactPath: string) => string,\n): Record<string, string> {\n const exposes: Record<string, string> = {}\n for (const artifact of artifacts) {\n if (artifact.expose) {\n exposes[artifact.expose] = toExposePath(artifact.path)\n }\n }\n return exposes\n}\n\n/**\n * Expand what the app exposes into the flat artifact set the federation build\n * writes — the single place that composes the per-type expanders, so the expose\n * mapping and the file writing read from one expansion.\n */\nexport function workbenchArtifacts(exposes: WorkbenchExposes): GeneratedArtifact[] {\n return [\n ...viewArtifacts(exposes.views ?? []),\n ...serviceArtifacts(exposes.webWorkers ?? []),\n ...configArtifacts(exposes.config),\n ]\n}\n"],"names":["configArtifacts","serviceArtifacts","viewArtifacts","artifactExposes","artifacts","toExposePath","exposes","artifact","expose","path","workbenchArtifacts","views","webWorkers","config"],"mappings":"AACA,SAAQA,eAAe,QAAO,wBAAuB;AACrD,SAAQC,gBAAgB,QAAO,yBAAwB;AACvD,SAAQC,aAAa,QAAO,sBAAqB;AAoCjD;;;;;CAKC,GACD,OAAO,SAASC,gBACdC,SAAuC,EACvCC,YAA8C;IAE9C,MAAMC,UAAkC,CAAC;IACzC,KAAK,MAAMC,YAAYH,UAAW;QAChC,IAAIG,SAASC,MAAM,EAAE;YACnBF,OAAO,CAACC,SAASC,MAAM,CAAC,GAAGH,aAAaE,SAASE,IAAI;QACvD;IACF;IACA,OAAOH;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASI,mBAAmBJ,OAAyB;IAC1D,OAAO;WACFJ,cAAcI,QAAQK,KAAK,IAAI,EAAE;WACjCV,iBAAiBK,QAAQM,UAAU,IAAI,EAAE;WACzCZ,gBAAgBM,QAAQO,MAAM;KAClC;AACH"}
1
+ {"version":3,"sources":["../../../src/actions/build/artifact.ts"],"sourcesContent":["import {type WorkbenchExposes} from '../../resolveWorkbenchApp.js'\nimport {configArtifacts} from './configs/artifact.js'\nimport {serviceArtifacts} from './services/artifact.js'\nimport {viewArtifacts} from './views/artifact.js'\n\n/**\n * What a {@link GeneratedArtifact.source} builder receives from the build — the\n * one thing it can't compute on its own, since only the build knows where the\n * runtime dir sits relative to the app's `src`.\n */\ninterface ArtifactContext {\n /** Import specifier for an app `src` file, relative to this artifact. */\n resolveImport: (src: string) => string\n\n isolateStyles?: boolean\n}\n\n/**\n * One file the federation build generates into the runtime dir for a declared\n * interface. Each interface type — views, web workers — expands its declarations\n * into a flat list of these; the build then writes them and maps the ones the\n * host loads directly into the module-federation manifest.\n *\n * Adding an interface type is adding a builder that returns\n * `GeneratedArtifact[]` — the write loop and the expose mapping never change.\n */\nexport interface GeneratedArtifact {\n /** Path relative to the federation runtime dir, e.g. `views/feed/panel.js`. */\n path: string\n /** Build the file's contents. */\n source: (context: ArtifactContext) => string\n\n /**\n * Module-federation expose key when the host loads this artifact directly —\n * a view component `./views/feed/panel`, a service loader `./services/unread`.\n * Omitted for a file the host never loads on its own, like a worker bundle\n * (reached through its sibling loader).\n */\n expose?: string\n}\n\n/**\n * Map the artifacts the host loads directly (those with an `expose`) to their\n * runtime-dir paths, for the module-federation `exposes` field. `toExposePath`\n * turns a runtime-relative artifact path into the value federation wants — the\n * caller owns the runtime-dir location and any entry resolution.\n */\nexport function artifactExposes(\n artifacts: readonly GeneratedArtifact[],\n toExposePath: (artifactPath: string) => string,\n): Record<string, string> {\n const exposes: Record<string, string> = {}\n for (const artifact of artifacts) {\n if (artifact.expose) {\n exposes[artifact.expose] = toExposePath(artifact.path)\n }\n }\n return exposes\n}\n\n/**\n * Expand what the app exposes into the flat artifact set the federation build\n * writes — the single place that composes the per-type expanders, so the expose\n * mapping and the file writing read from one expansion.\n */\nexport function workbenchArtifacts(exposes: WorkbenchExposes): GeneratedArtifact[] {\n return [\n ...viewArtifacts(exposes.views ?? []),\n ...serviceArtifacts(exposes.webWorkers ?? []),\n ...configArtifacts(exposes.config),\n ]\n}\n"],"names":["configArtifacts","serviceArtifacts","viewArtifacts","artifactExposes","artifacts","toExposePath","exposes","artifact","expose","path","workbenchArtifacts","views","webWorkers","config"],"mappings":"AACA,SAAQA,eAAe,QAAO,wBAAuB;AACrD,SAAQC,gBAAgB,QAAO,yBAAwB;AACvD,SAAQC,aAAa,QAAO,sBAAqB;AAsCjD;;;;;CAKC,GACD,OAAO,SAASC,gBACdC,SAAuC,EACvCC,YAA8C;IAE9C,MAAMC,UAAkC,CAAC;IACzC,KAAK,MAAMC,YAAYH,UAAW;QAChC,IAAIG,SAASC,MAAM,EAAE;YACnBF,OAAO,CAACC,SAASC,MAAM,CAAC,GAAGH,aAAaE,SAASE,IAAI;QACvD;IACF;IACA,OAAOH;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASI,mBAAmBJ,OAAyB;IAC1D,OAAO;WACFJ,cAAcI,QAAQK,KAAK,IAAI,EAAE;WACjCV,iBAAiBK,QAAQM,UAAU,IAAI,EAAE;WACzCZ,gBAAgBM,QAAQO,MAAM;KAClC;AACH"}
@@ -11,7 +11,11 @@
11
11
  * the shared HMR snippet.
12
12
  *
13
13
  * The render contract is
14
- * `render(rootElement, props, renderOptions?: {reactStrictMode?: boolean; moduleId?: string})`.
14
+ * `render(rootElement, props, renderOptions?: {reactStrictMode?: boolean; moduleId?: string; rootOptions?: import('react-dom/client').RootOptions})`.
15
+ * `rootOptions` (React's `createRoot` options — `onUncaughtError`, `onCaughtError`,
16
+ * `onRecoverableError`, `identifierPrefix`) is forwarded verbatim to `createRoot`
17
+ * and only applies when the root is first created (reused roots in `rootMap` keep
18
+ * the options they were created with).
15
19
  * `moduleId` is the host's canonical federation module id (e.g. `favorites/App`,
16
20
  * `favorites/views/list/panel`, `favorites/workers/sync`). It is provided to
17
21
  * `App` through a `React.Context<string | undefined>` keyed per React copy (by
@@ -39,12 +43,15 @@
39
43
  * `App` directly (the SDK-app entry).
40
44
  * - `version` is an expression the host reads to check contract compatibility;
41
45
  * omit it when the module carries no version (the studio/app entries).
42
- */ export function renderRemote({ app, hmr = false, preamble, version }) {
46
+ */ export function renderRemote({ app, hmr = false, isolateStyles = false, preamble, version }) {
47
+ // Keep apps without styled-components buildable; the unused branch is removed from their bundle.
48
+ const stylesheetImport = isolateStyles ? "import { StyleSheetManager } from 'styled-components'" : 'const StyleSheetManager = undefined';
43
49
  return `\
44
50
  // This file is auto-generated on 'sanity build' / 'sanity dev'
45
51
  // Modifications to this file are automatically discarded
46
52
  import * as React from 'react'
47
53
  import { createRoot } from 'react-dom/client'
54
+ ${stylesheetImport}
48
55
  ${preamble}
49
56
  ${app ? `\nconst App = ${app}\n` : ''}${version ? `\nexport const version = ${version}\n` : ''}
50
57
  // Module identity (the federation module id) is provided to App through a React
@@ -58,15 +65,24 @@ const moduleSlot = (globalThis[Symbol.for('sanity.os.module')] ??= new WeakMap()
58
65
  if (!moduleSlot.has(React.createContext)) moduleSlot.set(React.createContext, React.createContext(undefined))
59
66
  const ModuleContext = moduleSlot.get(React.createContext)
60
67
  const rootMap = new Map()
68
+ // A shared default sheet can overwrite another app's global rules; each root needs its own sheet.
69
+ const styleTargets = new Map()
61
70
  const renderArgs = new Map()
62
71
 
63
72
  function mount(rootElement, args) {
64
73
  let root = rootMap.get(rootElement)
65
74
  if (!root) {
66
- root = createRoot(rootElement)
75
+ root = createRoot(rootElement, args?.renderOptions?.rootOptions)
67
76
  rootMap.set(rootElement, root)
77
+ if (StyleSheetManager) {
78
+ const target = rootElement.ownerDocument.createElement('sanity-styles')
79
+ // React can replace the mount node's contents; keep its stylesheet outside that node.
80
+ rootElement.ownerDocument.head.appendChild(target)
81
+ styleTargets.set(rootElement, target)
82
+ }
68
83
  }
69
- const element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))
84
+ let element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))
85
+ if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement) }, element)
70
86
  root.render(args?.renderOptions?.reactStrictMode ? React.createElement(React.StrictMode, null, element) : element)
71
87
  }
72
88
 
@@ -79,6 +95,9 @@ export function render(rootElement, props, renderOptions) {
79
95
  rootMap.delete(rootElement)
80
96
  renderArgs.delete(rootElement)
81
97
  root?.unmount()
98
+ // Unmount first so effect cleanup can still reach this root's stylesheet.
99
+ styleTargets.get(rootElement)?.remove()
100
+ styleTargets.delete(rootElement)
82
101
  }
83
102
  }${hmr ? `\n\n${HMR_REMOUNT}` : ''}
84
103
  `;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every entry the federation build generates — the studio/app remote entries\n * and the per-view-component artifacts — is the same thing: a *render-contract\n * module* that owns its own React, renders into a host node via\n * `render(rootElement, props, renderOptions)`, and returns a disposer.\n *\n * They differ only in *what* they render. So each module binds an `App` to that\n * (the SDK app, a `Studio` with config, a view component) and the render body —\n * identical everywhere — just renders `App`. {@link renderRemote} assembles a\n * module from a `preamble` (its imports), the `app` expression, and, optionally,\n * the shared HMR snippet.\n *\n * The render contract is\n * `render(rootElement, props, renderOptions?: {reactStrictMode?: boolean; moduleId?: string})`.\n * `moduleId` is the host's canonical federation module id (e.g. `favorites/App`,\n * `favorites/views/list/panel`, `favorites/workers/sync`). It is provided to\n * `App` through a `React.Context<string | undefined>` keyed per React copy (by\n * `React.createContext`) on a global slot (`Symbol.for('sanity.os.module')`),\n * which the SDK reads via `getDashboardModuleContext()`.\n */\n\n/**\n * Hot-reload: on an update, re-render every live root through the new module —\n * so whatever it now binds `App` to (a recompiled component, a new studio\n * config) takes effect without a full page reload. Stripped from prod builds.\n */\nconst HMR_REMOUNT = `if (import.meta.hot) {\n import.meta.hot.accept((next) => {\n if (!next) return\n for (const [rootElement, args] of renderArgs) {\n rootMap.get(rootElement)?.unmount()\n rootMap.delete(rootElement)\n next.render(rootElement, args.props, args.renderOptions)\n }\n })\n}`\n\n/**\n * Assemble a render-contract module: its `preamble` (imports), the `App` it\n * renders, the render body, and — when `hmr` — the shared HMR snippet.\n *\n * - `app` is the expression bound to `App`; omit it when the preamble imports an\n * `App` directly (the SDK-app entry).\n * - `version` is an expression the host reads to check contract compatibility;\n * omit it when the module carries no version (the studio/app entries).\n */\nexport function renderRemote({\n app,\n hmr = false,\n preamble,\n version,\n}: {\n app?: string\n hmr?: boolean\n preamble: string\n version?: string\n}): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport * as React from 'react'\nimport { createRoot } from 'react-dom/client'\n${preamble}\n${app ? `\\nconst App = ${app}\\n` : ''}${version ? `\\nexport const version = ${version}\\n` : ''}\n// Module identity (the federation module id) is provided to App through a React\n// context keyed per React copy on a global slot. The SDK reads this same slot\n// via getDashboardModuleContext(), so the symbol, the key and the value type are\n// a contract. The key is React.createContext rather than the React namespace:\n// bundler interop (esbuild's __toESM in Vite dev pre-bundling) can hand two\n// importers of the same React copy different namespace objects, whereas the\n// createContext function is the same reference in both.\nconst moduleSlot = (globalThis[Symbol.for('sanity.os.module')] ??= new WeakMap())\nif (!moduleSlot.has(React.createContext)) moduleSlot.set(React.createContext, React.createContext(undefined))\nconst ModuleContext = moduleSlot.get(React.createContext)\nconst rootMap = new Map()\nconst renderArgs = new Map()\n\nfunction mount(rootElement, args) {\n let root = rootMap.get(rootElement)\n if (!root) {\n root = createRoot(rootElement)\n rootMap.set(rootElement, root)\n }\n const element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))\n root.render(args?.renderOptions?.reactStrictMode ? React.createElement(React.StrictMode, null, element) : element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return () => {\n const root = rootMap.get(rootElement)\n rootMap.delete(rootElement)\n renderArgs.delete(rootElement)\n root?.unmount()\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","preamble","version"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;CAmBC,GAED;;;;CAIC,GACD,MAAMA,cAAc,CAAC;;;;;;;;;CASpB,CAAC;AAEF;;;;;;;;CAQC,GACD,OAAO,SAASC,aAAa,EAC3BC,GAAG,EACHC,MAAM,KAAK,EACXC,QAAQ,EACRC,OAAO,EAMR;IACC,OAAO,CAAC;;;;;AAKV,EAAED,SAAS;AACX,EAAEF,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,KAAKG,UAAU,CAAC,yBAAyB,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkC9F,EAAEF,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
1
+ {"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every entry the federation build generates — the studio/app remote entries\n * and the per-view-component artifacts — is the same thing: a *render-contract\n * module* that owns its own React, renders into a host node via\n * `render(rootElement, props, renderOptions)`, and returns a disposer.\n *\n * They differ only in *what* they render. So each module binds an `App` to that\n * (the SDK app, a `Studio` with config, a view component) and the render body —\n * identical everywhere — just renders `App`. {@link renderRemote} assembles a\n * module from a `preamble` (its imports), the `app` expression, and, optionally,\n * the shared HMR snippet.\n *\n * The render contract is\n * `render(rootElement, props, renderOptions?: {reactStrictMode?: boolean; moduleId?: string; rootOptions?: import('react-dom/client').RootOptions})`.\n * `rootOptions` (React's `createRoot` options — `onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`, `identifierPrefix`) is forwarded verbatim to `createRoot`\n * and only applies when the root is first created (reused roots in `rootMap` keep\n * the options they were created with).\n * `moduleId` is the host's canonical federation module id (e.g. `favorites/App`,\n * `favorites/views/list/panel`, `favorites/workers/sync`). It is provided to\n * `App` through a `React.Context<string | undefined>` keyed per React copy (by\n * `React.createContext`) on a global slot (`Symbol.for('sanity.os.module')`),\n * which the SDK reads via `getDashboardModuleContext()`.\n */\n\n/**\n * Hot-reload: on an update, re-render every live root through the new module —\n * so whatever it now binds `App` to (a recompiled component, a new studio\n * config) takes effect without a full page reload. Stripped from prod builds.\n */\nconst HMR_REMOUNT = `if (import.meta.hot) {\n import.meta.hot.accept((next) => {\n if (!next) return\n for (const [rootElement, args] of renderArgs) {\n rootMap.get(rootElement)?.unmount()\n rootMap.delete(rootElement)\n next.render(rootElement, args.props, args.renderOptions)\n }\n })\n}`\n\n/**\n * Assemble a render-contract module: its `preamble` (imports), the `App` it\n * renders, the render body, and — when `hmr` — the shared HMR snippet.\n *\n * - `app` is the expression bound to `App`; omit it when the preamble imports an\n * `App` directly (the SDK-app entry).\n * - `version` is an expression the host reads to check contract compatibility;\n * omit it when the module carries no version (the studio/app entries).\n */\nexport function renderRemote({\n app,\n hmr = false,\n isolateStyles = false,\n preamble,\n version,\n}: {\n app?: string\n hmr?: boolean\n isolateStyles?: boolean\n preamble: string\n version?: string\n}): string {\n // Keep apps without styled-components buildable; the unused branch is removed from their bundle.\n const stylesheetImport = isolateStyles\n ? \"import { StyleSheetManager } from 'styled-components'\"\n : 'const StyleSheetManager = undefined'\n\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport * as React from 'react'\nimport { createRoot } from 'react-dom/client'\n${stylesheetImport}\n${preamble}\n${app ? `\\nconst App = ${app}\\n` : ''}${version ? `\\nexport const version = ${version}\\n` : ''}\n// Module identity (the federation module id) is provided to App through a React\n// context keyed per React copy on a global slot. The SDK reads this same slot\n// via getDashboardModuleContext(), so the symbol, the key and the value type are\n// a contract. The key is React.createContext rather than the React namespace:\n// bundler interop (esbuild's __toESM in Vite dev pre-bundling) can hand two\n// importers of the same React copy different namespace objects, whereas the\n// createContext function is the same reference in both.\nconst moduleSlot = (globalThis[Symbol.for('sanity.os.module')] ??= new WeakMap())\nif (!moduleSlot.has(React.createContext)) moduleSlot.set(React.createContext, React.createContext(undefined))\nconst ModuleContext = moduleSlot.get(React.createContext)\nconst rootMap = new Map()\n// A shared default sheet can overwrite another app's global rules; each root needs its own sheet.\nconst styleTargets = new Map()\nconst renderArgs = new Map()\n\nfunction mount(rootElement, args) {\n let root = rootMap.get(rootElement)\n if (!root) {\n root = createRoot(rootElement, args?.renderOptions?.rootOptions)\n rootMap.set(rootElement, root)\n if (StyleSheetManager) {\n const target = rootElement.ownerDocument.createElement('sanity-styles')\n // React can replace the mount node's contents; keep its stylesheet outside that node.\n rootElement.ownerDocument.head.appendChild(target)\n styleTargets.set(rootElement, target)\n }\n }\n let element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))\n if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement) }, element)\n root.render(args?.renderOptions?.reactStrictMode ? React.createElement(React.StrictMode, null, element) : element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return () => {\n const root = rootMap.get(rootElement)\n rootMap.delete(rootElement)\n renderArgs.delete(rootElement)\n root?.unmount()\n // Unmount first so effect cleanup can still reach this root's stylesheet.\n styleTargets.get(rootElement)?.remove()\n styleTargets.delete(rootElement)\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","isolateStyles","preamble","version","stylesheetImport"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED;;;;CAIC,GACD,MAAMA,cAAc,CAAC;;;;;;;;;CASpB,CAAC;AAEF;;;;;;;;CAQC,GACD,OAAO,SAASC,aAAa,EAC3BC,GAAG,EACHC,MAAM,KAAK,EACXC,gBAAgB,KAAK,EACrBC,QAAQ,EACRC,OAAO,EAOR;IACC,iGAAiG;IACjG,MAAMC,mBAAmBH,gBACrB,0DACA;IAEJ,OAAO,CAAC;;;;;AAKV,EAAEG,iBAAiB;AACnB,EAAEF,SAAS;AACX,EAAEH,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,KAAKI,UAAU,CAAC,yBAAyB,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8C9F,EAAEH,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
@@ -16,9 +16,10 @@ import { renderRemote } from '../render-remote.js';
16
16
  artifacts.push({
17
17
  expose: `./${VIEWS_DIR_NAME}/${view.name}/${component}`,
18
18
  path: `${VIEWS_DIR_NAME}/${view.name}/${component}.js`,
19
- source: ({ resolveImport })=>renderRemote({
19
+ source: ({ isolateStyles, resolveImport })=>renderRemote({
20
20
  app: `typeof view.components === 'function' ? view.components : view.components[${JSON.stringify(component)}]`,
21
21
  hmr: true,
22
+ isolateStyles,
22
23
  preamble: `import view from ${JSON.stringify(resolveImport(view.src))}`,
23
24
  version: `view.version`
24
25
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/views/artifact.ts"],"sourcesContent":["import {VIEW_COMPONENTS, type ViewSurface} from '../../../contract.js'\nimport {type GeneratedArtifact} from '../artifact.js'\nimport {renderRemote} from '../render-remote.js'\n\n/** Subdirectory under the federation runtime dir where view artifacts are written. */\nconst VIEWS_DIR_NAME = 'views'\n\n/**\n * An interface to generate render artifacts for. The `src` file default-exports\n * an `unstable_defineView(...)` result; the build emits one render-contract\n * artifact per component the view surface exposes.\n * @internal\n */\nexport interface InterfaceArtifact {\n /** Interface name, unique within the app. */\n name: string\n /** Path to the interface `src` file, relative to the app root (or absolute). */\n src: string\n /** Selects which components the build expands. */\n surface: ViewSurface\n}\n\n/**\n * Expand each view into one generated artifact per component it exposes. A\n * panel's `title` and `panel` each become their own render-contract module and\n * module-federation expose, so the host renders each as an independent island.\n *\n * Each artifact binds its component as the `App` the render contract renders —\n * a single-component view exports a bare function, a multi-component one keys by\n * name — behind an HMR boundary so view edits re-render through the new module.\n */\nexport function viewArtifacts(views: readonly InterfaceArtifact[]): GeneratedArtifact[] {\n const artifacts: GeneratedArtifact[] = []\n for (const view of views) {\n for (const component of VIEW_COMPONENTS[view.surface]) {\n artifacts.push({\n expose: `./${VIEWS_DIR_NAME}/${view.name}/${component}`,\n path: `${VIEWS_DIR_NAME}/${view.name}/${component}.js`,\n source: ({resolveImport}) =>\n renderRemote({\n app: `typeof view.components === 'function' ? view.components : view.components[${JSON.stringify(component)}]`,\n hmr: true,\n preamble: `import view from ${JSON.stringify(resolveImport(view.src))}`,\n version: `view.version`,\n }),\n })\n }\n }\n return artifacts\n}\n"],"names":["VIEW_COMPONENTS","renderRemote","VIEWS_DIR_NAME","viewArtifacts","views","artifacts","view","component","surface","push","expose","name","path","source","resolveImport","app","JSON","stringify","hmr","preamble","src","version"],"mappings":"AAAA,SAAQA,eAAe,QAAyB,uBAAsB;AAEtE,SAAQC,YAAY,QAAO,sBAAqB;AAEhD,oFAAoF,GACpF,MAAMC,iBAAiB;AAiBvB;;;;;;;;CAQC,GACD,OAAO,SAASC,cAAcC,KAAmC;IAC/D,MAAMC,YAAiC,EAAE;IACzC,KAAK,MAAMC,QAAQF,MAAO;QACxB,KAAK,MAAMG,aAAaP,eAAe,CAACM,KAAKE,OAAO,CAAC,CAAE;YACrDH,UAAUI,IAAI,CAAC;gBACbC,QAAQ,CAAC,EAAE,EAAER,eAAe,CAAC,EAAEI,KAAKK,IAAI,CAAC,CAAC,EAAEJ,WAAW;gBACvDK,MAAM,GAAGV,eAAe,CAAC,EAAEI,KAAKK,IAAI,CAAC,CAAC,EAAEJ,UAAU,GAAG,CAAC;gBACtDM,QAAQ,CAAC,EAACC,aAAa,EAAC,GACtBb,aAAa;wBACXc,KAAK,CAAC,0EAA0E,EAAEC,KAAKC,SAAS,CAACV,WAAW,CAAC,CAAC;wBAC9GW,KAAK;wBACLC,UAAU,CAAC,iBAAiB,EAAEH,KAAKC,SAAS,CAACH,cAAcR,KAAKc,GAAG,IAAI;wBACvEC,SAAS,CAAC,YAAY,CAAC;oBACzB;YACJ;QACF;IACF;IACA,OAAOhB;AACT"}
1
+ {"version":3,"sources":["../../../../src/actions/build/views/artifact.ts"],"sourcesContent":["import {VIEW_COMPONENTS, type ViewSurface} from '../../../contract.js'\nimport {type GeneratedArtifact} from '../artifact.js'\nimport {renderRemote} from '../render-remote.js'\n\n/** Subdirectory under the federation runtime dir where view artifacts are written. */\nconst VIEWS_DIR_NAME = 'views'\n\n/**\n * An interface to generate render artifacts for. The `src` file default-exports\n * an `unstable_defineView(...)` result; the build emits one render-contract\n * artifact per component the view surface exposes.\n * @internal\n */\nexport interface InterfaceArtifact {\n /** Interface name, unique within the app. */\n name: string\n /** Path to the interface `src` file, relative to the app root (or absolute). */\n src: string\n /** Selects which components the build expands. */\n surface: ViewSurface\n}\n\n/**\n * Expand each view into one generated artifact per component it exposes. A\n * panel's `title` and `panel` each become their own render-contract module and\n * module-federation expose, so the host renders each as an independent island.\n *\n * Each artifact binds its component as the `App` the render contract renders —\n * a single-component view exports a bare function, a multi-component one keys by\n * name — behind an HMR boundary so view edits re-render through the new module.\n */\nexport function viewArtifacts(views: readonly InterfaceArtifact[]): GeneratedArtifact[] {\n const artifacts: GeneratedArtifact[] = []\n for (const view of views) {\n for (const component of VIEW_COMPONENTS[view.surface]) {\n artifacts.push({\n expose: `./${VIEWS_DIR_NAME}/${view.name}/${component}`,\n path: `${VIEWS_DIR_NAME}/${view.name}/${component}.js`,\n source: ({isolateStyles, resolveImport}) =>\n renderRemote({\n app: `typeof view.components === 'function' ? view.components : view.components[${JSON.stringify(component)}]`,\n hmr: true,\n isolateStyles,\n preamble: `import view from ${JSON.stringify(resolveImport(view.src))}`,\n version: `view.version`,\n }),\n })\n }\n }\n return artifacts\n}\n"],"names":["VIEW_COMPONENTS","renderRemote","VIEWS_DIR_NAME","viewArtifacts","views","artifacts","view","component","surface","push","expose","name","path","source","isolateStyles","resolveImport","app","JSON","stringify","hmr","preamble","src","version"],"mappings":"AAAA,SAAQA,eAAe,QAAyB,uBAAsB;AAEtE,SAAQC,YAAY,QAAO,sBAAqB;AAEhD,oFAAoF,GACpF,MAAMC,iBAAiB;AAiBvB;;;;;;;;CAQC,GACD,OAAO,SAASC,cAAcC,KAAmC;IAC/D,MAAMC,YAAiC,EAAE;IACzC,KAAK,MAAMC,QAAQF,MAAO;QACxB,KAAK,MAAMG,aAAaP,eAAe,CAACM,KAAKE,OAAO,CAAC,CAAE;YACrDH,UAAUI,IAAI,CAAC;gBACbC,QAAQ,CAAC,EAAE,EAAER,eAAe,CAAC,EAAEI,KAAKK,IAAI,CAAC,CAAC,EAAEJ,WAAW;gBACvDK,MAAM,GAAGV,eAAe,CAAC,EAAEI,KAAKK,IAAI,CAAC,CAAC,EAAEJ,UAAU,GAAG,CAAC;gBACtDM,QAAQ,CAAC,EAACC,aAAa,EAAEC,aAAa,EAAC,GACrCd,aAAa;wBACXe,KAAK,CAAC,0EAA0E,EAAEC,KAAKC,SAAS,CAACX,WAAW,CAAC,CAAC;wBAC9GY,KAAK;wBACLL;wBACAM,UAAU,CAAC,iBAAiB,EAAEH,KAAKC,SAAS,CAACH,cAAcT,KAAKe,GAAG,IAAI;wBACvEC,SAAS,CAAC,YAAY,CAAC;oBACzB;YACJ;QACF;IACF;IACA,OAAOjB;AACT"}
@@ -0,0 +1,206 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createBuilder, createLogger } from 'vite';
4
+ import { FEDERATION_DIR_NAME } from './constants.js';
5
+ import { getFederationApi } from './plugins/plugin-module-federation.js';
6
+ import { aliasMayRewriteSharedImport, createFederationSharing, findSharedDependencyName } from './shared-dependencies.js';
7
+ export async function buildFederatedApp(config, { reuseStandaloneBuild = false } = {}) {
8
+ const plugins = await resolvePlugins(config.plugins ?? []);
9
+ const federation = getFederationApi(plugins);
10
+ if (!federation) {
11
+ const builder = await createBuilder(config);
12
+ await builder.buildApp();
13
+ return;
14
+ }
15
+ // Loading remote-only exposes in the SPA can emit worker bundles even when their imports are unused.
16
+ reuseStandaloneBuild &&= !federation.hasAdditionalExposes;
17
+ const discovery = createSharedDependencyDiscovery(reuseStandaloneBuild ? 'client' : FEDERATION_DIR_NAME);
18
+ const localPlugins = plugins.filter((plugin)=>plugin.api?.sanityFederation !== federation);
19
+ if (reuseStandaloneBuild) {
20
+ const standalone = await createBuilder({
21
+ ...config,
22
+ plugins: [
23
+ ...localPlugins,
24
+ discovery.plugin
25
+ ]
26
+ });
27
+ await standalone.build(standalone.environments.client);
28
+ } else {
29
+ await scanDependencies(config, localPlugins, discovery.plugin, federation.inputs);
30
+ }
31
+ const firstFederationPlugin = plugins.find((plugin)=>plugin.api?.sanityFederation === federation);
32
+ const sharing = discovery.getSharing();
33
+ const replacement = federation.create('disabledReason' in sharing ? undefined : sharing);
34
+ const builder = await createBuilder({
35
+ ...config,
36
+ plugins: plugins.flatMap((plugin)=>{
37
+ if (plugin === firstFederationPlugin) return [
38
+ replacement
39
+ ];
40
+ return plugin.api?.sanityFederation === federation ? [] : [
41
+ plugin
42
+ ];
43
+ })
44
+ });
45
+ if ('disabledReason' in sharing) {
46
+ // CLI builds silence Vite's progress output; keep the reason for disabled sharing visible.
47
+ createLogger('warn', {
48
+ customLogger: builder.config.customLogger
49
+ }).warn(`Dependency sharing disabled: ${sharing.disabledReason}. Dependencies will be bundled locally.`);
50
+ }
51
+ await (reuseStandaloneBuild ? builder.build(builder.environments[FEDERATION_DIR_NAME]) : builder.buildApp());
52
+ }
53
+ async function scanDependencies(config, plugins, discovery, inputs) {
54
+ const discoveryComplete = new Error('Shared dependency discovery complete');
55
+ const scanner = await createBuilder({
56
+ ...config,
57
+ // Vite would log our intentional stop as a build failure, so silence its logger during the scan.
58
+ // The catch below ignores only that stop signal and rethrows real errors for the CLI to report.
59
+ logLevel: 'silent',
60
+ plugins: [
61
+ ...plugins.map((plugin)=>({
62
+ ...plugin,
63
+ // The scan needs import hooks, while output hooks would emit or upload a second build.
64
+ augmentChunkHash: undefined,
65
+ buildEnd: undefined,
66
+ closeBundle: undefined,
67
+ generateBundle: undefined,
68
+ outputOptions: undefined,
69
+ renderChunk: undefined,
70
+ renderError: undefined,
71
+ renderStart: undefined,
72
+ writeBundle: undefined
73
+ })),
74
+ discovery,
75
+ {
76
+ buildEnd (error) {
77
+ // Vite has no scan-only build API; stop after the graph, before generating unused chunks.
78
+ if (!error) throw discoveryComplete;
79
+ },
80
+ config: ()=>({
81
+ environments: {
82
+ [FEDERATION_DIR_NAME]: {
83
+ build: {
84
+ minify: false,
85
+ sourcemap: false,
86
+ write: false,
87
+ ...inputs.length > 0 ? {
88
+ rolldownOptions: {
89
+ input: inputs
90
+ }
91
+ } : {}
92
+ }
93
+ }
94
+ }
95
+ }),
96
+ enforce: 'post',
97
+ name: 'sanity/shared-discovery-build'
98
+ }
99
+ ]
100
+ });
101
+ try {
102
+ await scanner.build(scanner.environments[FEDERATION_DIR_NAME]);
103
+ } catch (error) {
104
+ // Rolldown groups hook errors; only suppress our marker when no other hook failed.
105
+ const errors = error instanceof Error && 'errors' in error ? error.errors : [
106
+ error
107
+ ];
108
+ if (!Array.isArray(errors) || errors.length !== 1 || errors[0] !== discoveryComplete) {
109
+ throw error;
110
+ }
111
+ }
112
+ }
113
+ async function resolvePlugins(options) {
114
+ // Vite flattens PluginOption internally, but discovery needs concrete plugins before createBuilder runs.
115
+ const plugins = (await Promise.all(options)).flatMap((plugin)=>Array.isArray(plugin) ? plugin : [
116
+ plugin
117
+ ]).filter(Boolean);
118
+ return plugins.some((plugin)=>plugin instanceof Promise || Array.isArray(plugin)) ? resolvePlugins(plugins) : plugins;
119
+ }
120
+ function createSharedDependencyDiscovery(environmentName) {
121
+ const dependencies = [];
122
+ const packageCache = new Map();
123
+ let disabledReason;
124
+ async function findSharedPackage(id) {
125
+ let directory = path.dirname(id);
126
+ while(directory !== path.dirname(directory)){
127
+ const manifest = await readPackageManifest(directory);
128
+ if (!manifest) {
129
+ directory = path.dirname(directory);
130
+ continue;
131
+ }
132
+ if (!manifest.name || findSharedDependencyName(manifest.name) !== manifest.name) return;
133
+ if (!manifest.version) {
134
+ disabledReason ??= `${manifest.name} has no version in its package.json`;
135
+ return;
136
+ }
137
+ return {
138
+ name: manifest.name,
139
+ root: directory,
140
+ version: manifest.version
141
+ };
142
+ }
143
+ }
144
+ async function packageForModule(id) {
145
+ // Virtual module IDs and transform query suffixes do not map to a package.json on disk.
146
+ if (!path.isAbsolute(id) || id.includes('?')) return;
147
+ const directory = path.dirname(id);
148
+ const cached = packageCache.get(directory);
149
+ if (cached) return cached;
150
+ const pending = findSharedPackage(id);
151
+ packageCache.set(directory, pending);
152
+ return pending;
153
+ }
154
+ const plugin = {
155
+ apply: 'build',
156
+ applyToEnvironment: (environment)=>environment.name === environmentName,
157
+ configResolved (config) {
158
+ if (!config.isProduction) disabledReason ??= 'This is not a production build';
159
+ const alias = config.resolve.alias.find(({ find })=>aliasMayRewriteSharedImport(find));
160
+ if (alias) disabledReason ??= `The Vite alias ${String(alias.find)} may rewrite a shared dependency import`;
161
+ },
162
+ enforce: 'pre',
163
+ // Relative imports can reach a second installed copy without a bare package import.
164
+ async moduleParsed (module) {
165
+ const dependency = await packageForModule(module.id);
166
+ if (dependency) dependencies.push(dependency);
167
+ },
168
+ name: 'sanity/shared-discovery',
169
+ async resolveId (source, importer, options) {
170
+ const dependencyName = findSharedDependencyName(source);
171
+ if (!dependencyName) return;
172
+ const resolved = await this.resolve(source, importer, {
173
+ ...options,
174
+ skipSelf: true
175
+ });
176
+ if (!resolved || resolved.external) {
177
+ disabledReason ??= resolved?.external ? `${source} is external to the build` : `${source} could not be resolved`;
178
+ return resolved;
179
+ }
180
+ const dependency = await packageForModule(resolved.id);
181
+ if (!dependency || dependency.name !== dependencyName) {
182
+ disabledReason ??= `${source} does not resolve to an installed ${dependencyName} package`;
183
+ } else dependencies.push({
184
+ ...dependency,
185
+ specifier: source
186
+ });
187
+ return resolved;
188
+ }
189
+ };
190
+ return {
191
+ getSharing: ()=>disabledReason ? {
192
+ disabledReason
193
+ } : createFederationSharing(dependencies),
194
+ plugin
195
+ };
196
+ }
197
+ async function readPackageManifest(directory) {
198
+ try {
199
+ return JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8'));
200
+ } catch (error) {
201
+ if (error.code === 'ENOENT') return undefined;
202
+ throw error;
203
+ }
204
+ }
205
+
206
+ //# sourceMappingURL=discover-shared-dependencies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/actions/build/vite/discover-shared-dependencies.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {createBuilder, createLogger, type InlineConfig, type Plugin, type PluginOption} from 'vite'\n\nimport {FEDERATION_DIR_NAME} from './constants.js'\nimport {getFederationApi} from './plugins/plugin-module-federation.js'\nimport {\n aliasMayRewriteSharedImport,\n createFederationSharing,\n findSharedDependencyName,\n type ResolvedDependency,\n} from './shared-dependencies.js'\n\nexport async function buildFederatedApp(\n config: InlineConfig,\n {\n reuseStandaloneBuild = false,\n }: {\n // Only the unmodified CLI config guarantees matching resolution in both environments.\n reuseStandaloneBuild?: boolean\n } = {},\n): Promise<void> {\n const plugins = await resolvePlugins(config.plugins ?? [])\n const federation = getFederationApi(plugins)\n if (!federation) {\n const builder = await createBuilder(config)\n await builder.buildApp()\n return\n }\n\n // Loading remote-only exposes in the SPA can emit worker bundles even when their imports are unused.\n reuseStandaloneBuild &&= !federation.hasAdditionalExposes\n const discovery = createSharedDependencyDiscovery(\n reuseStandaloneBuild ? 'client' : FEDERATION_DIR_NAME,\n )\n const localPlugins = plugins.filter((plugin) => plugin.api?.sanityFederation !== federation)\n\n if (reuseStandaloneBuild) {\n const standalone = await createBuilder({\n ...config,\n plugins: [...localPlugins, discovery.plugin],\n })\n await standalone.build(standalone.environments.client)\n } else {\n await scanDependencies(config, localPlugins, discovery.plugin, federation.inputs)\n }\n\n const firstFederationPlugin = plugins.find(\n (plugin) => plugin.api?.sanityFederation === federation,\n )\n const sharing = discovery.getSharing()\n const replacement = federation.create('disabledReason' in sharing ? undefined : sharing)\n const builder = await createBuilder({\n ...config,\n plugins: plugins.flatMap((plugin): PluginOption[] => {\n if (plugin === firstFederationPlugin) return [replacement]\n return plugin.api?.sanityFederation === federation ? [] : [plugin]\n }),\n })\n if ('disabledReason' in sharing) {\n // CLI builds silence Vite's progress output; keep the reason for disabled sharing visible.\n createLogger('warn', {customLogger: builder.config.customLogger}).warn(\n `Dependency sharing disabled: ${sharing.disabledReason}. Dependencies will be bundled locally.`,\n )\n }\n await (reuseStandaloneBuild\n ? builder.build(builder.environments[FEDERATION_DIR_NAME])\n : builder.buildApp())\n}\n\nasync function scanDependencies(\n config: InlineConfig,\n plugins: Plugin[],\n discovery: Plugin,\n inputs: string[],\n): Promise<void> {\n const discoveryComplete = new Error('Shared dependency discovery complete')\n const scanner = await createBuilder({\n ...config,\n // Vite would log our intentional stop as a build failure, so silence its logger during the scan.\n // The catch below ignores only that stop signal and rethrows real errors for the CLI to report.\n logLevel: 'silent',\n plugins: [\n ...plugins.map((plugin): Plugin => ({\n ...plugin,\n // The scan needs import hooks, while output hooks would emit or upload a second build.\n augmentChunkHash: undefined,\n buildEnd: undefined,\n closeBundle: undefined,\n generateBundle: undefined,\n outputOptions: undefined,\n renderChunk: undefined,\n renderError: undefined,\n renderStart: undefined,\n writeBundle: undefined,\n })),\n discovery,\n {\n buildEnd(error) {\n // Vite has no scan-only build API; stop after the graph, before generating unused chunks.\n if (!error) throw discoveryComplete\n },\n config: () => ({\n environments: {\n [FEDERATION_DIR_NAME]: {\n build: {\n minify: false,\n sourcemap: false,\n write: false,\n ...(inputs.length > 0 ? {rolldownOptions: {input: inputs}} : {}),\n },\n },\n },\n }),\n enforce: 'post',\n name: 'sanity/shared-discovery-build',\n },\n ],\n })\n try {\n await scanner.build(scanner.environments[FEDERATION_DIR_NAME])\n } catch (error) {\n // Rolldown groups hook errors; only suppress our marker when no other hook failed.\n const errors = error instanceof Error && 'errors' in error ? error.errors : [error]\n if (!Array.isArray(errors) || errors.length !== 1 || errors[0] !== discoveryComplete) {\n throw error\n }\n }\n}\n\nasync function resolvePlugins(options: PluginOption[]): Promise<Plugin[]> {\n // Vite flattens PluginOption internally, but discovery needs concrete plugins before createBuilder runs.\n const plugins = (await Promise.all(options))\n .flatMap((plugin) => (Array.isArray(plugin) ? plugin : [plugin]))\n .filter(Boolean)\n return plugins.some((plugin) => plugin instanceof Promise || Array.isArray(plugin))\n ? resolvePlugins(plugins)\n : (plugins as Plugin[])\n}\n\nfunction createSharedDependencyDiscovery(environmentName: string): {\n getSharing: () => ReturnType<typeof createFederationSharing>\n plugin: Plugin\n} {\n const dependencies: ResolvedDependency[] = []\n const packageCache = new Map<string, Promise<ResolvedDependency | undefined>>()\n let disabledReason: string | undefined\n\n async function findSharedPackage(id: string): Promise<ResolvedDependency | undefined> {\n let directory = path.dirname(id)\n while (directory !== path.dirname(directory)) {\n const manifest = await readPackageManifest(directory)\n if (!manifest) {\n directory = path.dirname(directory)\n continue\n }\n\n if (!manifest.name || findSharedDependencyName(manifest.name) !== manifest.name) return\n if (!manifest.version) {\n disabledReason ??= `${manifest.name} has no version in its package.json`\n return\n }\n return {name: manifest.name, root: directory, version: manifest.version}\n }\n }\n\n async function packageForModule(id: string): Promise<ResolvedDependency | undefined> {\n // Virtual module IDs and transform query suffixes do not map to a package.json on disk.\n if (!path.isAbsolute(id) || id.includes('?')) return\n const directory = path.dirname(id)\n const cached = packageCache.get(directory)\n if (cached) return cached\n\n const pending = findSharedPackage(id)\n packageCache.set(directory, pending)\n return pending\n }\n\n const plugin: Plugin = {\n apply: 'build',\n applyToEnvironment: (environment) => environment.name === environmentName,\n configResolved(config) {\n if (!config.isProduction) disabledReason ??= 'This is not a production build'\n const alias = config.resolve.alias.find(({find}) => aliasMayRewriteSharedImport(find))\n if (alias)\n disabledReason ??= `The Vite alias ${String(alias.find)} may rewrite a shared dependency import`\n },\n enforce: 'pre',\n // Relative imports can reach a second installed copy without a bare package import.\n async moduleParsed(module) {\n const dependency = await packageForModule(module.id)\n if (dependency) dependencies.push(dependency)\n },\n name: 'sanity/shared-discovery',\n async resolveId(source, importer, options) {\n const dependencyName = findSharedDependencyName(source)\n if (!dependencyName) return\n\n const resolved = await this.resolve(source, importer, {...options, skipSelf: true})\n if (!resolved || resolved.external) {\n disabledReason ??= resolved?.external\n ? `${source} is external to the build`\n : `${source} could not be resolved`\n return resolved\n }\n\n const dependency = await packageForModule(resolved.id)\n if (!dependency || dependency.name !== dependencyName) {\n disabledReason ??= `${source} does not resolve to an installed ${dependencyName} package`\n } else dependencies.push({...dependency, specifier: source})\n return resolved\n },\n }\n\n return {\n getSharing: () => (disabledReason ? {disabledReason} : createFederationSharing(dependencies)),\n plugin,\n }\n}\n\nasync function readPackageManifest(\n directory: string,\n): Promise<{name?: string; version?: string} | undefined> {\n try {\n return JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8')) as {\n name?: string\n version?: string\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n"],"names":["readFile","path","createBuilder","createLogger","FEDERATION_DIR_NAME","getFederationApi","aliasMayRewriteSharedImport","createFederationSharing","findSharedDependencyName","buildFederatedApp","config","reuseStandaloneBuild","plugins","resolvePlugins","federation","builder","buildApp","hasAdditionalExposes","discovery","createSharedDependencyDiscovery","localPlugins","filter","plugin","api","sanityFederation","standalone","build","environments","client","scanDependencies","inputs","firstFederationPlugin","find","sharing","getSharing","replacement","create","undefined","flatMap","customLogger","warn","disabledReason","discoveryComplete","Error","scanner","logLevel","map","augmentChunkHash","buildEnd","closeBundle","generateBundle","outputOptions","renderChunk","renderError","renderStart","writeBundle","error","minify","sourcemap","write","length","rolldownOptions","input","enforce","name","errors","Array","isArray","options","Promise","all","Boolean","some","environmentName","dependencies","packageCache","Map","findSharedPackage","id","directory","dirname","manifest","readPackageManifest","version","root","packageForModule","isAbsolute","includes","cached","get","pending","set","apply","applyToEnvironment","environment","configResolved","isProduction","alias","resolve","String","moduleParsed","module","dependency","push","resolveId","source","importer","dependencyName","resolved","skipSelf","external","specifier","JSON","parse","join","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,OAAOC,UAAU,YAAW;AAE5B,SAAQC,aAAa,EAAEC,YAAY,QAA0D,OAAM;AAEnG,SAAQC,mBAAmB,QAAO,iBAAgB;AAClD,SAAQC,gBAAgB,QAAO,wCAAuC;AACtE,SACEC,2BAA2B,EAC3BC,uBAAuB,EACvBC,wBAAwB,QAEnB,2BAA0B;AAEjC,OAAO,eAAeC,kBACpBC,MAAoB,EACpB,EACEC,uBAAuB,KAAK,EAI7B,GAAG,CAAC,CAAC;IAEN,MAAMC,UAAU,MAAMC,eAAeH,OAAOE,OAAO,IAAI,EAAE;IACzD,MAAME,aAAaT,iBAAiBO;IACpC,IAAI,CA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EA,OAAO;QACL1E,YAAY,IAAOO,iBAAiB;gBAACA;YAAc,IAAIlC,wBAAwBmE;QAC/EpD;IACF;AACF;AAEA,eAAe4D,oBACbH,SAAiB;IAEjB,IAAI;QACF,OAAOiC,KAAKC,KAAK,CAAC,MAAMjH,SAASC,KAAKiH,IAAI,CAACnC,WAAW,iBAAiB;IAIzE,EAAE,OAAOvB,OAAO;QACd,IAAI,AAACA,MAAgC2D,IAAI,KAAK,UAAU,OAAO9E;QAC/D,MAAMmB;IACR;AACF"}
@@ -1,7 +1,21 @@
1
1
  import { federation as moduleFederation } from '@module-federation/vite';
2
2
  import { FEDERATION_DIR_NAME } from '../constants.js';
3
- export function sanityModuleFederation({ exposes, name }) {
4
- const mfPlugins = moduleFederation({
3
+ export function getFederationApi(plugins = []) {
4
+ return plugins.find((plugin)=>plugin.api?.sanityFederation)?.api.sanityFederation;
5
+ }
6
+ export function sanityModuleFederation(options, sharing) {
7
+ const { exposes, name } = options;
8
+ // Development keeps styled-components local. Sharing it across production apps requires
9
+ // a stylesheet per mounted root so their global rules don't overwrite each other.
10
+ const isolateStyles = Boolean(sharing && 'styled-components' in sharing.shared);
11
+ // Discovery replaces this plugin set as a group; callers need no knowledge of upstream plugin names.
12
+ const api = {
13
+ create: (sharing)=>sanityModuleFederation(options, sharing),
14
+ hasAdditionalExposes: Object.keys(exposes ?? {}).some((expose)=>expose !== './App'),
15
+ inputs: Object.values(exposes ?? {}).flatMap((expose)=>typeof expose === 'string' ? expose : expose.import),
16
+ isolateStyles
17
+ };
18
+ return moduleFederation({
5
19
  dev: {
6
20
  disableDynamicRemoteTypeHints: true,
7
21
  remoteHmr: true
@@ -11,34 +25,42 @@ export function sanityModuleFederation({ exposes, name }) {
11
25
  // Ctrl-C by sending on a still-CONNECTING websocket.
12
26
  dts: false,
13
27
  exposes,
14
- manifest: true,
28
+ manifest: sharing ? {
29
+ additionalData: ({ stats })=>{
30
+ const { exposes, shared } = stats;
31
+ // TODO: Remove after https://github.com/module-federation/vite/pull/1313 ships; expose preloads otherwise fetch fallback providers.
32
+ for (const kind of [
33
+ 'js',
34
+ 'css'
35
+ ]){
36
+ const providers = new Set(shared.flatMap(({ assets })=>[
37
+ ...assets[kind].sync,
38
+ ...assets[kind].async
39
+ ]));
40
+ for (const expose of exposes){
41
+ expose.assets[kind].async = expose.assets[kind].async.filter((asset)=>!providers.has(asset));
42
+ }
43
+ }
44
+ return stats;
45
+ }
46
+ } : true,
15
47
  name,
16
48
  // Resolves the remote entry path relative to the manifest rather than the
17
49
  // host origin.
18
50
  publicPath: 'auto',
19
- // @module-federation/vite auto-shares every package.json dependency
20
- // that exposes an `exports` field. That breaks for workspace packages with
21
- // subpath-only exports (no `.` entry) like `@sanity/cli-build` and
22
- // `@sanity/workbench`, because vite tries to resolve them as bare imports
23
- // and fails. Workbench remotes manage runtime sharing through the host's
24
- // federation runtime, so we opt out of auto-share entirely.
25
- shared: {}
26
- });
27
- // module-federation can deliver a plugin as a Promise resolving to an array;
28
- // spreading a promise (or an array) yields a junk object that silently drops
29
- // it. Recurse through the PluginOption shape so every actual plugin gets scoped.
30
- const scopeToEnvironment = (option)=>{
31
- if (!option) return option;
32
- if (option instanceof Promise) return option.then((resolved)=>scopeToEnvironment(resolved));
33
- if (Array.isArray(option)) return option.map((entry)=>scopeToEnvironment(entry));
34
- return {
35
- ...option,
51
+ // Keep dependencies local when discovery cannot prove that sharing is safe.
52
+ shared: {},
53
+ ...sharing
54
+ }).map((plugin)=>({
55
+ ...plugin,
56
+ api: {
57
+ ...plugin.api,
58
+ sanityFederation: api
59
+ },
36
60
  // In dev, MF must run on client — the dev server serves through it.
37
61
  // In build, scope to the federation environment to keep the library build clean.
38
62
  applyToEnvironment: (env)=>env.config.command === 'serve' || env.name === FEDERATION_DIR_NAME
39
- };
40
- };
41
- return mfPlugins.map((plugin)=>scopeToEnvironment(plugin));
63
+ }));
42
64
  }
43
65
 
44
66
  //# sourceMappingURL=plugin-module-federation.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-module-federation.ts"],"sourcesContent":["import {federation as moduleFederation, type ModuleFederationOptions} from '@module-federation/vite'\nimport {type Plugin, type PluginOption} from 'vite'\n\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\n/**\n * @internal\n */\nexport interface FederationOptions extends Pick<ModuleFederationOptions, 'exposes'> {\n /**\n * namespace of the federation build, used as the global variable name for the exposed modules\n * e.g `@acme/studio` would then allow you to import modules like `import (\"@acme/studio/Button\")`\n * defaults to your package.json name if not provided.\n */\n name: string\n}\n\nexport function sanityModuleFederation({exposes, name}: FederationOptions): PluginOption {\n const mfPlugins = moduleFederation({\n dev: {\n disableDynamicRemoteTypeHints: true,\n remoteHmr: true,\n },\n // Fully off (`false`, not `{generateTypes: false}`) so the dts plugin's\n // dev worker and broker never load — left on, they crash `sanity dev` on\n // Ctrl-C by sending on a still-CONNECTING websocket.\n dts: false,\n exposes,\n manifest: true,\n name,\n // Resolves the remote entry path relative to the manifest rather than the\n // host origin.\n publicPath: 'auto',\n // @module-federation/vite auto-shares every package.json dependency\n // that exposes an `exports` field. That breaks for workspace packages with\n // subpath-only exports (no `.` entry) like `@sanity/cli-build` and\n // `@sanity/workbench`, because vite tries to resolve them as bare imports\n // and fails. Workbench remotes manage runtime sharing through the host's\n // federation runtime, so we opt out of auto-share entirely.\n shared: {},\n })\n\n // module-federation can deliver a plugin as a Promise resolving to an array;\n // spreading a promise (or an array) yields a junk object that silently drops\n // it. Recurse through the PluginOption shape so every actual plugin gets scoped.\n const scopeToEnvironment = (option: PluginOption): PluginOption => {\n if (!option) return option\n if (option instanceof Promise) return option.then((resolved) => scopeToEnvironment(resolved))\n if (Array.isArray(option)) return option.map((entry) => scopeToEnvironment(entry))\n return {\n ...option,\n // In dev, MF must run on client — the dev server serves through it.\n // In build, scope to the federation environment to keep the library build clean.\n applyToEnvironment: (env) =>\n env.config.command === 'serve' || env.name === FEDERATION_DIR_NAME,\n } satisfies Plugin\n }\n\n return mfPlugins.map((plugin: PluginOption) => scopeToEnvironment(plugin))\n}\n"],"names":["federation","moduleFederation","FEDERATION_DIR_NAME","sanityModuleFederation","exposes","name","mfPlugins","dev","disableDynamicRemoteTypeHints","remoteHmr","dts","manifest","publicPath","shared","scopeToEnvironment","option","Promise","then","resolved","Array","isArray","map","entry","applyToEnvironment","env","config","command","plugin"],"mappings":"AAAA,SAAQA,cAAcC,gBAAgB,QAAqC,0BAAyB;AAGpG,SAAQC,mBAAmB,QAAO,kBAAiB;AAcnD,OAAO,SAASC,uBAAuB,EAACC,OAAO,EAAEC,IAAI,EAAoB;IACvE,MAAMC,YAAYL,iBAAiB;QACjCM,KAAK;YACHC,+BAA+B;YAC/BC,WAAW;QACb;QACA,wEAAwE;QACxE,yEAAyE;QACzE,qDAAqD;QACrDC,KAAK;QACLN;QACAO,UAAU;QACVN;QACA,0EAA0E;QAC1E,eAAe;QACfO,YAAY;QACZ,oEAAoE;QACpE,2EAA2E;QAC3E,mEAAmE;QACnE,0EAA0E;QAC1E,yEAAyE;QACzE,4DAA4D;QAC5DC,QAAQ,CAAC;IACX;IAEA,6EAA6E;IAC7E,6EAA6E;IAC7E,iFAAiF;IACjF,MAAMC,qBAAqB,CAACC;QAC1B,IAAI,CAACA,QAAQ,OAAOA;QACpB,IAAIA,kBAAkBC,SAAS,OAAOD,OAAOE,IAAI,CAAC,CAACC,WAAaJ,mBAAmBI;QACnF,IAAIC,MAAMC,OAAO,CAACL,SAAS,OAAOA,OAAOM,GAAG,CAAC,CAACC,QAAUR,mBAAmBQ;QAC3E,OAAO;YACL,GAAGP,MAAM;YACT,oEAAoE;YACpE,iFAAiF;YACjFQ,oBAAoB,CAACC,MACnBA,IAAIC,MAAM,CAACC,OAAO,KAAK,WAAWF,IAAInB,IAAI,KAAKH;QACnD;IACF;IAEA,OAAOI,UAAUe,GAAG,CAAC,CAACM,SAAyBb,mBAAmBa;AACpE"}
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-module-federation.ts"],"sourcesContent":["import {federation as moduleFederation, type ModuleFederationOptions} from '@module-federation/vite'\nimport {type Plugin, type PluginOption} from 'vite'\n\nimport {FEDERATION_DIR_NAME} from '../constants.js'\nimport {type FederationSharing} from '../shared-dependencies.js'\n\ntype ManifestAssets = Record<'css' | 'js', {async: string[]; sync: string[]}>\n\ninterface FederationPluginApi {\n create: (sharing?: FederationSharing) => PluginOption\n hasAdditionalExposes: boolean\n inputs: string[]\n isolateStyles: boolean\n}\n\nexport function getFederationApi(plugins: readonly Plugin[] = []): FederationPluginApi | undefined {\n return plugins.find((plugin) => plugin.api?.sanityFederation)?.api.sanityFederation\n}\n\n/**\n * @internal\n */\nexport interface FederationOptions extends Pick<ModuleFederationOptions, 'exposes'> {\n /**\n * namespace of the federation build, used as the global variable name for the exposed modules\n * e.g `@acme/studio` would then allow you to import modules like `import (\"@acme/studio/Button\")`\n * defaults to your package.json name if not provided.\n */\n name: string\n}\n\nexport function sanityModuleFederation(\n options: FederationOptions,\n sharing?: FederationSharing,\n): PluginOption {\n const {exposes, name} = options\n // Development keeps styled-components local. Sharing it across production apps requires\n // a stylesheet per mounted root so their global rules don't overwrite each other.\n const isolateStyles = Boolean(sharing && 'styled-components' in sharing.shared)\n // Discovery replaces this plugin set as a group; callers need no knowledge of upstream plugin names.\n const api: FederationPluginApi = {\n create: (sharing) => sanityModuleFederation(options, sharing),\n hasAdditionalExposes: Object.keys(exposes ?? {}).some((expose) => expose !== './App'),\n inputs: Object.values(exposes ?? {}).flatMap((expose) =>\n typeof expose === 'string' ? expose : expose.import,\n ),\n isolateStyles,\n }\n return moduleFederation({\n dev: {\n disableDynamicRemoteTypeHints: true,\n remoteHmr: true,\n },\n // Fully off (`false`, not `{generateTypes: false}`) so the dts plugin's\n // dev worker and broker never load — left on, they crash `sanity dev` on\n // Ctrl-C by sending on a still-CONNECTING websocket.\n dts: false,\n exposes,\n manifest: sharing\n ? {\n additionalData: ({stats}) => {\n const {exposes, shared} = stats as {\n exposes: {assets: ManifestAssets}[]\n shared: {assets: ManifestAssets}[]\n }\n // TODO: Remove after https://github.com/module-federation/vite/pull/1313 ships; expose preloads otherwise fetch fallback providers.\n for (const kind of ['js', 'css'] as const) {\n const providers = new Set(\n shared.flatMap(({assets}) => [...assets[kind].sync, ...assets[kind].async]),\n )\n for (const expose of exposes) {\n expose.assets[kind].async = expose.assets[kind].async.filter(\n (asset) => !providers.has(asset),\n )\n }\n }\n return stats\n },\n }\n : true,\n name,\n // Resolves the remote entry path relative to the manifest rather than the\n // host origin.\n publicPath: 'auto',\n // Keep dependencies local when discovery cannot prove that sharing is safe.\n shared: {},\n ...sharing,\n }).map((plugin: Plugin): Plugin => ({\n ...plugin,\n api: {...plugin.api, sanityFederation: api},\n // In dev, MF must run on client — the dev server serves through it.\n // In build, scope to the federation environment to keep the library build clean.\n applyToEnvironment: (env) => env.config.command === 'serve' || env.name === FEDERATION_DIR_NAME,\n }))\n}\n"],"names":["federation","moduleFederation","FEDERATION_DIR_NAME","getFederationApi","plugins","find","plugin","api","sanityFederation","sanityModuleFederation","options","sharing","exposes","name","isolateStyles","Boolean","shared","create","hasAdditionalExposes","Object","keys","some","expose","inputs","values","flatMap","import","dev","disableDynamicRemoteTypeHints","remoteHmr","dts","manifest","additionalData","stats","kind","providers","Set","assets","sync","async","filter","asset","has","publicPath","map","applyToEnvironment","env","config","command"],"mappings":"AAAA,SAAQA,cAAcC,gBAAgB,QAAqC,0BAAyB;AAGpG,SAAQC,mBAAmB,QAAO,kBAAiB;AAYnD,OAAO,SAASC,iBAAiBC,UAA6B,EAAE;IAC9D,OAAOA,QAAQC,IAAI,CAAC,CAACC,SAAWA,OAAOC,GAAG,EAAEC,mBAAmBD,IAAIC;AACrE;AAcA,OAAO,SAASC,uBACdC,OAA0B,EAC1BC,OAA2B;IAE3B,MAAM,EAACC,OAAO,EAAEC,IAAI,EAAC,GAAGH;IACxB,wFAAwF;IACxF,kFAAkF;IAClF,MAAMI,gBAAgBC,QAAQJ,W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GAAGD,OAAOC,GAAG;gBAAEC,kBAAkBD;YAAG;YAC1C,oEAAoE;YACpE,iFAAiF;YACjFsC,oBAAoB,CAACC,MAAQA,IAAIC,MAAM,CAACC,OAAO,KAAK,WAAWF,IAAIjC,IAAI,KAAKX;QAC9E,CAAA;AACF"}
@@ -1,17 +1,19 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { RUNTIME_DIR } from '../constants.js';
4
+ import { getFederationApi } from './plugin-module-federation.js';
4
5
  function relativeImport(fromFile, toFile) {
5
6
  const rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join('/');
6
7
  return rel.startsWith('.') ? rel : `./${rel}`;
7
8
  }
8
- function writeArtifacts(root, artifacts) {
9
+ function writeArtifacts({ artifacts, isolateStyles, root }) {
9
10
  for (const artifact of artifacts){
10
11
  const artifactPath = path.resolve(root, RUNTIME_DIR, artifact.path);
11
12
  fs.mkdirSync(path.dirname(artifactPath), {
12
13
  recursive: true
13
14
  });
14
15
  fs.writeFileSync(artifactPath, artifact.source({
16
+ isolateStyles,
15
17
  resolveImport: (src)=>relativeImport(artifactPath, path.resolve(root, src))
16
18
  }));
17
19
  }
@@ -24,7 +26,11 @@ function writeArtifacts(root, artifacts) {
24
26
  */ export function sanityExtensionArtifacts(options) {
25
27
  return {
26
28
  configResolved (config) {
27
- writeArtifacts(config.root, options.artifacts);
29
+ writeArtifacts({
30
+ artifacts: options.artifacts,
31
+ isolateStyles: getFederationApi(config.plugins)?.isolateStyles ?? false,
32
+ root: config.root
33
+ });
28
34
  },
29
35
  name: 'sanity/extension-artifacts'
30
36
  };