@sanity/workbench-cli 2.14.1 → 2.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/_exports/_internal_auto_updates.d.ts +14 -0
  2. package/dist/_exports/_internal_auto_updates.js +3 -0
  3. package/dist/_exports/_internal_auto_updates.js.map +1 -0
  4. package/dist/_exports/_internal_worker_bus.d.ts +1 -1
  5. package/dist/_exports/build.d.ts +8 -0
  6. package/dist/_exports/{defineService-D_DFLM8x.d.ts → defineService-DPZwNN6_.d.ts} +5 -2
  7. package/dist/_exports/deploy.d.ts +15 -1
  8. package/dist/_exports/deploy.js +1 -0
  9. package/dist/_exports/deploy.js.map +1 -1
  10. package/dist/_exports/dev.d.ts +1 -1
  11. package/dist/_exports/index.d.ts +1 -1
  12. package/dist/_exports/preview.d.ts +1 -1
  13. package/dist/_exports/{registry-DCjjQ1sS.d.ts → registry-NvtHmoN1.d.ts} +3 -1
  14. package/dist/actions/build/autoUpdatesLoader.js +36 -0
  15. package/dist/actions/build/autoUpdatesLoader.js.map +1 -0
  16. package/dist/actions/build/render-remote.js +22 -7
  17. package/dist/actions/build/render-remote.js.map +1 -1
  18. package/dist/actions/build/services/workerBus.js +6 -7
  19. package/dist/actions/build/services/workerBus.js.map +1 -1
  20. package/dist/actions/build/vite/plugin.js +3 -1
  21. package/dist/actions/build/vite/plugin.js.map +1 -1
  22. package/dist/actions/build/vite/plugins/plugin-sanity-auto-updates.js +125 -0
  23. package/dist/actions/build/vite/plugins/plugin-sanity-auto-updates.js.map +1 -0
  24. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js +3 -1
  25. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js.map +1 -1
  26. package/dist/actions/build/vite/workbench-vite-plugins.js +5 -1
  27. package/dist/actions/build/vite/workbench-vite-plugins.js.map +1 -1
  28. package/dist/actions/deploy/selectWorkbenchAppId.js +31 -0
  29. package/dist/actions/deploy/selectWorkbenchAppId.js.map +1 -0
  30. package/dist/actions/dev/registry.js +20 -1
  31. package/dist/actions/dev/registry.js.map +1 -1
  32. package/dist/actions/dev/startDevServerRegistration.js +11 -19
  33. package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
  34. package/dist/actions/dev/startWorkbenchDevServer.js +2 -1
  35. package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
  36. package/dist/actions/preview/startWorkbenchPreview.js +3 -4
  37. package/dist/actions/preview/startWorkbenchPreview.js.map +1 -1
  38. package/dist/defineService.js +4 -1
  39. package/dist/defineService.js.map +1 -1
  40. package/package.json +7 -3
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-auto-updates.ts"],"sourcesContent":["/*\n * Wraps the app's imports of auto-updated packages so they load from the module server at runtime:\n *\n * import {Studio} from 'sanity'\n * -> const m = await load('sanity')\n * export {m.Studio as Studio, ...} (export names read from the installed copy)\n *\n * `virtual:sanity/auto-updates` always resolves; `studioProps()` is empty without auto-updates.\n */\nimport {readFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport {parseSync, type Plugin, type Rolldown} from 'vite'\n\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\nexport const AUTO_UPDATES_ID = 'virtual:sanity/auto-updates'\nconst RESOLVED_AUTO_UPDATES_ID = `\\0${AUTO_UPDATES_ID}`\nconst WRAPPER_PREFIX = '\\0sanity/auto-updates:'\nconst SPECIFIERS_PLACEHOLDER = '__SANITY_AUTO_UPDATES_SPECIFIERS__'\nconst LOADER_ENTRY = '@sanity/workbench-cli/_internal_auto_updates'\n\nconst loaderPath = fileURLToPath(\n new URL('../../../../_exports/_internal_auto_updates.js', import.meta.url),\n)\n\n// The build's `autoUpdates` config, as far as the remote uses it.\nexport interface AutoUpdates {\n imports: Record<string, string>\n vendor: {specifiersByChunkName: Record<string, string>}\n\n cssUrls?: string[]\n}\n\nexport function sanityAutoUpdates(autoUpdates?: AutoUpdates): Plugin[] {\n return [\n {\n config: () => ({resolve: {alias: {[LOADER_ENTRY]: loaderPath}}}),\n load: (id) => (id === RESOLVED_AUTO_UPDATES_ID ? renderAutoUpdatesModule(autoUpdates) : null),\n name: 'sanity/auto-updates',\n resolveId: (source) => (source === AUTO_UPDATES_ID ? RESOLVED_AUTO_UPDATES_ID : null),\n },\n ...(autoUpdates ? [wrapAutoUpdatedImports(autoUpdates.imports)] : []),\n ]\n}\n\nfunction wrapAutoUpdatedImports(imports: Record<string, string>): Plugin {\n // Import map keys: `sanity` for the package, `sanity/` for its subpaths.\n const isAutoUpdated = (source: string) =>\n Object.keys(imports).some((key) =>\n key.endsWith('/') ? source.startsWith(key) : source === key,\n )\n const wrapped = new Set<string>()\n let root = ''\n\n return {\n applyToEnvironment: (env) => env.config.command === 'build' && env.name === FEDERATION_DIR_NAME,\n configResolved(config) {\n root = config.root\n },\n // Ahead of Vite's resolver, which would resolve the installed package.\n enforce: 'pre',\n async load(id) {\n if (!id.startsWith(WRAPPER_PREFIX)) return null\n\n const specifier = id.slice(WRAPPER_PREFIX.length)\n const installed = await this.resolve(specifier, path.join(root, 'package.json'), {\n skipSelf: true,\n })\n if (!installed) throw new Error(`Could not resolve ${specifier}`)\n\n return renderWrapper(specifier, await collectExports(this, installed.id))\n },\n name: 'sanity/auto-updates/wrap-imports',\n // The loader imports every wrapped specifier up front; the list is complete only after the build.\n renderChunk(code) {\n const placeholder = new RegExp(`([\"'\\`])${SPECIFIERS_PLACEHOLDER}\\\\1`)\n if (!placeholder.test(code)) return null\n\n return {\n code: code.replace(placeholder, () => JSON.stringify(JSON.stringify([...wrapped]))),\n map: null,\n }\n },\n resolveId(source, importer) {\n if (importer && isAutoUpdated(source)) {\n wrapped.add(source)\n return WRAPPER_PREFIX + source\n }\n\n return null\n },\n }\n}\n\nfunction renderAutoUpdatesModule(autoUpdates: AutoUpdates | undefined): string {\n if (!autoUpdates) return 'export const studioProps = () => ({})\\n'\n\n const vendor = Object.values(autoUpdates.vendor.specifiersByChunkName).map(\n (specifier) => `${JSON.stringify(specifier)}: () => import(${JSON.stringify(specifier)})`,\n )\n\n return `import {createAutoUpdatesLoader} from ${JSON.stringify(LOADER_ENTRY)}\nexport const {importMapUrl, load} = createAutoUpdatesLoader({\n appId: __SANITY_APP_ID__,\n cssUrls: ${JSON.stringify(autoUpdates.cssUrls ?? [])},\n imports: ${JSON.stringify(autoUpdates.imports)},\n specifiers: JSON.parse(${JSON.stringify(SPECIFIERS_PLACEHOLDER)}),\n vendor: {${vendor.join(', ')}},\n})\nexport const studioProps = () =>\n importMapUrl('sanity') ? {unstable_importMapUrl: importMapUrl('sanity')} : {}\n`\n}\n\nfunction renderWrapper(specifier: string, names: string[]): string {\n return `import {load} from ${JSON.stringify(AUTO_UPDATES_ID)}\nconst m = await load(${JSON.stringify(specifier)})\n${names.map((name, index) => `const e${index} = m[${JSON.stringify(name)}]`).join('\\n')}\nexport {${names.map((name, index) => `e${index} as ${JSON.stringify(name)}`).join(', ')}}\n`\n}\n\nasync function collectExports(\n context: Rolldown.PluginContext,\n id: string,\n seen = new Set<string>(),\n): Promise<string[]> {\n if (seen.has(id)) return []\n seen.add(id)\n\n const {module} = parseSync(id, await readFile(id, 'utf8'))\n const names: string[] = []\n for (const {exportName, moduleRequest} of module.staticExports.flatMap(({entries}) => entries)) {\n if (exportName.kind === 'Default') {\n names.push('default')\n } else if (exportName.name) {\n names.push(exportName.name)\n } else if (moduleRequest) {\n const resolved = await context.resolve(moduleRequest.value, id)\n if (!resolved) throw new Error(`Could not resolve ${moduleRequest.value} from ${id}`)\n\n const reexported = await collectExports(context, resolved.id, seen)\n names.push(...reexported.filter((name) => name !== 'default'))\n }\n }\n\n return [...new Set(names)]\n}\n"],"names":["readFile","path","fileURLToPath","parseSync","FEDERATION_DIR_NAME","AUTO_UPDATES_ID","RESOLVED_AUTO_UPDATES_ID","WRAPPER_PREFIX","SPECIFIERS_PLACEHOLDER","LOADER_ENTRY","loaderPath","URL","url","sanityAutoUpdates","autoUpdates","config","resolve","alias","load","id","renderAutoUpdatesModule","name","resolveId","source","wrapAutoUpdatedImports","imports","isAutoUpdated","Object","keys","some","key","endsWith","startsWith","wrapped","Set","root","applyToEnvironment","env","command","configResolved","enforce","specifier","slice","length","installed","join","skipSelf","Error","renderWrapper","collectExports","renderChunk","code","placeholder","RegExp","test","replace","JSON","stringify","map","importer","add","vendor","values","specifiersByChunkName","cssUrls","names","index","context","seen","has","module","exportName","moduleRequest","staticExports","flatMap","entries","kind","push","resolved","value","reexported","filter"],"mappings":"AAAA;;;;;;;;CAQC,GACD,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,aAAa,QAAO,WAAU;AAEtC,SAAQC,SAAS,QAAmC,OAAM;AAE1D,SAAQC,mBAAmB,QAAO,kBAAiB;AAEnD,OAAO,MAAMC,kBAAkB,8BAA6B;AAC5D,MAAMC,2BAA2B,CAAC,EAAE,EAAED,iBAAiB;AACvD,MAAME,iBAAiB;AACvB,MAAMC,yBAAyB;AAC/B,MAAMC,eAAe;AAErB,MAAMC,aAAaR,cACjB,IAAIS,IAAI,kDAAkD,YAAYC,GAAG;AAW3E,OAAO,SAASC,kBAAkBC,WAAyB;IACzD,OAAO;QACL;YACEC,QAAQ,IAAO,CAAA;oBAACC,SAAS;wBAACC,OAAO;4BAAC,CAACR,aAAa,EAAEC;wBAAU;oBAAC;gBAAC,CAAA;YAC9DQ,MAAM,CAACC,KAAQA,OAAOb,2BAA2Bc,wBAAwBN,eAAe;YACxFO,MAAM;YACNC,WAAW,CAACC,SAAYA,WAAWlB,kBAAkBC,2BAA2B;QAClF;WACIQ,cAAc;YAACU,uBAAuBV,YAAYW,OAAO;SAAE,GAAG,EAAE;KACrE;AACH;AAEA,SAASD,uBAAuBC,OAA+B;IAC7D,yEAAyE;IACzE,MAAMC,gBAAgB,CAACH,SACrBI,OAAOC,IAAI,CAACH,SAASI,IAAI,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AC1B,KAAK,MAAM,EAACM,UAAU,EAAEC,aAAa,EAAC,IAAIF,OAAOG,aAAa,CAACC,OAAO,CAAC,CAAC,EAACC,OAAO,EAAC,GAAKA,SAAU;QAC9F,IAAIJ,WAAWK,IAAI,KAAK,WAAW;YACjCX,MAAMY,IAAI,CAAC;QACb,OAAO,IAAIN,WAAWlD,IAAI,EAAE;YAC1B4C,MAAMY,IAAI,CAACN,WAAWlD,IAAI;QAC5B,OAAO,IAAImD,eAAe;YACxB,MAAMM,WAAW,MAAMX,QAAQnD,OAAO,CAACwD,cAAcO,KAAK,EAAE5D;YAC5D,IAAI,CAAC2D,UAAU,MAAM,IAAI/B,MAAM,CAAC,kBAAkB,EAAEyB,cAAcO,KAAK,CAAC,MAAM,EAAE5D,IAAI;YAEpF,MAAM6D,aAAa,MAAM/B,eAAekB,SAASW,SAAS3D,EAAE,EAAEiD;YAC9DH,MAAMY,IAAI,IAAIG,WAAWC,MAAM,CAAC,CAAC5D,OAASA,SAAS;QACrD;IACF;IAEA,OAAO;WAAI,IAAIa,IAAI+B;KAAO;AAC5B"}
@@ -4,15 +4,17 @@ import { renderRemote } from '../../render-remote.js';
4
4
  import { RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE } from '../../resource-bindings.js';
5
5
  import { FEDERATION_FILE_NAME, RUNTIME_DIR } from '../constants.js';
6
6
  import { getFederationApi } from './plugin-module-federation.js';
7
+ import { AUTO_UPDATES_ID } from './plugin-sanity-auto-updates.js';
7
8
  const REMOTE_ENTRY_FILE = `${FEDERATION_FILE_NAME}.jsx`;
8
9
  // The studio wraps `Studio` with the user's config; HMR re-renders through the
9
10
  // new module so a config edit takes effect. The `%RESOURCE_BINDINGS_IMPORT%`
10
11
  // placeholder is filled in per-build (Blueprints only — see below).
11
12
  const studioEntry = (isolateStyles)=>renderRemote({
12
- app: `(props) => React.createElement(Studio, { config, ...props })`,
13
+ app: `(props) => React.createElement(Studio, { config, ...studioProps(), ...props })`,
13
14
  hmr: true,
14
15
  isolateStyles,
15
16
  preamble: `%RESOURCE_BINDINGS_IMPORT%import { Studio } from 'sanity'
17
+ import { studioProps } from '${AUTO_UPDATES_ID}'
16
18
  import config from %STUDIO_CONFIG%`
17
19
  });
18
20
  // An SDK app's default export is the component; it Fast-Refreshes through its
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-federation-runtime.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type EnvironmentModuleNode, type Plugin} from 'vite'\n\nimport {renderRemote} from '../../render-remote.js'\nimport {\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n} from '../../resource-bindings.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\n\nconst REMOTE_ENTRY_FILE = `${FEDERATION_FILE_NAME}.jsx`\n\n// The studio wraps `Studio` with the user's config; HMR re-renders through the\n// new module so a config edit takes effect. The `%RESOURCE_BINDINGS_IMPORT%`\n// placeholder is filled in per-build (Blueprints only — see below).\nconst studioEntry = (isolateStyles: boolean) =>\n renderRemote({\n app: `(props) => React.createElement(Studio, { config, ...props })`,\n hmr: true,\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import { Studio } from 'sanity'\nimport config from %STUDIO_CONFIG%`,\n })\n\n// An SDK app's default export is the component; it Fast-Refreshes through its\n// own dev server, so the wrapper needs no HMR boundary.\nconst appEntry = (isolateStyles: boolean) =>\n renderRemote({\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`,\n })\n\n// A branded app that declares no `entry` (e.g. a dock-only panel/worker app)\n// has no navigable full-page view, so there's no `App` to import. The runtime\n// still needs a valid module for the federation build input, but it exposes no\n// `./App` (see `plugin.ts`) — its `render` is unreachable and throws if reached.\n// It renders no React tree, so it carries no lifecycle controller: there is\n// nothing to pause.\nconst HEADLESS_APP_ENTRY = `\\\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file are automatically discarded\n// This application declares no app view (no \\`entry\\`): it isn't navigable as a\n// full-page app, only its panels/web workers are exposed.\n%RESOURCE_BINDINGS_IMPORT%export function render() {\n throw new Error('This application has no app view: it declares no \\`entry\\`.')\n}\n`\n\nexport type FederationRuntimeOptions =\n | {appEntry?: string; isApp: true; isBlueprints?: boolean}\n | {isApp: false; isBlueprints?: boolean; studioConfigPath: string}\n\nfunction renderEntry(options: FederationRuntimeOptions, isolateStyles: boolean): string {\n const {isBlueprints} = options\n\n let content: string\n if (options.isApp) {\n content = options.appEntry\n ? appEntry(isolateStyles).replace(/%APP_ENTRY%/, JSON.stringify(options.appEntry))\n : HEADLESS_APP_ENTRY\n } else {\n content = studioEntry(isolateStyles).replace(\n /%STUDIO_CONFIG%/,\n JSON.stringify(options.studioConfigPath),\n )\n }\n\n // Blueprints only: the remote entry statically imports the resource-bindings\n // module first, so bindings evaluate before app code. Off Blueprints the\n // placeholder resolves to nothing and the module is neither imported nor\n // written below.\n return content.replace(\n /%RESOURCE_BINDINGS_IMPORT%/,\n isBlueprints ? `${RESOURCE_BINDINGS_ENTRY_IMPORT}\\n` : '',\n )\n}\n\nexport function sanityFederationRuntime(options: FederationRuntimeOptions): Plugin {\n const {isBlueprints} = options\n let entryFileAbsPath = ''\n\n return {\n configResolved(config) {\n const dir = path.resolve(config.root, RUNTIME_DIR)\n entryFileAbsPath = path.join(dir, REMOTE_ENTRY_FILE)\n\n fs.mkdirSync(dir, {recursive: true})\n const isolateStyles = getFederationApi(config.plugins)?.isolateStyles ?? false\n fs.writeFileSync(entryFileAbsPath, renderEntry(options, isolateStyles))\n\n if (isBlueprints) {\n // Brett bakes the resolved values into this module at deploy.\n fs.writeFileSync(\n path.join(dir, RESOURCE_BINDINGS_FILENAME),\n RESOURCE_BINDINGS_MODULE_SOURCE,\n )\n }\n },\n hotUpdate({file, modules, timestamp}) {\n if (options.isApp) return\n if (this.environment.name !== 'client') return\n\n const {moduleGraph} = this.environment\n const studioMods = moduleGraph.getModulesByFile(entryFileAbsPath)\n if (!studioMods?.size) return\n\n // Is the changed file reachable from the studio entry?\n const visited = new Set<EnvironmentModuleNode>()\n const queue: EnvironmentModuleNode[] = [...studioMods]\n while (queue.length > 0) {\n const mod = queue.pop()!\n if (visited.has(mod)) continue\n visited.add(mod)\n if (mod.file === file) {\n // The walk from `file` up through importers dead-ends at federation\n // gaps, so invalidate changed modules ourselves and route HMR to the\n // self-accepting studio entry.\n const seen = new Set<EnvironmentModuleNode>()\n for (const m of modules) {\n moduleGraph.invalidateModule(m, seen, timestamp, true)\n }\n return [...studioMods]\n }\n for (const dep of mod.importedModules) queue.push(dep)\n }\n },\n name: 'sanity/federation-runtime',\n }\n}\n"],"names":["fs","path","renderRemote","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","FEDERATION_FILE_NAME","RUNTIME_DIR","getFederationApi","REMOTE_ENTRY_FILE","studioEntry","isolateStyles","app","hmr","preamble","appEntry","HEADLESS_APP_ENTRY","renderEntry","options","isBlueprints","content","isApp","replace","JSON","stringify","studioConfigPath","sanityFederationRuntime","entryFileAbsPath","configResolved","config","dir","resolve","root","join","mkdirSync","recursive","plugins","writeFileSync","hotUpdate","file","modules","timestamp","environment","name","moduleGraph","studioMods","getModulesByFile","size","visited","Set","queue","length","mod","pop","has","add","seen","m","invalidateModule","dep","importedModules","push"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAI5B,SAAQC,YAAY,QAAO,yBAAwB;AACnD,SACEC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,QAC1B,6BAA4B;AACnC,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,kBAAiB;AACjE,SAAQC,gBAAg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T,GAAGkC,SAAS,CAACJ,KAAK;gBAACK,WAAW;YAAI;YAClC,MAAMxB,gBAAgBH,iBAAiBqB,OAAOO,OAAO,GAAGzB,iBAAiB;YACzEX,GAAGqC,aAAa,CAACV,kBAAkBV,YAAYC,SAASP;YAExD,IAAIQ,cAAc;gBAChB,8DAA8D;gBAC9DnB,GAAGqC,aAAa,CACdpC,KAAKgC,IAAI,CAACH,KAAK1B,6BACfC;YAEJ;QACF;QACAiC,WAAU,EAACC,IAAI,EAAEC,OAAO,EAAEC,SAAS,EAAC;YAClC,IAAIvB,QAAQG,KAAK,EAAE;YACnB,IAAI,IAAI,CAACqB,WAAW,CAACC,IAAI,KAAK,UAAU;YAExC,MAAM,EAACC,WAAW,EAAC,GAAG,IAAI,CAACF,WAAW;YACtC,MAAMG,aAAaD,YAAYE,gBAAgB,CAACnB;YAChD,IAAI,CAACkB,YAAYE,MAAM;YAEvB,uDAAuD;YACvD,MAAMC,UAAU,IAAIC;YACpB,MAAMC,QAAiC;mBAAIL;aAAW;YACtD,MAAOK,MAAMC,MAAM,GAAG,EAAG;gBACvB,MAAMC,MAAMF,MAAMG,GAAG;gBACrB,IAAIL,QAAQM,GAAG,CAACF,MAAM;gBACtBJ,QAAQO,GAAG,CAACH;gBACZ,IAAIA,IAAIb,IAAI,KAAKA,MAAM;oBACrB,oEAAoE;oBACpE,qEAAqE;oBACrE,+BAA+B;oBAC/B,MAAMiB,OAAO,IAAIP;oBACjB,KAAK,MAAMQ,KAAKjB,QAAS;wBACvBI,YAAYc,gBAAgB,CAACD,GAAGD,MAAMf,WAAW;oBACnD;oBACA,OAAO;2BAAII;qBAAW;gBACxB;gBACA,KAAK,MAAMc,OAAOP,IAAIQ,eAAe,CAAEV,MAAMW,IAAI,CAACF;YACpD;QACF;QACAhB,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-federation-runtime.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type EnvironmentModuleNode, type Plugin} from 'vite'\n\nimport {renderRemote} from '../../render-remote.js'\nimport {\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n} from '../../resource-bindings.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\nimport {AUTO_UPDATES_ID} from './plugin-sanity-auto-updates.js'\n\nconst REMOTE_ENTRY_FILE = `${FEDERATION_FILE_NAME}.jsx`\n\n// The studio wraps `Studio` with the user's config; HMR re-renders through the\n// new module so a config edit takes effect. The `%RESOURCE_BINDINGS_IMPORT%`\n// placeholder is filled in per-build (Blueprints only — see below).\nconst studioEntry = (isolateStyles: boolean) =>\n renderRemote({\n app: `(props) => React.createElement(Studio, { config, ...studioProps(), ...props })`,\n hmr: true,\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import { Studio } from 'sanity'\nimport { studioProps } from '${AUTO_UPDATES_ID}'\nimport config from %STUDIO_CONFIG%`,\n })\n\n// An SDK app's default export is the component; it Fast-Refreshes through its\n// own dev server, so the wrapper needs no HMR boundary.\nconst appEntry = (isolateStyles: boolean) =>\n renderRemote({\n isolateStyles,\n preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`,\n })\n\n// A branded app that declares no `entry` (e.g. a dock-only panel/worker app)\n// has no navigable full-page view, so there's no `App` to import. The runtime\n// still needs a valid module for the federation build input, but it exposes no\n// `./App` (see `plugin.ts`) — its `render` is unreachable and throws if reached.\n// It renders no React tree, so it carries no lifecycle controller: there is\n// nothing to pause.\nconst HEADLESS_APP_ENTRY = `\\\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file are automatically discarded\n// This application declares no app view (no \\`entry\\`): it isn't navigable as a\n// full-page app, only its panels/web workers are exposed.\n%RESOURCE_BINDINGS_IMPORT%export function render() {\n throw new Error('This application has no app view: it declares no \\`entry\\`.')\n}\n`\n\nexport type FederationRuntimeOptions =\n | {appEntry?: string; isApp: true; isBlueprints?: boolean}\n | {isApp: false; isBlueprints?: boolean; studioConfigPath: string}\n\nfunction renderEntry(options: FederationRuntimeOptions, isolateStyles: boolean): string {\n const {isBlueprints} = options\n\n let content: string\n if (options.isApp) {\n content = options.appEntry\n ? appEntry(isolateStyles).replace(/%APP_ENTRY%/, JSON.stringify(options.appEntry))\n : HEADLESS_APP_ENTRY\n } else {\n content = studioEntry(isolateStyles).replace(\n /%STUDIO_CONFIG%/,\n JSON.stringify(options.studioConfigPath),\n )\n }\n\n // Blueprints only: the remote entry statically imports the resource-bindings\n // module first, so bindings evaluate before app code. Off Blueprints the\n // placeholder resolves to nothing and the module is neither imported nor\n // written below.\n return content.replace(\n /%RESOURCE_BINDINGS_IMPORT%/,\n isBlueprints ? `${RESOURCE_BINDINGS_ENTRY_IMPORT}\\n` : '',\n )\n}\n\nexport function sanityFederationRuntime(options: FederationRuntimeOptions): Plugin {\n const {isBlueprints} = options\n let entryFileAbsPath = ''\n\n return {\n configResolved(config) {\n const dir = path.resolve(config.root, RUNTIME_DIR)\n entryFileAbsPath = path.join(dir, REMOTE_ENTRY_FILE)\n\n fs.mkdirSync(dir, {recursive: true})\n const isolateStyles = getFederationApi(config.plugins)?.isolateStyles ?? false\n fs.writeFileSync(entryFileAbsPath, renderEntry(options, isolateStyles))\n\n if (isBlueprints) {\n // Brett bakes the resolved values into this module at deploy.\n fs.writeFileSync(\n path.join(dir, RESOURCE_BINDINGS_FILENAME),\n RESOURCE_BINDINGS_MODULE_SOURCE,\n )\n }\n },\n hotUpdate({file, modules, timestamp}) {\n if (options.isApp) return\n if (this.environment.name !== 'client') return\n\n const {moduleGraph} = this.environment\n const studioMods = moduleGraph.getModulesByFile(entryFileAbsPath)\n if (!studioMods?.size) return\n\n // Is the changed file reachable from the studio entry?\n const visited = new Set<EnvironmentModuleNode>()\n const queue: EnvironmentModuleNode[] = [...studioMods]\n while (queue.length > 0) {\n const mod = queue.pop()!\n if (visited.has(mod)) continue\n visited.add(mod)\n if (mod.file === file) {\n // The walk from `file` up through importers dead-ends at federation\n // gaps, so invalidate changed modules ourselves and route HMR to the\n // self-accepting studio entry.\n const seen = new Set<EnvironmentModuleNode>()\n for (const m of modules) {\n moduleGraph.invalidateModule(m, seen, timestamp, true)\n }\n return [...studioMods]\n }\n for (const dep of mod.importedModules) queue.push(dep)\n }\n },\n name: 'sanity/federation-runtime',\n }\n}\n"],"names":["fs","path","renderRemote","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","FEDERATION_FILE_NAME","RUNTIME_DIR","getFederationApi","AUTO_UPDATES_ID","REMOTE_ENTRY_FILE","studioEntry","isolateStyles","app","hmr","preamble","appEntry","HEADLESS_APP_ENTRY","renderEntry","options","isBlueprints","content","isApp","replace","JSON","stringify","studioConfigPath","sanityFederationRuntime","entryFileAbsPath","configResolved","config","dir","resolve","root","join","mkdirSync","recursive","plugins","writeFileSync","hotUpdate","file","modules","timestamp","environment","name","moduleGraph","studioMods","getModulesByFile","size","visited","Set","queue","length","mod","pop","has","add","seen","m","invalidateModule","dep","importedModules","push"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAI5B,SAAQC,YAAY,QAAO,yBAAwB;AACnD,SACEC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,QAC1B,6BAA4B;AACnC,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,kBAAiB;AACjE,SAAQC,gBAAgB,QAAO,gCAA+B;AAC9D,SAAQC,eAAe,QAAO,kCAAiC;AAE/D,MAAMC,oBAAoB,GAAGJ,qBAAqB,IAAI,CAAC;AAEvD,+EAA+E;AAC/E,6EAA6E;AAC7E,oEAAoE;AACpE,MAAMK,cAAc,CAACC,gBACnBV,aAAa;QACXW,KAAK,CAAC,8EAA8E,CAAC;QACrFC,KAAK;Q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,cAAc;gBAChB,8DAA8D;gBAC9DpB,GAAGsC,aAAa,CACdrC,KAAKiC,IAAI,CAACH,KAAK3B,6BACfC;YAEJ;QACF;QACAkC,WAAU,EAACC,IAAI,EAAEC,OAAO,EAAEC,SAAS,EAAC;YAClC,IAAIvB,QAAQG,KAAK,EAAE;YACnB,IAAI,IAAI,CAACqB,WAAW,CAACC,IAAI,KAAK,UAAU;YAExC,MAAM,EAACC,WAAW,EAAC,GAAG,IAAI,CAACF,WAAW;YACtC,MAAMG,aAAaD,YAAYE,gBAAgB,CAACnB;YAChD,IAAI,CAACkB,YAAYE,MAAM;YAEvB,uDAAuD;YACvD,MAAMC,UAAU,IAAIC;YACpB,MAAMC,QAAiC;mBAAIL;aAAW;YACtD,MAAOK,MAAMC,MAAM,GAAG,EAAG;gBACvB,MAAMC,MAAMF,MAAMG,GAAG;gBACrB,IAAIL,QAAQM,GAAG,CAACF,MAAM;gBACtBJ,QAAQO,GAAG,CAACH;gBACZ,IAAIA,IAAIb,IAAI,KAAKA,MAAM;oBACrB,oEAAoE;oBACpE,qEAAqE;oBACrE,+BAA+B;oBAC/B,MAAMiB,OAAO,IAAIP;oBACjB,KAAK,MAAMQ,KAAKjB,QAAS;wBACvBI,YAAYc,gBAAgB,CAACD,GAAGD,MAAMf,WAAW;oBACnD;oBACA,OAAO;2BAAII;qBAAW;gBACxB;gBACA,KAAK,MAAMc,OAAOP,IAAIQ,eAAe,CAAEV,MAAMW,IAAI,CAACF;YACpD;QACF;QACAhB,MAAM;IACR;AACF"}
@@ -22,7 +22,10 @@ import { stripSuiGlobalReset } from './plugins/plugin-strip-sui-global-reset.js'
22
22
  return relativeConfigLocation;
23
23
  }
24
24
  /** Build the Vite plugins for a workbench app's module-federation remote. */ export async function workbenchVitePlugins(options) {
25
- const { appId, cwd, entries, exposes, isApp, isBlueprints } = options;
25
+ const { appId, autoUpdates, cwd, entries, exposes, isApp, isBlueprints } = options;
26
+ if (autoUpdates && appId === undefined) {
27
+ throw new Error('An auto-updating workbench app needs an app ID');
28
+ }
26
29
  const pkgJson = await readPackageJson(path.join(cwd, 'package.json'));
27
30
  const federationPlugin = federation({
28
31
  ...isApp ? {
@@ -36,6 +39,7 @@ import { stripSuiGlobalReset } from './plugins/plugin-strip-sui-global-reset.js'
36
39
  isApp: false,
37
40
  studioConfigPath: requireStudioConfigPath(entries.relativeConfigLocation)
38
41
  },
42
+ autoUpdates,
39
43
  exposes,
40
44
  isBlueprints,
41
45
  pkgJson,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/vite/workbench-vite-plugins.ts"],"sourcesContent":["// The build-facing entry of the workbench federation stack: turn a workbench\n// app's build inputs into the Vite plugins that produce its module-federation\n// remote. `@sanity/cli-build`'s `getViteConfig` calls this instead of\n// assembling `federation`'s options itself, so the discriminated app-vs-studio\n// option shape, the no-app-view rule, and the studio-config requirement all\n// live here next to `federation` — the build package just hands over its inputs.\n\nimport path from 'node:path'\n\nimport {readPackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {federation} from './plugin.js'\nimport {sanityAppId} from './plugins/plugin-sanity-app-id.js'\nimport {stripSuiGlobalReset} from './plugins/plugin-strip-sui-global-reset.js'\n\ninterface WorkbenchViteOptions {\n /** Project root — read for the federation remote name, and the plugin workDir. */\n cwd: string\n /**\n * Build entry paths relative to the federation runtime dir. `relativeEntry` is\n * the app's `entry` (null for a dock-only app with no app view);\n * `relativeConfigLocation` is the studio's `sanity.config.*` (null when absent).\n */\n entries: {relativeConfigLocation: string | null; relativeEntry: string | null}\n\n /** The app's bus identity, stamped into its modules for `@sanity/runtime`. */\n appId?: string\n\n exposes?: WorkbenchExposes\n /** App (vs studio) build — selects the discriminated federation option shape. */\n isApp?: boolean\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\n/**\n * A workbench studio renders from its `sanity.config.*`, so the build needs one.\n * An explicit `applicationType: 'studio'` wins over detection, so a studio can\n * reach here with no config file — fail with the fix rather than a cryptic build\n * error downstream.\n */\nfunction requireStudioConfigPath(relativeConfigLocation: string | null): string {\n if (relativeConfigLocation === null) {\n throw new Error(\n 'Dashboard studios need a sanity.config.js or sanity.config.ts file. ' +\n \"Add one, or remove `applicationType: 'studio'` from `defineApplication` \" +\n 'to let the CLI infer the application type.',\n )\n }\n return relativeConfigLocation\n}\n\n/** Build the Vite plugins for a workbench app's module-federation remote. */\nexport async function workbenchVitePlugins(options: WorkbenchViteOptions): Promise<PluginOption> {\n const {appId, cwd, entries, exposes, isApp, isBlueprints} = options\n const pkgJson = await readPackageJson(path.join(cwd, 'package.json'))\n\n const federationPlugin = federation({\n ...(isApp\n ? {\n // `null` relativeEntry (a branded app with no `entry`) → omit `appEntry`,\n // so the remote exposes no `./App`, only its views.\n ...(entries.relativeEntry ? {appEntry: entries.relativeEntry} : {}),\n isApp: true as const,\n }\n : {\n isApp: false as const,\n studioConfigPath: requireStudioConfigPath(entries.relativeConfigLocation),\n }),\n exposes,\n isBlueprints,\n pkgJson,\n workDir: cwd,\n })\n\n // Media Library config apps run their modules inside the host's page, so\n // the `sanity` barrel's document-wide CSS reset must not travel with the\n // bundle (see the plugin for the full why).\n const configAppPlugins: PluginOption[] = isMediaLibraryConfigApp(exposes)\n ? [stripSuiGlobalReset()]\n : []\n\n return [\n ...configAppPlugins,\n federationPlugin,\n ...(appId === undefined ? [] : [sanityAppId(appId)]),\n ]\n}\n"],"names":["path","readPackageJson","isMediaLibraryConfigApp","federation","sanityAppId","stripSuiGlobalReset","requireStudioConfigPath","relativeConfigLocation","Error","workbenchVitePlugins","options","appId","cwd","entries","exposes","isApp","isBlueprints","pkgJson","join","federationPlugin","relativeEntry","appEntry","studioConfigPath","workDir","configAppPlugins","undefined"],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,sEAAsE;AACtE,+EAA+E;AAC/E,4EAA4E;AAC5E,iFAAiF;AAEjF,OAAOA,UAAU,YAAW;AAE5B,SAAQC,eAAe,QAAO,mBAAkB;AAIhD,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SAAQC,UAAU,QAAO,cAAa;AACtC,SAAQC,WAAW,QAAO,oCAAmC;AAC7D,SAAQC,mBAAmB,QAAO,6CAA4C;AAsB9E;;;;;CAKC,GACD,SAASC,wBAAwBC,sBAAqC;IACpE,IAAIA,2BAA2B,MAAM;QACnC,MAAM,IAAIC,MACR,yEACE,6EACA;IAEN;IACA,OAAOD;AACT;AAEA,2EAA2E,GAC3E,OAAO,eAAeE,qBAAqBC,OAA6B;IACtE,MAAM,EAACC,KAAK,EAAEC,GAAG,EAAEC,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGN;IAC5D,MAAMO,UAAU,MAAMhB,gBAAgBD,KAAKkB,IAAI,CAACN,KAAK;IAErD,MAAMO,mBAAmBhB,WAAW;QAClC,GAAIY,QACA;YACE,0EAA0E;YAC1E,oDAAoD;YACpD,GAAIF,QAAQO,aAAa,GAAG;gBAACC,UAAUR,QAAQO,aAAa;YAAA,IAAI,CAAC,CAAC;YAClEL,OAAO;QACT,IACA;YACEA,OAAO;YACPO,kBAAkBhB,wBAAwBO,QAAQN,sBAAsB;QAC1E,CAAC;QACLO;QACAE;QACAC;QACAM,SAASX;IACX;IAEA,yEAAyE;IACzE,yEAAyE;IACzE,4CAA4C;IAC5C,MAAMY,mBAAmCtB,wBAAwBY,WAC7D;QAACT;KAAsB,GACvB,EAAE;IAEN,OAAO;WACFmB;QACHL;WACIR,UAAUc,YAAY,EAAE,GAAG;YAACrB,YAAYO;SAAO;KACpD;AACH"}
1
+ {"version":3,"sources":["../../../../src/actions/build/vite/workbench-vite-plugins.ts"],"sourcesContent":["// The build-facing entry of the workbench federation stack: turn a workbench\n// app's build inputs into the Vite plugins that produce its module-federation\n// remote. `@sanity/cli-build`'s `getViteConfig` calls this instead of\n// assembling `federation`'s options itself, so the discriminated app-vs-studio\n// option shape, the no-app-view rule, and the studio-config requirement all\n// live here next to `federation` — the build package just hands over its inputs.\n\nimport path from 'node:path'\n\nimport {readPackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {federation} from './plugin.js'\nimport {sanityAppId} from './plugins/plugin-sanity-app-id.js'\nimport {type AutoUpdates} from './plugins/plugin-sanity-auto-updates.js'\nimport {stripSuiGlobalReset} from './plugins/plugin-strip-sui-global-reset.js'\n\ninterface WorkbenchViteOptions {\n /** Project root — read for the federation remote name, and the plugin workDir. */\n cwd: string\n /**\n * Build entry paths relative to the federation runtime dir. `relativeEntry` is\n * the app's `entry` (null for a dock-only app with no app view);\n * `relativeConfigLocation` is the studio's `sanity.config.*` (null when absent).\n */\n entries: {relativeConfigLocation: string | null; relativeEntry: string | null}\n\n /** The app's bus identity, stamped into its modules for `@sanity/runtime`. */\n appId?: string\n\n autoUpdates?: AutoUpdates\n exposes?: WorkbenchExposes\n /** App (vs studio) build — selects the discriminated federation option shape. */\n isApp?: boolean\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\n/**\n * A workbench studio renders from its `sanity.config.*`, so the build needs one.\n * An explicit `applicationType: 'studio'` wins over detection, so a studio can\n * reach here with no config file — fail with the fix rather than a cryptic build\n * error downstream.\n */\nfunction requireStudioConfigPath(relativeConfigLocation: string | null): string {\n if (relativeConfigLocation === null) {\n throw new Error(\n 'Dashboard studios need a sanity.config.js or sanity.config.ts file. ' +\n \"Add one, or remove `applicationType: 'studio'` from `defineApplication` \" +\n 'to let the CLI infer the application type.',\n )\n }\n return relativeConfigLocation\n}\n\n/** Build the Vite plugins for a workbench app's module-federation remote. */\nexport async function workbenchVitePlugins(options: WorkbenchViteOptions): Promise<PluginOption> {\n const {appId, autoUpdates, cwd, entries, exposes, isApp, isBlueprints} = options\n if (autoUpdates && appId === undefined) {\n throw new Error('An auto-updating workbench app needs an app ID')\n }\n\n const pkgJson = await readPackageJson(path.join(cwd, 'package.json'))\n\n const federationPlugin = federation({\n ...(isApp\n ? {\n // `null` relativeEntry (a branded app with no `entry`) → omit `appEntry`,\n // so the remote exposes no `./App`, only its views.\n ...(entries.relativeEntry ? {appEntry: entries.relativeEntry} : {}),\n isApp: true as const,\n }\n : {\n isApp: false as const,\n studioConfigPath: requireStudioConfigPath(entries.relativeConfigLocation),\n }),\n autoUpdates,\n exposes,\n isBlueprints,\n pkgJson,\n workDir: cwd,\n })\n\n // Media Library config apps run their modules inside the host's page, so\n // the `sanity` barrel's document-wide CSS reset must not travel with the\n // bundle (see the plugin for the full why).\n const configAppPlugins: PluginOption[] = isMediaLibraryConfigApp(exposes)\n ? [stripSuiGlobalReset()]\n : []\n\n return [\n ...configAppPlugins,\n federationPlugin,\n ...(appId === undefined ? [] : [sanityAppId(appId)]),\n ]\n}\n"],"names":["path","readPackageJson","isMediaLibraryConfigApp","federation","sanityAppId","stripSuiGlobalReset","requireStudioConfigPath","relativeConfigLocation","Error","workbenchVitePlugins","options","appId","autoUpdates","cwd","entries","exposes","isApp","isBlueprints","undefined","pkgJson","join","federationPlugin","relativeEntry","appEntry","studioConfigPath","workDir","configAppPlugins"],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,sEAAsE;AACtE,+EAA+E;AAC/E,4EAA4E;AAC5E,iFAAiF;AAEjF,OAAOA,UAAU,YAAW;AAE5B,SAAQC,eAAe,QAAO,mBAAkB;AAIhD,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SAAQC,UAAU,QAAO,cAAa;AACtC,SAAQC,WAAW,QAAO,oCAAmC;AAE7D,SAAQC,mBAAmB,QAAO,6CAA4C;AAuB9E;;;;;CAKC,GACD,SAASC,wBAAwBC,sBAAqC;IACpE,IAAIA,2BAA2B,MAAM;QACnC,MAAM,IAAIC,MACR,yEACE,6EACA;IAEN;IACA,OAAOD;AACT;AAEA,2EAA2E,GAC3E,OAAO,eAAeE,qBAAqBC,OAA6B;IACtE,MAAM,EAACC,KAAK,EAAEC,WAAW,EAAEC,GAAG,EAAEC,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGP;IACzE,IAAIE,eAAeD,UAAUO,WAAW;QACtC,MAAM,IAAIV,MAAM;IAClB;IAEA,MAAMW,UAAU,MAAMlB,gBAAgBD,KAAKoB,IAAI,CAACP,KAAK;IAErD,MAAMQ,mBAAmBlB,WAAW;QAClC,GAAIa,QACA;YACE,0EAA0E;YAC1E,oDAAoD;YACpD,GAAIF,QAAQQ,aAAa,GAAG;gBAACC,UAAUT,QAAQQ,aAAa;YAAA,IAAI,CAAC,CAAC;YAClEN,OAAO;QACT,IACA;YACEA,OAAO;YACPQ,kBAAkBlB,wBAAwBQ,QAAQP,sBAAsB;QAC1E,CAAC;QACLK;QACAG;QACAE;QACAE;QACAM,SAASZ;IACX;IAEA,yEAAyE;IACzE,yEAAyE;IACzE,4CAA4C;IAC5C,MAAMa,mBAAmCxB,wBAAwBa,WAC7D;QAACV;KAAsB,GACvB,EAAE;IAEN,OAAO;WACFqB;QACHL;WACIV,UAAUO,YAAY,EAAE,GAAG;YAACd,YAAYO;SAAO;KACpD;AACH"}
@@ -0,0 +1,31 @@
1
+ import { select, Separator } from '@sanity/cli-core/ux';
2
+ import { listApplications } from '../../services/applications.js';
3
+ /**
4
+ * Offers an interactive deploy without `deployment.appId` the organization's
5
+ * applications of `type`. Returns the configured or picked id; undefined creates one.
6
+ * @internal
7
+ */ export async function selectWorkbenchAppId({ appId, flags, organizationId, type }) {
8
+ // --yes also covers dry runs and CI; --no-build fails a first deploy regardless of the pick
9
+ if (appId || !organizationId || flags.yes || !flags.build) return appId;
10
+ const existing = (await listApplications(organizationId)).filter((app)=>app.type === type);
11
+ if (existing.length === 0) return undefined;
12
+ const selected = await select({
13
+ choices: [
14
+ {
15
+ name: 'New application deployment',
16
+ value: 'NEW_APP'
17
+ },
18
+ new Separator(' ════ Existing applications: ════ '),
19
+ ...existing.map((app)=>({
20
+ name: app.title,
21
+ value: app.id
22
+ }))
23
+ ],
24
+ loop: false,
25
+ message: 'Would you like to create a new application deployment, or deploy to an existing one?',
26
+ pageSize: 10
27
+ });
28
+ return selected === 'NEW_APP' ? undefined : selected;
29
+ }
30
+
31
+ //# sourceMappingURL=selectWorkbenchAppId.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/deploy/selectWorkbenchAppId.ts"],"sourcesContent":["import {select, Separator} from '@sanity/cli-core/ux'\n\nimport {type ApplicationType, listApplications} from '../../services/applications.js'\n\n/**\n * Offers an interactive deploy without `deployment.appId` the organization's\n * applications of `type`. Returns the configured or picked id; undefined creates one.\n * @internal\n */\nexport async function selectWorkbenchAppId({\n appId,\n flags,\n organizationId,\n type,\n}: {\n appId: string | undefined\n flags: {build: boolean; yes: boolean}\n organizationId: string | undefined\n type: ApplicationType\n}): Promise<string | undefined> {\n // --yes also covers dry runs and CI; --no-build fails a first deploy regardless of the pick\n if (appId || !organizationId || flags.yes || !flags.build) return appId\n\n const existing = (await listApplications(organizationId)).filter((app) => app.type === type)\n\n if (existing.length === 0) return undefined\n\n const selected = await select({\n choices: [\n {name: 'New application deployment', value: 'NEW_APP'},\n new Separator(' ════ Existing applications: ════ '),\n ...existing.map((app) => ({name: app.title, value: app.id})),\n ],\n loop: false,\n message: 'Would you like to create a new application deployment, or deploy to an existing one?',\n pageSize: 10,\n })\n\n return selected === 'NEW_APP' ? undefined : selected\n}\n"],"names":["select","Separator","listApplications","selectWorkbenchAppId","appId","flags","organizationId","type","yes","build","existing","filter","app","length","undefined","selected","choices","name","value","map","title","id","loop","message","pageSize"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,sBAAqB;AAErD,SAA8BC,gBAAgB,QAAO,iCAAgC;AAErF;;;;CAIC,GACD,OAAO,eAAeC,qBAAqB,EACzCC,KAAK,EACLC,KAAK,EACLC,cAAc,EACdC,IAAI,EAML;IACC,4FAA4F;IAC5F,IAAIH,SAAS,CAACE,kBAAkBD,MAAMG,GAAG,IAAI,CAACH,MAAMI,KAAK,EAAE,OAAOL;IAElE,MAAMM,WAAW,AAAC,CAAA,MAAMR,iBAAiBI,eAAc,EAAGK,MAAM,CAAC,CAACC,MAAQA,IAAIL,IAAI,KAAKA;IAEvF,IAAIG,SAASG,MAAM,KAAK,GAAG,OAAOC;IAElC,MAAMC,WAAW,MAAMf,OAAO;QAC5BgB,SAAS;YACP;gBAACC,MAAM;gBAA8BC,OAAO;YAAS;YACrD,IAAIjB,UAAU;eACXS,SAASS,GAAG,CAAC,CAACP,MAAS,CAAA;oBAACK,MAAML,IAAIQ,KAAK;oBAAEF,OAAON,IAAIS,EAAE;gBAAA,CAAA;SAC1D;QACDC,MAAM;QACNC,SAAS;QACTC,UAAU;IACZ;IAEA,OAAOT,aAAa,YAAYD,YAAYC;AAC9C"}
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, watch, wr
2
2
  import { join } from 'node:path';
3
3
  import { coreAppManifestSchema, getSanityDataDir, studioManifestSchema, subdebug } from '@sanity/cli-core';
4
4
  import { z } from 'zod/mini';
5
+ import { applicationReference } from '../../applicationReference.js';
5
6
  import { TileInterfaceMetadataSchema, ViewPlacementMetadataSchema } from '../../contract.js';
6
7
  import { canonicalizeWatchDir } from './canonicalizeWatchDir.js';
7
8
  import { getProcessStartTime, isOurProcess } from './processLiveness.js';
@@ -76,6 +77,7 @@ const interfaceBaseFields = {
76
77
  // Exported so test fixtures can validate against the same schema the registry
77
78
  // parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.
78
79
  export const devServerManifestSchema = z.object({
80
+ applicationId: z.optional(z.string()),
79
81
  /**
80
82
  * Field schema *values* load from the federation module; each field's `src`
81
83
  * rides along so a repoint bumps the exposes-set id and forces a rebuild.
@@ -100,7 +102,10 @@ export const devServerManifestSchema = z.object({
100
102
  version: z.string()
101
103
  }))),
102
104
  host: z.string(),
103
- id: z.optional(z.string()),
105
+ /**
106
+ * The id the app runs under on the bus. It stays apart from `applicationId`,
107
+ * because Dashboards that predate `applicationId` key local apps on it.
108
+ */ id: z.optional(z.string()),
104
109
  interfaces: z.optional(z.array(devServerInterfaceSchema)),
105
110
  /**
106
111
  * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},
@@ -146,6 +151,20 @@ export const devServerManifestSchema = z.object({
146
151
  */ export function isConfigOnlyServer(server) {
147
152
  return Boolean(server.configs?.length) && !server.interfaces?.length;
148
153
  }
154
+ export function localAppIdentity(app) {
155
+ const name = app.name ?? app.slug;
156
+ return {
157
+ name,
158
+ organizationId: app.organizationId,
159
+ reference: applicationReference({
160
+ isSingleton: app.isSingleton ?? false,
161
+ name,
162
+ organizationId: app.organizationId
163
+ }),
164
+ slug: app.slug,
165
+ visibility: app.visibility ?? 'default'
166
+ };
167
+ }
149
168
  /**
150
169
  * Where the Dashboard shell opens a registered server: `/local/<id>`, only when
151
170
  * it has an id and a `surface: 'window'` interface. That interface is the app
@@ -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-<organizationId>.lock` — one lock per organization, so only one\n * workbench shell per org runs at a time and later `dev`s register into it\n * instead of starting their 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 * Where the Dashboard shell opens a registered server: `/local/<id>`, only when\n * it has an id and a `surface: 'window'` interface. That interface is the app\n * view the shell's `/local/:applicationId` route renders (see toWireInterface);\n * studios always get one, configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n return server.id && hasAppView ? `/local/${encodeURIComponent(server.id)}` : undefined\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 organization\". 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(\n organizationId: string,\n): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile(organizationId)\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(organizationId))\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(\n organizationId: string,\n): Promise<z.infer<typeof workbenchLockSchema> | undefined> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock(organizationId)\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(organizationId)\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(organizationId)\n}\n\nconst getLockPath = (organizationId: string) =>\n join(getRegistryDir(), `workbench-${organizationId}.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(\n organizationId: string,\n): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(organizationId), '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; organizationId: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = getLockPath(info.organizationId)\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(info.organizationId)?.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(info.organizationId)\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","dashboardPath","hasAppView","some","iface","encodeURIComponent","undefined","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","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":"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,EAAEyB,MAAM,CAAC;YACP,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SAAS;QAET,IAAI6E,WAAW;QACf,8EAA8E;QAC9E,kDAAkD;QAClD,MAAMC,oBAAoBb,oBAAoBuD,UAAU;YACtD,IAAI3C,UAAU,OAAO;YACrB,MAAMiD,OAAOnB,aAAae,KAAKpF,cAAc,GAAGqD;YAChD,OAAOmC,MAAM1H,QAAQD,QAAQC,GAAG,IAAI0H,KAAKlF,SAAS,KAAKA;QACzD;QAEA,OAAO;YACLmC;gBACEF,WAAW;gBACXC;gBACA,IAAI;oBACF5F,WAAWsI;gBACb,EAAE,OAAM;gBACN,qBAAqB;gBACvB;YACF;YACAO,YAAWvF,IAAY;gBACrBpD,cAAcoI,UAAU7C,KAAKC,SAAS,CAAC;oBAAC,GAAGgD,QAAQ;oBAAEpF;oBAAMiE,OAAO;gBAAI;YACxE;QACF;IACF,EAAE,OAAOuB,KAAc;QACrBhI,SACE,wCACAgI,eAAeC,QAAQD,IAAIE,OAAO,GAAGC,OAAOH;QAE9C,IAAI,CAACI,YAAYJ,QAAQA,IAAIK,IAAI,KAAK,UAAU,OAAO5E;QAEvD,mDAAmD;QACnD,MAAM6E,WAAW5B,kBAAkBgB,KAAKpF,cAAc;QACtD,IAAIgG,UAAU,OAAO7E;QAErB,6FAA6F;QAC7F,IAAIkE,WAAW,GAAG,OAAOlE;QACzB,OAAOgE,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 {applicationReference} from '../../applicationReference.js'\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {type WorkbenchApp} from '../../defineApp.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-<organizationId>.lock` — one lock per organization, so only one\n * workbench shell per org runs at a time and later `dev`s register into it\n * instead of starting their 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 applicationId: z.optional(z.string()),\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 /**\n * The id the app runs under on the bus. It stays apart from `applicationId`,\n * because Dashboards that predate `applicationId` key local apps on it.\n */\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\nexport function localAppIdentity(\n app: Pick<WorkbenchApp, 'isSingleton' | 'name' | 'organizationId' | 'slug' | 'visibility'>,\n): Pick<DevServerManifest, 'name' | 'organizationId' | 'reference' | 'slug' | 'visibility'> {\n const name = app.name ?? app.slug\n\n return {\n name,\n organizationId: app.organizationId,\n reference: applicationReference({\n isSingleton: app.isSingleton ?? false,\n name,\n organizationId: app.organizationId,\n }),\n slug: app.slug,\n visibility: app.visibility ?? 'default',\n }\n}\n\n/**\n * Where the Dashboard shell opens a registered server: `/local/<id>`, only when\n * it has an id and a `surface: 'window'` interface. That interface is the app\n * view the shell's `/local/:applicationId` route renders (see toWireInterface);\n * studios always get one, configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n return server.id && hasAppView ? `/local/${encodeURIComponent(server.id)}` : undefined\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 organization\". 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(\n organizationId: string,\n): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile(organizationId)\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(organizationId))\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(\n organizationId: string,\n): Promise<z.infer<typeof workbenchLockSchema> | undefined> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock(organizationId)\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(organizationId)\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(organizationId)\n}\n\nconst getLockPath = (organizationId: string) =>\n join(getRegistryDir(), `workbench-${organizationId}.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(\n organizationId: string,\n): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(organizationId), '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; organizationId: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = getLockPath(info.organizationId)\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(info.organizationId)?.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(info.organizationId)\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","applicationReference","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","applicationId","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","localAppIdentity","app","isSingleton","dashboardPath","hasAppView","some","iface","encodeURIComponent","undefined","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","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":"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,oBAAoB,QAAO,gCAA+B;AAClE,SAAQC,2BAA2B,EAAEC,2BAA2B,QAAO,oBAAmB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OAAOnB,aAAae,KAAKvF,cAAc,GAAGwD;YAChD,OAAOmC,MAAM9H,QAAQD,QAAQC,GAAG,IAAI8H,KAAKrF,SAAS,KAAKA;QACzD;QAEA,OAAO;YACLsC;gBACEF,WAAW;gBACXC;gBACA,IAAI;oBACFjG,WAAW2I;gBACb,EAAE,OAAM;gBACN,qBAAqB;gBACvB;YACF;YACAO,YAAW1F,IAAY;gBACrBtD,cAAcyI,UAAU7C,KAAKC,SAAS,CAAC;oBAAC,GAAGgD,QAAQ;oBAAEvF;oBAAMoE,OAAO;gBAAI;YACxE;QACF;IACF,EAAE,OAAOuB,KAAc;QACrBpI,SACE,wCACAoI,eAAeC,QAAQD,IAAIE,OAAO,GAAGC,OAAOH;QAE9C,IAAI,CAACI,YAAYJ,QAAQA,IAAIK,IAAI,KAAK,UAAU,OAAO5E;QAEvD,mDAAmD;QACnD,MAAM6E,WAAW5B,kBAAkBgB,KAAKvF,cAAc;QACtD,IAAImG,UAAU,OAAO7E;QAErB,6FAA6F;QAC7F,IAAIkE,WAAW,GAAG,OAAOlE;QACzB,OAAOgE,qBAAqBC,MAAMC,UAAU;IAC9C;AACF;AAEA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
@@ -1,12 +1,11 @@
1
1
  import { getCliConfigUncached } from '@sanity/cli-core';
2
- import { applicationReference } from '../../applicationReference.js';
3
2
  import { isWorkbenchApp, isWorkbenchConfig } from '../../defineApp.js';
4
3
  import { deriveInterfaces } from '../../deriveInterfaces.js';
5
4
  import { resolveWorkbenchConfig } from '../../resolveWorkbenchConfig.js';
6
5
  import { formatWorkbenchAppErrors, validateWorkbenchApp } from '../../validateWorkbenchApp.js';
7
6
  import { deriveConfigs } from './deriveConfigs.js';
8
7
  import { trackExposesSet } from './exposesSetId.js';
9
- import { dashboardPath, getRegisteredServers, registerDevServer } from './registry.js';
8
+ import { dashboardPath, getRegisteredServers, localAppIdentity, registerDevServer } from './registry.js';
10
9
  import { startDevManifestWatcher } from './startDevManifestWatcher.js';
11
10
  /**
12
11
  * Log any app validation errors without aborting. Unlike build and deploy, dev
@@ -46,22 +45,17 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
46
45
  // A config runs alongside the app it configures, so give it its own id
47
46
  // namespace — sharing the app's slug would make the two indistinguishable here.
48
47
  const id = config ? `config:${config.appType}` : workbenchApp?.slug;
48
+ const applicationId = workbenchApp ? cliConfig.deployment?.appId : undefined;
49
49
  // Identity is resolved and the reference composed here, so the workbench reads
50
- // both off the registry entry instead of recomposing them. Name defaults to the
51
- // slug, mirroring brett.
52
- const name = workbenchApp?.name ?? workbenchApp?.slug;
53
- const reference = workbenchApp && name ? // is a config, not an app — so its reference is always `<org>/<name>`.
54
- applicationReference({
55
- isSingleton: false,
56
- name,
57
- organizationId: workbenchApp.organizationId
58
- }) : undefined;
59
- // Separate namespaces mean a shared id is a genuine duplicate, so the gate is
60
- // an id match within the org — no config-vs-app role left to reconcile.
50
+ // both off the registry entry instead of recomposing them.
51
+ const identity = workbenchApp ? localAppIdentity(workbenchApp) : undefined;
52
+ // The Dashboard tells local apps apart by their bus id and by the application
53
+ // they stand in for.
61
54
  const organizationId = cliConfig.app?.organizationId;
62
- const devServer = id ? getRegisteredServers().find((server)=>server.id === id && server.organizationId === organizationId) : undefined;
55
+ const devServer = getRegisteredServers().find((server)=>server.organizationId === organizationId && (server.id === id || applicationId && server.applicationId === applicationId));
63
56
  if (id && devServer) {
64
- output.error(`"${id}" is already served by another dev server running on port ${devServer.port}, ` + "so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.", {
57
+ const served = devServer.id === id ? `"${id}" is already served` : `"${id}" is the same application as "${devServer.id}", served`;
58
+ output.error(`${served} by another dev server running on port ${devServer.port}, ` + "so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.", {
65
59
  exit: false
66
60
  });
67
61
  return {
@@ -69,18 +63,16 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
69
63
  };
70
64
  }
71
65
  const registration = registerDevServer({
66
+ applicationId,
72
67
  configs,
73
68
  host: appHost,
74
69
  id,
75
70
  interfaces,
76
- name,
77
71
  organizationId,
78
72
  port: appPort,
79
73
  projectId: cliConfig?.api?.projectId,
80
- reference,
81
- slug: workbenchApp?.slug,
74
+ ...identity,
82
75
  type: isApp ? 'coreApp' : 'studio',
83
- visibility: workbenchApp ? workbenchApp.visibility ?? 'default' : undefined,
84
76
  workDir
85
77
  });
86
78
  const exposesSet = trackExposesSet({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {applicationReference} from '../../applicationReference.js'\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from '../../validateWorkbenchApp.js'\nimport {deriveConfigs} from './deriveConfigs.js'\nimport {trackExposesSet} from './exposesSetId.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n getRegisteredServers,\n registerDevServer,\n} from './registry.js'\nimport {startDevManifestWatcher} from './startDevManifestWatcher.js'\n\ninterface DevServerRegistrationOptions {\n cliConfig: CliConfig\n /**\n * Extract the project manifest to inline into the registry. The caller owns the\n * studio-vs-app split (manifest formats are CLI-domain); registration re-derives\n * the interface set alongside it.\n */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n isApp: boolean\n output: Output\n server: ViteDevServer\n workDir: string\n\n /**\n * Rebuild the app's federation remote when its interface set changes, awaited\n * *before* the registry patch — the patch reloads the workbench page, which must\n * re-fetch a remote that already exposes the new interface. Resolves with the\n * recreated server so the entry gets its actual address (non-strict ports may\n * shift it); must reject if the restart produces no server, so the set stays\n * uncommitted and the next save retries instead of advertising a dead port.\n */\n onInterfaceSetChange?: () => Promise<ViteDevServer>\n}\n\ninterface DevServerRegistrationHandle {\n close: () => Promise<void>\n\n /** Where the Dashboard opens this server; unset when it can't open it there. */\n path?: string\n}\n\n/**\n * Log any app validation errors without aborting. Unlike build and deploy, dev\n * stays up on an invalid app so the author sees the errors and fixes them live on\n * the next save. A config is not an app — it isn't validated by the app schema\n * (which would spuriously demand a slug/title), so skip it here.\n */\nfunction reportConfigErrors(app: CliConfig['app'], output: Output): void {\n if (isWorkbenchConfig(app)) return\n const errors = validateWorkbenchApp(app)\n if (errors.length === 0) return\n output.warn(formatWorkbenchAppErrors(errors))\n}\n\n/** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */\nfunction serverAddress(server: ViteDevServer) {\n const resolvedHost = server.config.server.host\n const addr = server.httpServer?.address()\n return {\n host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',\n port: typeof addr === 'object' && addr ? addr.port : server.config.server.port,\n }\n}\n\n/**\n * Register the dev server in the registry and watch its config for manifest +\n * interface changes. The workbench reads the entry to locate and render the\n * server; the watcher keeps it current as `sanity.cli.ts` is edited.\n */\nexport async function startDevServerRegistration(\n options: DevServerRegistrationOptions,\n): Promise<DevServerRegistrationHandle> {\n const {cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir} = options\n\n const {host: appHost, port: appPort} = serverAddress(server)\n\n reportConfigErrors(cliConfig.app, output)\n\n // Forwarded alongside (not inside) the manifest so the workbench renders local\n // panels/workers and reads the configs without a deploy.\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const configs = await deriveConfigs(cliConfig)\n\n const workbenchApp = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const config = resolveWorkbenchConfig(cliConfig)\n // A config runs alongside the app it configures, so give it its own id\n // namespace — sharing the app's slug would make the two indistinguishable here.\n const id = config ? `config:${config.appType}` : workbenchApp?.slug\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them. Name defaults to the\n // slug, mirroring brett.\n const name = workbenchApp?.name ?? workbenchApp?.slug\n const reference =\n workbenchApp && name\n ? // No workbench app is a singleton now that the only one (the Media Library)\n // is a config, not an app — so its reference is always `<org>/<name>`.\n applicationReference({\n isSingleton: false,\n name,\n organizationId: workbenchApp.organizationId,\n })\n : undefined\n\n // Separate namespaces mean a shared id is a genuine duplicate, so the gate is\n // an id match within the org — no config-vs-app role left to reconcile.\n const organizationId = cliConfig.app?.organizationId\n const devServer = id\n ? getRegisteredServers().find(\n (server) => server.id === id && server.organizationId === organizationId,\n )\n : undefined\n\n if (id && devServer) {\n output.error(\n `\"${id}\" is already served by another dev server running on port ${devServer.port}, ` +\n \"so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.\",\n {exit: false},\n )\n return {close: async () => {}}\n }\n\n const registration = registerDevServer({\n configs,\n host: appHost,\n id,\n interfaces,\n name,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n reference,\n slug: workbenchApp?.slug,\n type: isApp ? 'coreApp' : 'studio',\n visibility: workbenchApp ? (workbenchApp.visibility ?? 'default') : undefined,\n workDir,\n })\n\n const exposesSet = trackExposesSet({configs, interfaces})\n\n const watcher = await startDevManifestWatcher({\n // Re-derive every pass (don't omit): the registry patch is a shallow merge,\n // so omitting would wipe the registered set.\n extract: async (params) => {\n const nextConfig = await getCliConfigUncached(params.workDir)\n reportConfigErrors(nextConfig.app, output)\n return {\n configs: await deriveConfigs(nextConfig),\n interfaces: deriveInterfaces(nextConfig.app, {isApp}),\n manifest: await extractManifest({...params, applicationId: id}),\n }\n },\n // A studio's root resolves to `sanity.config.*` but its interfaces live in\n // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.\n extraWatchFilenames: isApp ? undefined : ['sanity.cli.js', 'sanity.cli.ts'],\n output,\n update: async (patch) => {\n if (\n !exposesSet.changed({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n ) {\n registration.update(patch)\n return\n }\n // Rebuild the remote *before* patching the registry — the patch reloads the\n // page, which must re-fetch a remote that already exposes the new interface.\n const rebuiltServer = await onInterfaceSetChange?.()\n // Commit only after a successful rebuild, so a thrown one retries next pass.\n exposesSet.commit({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n // The recreated server can bind a different port (non-strict ports).\n registration.update(rebuiltServer ? {...patch, ...serverAddress(rebuiltServer)} : patch)\n },\n workDir,\n })\n\n return {\n close: async () => {\n registration.release()\n await watcher.close()\n },\n path: dashboardPath({id, interfaces}),\n }\n}\n"],"names":["getCliConfigUncached","applicationReference","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","name","reference","isSingleton","organizationId","devServer","find","error","exit","close","registration","projectId","api","type","visibility","exposesSet","watcher","extract","params","nextConfig","manifest","applicationId","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,oBAAoB,QAAO,gCAA+B;AAClE,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,gCAA+B;AAC5F,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,eAAe,QAAO,oBAAmB;AACjD,SACEC,aAAa,EAEbC,oBAAoB,EACpBC,iBAAiB,QACZ,gBAAe;AACtB,SAAQC,uBAAuB,QAAO,+BAA8B;AAqCpE;;;;;CAKC,G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jC,QAAQQ,YAAY;YAAC;YAAiB;SAAgB;QAC3EzB;QACAmD,QAAQ,OAAOC;YACb,IACE,CAACT,WAAWU,OAAO,CAAC;gBAClB9B,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B,IACA;gBACAgB,aAAaa,MAAM,CAACC;gBACpB;YACF;YACA,4EAA4E;YAC5E,6EAA6E;YAC7E,MAAME,gBAAgB,MAAMpC;YAC5B,6EAA6E;YAC7EyB,WAAWY,MAAM,CAAC;gBAChBhC,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B;YACA,qEAAqE;YACrEgB,aAAaa,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGhD,cAAckD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLkB,OAAO;YACLC,aAAakB,OAAO;YACpB,MAAMZ,QAAQP,KAAK;QACrB;QACAoB,MAAM/D,cAAc;YAACgC;YAAIJ;QAAU;IACrC;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from '../../validateWorkbenchApp.js'\nimport {deriveConfigs} from './deriveConfigs.js'\nimport {trackExposesSet} from './exposesSetId.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n getRegisteredServers,\n localAppIdentity,\n registerDevServer,\n} from './registry.js'\nimport {startDevManifestWatcher} from './startDevManifestWatcher.js'\n\ninterface DevServerRegistrationOptions {\n cliConfig: CliConfig\n /**\n * Extract the project manifest to inline into the registry. The caller owns the\n * studio-vs-app split (manifest formats are CLI-domain); registration re-derives\n * the interface set alongside it.\n */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n isApp: boolean\n output: Output\n server: ViteDevServer\n workDir: string\n\n /**\n * Rebuild the app's federation remote when its interface set changes, awaited\n * *before* the registry patch — the patch reloads the workbench page, which must\n * re-fetch a remote that already exposes the new interface. Resolves with the\n * recreated server so the entry gets its actual address (non-strict ports may\n * shift it); must reject if the restart produces no server, so the set stays\n * uncommitted and the next save retries instead of advertising a dead port.\n */\n onInterfaceSetChange?: () => Promise<ViteDevServer>\n}\n\ninterface DevServerRegistrationHandle {\n close: () => Promise<void>\n\n /** Where the Dashboard opens this server; unset when it can't open it there. */\n path?: string\n}\n\n/**\n * Log any app validation errors without aborting. Unlike build and deploy, dev\n * stays up on an invalid app so the author sees the errors and fixes them live on\n * the next save. A config is not an app — it isn't validated by the app schema\n * (which would spuriously demand a slug/title), so skip it here.\n */\nfunction reportConfigErrors(app: CliConfig['app'], output: Output): void {\n if (isWorkbenchConfig(app)) return\n const errors = validateWorkbenchApp(app)\n if (errors.length === 0) return\n output.warn(formatWorkbenchAppErrors(errors))\n}\n\n/** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */\nfunction serverAddress(server: ViteDevServer) {\n const resolvedHost = server.config.server.host\n const addr = server.httpServer?.address()\n return {\n host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',\n port: typeof addr === 'object' && addr ? addr.port : server.config.server.port,\n }\n}\n\n/**\n * Register the dev server in the registry and watch its config for manifest +\n * interface changes. The workbench reads the entry to locate and render the\n * server; the watcher keeps it current as `sanity.cli.ts` is edited.\n */\nexport async function startDevServerRegistration(\n options: DevServerRegistrationOptions,\n): Promise<DevServerRegistrationHandle> {\n const {cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir} = options\n\n const {host: appHost, port: appPort} = serverAddress(server)\n\n reportConfigErrors(cliConfig.app, output)\n\n // Forwarded alongside (not inside) the manifest so the workbench renders local\n // panels/workers and reads the configs without a deploy.\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const configs = await deriveConfigs(cliConfig)\n\n const workbenchApp = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const config = resolveWorkbenchConfig(cliConfig)\n // A config runs alongside the app it configures, so give it its own id\n // namespace — sharing the app's slug would make the two indistinguishable here.\n const id = config ? `config:${config.appType}` : workbenchApp?.slug\n const applicationId = workbenchApp ? cliConfig.deployment?.appId : undefined\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them.\n const identity = workbenchApp ? localAppIdentity(workbenchApp) : undefined\n\n // The Dashboard tells local apps apart by their bus id and by the application\n // they stand in for.\n const organizationId = cliConfig.app?.organizationId\n const devServer = getRegisteredServers().find(\n (server) =>\n server.organizationId === organizationId &&\n (server.id === id || (applicationId && server.applicationId === applicationId)),\n )\n\n if (id && devServer) {\n const served =\n devServer.id === id\n ? `\"${id}\" is already served`\n : `\"${id}\" is the same application as \"${devServer.id}\", served`\n output.error(\n `${served} by another dev server running on port ${devServer.port}, ` +\n \"so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.\",\n {exit: false},\n )\n return {close: async () => {}}\n }\n\n const registration = registerDevServer({\n applicationId,\n configs,\n host: appHost,\n id,\n interfaces,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n ...identity,\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n\n const exposesSet = trackExposesSet({configs, interfaces})\n\n const watcher = await startDevManifestWatcher({\n // Re-derive every pass (don't omit): the registry patch is a shallow merge,\n // so omitting would wipe the registered set.\n extract: async (params) => {\n const nextConfig = await getCliConfigUncached(params.workDir)\n reportConfigErrors(nextConfig.app, output)\n return {\n configs: await deriveConfigs(nextConfig),\n interfaces: deriveInterfaces(nextConfig.app, {isApp}),\n manifest: await extractManifest({...params, applicationId: id}),\n }\n },\n // A studio's root resolves to `sanity.config.*` but its interfaces live in\n // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.\n extraWatchFilenames: isApp ? undefined : ['sanity.cli.js', 'sanity.cli.ts'],\n output,\n update: async (patch) => {\n if (\n !exposesSet.changed({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n ) {\n registration.update(patch)\n return\n }\n // Rebuild the remote *before* patching the registry — the patch reloads the\n // page, which must re-fetch a remote that already exposes the new interface.\n const rebuiltServer = await onInterfaceSetChange?.()\n // Commit only after a successful rebuild, so a thrown one retries next pass.\n exposesSet.commit({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n // The recreated server can bind a different port (non-strict ports).\n registration.update(rebuiltServer ? {...patch, ...serverAddress(rebuiltServer)} : patch)\n },\n workDir,\n })\n\n return {\n close: async () => {\n registration.release()\n await watcher.close()\n },\n path: dashboardPath({id, interfaces}),\n }\n}\n"],"names":["getCliConfigUncached","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","localAppIdentity","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","applicationId","deployment","appId","identity","organizationId","devServer","find","served","error","exit","close","registration","projectId","api","type","exposesSet","watcher","extract","params","nextConfig","manifest","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,gCAA+B;AAC5F,SAAQC,aAAa,QAAO,qBAA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gBACLuB,SAAS,MAAMhC,cAAcyD;gBAC7B1B,YAAYnC,iBAAiB6D,WAAWjD,GAAG,EAAE;oBAACkB;gBAAK;gBACnDgC,UAAU,MAAMjC,gBAAgB;oBAAC,GAAG+B,MAAM;oBAAElB,eAAeH;gBAAE;YAC/D;QACF;QACA,2EAA2E;QAC3E,wEAAwE;QACxEwB,qBAAqBjC,QAAQQ,YAAY;YAAC;YAAiB;SAAgB;QAC3EzB;QACAmD,QAAQ,OAAOC;YACb,IACE,CAACR,WAAWS,OAAO,CAAC;gBAClB9B,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B,IACA;gBACAkB,aAAaW,MAAM,CAACC;gBACpB;YACF;YACA,4EAA4E;YAC5E,6EAA6E;YAC7E,MAAME,gBAAgB,MAAMpC;YAC5B,6EAA6E;YAC7E0B,WAAWW,MAAM,CAAC;gBAChBhC,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B;YACA,qEAAqE;YACrEkB,aAAaW,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGhD,cAAckD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLoB,OAAO;YACLC,aAAagB,OAAO;YACpB,MAAMX,QAAQN,KAAK;QACrB;QACAkB,MAAMhE,cAAc;YAACiC;YAAIJ;QAAU;IACrC;AACF"}
@@ -16,7 +16,8 @@ const noop = async ()=>{};
16
16
  // Every server is a local app except a config-only one — a config
17
17
  // with no interfaces (the media library). A server with both lands in both channels.
18
18
  const toApplicationsPayload = (servers)=>({
19
- applications: servers.filter((server)=>!isConfigOnlyServer(server)).map(({ host, id, interfaces, manifest, name, organizationId, port, projectId, reference, slug, type, visibility })=>({
19
+ applications: servers.filter((server)=>!isConfigOnlyServer(server)).map(({ applicationId, host, id, interfaces, manifest, name, organizationId, port, projectId, reference, slug, type, visibility })=>({
20
+ applicationId,
20
21
  host,
21
22
  id,
22
23
  // Views cross to the remote keyed on `type`, never the internal `surface`.