@sanity/workbench-cli 2.7.0 → 2.8.1

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.
@@ -40,7 +40,17 @@ const ModuleContext = moduleSlot.get(React.createContext)
40
40
  const rootMap = new Map()
41
41
  // A shared default sheet can overwrite another app's global rules; each root needs its own sheet.
42
42
  const styleTargets = new Map()
43
+ const stylisPlugins = new Map()
43
44
  const renderArgs = new Map()
45
+ // On globalThis: every module embeds its own copy of this harness, and names must be page-unique.
46
+ const stylisPluginCount = Symbol.for('sanity.os.stylisPluginCount')
47
+
48
+ // Identical CSS gets an identical class in every sheet, so a later sheet overrides earlier rules.
49
+ // StyleSheetManager hashes stylis plugin names into class names: a uniquely named no-op isolates a root.
50
+ function uniqueStylisPlugin() {
51
+ globalThis[stylisPluginCount] = (globalThis[stylisPluginCount] ?? 0) + 1
52
+ return Object.defineProperty(() => {}, 'name', { value: 'sanity-root-' + globalThis[stylisPluginCount] })
53
+ }
44
54
 
45
55
  function mount(rootElement, args) {
46
56
  let root = rootMap.get(rootElement)
@@ -52,10 +62,11 @@ function mount(rootElement, args) {
52
62
  // React can replace the mount node's contents; keep its stylesheet outside that node.
53
63
  rootElement.ownerDocument.head.appendChild(target)
54
64
  styleTargets.set(rootElement, target)
65
+ stylisPlugins.set(rootElement, [uniqueStylisPlugin()])
55
66
  }
56
67
  }
57
68
  let element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))
58
- if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement) }, element)
69
+ if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement), stylisPlugins: stylisPlugins.get(rootElement) }, element)
59
70
  // The host's React can't pause this root, so the host pauses the app through this Activity.
60
71
  // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.
61
72
  element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)
@@ -78,6 +89,7 @@ export function render(rootElement, props, renderOptions) {
78
89
  // Unmount first so effect cleanup can still reach this root's stylesheet.
79
90
  styleTargets.get(rootElement)?.remove()
80
91
  styleTargets.delete(rootElement)
92
+ stylisPlugins.delete(rootElement)
81
93
  },
82
94
  setLifecycle(state) {
83
95
  const current = renderArgs.get(rootElement)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every generated entry (studio, SDK app, view artifacts) shares one render body\n * so the host can drive them all the same way; only the `App` they bind differs.\n * The workbench host depends on `render`'s signature and return shape, so change\n * them together.\n */\n\n// Re-renders through the new module so edits apply without a page reload. The\n// new module mounts in the foreground, so reapply the host's lifecycle. The host\n// still holds this module's controller, so it forwards to the new one.\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 args.next = next.render(rootElement, args.props, args.renderOptions)\n args.next.setLifecycle(args.lifecycle)\n }\n })\n}`\n\n/**\n * - `app`: omit when the preamble imports `App` itself (the SDK-app entry).\n * - `version`: lets the host check view/service contract compatibility.\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// The SDK reads this slot via getDashboardModuleContext(), so its symbol, key and\n// value are a contract. Keyed by createContext, not the React namespace: Vite dev\n// pre-bundling can give two importers of one React copy different namespaces.\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 // The host's React can't pause this root, so the host pauses the app through this Activity.\n // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.\n element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)\n if (args?.renderOptions?.reactStrictMode) element = React.createElement(React.StrictMode, null, element)\n root.render(element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { lifecycle: 'foreground', props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return {\n dispose() {\n const current = renderArgs.get(rootElement)\n renderArgs.delete(rootElement)\n if (current?.next) return current.next.dispose()\n const root = rootMap.get(rootElement)\n rootMap.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 setLifecycle(state) {\n const current = renderArgs.get(rootElement)\n if (!current) return\n if (current.next) return current.next.setLifecycle(state)\n current.lifecycle = state\n mount(rootElement, current)\n },\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","isolateStyles","preamble","version","stylesheetImport"],"mappings":"AAAA;;;;;CAKC,GAED,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,MAAMA,cAAc,CAAC;;;;;;;;;;CAUpB,CAAC;AAEF;;;CAGC,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyD9F,EAAEH,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
1
+ {"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every generated entry (studio, SDK app, view artifacts) shares one render body\n * so the host can drive them all the same way; only the `App` they bind differs.\n * The workbench host depends on `render`'s signature and return shape, so change\n * them together.\n */\n\n// Re-renders through the new module so edits apply without a page reload. The\n// new module mounts in the foreground, so reapply the host's lifecycle. The host\n// still holds this module's controller, so it forwards to the new one.\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 args.next = next.render(rootElement, args.props, args.renderOptions)\n args.next.setLifecycle(args.lifecycle)\n }\n })\n}`\n\n/**\n * - `app`: omit when the preamble imports `App` itself (the SDK-app entry).\n * - `version`: lets the host check view/service contract compatibility.\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// The SDK reads this slot via getDashboardModuleContext(), so its symbol, key and\n// value are a contract. Keyed by createContext, not the React namespace: Vite dev\n// pre-bundling can give two importers of one React copy different namespaces.\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 stylisPlugins = new Map()\nconst renderArgs = new Map()\n// On globalThis: every module embeds its own copy of this harness, and names must be page-unique.\nconst stylisPluginCount = Symbol.for('sanity.os.stylisPluginCount')\n\n// Identical CSS gets an identical class in every sheet, so a later sheet overrides earlier rules.\n// StyleSheetManager hashes stylis plugin names into class names: a uniquely named no-op isolates a root.\nfunction uniqueStylisPlugin() {\n globalThis[stylisPluginCount] = (globalThis[stylisPluginCount] ?? 0) + 1\n return Object.defineProperty(() => {}, 'name', { value: 'sanity-root-' + globalThis[stylisPluginCount] })\n}\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 stylisPlugins.set(rootElement, [uniqueStylisPlugin()])\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), stylisPlugins: stylisPlugins.get(rootElement) }, element)\n // The host's React can't pause this root, so the host pauses the app through this Activity.\n // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.\n element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)\n if (args?.renderOptions?.reactStrictMode) element = React.createElement(React.StrictMode, null, element)\n root.render(element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { lifecycle: 'foreground', props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return {\n dispose() {\n const current = renderArgs.get(rootElement)\n renderArgs.delete(rootElement)\n if (current?.next) return current.next.dispose()\n const root = rootMap.get(rootElement)\n rootMap.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 stylisPlugins.delete(rootElement)\n },\n setLifecycle(state) {\n const current = renderArgs.get(rootElement)\n if (!current) return\n if (current.next) return current.next.setLifecycle(state)\n current.lifecycle = state\n mount(rootElement, current)\n },\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","isolateStyles","preamble","version","stylesheetImport"],"mappings":"AAAA;;;;;CAKC,GAED,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,MAAMA,cAAc,CAAC;;;;;;;;;;CAUpB,CAAC;AAEF;;;CAGC,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqE9F,EAAEH,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
@@ -2,6 +2,7 @@ import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { createBuilder, createLogger } from 'vite';
4
4
  import { FEDERATION_DIR_NAME } from './constants.js';
5
+ import { getFederationHostApi } from './plugins/plugin-federation-host.js';
5
6
  import { getFederationApi } from './plugins/plugin-module-federation.js';
6
7
  import { aliasMayRewriteSharedImport, createFederationSharing, findSharedDependencyName } from './shared-dependencies.js';
7
8
  export async function buildFederatedApp(config, { reuseStandaloneBuild = false } = {}) {
@@ -30,7 +31,10 @@ export async function buildFederatedApp(config, { reuseStandaloneBuild = false }
30
31
  }
31
32
  const firstFederationPlugin = plugins.find((plugin)=>plugin.api?.sanityFederation === federation);
32
33
  const sharing = discovery.getSharing();
33
- const replacement = federation.create('disabledReason' in sharing ? undefined : sharing);
34
+ const enabledSharing = 'disabledReason' in sharing ? undefined : sharing;
35
+ const host = getFederationHostApi(plugins);
36
+ if (host) host.sharing = enabledSharing;
37
+ const replacement = federation.create(enabledSharing);
34
38
  const builder = await createBuilder({
35
39
  ...config,
36
40
  plugins: plugins.flatMap((plugin)=>{
@@ -48,7 +52,8 @@ export async function buildFederatedApp(config, { reuseStandaloneBuild = false }
48
52
  customLogger: builder.config.customLogger
49
53
  }).warn(`Dependency sharing disabled: ${sharing.disabledReason}. Dependencies will be bundled locally.`);
50
54
  }
51
- await (reuseStandaloneBuild ? builder.build(builder.environments[FEDERATION_DIR_NAME]) : builder.buildApp());
55
+ // A reused standalone build served the host module before discovery settled its providers.
56
+ await (reuseStandaloneBuild && !host?.requested ? builder.build(builder.environments[FEDERATION_DIR_NAME]) : builder.buildApp());
52
57
  }
53
58
  async function scanDependencies(config, plugins, discovery, inputs) {
54
59
  const discoveryComplete = new Error('Shared dependency discovery complete');
@@ -1 +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,CAACE,YAAY;QACf,MAAMC,UAAU,MAAMb,cAAcQ;QACpC,MAAMK,QAAQC,QAAQ;QACtB;IACF;IAEA,qGAAqG;IACrGL,yBAAyB,CAACG,WAAWG,oBAAoB;IACzD,MAAMC,YAAYC,gCAChBR,uBAAuB,WAAWP;IAEpC,MAAMgB,eAAeR,QAAQS,MAAM,CAAC,CAACC,SAAWA,OAAOC,GAAG,EAAEC,qBAAqBV;IAEjF,IAAIH,sBAAsB;QACxB,MAAMc,aAAa,MAAMvB,cAAc;YACrC,GAAGQ,MAAM;YACTE,SAAS;mBAAIQ;gBAAcF,UAAUI,MAAM;aAAC;QAC9C;QACA,MAAMG,WAAWC,KAAK,CAACD,WAAWE,YAAY,CAACC,MAAM;IACvD,OAAO;QACL,MAAMC,iBAAiBnB,QAAQU,cAAcF,UAAUI,MAAM,EAAER,WAAWgB,MAAM;IAClF;IAEA,MAAMC,wBAAwBnB,QAAQoB,IAAI,CACxC,CAACV,SAAWA,OAAOC,GAAG,EAAEC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AO;YACvC,MAAMuC,iBAAiBnG,yBAAyBiG;YAChD,IAAI,CAACE,gBAAgB;YAErB,MAAMC,WAAW,MAAM,IAAI,CAACV,OAAO,CAACO,QAAQC,UAAU;gBAAC,GAAGtC,OAAO;gBAAEyC,UAAU;YAAI;YACjF,IAAI,CAACD,YAAYA,SAASE,QAAQ,EAAE;gBAClCrE,mBAAmBmE,UAAUE,WACzB,GAAGL,OAAO,yBAAyB,CAAC,GACpC,GAAGA,OAAO,sBAAsB,CAAC;gBACrC,OAAOG;YACT;YAEA,MAAMN,aAAa,MAAMjB,iBAAiBuB,SAAS9B,EAAE;YACrD,IAAI,CAACwB,cAAcA,WAAWtC,IAAI,KAAK2C,gBAAgB;gBACrDlE,mBAAmB,GAAGgE,OAAO,kCAAkC,EAAEE,eAAe,QAAQ,CAAC;YAC3F,OAAOjC,aAAa6B,IAAI,CAAC;gBAAC,GAAGD,UAAU;gBAAES,WAAWN;YAAM;YAC1D,OAAOG;QACT;IACF;IAEA,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
+ {"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 {getFederationHostApi} from './plugins/plugin-federation-host.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 enabledSharing = 'disabledReason' in sharing ? undefined : sharing\n const host = getFederationHostApi(plugins)\n if (host) host.sharing = enabledSharing\n const replacement = federation.create(enabledSharing)\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 // A reused standalone build served the host module before discovery settled its providers.\n await (reuseStandaloneBuild && !host?.requested\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","getFederationHostApi","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","enabledSharing","undefined","host","replacement","create","flatMap","customLogger","warn","disabledReason","requested","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,oBAAoB,QAAO,sCAAqC;AACxE,SAAQC,gBAAgB,QAAO,wCAAuC;AACtE,SACEC,2BAA2B,EAC3BC,uBAAuB,EACvBC,wBAAwB,QAEnB,2BAA0B;AAEjC,OAAO,eAAeC,kBACp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gBACrC,OAAOG;YACT;YAEA,MAAMN,aAAa,MAAMjB,iBAAiBuB,SAAS9B,EAAE;YACrD,IAAI,CAACwB,cAAcA,WAAWtC,IAAI,KAAK2C,gBAAgB;gBACrDnE,mBAAmB,GAAGiE,OAAO,kCAAkC,EAAEE,eAAe,QAAQ,CAAC;YAC3F,OAAOjC,aAAa6B,IAAI,CAAC;gBAAC,GAAGD,UAAU;gBAAES,WAAWN;YAAM;YAC1D,OAAOG;QACT;IACF;IAEA,OAAO;QACL7E,YAAY,IAAOS,iBAAiB;gBAACA;YAAc,IAAIpC,wBAAwBsE;QAC/EvD;IACF;AACF;AAEA,eAAe+D,oBACbH,SAAiB;IAEjB,IAAI;QACF,OAAOiC,KAAKC,KAAK,CAAC,MAAMrH,SAASC,KAAKqH,IAAI,CAACnC,WAAW,iBAAiB;IAIzE,EAAE,OAAOvB,OAAO;QACd,IAAI,AAACA,MAAgC2D,IAAI,KAAK,UAAU,OAAOlF;QAC/D,MAAMuB;IACR;AACF"}
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { artifactExposes, workbenchArtifacts } from '../artifact.js';
3
3
  import { FEDERATION_FILE_NAME, RUNTIME_DIR } from './constants.js';
4
+ import { sanityFederationHost } from './plugins/plugin-federation-host.js';
4
5
  import { sanityModuleFederation } from './plugins/plugin-module-federation.js';
5
6
  import { sanityEnvironmentPlugin } from './plugins/plugin-sanity-environment.js';
6
7
  import { sanityExtensionArtifacts } from './plugins/plugin-sanity-extension-artifacts.js';
@@ -67,7 +68,8 @@ import { sanityFederationRuntime } from './plugins/plugin-sanity-federation-runt
67
68
  sanityModuleFederation({
68
69
  exposes: federationExposes,
69
70
  name
70
- })
71
+ }),
72
+ sanityFederationHost()
71
73
  ];
72
74
  };
73
75
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/vite/plugin.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type ModuleFederationOptions} from '@module-federation/vite'\nimport {type PackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {artifactExposes, workbenchArtifacts} from '../artifact.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './constants.js'\nimport {type FederationOptions, sanityModuleFederation} from './plugins/plugin-module-federation.js'\nimport {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // Each view component (`./views/<view>/<component>`) and each service loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A service's\n // worker bundle carries no expose — the host reaches it through its loader.\n const artifacts = workbenchArtifacts(exposes ?? {})\n const artifactModuleExposes = artifactExposes(artifacts, (artifactPath) =>\n resolveEntryPath(`./${RUNTIME_DIR}/${artifactPath}`),\n )\n\n // A dock-only app (`isApp` with no `appEntry`) has no navigable full-page\n // view, so it exposes no `./App` — only its views. Studios and apps with an\n // entry expose `./App` (the generated render entry).\n const exposesApp = !options.isApp || options.appEntry !== undefined\n\n const federationExposes: NonNullable<ModuleFederationOptions['exposes']> = {\n ...(exposesApp ? {'./App': entryPath} : {}),\n ...artifactModuleExposes,\n }\n\n const runtimeOptions: FederationRuntimeOptions = options.isApp\n ? {appEntry: options.appEntry, isApp: true, isBlueprints}\n : {isApp: false, isBlueprints, studioConfigPath: options.studioConfigPath}\n\n // Every federated app and studio also serves itself standalone. Whenever there's\n // an `./App` to mount (never for a dock-only app), build the SPA client\n // environment from the runtime bootstrap cli-build writes.\n const clientInput = exposesApp ? path.join(workDir, '.sanity', 'runtime', 'app.js') : undefined\n\n return [\n sanityEnvironmentPlugin({clientInput, input: entryPath, isBlueprints}),\n sanityFederationRuntime(runtimeOptions),\n sanityExtensionArtifacts({artifacts}),\n sanityModuleFederation({exposes: federationExposes, name}),\n ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityModuleFederation","sanityEnvironmentPlugin","sanityExtensionArtifacts","sanityFederationRuntime","federation","options","exposes","isBlueprints","name","defaultName","pkgJson","workDir","process","cwd","Error","generatedEntry","resolveEntryPath","entry","resolvedPath","resolve","entryPath","artifacts","artifactModuleExposes","artifactPath","exposesApp","isApp","appEntry","undefined","federationExposes","runtimeOptions","studioConfigPath","clientInput","join","input"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC,eAAe,EAAEC,kBAAkB,QAAO,iBAAgB;AAClE,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,iBAAgB;AAChE,SAAgCC,sBAAsB,QAAO,wCAAuC;AACpG,SAAQC,uBAAuB,QAAO,yCAAwC;AAC9E,SAAQC,wBAAwB,QAAO,iDAAgD;AACvF,SAEEC,uBAAuB,QAClB,gDAA+C;AA6CtD;;CAEC,GACD,OAAO,MAAMC,aAAa,CAACC;IACzB,MAAM,EAACC,OAAO,EAAEC,YAAY,EAAEC,MAAMC,WAAW,EAAEC,OAAO,EAAEC,UAAUC,QAAQC,GAAG,EAAE,EAAC,GAAGR;IAErF,IAAIG,OAAOC;IAEX,IAAI,CAACD,MAAM;QACTA,OAAOE,SAASF;IAClB;IAEA,IAAI,CAACA,MAAM;QACT,MAAM,IAAIM,MAAM;IAClB;IAEA,MAAMC,iBAAiB,CAAC,EAAE,EAAEhB,YAAY,CAAC,EAAED,qBAAqB,IAAI,CAAC;IAErE,SAASkB,iBAAiBC,KAAa;QACrC,MAAMC,eAAevB,KAAKwB,OAAO,CAACR,SAASM;QAE3C,IAAI,CAACC,cAAc;YACjB,MAAM,IAAIJ,MACR,CAAC,kCAAkC,EAAEG,MAAM,6DAA6D,CAAC;QAE7G;QAEA,OAAOC;IACT;IAEA,MAAME,YAAYJ,iBAAiBD;IAEnC,6EAA6E;IAC7E,8EAA8E;IAC9E,0EAA0E;IAC1E,4EAA4E;IAC5E,MAAMM,YAAYxB,mBAAmBS,WAAW,CAAC;IACjD,MAAMgB,wBAAwB1B,gBAAgByB,WAAW,CAACE,eACxDP,iBAAiB,CAAC,EAAE,EAAEjB,YAAY,CAAC,EAAEwB,cAAc;IAGrD,0EAA0E;IAC1E,4EAA4E;IAC5E,qDAAqD;IACrD,MAAMC,aAAa,CAACnB,QAAQoB,KAAK,IAAIpB,QAAQqB,QAAQ,KAAKC;IAE1D,MAAMC,oBAAqE;QACzE,GAAIJ,aAAa;YAAC,SAASJ;QAAS,IAAI,CAAC,CAAC;QAC1C,GAAGE,qBAAqB;IAC1B;IAEA,MAAMO,iBAA2CxB,QAAQoB,KAAK,GAC1D;QAACC,UAAUrB,QAAQqB,QAAQ;QAAED,OAAO;QAAMlB;IAAY,IACtD;QAACkB,OAAO;QAAOlB;QAAcuB,kBAAkBzB,QAAQyB,gBAAgB;IAAA;IAE3E,iFAAiF;IACjF,wEAAwE;IACxE,2DAA2D;IAC3D,MAAMC,cAAcP,aAAa7B,KAAKqC,IAAI,CAACrB,SAAS,WAAW,WAAW,YAAYgB;IAEtF,OAAO;QACL1B,wBAAwB;YAAC8B;YAAaE,OAAOb;YAAWb;QAAY;QACpEJ,wBAAwB0B;QACxB3B,yBAAyB;YAACmB;QAAS;QACnCrB,uBAAuB;YAACM,SAASsB;YAAmBpB;QAAI;KACzD;AACH,EAAC"}
1
+ {"version":3,"sources":["../../../../src/actions/build/vite/plugin.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type ModuleFederationOptions} from '@module-federation/vite'\nimport {type PackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {artifactExposes, workbenchArtifacts} from '../artifact.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './constants.js'\nimport {sanityFederationHost} from './plugins/plugin-federation-host.js'\nimport {type FederationOptions, sanityModuleFederation} from './plugins/plugin-module-federation.js'\nimport {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // Each view component (`./views/<view>/<component>`) and each service loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A service's\n // worker bundle carries no expose — the host reaches it through its loader.\n const artifacts = workbenchArtifacts(exposes ?? {})\n const artifactModuleExposes = artifactExposes(artifacts, (artifactPath) =>\n resolveEntryPath(`./${RUNTIME_DIR}/${artifactPath}`),\n )\n\n // A dock-only app (`isApp` with no `appEntry`) has no navigable full-page\n // view, so it exposes no `./App` — only its views. Studios and apps with an\n // entry expose `./App` (the generated render entry).\n const exposesApp = !options.isApp || options.appEntry !== undefined\n\n const federationExposes: NonNullable<ModuleFederationOptions['exposes']> = {\n ...(exposesApp ? {'./App': entryPath} : {}),\n ...artifactModuleExposes,\n }\n\n const runtimeOptions: FederationRuntimeOptions = options.isApp\n ? {appEntry: options.appEntry, isApp: true, isBlueprints}\n : {isApp: false, isBlueprints, studioConfigPath: options.studioConfigPath}\n\n // Every federated app and studio also serves itself standalone. Whenever there's\n // an `./App` to mount (never for a dock-only app), build the SPA client\n // environment from the runtime bootstrap cli-build writes.\n const clientInput = exposesApp ? path.join(workDir, '.sanity', 'runtime', 'app.js') : undefined\n\n return [\n sanityEnvironmentPlugin({clientInput, input: entryPath, isBlueprints}),\n sanityFederationRuntime(runtimeOptions),\n sanityExtensionArtifacts({artifacts}),\n sanityModuleFederation({exposes: federationExposes, name}),\n sanityFederationHost(),\n ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityFederationHost","sanityModuleFederation","sanityEnvironmentPlugin","sanityExtensionArtifacts","sanityFederationRuntime","federation","options","exposes","isBlueprints","name","defaultName","pkgJson","workDir","process","cwd","Error","generatedEntry","resolveEntryPath","entry","resolvedPath","resolve","entryPath","artifacts","artifactModuleExposes","artifactPath","exposesApp","isApp","appEntry","undefined","federationExposes","runtimeOptions","studioConfigPath","clientInput","join","input"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC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,aAAa;YAAC,SAASJ;QAAS,IAAI,CAAC,CAAC;QAC1C,GAAGE,qBAAqB;IAC1B;IAEA,MAAMO,iBAA2CxB,QAAQoB,KAAK,GAC1D;QAACC,UAAUrB,QAAQqB,QAAQ;QAAED,OAAO;QAAMlB;IAAY,IACtD;QAACkB,OAAO;QAAOlB;QAAcuB,kBAAkBzB,QAAQyB,gBAAgB;IAAA;IAE3E,iFAAiF;IACjF,wEAAwE;IACxE,2DAA2D;IAC3D,MAAMC,cAAcP,aAAa9B,KAAKsC,IAAI,CAACrB,SAAS,WAAW,WAAW,YAAYgB;IAEtF,OAAO;QACL1B,wBAAwB;YAAC8B;YAAaE,OAAOb;YAAWb;QAAY;QACpEJ,wBAAwB0B;QACxB3B,yBAAyB;YAACmB;QAAS;QACnCrB,uBAAuB;YAACM,SAASsB;YAAmBpB;QAAI;QACxDT;KACD;AACH,EAAC"}
@@ -0,0 +1,46 @@
1
+ export const FEDERATION_HOST_ID = 'virtual:sanity/federation-host';
2
+ const RESOLVED_ID = `\0${FEDERATION_HOST_ID}`;
3
+ export function getFederationHostApi(plugins) {
4
+ return plugins.find((plugin)=>plugin.api?.sanityFederationHost)?.api.sanityFederationHost;
5
+ }
6
+ // Hands the standalone build's own copies of shared dependencies to the apps it loads: its SPA
7
+ // never initializes a federation container, so each app would otherwise download a second copy.
8
+ export function sanityFederationHost() {
9
+ const api = {
10
+ requested: false
11
+ };
12
+ return {
13
+ api: {
14
+ sanityFederationHost: api
15
+ },
16
+ load (id) {
17
+ if (id !== RESOLVED_ID) return;
18
+ api.requested = true;
19
+ return federationHostModule(this.environment.name === 'client' ? api.sharing : undefined);
20
+ },
21
+ name: 'sanity/federation-host',
22
+ resolveId: (id)=>id === FEDERATION_HOST_ID ? RESOLVED_ID : undefined
23
+ };
24
+ }
25
+ function federationHostModule(sharing) {
26
+ const entries = Object.entries(sharing?.shared ?? {});
27
+ const imports = entries.map(([specifier], index)=>`import * as m${index} from ${JSON.stringify(specifier)}\n`);
28
+ const providers = entries.map(([specifier, entry], index)=>{
29
+ const { requiredVersion, shareScope, singleton, strictVersion, version } = entry;
30
+ const options = {
31
+ scope: [
32
+ shareScope
33
+ ],
34
+ shareConfig: {
35
+ requiredVersion,
36
+ singleton,
37
+ strictVersion
38
+ },
39
+ version
40
+ };
41
+ return ` ${JSON.stringify(specifier)}: {...${JSON.stringify(options)}, lib: () => m${index}, loaded: true},\n`;
42
+ });
43
+ return `${imports.join('')}export const shared = {\n${providers.join('')}}\n`;
44
+ }
45
+
46
+ //# sourceMappingURL=plugin-federation-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-federation-host.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {type FederationSharing} from '../shared-dependencies.js'\n\nexport const FEDERATION_HOST_ID = 'virtual:sanity/federation-host'\nconst RESOLVED_ID = `\\0${FEDERATION_HOST_ID}`\n\nexport interface FederationHostApi {\n requested: boolean\n\n sharing?: FederationSharing\n}\n\nexport function getFederationHostApi(plugins: readonly Plugin[]): FederationHostApi | undefined {\n return plugins.find((plugin) => plugin.api?.sanityFederationHost)?.api.sanityFederationHost\n}\n\n// Hands the standalone build's own copies of shared dependencies to the apps it loads: its SPA\n// never initializes a federation container, so each app would otherwise download a second copy.\nexport function sanityFederationHost(): Plugin {\n const api: FederationHostApi = {requested: false}\n return {\n api: {sanityFederationHost: api},\n load(id) {\n if (id !== RESOLVED_ID) return\n api.requested = true\n return federationHostModule(this.environment.name === 'client' ? api.sharing : undefined)\n },\n name: 'sanity/federation-host',\n resolveId: (id) => (id === FEDERATION_HOST_ID ? RESOLVED_ID : undefined),\n }\n}\n\nfunction federationHostModule(sharing: FederationSharing | undefined): string {\n const entries = Object.entries(sharing?.shared ?? {})\n const imports = entries.map(\n ([specifier], index) => `import * as m${index} from ${JSON.stringify(specifier)}\\n`,\n )\n const providers = entries.map(([specifier, entry], index) => {\n const {requiredVersion, shareScope, singleton, strictVersion, version} = entry\n const options = {\n scope: [shareScope],\n shareConfig: {requiredVersion, singleton, strictVersion},\n version,\n }\n return ` ${JSON.stringify(specifier)}: {...${JSON.stringify(options)}, lib: () => m${index}, loaded: true},\\n`\n })\n return `${imports.join('')}export const shared = {\\n${providers.join('')}}\\n`\n}\n"],"names":["FEDERATION_HOST_ID","RESOLVED_ID","getFederationHostApi","plugins","find","plugin","api","sanityFederationHost","requested","load","id","federationHostModule","environment","name","sharing","undefined","resolveId","entries","Object","shared","imports","map","specifier","index","JSON","stringify","providers","entry","requiredVersion","shareScope","singleton","strictVersion","version","options","scope","shareConfig","join"],"mappings":"AAIA,OAAO,MAAMA,qBAAqB,iCAAgC;AAClE,MAAMC,cAAc,CAAC,EAAE,EAAED,oBAAoB;AAQ7C,OAAO,SAASE,qBAAqBC,OAA0B;IAC7D,OAAOA,QAAQC,IAAI,CAAC,CAACC,SAAWA,OAAOC,GAAG,EAAEC,uBAAuBD,IAAIC;AACzE;AAEA,+FAA+F;AAC/F,gGAAgG;AAChG,OAAO,SAASA;IACd,MAAMD,MAAyB;QAACE,WAAW;IAAK;IAChD,OAAO;QACLF,KAAK;YAACC,sBAAsBD;QAAG;QAC/BG,MAAKC,EAAE;YACL,IAAIA,OAAOT,aAAa;YACxBK,IAAIE,SAAS,GAAG;YAChB,OAAOG,qBAAqB,IAAI,CAACC,WAAW,CAACC,IAAI,KAAK,WAAWP,IAAIQ,OAAO,GAAGC;QACjF;QACAF,MAAM;QACNG,WAAW,CAACN,KAAQA,OAAOV,qBAAqBC,cAAcc;IAChE;AACF;AAEA,SAASJ,qBAAqBG,OAAsC;IAClE,MAAMG,UAAUC,OAAOD,OAAO,CAACH,SAASK,UAAU,CAAC;IACnD,MAAMC,UAAUH,QAAQI,GAAG,CACzB,CAAC,CAACC,UAAU,EAAEC,QAAU,CAAC,aAAa,EAAEA,MAAM,MAAM,EAAEC,KAAKC,SAAS,CAACH,WAAW,EAAE,CAAC;IAErF,MAAMI,YAAYT,QAAQI,GAAG,CAAC,CAAC,CAACC,WAAWK,MAAM,EAAEJ;QACjD,MAAM,EAACK,eAAe,EAAEC,UAAU,EAAEC,SAAS,EAAEC,aAAa,EAAEC,OAAO,EAAC,GAAGL;QACzE,MAAMM,UAAU;YACdC,OAAO;gBAACL;aAAW;YACnBM,aAAa;gBAACP;gBAAiBE;gBAAWC;YAAa;YACvDC;QACF;QACA,OAAO,CAAC,EAAE,EAAER,KAAKC,SAAS,CAACH,WAAW,MAAM,EAAEE,KAAKC,SAAS,CAACQ,SAAS,cAAc,EAAEV,MAAM,kBAAkB,CAAC;IACjH;IACA,OAAO,GAAGH,QAAQgB,IAAI,CAAC,IAAI,yBAAyB,EAAEV,UAAUU,IAAI,CAAC,IAAI,GAAG,CAAC;AAC/E"}
@@ -23,9 +23,11 @@ export function sanityEnvironmentPlugin(options) {
23
23
  return {
24
24
  builder: {
25
25
  async buildApp (builder) {
26
- // `emptyOutDir` is false on both environments and the CLI clears
27
- // `dist` once up-front, so the SPA and federation outputs coexist
28
- // without either build wiping the other's files.
26
+ // Both environments inherit the top-level `build.outDir` (`dist` by
27
+ // default, or the `outputDir` a caller such as Blueprints passes).
28
+ // `emptyOutDir` is false on both and the CLI clears the output dir
29
+ // once up-front, so the SPA and federation outputs coexist without
30
+ // either build wiping the other's files.
29
31
  if (clientInput) {
30
32
  await builder.build(builder.environments.client);
31
33
  }
@@ -39,7 +41,6 @@ export function sanityEnvironmentPlugin(options) {
39
41
  assetsDir: 'static',
40
42
  copyPublicDir: false,
41
43
  emptyOutDir: false,
42
- outDir: `dist`,
43
44
  rolldownOptions: {
44
45
  input: {
45
46
  sanity: clientInput
@@ -55,7 +56,6 @@ export function sanityEnvironmentPlugin(options) {
55
56
  assetsDir: 'static',
56
57
  copyPublicDir: false,
57
58
  emptyOutDir: false,
58
- outDir: `dist`,
59
59
  rolldownOptions: {
60
60
  input,
61
61
  output
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-environment.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../../resource-bindings.js'\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\n// Keep the resource-bindings module in its own unhashed chunk at the bundle root\n// so Brett can rewrite it at deploy. `@module-federation/vite` preserves user\n// `codeSplitting` groups (clamped below its own), so this survives the federation\n// build. The chunk sizing lives on the group itself (see\n// `resourceBindingsCodeSplittingGroup`), so it only affects the bindings module.\nconst resourceBindingsOutput = {\n chunkFileNames: (chunk: {name: string}) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n}\n\ninterface EnvironmentOptions {\n input: string\n\n /**\n * When set, also build a standalone `client` SPA environment (its own\n * `index.html` + bootstrap) alongside the federation remote, from this entry.\n * Set for every federated app and studio; omitted only for a dock-only app.\n */\n clientInput?: string\n\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\nexport function sanityEnvironmentPlugin(options: EnvironmentOptions): Plugin {\n const {clientInput, input, isBlueprints} = options\n\n // Blueprints only: force the resource-bindings module into its own unhashed\n // chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.\n const output = isBlueprints ? resourceBindingsOutput : undefined\n\n return {\n config() {\n return {\n builder: {\n async buildApp(builder) {\n // `emptyOutDir` is false on both environments and the CLI clears\n // `dist` once up-front, so the SPA and federation outputs coexist\n // without either build wiping the other's files.\n if (clientInput) {\n await builder.build(builder.environments.client)\n }\n await builder.build(builder.environments[FEDERATION_DIR_NAME])\n },\n },\n environments: {\n ...(clientInput\n ? {\n client: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n outDir: `dist`,\n rolldownOptions: {\n input: {sanity: clientInput},\n output,\n },\n },\n consumer: 'client',\n },\n }\n : {}),\n [FEDERATION_DIR_NAME]: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n outDir: `dist`,\n rolldownOptions: {input, output},\n },\n consumer: 'client',\n },\n },\n }\n },\n name: 'sanity/environment',\n }\n}\n"],"names":["resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","FEDERATION_DIR_NAME","resourceBindingsOutput","chunkFileNames","chunk","name","codeSplitting","groups","sanityEnvironmentPlugin","options","clientInput","input","isBlueprints","output","undefined","config","builder","buildApp","build","environments","client","assetsDir","copyPublicDir","emptyOutDir","outDir","rolldownOptions","sanity","consumer"],"mappings":"AAEA,SACEA,6BAA6B,EAC7BC,kCAAkC,QAC7B,6BAA4B;AACnC,SAAQC,mBAAmB,QAAO,kBAAiB;AAEnD,iFAAiF;AACjF,8EAA8E;AAC9E,kFAAkF;AAClF,yDAAyD;AACzD,iFAAiF;AACjF,MAAMC,yBAAyB;IAC7BC,gBAAgB,CAACC,QACfL,8BAA8BK,MAAMC,IAAI,KAAK;IAC/CC,eAAe;QACbC,QAAQ;YAACP;SAAmC;IAC9C;AACF;AAgBA,OAAO,SAASQ,wBAAwBC,OAA2B;IACjE,MAAM,EAACC,WAAW,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGH;IAE3C,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAMI,SAASD,eAAeV,yBAAyBY;IAEvD,OAAO;QACLC;YACE,OAAO;gBACLC,SAAS;oBACP,MAAMC,UAASD,OAAO;wBACpB,iEAAiE;wBACjE,kEAAkE;wBAClE,iDAAiD;wBACjD,IAAIN,aAAa;4BACf,MAAMM,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAACC,MAAM;wBACjD;wBACA,MAAMJ,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAAClB,oBAAoB;oBAC/D;gBACF;gBACAkB,cAAc;oBACZ,GAAIT,cACA;wBACEU,QAAQ;4BACNF,OAAO;gCACLG,WAAW;gCACXC,eAAe;gCACfC,aAAa;gCACbC,QAAQ,CAAC,IAAI,CAAC;gCACdC,iBAAiB;oCACfd,OAAO;wCAACe,QAAQhB;oCAAW;oCAC3BG;gCACF;4BACF;4BACAc,UAAU;wBACZ;oBACF,IACA,CAAC,CAAC;oBACN,CAAC1B,oBAAoB,EAAE;wBACrBiB,OAAO;4BACLG,WAAW;4BACXC,eAAe;4BACfC,aAAa;4BACbC,QAAQ,CAAC,IAAI,CAAC;4BACdC,iBAAiB;gCAACd;gCAAOE;4BAAM;wBACjC;wBACAc,UAAU;oBACZ;gBACF;YACF;QACF;QACAtB,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-environment.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../../resource-bindings.js'\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\n// Keep the resource-bindings module in its own unhashed chunk at the bundle root\n// so Brett can rewrite it at deploy. `@module-federation/vite` preserves user\n// `codeSplitting` groups (clamped below its own), so this survives the federation\n// build. The chunk sizing lives on the group itself (see\n// `resourceBindingsCodeSplittingGroup`), so it only affects the bindings module.\nconst resourceBindingsOutput = {\n chunkFileNames: (chunk: {name: string}) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n}\n\ninterface EnvironmentOptions {\n input: string\n\n /**\n * When set, also build a standalone `client` SPA environment (its own\n * `index.html` + bootstrap) alongside the federation remote, from this entry.\n * Set for every federated app and studio; omitted only for a dock-only app.\n */\n clientInput?: string\n\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\nexport function sanityEnvironmentPlugin(options: EnvironmentOptions): Plugin {\n const {clientInput, input, isBlueprints} = options\n\n // Blueprints only: force the resource-bindings module into its own unhashed\n // chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.\n const output = isBlueprints ? resourceBindingsOutput : undefined\n\n return {\n config() {\n return {\n builder: {\n async buildApp(builder) {\n // Both environments inherit the top-level `build.outDir` (`dist` by\n // default, or the `outputDir` a caller such as Blueprints passes).\n // `emptyOutDir` is false on both and the CLI clears the output dir\n // once up-front, so the SPA and federation outputs coexist without\n // either build wiping the other's files.\n if (clientInput) {\n await builder.build(builder.environments.client)\n }\n await builder.build(builder.environments[FEDERATION_DIR_NAME])\n },\n },\n environments: {\n ...(clientInput\n ? {\n client: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {\n input: {sanity: clientInput},\n output,\n },\n },\n consumer: 'client',\n },\n }\n : {}),\n [FEDERATION_DIR_NAME]: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {input, output},\n },\n consumer: 'client',\n },\n },\n }\n },\n name: 'sanity/environment',\n }\n}\n"],"names":["resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","FEDERATION_DIR_NAME","resourceBindingsOutput","chunkFileNames","chunk","name","codeSplitting","groups","sanityEnvironmentPlugin","options","clientInput","input","isBlueprints","output","undefined","config","builder","buildApp","build","environments","client","assetsDir","copyPublicDir","emptyOutDir","rolldownOptions","sanity","consumer"],"mappings":"AAEA,SACEA,6BAA6B,EAC7BC,kCAAkC,QAC7B,6BAA4B;AACnC,SAAQC,mBAAmB,QAAO,kBAAiB;AAEnD,iFAAiF;AACjF,8EAA8E;AAC9E,kFAAkF;AAClF,yDAAyD;AACzD,iFAAiF;AACjF,MAAMC,yBAAyB;IAC7BC,gBAAgB,CAACC,QACfL,8BAA8BK,MAAMC,IAAI,KAAK;IAC/CC,eAAe;QACbC,QAAQ;YAACP;SAAmC;IAC9C;AACF;AAgBA,OAAO,SAASQ,wBAAwBC,OAA2B;IACjE,MAAM,EAACC,WAAW,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGH;IAE3C,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAMI,SAASD,eAAeV,yBAAyBY;IAEvD,OAAO;QACLC;YACE,OAAO;gBACLC,SAAS;oBACP,MAAMC,UAASD,OAAO;wBACpB,oEAAoE;wBACpE,mEAAmE;wBACnE,mEAAmE;wBACnE,mEAAmE;wBACnE,yCAAyC;wBACzC,IAAIN,aAAa;4BACf,MAAMM,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAACC,MAAM;wBACjD;wBACA,MAAMJ,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAAClB,oBAAoB;oBAC/D;gBACF;gBACAkB,cAAc;oBACZ,GAAIT,cACA;wBACEU,QAAQ;4BACNF,OAAO;gCACLG,WAAW;gCACXC,eAAe;gCACfC,aAAa;gCACbC,iBAAiB;oCACfb,OAAO;wCAACc,QAAQf;oCAAW;oCAC3BG;gCACF;4BACF;4BACAa,UAAU;wBACZ;oBACF,IACA,CAAC,CAAC;oBACN,CAACzB,oBAAoB,EAAE;wBACrBiB,OAAO;4BACLG,WAAW;4BACXC,eAAe;4BACfC,aAAa;4BACbC,iBAAiB;gCAACb;gCAAOE;4BAAM;wBACjC;wBACAa,UAAU;oBACZ;gBACF;YACF;QACF;QACArB,MAAM;IACR;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/vite/shared-dependencies.ts"],"sourcesContent":["import {type ModuleFederationOptions} from '@module-federation/vite'\nimport {valid as validSemver} from 'semver'\n\ninterface SharedDependency {\n // Package name used for import matching and in the share scope.\n name: string\n\n // Optional packages do not disable sharing when an app does not use them.\n optional?: boolean\n // `false` selects this package's exact version without splitting the React compatibility group.\n scope?: false\n // `false` checks compatibility without publishing the package as a provider.\n share?: false\n}\n\n// Add approved packages here; versions contribute to the scope unless explicitly excluded.\nconst sharedDependencies: readonly SharedDependency[] = [\n {name: 'react'},\n {name: 'react-dom'},\n // React DOM owns scheduler's mutable queue, so only its version joins the scope.\n {name: 'scheduler', share: false},\n {name: 'styled-components', optional: true, scope: false},\n]\n\n// Vite injects these aliases for its own modules; neither can redirect a shared package import.\nconst viteInternalAliases = new Set([/^\\/?@vite\\/client/.source, /^\\/?@vite\\/env/.source])\n\nexport interface ResolvedDependency {\n name: string\n root: string\n version: string\n\n specifier?: string\n}\n\ntype SharedEntries = Exclude<ModuleFederationOptions['shared'], string[] | undefined>\n\nexport interface FederationSharing extends Pick<\n ModuleFederationOptions,\n 'shareScope' | 'shareStrategy'\n> {\n shared: SharedEntries\n}\n\nexport function findSharedDependencyName(specifier: string): string | undefined {\n return sharedDependencies.find(({name}) => specifier === name || specifier.startsWith(`${name}/`))\n ?.name\n}\n\nexport function createFederationSharing(\n dependencies: ResolvedDependency[],\n): FederationSharing | {disabledReason: string} {\n const versions = resolveCompatibleVersions(dependencies)\n if (!(versions instanceof Map)) return versions\n\n // React and its renderer must agree; styled-components selects its own exact version in this pool.\n const shareScope =\n 'sanity-' +\n sharedDependencies\n .filter(({scope}) => scope !== false)\n .map(({name}) => `${name}-${versions.get(name)}`)\n .join('-')\n return {\n shared: createSharedEntries(dependencies, shareScope),\n // The array form makes Module Federation use named pools instead of the host's default pool.\n shareScope: [shareScope],\n // Prefer a compatible provider that another app already loaded before downloading a local copy.\n shareStrategy: 'loaded-first',\n }\n}\n\nexport function aliasMayRewriteSharedImport(find: RegExp | string): boolean {\n if (typeof find === 'string') {\n return (\n Boolean(findSharedDependencyName(find)) ||\n sharedDependencies.some(({name}) => name.startsWith(`${find}/`))\n )\n }\n\n if (find.ignoreCase || find.multiline) return true\n if (viteInternalAliases.has(find.source)) return false\n\n // Only accept a literal prefix like /^@app\\//; more complex regexes may also match shared imports.\n const namespace = find.source.match(/^\\^([@\\w-]+)\\\\\\/$/u)?.[1]\n if (!namespace) return true\n return sharedDependencies.some(({name}) => name === namespace || name.startsWith(`${namespace}/`))\n}\n\nfunction resolveCompatibleVersions(\n dependencies: ResolvedDependency[],\n): Map<string, string> | {disabledReason: string} {\n const versions = new Map<string, string>()\n for (const {name, optional} of sharedDependencies) {\n const copies = dependencies.filter((dependency) => dependency.name === name)\n if (copies.length === 0 && optional) {\n versions.set(name, 'none')\n continue\n }\n if (copies.length === 0) return {disabledReason: `No installed copy of ${name} was found`}\n const {root, version} = copies[0]\n if (copies.some((copy) => copy.root !== root || copy.version !== version)) {\n return {disabledReason: `Multiple installed copies of ${name} were found`}\n }\n // pnpm patch hashes identify different package code under the same version, so patched copies stay local.\n if (root.includes('patch_hash=')) return {disabledReason: `${name} has a local pnpm patch`}\n // Semver ignores build metadata, so only its unchanged canonical form is safe to share.\n if (validSemver(version) !== version) {\n return {disabledReason: `${name} has an unsupported version: ${JSON.stringify(version)}`}\n }\n versions.set(name, version)\n }\n\n // Sharing the renderer without its React import would split hook and context identity.\n if (!dependencies.some(({name, specifier}) => name === 'react' && specifier === 'react')) {\n return {disabledReason: 'The react import could not be resolved to a shared provider'}\n }\n if (versions.get('react') !== versions.get('react-dom')) {\n return {\n disabledReason: `React (${versions.get('react')}) and React DOM (${versions.get('react-dom')}) versions differ`,\n }\n }\n return versions\n}\n\nfunction createSharedEntries(\n dependencies: ResolvedDependency[],\n shareScope: string,\n): SharedEntries {\n const entries: SharedEntries = {}\n const providers = new Set(\n sharedDependencies.filter(({share}) => share !== false).map(({name}) => name),\n )\n for (const {name, specifier, version} of dependencies) {\n if (!specifier || !providers.has(name)) continue\n entries[specifier] = {\n eager: false,\n requiredVersion: version,\n // @module-federation/vite defaults providers to \"default\" unless each entry repeats this scope.\n shareScope,\n singleton: false,\n strictVersion: true,\n version,\n }\n }\n // Vite resolves imports concurrently, so sort providers to keep generated chunks reproducible.\n return Object.fromEntries(\n Object.entries(entries).toSorted(([left], [right]) => left.localeCompare(right)),\n )\n}\n"],"names":["valid","validSemver","sharedDependencies","name","share","optional","scope","viteInternalAliases","Set","source","findSharedDependencyName","specifier","find","startsWith","createFederationSharing","dependencies","versions","resolveCompatibleVersions","Map","shareScope","filter","map","get","join","shared","createSharedEntries","shareStrategy","aliasMayRewriteSharedImport","Boolean","some","ignoreCase","multiline","has","namespace","match","copies","dependency","length","set","disabledReason","root","version","copy","includes","JSON","stringify","entries","providers","eager","requiredVersion","singleton","strictVersion","Object","fromEntries","toSorted","left","right","localeCompare"],"mappings":"AACA,SAAQA,SAASC,WAAW,QAAO,SAAQ;AAc3C,2FAA2F;AAC3F,MAAMC,qBAAkD;IACtD;QAACC,MAAM;IAAO;IACd;QAACA,MAAM;IAAW;IAClB,iFAAiF;IACjF;QAACA,MAAM;QAAaC,OAAO;IAAK;IAChC;QAACD,MAAM;QAAqBE,UAAU;QAAMC,OAAO;IAAK;CACzD;AAED,gGAAgG;AAChG,MAAMC,sBAAsB,IAAIC,IAAI;IAAC,oBAAoBC,MAAM;IAAE,iBAAiBA,MAAM;CAAC;AAmBzF,OAAO,SAASC,yBAAyBC,SAAiB;IACxD,OAAOT,mBAAmBU,IAAI,CAAC,CAAC,EAACT,IAAI,EAAC,GAAKQ,cAAcR,QAAQQ,UAAUE,UAAU,CAAC,GAAGV,KAAK,CAAC,CAAC,IAC5FA;AACN;AAEA,OAAO,SAASW,wBACdC,YAAkC;IAElC,MAAMC,WAAWC,0BAA0BF;IAC3C,IAAI,CAAEC,CAAAA,oBAAoBE,GAAE,GAAI,OAAOF;IAEvC,mGAAmG;IACnG,MAAMG,aACJ,YACAjB,mBACGkB,MAAM,CAAC,CAAC,EAACd,KAAK,EAAC,GAAKA,UAAU,OAC9Be,GAAG,CAAC,CAAC,EAAClB,IAAI,EAAC,GAAK,GAAGA,KAAK,CAAC,EAAEa,SAASM,GAAG,CAACnB,OAAO,EAC/CoB,IAAI,CAAC;IACV,OAAO;QACLC,QAAQC,oBAAoBV,cAAcI;QAC1C,6FAA6F;QAC7FA,YAAY;YAACA;SAAW;QACxB,gGAAgG;QAChGO,eAAe;IACjB;AACF;AAEA,OAAO,SAASC,4BAA4Bf,IAAqB;IAC/D,IAAI,OAAOA,SAAS,UAAU;QAC5B,OACEgB,QAAQlB,yBAAyBE,UACjCV,mBAAmB2B,IAAI,CAAC,CAAC,EAAC1B,IAAI,EAAC,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-dependencies.ts"],"sourcesContent":["import {type ModuleFederationOptions} from '@module-federation/vite'\nimport {valid as validSemver} from 'semver'\n\ninterface SharedDependency {\n // Package name used for import matching and in the share scope.\n name: string\n\n // Optional packages do not disable sharing when an app does not use them.\n optional?: boolean\n // `false` selects this package's exact version without splitting the React compatibility group.\n scope?: false\n // `false` checks compatibility without publishing the package as a provider.\n share?: false\n}\n\n// Add approved packages here; versions contribute to the scope unless explicitly excluded.\nconst sharedDependencies: readonly SharedDependency[] = [\n {name: 'react'},\n {name: 'react-dom'},\n // React DOM owns scheduler's mutable queue, so only its version joins the scope.\n {name: 'scheduler', share: false},\n {name: 'styled-components', optional: true, scope: false},\n]\n\n// Vite injects these aliases for its own modules; neither can redirect a shared package import.\nconst viteInternalAliases = new Set([/^\\/?@vite\\/client/.source, /^\\/?@vite\\/env/.source])\n\nexport interface ResolvedDependency {\n name: string\n root: string\n version: string\n\n specifier?: string\n}\n\ntype SharedEntries = Exclude<ModuleFederationOptions['shared'], string[] | undefined>\ntype SharedEntry = Extract<SharedEntries[string], object> & {shareScope: string}\n\nexport interface FederationSharing extends Pick<\n ModuleFederationOptions,\n 'shareScope' | 'shareStrategy'\n> {\n shared: Record<string, SharedEntry>\n}\n\nexport function findSharedDependencyName(specifier: string): string | undefined {\n return sharedDependencies.find(({name}) => specifier === name || specifier.startsWith(`${name}/`))\n ?.name\n}\n\nexport function createFederationSharing(\n dependencies: ResolvedDependency[],\n): FederationSharing | {disabledReason: string} {\n const versions = resolveCompatibleVersions(dependencies)\n if (!(versions instanceof Map)) return versions\n\n // React and its renderer must agree; styled-components selects its own exact version in this pool.\n const shareScope =\n 'sanity-' +\n sharedDependencies\n .filter(({scope}) => scope !== false)\n .map(({name}) => `${name}-${versions.get(name)}`)\n .join('-')\n return {\n shared: createSharedEntries(dependencies, shareScope),\n // The array form makes Module Federation use named pools instead of the host's default pool.\n shareScope: [shareScope],\n // Prefer a compatible provider that another app already loaded before downloading a local copy.\n shareStrategy: 'loaded-first',\n }\n}\n\nexport function aliasMayRewriteSharedImport(find: RegExp | string): boolean {\n if (typeof find === 'string') {\n return (\n Boolean(findSharedDependencyName(find)) ||\n sharedDependencies.some(({name}) => name.startsWith(`${find}/`))\n )\n }\n\n if (find.ignoreCase || find.multiline) return true\n if (viteInternalAliases.has(find.source)) return false\n\n // Only accept a literal prefix like /^@app\\//; more complex regexes may also match shared imports.\n const namespace = find.source.match(/^\\^([@\\w-]+)\\\\\\/$/u)?.[1]\n if (!namespace) return true\n return sharedDependencies.some(({name}) => name === namespace || name.startsWith(`${namespace}/`))\n}\n\nfunction resolveCompatibleVersions(\n dependencies: ResolvedDependency[],\n): Map<string, string> | {disabledReason: string} {\n const versions = new Map<string, string>()\n for (const {name, optional} of sharedDependencies) {\n const copies = dependencies.filter((dependency) => dependency.name === name)\n if (copies.length === 0 && optional) {\n versions.set(name, 'none')\n continue\n }\n if (copies.length === 0) return {disabledReason: `No installed copy of ${name} was found`}\n const {root, version} = copies[0]\n if (copies.some((copy) => copy.root !== root || copy.version !== version)) {\n return {disabledReason: `Multiple installed copies of ${name} were found`}\n }\n // pnpm patch hashes identify different package code under the same version, so patched copies stay local.\n if (root.includes('patch_hash=')) return {disabledReason: `${name} has a local pnpm patch`}\n // Semver ignores build metadata, so only its unchanged canonical form is safe to share.\n if (validSemver(version) !== version) {\n return {disabledReason: `${name} has an unsupported version: ${JSON.stringify(version)}`}\n }\n versions.set(name, version)\n }\n\n // Sharing the renderer without its React import would split hook and context identity.\n if (!dependencies.some(({name, specifier}) => name === 'react' && specifier === 'react')) {\n return {disabledReason: 'The react import could not be resolved to a shared provider'}\n }\n if (versions.get('react') !== versions.get('react-dom')) {\n return {\n disabledReason: `React (${versions.get('react')}) and React DOM (${versions.get('react-dom')}) versions differ`,\n }\n }\n return versions\n}\n\nfunction createSharedEntries(\n dependencies: ResolvedDependency[],\n shareScope: string,\n): Record<string, SharedEntry> {\n const entries: Record<string, SharedEntry> = {}\n const providers = new Set(\n sharedDependencies.filter(({share}) => share !== false).map(({name}) => name),\n )\n for (const {name, specifier, version} of dependencies) {\n if (!specifier || !providers.has(name)) continue\n entries[specifier] = {\n eager: false,\n requiredVersion: version,\n // @module-federation/vite defaults providers to \"default\" unless each entry repeats this scope.\n shareScope,\n singleton: false,\n strictVersion: true,\n version,\n }\n }\n // Vite resolves imports concurrently, so sort providers to keep generated chunks reproducible.\n return Object.fromEntries(\n Object.entries(entries).toSorted(([left], [right]) => left.localeCompare(right)),\n )\n}\n"],"names":["valid","validSemver","sharedDependencies","name","share","optional","scope","viteInternalAliases","Set","source","findSharedDependencyName","specifier","find","startsWith","createFederationSharing","dependencies","versions","resolveCompatibleVersions","Map","shareScope","filter","map","get","join","shared","createSharedEntries","shareStrategy","aliasMayRewriteSharedImport","Boolean","some","ignoreCase","multiline","has","namespace","match","copies","dependency","length","set","disabledReason","root","version","copy","includes","JSON","stringify","entries","providers","eager","requiredVersion","singleton","strictVersion","Object","fromEntries","toSorted","left","right","localeCompare"],"mappings":"AACA,SAAQA,SAASC,WAAW,QAAO,SAAQ;AAc3C,2FAA2F;AAC3F,MAAMC,qBAAkD;IACtD;QAACC,MAAM;IAAO;IACd;QAACA,MAAM;IAAW;IAClB,iFAAiF;IACjF;QAACA,MAAM;QAAaC,OAAO;IAAK;IAChC;QAACD,MAAM;QAAqBE,UAAU;QAAMC,OAAO;IAAK;CACzD;AAED,gGAAgG;AAChG,MAAMC,sBAAsB,IAAIC,IAAI;IAAC,oBAAoBC,MAAM;IAAE,iBAAiBA,MAAM;CAAC;AAoBzF,OAAO,SAASC,yBAAyBC,SAAiB;IACxD,OAAOT,mBAAmBU,IAAI,CAAC,CAAC,EAACT,IAAI,EAAC,GAAKQ,cAAcR,QAAQQ,UAAUE,UAAU,CAAC,GAAGV,KAAK,CAAC,CAAC,IAC5FA;AACN;AAEA,OAAO,SAASW,wBACdC,YAAkC;IAElC,MAAMC,WAAWC,0BAA0BF;IAC3C,IAAI,CAAEC,CAAAA,oBAAoBE,GAAE,G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OAAOiB,GAAG,CAAC,CAAC,EAAClB,IAAI,EAAC,GAAKA;IAE1E,KAAK,MAAM,EAACA,IAAI,EAAEQ,SAAS,EAAE8B,OAAO,EAAC,IAAI1B,aAAc;QACrD,IAAI,CAACJ,aAAa,CAACoC,UAAUf,GAAG,CAAC7B,OAAO;QACxC2C,OAAO,CAACnC,UAAU,GAAG;YACnBqC,OAAO;YACPC,iBAAiBR;YACjB,gGAAgG;YAChGtB;YACA+B,WAAW;YACXC,eAAe;YACfV;QACF;IACF;IACA,+FAA+F;IAC/F,OAAOW,OAAOC,WAAW,CACvBD,OAAON,OAAO,CAACA,SAASQ,QAAQ,CAAC,CAAC,CAACC,KAAK,EAAE,CAACC,MAAM,GAAKD,KAAKE,aAAa,CAACD;AAE7E"}
@@ -297,6 +297,7 @@ const workbenchLockSchema = z.object({
297
297
  host: z.string(),
298
298
  pid: z.number(),
299
299
  port: z.number(),
300
+ ready: z.optional(z.boolean()),
300
301
  startedAt: z.string(),
301
302
  version: z.literal(REGISTRY_VERSION)
302
303
  });
@@ -304,34 +305,66 @@ const workbenchLockSchema = z.object({
304
305
  * Read the workbench lock file and return its contents if the holding
305
306
  * process is still alive. Prunes stale locks from crashed processes.
306
307
  */ export function readWorkbenchLock() {
307
- const lockPath = join(getRegistryDir(), 'workbench.lock');
308
- let contents;
309
- try {
310
- contents = readFileSync(lockPath, 'utf8');
311
- } catch {
312
- // File doesn't exist — nothing to prune, nothing to return
313
- return undefined;
314
- }
308
+ const file = readLockFile();
309
+ // File doesn't exist — nothing to prune, nothing to return
310
+ if (!file) return undefined;
315
311
  // Past this point the file exists. Anything that isn't a live, valid lock
316
312
  // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be
317
313
  // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by
318
314
  // EEXIST forever and `sanity dev` silently no-ops the workbench server.
319
- const data = parseLockContents(contents);
315
+ const { data } = file;
320
316
  devDebug('Read workbench lock: %o', data);
321
317
  if (data && isOurProcess(data.pid, data.startedAt)) {
322
318
  devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port);
323
319
  return data;
324
320
  }
325
- pruneWorkbenchLock(lockPath);
321
+ pruneWorkbenchLock(getLockPath());
326
322
  return undefined;
327
323
  }
328
- function parseLockContents(contents) {
324
+ const LOCK_READY_TIMEOUT_MS = 10_000;
325
+ const LOCK_READY_POLL_MS = 50;
326
+ /**
327
+ * Read the workbench lock once its holder's shell is listening, so the port is
328
+ * the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.
329
+ */ export async function waitForWorkbenchLock() {
330
+ const deadline = Date.now() + LOCK_READY_TIMEOUT_MS;
331
+ let lock = readWorkbenchLock();
332
+ // Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call
333
+ // and deletes a lock it catches half-written by `updatePort`.
334
+ while(lock?.ready === false && Date.now() < deadline){
335
+ await new Promise((resolve)=>setTimeout(resolve, LOCK_READY_POLL_MS));
336
+ const file = readLockFile();
337
+ if (!file) break;
338
+ lock = file.data ?? lock;
339
+ }
340
+ if (lock?.ready === false && Date.now() >= deadline) {
341
+ devDebug('Workbench lock not ready after %d ms, using port %d', LOCK_READY_TIMEOUT_MS, lock.port);
342
+ }
343
+ return readWorkbenchLock();
344
+ }
345
+ const getLockPath = ()=>join(getRegistryDir(), 'workbench.lock');
346
+ /**
347
+ * Read the lock file with no liveness check and no pruning. `undefined` when
348
+ * there is no file; `data` is `undefined` when its contents don't parse.
349
+ */ function readLockFile() {
350
+ let contents;
329
351
  try {
330
- const { data, success } = workbenchLockSchema.safeParse(JSON.parse(contents));
331
- return success ? data : undefined;
352
+ contents = readFileSync(getLockPath(), 'utf8');
332
353
  } catch {
333
354
  return undefined;
334
355
  }
356
+ let json;
357
+ try {
358
+ json = JSON.parse(contents);
359
+ } catch {
360
+ return {
361
+ data: undefined
362
+ };
363
+ }
364
+ const { data, success } = workbenchLockSchema.safeParse(json);
365
+ return {
366
+ data: success ? data : undefined
367
+ };
335
368
  }
336
369
  function pruneWorkbenchLock(lockPath) {
337
370
  try {
@@ -358,12 +391,13 @@ function pruneWorkbenchLock(lockPath) {
358
391
  mkdirSync(registryDir, {
359
392
  recursive: true
360
393
  });
361
- const lockPath = join(registryDir, 'workbench.lock');
394
+ const lockPath = getLockPath();
362
395
  const startedAt = ownStartedAt();
363
396
  const lockData = {
364
397
  host: info.host,
365
398
  pid: process.pid,
366
399
  port: info.port,
400
+ ready: false,
367
401
  startedAt,
368
402
  version: REGISTRY_VERSION
369
403
  };
@@ -378,12 +412,8 @@ function pruneWorkbenchLock(lockPath) {
378
412
  // it after our own release must not be clobbered.
379
413
  const detachExitCleanup = unlinkOnProcessExit(lockPath, ()=>{
380
414
  if (released) return false;
381
- try {
382
- const disk = parseLockContents(readFileSync(lockPath, 'utf8'));
383
- return disk?.pid === process.pid && disk.startedAt === startedAt;
384
- } catch {
385
- return false;
386
- }
415
+ const disk = readLockFile()?.data;
416
+ return disk?.pid === process.pid && disk.startedAt === startedAt;
387
417
  });
388
418
  return {
389
419
  release () {
@@ -398,7 +428,8 @@ function pruneWorkbenchLock(lockPath) {
398
428
  updatePort (port) {
399
429
  writeFileSync(lockPath, JSON.stringify({
400
430
  ...lockData,
401
- port
431
+ port,
432
+ ready: true
402
433
  }));
403
434
  }
404
435
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/registry.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n watch,\n writeFileSync,\n} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {\n coreAppManifestSchema,\n getSanityDataDir,\n studioManifestSchema,\n subdebug,\n} from '@sanity/cli-core'\nimport {z} from 'zod/mini'\n\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\n/**\n * The dev-server registry: how a running `sanity dev` / `sanity start` process\n * advertises itself so the workbench on this machine can find and load it.\n *\n * Two kinds of file under `~/.sanity/dev-servers/` do the coordinating:\n *\n * - `<pid>.json` — one per running app/studio server, holding where it's served\n * plus its inlined manifest and interfaces. The workbench reads these to\n * discover and render local apps. Written by `registerDevServer`, watched by\n * `watchRegistry`.\n * - `workbench.lock` — a single machine-wide lock, so only one workbench shell\n * runs at a time and later `dev`s register into it instead of starting their\n * own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.\n *\n * Both files belong to the process that created them and must not outlive it.\n * Three things keep that true: an explicit `release()` on clean shutdown, an\n * `exit` backstop for abrupt exits (`unlinkOnProcessExit`), and a dead-pid prune\n * on read (`isOurProcess`) that clears whatever a crashed process left behind.\n */\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 2\n\n/**\n * The current process's start time as reported by the OS, for the `startedAt`\n * that `isOurProcess` checks on re-read. Falls back to now when the OS time is\n * unavailable — `new Date()` alone records the write time, which drifts from\n * process start by enough to look stale and get pruned right after writing.\n */\nfunction ownStartedAt(): string {\n return (getProcessStartTime(process.pid) ?? new Date()).toISOString()\n}\n\nconst interfaceBaseFields = {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n /** Raw source vite serves; a deployed interface carries only the `moduleId`. */\n src: z.string(),\n title: z.string(),\n version: z.optional(z.string()),\n}\n\n/**\n * A forwarded interface. Kept outside the manifest so\n * the workbench renders local panels and runs workers without a deploy.\n */\nconst devServerInterfaceSchema = z.union([\n z.discriminatedUnion('surface', [\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('window'),\n }),\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('panel'),\n }),\n z.object({...interfaceBaseFields, metadata: z.null(), surface: z.literal('asset_source')}),\n z.object({\n ...interfaceBaseFields,\n metadata: TileInterfaceMetadataSchema,\n surface: z.literal('tile'),\n }),\n ]),\n z.object({...interfaceBaseFields, metadata: z.null(), type: z.literal('worker')}),\n])\n\n// Exported so test fixtures can validate against the same schema the registry\n// parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.\nexport const devServerManifestSchema = z.object({\n /**\n * Field schema *values* load from the federation module; each field's `src`\n * rides along so a repoint bumps the exposes-set id and forces a rebuild.\n * Lenient — the workbench is the authority.\n */\n configs: z.optional(\n z.array(\n z.object({\n // Identifies the owning app when it has no app id (singletons).\n appType: z.optional(z.string()),\n fields: z.array(\n z.object({\n name: z.string(),\n public: z.optional(z.boolean()),\n src: z.string(),\n title: z.string(),\n }),\n ),\n // Content hash of the config — the workbench's change-detection key\n // (see deriveConfigs).\n id: z.string(),\n // The app's `defineApplication` slug — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // The version the workbench federates this config's module under —\n // a string, like the one Brett returns on a deployed `activeConfig`.\n version: z.string(),\n }),\n ),\n ),\n host: z.string(),\n id: z.optional(z.string()),\n interfaces: z.optional(z.array(devServerInterfaceSchema)),\n /**\n * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},\n * validated against the shared cli-core schemas. The registry stores and\n * rebroadcasts it; the CLI is what extracts and writes it.\n */\n manifest: z.optional(z.union([studioManifestSchema, coreAppManifestSchema])),\n /**\n * ISO timestamp of the most recent successful manifest extraction. Bumped\n * on every regeneration so re-writing this registry entry triggers the\n * workbench `watchRegistry` watcher and forces a rebroadcast to clients.\n */\n manifestUpdatedAt: z.optional(z.string()),\n // Stable identity + qualified reference, composed by the CLI (the authority for\n // local apps, which never reach brett) and read straight by the workbench.\n name: z.optional(z.string()),\n organizationId: z.optional(z.string()),\n pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n reference: z.optional(z.string()),\n slug: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\n visibility: z.optional(z.enum(['default', 'unlisted', 'disabled'])),\n workDir: z.string(),\n})\n/**\n * A manifest describing a running dev server process (studio or app).\n * Stored as `~/.sanity/dev-servers/<pid>.json`.\n *\n * The workbench singleton is tracked separately via the lock file — see\n * `acquireWorkbenchLock` and `readWorkbenchLock` below.\n */\nexport type DevServerManifest = z.infer<typeof devServerManifestSchema>\n\n/**\n * A config-only server carries configs but no interfaces — e.g. a\n * media-library config app under development. The workbench never routes it\n * as an app; only its configs are published. It therefore plays a different\n * role than an app server, and the two may share a slug (a config app\n * developed alongside the locally served singleton it configures).\n */\nexport function isConfigOnlyServer(\n server: Pick<DevServerManifest, 'configs' | 'interfaces'>,\n): boolean {\n return Boolean(server.configs?.length) && !server.interfaces?.length\n}\n\n/**\n * Path to the dev server registry directory. Lives under the shared Sanity\n * config directory to stay consistent with other CLI paths.\n */\nfunction getRegistryDir(): string {\n return join(getSanityDataDir(), 'dev-servers')\n}\n\n// One shared `exit` listener drives every registered cleanup, so N locks/entries\n// don't each add a listener and trip Node's MaxListeners warning.\nconst exitCleanups = new Set<() => void>()\nlet exitListenerInstalled = false\n\nfunction runExitCleanups(): void {\n for (const cleanup of exitCleanups) cleanup()\n}\n\n/** Exercise the exit backstop in tests without terminating the process; not part\n * of the package's public surface. */\nexport const runRegistryExitCleanupForTesting = runExitCleanups\n\n/**\n * Delete a registry file synchronously on process exit, as a backstop for abrupt\n * termination. Vite installs its own SIGTERM handler that calls `process.exit()`,\n * which can outrun the async server teardown and leave the lock or registry entry\n * behind — a stray dev-server that lingers until the dead-pid prune clears it. The\n * `exit` event only runs synchronous work, hence `unlinkSync`. `ownedByUs` guards\n * the shared lock so a successor that reacquired it isn't wiped. Returns a\n * detacher to call after a clean release.\n */\nfunction unlinkOnProcessExit(filePath: string, ownedByUs: () => boolean): () => void {\n const cleanup = () => {\n if (!ownedByUs()) return\n try {\n unlinkSync(filePath)\n } catch {\n // The file may already have been removed during shutdown.\n }\n }\n exitCleanups.add(cleanup)\n\n if (!exitListenerInstalled) {\n exitListenerInstalled = true\n process.once('exit', runExitCleanups)\n }\n\n return () => exitCleanups.delete(cleanup)\n}\n\ninterface DevServerRegistration {\n /** Remove the registry entry. */\n release: () => void\n /**\n * Rewrite the registry entry with partial updates merged in. Also bumps the\n * file's mtime, which fires `watchRegistry` in any workbench process and\n * triggers a rebroadcast to connected clients.\n */\n update: (patch: Partial<Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>>) => void\n}\n\n/**\n * Write a manifest file for the current process and return a handle with a\n * `release` function that removes it plus an `update` function for patching\n * fields post-registration. Uses synchronous I/O so the file exists before\n * any signal handler could fire.\n */\nexport function registerDevServer(\n manifest: Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>,\n): DevServerRegistration {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per machine\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(): z.infer<typeof workbenchLockSchema> | undefined {\n const lockPath = join(getRegistryDir(), 'workbench.lock')\n\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8')\n } catch {\n // File doesn't exist — nothing to prune, nothing to return\n return undefined\n }\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const data = parseLockContents(contents)\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(lockPath)\n return undefined\n}\n\nfunction parseLockContents(contents: string): z.infer<typeof workbenchLockSchema> | undefined {\n try {\n const {data, success} = workbenchLockSchema.safeParse(JSON.parse(contents))\n return success ? data : undefined\n } catch {\n return undefined\n }\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = join(registryDir, 'workbench.lock')\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx'})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n try {\n const disk = parseLockContents(readFileSync(lockPath, 'utf8'))\n return disk?.pid === process.pid && disk.startedAt === startedAt\n } catch {\n return false\n }\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port}))\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock()\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","configs","array","appType","fields","public","boolean","moduleName","host","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","readWorkbenchLock","lockPath","contents","undefined","parseLockContents","pruneWorkbenchLock","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,KAAK,EACLC,aAAa,QACR,UAAS;AAChB,SAAQC,IAAI,QAAO,YAAW;AAE9B,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,oBAAoB,EACpBC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,2BAA2B,EAAEC,2BAA2B,QAAO,oBAAmB;AAC1F,SAAQC,oBAAoB,QAAO,4BAA2B;AAC9D,SAAQC,mBAAmB,EAAEC,YAAY,QAAO,uBAAsB;AAEtE;;;;;;;;;;;;;;;;;;CAkBC,GAED,MAAMC,WAAWP,SAAS;AAE1B,iEAAiE,GACjE,MAAMQ,mBAAmB;AAEzB;;;;;CAKC,GACD,SAASC;IACP,OAAO,AAACJ,CAAAA,oBAAoBK,QAAQC,GAAG,KAAK,IAAIC,MAAK,EAAGC,WAAW;AACrE;AAEA,MAAMC,sBAAsB;IAC1B,6EAA6E,GAC7EC,IAAId,EAAEe,MAAM;IACZC,UAAUhB,EAAEe,MAAM;IAClBE,MAAMjB,EAAEe,MAAM;IACd,8EAA8E,GAC9EG,KAAKlB,EAAEe,MAAM;IACbI,OAAOnB,EAAEe,MAAM;IACfK,SAASpB,EAAEqB,QAAQ,CAACrB,EAAEe,MAAM;AAC9B;AAEA;;;CAGC,GACD,MAAMO,2BAA2BtB,EAAEuB,KAAK,CAAC;IACvCvB,EAAEwB,kBAAkB,CAAC,WAAW;QAC9BxB,E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AAcgH,UAAU/B,KAAKC,SAAS,CAACsC,WAAW;YAACC,MAAM;QAAI;QAC7D7G,SAAS;QAET,IAAIuE,WAAW;QACf,8EAA8E;QAC9E,kDAAkD;QAClD,MAAMC,oBAAoBb,oBAAoByC,UAAU;YACtD,IAAI7B,UAAU,OAAO;YACrB,IAAI;gBACF,MAAMuC,OAAOP,kBAAkBtH,aAAamH,UAAU;gBACtD,OAAOU,MAAM1G,QAAQD,QAAQC,GAAG,IAAI0G,KAAKlE,SAAS,KAAKA;YACzD,EAAE,OAAM;gBACN,OAAO;YACT;QACF;QAEA,OAAO;YACL6B;gBACEF,WAAW;gBACXC;gBACA,IAAI;oBACFtF,WAAWkH;gBACb,EAAE,OAAM;gBACN,qBAAqB;gBACvB;YACF;YACAW,YAAWvE,IAAY;gBACrBpD,cAAcgH,UAAU/B,KAAKC,SAAS,CAAC;oBAAC,GAAGsC,QAAQ;oBAAEpE;gBAAI;YAC3D;QACF;IACF,EAAE,OAAOwE,KAAc;QACrBhH,SACE,wCACAgH,eAAeC,QAAQD,IAAIE,OAAO,GAAGC,OAAOH;QAE9C,IAAI,CAACI,YAAYJ,QAAQA,IAAIK,IAAI,KAAK,UAAU,OAAOf;QAEvD,mDAAmD;QACnD,MAAMgB,WAAWnB;QACjB,IAAImB,UAAU,OAAOhB;QAErB,6FAA6F;QAC7F,IAAIK,WAAW,GAAG,OAAOL;QACzB,OAAOG,qBAAqBC,MAAMC,UAAU;IAC9C;AACF;AAEA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
1
+ {"version":3,"sources":["../../../src/actions/dev/registry.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n watch,\n writeFileSync,\n} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {\n coreAppManifestSchema,\n getSanityDataDir,\n studioManifestSchema,\n subdebug,\n} from '@sanity/cli-core'\nimport {z} from 'zod/mini'\n\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\n/**\n * The dev-server registry: how a running `sanity dev` / `sanity start` process\n * advertises itself so the workbench on this machine can find and load it.\n *\n * Two kinds of file under `~/.sanity/dev-servers/` do the coordinating:\n *\n * - `<pid>.json` — one per running app/studio server, holding where it's served\n * plus its inlined manifest and interfaces. The workbench reads these to\n * discover and render local apps. Written by `registerDevServer`, watched by\n * `watchRegistry`.\n * - `workbench.lock` — a single machine-wide lock, so only one workbench shell\n * runs at a time and later `dev`s register into it instead of starting their\n * own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.\n *\n * Both files belong to the process that created them and must not outlive it.\n * Three things keep that true: an explicit `release()` on clean shutdown, an\n * `exit` backstop for abrupt exits (`unlinkOnProcessExit`), and a dead-pid prune\n * on read (`isOurProcess`) that clears whatever a crashed process left behind.\n */\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 2\n\n/**\n * The current process's start time as reported by the OS, for the `startedAt`\n * that `isOurProcess` checks on re-read. Falls back to now when the OS time is\n * unavailable — `new Date()` alone records the write time, which drifts from\n * process start by enough to look stale and get pruned right after writing.\n */\nfunction ownStartedAt(): string {\n return (getProcessStartTime(process.pid) ?? new Date()).toISOString()\n}\n\nconst interfaceBaseFields = {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n /** Raw source vite serves; a deployed interface carries only the `moduleId`. */\n src: z.string(),\n title: z.string(),\n version: z.optional(z.string()),\n}\n\n/**\n * A forwarded interface. Kept outside the manifest so\n * the workbench renders local panels and runs workers without a deploy.\n */\nconst devServerInterfaceSchema = z.union([\n z.discriminatedUnion('surface', [\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('window'),\n }),\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('panel'),\n }),\n z.object({...interfaceBaseFields, metadata: z.null(), surface: z.literal('asset_source')}),\n z.object({\n ...interfaceBaseFields,\n metadata: TileInterfaceMetadataSchema,\n surface: z.literal('tile'),\n }),\n ]),\n z.object({...interfaceBaseFields, metadata: z.null(), type: z.literal('worker')}),\n])\n\n// Exported so test fixtures can validate against the same schema the registry\n// parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.\nexport const devServerManifestSchema = z.object({\n /**\n * Field schema *values* load from the federation module; each field's `src`\n * rides along so a repoint bumps the exposes-set id and forces a rebuild.\n * Lenient — the workbench is the authority.\n */\n configs: z.optional(\n z.array(\n z.object({\n // Identifies the owning app when it has no app id (singletons).\n appType: z.optional(z.string()),\n fields: z.array(\n z.object({\n name: z.string(),\n public: z.optional(z.boolean()),\n src: z.string(),\n title: z.string(),\n }),\n ),\n // Content hash of the config — the workbench's change-detection key\n // (see deriveConfigs).\n id: z.string(),\n // The app's `defineApplication` slug — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // The version the workbench federates this config's module under —\n // a string, like the one Brett returns on a deployed `activeConfig`.\n version: z.string(),\n }),\n ),\n ),\n host: z.string(),\n id: z.optional(z.string()),\n interfaces: z.optional(z.array(devServerInterfaceSchema)),\n /**\n * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},\n * validated against the shared cli-core schemas. The registry stores and\n * rebroadcasts it; the CLI is what extracts and writes it.\n */\n manifest: z.optional(z.union([studioManifestSchema, coreAppManifestSchema])),\n /**\n * ISO timestamp of the most recent successful manifest extraction. Bumped\n * on every regeneration so re-writing this registry entry triggers the\n * workbench `watchRegistry` watcher and forces a rebroadcast to clients.\n */\n manifestUpdatedAt: z.optional(z.string()),\n // Stable identity + qualified reference, composed by the CLI (the authority for\n // local apps, which never reach brett) and read straight by the workbench.\n name: z.optional(z.string()),\n organizationId: z.optional(z.string()),\n pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n reference: z.optional(z.string()),\n slug: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\n visibility: z.optional(z.enum(['default', 'unlisted', 'disabled'])),\n workDir: z.string(),\n})\n/**\n * A manifest describing a running dev server process (studio or app).\n * Stored as `~/.sanity/dev-servers/<pid>.json`.\n *\n * The workbench singleton is tracked separately via the lock file — see\n * `acquireWorkbenchLock` and `readWorkbenchLock` below.\n */\nexport type DevServerManifest = z.infer<typeof devServerManifestSchema>\n\n/**\n * A config-only server carries configs but no interfaces — e.g. a\n * media-library config app under development. The workbench never routes it\n * as an app; only its configs are published. It therefore plays a different\n * role than an app server, and the two may share a slug (a config app\n * developed alongside the locally served singleton it configures).\n */\nexport function isConfigOnlyServer(\n server: Pick<DevServerManifest, 'configs' | 'interfaces'>,\n): boolean {\n return Boolean(server.configs?.length) && !server.interfaces?.length\n}\n\n/**\n * Path to the dev server registry directory. Lives under the shared Sanity\n * config directory to stay consistent with other CLI paths.\n */\nfunction getRegistryDir(): string {\n return join(getSanityDataDir(), 'dev-servers')\n}\n\n// One shared `exit` listener drives every registered cleanup, so N locks/entries\n// don't each add a listener and trip Node's MaxListeners warning.\nconst exitCleanups = new Set<() => void>()\nlet exitListenerInstalled = false\n\nfunction runExitCleanups(): void {\n for (const cleanup of exitCleanups) cleanup()\n}\n\n/** Exercise the exit backstop in tests without terminating the process; not part\n * of the package's public surface. */\nexport const runRegistryExitCleanupForTesting = runExitCleanups\n\n/**\n * Delete a registry file synchronously on process exit, as a backstop for abrupt\n * termination. Vite installs its own SIGTERM handler that calls `process.exit()`,\n * which can outrun the async server teardown and leave the lock or registry entry\n * behind — a stray dev-server that lingers until the dead-pid prune clears it. The\n * `exit` event only runs synchronous work, hence `unlinkSync`. `ownedByUs` guards\n * the shared lock so a successor that reacquired it isn't wiped. Returns a\n * detacher to call after a clean release.\n */\nfunction unlinkOnProcessExit(filePath: string, ownedByUs: () => boolean): () => void {\n const cleanup = () => {\n if (!ownedByUs()) return\n try {\n unlinkSync(filePath)\n } catch {\n // The file may already have been removed during shutdown.\n }\n }\n exitCleanups.add(cleanup)\n\n if (!exitListenerInstalled) {\n exitListenerInstalled = true\n process.once('exit', runExitCleanups)\n }\n\n return () => exitCleanups.delete(cleanup)\n}\n\ninterface DevServerRegistration {\n /** Remove the registry entry. */\n release: () => void\n /**\n * Rewrite the registry entry with partial updates merged in. Also bumps the\n * file's mtime, which fires `watchRegistry` in any workbench process and\n * triggers a rebroadcast to connected clients.\n */\n update: (patch: Partial<Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>>) => void\n}\n\n/**\n * Write a manifest file for the current process and return a handle with a\n * `release` function that removes it plus an `update` function for patching\n * fields post-registration. Uses synchronous I/O so the file exists before\n * any signal handler could fire.\n */\nexport function registerDevServer(\n manifest: Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>,\n): DevServerRegistration {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per machine\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n ready: z.optional(z.boolean()),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile()\n // File doesn't exist — nothing to prune, nothing to return\n if (!file) return undefined\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const {data} = file\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(getLockPath())\n return undefined\n}\n\nconst LOCK_READY_TIMEOUT_MS = 10_000\nconst LOCK_READY_POLL_MS = 50\n\n/**\n * Read the workbench lock once its holder's shell is listening, so the port is\n * the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.\n */\nexport async function waitForWorkbenchLock(): Promise<\n z.infer<typeof workbenchLockSchema> | undefined\n> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock()\n // Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call\n // and deletes a lock it catches half-written by `updatePort`.\n while (lock?.ready === false && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, LOCK_READY_POLL_MS))\n const file = readLockFile()\n if (!file) break\n lock = file.data ?? lock\n }\n if (lock?.ready === false && Date.now() >= deadline) {\n devDebug(\n 'Workbench lock not ready after %d ms, using port %d',\n LOCK_READY_TIMEOUT_MS,\n lock.port,\n )\n }\n return readWorkbenchLock()\n}\n\nconst getLockPath = () => join(getRegistryDir(), 'workbench.lock')\n\n/**\n * Read the lock file with no liveness check and no pruning. `undefined` when\n * there is no file; `data` is `undefined` when its contents don't parse.\n */\nfunction readLockFile(): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(), 'utf8')\n } catch {\n return undefined\n }\n let json: unknown\n try {\n json = JSON.parse(contents)\n } catch {\n return {data: undefined}\n }\n const {data, success} = workbenchLockSchema.safeParse(json)\n return {data: success ? data : undefined}\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = getLockPath()\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n ready: false,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx'})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n const disk = readLockFile()?.data\n return disk?.pid === process.pid && disk.startedAt === startedAt\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port, ready: true}))\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock()\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","configs","array","appType","fields","public","boolean","moduleName","host","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","ready","readWorkbenchLock","readLockFile","undefined","pruneWorkbenchLock","getLockPath","LOCK_READY_TIMEOUT_MS","LOCK_READY_POLL_MS","waitForWorkbenchLock","deadline","now","lock","Promise","resolve","contents","json","lockPath","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"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AAG,OAAOhB;QACzB,OAAOc,qBAAqBC,MAAMC,UAAU;IAC9C;AACF;AAEA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
@@ -15,8 +15,7 @@ import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './star
15
15
  */ export async function startWorkbenchDev(options) {
16
16
  const { cacheDir, checkForDeprecatedAppId, cliConfig, extractManifest, httpHost, httpPort, isApp, output, reactStrictMode, startAppServer, workDir } = options;
17
17
  // The remote can't render itself, so it runs as a plain app server (not the
18
- // shell) that still claims the lock and bridges the registry, so app
19
- // `sanity dev`s register into it.
18
+ // shell) that still bridges the registry.
20
19
  if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {
21
20
  const remote = await startAppServer({
22
21
  announceUrl: true,
@@ -26,11 +25,7 @@ import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './star
26
25
  if (!remote.started) return {
27
26
  close: async ()=>{}
28
27
  };
29
- const addr = remote.server.httpServer?.address();
30
- const port = (typeof addr === 'object' && addr ? addr.port : remote.server.config.server.port) ?? httpPort;
31
28
  const coordinator = startWorkbenchRemoteCoordinator({
32
- httpHost,
33
- port,
34
29
  server: remote.server
35
30
  });
36
31
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n announceUrl: boolean\n cliConfig: CliConfig\n httpPort: number\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/service edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still claims the lock and bridges the registry, so app\n // `sanity dev`s register into it.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({announceUrl: true, cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const addr = remote.server.httpServer?.address()\n const port =\n (typeof addr === 'object' && addr ? addr.port : remote.server.config.server.port) ?? httpPort\n const coordinator = startWorkbenchRemoteCoordinator({httpHost, port, server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n const announceUrl = !workbench.workbenchAvailable\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config) => startAppServer({announceUrl, cliConfig: config, httpPort: appPort}),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\n await close()\n throw err\n }\n\n if (workbench.workbenchAvailable) {\n const workbenchUrl = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}`\n const addr = supervisor.server.httpServer?.address()\n const port = typeof addr === 'object' && addr ? addr.port : supervisor.server.config.server.port\n output.log(\n `Workbench dev server started at ${styleText(['blue', 'underline'], workbenchUrl)} (app on port ${port})`,\n )\n }\n\n installSignalHandlers()\n\n return {close}\n}\n"],"names":["styleText","createServerLifecycle","toDisplayHost","startAppServerSupervisor","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","announceUrl","started","close","addr","server","httpServer","address","port","config","coordinator","closers","installSignalHandlers","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","catch","err","supervisor","registration","onInterfaceSetChange","rebuild","workbenchUrl","log"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAInC,SAAQC,qBAAqB,EAAEC,aAAa,QAAO,oCAAmC;AACtF,SAA8BC,wBAAwB,QAAO,2BAA0B;AAEvF,SAAQC,0BAA0B,QAAO,kCAAiC;AAC1E,SACEC,uBAAuB,EACvBC,+BAA+B,QAC1B,+BAA8B;AA4BrC;;;;;;;;;CASC,GACD,OAAO,eAAeC,kBACpBC,OAAiC;IAEjC,MAAM,EACJC,QAAQ,EACRC,uBAAuB,EACvBC,SAAS,EACTC,eAAe,EACfC,QAAQ,EACRC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,eAAe,EACfC,cAAc,EACdC,OAAO,EACR,GAAGX;IAEJ,4EAA4E;IAC5E,qEAAqE;IACrE,kCAAkC;IAClC,IAAIY,QAAQC,GAAG,CAACC,mCAAmC,KAAK,QAAQ;QAC9D,MAAMC,SAAS,MAAML,eAAe;YAACM,aAAa;YAAMb;YAAWG;QAAQ;QAC3E,IAAI,CAACS,OAAOE,OAAO,EAAE,OAAO;YAACC,OAAO,WAAa;QAAC;QAElD,MAAMC,OAAOJ,OAAOK,MAAM,CAACC,UAAU,EAAEC;QACvC,MAAMC,OACJ,AAAC,CAAA,OAAOJ,SAAS,YAAYA,OAAOA,KAAKI,IAAI,GAAGR,OAAOK,MAAM,CAACI,MAAM,CAACJ,MAAM,CAACG,IAAI,AAAD,KAAMjB;QACvF,MAAMmB,cAAc3B,gCAAgC;YAACO;YAAUkB;YAAMH,QAAQL,OAAOK,MAAM;QAAA;QAE1F,OAAO;YACLF,OAAO;gBACL,MAAMO,YAAYP,KAAK;gBACvB,MAAMH,OAAOG,KAAK;YACpB;QACF;IACF;IAEA,4EAA4E;IAC5E,qEAAqE;IACrE,MAAM,EAACA,KAAK,EAAEQ,OAAO,EAAEC,qBAAqB,EAAC,GAAGlC;I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MAAM,CAACJ,MAAM,CAACG,IAAI;QAChGf,OAAOkC,GAAG,CACR,CAAC,gCAAgC,EAAElD,UAAU;YAAC;YAAQ;SAAY,EAAEiD,cAAc,cAAc,EAAElB,KAAK,CAAC,CAAC;IAE7G;IAEAI;IAEA,OAAO;QAACT;IAAK;AACf"}
1
+ {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n announceUrl: boolean\n cliConfig: CliConfig\n httpPort: number\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/service edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still bridges the registry.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({announceUrl: true, cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const coordinator = startWorkbenchRemoteCoordinator({server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n const announceUrl = !workbench.workbenchAvailable\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config) => startAppServer({announceUrl, cliConfig: config, httpPort: appPort}),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\n await close()\n throw err\n }\n\n if (workbench.workbenchAvailable) {\n const workbenchUrl = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}`\n const addr = supervisor.server.httpServer?.address()\n const port = typeof addr === 'object' && addr ? addr.port : supervisor.server.config.server.port\n output.log(\n `Workbench dev server started at ${styleText(['blue', 'underline'], workbenchUrl)} (app on port ${port})`,\n )\n }\n\n installSignalHandlers()\n\n return {close}\n}\n"],"names":["styleText","createServerLifecycle","toDisplayHost","startAppServerSupervisor","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","announceUrl","started","close","coordinator","server","closers","installSignalHandlers","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","config","catch","err","supervisor","registration","onInterfaceSetChange","rebuild","workbenchUrl","addr","httpServer","address","port","log"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAInC,SAAQC,qBAAqB,EAAEC,aAAa,QAAO,oCAAmC;AACtF,SAA8BC,wBAAwB,QAAO,2BAA0B;AAEvF,SAAQC,0BAA0B,QAAO,kCAAiC;AAC1E,SACEC,uBAAuB,EACvBC,+BAA+B,QAC1B,+BAA8B;AA4BrC;;;;;;;;;CASC,GACD,OAAO,eAAeC,kBACpBC,OAAiC;IAEjC,MAAM,EACJC,QAAQ,EACRC,uBAAuB,EACvBC,SAAS,EACTC,eAAe,EACfC,QAAQ,EACRC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,eAAe,EACfC,cAAc,EACdC,OAAO,EACR,GAAGX;IAEJ,4EAA4E;IAC5E,0CAA0C;IAC1C,IAAIY,QAAQC,GAAG,CAACC,mCAAmC,KAAK,QAAQ;QAC9D,MAAMC,SAAS,MAAML,eAAe;YAACM,aAAa;YAAMb;YAAWG;QAAQ;QAC3E,IAAI,CAACS,OAAOE,OAAO,EAAE,OAAO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AAUG,kBAAkB,EAAE;QAChC,MAAMW,eAAe,CAAC,OAAO,EAAE3C,cAAc6B,UAAUlB,QAAQ,EAAE,CAAC,EAAEkB,UAAUI,aAAa,EAAE;QAC7F,MAAMW,OAAOL,WAAWb,MAAM,CAACmB,UAAU,EAAEC;QAC3C,MAAMC,OAAO,OAAOH,SAAS,YAAYA,OAAOA,KAAKG,IAAI,GAAGR,WAAWb,MAAM,CAACU,MAAM,CAACV,MAAM,CAACqB,IAAI;QAChGjC,OAAOkC,GAAG,CACR,CAAC,gCAAgC,EAAElD,UAAU;YAAC;YAAQ;SAAY,EAAE6C,cAAc,cAAc,EAAEI,KAAK,CAAC,CAAC;IAE7G;IAEAnB;IAEA,OAAO;QAACJ;IAAK;AACf"}
@@ -6,7 +6,7 @@ import { createServer } from 'vite';
6
6
  import { z } from 'zod/mini';
7
7
  import { isWorkbenchApp, isWorkbenchConfig } from '../../defineApp.js';
8
8
  import { createExposesTracker } from './exposesSetId.js';
9
- import { acquireWorkbenchLock, getRegisteredServers, isConfigOnlyServer, readWorkbenchLock, watchRegistry } from './registry.js';
9
+ import { acquireWorkbenchLock, getRegisteredServers, isConfigOnlyServer, waitForWorkbenchLock, watchRegistry } from './registry.js';
10
10
  import { toWireInterface } from './toWireInterface.js';
11
11
  import { writeWorkbenchRuntime } from './writeWorkbenchRuntime.js';
12
12
  const devDebug = subdebug('dev');
@@ -67,26 +67,13 @@ const toApplicationsPayload = (servers)=>({
67
67
  return ()=>registryWatcher.close();
68
68
  }
69
69
  /**
70
- * Make the workbench remote act as the machine's workbench: claim the singleton
71
- * lock so app `sanity dev`s register into it instead of each starting their own,
72
- * and bridge the registry so the remote shows the local apps. No-op lock if one
73
- * is already held.
70
+ * Bridge the registry into the workbench remote's HMR channel. The remote never
71
+ * claims the workbench lock: a held lock tells the next `sanity dev` a shell is
72
+ * running, and the remote only renders inside that shell.
74
73
  */ export function startWorkbenchRemoteCoordinator(options) {
75
- const { httpHost, port, server } = options;
76
- const lock = acquireWorkbenchLock({
77
- host: httpHost || 'localhost',
78
- port
79
- });
80
- if (!lock) {
81
- const existing = readWorkbenchLock();
82
- devDebug('Workbench lock already held by pid %d on port %d; bridging the registry without claiming it', existing?.pid, existing?.port);
83
- }
84
- const detachBridge = attachViteDevServerBridge(server);
74
+ const detachBridge = attachViteDevServerBridge(options.server);
85
75
  return {
86
- close: async ()=>{
87
- detachBridge();
88
- lock?.release();
89
- }
76
+ close: async ()=>detachBridge()
90
77
  };
91
78
  }
92
79
  export async function startWorkbenchDevServer(options) {
@@ -111,7 +98,7 @@ export async function startWorkbenchDevServer(options) {
111
98
  port: workbenchPort
112
99
  });
113
100
  if (!workbenchLock) {
114
- const existing = readWorkbenchLock();
101
+ const existing = await waitForWorkbenchLock();
115
102
  devDebug('Workbench already running at pid %d on port %d, skipping', existing?.pid, existing?.port);
116
103
  return {
117
104
  close: noop,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\n\nimport {type CliConfig, type Output, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n readWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {toWireInterface} from './toWireInterface.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\nconst renderDashboardEntry = '@sanity/workbench-cli/_internal_render'\nconst renderDashboardPath = fileURLToPath(\n new URL('../../_exports/_internal_render.js', import.meta.url),\n)\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => !isConfigOnlyServer(server))\n .map(\n ({\n host,\n id,\n interfaces,\n manifest,\n name,\n organizationId,\n port,\n projectId,\n reference,\n slug,\n type,\n visibility,\n }) => ({\n host,\n id,\n // Views cross to the remote keyed on `type`, never the internal `surface`.\n interfaces: interfaces?.map((iface) => toWireInterface(iface)),\n manifest,\n name,\n port,\n projectId,\n reference,\n type,\n ...(organizationId && slug && visibility ? {organizationId, slug, visibility} : {}),\n }),\n ),\n configs: servers.flatMap(({configs, host, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `http://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer): () => void {\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(getRegisteredServers()),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((servers) => {\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Make the workbench remote act as the machine's workbench: claim the singleton\n * lock so app `sanity dev`s register into it instead of each starting their own,\n * and bridge the registry so the remote shows the local apps. No-op lock if one\n * is already held.\n */\nexport function startWorkbenchRemoteCoordinator(options: {\n httpHost: string | undefined\n port: number\n server: ViteDevServer\n}): {close: () => Promise<void>} {\n const {httpHost, port, server} = options\n\n const lock = acquireWorkbenchLock({host: httpHost || 'localhost', port})\n if (!lock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench lock already held by pid %d on port %d; bridging the registry without claiming it',\n existing?.pid,\n existing?.port,\n )\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n close: async () => {\n detachBridge()\n lock?.release()\n },\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into by a `defineApplication` app or a config-only\n // `unstable_defineMediaLibrary` config — the latter still needs the shell to\n // render it.\n if (!isWorkbenchApp(cliConfig?.app) && !isWorkbenchConfig(cliConfig?.app)) {\n devDebug('Not a workbench app or config, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n // Acquire an exclusive lock — only one workbench per machine.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({host: httpHost || 'localhost', port: workbenchPort})\n if (!workbenchLock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n cliConfig,\n httpHost,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable: true,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, cliConfig, httpHost, output, reactStrictMode, workbenchPort, workDir} = options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Keep this entry out of pre-bundling so Vite injects its HMR context.\n exclude: [renderDashboardEntry],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {\n // The generated Vite root cannot reliably resolve this package.\n alias: {[renderDashboardEntry]: renderDashboardPath},\n dedupe: ['react', 'react-dom'],\n },\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Workbench dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `defineApplication`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'Workbench requires an organization ID. Pass \"organizationId\" to defineApplication() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["fileURLToPath","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","isWorkbenchConfig","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","readWorkbenchLock","watchRegistry","toWireInterface","writeWorkbenchRuntime","devDebug","renderDashboardEntry","renderDashboardPath","URL","url","noop","toApplicationsPayload","servers","applications","filter","server","map","host","id","interfaces","manifest","name","organizationId","port","projectId","reference","slug","type","visibility","iface","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ws","on","_","client","send","setTracker","registryWatcher","hasChanged","close","startWorkbenchRemoteCoordinator","options","httpHost","lock","existing","pid","detachBridge","release","startWorkbenchDevServer","cacheDir","cliConfig","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","workbenchLock","result","createWorkbenchViteServer","err","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","resolveOrganizationId","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","mode","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","undefined","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AAEtC,SAAqCC,QAAQ,QAAO,mBAAkB;AACtE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,eAAe,uBAAsB;AAC5C,SAAQC,YAAY,QAA2D,OAAM;AACrF,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,oBAAoB,QAAO,oBAAmB;AACtD,SACEC,oBAAoB,EAEpBC,oBAAoB,EACpBC,kBAAkB,EAClBC,iBAAiB,EACjBC,aAAa,QACR,gBAAe;AACtB,SAAQC,eAAe,QAAO,uBAAsB;AACpD,SAAQC,qBAAqB,QAAO,6BAA4B;AAEhE,MAAMC,WAAWf,SAAS;AAC1B,MAAMgB,uBAAuB;AAC7B,MAAMC,sBAAsBlB,cAC1B,IAAImB,IAAI,sCAAsC,YAAYC,GAAG;AAG/D,MAAMC,OAAO,WAAa;AAE1B,kEAAkE;AAClE,qFAAqF;AACrF,MAAMC,wBAAwB,CAACC,UAAkC,CAAA;QAC/DC,cAAcD,QACXE,MAAM,CAAC,CAACC,SAAW,CAACf,mBAAmBe,SACvCC,GAAG,CACF,CAAC,EACCC,IAAI,EACJC,EAAE,EACFC,UAAU,EACVC,QAAQ,EACRC,IAAI,EACJC,cAAc,EACdC,IAAI,EACJC,SAAS,EACTC,SAAS,EACTC,IAAI,EACJC,IAAI,EACJC,UAAU,EACX,GAA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ACD,SAAS5B,kCAAkCnB,SAAiB;IAC1D,OAAO;QACLgD,OAAO;QACPC,iBAAgBzG,MAAM;YACpBA,OAAO0G,WAAW,CAACC,GAAG,CAAC,CAACC,KAAKC,KAAKC;gBAChC,MAAMC,WAAW,AAACH,CAAAA,IAAIlH,GAAG,IAAI,GAAE,EAAGsH,KAAK,CAAC,IAAI,CAAC,EAAE;gBAC/C,IAAID,aAAa,OAAOA,aAAa,eAAe;oBAClDF,IAAII,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAEzD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAsD;YACF;QACF;QACAxG,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\n\nimport {type CliConfig, type Output, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n waitForWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {toWireInterface} from './toWireInterface.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\nconst renderDashboardEntry = '@sanity/workbench-cli/_internal_render'\nconst renderDashboardPath = fileURLToPath(\n new URL('../../_exports/_internal_render.js', import.meta.url),\n)\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => !isConfigOnlyServer(server))\n .map(\n ({\n host,\n id,\n interfaces,\n manifest,\n name,\n organizationId,\n port,\n projectId,\n reference,\n slug,\n type,\n visibility,\n }) => ({\n host,\n id,\n // Views cross to the remote keyed on `type`, never the internal `surface`.\n interfaces: interfaces?.map((iface) => toWireInterface(iface)),\n manifest,\n name,\n port,\n projectId,\n reference,\n type,\n ...(organizationId && slug && visibility ? {organizationId, slug, visibility} : {}),\n }),\n ),\n configs: servers.flatMap(({configs, host, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `http://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer): () => void {\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(getRegisteredServers()),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((servers) => {\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Bridge the registry into the workbench remote's HMR channel. The remote never\n * claims the workbench lock: a held lock tells the next `sanity dev` a shell is\n * running, and the remote only renders inside that shell.\n */\nexport function startWorkbenchRemoteCoordinator(options: {server: ViteDevServer}): {\n close: () => Promise<void>\n} {\n const detachBridge = attachViteDevServerBridge(options.server)\n\n return {\n close: async () => detachBridge(),\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into by a `defineApplication` app or a config-only\n // `unstable_defineMediaLibrary` config — the latter still needs the shell to\n // render it.\n if (!isWorkbenchApp(cliConfig?.app) && !isWorkbenchConfig(cliConfig?.app)) {\n devDebug('Not a workbench app or config, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n // Acquire an exclusive lock — only one workbench per machine.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({host: httpHost || 'localhost', port: workbenchPort})\n if (!workbenchLock) {\n const existing = await waitForWorkbenchLock()\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n cliConfig,\n httpHost,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable: true,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, cliConfig, httpHost, output, reactStrictMode, workbenchPort, workDir} = options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Keep this entry out of pre-bundling so Vite injects its HMR context.\n exclude: [renderDashboardEntry],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {\n // The generated Vite root cannot reliably resolve this package.\n alias: {[renderDashboardEntry]: renderDashboardPath},\n dedupe: ['react', 'react-dom'],\n },\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Workbench dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `defineApplication`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'Workbench requires an organization ID. Pass \"organizationId\" to defineApplication() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["fileURLToPath","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","isWorkbenchConfig","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","waitForWorkbenchLock","watchRegistry","toWireInterface","writeWorkbenchRuntime","devDebug","renderDashboardEntry","renderDashboardPath","URL","url","noop","toApplicationsPayload","servers","applications","filter","server","map","host","id","interfaces","manifest","name","organizationId","port","projectId","reference","slug","type","visibility","iface","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ws","on","_","client","send","setTracker","registryWatcher","hasChanged","close","startWorkbenchRemoteCoordinator","options","detachBridge","startWorkbenchDevServer","cacheDir","cliConfig","httpHost","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","workbenchLock","existing","pid","result","createWorkbenchViteServer","err","release","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","resolveOrganizationId","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","mode","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","undefined","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AAEtC,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YACA,MAAMlC,OAAO+B,KAAK;QACpB;IACF;AACF;AAEA,qEAAqE;AACrE,wEAAwE;AACxE,0EAA0E;AAC1E,6EAA6E;AAC7E,MAAM6B,wBAAwB,CAACvB;IAC7B,IAAIA,UAAUO,GAAG,EAAErC,gBAAgB;QACjC,OAAO8B,UAAUO,GAAG,CAACrC,cAAc;IACrC;IAEA,MAAM,IAAI4E,MACR;AAEJ;AAEA,4EAA4E;AAC5E,0CAA0C;AAC1C,MAAMa,kBAAkBrH,EAAEe,GAAG,CAAC;IAACuG,WAAW;IAAMC,UAAU;AAAU;AAEpE,SAAS1C,eAAe2C,KAAyB;IAC/C,IAAI,CAACA,OAAO,OAAOb;IAEnB,MAAMrC,SAAS+C,gBAAgBI,SAAS,CAACD;IAEzC,IAAI,CAAClD,OAAOoD,OAAO,EAAE;QACnB,MAAM,IAAIlB,MACR,CAAC,8CAA8C,EAAEgB,MAAM,yBAAyB,CAAC;IAErF;IAEA,OAAOlD,OAAOqD,IAAI;AACpB;AAEA;;;;;;CAMC,GACD,SAAS5B,kCAAkCnB,SAAiB;IAC1D,OAAO;QACLgD,OAAO;QACPC,iBAAgBxG,MAAM;YACpBA,OAAOyG,WAAW,CAACC,GAAG,CAAC,CAACC,KAAKC,KAAKC;gBAChC,MAAMC,WAAW,AAACH,CAAAA,IAAIjH,GAAG,IAAI,GAAE,EAAGqH,KAAK,CAAC,IAAI,CAAC,EAAE;gBAC/C,IAAID,aAAa,OAAOA,aAAa,eAAe;oBAClDF,IAAII,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAEzD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAsD;YACF;QACF;QACAvG,MAAM;IACR;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/workbench-cli",
3
- "version": "2.7.0",
3
+ "version": "2.8.1",
4
4
  "description": "Internal implementation detail of the Sanity CLI's unstable workbench support. Not intended for direct use.",
5
5
  "homepage": "https://github.com/sanity-io/cli",
6
6
  "bugs": "https://github.com/sanity-io/cli/issues",
@@ -57,9 +57,9 @@
57
57
  "access": "public"
58
58
  },
59
59
  "dependencies": {
60
- "@module-federation/runtime": "2.9.0",
61
- "@module-federation/vite": "1.22.1",
62
- "@sanity/cli-core": "^3.8.0",
60
+ "@module-federation/runtime": "2.9.2",
61
+ "@module-federation/vite": "1.23.0",
62
+ "@sanity/cli-core": "^3.8.2",
63
63
  "@sanity/types": "^6.15.0",
64
64
  "@vitejs/plugin-react": "^6.1.1",
65
65
  "form-data": "^4.0.5",
@@ -73,7 +73,7 @@
73
73
  "@eslint/compat": "^2.1.0",
74
74
  "@repo/package.config": "0.0.1",
75
75
  "@repo/tsconfig": "3.70.0",
76
- "@sanity/cli-test": "18.0.0",
76
+ "@sanity/cli-test": "18.0.2",
77
77
  "@sanity/eslint-config-cli": "^1.1.3",
78
78
  "@sanity/pkg-utils": "^12.3.4",
79
79
  "@swc/cli": "^0.8.1",