@sanity/workbench-cli 2.15.2 → 2.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/_exports/_internal_worker_bus.d.ts +3 -3
  2. package/dist/_exports/_internal_worker_bus.js +1 -1
  3. package/dist/_exports/_internal_worker_bus.js.map +1 -1
  4. package/dist/_exports/build.d.ts +3 -3
  5. package/dist/_exports/{contract-C4Y6gi-b.d.ts → contract-WrU3aOYd.d.ts} +9 -6
  6. package/dist/_exports/deploy.d.ts +3 -3
  7. package/dist/_exports/dev.d.ts +1 -1
  8. package/dist/_exports/index.d.ts +5 -4
  9. package/dist/_exports/index.js +1 -1
  10. package/dist/_exports/index.js.map +1 -1
  11. package/dist/_exports/{resolveWorkbenchConfig-CgKD8AJ7.d.ts → resolveWorkbenchConfig-JRi01VJM.d.ts} +2 -2
  12. package/dist/_exports/{summarizeInterfaces-CeV5Umpj.d.ts → summarizeInterfaces-CpCUSMrz.d.ts} +6 -6
  13. package/dist/_exports/undeploy.d.ts +2 -2
  14. package/dist/_exports/{defineService-DPZwNN6_.d.ts → webWorker-TWUbh0uo.d.ts} +63 -39
  15. package/dist/actions/build/artifact.js +2 -2
  16. package/dist/actions/build/artifact.js.map +1 -1
  17. package/dist/actions/build/render-remote.js +11 -5
  18. package/dist/actions/build/render-remote.js.map +1 -1
  19. package/dist/actions/build/views/artifact.js +7 -5
  20. package/dist/actions/build/views/artifact.js.map +1 -1
  21. package/dist/actions/build/vite/optimize-deps.js +2 -2
  22. package/dist/actions/build/vite/optimize-deps.js.map +1 -1
  23. package/dist/actions/build/vite/plugin.js +2 -2
  24. package/dist/actions/build/vite/plugin.js.map +1 -1
  25. package/dist/actions/build/vite/plugins/plugin-sanity-environment.js +1 -0
  26. package/dist/actions/build/vite/plugins/plugin-sanity-environment.js.map +1 -1
  27. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js +2 -2
  28. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js.map +1 -1
  29. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js +5 -2
  30. package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js.map +1 -1
  31. package/dist/actions/build/{services → webWorkers}/artifact.js +28 -27
  32. package/dist/actions/build/webWorkers/artifact.js.map +1 -0
  33. package/dist/actions/build/{services → webWorkers}/workerBus.js +1 -1
  34. package/dist/actions/build/webWorkers/workerBus.js.map +1 -0
  35. package/dist/actions/deploy/deployWorkbenchApp.js +7 -14
  36. package/dist/actions/deploy/deployWorkbenchApp.js.map +1 -1
  37. package/dist/actions/deploy/getWorkbench.js.map +1 -1
  38. package/dist/actions/deploy/summarizeInterfaces.js +3 -3
  39. package/dist/actions/deploy/summarizeInterfaces.js.map +1 -1
  40. package/dist/actions/dev/appServerSupervisor.js +2 -2
  41. package/dist/actions/dev/appServerSupervisor.js.map +1 -1
  42. package/dist/actions/dev/exposesSetId.js +1 -1
  43. package/dist/actions/dev/exposesSetId.js.map +1 -1
  44. package/dist/actions/dev/registry.js +14 -4
  45. package/dist/actions/dev/registry.js.map +1 -1
  46. package/dist/actions/dev/startWorkbenchDev.js +1 -1
  47. package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
  48. package/dist/contract.js +8 -8
  49. package/dist/contract.js.map +1 -1
  50. package/dist/defineApp.js +2 -2
  51. package/dist/defineApp.js.map +1 -1
  52. package/dist/defineView.js +2 -2
  53. package/dist/defineView.js.map +1 -1
  54. package/dist/deriveInterfaces.js.map +1 -1
  55. package/dist/webWorker.js +20 -0
  56. package/dist/webWorker.js.map +1 -0
  57. package/package.json +11 -11
  58. package/dist/actions/build/services/artifact.js.map +0 -1
  59. package/dist/actions/build/services/workerBus.js.map +0 -1
  60. package/dist/defineService.js +0 -52
  61. package/dist/defineService.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/vite/optimize-deps.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {\n hasMediaLibraryIslandRuntime,\n MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE,\n} from '../configs/mediaLibraryIslandRuntime.js'\n\n/**\n * React APIs only the generated render-contract modules import — the SPA\n * bootstrap (`getEntryModule`) and every render artifact (`renderRemote`)\n * `createRoot` from `react-dom/client` and `createElement` from `react`. No\n * app/interface source imports `react-dom/client` itself, so scanning `entries`\n * never surfaces it; every workbench app depends on react/react-dom, so both\n * always resolve.\n */\nconst RENDER_CONTRACT_DEPS = ['react', 'react-dom/client']\n\n/** Extensions an import-style source path may omit, in resolution order. */\nconst SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs']\n\n/**\n * Resolve an import-style source path to the file on disk. The app `entry`\n * defaults to the extensionless `./src/App` (and a user may omit the extension\n * anywhere), which the runtime imports fine through Vite's resolver — but\n * `optimizeDeps.entries` is matched against the filesystem, so an extensionless\n * path never matches and its deps go unscanned. Try the path as-is, then the\n * common source extensions; fall back to the input so an already-resolved path\n * (or a genuinely missing one) passes through unchanged.\n */\nfunction resolveSourceFile(absPath: string): string {\n if (fs.existsSync(absPath) && fs.statSync(absPath).isFile()) return absPath\n for (const extension of SOURCE_EXTENSIONS) {\n if (fs.existsSync(`${absPath}${extension}`)) return `${absPath}${extension}`\n }\n return absPath\n}\n\n/**\n * Dep pre-bundling inputs for a workbench app's dev server.\n *\n * Vite's dep scanner crawls from the app's HTML entry, which reaches only the\n * app's `entry` (or a studio's config) — never the federation `exposes` (dock\n * views, web workers, media-library config fields), which the host loads\n * dynamically at runtime. So a dep imported only by an exposed module (e.g.\n * `sanity/workbench` in a service or view) escapes the startup scan; Vite\n * discovers it on first request, re-optimizes, and full-page reloads — which\n * flakes Playwright in e2e.\n *\n * Point `entries` at the source of every interface: the app `entry` (or, for a\n * studio, its config), plus each view, service, and installation-config source.\n * `entries` follows real import statements, so it covers whatever those sources\n * transitively use — correct subpaths and all — with no hand-maintained dep\n * list, and never crashes on an unresolvable name the way a bad `include` entry\n * does. Each source is resolved to its on-disk file so an extensionless path\n * (like the default `./src/App`) still matches `entries`' filesystem glob.\n *\n * @param cwd - Project root; `entries` are returned relative to it.\n * @param appSources - Absolute paths to the app's `entry` and/or studio config.\n * @param exposes - The app's declared views/web workers/config.\n * @internal\n */\nexport function workbenchOptimizeDeps(options: {\n appSources: readonly string[]\n cwd: string\n exposes?: WorkbenchExposes\n}): {entries: string[]; include: string[]} {\n const {appSources, cwd, exposes} = options\n\n const interfaceSources = [\n ...(exposes?.views ?? []).map((view) => view.src),\n ...(exposes?.webWorkers ?? []).map((webWorker) => webWorker.src),\n ...(exposes?.config?.fields ?? []).map((field) => field.src),\n ].map((src) => path.resolve(cwd, src))\n\n const entries = [...appSources, ...interfaceSources].map((absPath) => {\n const resolved = resolveSourceFile(absPath)\n return path.relative(cwd, resolved).split(path.sep).join('/')\n })\n\n // The generated `./island-runtime` expose imports this entry, but the file is\n // codegen (never in `entries`), so the startup scan misses it. Only when the\n // installed `sanity` ships the entry — an unresolvable `include` name crashes\n // the dev server, and the expose is skipped in that case anyway.\n const islandRuntimeDeps =\n isMediaLibraryConfigApp(exposes) && hasMediaLibraryIslandRuntime(cwd)\n ? [MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE]\n : []\n\n return {\n entries: [...new Set(entries)],\n include: [...RENDER_CONTRACT_DEPS, ...islandRuntimeDeps],\n }\n}\n"],"names":["fs","path","isMediaLibraryConfigApp","hasMediaLibraryIslandRuntime","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","RENDER_CONTRACT_DEPS","SOURCE_EXTENSIONS","resolveSourceFile","absPath","existsSync","statSync","isFile","extension","workbenchOptimizeDeps","options","appSources","cwd","exposes","interfaceSources","views","map","view","src","webWorkers","webWorker","config","fields","field","resolve","entries","resolved","relative","split","sep","join","islandRuntimeDeps","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KAAK,CAAC/B,KAAKgC,GAAG,EAAEC,IAAI,CAAC;IAC3D;IAEA,8EAA8E;IAC9E,6EAA6E;IAC7E,8EAA8E;IAC9E,iEAAiE;IACjE,MAAMC,oBACJjC,wBAAwBe,YAAYd,6BAA6Ba,OAC7D;QAACZ;KAAoC,GACrC,EAAE;IAER,OAAO;QACLyB,SAAS;eAAI,IAAIO,IAAIP;SAAS;QAC9BQ,SAAS;eAAIhC;eAAyB8B;SAAkB;IAC1D;AACF"}
1
+ {"version":3,"sources":["../../../../src/actions/build/vite/optimize-deps.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {\n hasMediaLibraryIslandRuntime,\n MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE,\n} from '../configs/mediaLibraryIslandRuntime.js'\n\n/**\n * React APIs only the generated render-contract modules import — the SPA\n * bootstrap (`getEntryModule`) and every render artifact (`renderRemote`)\n * `createRoot` from `react-dom/client` and `createElement` from `react`. No\n * app/interface source imports `react-dom/client` itself, so scanning `entries`\n * never surfaces it; every workbench app depends on react/react-dom, so both\n * always resolve.\n */\nconst RENDER_CONTRACT_DEPS = ['react', 'react-dom/client']\n\n/** Extensions an import-style source path may omit, in resolution order. */\nconst SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs']\n\n/**\n * Resolve an import-style source path to the file on disk. The app `entry`\n * defaults to the extensionless `./src/App` (and a user may omit the extension\n * anywhere), which the runtime imports fine through Vite's resolver — but\n * `optimizeDeps.entries` is matched against the filesystem, so an extensionless\n * path never matches and its deps go unscanned. Try the path as-is, then the\n * common source extensions; fall back to the input so an already-resolved path\n * (or a genuinely missing one) passes through unchanged.\n */\nfunction resolveSourceFile(absPath: string): string {\n if (fs.existsSync(absPath) && fs.statSync(absPath).isFile()) return absPath\n for (const extension of SOURCE_EXTENSIONS) {\n if (fs.existsSync(`${absPath}${extension}`)) return `${absPath}${extension}`\n }\n return absPath\n}\n\n/**\n * Dep pre-bundling inputs for a workbench app's dev server.\n *\n * Vite's dep scanner crawls from the app's HTML entry, which reaches only the\n * app's `entry` (or a studio's config) — never the federation `exposes` (dock\n * views, web workers, media-library config fields), which the host loads\n * dynamically at runtime. So a dep imported only by an exposed module (e.g.\n * `sanity/workbench` in a web worker or view) escapes the startup scan; Vite\n * discovers it on first request, re-optimizes, and full-page reloads — which\n * flakes Playwright in e2e.\n *\n * Point `entries` at the source of every interface: the app `entry` (or, for a\n * studio, its config), plus each view, web worker, and installation-config source.\n * `entries` follows real import statements, so it covers whatever those sources\n * transitively use — correct subpaths and all — with no hand-maintained dep\n * list, and never crashes on an unresolvable name the way a bad `include` entry\n * does. Each source is resolved to its on-disk file so an extensionless path\n * (like the default `./src/App`) still matches `entries`' filesystem glob.\n *\n * @param cwd - Project root; `entries` are returned relative to it.\n * @param appSources - Absolute paths to the app's `entry` and/or studio config.\n * @param exposes - The app's declared views/web workers/config.\n * @internal\n */\nexport function workbenchOptimizeDeps(options: {\n appSources: readonly string[]\n cwd: string\n exposes?: WorkbenchExposes\n}): {entries: string[]; include: string[]} {\n const {appSources, cwd, exposes} = options\n\n const interfaceSources = [\n ...(exposes?.views ?? []).map((view) => view.src),\n ...(exposes?.webWorkers ?? []).map((webWorker) => webWorker.src),\n ...(exposes?.config?.fields ?? []).map((field) => field.src),\n ].map((src) => path.resolve(cwd, src))\n\n const entries = [...appSources, ...interfaceSources].map((absPath) => {\n const resolved = resolveSourceFile(absPath)\n return path.relative(cwd, resolved).split(path.sep).join('/')\n })\n\n // The generated `./island-runtime` expose imports this entry, but the file is\n // codegen (never in `entries`), so the startup scan misses it. Only when the\n // installed `sanity` ships the entry — an unresolvable `include` name crashes\n // the dev server, and the expose is skipped in that case anyway.\n const islandRuntimeDeps =\n isMediaLibraryConfigApp(exposes) && hasMediaLibraryIslandRuntime(cwd)\n ? [MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE]\n : []\n\n return {\n entries: [...new Set(entries)],\n include: [...RENDER_CONTRACT_DEPS, ...islandRuntimeDeps],\n }\n}\n"],"names":["fs","path","isMediaLibraryConfigApp","hasMediaLibraryIslandRuntime","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","RENDER_CONTRACT_DEPS","SOURCE_EXTENSIONS","resolveSourceFile","absPath","existsSync","statSync","isFile","extension","workbenchOptimizeDeps","options","appSources","cwd","exposes","interfaceSources","views","map","view","src","webWorkers","webWorker","config","fields","field","resolve","entries","resolved","relative","split","sep","join","islandRuntimeDeps","Set","include"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAG5B,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SACEC,4BAA4B,EAC5BC,mCAAmC,QAC9B,0CAAyC;AAEhD;;;;;;;CAOC,GACD,MAAMC,uBAAuB;IAAC;IAAS;CAAmB;AAE1D,0EAA0E,GAC1E,MAAMC,oBAAoB;IAAC;IAAQ;IAAO;IAAQ;IAAO;IAAQ;CAAO;AAExE;;;;;;;;CAQC,GACD,SAASC,kBAAkBC,OAAe;IACxC,IAAIR,GAAGS,UAAU,CAACD,YAAYR,GAAGU,QAAQ,CAACF,SAASG,MAAM,IAAI,OAAOH;IACpE,KAAK,MAAMI,aAAaN,kBAAmB;QACzC,IAAIN,GAAGS,UAAU,CAAC,GAAGD,UAAUI,WAAW,GAAG,OAAO,GAAGJ,UAAUI,WAAW;IAC9E;IACA,OAAOJ;AACT;AAEA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,SAASK,sBAAsBC,OAIrC;IACC,MAAM,EAACC,UAAU,EAAEC,GAAG,EAAEC,OAAO,EAAC,GAAGH;IAEnC,MAAMI,mBAAmB;WACpB,AAACD,CAAAA,SAASE,SAAS,EAAE,AAAD,EAAGC,GAAG,CAAC,CAACC,OAASA,KAAKC,GAAG;WAC7C,AAACL,CAAAA,SAASM,cAAc,EAAE,AAAD,EAAGH,GAAG,CAAC,CAACI,YAAcA,UAAUF,GAAG;WAC5D,AAACL,CAAAA,SAASQ,QAAQC,UAAU,EAAE,AAAD,EAAGN,GAAG,CAAC,CAACO,QAAUA,MAAML,GAAG;KAC5D,CAACF,GAAG,CAAC,CAACE,MAAQrB,KAAK2B,OAAO,CAACZ,KAAKM;IAEjC,MAAMO,UAAU;WAAId;WAAeG;KAAiB,CAACE,GAAG,CAAC,CAACZ;QACxD,MAAMsB,WAAWvB,kBAAkBC;QACnC,OAAOP,KAAK8B,QAAQ,CAACf,KAAKc,UAAUE,KAAK,CAAC/B,KAAKgC,GAAG,EAAEC,IAAI,CAAC;IAC3D;IAEA,8EAA8E;IAC9E,6EAA6E;IAC7E,8EAA8E;IAC9E,iEAAiE;IACjE,MAAMC,oBACJjC,wBAAwBe,YAAYd,6BAA6Ba,OAC7D;QAACZ;KAAoC,GACrC,EAAE;IAER,OAAO;QACLyB,SAAS;eAAI,IAAIO,IAAIP;SAAS;QAC9BQ,SAAS;eAAIhC;eAAyB8B;SAAkB;IAC1D;AACF"}
@@ -39,9 +39,9 @@ import { sanityFederationRuntime } from './plugins/plugin-sanity-federation-runt
39
39
  // eslint-disable-next-line no-console -- build-time warning for the app developer
40
40
  console.warn(`The installed sanity version does not ship ${MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE}; ` + 'custom field inputs will not render in the Media Library until sanity is upgraded.');
41
41
  }
42
- // Each view component (`./views/<view>/<component>`) and each service loader
42
+ // Each view component (`./views/<view>/<component>`) and each web worker loader
43
43
  // (`./services/<name>`) is exposed straight to the host, pointing at the file
44
- // the extension-artifacts plugin generates under RUNTIME_DIR. A service's
44
+ // the extension-artifacts plugin generates under RUNTIME_DIR. A web worker's
45
45
  // worker bundle carries no expose — the host reaches it through its loader.
46
46
  const artifacts = workbenchArtifacts(exposes ?? {}, {
47
47
  islandRuntime
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/vite/plugin.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type ModuleFederationOptions} from '@module-federation/vite'\nimport {type PackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {artifactExposes, workbenchArtifacts} from '../artifact.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {\n hasMediaLibraryIslandRuntime,\n MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE,\n} from '../configs/mediaLibraryIslandRuntime.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './constants.js'\nimport {sanityFederationHost} from './plugins/plugin-federation-host.js'\nimport {type FederationOptions, sanityModuleFederation} from './plugins/plugin-module-federation.js'\nimport {type AutoUpdates, sanityAutoUpdates} from './plugins/plugin-sanity-auto-updates.js'\nimport {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n autoUpdates?: AutoUpdates\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // A Media Library config's `./island-runtime` expose re-exports the mount\n // runtime from the app's installed `sanity`; skip it (the host falls back to\n // degraded rendering for custom inputs) when that version predates the entry,\n // since an unresolvable import would fail the whole build.\n const isConfigApp = isMediaLibraryConfigApp(exposes)\n const islandRuntime = isConfigApp && hasMediaLibraryIslandRuntime(workDir)\n if (isConfigApp && !islandRuntime) {\n // eslint-disable-next-line no-console -- build-time warning for the app developer\n console.warn(\n `The installed sanity version does not ship ${MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE}; ` +\n 'custom field inputs will not render in the Media Library until sanity is upgraded.',\n )\n }\n\n // Each view component (`./views/<view>/<component>`) and each service loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A service's\n // worker bundle carries no expose — the host reaches it through its loader.\n const artifacts = workbenchArtifacts(exposes ?? {}, {islandRuntime})\n const artifactModuleExposes = artifactExposes(artifacts, (artifactPath) =>\n resolveEntryPath(`./${RUNTIME_DIR}/${artifactPath}`),\n )\n\n // A dock-only app (`isApp` with no `appEntry`) has no navigable full-page\n // view, so it exposes no `./App` — only its views. Studios and apps with an\n // entry expose `./App` (the generated render entry).\n const exposesApp = !options.isApp || options.appEntry !== undefined\n\n const federationExposes: NonNullable<ModuleFederationOptions['exposes']> = {\n ...(exposesApp ? {'./App': entryPath} : {}),\n ...artifactModuleExposes,\n }\n\n const runtimeOptions: FederationRuntimeOptions = options.isApp\n ? {appEntry: options.appEntry, isApp: true, isBlueprints}\n : {isApp: false, isBlueprints, studioConfigPath: options.studioConfigPath}\n\n // Every federated app and studio also serves itself standalone. Whenever there's\n // an `./App` to mount (never for a dock-only app), build the SPA client\n // environment from the runtime bootstrap cli-build writes.\n const clientInput = exposesApp ? path.join(workDir, '.sanity', 'runtime', 'app.js') : undefined\n\n return [\n sanityEnvironmentPlugin({clientInput, input: entryPath, isBlueprints}),\n sanityFederationRuntime(runtimeOptions),\n sanityExtensionArtifacts({artifacts}),\n sanityModuleFederation({exposes: federationExposes, name}),\n sanityFederationHost(),\n sanityAutoUpdates(options.autoUpdates),\n ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","isMediaLibraryConfigApp","hasMediaLibraryIslandRuntime","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityFederationHost","sanityModuleFederation","sanityAutoUpdates","sanityEnvironmentPlugin","sanityExtensionArtifacts","sanityFederationRuntime","federation","options","exposes","isBlueprints","name","defaultName","pkgJson","workDir","process","cwd","Error","generatedEntry","resolveEntryPath","entry","resolvedPath","resolve","entryPath","isConfigApp","islandRuntime","console","warn","artifacts","artifactModuleExposes","artifactPath","exposesApp","isApp","appEntry","undefined","federationExposes","runtimeOptions","studioConfigPath","clientInput","join","input","autoUpdates"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC,eAAe,EAAEC,kBAAkB,QAAO,iBAAgB;AAClE,SAAQC,uBAAuB,QAAO,0BAAyB;AA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,4EAA4E;IAC5E,MAAM8B,YAAYjC,mBAAmBc,WAAW,CAAC,GAAG;QAACgB;IAAa;IAClE,MAAMI,wBAAwBnC,gBAAgBkC,WAAW,CAACE,eACxDX,iBAAiB,CAAC,EAAE,EAAEnB,YAAY,CAAC,EAAE8B,cAAc;IAGrD,0EAA0E;IAC1E,4EAA4E;IAC5E,qDAAqD;IACrD,MAAMC,aAAa,CAACvB,QAAQwB,KAAK,IAAIxB,QAAQyB,QAAQ,KAAKC;IAE1D,MAAMC,oBAAqE;QACzE,GAAIJ,aAAa;YAAC,SAASR;QAAS,IAAI,CAAC,CAAC;QAC1C,GAAGM,qBAAqB;IAC1B;IAEA,MAAMO,iBAA2C5B,QAAQwB,KAAK,GAC1D;QAACC,UAAUzB,QAAQyB,QAAQ;QAAED,OAAO;QAAMtB;IAAY,IACtD;QAACsB,OAAO;QAAOtB;QAAc2B,kBAAkB7B,QAAQ6B,gBAAgB;IAAA;IAE3E,iFAAiF;IACjF,wEAAwE;IACxE,2DAA2D;IAC3D,MAAMC,cAAcP,aAAatC,KAAK8C,IAAI,CAACzB,SAAS,WAAW,WAAW,YAAYoB;IAEtF,OAAO;QACL9B,wBAAwB;YAACkC;YAAaE,OAAOjB;YAAWb;QAAY;QACpEJ,wBAAwB8B;QACxB/B,yBAAyB;YAACuB;QAAS;QACnC1B,uBAAuB;YAACO,SAAS0B;YAAmBxB;QAAI;QACxDV;QACAE,kBAAkBK,QAAQiC,WAAW;KACtC;AACH,EAAC"}
1
+ {"version":3,"sources":["../../../../src/actions/build/vite/plugin.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type ModuleFederationOptions} from '@module-federation/vite'\nimport {type PackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {artifactExposes, workbenchArtifacts} from '../artifact.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {\n hasMediaLibraryIslandRuntime,\n MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE,\n} from '../configs/mediaLibraryIslandRuntime.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './constants.js'\nimport {sanityFederationHost} from './plugins/plugin-federation-host.js'\nimport {type FederationOptions, sanityModuleFederation} from './plugins/plugin-module-federation.js'\nimport {type AutoUpdates, sanityAutoUpdates} from './plugins/plugin-sanity-auto-updates.js'\nimport {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n autoUpdates?: AutoUpdates\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // A Media Library config's `./island-runtime` expose re-exports the mount\n // runtime from the app's installed `sanity`; skip it (the host falls back to\n // degraded rendering for custom inputs) when that version predates the entry,\n // since an unresolvable import would fail the whole build.\n const isConfigApp = isMediaLibraryConfigApp(exposes)\n const islandRuntime = isConfigApp && hasMediaLibraryIslandRuntime(workDir)\n if (isConfigApp && !islandRuntime) {\n // eslint-disable-next-line no-console -- build-time warning for the app developer\n console.warn(\n `The installed sanity version does not ship ${MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE}; ` +\n 'custom field inputs will not render in the Media Library until sanity is upgraded.',\n )\n }\n\n // Each view component (`./views/<view>/<component>`) and each web worker loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A web worker's\n // worker bundle carries no expose — the host reaches it through its loader.\n const artifacts = workbenchArtifacts(exposes ?? {}, {islandRuntime})\n const artifactModuleExposes = artifactExposes(artifacts, (artifactPath) =>\n resolveEntryPath(`./${RUNTIME_DIR}/${artifactPath}`),\n )\n\n // A dock-only app (`isApp` with no `appEntry`) has no navigable full-page\n // view, so it exposes no `./App` — only its views. Studios and apps with an\n // entry expose `./App` (the generated render entry).\n const exposesApp = !options.isApp || options.appEntry !== undefined\n\n const federationExposes: NonNullable<ModuleFederationOptions['exposes']> = {\n ...(exposesApp ? {'./App': entryPath} : {}),\n ...artifactModuleExposes,\n }\n\n const runtimeOptions: FederationRuntimeOptions = options.isApp\n ? {appEntry: options.appEntry, isApp: true, isBlueprints}\n : {isApp: false, isBlueprints, studioConfigPath: options.studioConfigPath}\n\n // Every federated app and studio also serves itself standalone. Whenever there's\n // an `./App` to mount (never for a dock-only app), build the SPA client\n // environment from the runtime bootstrap cli-build writes.\n const clientInput = exposesApp ? path.join(workDir, '.sanity', 'runtime', 'app.js') : undefined\n\n return [\n sanityEnvironmentPlugin({clientInput, input: entryPath, isBlueprints}),\n sanityFederationRuntime(runtimeOptions),\n sanityExtensionArtifacts({artifacts}),\n sanityModuleFederation({exposes: federationExposes, name}),\n sanityFederationHost(),\n sanityAutoUpdates(options.autoUpdates),\n ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","isMediaLibraryConfigApp","hasMediaLibraryIslandRuntime","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityFederationHost","sanityModuleFederation","sanityAutoUpdates","sanityEnvironmentPlugin","sanityExtensionArtifacts","sanityFederationRuntime","federation","options","exposes","isBlueprints","name","defaultName","pkgJson","workDir","process","cwd","Error","generatedEntry","resolveEntryPath","entry","resolvedPath","resolve","entryPath","isConfigApp","islandRuntime","console","warn","artifacts","artifactModuleExposes","artifactPath","exposesApp","isApp","appEntry","undefined","federationExposes","runtimeOptions","studioConfigPath","clientInput","join","input","autoUpdates"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC,eAAe,EAAEC,kBAAkB,QAAO,iBAAgB;AAClE,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SACEC,4BAA4B,EAC5BC,mCAAmC,QAC9B,0CAAyC;AAChD,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,iBAAgB;AAChE,SAAQC,oBAAoB,QAAO,sCAAqC;AACxE,SAAgCC,sBAAsB,QAAO,wCAAuC;AACpG,SAA0BC,iBAAiB,QAAO,0CAAyC;AAC3F,SAAQC,uBAAuB,QAAO,yCAAwC;AAC9E,SAAQC,wB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AAK,IAAIxB,QAAQyB,QAAQ,KAAKC;IAE1D,MAAMC,oBAAqE;QACzE,GAAIJ,aAAa;YAAC,SAASR;QAAS,IAAI,CAAC,CAAC;QAC1C,GAAGM,qBAAqB;IAC1B;IAEA,MAAMO,iBAA2C5B,QAAQwB,KAAK,GAC1D;QAACC,UAAUzB,QAAQyB,QAAQ;QAAED,OAAO;QAAMtB;IAAY,IACtD;QAACsB,OAAO;QAAOtB;QAAc2B,kBAAkB7B,QAAQ6B,gBAAgB;IAAA;IAE3E,iFAAiF;IACjF,wEAAwE;IACxE,2DAA2D;IAC3D,MAAMC,cAAcP,aAAatC,KAAK8C,IAAI,CAACzB,SAAS,WAAW,WAAW,YAAYoB;IAEtF,OAAO;QACL9B,wBAAwB;YAACkC;YAAaE,OAAOjB;YAAWb;QAAY;QACpEJ,wBAAwB8B;QACxB/B,yBAAyB;YAACuB;QAAS;QACnC1B,uBAAuB;YAACO,SAAS0B;YAAmBxB;QAAI;QACxDV;QACAE,kBAAkBK,QAAQiC,WAAW;KACtC;AACH,EAAC"}
@@ -19,6 +19,7 @@ export function sanityEnvironmentPlugin(options) {
19
19
  // chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.
20
20
  const output = isBlueprints ? resourceBindingsOutput : undefined;
21
21
  return {
22
+ apply: 'build',
22
23
  config () {
23
24
  return {
24
25
  builder: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-environment.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../../resource-bindings.js'\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\n// Keep the resource-bindings module in its own unhashed chunk at the bundle root\n// so Brett can rewrite it at deploy. `@module-federation/vite` preserves user\n// `codeSplitting` groups (clamped below its own), so this survives the federation\n// build. The chunk sizing lives on the group itself (see\n// `resourceBindingsCodeSplittingGroup`), so it only affects the bindings module.\nconst resourceBindingsOutput = {\n chunkFileNames: (chunk: {name: string}) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n}\n\ninterface EnvironmentOptions {\n input: string\n\n /**\n * When set, also build a standalone `client` SPA environment (its own\n * `index.html` + bootstrap) alongside the federation remote, from this entry.\n * Set for every federated app and studio; omitted only for a dock-only app.\n */\n clientInput?: string\n\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\nexport function sanityEnvironmentPlugin(options: EnvironmentOptions): Plugin {\n const {clientInput, input, isBlueprints} = options\n\n // Blueprints only: force the resource-bindings module into its own unhashed\n // chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.\n const output = isBlueprints ? resourceBindingsOutput : undefined\n\n return {\n config() {\n return {\n builder: {\n async buildApp(builder) {\n // Both environments inherit the top-level `build.outDir` (`dist` by\n // default, or the `outputDir` a caller such as Blueprints passes).\n // `emptyOutDir` is false on both and the CLI clears the output dir\n // once up-front, so the SPA and federation outputs coexist without\n // either build wiping the other's files.\n if (clientInput) {\n await builder.build(builder.environments.client)\n }\n await builder.build(builder.environments[FEDERATION_DIR_NAME])\n },\n },\n environments: {\n ...(clientInput\n ? {\n client: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {\n input: {sanity: clientInput},\n output,\n },\n },\n consumer: 'client',\n },\n }\n : {}),\n [FEDERATION_DIR_NAME]: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {input, output},\n },\n consumer: 'client',\n },\n },\n }\n },\n name: 'sanity/environment',\n }\n}\n"],"names":["resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","FEDERATION_DIR_NAME","resourceBindingsOutput","chunkFileNames","chunk","name","codeSplitting","groups","sanityEnvironmentPlugin","options","clientInput","input","isBlueprints","output","undefined","config","builder","buildApp","build","environments","client","assetsDir","copyPublicDir","emptyOutDir","rolldownOptions","sanity","consumer"],"mappings":"AAEA,SACEA,6BAA6B,EAC7BC,kCAAkC,QAC7B,6BAA4B;AACnC,SAAQC,mBAAmB,QAAO,kBAAiB;AAEnD,iFAAiF;AACjF,8EAA8E;AAC9E,kFAAkF;AAClF,yDAAyD;AACzD,iFAAiF;AACjF,MAAMC,yBAAyB;IAC7BC,gBAAgB,CAACC,QACfL,8BAA8BK,MAAMC,IAAI,KAAK;IAC/CC,eAAe;QACbC,QAAQ;YAACP;SAAmC;IAC9C;AACF;AAgBA,OAAO,SAASQ,wBAAwBC,OAA2B;IACjE,MAAM,EAACC,WAAW,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGH;IAE3C,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAMI,SAASD,eAAeV,yBAAyBY;IAEvD,OAAO;QACLC;YACE,OAAO;gBACLC,SAAS;oBACP,MAAMC,UAASD,OAAO;wBACpB,oEAAoE;wBACpE,mEAAmE;wBACnE,mEAAmE;wBACnE,mEAAmE;wBACnE,yCAAyC;wBACzC,IAAIN,aAAa;4BACf,MAAMM,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAACC,MAAM;wBACjD;wBACA,MAAMJ,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAAClB,oBAAoB;oBAC/D;gBACF;gBACAkB,cAAc;oBACZ,GAAIT,cACA;wBACEU,QAAQ;4BACNF,OAAO;gCACLG,WAAW;gCACXC,eAAe;gCACfC,aAAa;gCACbC,iBAAiB;oCACfb,OAAO;wCAACc,QAAQf;oCAAW;oCAC3BG;gCACF;4BACF;4BACAa,UAAU;wBACZ;oBACF,IACA,CAAC,CAAC;oBACN,CAACzB,oBAAoB,EAAE;wBACrBiB,OAAO;4BACLG,WAAW;4BACXC,eAAe;4BACfC,aAAa;4BACbC,iBAAiB;gCAACb;gCAAOE;4BAAM;wBACjC;wBACAa,UAAU;oBACZ;gBACF;YACF;QACF;QACArB,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-environment.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\nimport {\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../../resource-bindings.js'\nimport {FEDERATION_DIR_NAME} from '../constants.js'\n\n// Keep the resource-bindings module in its own unhashed chunk at the bundle root\n// so Brett can rewrite it at deploy. `@module-federation/vite` preserves user\n// `codeSplitting` groups (clamped below its own), so this survives the federation\n// build. The chunk sizing lives on the group itself (see\n// `resourceBindingsCodeSplittingGroup`), so it only affects the bindings module.\nconst resourceBindingsOutput = {\n chunkFileNames: (chunk: {name: string}) =>\n resourceBindingsChunkFileName(chunk.name) ?? 'static/[name]-[hash].js',\n codeSplitting: {\n groups: [resourceBindingsCodeSplittingGroup],\n },\n}\n\ninterface EnvironmentOptions {\n input: string\n\n /**\n * When set, also build a standalone `client` SPA environment (its own\n * `index.html` + bootstrap) alongside the federation remote, from this entry.\n * Set for every federated app and studio; omitted only for a dock-only app.\n */\n clientInput?: string\n\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\nexport function sanityEnvironmentPlugin(options: EnvironmentOptions): Plugin {\n const {clientInput, input, isBlueprints} = options\n\n // Blueprints only: force the resource-bindings module into its own unhashed\n // chunk so Brett can rewrite it at deploy. Off Blueprints, no such chunk.\n const output = isBlueprints ? resourceBindingsOutput : undefined\n\n return {\n apply: 'build',\n config() {\n return {\n builder: {\n async buildApp(builder) {\n // Both environments inherit the top-level `build.outDir` (`dist` by\n // default, or the `outputDir` a caller such as Blueprints passes).\n // `emptyOutDir` is false on both and the CLI clears the output dir\n // once up-front, so the SPA and federation outputs coexist without\n // either build wiping the other's files.\n if (clientInput) {\n await builder.build(builder.environments.client)\n }\n await builder.build(builder.environments[FEDERATION_DIR_NAME])\n },\n },\n environments: {\n ...(clientInput\n ? {\n client: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {\n input: {sanity: clientInput},\n output,\n },\n },\n consumer: 'client',\n },\n }\n : {}),\n [FEDERATION_DIR_NAME]: {\n build: {\n assetsDir: 'static',\n copyPublicDir: false,\n emptyOutDir: false,\n rolldownOptions: {input, output},\n },\n consumer: 'client',\n },\n },\n }\n },\n name: 'sanity/environment',\n }\n}\n"],"names":["resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","FEDERATION_DIR_NAME","resourceBindingsOutput","chunkFileNames","chunk","name","codeSplitting","groups","sanityEnvironmentPlugin","options","clientInput","input","isBlueprints","output","undefined","apply","config","builder","buildApp","build","environments","client","assetsDir","copyPublicDir","emptyOutDir","rolldownOptions","sanity","consumer"],"mappings":"AAEA,SACEA,6BAA6B,EAC7BC,kCAAkC,QAC7B,6BAA4B;AACnC,SAAQC,mBAAmB,QAAO,kBAAiB;AAEnD,iFAAiF;AACjF,8EAA8E;AAC9E,kFAAkF;AAClF,yDAAyD;AACzD,iFAAiF;AACjF,MAAMC,yBAAyB;IAC7BC,gBAAgB,CAACC,QACfL,8BAA8BK,MAAMC,IAAI,KAAK;IAC/CC,eAAe;QACbC,QAAQ;YAACP;SAAmC;IAC9C;AACF;AAgBA,OAAO,SAASQ,wBAAwBC,OAA2B;IACjE,MAAM,EAACC,WAAW,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGH;IAE3C,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAMI,SAASD,eAAeV,yBAAyBY;IAEvD,OAAO;QACLC,OAAO;QACPC;YACE,OAAO;gBACLC,SAAS;oBACP,MAAMC,UAASD,OAAO;wBACpB,oEAAoE;wBACpE,mEAAmE;wBACnE,mEAAmE;wBACnE,mEAAmE;wBACnE,yCAAyC;wBACzC,IAAIP,aAAa;4BACf,MAAMO,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAACC,MAAM;wBACjD;wBACA,MAAMJ,QAAQE,KAAK,CAACF,QAAQG,YAAY,CAACnB,oBAAoB;oBAC/D;gBACF;gBACAmB,cAAc;oBACZ,GAAIV,cACA;wBACEW,QAAQ;4BACNF,OAAO;gCACLG,WAAW;gCACXC,eAAe;gCACfC,aAAa;gCACbC,iBAAiB;oCACfd,OAAO;wCAACe,QAAQhB;oCAAW;oCAC3BG;gCACF;4BACF;4BACAc,UAAU;wBACZ;oBACF,IACA,CAAC,CAAC;oBACN,CAAC1B,oBAAoB,EAAE;wBACrBkB,OAAO;4BACLG,WAAW;4BACXC,eAAe;4BACfC,aAAa;4BACbC,iBAAiB;gCAACd;gCAAOE;4BAAM;wBACjC;wBACAc,UAAU;oBACZ;gBACF;YACF;QACF;QACAtB,MAAM;IACR;AACF"}
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { WORKER_BUS_ENTRY } from '../../services/artifact.js';
4
+ import { WORKER_BUS_ENTRY } from '../../webWorkers/artifact.js';
5
5
  import { RUNTIME_DIR } from '../constants.js';
6
6
  import { getFederationApi } from './plugin-module-federation.js';
7
7
  const workerBusPath = fileURLToPath(new URL('../../../../_exports/_internal_worker_bus.js', import.meta.url));
@@ -22,7 +22,7 @@ function writeArtifacts({ artifacts, isolateStyles, root }) {
22
22
  }
23
23
  }
24
24
  /**
25
- * Writes the federation runtime artifacts (view render-contract modules, service
25
+ * Writes the federation runtime artifacts (view render-contract modules, web worker
26
26
  * worker bundles + loaders) into `RUNTIME_DIR`, resolving each artifact's import
27
27
  * paths relative to where it lands on disk. The set is expanded once by
28
28
  * `workbenchArtifacts` and handed in — this plugin only writes it.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-extension-artifacts.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport {type Plugin} from 'vite'\n\nimport {type GeneratedArtifact} from '../../artifact.js'\nimport {WORKER_BUS_ENTRY} from '../../services/artifact.js'\nimport {RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\n\nconst workerBusPath = fileURLToPath(\n new URL('../../../../_exports/_internal_worker_bus.js', import.meta.url),\n)\n\nfunction relativeImport(fromFile: string, toFile: string): string {\n const rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join('/')\n return rel.startsWith('.') ? rel : `./${rel}`\n}\n\nfunction writeArtifacts({\n artifacts,\n isolateStyles,\n root,\n}: {\n artifacts: readonly GeneratedArtifact[]\n isolateStyles: boolean\n root: string\n}): void {\n for (const artifact of artifacts) {\n const artifactPath = path.resolve(root, RUNTIME_DIR, artifact.path)\n fs.mkdirSync(path.dirname(artifactPath), {recursive: true})\n fs.writeFileSync(\n artifactPath,\n artifact.source({\n isolateStyles,\n resolveImport: (src) => relativeImport(artifactPath, path.resolve(root, src)),\n }),\n )\n }\n}\n\n/**\n * Writes the federation runtime artifacts (view render-contract modules, service\n * worker bundles + loaders) into `RUNTIME_DIR`, resolving each artifact's import\n * paths relative to where it lands on disk. The set is expanded once by\n * `workbenchArtifacts` and handed in — this plugin only writes it.\n */\nexport function sanityExtensionArtifacts(options: {\n artifacts: readonly GeneratedArtifact[]\n}): Plugin {\n return {\n // The generated worker.js imports the bus client from this package, which\n // the app has no dependency on and so can't resolve by name.\n config: () => ({\n optimizeDeps: {exclude: [WORKER_BUS_ENTRY]},\n resolve: {alias: {[WORKER_BUS_ENTRY]: workerBusPath}},\n }),\n configResolved(config) {\n writeArtifacts({\n artifacts: options.artifacts,\n isolateStyles: getFederationApi(config.plugins)?.isolateStyles ?? false,\n root: config.root,\n })\n },\n name: 'sanity/extension-artifacts',\n }\n}\n"],"names":["fs","path","fileURLToPath","WORKER_BUS_ENTRY","RUNTIME_DIR","getFederationApi","workerBusPath","URL","url","relativeImport","fromFile","toFile","rel","relative","dirname","split","sep","join","startsWith","writeArtifacts","artifacts","isolateStyles","root","artifact","artifactPath","resolve","mkdirSync","recursive","writeFileSync","source","resolveImport","src","sanityExtensionArtifacts","options","config","optimizeDeps","exclude","alias","configResolved","plugins","name"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,SAAQC,aAAa,QAAO,WAAU;AAKtC,SAAQC,gBAAgB,QAAO,6BAA4B;AAC3D,SAAQC,WAAW,QAAO,kBAAiB;AAC3C,SAAQC,gBAAgB,QAAO,gCAA+B;AAE9D,MAAMC,gBAAgBJ,cACpB,IAAIK,IAAI,gDAAgD,YAAYC,GAAG;AAGzE,SAASC,eAAeC,QAAgB,EAAEC,MAAc;IACtD,MAAMC,MAAMX,KAAKY,QAAQ,CAACZ,KAAKa,OAAO,CAACJ,WAAWC,QAAQI,KAAK,CAACd,KAAKe,GAAG,EAAEC,IAAI,CAAC;IAC/E,OAAOL,IAAIM,UAAU,CAAC,OAAON,MAAM,CAAC,EAAE,EAAEA,KAAK;AAC/C;AAEA,SAASO,eAAe,EACtBC,SAAS,EACTC,aAAa,EACbC,IAAI,EAKL;IACC,KAAK,MAAMC,YAAYH,UAAW;QAChC,MAAMI,eAAevB,KAAKwB,OAAO,CAACH,MAAMlB,aAAamB,SAAStB,IAAI;QAClED,GAAG0B,SAAS,CAACzB,KAAKa,OAAO,CAACU,eAAe;YAACG,WAAW;QAAI;QACzD3B,GAAG4B,aAAa,CACdJ,cACAD,SAASM,MAAM,CAAC;YACdR;YACAS,eAAe,CAACC,MAAQtB,eAAee,cAAcvB,KAAKwB,OAAO,CAACH,MAAMS;QAC1E;IAEJ;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASC,yBAAyBC,OAExC;IACC,OAAO;QACL,0EAA0E;QAC1E,6DAA6D;QAC7DC,QAAQ,IAAO,CAAA;gBACbC,cAAc;oBAACC,SAAS;wBAACjC;qBAAiB;gBAAA;gBAC1CsB,SAAS;oBAACY,OAAO;wBAAC,CAAClC,iBAAiB,EAAEG;oBAAa;gBAAC;YACtD,CAAA;QACAgC,gBAAeJ,MAAM;YACnBf,eAAe;gBACbC,WAAWa,QAAQb,SAAS;gBAC5BC,eAAehB,iBAAiB6B,OAAOK,OAAO,GAAGlB,iBAAiB;gBAClEC,MAAMY,OAAOZ,IAAI;YACnB;QACF;QACAkB,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-sanity-extension-artifacts.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport {type Plugin} from 'vite'\n\nimport {type GeneratedArtifact} from '../../artifact.js'\nimport {WORKER_BUS_ENTRY} from '../../webWorkers/artifact.js'\nimport {RUNTIME_DIR} from '../constants.js'\nimport {getFederationApi} from './plugin-module-federation.js'\n\nconst workerBusPath = fileURLToPath(\n new URL('../../../../_exports/_internal_worker_bus.js', import.meta.url),\n)\n\nfunction relativeImport(fromFile: string, toFile: string): string {\n const rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join('/')\n return rel.startsWith('.') ? rel : `./${rel}`\n}\n\nfunction writeArtifacts({\n artifacts,\n isolateStyles,\n root,\n}: {\n artifacts: readonly GeneratedArtifact[]\n isolateStyles: boolean\n root: string\n}): void {\n for (const artifact of artifacts) {\n const artifactPath = path.resolve(root, RUNTIME_DIR, artifact.path)\n fs.mkdirSync(path.dirname(artifactPath), {recursive: true})\n fs.writeFileSync(\n artifactPath,\n artifact.source({\n isolateStyles,\n resolveImport: (src) => relativeImport(artifactPath, path.resolve(root, src)),\n }),\n )\n }\n}\n\n/**\n * Writes the federation runtime artifacts (view render-contract modules, web worker\n * worker bundles + loaders) into `RUNTIME_DIR`, resolving each artifact's import\n * paths relative to where it lands on disk. The set is expanded once by\n * `workbenchArtifacts` and handed in — this plugin only writes it.\n */\nexport function sanityExtensionArtifacts(options: {\n artifacts: readonly GeneratedArtifact[]\n}): Plugin {\n return {\n // The generated worker.js imports the bus client from this package, which\n // the app has no dependency on and so can't resolve by name.\n config: () => ({\n optimizeDeps: {exclude: [WORKER_BUS_ENTRY]},\n resolve: {alias: {[WORKER_BUS_ENTRY]: workerBusPath}},\n }),\n configResolved(config) {\n writeArtifacts({\n artifacts: options.artifacts,\n isolateStyles: getFederationApi(config.plugins)?.isolateStyles ?? false,\n root: config.root,\n })\n },\n name: 'sanity/extension-artifacts',\n }\n}\n"],"names":["fs","path","fileURLToPath","WORKER_BUS_ENTRY","RUNTIME_DIR","getFederationApi","workerBusPath","URL","url","relativeImport","fromFile","toFile","rel","relative","dirname","split","sep","join","startsWith","writeArtifacts","artifacts","isolateStyles","root","artifact","artifactPath","resolve","mkdirSync","recursive","writeFileSync","source","resolveImport","src","sanityExtensionArtifacts","options","config","optimizeDeps","exclude","alias","configResolved","plugins","name"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,SAAQC,aAAa,QAAO,WAAU;AAKtC,SAAQC,gBAAgB,QAAO,+BAA8B;AAC7D,SAAQC,WAAW,QAAO,kBAAiB;AAC3C,SAAQC,gBAAgB,QAAO,gCAA+B;AAE9D,MAAMC,gBAAgBJ,cACpB,IAAIK,IAAI,gDAAgD,YAAYC,GAAG;AAGzE,SAASC,eAAeC,QAAgB,EAAEC,MAAc;IACtD,MAAMC,MAAMX,KAAKY,QAAQ,CAACZ,KAAKa,OAAO,CAACJ,WAAWC,QAAQI,KAAK,CAACd,KAAKe,GAAG,EAAEC,IAAI,CAAC;IAC/E,OAAOL,IAAIM,UAAU,CAAC,OAAON,MAAM,CAAC,EAAE,EAAEA,KAAK;AAC/C;AAEA,SAASO,eAAe,EACtBC,SAAS,EACTC,aAAa,EACbC,IAAI,EAKL;IACC,KAAK,MAAMC,YAAYH,UAAW;QAChC,MAAMI,eAAevB,KAAKwB,OAAO,CAACH,MAAMlB,aAAamB,SAAStB,IAAI;QAClED,GAAG0B,SAAS,CAACzB,KAAKa,OAAO,CAACU,eAAe;YAACG,WAAW;QAAI;QACzD3B,GAAG4B,aAAa,CACdJ,cACAD,SAASM,MAAM,CAAC;YACdR;YACAS,eAAe,CAACC,MAAQtB,eAAee,cAAcvB,KAAKwB,OAAO,CAACH,MAAMS;QAC1E;IAEJ;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASC,yBAAyBC,OAExC;IACC,OAAO;QACL,0EAA0E;QAC1E,6DAA6D;QAC7DC,QAAQ,IAAO,CAAA;gBACbC,cAAc;oBAACC,SAAS;wBAACjC;qBAAiB;gBAAA;gBAC1CsB,SAAS;oBAACY,OAAO;wBAAC,CAAClC,iBAAiB,EAAEG;oBAAa;gBAAC;YACtD,CAAA;QACAgC,gBAAeJ,MAAM;YACnBf,eAAe;gBACbC,WAAWa,QAAQb,SAAS;gBAC5BC,eAAehB,iBAAiB6B,OAAOK,OAAO,GAAGlB,iBAAiB;gBAClEC,MAAMY,OAAOZ,IAAI;YACnB;QACF;QACAkB,MAAM;IACR;AACF"}
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { WINDOW_CONTRACT_VERSION } from '../../../../contract.js';
3
4
  import { renderRemote } from '../../render-remote.js';
4
5
  import { RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE } from '../../resource-bindings.js';
5
6
  import { FEDERATION_FILE_NAME, RUNTIME_DIR } from '../constants.js';
@@ -15,13 +16,15 @@ const studioEntry = (isolateStyles)=>renderRemote({
15
16
  isolateStyles,
16
17
  preamble: `%RESOURCE_BINDINGS_IMPORT%import { Studio } from 'sanity'
17
18
  import { studioProps } from '${AUTO_UPDATES_ID}'
18
- import config from %STUDIO_CONFIG%`
19
+ import config from %STUDIO_CONFIG%`,
20
+ version: String(WINDOW_CONTRACT_VERSION)
19
21
  });
20
22
  // An SDK app's default export is the component; it Fast-Refreshes through its
21
23
  // own dev server, so the wrapper needs no HMR boundary.
22
24
  const appEntry = (isolateStyles)=>renderRemote({
23
25
  isolateStyles,
24
- preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`
26
+ preamble: `%RESOURCE_BINDINGS_IMPORT%import App from %APP_ENTRY%`,
27
+ version: String(WINDOW_CONTRACT_VERSION)
25
28
  });
26
29
  // A branded app that declares no `entry` (e.g. a dock-only panel/worker app)
27
30
  // has no navigable full-page view, so there's no `App` to import. The runtime
@@ -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'\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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;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 {WINDOW_CONTRACT_VERSION} from '../../../../contract.js'\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 version: String(WINDOW_CONTRACT_VERSION),\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 version: String(WINDOW_CONTRACT_VERSION),\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","WINDOW_CONTRACT_VERSION","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","version","String","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,uBAAuB,QAAO,0BAAyB;AAC/D,SAAQC,YAAY,QAAO,yBAAwB;AACnD,SACEC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,QAC1B,6BAA4B;AACnC,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,MAAMW,IAAI,CAACF;YACpD;QACF;QACAhB,MAAM;IACR;AACF"}
@@ -1,57 +1,57 @@
1
- import { SERVICE_CONTRACT_VERSION } from '../../../contract.js';
1
+ import { WEB_WORKER_CONTRACT_VERSION } from '../../../contract.js';
2
2
  /** The worker bus client the generated `worker.js` imports; see the extension-artifacts plugin's alias. */ export const WORKER_BUS_ENTRY = '@sanity/workbench-cli/_internal_worker_bus';
3
- /** Subdirectory under the federation runtime dir where service artifacts live. */ const SERVICES_DIR_NAME = 'services';
4
- const SERVICE_TYPES = [
3
+ /** Subdirectory under the federation runtime dir for web worker artifacts; hosts load them as `services/<name>`. */ const WEB_WORKERS_DIR_NAME = 'services';
4
+ const WEB_WORKER_TYPES = [
5
5
  'worker'
6
6
  ];
7
7
  /**
8
- * Expand each service into its two generated artifacts: a self-contained worker
8
+ * Expand each web worker into its two generated artifacts: a self-contained worker
9
9
  * bundle (imports the user's `src`, runs the callback) and a loader module the
10
10
  * host loads to read the worker's URL. Only the loader is a federation expose —
11
11
  * the host reaches the worker bundle through it, never directly.
12
- */ export function serviceArtifacts(services) {
13
- return services.filter((service)=>SERVICE_TYPES.includes(service.type)).flatMap((service)=>{
14
- const dir = `${SERVICES_DIR_NAME}/${service.name}`;
12
+ */ export function webWorkerArtifacts(workers) {
13
+ return workers.filter((worker)=>WEB_WORKER_TYPES.includes(worker.type)).flatMap((worker)=>{
14
+ const dir = `${WEB_WORKERS_DIR_NAME}/${worker.name}`;
15
15
  return [
16
16
  {
17
17
  path: `${dir}/worker.js`,
18
- source: ({ resolveImport })=>serviceWorkerArtifactSource({
19
- importPath: resolveImport(service.src),
20
- service
18
+ source: ({ resolveImport })=>webWorkerArtifactSource({
19
+ importPath: resolveImport(worker.src),
20
+ worker
21
21
  })
22
22
  },
23
23
  {
24
24
  expose: `./${dir}`,
25
25
  path: `${dir}/index.js`,
26
- source: ()=>serviceLoaderArtifactSource({
27
- service
26
+ source: ()=>webWorkerLoaderArtifactSource({
27
+ worker
28
28
  })
29
29
  }
30
30
  ];
31
31
  });
32
32
  }
33
33
  /**
34
- * Source for one service's **worker** bundle — the Web Worker entry. Imports
35
- * the user's `unstable_defineService` result and runs its callback with the
36
- * service's own declaration (mirroring how a view component receives its
34
+ * Source for one web worker's **worker** bundle — the Web Worker entry. Imports
35
+ * the user's worker function or `unstable_defineService` result and runs it with the
36
+ * web worker's own declaration (mirroring how a view component receives its
37
37
  * `view`) and a message bus client (`workerBus.ts`), then wires the returned
38
38
  * disposer to the host's terminate message.
39
39
  * Crashes — and the worker's `console.*`, which is patched to forward to the
40
40
  * host — are surfaced through the host logger (the host owns logging; a worker's
41
41
  * own console isn't visible in the page DevTools anyway).
42
- */ function serviceWorkerArtifactSource(input) {
42
+ */ function webWorkerArtifactSource(input) {
43
43
  return `\
44
44
  // This file is auto-generated on 'sanity build' / 'sanity dev'
45
45
  // Modifications to this file are automatically discarded
46
- import service from ${JSON.stringify(input.importPath)}
46
+ import worker from ${JSON.stringify(input.importPath)}
47
47
  import { createWorkerBus } from ${JSON.stringify(WORKER_BUS_ENTRY)}
48
48
 
49
- const SERVICE = { type: ${JSON.stringify(input.service.type)}, name: ${JSON.stringify(input.service.name)} }
49
+ const WORKER = { type: ${JSON.stringify(input.worker.type)}, name: ${JSON.stringify(input.worker.name)} }
50
50
 
51
51
  // Bridge the worker's console to the host. A worker's own console isn't visible
52
52
  // in the page DevTools, so patch console.* to forward each call as a message
53
53
  // the host re-emits through the workbench logger — any console.log in the
54
- // service (or its deps) just shows up in the page console.
54
+ // worker (or its deps) just shows up in the page console.
55
55
  const __format = (arg) => {
56
56
  if (typeof arg === 'string') return arg
57
57
  try { return JSON.stringify(arg) } catch (_) { return String(arg) }
@@ -70,7 +70,8 @@ const { bus, close: closeBus, receive: receiveBus } = createWorkerBus()
70
70
 
71
71
  let dispose
72
72
  try {
73
- const result = service.run({ bus, service: SERVICE })
73
+ // Backwards compatibility: an \`unstable_defineService\` result passes the worker as \`service\`. Remove in SDK-3210.
74
+ const result = worker.run ? worker.run({ bus, service: WORKER }) : worker({ bus, worker: WORKER })
74
75
  if (typeof result === 'function') dispose = result
75
76
  } catch (error) {
76
77
  self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(error) } })
@@ -101,8 +102,8 @@ self.addEventListener('unhandledrejection', (event) => {
101
102
  `;
102
103
  }
103
104
  /**
104
- * Source for one service's **loader** — the module-federation expose. Hands the
105
- * host the worker bundle's URL (via Vite `?worker&url`) plus the service's
105
+ * Source for one web worker's **loader** — the module-federation expose. Hands the
106
+ * host the worker bundle's URL (via Vite `?worker&url`) plus the web worker's
106
107
  * type/version.
107
108
  *
108
109
  * A URL (not an inlined worker) on purpose: the host can't `new Worker()` it
@@ -114,7 +115,7 @@ self.addEventListener('unhandledrejection', (event) => {
114
115
  * No HMR boundary: a worker lives in its own `?worker&url` module graph with no
115
116
  * accepting importer, so Vite full-reloads the page on a `src` edit (which
116
117
  * re-loads the worker with the new code) — in-place worker HMR isn't possible.
117
- */ function serviceLoaderArtifactSource(input) {
118
+ */ function webWorkerLoaderArtifactSource(input) {
118
119
  return `\
119
120
  // This file is auto-generated on 'sanity build' / 'sanity dev'
120
121
  // Modifications to this file are automatically discarded
@@ -122,10 +123,10 @@ import workerUrl from './worker.js?worker&url'
122
123
 
123
124
  /** URL of the worker bundle, on the app's origin. */
124
125
  export const url = workerUrl
125
- /** Service type and contract version, surfaced for the host to dispatch on. */
126
- export const type = ${JSON.stringify(input.service.type)}
127
- export const name = ${JSON.stringify(input.service.name)}
128
- export const version = ${SERVICE_CONTRACT_VERSION}
126
+ /** Web worker type and contract version, surfaced for the host to dispatch on. */
127
+ export const type = ${JSON.stringify(input.worker.type)}
128
+ export const name = ${JSON.stringify(input.worker.name)}
129
+ export const version = ${WEB_WORKER_CONTRACT_VERSION}
129
130
  `;
130
131
  }
131
132
 
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/actions/build/webWorkers/artifact.ts"],"sourcesContent":["import {WEB_WORKER_CONTRACT_VERSION, type WebWorkerType} from '../../../contract.js'\nimport {type GeneratedArtifact} from '../artifact.js'\n\n/** The worker bus client the generated `worker.js` imports; see the extension-artifacts plugin's alias. */\nexport const WORKER_BUS_ENTRY = '@sanity/workbench-cli/_internal_worker_bus'\n\n/** Subdirectory under the federation runtime dir for web worker artifacts; hosts load them as `services/<name>`. */\nconst WEB_WORKERS_DIR_NAME = 'services'\n\nconst WEB_WORKER_TYPES: readonly WebWorkerType[] = ['worker']\n\n/**\n * A web worker to generate artifacts for. The `src` file default-exports\n * a worker function or an `unstable_defineService(...)` result; the build emits\n * a self-contained Web Worker bundle plus a loader module that hands the host its URL.\n * @internal\n */\nexport interface WebWorkerArtifact {\n /** Web worker name, unique within the app. */\n name: string\n /** Path to the web worker `src` file, relative to the app root (or absolute). */\n src: string\n /** Web worker type, e.g. `\"worker\"`. */\n type: string\n}\n\n/**\n * Expand each web worker into its two generated artifacts: a self-contained worker\n * bundle (imports the user's `src`, runs the callback) and a loader module the\n * host loads to read the worker's URL. Only the loader is a federation expose —\n * the host reaches the worker bundle through it, never directly.\n */\nexport function webWorkerArtifacts(workers: readonly WebWorkerArtifact[]): GeneratedArtifact[] {\n return workers\n .filter((worker) => (WEB_WORKER_TYPES as readonly string[]).includes(worker.type))\n .flatMap((worker): GeneratedArtifact[] => {\n const dir = `${WEB_WORKERS_DIR_NAME}/${worker.name}`\n return [\n {\n path: `${dir}/worker.js`,\n source: ({resolveImport}) =>\n webWorkerArtifactSource({\n importPath: resolveImport(worker.src),\n worker,\n }),\n },\n {\n expose: `./${dir}`,\n path: `${dir}/index.js`,\n source: () => webWorkerLoaderArtifactSource({worker}),\n },\n ]\n })\n}\n\n/**\n * Source for one web worker's **worker** bundle — the Web Worker entry. Imports\n * the user's worker function or `unstable_defineService` result and runs it with the\n * web worker's own declaration (mirroring how a view component receives its\n * `view`) and a message bus client (`workerBus.ts`), then wires the returned\n * disposer to the host's terminate message.\n * Crashes — and the worker's `console.*`, which is patched to forward to the\n * host — are surfaced through the host logger (the host owns logging; a worker's\n * own console isn't visible in the page DevTools anyway).\n */\nfunction webWorkerArtifactSource(input: {\n importPath: string\n worker: {name: string; type: string}\n}): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport worker from ${JSON.stringify(input.importPath)}\nimport { createWorkerBus } from ${JSON.stringify(WORKER_BUS_ENTRY)}\n\nconst WORKER = { type: ${JSON.stringify(input.worker.type)}, name: ${JSON.stringify(input.worker.name)} }\n\n// Bridge the worker's console to the host. A worker's own console isn't visible\n// in the page DevTools, so patch console.* to forward each call as a message\n// the host re-emits through the workbench logger — any console.log in the\n// worker (or its deps) just shows up in the page console.\nconst __format = (arg) => {\n if (typeof arg === 'string') return arg\n try { return JSON.stringify(arg) } catch (_) { return String(arg) }\n}\nfor (const __level of ['log', 'info', 'warn', 'error', 'debug']) {\n const __native = typeof console[__level] === 'function' ? console[__level].bind(console) : () => {}\n console[__level] = (...args) => {\n __native(...args)\n try {\n self.postMessage({ kind: 'workbench.worker.log', payload: { level: __level, message: args.map(__format).join(' ') } })\n } catch (_) {}\n }\n}\n\nconst { bus, close: closeBus, receive: receiveBus } = createWorkerBus()\n\nlet dispose\ntry {\n // Backwards compatibility: an \\`unstable_defineService\\` result passes the worker as \\`service\\`. Remove in SDK-3210.\n const result = worker.run ? worker.run({ bus, service: WORKER }) : worker({ bus, worker: WORKER })\n if (typeof result === 'function') dispose = result\n} catch (error) {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(error) } })\n}\n\nself.addEventListener('message', (event) => {\n if (!event.data) return\n if (event.data.kind === 'workbench.worker.terminate') {\n // Close the bus first: the host has disconnected, so the disposer's bus calls must fail at once.\n closeBus()\n try { dispose && dispose() } finally { self.close() }\n } else {\n receiveBus(event.data)\n }\n})\n\nself.addEventListener('error', (event) => {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(event.message || event) } })\n})\n\n// An async run callback (or async work it kicks off) rejects without hitting\n// the synchronous try/catch above; module workers surface that as\n// 'unhandledrejection' on self, not 'error'. Forward it so the crash reaches\n// the host either way.\nself.addEventListener('unhandledrejection', (event) => {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(event.reason) } })\n})\n`\n}\n\n/**\n * Source for one web worker's **loader** — the module-federation expose. Hands the\n * host the worker bundle's URL (via Vite `?worker&url`) plus the web worker's\n * type/version.\n *\n * A URL (not an inlined worker) on purpose: the host can't `new Worker()` it\n * directly — cross-origin in dev/prod, and `?worker&inline` only self-contains\n * the worker in a build, not under `sanity dev`. Instead the host bootstraps a\n * same-origin worker that dynamically `import()`s this URL, so the worker\n * resolves its own imports against the app origin. Works in dev and build alike.\n *\n * No HMR boundary: a worker lives in its own `?worker&url` module graph with no\n * accepting importer, so Vite full-reloads the page on a `src` edit (which\n * re-loads the worker with the new code) — in-place worker HMR isn't possible.\n */\nfunction webWorkerLoaderArtifactSource(input: {worker: {name: string; type: string}}): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport workerUrl from './worker.js?worker&url'\n\n/** URL of the worker bundle, on the app's origin. */\nexport const url = workerUrl\n/** Web worker type and contract version, surfaced for the host to dispatch on. */\nexport const type = ${JSON.stringify(input.worker.type)}\nexport const name = ${JSON.stringify(input.worker.name)}\nexport const version = ${WEB_WORKER_CONTRACT_VERSION}\n`\n}\n"],"names":["WEB_WORKER_CONTRACT_VERSION","WORKER_BUS_ENTRY","WEB_WORKERS_DIR_NAME","WEB_WORKER_TYPES","webWorkerArtifacts","workers","filter","worker","includes","type","flatMap","dir","name","path","source","resolveImport","webWorkerArtifactSource","importPath","src","expose","webWorkerLoaderArtifactSource","input","JSON","stringify"],"mappings":"AAAA,SAAQA,2BAA2B,QAA2B,uBAAsB;AAGpF,yGAAyG,GACzG,OAAO,MAAMC,mBAAmB,6CAA4C;AAE5E,kHAAkH,GAClH,MAAMC,uBAAuB;AAE7B,MAAMC,mBAA6C;IAAC;CAAS;AAiB7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generated
1
+ // Runs inside the web worker's Web Worker, bundled by Vite from the generated
2
2
  // `worker.js`. Keep it free of Node and of runtime imports: `@sanity/sdk` is
3
3
  // only ever imported for types.
4
4
  const DEFAULT_TIMEOUT_MS = 5000;
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/actions/build/webWorkers/workerBus.ts"],"sourcesContent":["// Runs inside the web worker's Web Worker, bundled by Vite from the generated\n// `worker.js`. Keep it free of Node and of runtime imports: `@sanity/sdk` is\n// only ever imported for types.\nimport {\n type MessageBusEmitResult,\n type MessageBusErrorCode,\n type MessageBusMessage,\n type MessageBusMeta,\n} from '@sanity/sdk/dashboard'\n\nimport {type WebWorkerBus} from '../../../webWorker.js'\n\nconst DEFAULT_TIMEOUT_MS = 5000\n\ninterface RequestOptions {\n signal?: AbortSignal\n timeout?: number | null\n}\n\ntype Outcome = {error: Error; ok: false} | {ok: true; value: unknown}\n\ntype Answer =\n | {error: {code: 'HANDLER_THREW' | 'REFUSED'; message: string}; ok: false}\n | {ok: true; value: unknown}\n\n// What a host refusal can carry besides its code and message, such as the fix\n// and docs link for one of the Dashboard's coded errors.\ninterface RefusalDetails {\n docsUrl?: string\n fix?: string\n}\n\ntype HostMessage =\n | {\n error: RefusalDetails & {code: MessageBusErrorCode; message: string}\n id: number\n kind: 'workbench.bus.reply'\n ok: false\n }\n | {id: number; kind: 'workbench.bus.reply'; ok: true; value: unknown}\n | {id: number; kind: 'workbench.bus.value'; value: unknown}\n | {\n id: number\n kind: 'workbench.bus.message'\n messageId: number\n meta: MessageBusMeta\n payload: unknown\n type: string\n }\n | {kind: 'workbench.bus.cancel'; messageId: number}\n\n// Mirrors the SDK's MessageBusError: importing the class would pull the SDK\n// runtime into the worker bundle.\nconst busError = (code: MessageBusErrorCode, message?: string, details?: RefusalDetails): Error =>\n Object.assign(new Error(message || code), {\n code,\n docsUrl: details?.docsUrl,\n fix: details?.fix,\n name: 'MessageBusError',\n })\n\n/**\n * The worker's side of the `workbench.bus.*` wire contract. The host relays\n * each request to the Dashboard bus and stamps it with the worker's identity,\n * so the client only tracks ids.\n * @internal\n */\nexport function createWorkerBus(): {\n /**\n * The web worker author's API. The host owns the connection, opening it and ending it when\n * it terminates the worker, so the worker cannot end it.\n */\n bus: WebWorkerBus\n /**\n * The generated entry's terminate hook, not the author's. It sends nothing to\n * the host, which has already disconnected; it only marks the client closed so\n * the disposer's bus calls reject `ABORTED` at once instead of waiting out the\n * local timeout. Hence not `disconnect`.\n */\n close: () => void\n /**\n * The generated `worker.js` is the single `message` listener on `self` and\n * routes every kind (terminate to the disposer, `workbench.bus.*` here), the\n * way the host's `runWorker` routes to its relay.\n */\n receive: (data: unknown) => void\n} {\n const pending = new Map<number, (outcome: Outcome) => void>()\n // The worker can't tell a state topic from an event topic, so it stores every\n // handler alike; the host's `value` or `message` decides how it is called.\n const subscriptions = new Map<number, (value: unknown) => unknown>()\n const inFlight = new Map<number, AbortController>()\n let nextId = 0\n let closed = false\n\n // Posts a request and returns a function that creates its promise on first\n // call. Until then a reply, even an error, is only held: a rejected promise\n // nobody awaits would reach the worker's 'unhandledrejection' forwarder as a crash.\n function request(message: Record<string, unknown>, options: RequestOptions = {}) {\n const {signal, timeout} = options\n const id = ++nextId\n let outcome: Outcome | undefined\n let onOutcome: ((result: Outcome) => void) | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const settle = (result: Outcome) => {\n if (outcome) return\n outcome = result\n clearTimeout(timer)\n pending.delete(id)\n signal?.removeEventListener('abort', onAbort)\n onOutcome?.(result)\n }\n const onAbort = () => {\n self.postMessage({id, kind: 'workbench.bus.abort'})\n settle({error: busError('ABORTED'), ok: false})\n }\n\n if (closed || signal?.aborted) {\n outcome = {error: busError('ABORTED'), ok: false}\n } else {\n // An omitted timeout must stay absent on the wire, so the host applies its default.\n self.postMessage(timeout === undefined ? {...message, id} : {...message, id, timeout})\n pending.set(id, settle)\n // A host that predates the bus never replies; time out here too so the call still settles.\n if (timeout !== null) {\n timer = setTimeout(\n () => settle({error: busError('TIMEOUT'), ok: false}),\n timeout ?? DEFAULT_TIMEOUT_MS,\n )\n }\n signal?.addEventListener('abort', onAbort, {once: true})\n }\n\n let promise: Promise<unknown> | undefined\n return () =>\n (promise ??= new Promise((resolve, reject) => {\n onOutcome = (result) => (result.ok ? resolve(result.value) : reject(result.error))\n if (outcome) onOutcome(outcome)\n }))\n }\n\n // Matches the SDK's `invokeResponder`, so a responder behaves the same in a\n // worker as on the page.\n function respond(\n handler: (message: MessageBusMessage<unknown, unknown, string>) => unknown,\n {messageId, meta, payload, type}: Extract<HostMessage, {kind: 'workbench.bus.message'}>,\n ) {\n const controller = new AbortController()\n inFlight.set(messageId, controller)\n const answer = (result: Answer) => {\n if (inFlight.get(messageId) !== controller) return false\n inFlight.delete(messageId)\n self.postMessage({...result, kind: 'workbench.bus.answer', messageId})\n return true\n }\n const warnIfIgnored = (answered: boolean, action: string) => {\n if (answered) return\n // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger\n console.warn(\n `Message bus ${action} ignored for \"${type}\": no waiting caller or already replied`,\n )\n }\n const fail = () => answer({error: {code: 'HANDLER_THREW', message: 'HANDLER_THREW'}, ok: false})\n\n try {\n const result = handler({\n meta,\n payload,\n reject: (reason) =>\n warnIfIgnored(\n answer({error: {code: 'REFUSED', message: reason ?? 'REFUSED'}, ok: false}),\n 'reject',\n ),\n reply: (value) => warnIfIgnored(answer({ok: true, value}), 'reply'),\n signal: controller.signal,\n type,\n })\n if (result instanceof Promise) result.catch(fail)\n } catch {\n fail()\n }\n }\n\n const bus = {\n emit: (topic: string, payload?: unknown, options?: RequestOptions) => {\n const awaitReply = request({kind: 'workbench.bus.emit', payload, topic}, options)\n const result: MessageBusEmitResult<unknown> = {\n catch: (onRejected) => awaitReply().then(undefined, onRejected),\n finally: (onFinally) => awaitReply().finally(onFinally),\n // eslint-disable-next-line unicorn/no-thenable -- awaiting arms reply failure handling; fire-and-forget does not.\n then: (onFulfilled, onRejected) => awaitReply().then(onFulfilled, onRejected),\n }\n return result\n },\n query: (topic: string, options?: RequestOptions) =>\n request({kind: 'workbench.bus.query', topic}, options)(),\n subscribe: (topic: string, handler: (value: unknown) => unknown, options?: RequestOptions) => {\n if (closed) throw busError('ABORTED')\n const signal = options?.signal\n if (signal?.aborted) return\n const id = ++nextId\n self.postMessage({id, kind: 'workbench.bus.subscribe', topic})\n subscriptions.set(id, handler)\n signal?.addEventListener(\n 'abort',\n () => {\n if (subscriptions.delete(id)) self.postMessage({id, kind: 'workbench.bus.abort'})\n },\n {once: true},\n )\n },\n }\n\n return {\n // The topic generics only exist at the call site; the wire carries plain strings.\n bus: bus as unknown as WebWorkerBus,\n close: () => {\n closed = true\n subscriptions.clear()\n const controllers = [...inFlight.values()]\n inFlight.clear()\n for (const controller of controllers) controller.abort()\n for (const settle of pending.values()) settle({error: busError('ABORTED'), ok: false})\n },\n receive: (data) => {\n const message = data as HostMessage\n switch (message.kind) {\n case 'workbench.bus.cancel': {\n const controller = inFlight.get(message.messageId)\n // Forget it first so an abort listener's reply is ignored.\n inFlight.delete(message.messageId)\n controller?.abort()\n return\n }\n case 'workbench.bus.message': {\n const handler = subscriptions.get(message.id)\n if (handler) respond(handler, message)\n return\n }\n case 'workbench.bus.reply': {\n const settle = pending.get(message.id)\n if (message.ok) {\n settle?.({ok: true, value: message.value})\n return\n }\n // A refused subscription has no promise to reject. The Dashboard prints the refusal.\n subscriptions.delete(message.id)\n settle?.({\n error: busError(message.error.code, message.error.message, message.error),\n ok: false,\n })\n return\n }\n case 'workbench.bus.value': {\n subscriptions.get(message.id)?.(message.value)\n }\n }\n },\n }\n}\n"],"names":["DEFAULT_TIMEOUT_MS","busError","code","message","details","Object","assign","Error","docsUrl","fix","name","createWorkerBus","pending","Map","subscriptions","inFlight","nextId","closed","request","options","signal","timeout","id","outcome","onOutcome","timer","settle","result","clearTimeout","delete","removeEventListener","onAbort","self","postMessage","kind","error","ok","aborted","undefined","set","setTimeout","addEventListener","once","promise","Promise","resolve","reject","value","respond","handler","messageId","meta","payload","type","controller","AbortController","answer","get","warnIfIgnored","answered","action","console","warn","fail","reason","reply","catch","bus","emit","topic","awaitReply","onRejected","then","finally","onFinally","onFulfilled","query","subscribe","close","clear","controllers","values","abort","receive","data"],"mappings":"AAAA,8EAA8E;AAC9E,6EAA6E;AAC7E,gCAAgC;AAUhC,MAAMA,qBAAqB;AAuC3B,4EAA4E;AAC5E,kCAAkC;AAClC,MAAMC,WAAW,CAACC,MAA2BC,SAAkBC,UAC7DC,OAAOC,MAAM,CAAC,IAAIC,MAAMJ,WAAWD,OAAO;QACxCA;QACAM,SAASJ,SAASI;QAClBC,KAAKL,SAASK;QACdC,MAAM;IACR;AAEF;;;;;CAKC,GACD,OAAO,SAASC;IAoBd,MAAMC,UAAU,IAAIC;IACpB,8EAA8E;IAC9E,2EAA2E;IAC3E,MAAMC,gBAAgB,IAAID;IAC1B,MAAME,WAAW,IAAIF;IACrB,IAAIG,SAAS;IACb,IAAIC,SAAS;IAEb,2EAA2E;IAC3E,4EAA4E;IAC5E,oFAAoF;IACpF,SAASC,QAAQf,OAAgC,EAAEgB,UAA0B,CAAC,CAAC;QAC7E,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;QAC1B,MAAMG,KAAK,EAAEN;QACb,IAAIO;QACJ,IAAIC;QACJ,IAAIC;QAEJ,MAAMC,SAAS,CAACC;YACd,IAAIJ,SAAS;YACbA,UAAUI;YACVC,aAAaH;YACbb,QAAQiB,MAAM,CAACP;YACfF,QAAQU,oBAAoB,SAASC;YACrCP,YAAYG;QACd;QACA,MAAMI,UAAU;YACdC,KAAKC,WAAW,CAAC;gBAACX;gBAAIY,MAAM;YAAqB;YACjDR,OAAO;gBAACS,OAAOlC,SAAS;gBAAYmC,IAAI;YAAK;QAC/C;QAEA,IAAInB,UAAUG,QAAQiB,SAAS;YAC7Bd,UAAU;gBAACY,OAAOlC,SAAS;gBAAYmC,IAAI;YAAK;QAClD,OAAO;YACL,oFAAoF;YACpFJ,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;AACF"}
@@ -5,20 +5,16 @@ import { spinner } from '@sanity/cli-core/ux';
5
5
  import { c as createTar } from 'tar';
6
6
  import { deriveInterfaces } from '../../deriveInterfaces.js';
7
7
  import { createApplication, createDeployment, deleteApplication, updateApplication } from '../../services/applications.js';
8
- function toBrettInterface(iface, version) {
8
+ function toBrettInterface(iface) {
9
9
  const { id: _id, src: _src, ...declaration } = iface;
10
- if ('type' in declaration) return {
11
- ...declaration,
12
- version
13
- };
10
+ if ('type' in declaration) return declaration;
14
11
  switch(declaration.surface){
15
12
  case 'asset_source':
16
13
  {
17
14
  const { surface, ...view } = declaration;
18
15
  return {
19
16
  ...view,
20
- type: surface,
21
- version
17
+ type: surface
22
18
  };
23
19
  }
24
20
  case 'panel':
@@ -26,8 +22,7 @@ function toBrettInterface(iface, version) {
26
22
  const { surface, ...view } = declaration;
27
23
  return {
28
24
  ...view,
29
- type: surface,
30
- version
25
+ type: surface
31
26
  };
32
27
  }
33
28
  case 'tile':
@@ -35,8 +30,7 @@ function toBrettInterface(iface, version) {
35
30
  const { surface, ...view } = declaration;
36
31
  return {
37
32
  ...view,
38
- type: surface,
39
- version
33
+ type: surface
40
34
  };
41
35
  }
42
36
  case 'window':
@@ -44,8 +38,7 @@ function toBrettInterface(iface, version) {
44
38
  const { surface, ...view } = declaration;
45
39
  return {
46
40
  ...view,
47
- type: 'app',
48
- version
41
+ type: 'app'
49
42
  };
50
43
  }
51
44
  }
@@ -120,7 +113,7 @@ function toBrettInterface(iface, version) {
120
113
  interfaces: deriveInterfaces(app, {
121
114
  appTitle: title,
122
115
  isApp
123
- }).map((iface)=>toBrettInterface(iface, version)),
116
+ }).map((iface)=>toBrettInterface(iface)),
124
117
  isAutoUpdating,
125
118
  mfManifest,
126
119
  tarball,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {c as createTar} from 'tar'\n\nimport {type DerivedInterface, deriveInterfaces} from '../../deriveInterfaces.js'\nimport {\n type Application,\n type BrettAccess,\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n deleteApplication,\n updateApplication,\n} from '../../services/applications.js'\n\n/**\n * `rollback` undoes the creation, so a later failure leaves no record stranded at the slug.\n * @internal\n */\nexport interface CreatedApplication {\n application: Application\n rollback: () => Promise<void>\n}\n\nfunction toBrettInterface(iface: DerivedInterface, version: string): BrettInterface {\n const {id: _id, src: _src, ...declaration} = iface\n if ('type' in declaration) return {...declaration, version}\n\n switch (declaration.surface) {\n case 'asset_source': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'panel': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'tile': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'window': {\n const {surface, ...view} = declaration\n return {...view, type: 'app', version}\n }\n }\n}\n\n/**\n * Create a coreApp record (no deployment), so the CLI can build with its id\n * before shipping the first deployment. First deploy only.\n * @internal\n */\nexport async function createCoreApp(options: {\n isSingleton?: boolean\n name?: string\n organizationId: string\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating application...').start()\n try {\n const application = await createApplication({...options, type: 'coreApp'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Create a studio record (no deployment).\n * @internal\n */\nexport async function createStudio(options: {\n externalUrl?: string\n name?: string\n organizationId: string\n projectId: string | undefined\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating studio...').start()\n try {\n const application = await createApplication({...options, type: 'studio'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Ship a deployment to an already-created (or `deployment.appId`) application,\n * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when\n * set) from config. The deploy endpoint ignores these, so a redeploy patches\n * them here alongside the new deployment.\n *\n * `onDeployed` fires the instant the deployment is live, before the metadata\n * sync — so a caller can disarm a create-time rollback that must not delete an\n * application once it has an active deployment.\n *\n * `isExternal` skips the tarball: the customer serves the build from the\n * application's registered origin.\n * @internal\n */\nexport async function deployWorkbenchApp(options: {\n access?: readonly BrettAccess[]\n app: CliConfig['app']\n applicationId: string\n icon?: string\n isApp: boolean\n isAutoUpdating: boolean\n isExternal?: boolean\n label?: string\n mfManifest: Record<string, unknown>\n onDeployed?: () => void\n /**\n * The address from config. Only `createApplication` used to send it, so an\n * app with a `deployment.appId` kept whatever slug it was created at.\n */\n slug?: string\n sourceDir: string\n title: string\n version: string\n visibility?: AppVisibility\n workspaces?: readonly BrettWorkspace[]\n}): Promise<void> {\n const {\n access,\n app,\n applicationId,\n icon,\n isApp,\n isAutoUpdating,\n isExternal = false,\n label = 'Deploying...',\n mfManifest,\n onDeployed,\n slug,\n sourceDir,\n title,\n version,\n visibility,\n workspaces,\n } = options\n const tarball = isExternal\n ? undefined\n : createTar({cwd: dirname(sourceDir)}, [basename(sourceDir)]).pipe(createGzip())\n\n const spin = spinner(label).start()\n try {\n await createDeployment({\n access,\n applicationId,\n // Brett assigns the id and resolves modules by `moduleId`, so neither travels.\n interfaces: deriveInterfaces(app, {appTitle: title, isApp}).map((iface) =>\n toBrettInterface(iface, version),\n ),\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n })\n onDeployed?.()\n try {\n await updateApplication(applicationId, {\n title,\n ...(icon ? {icon} : {}),\n ...(slug ? {slug} : {}),\n ...(visibility ? {visibility} : {}),\n })\n } catch (error) {\n throw toSlugRejection(error, slug)\n }\n spin.succeed()\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * The slug is the one synced field the server validates — it must be free\n * within the organization, and a singleton app only accepts its reserved\n * identifiers — so a 4xx on the metadata patch is a rejected rename. Name the\n * slug and the server's reason; anything else propagates untouched.\n */\nfunction toSlugRejection(error: unknown, slug: string | undefined): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (!slug || statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `Slug \"${slug}\" was rejected: ${getErrorMessage(error)}. The deployment is live at the application's previous slug — change \\`app.slug\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n"],"names":["basename","dirname","createGzip","getErrorMessage","spinner","c","createTar","deriveInterfaces","createApplication","createDeployment","deleteApplication","updateApplication","toBrettInterface","iface","version","id","_id","src","_src","declaration","surface","view","type","createCoreApp","options","spin","start","application","succeed","rollback","error","fail","createStudio","deployWorkbenchApp","access","app","applicationId","icon","isApp","isAutoUpdating","isExternal","label","mfManifest","onDeployed","slug","sourceDir","title","visibility","workspaces","tarball","undefined","cwd","pipe","interfaces","appTitle","map","toSlugRejection","clear","statusCode","Error","cause"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,UAAU,QAAO,YAAW;AAGpC,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAKC,SAAS,QAAO,MAAK;AAElC,SAA+BC,gBAAgB,QAAO,4BAA2B;AACjF,SAKEC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,iCAAgC;AAWvC,SAASC,iBAAiBC,KAAuB,EAAEC,OAAe;IAChE,MAAM,EAACC,IAAIC,GAAG,EAAEC,KAAKC,IAAI,EAAE,GAAGC,aAAY,GAAGN;IAC7C,IAAI,UAAUM,aAAa,OAAO;QAAC,GAAGA,WAAW;QAAEL;IAAO;IAE1D,OAAQK,YAAYC,OAAO;QACzB,KAAK;YAAgB;gBACnB,MAAM,EAACA,OAAO,EA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AAK,gBAAgB,EAAEzC,gBAAgB2B,OAAO,oHAAoH,CAAC,EAC5K;QAAC8B,OAAO9B;IAAK;AAEjB"}
1
+ {"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {c as createTar} from 'tar'\n\nimport {type DerivedInterface, deriveInterfaces} from '../../deriveInterfaces.js'\nimport {\n type Application,\n type BrettAccess,\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n deleteApplication,\n updateApplication,\n} from '../../services/applications.js'\n\n/**\n * `rollback` undoes the creation, so a later failure leaves no record stranded at the slug.\n * @internal\n */\nexport interface CreatedApplication {\n application: Application\n rollback: () => Promise<void>\n}\n\nfunction toBrettInterface(iface: DerivedInterface): BrettInterface {\n const {id: _id, src: _src, ...declaration} = iface\n if ('type' in declaration) return declaration\n\n switch (declaration.surface) {\n case 'asset_source': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'panel': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'tile': {\n const {surface, ...view} = declaration\n return {...view, type: surface}\n }\n case 'window': {\n const {surface, ...view} = declaration\n return {...view, type: 'app'}\n }\n }\n}\n\n/**\n * Create a coreApp record (no deployment), so the CLI can build with its id\n * before shipping the first deployment. First deploy only.\n * @internal\n */\nexport async function createCoreApp(options: {\n isSingleton?: boolean\n name?: string\n organizationId: string\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating application...').start()\n try {\n const application = await createApplication({...options, type: 'coreApp'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Create a studio record (no deployment).\n * @internal\n */\nexport async function createStudio(options: {\n externalUrl?: string\n name?: string\n organizationId: string\n projectId: string | undefined\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating studio...').start()\n try {\n const application = await createApplication({...options, type: 'studio'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Ship a deployment to an already-created (or `deployment.appId`) application,\n * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when\n * set) from config. The deploy endpoint ignores these, so a redeploy patches\n * them here alongside the new deployment.\n *\n * `onDeployed` fires the instant the deployment is live, before the metadata\n * sync — so a caller can disarm a create-time rollback that must not delete an\n * application once it has an active deployment.\n *\n * `isExternal` skips the tarball: the customer serves the build from the\n * application's registered origin.\n * @internal\n */\nexport async function deployWorkbenchApp(options: {\n access?: readonly BrettAccess[]\n app: CliConfig['app']\n applicationId: string\n icon?: string\n isApp: boolean\n isAutoUpdating: boolean\n isExternal?: boolean\n label?: string\n mfManifest: Record<string, unknown>\n onDeployed?: () => void\n /**\n * The address from config. Only `createApplication` used to send it, so an\n * app with a `deployment.appId` kept whatever slug it was created at.\n */\n slug?: string\n sourceDir: string\n title: string\n version: string\n visibility?: AppVisibility\n workspaces?: readonly BrettWorkspace[]\n}): Promise<void> {\n const {\n access,\n app,\n applicationId,\n icon,\n isApp,\n isAutoUpdating,\n isExternal = false,\n label = 'Deploying...',\n mfManifest,\n onDeployed,\n slug,\n sourceDir,\n title,\n version,\n visibility,\n workspaces,\n } = options\n const tarball = isExternal\n ? undefined\n : createTar({cwd: dirname(sourceDir)}, [basename(sourceDir)]).pipe(createGzip())\n\n const spin = spinner(label).start()\n try {\n await createDeployment({\n access,\n applicationId,\n // Brett assigns the id and resolves modules by `moduleId`, so neither travels.\n interfaces: deriveInterfaces(app, {appTitle: title, isApp}).map((iface) =>\n toBrettInterface(iface),\n ),\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n })\n onDeployed?.()\n try {\n await updateApplication(applicationId, {\n title,\n ...(icon ? {icon} : {}),\n ...(slug ? {slug} : {}),\n ...(visibility ? {visibility} : {}),\n })\n } catch (error) {\n throw toSlugRejection(error, slug)\n }\n spin.succeed()\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * The slug is the one synced field the server validates — it must be free\n * within the organization, and a singleton app only accepts its reserved\n * identifiers — so a 4xx on the metadata patch is a rejected rename. Name the\n * slug and the server's reason; anything else propagates untouched.\n */\nfunction toSlugRejection(error: unknown, slug: string | undefined): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (!slug || statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `Slug \"${slug}\" was rejected: ${getErrorMessage(error)}. The deployment is live at the application's previous slug — change \\`app.slug\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n"],"names":["basename","dirname","createGzip","getErrorMessage","spinner","c","createTar","deriveInterfaces","createApplication","createDeployment","deleteApplication","updateApplication","toBrettInterface","iface","id","_id","src","_src","declaration","surface","view","type","createCoreApp","options","spin","start","application","succeed","rollback","error","fail","createStudio","deployWorkbenchApp","access","app","applicationId","icon","isApp","isAutoUpdating","isExternal","label","mfManifest","onDeployed","slug","sourceDir","title","version","visibility","workspaces","tarball","undefined","cwd","pipe","interfaces","appTitle","map","toSlugRejection","clear","statusCode","Error","cause"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,UAAU,QAAO,YAAW;AAGpC,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAKC,SAAS,QAAO,MAAK;AAElC,SAA+BC,gBAAgB,QAAO,4BAA2B;AACjF,SAKEC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,iCAAgC;AAWvC,SAASC,iBAAiBC,KAAuB;IAC/C,MAAM,EAACC,IAAIC,GAAG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IAAI,CAACf,QAAQe,eAAeR,aAAaQ,aAAa,OAAOA,cAAc,KAAK,OAAO7B;IACvF,OAAO,IAAI8B,MACT,CAAC,MAAM,EAAEhB,KAAK,gBAAgB,EAAExC,gBAAgB0B,OAAO,oHAAoH,CAAC,EAC5K;QAAC+B,OAAO/B;IAAK;AAEjB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/deploy/getWorkbench.ts"],"sourcesContent":["// The deploy command's view of a workbench app: the resolved interfaces plus\n// the deploy-time guards that need the app's declarations. `sanity deploy` calls\n// `getWorkbench(config)` once and either gets `null` (plain project — normal\n// deploy) or an object it asks to validate the app before shipping.\n\nimport {type CliConfig} from '@sanity/cli-core'\n\nimport {type ResolvedWorkbenchApp, resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {buildViewDeploymentPayload, type ViewDeploymentPayload} from './viewDeployment.js'\n\nexport interface DeployableWorkbenchApp extends ResolvedWorkbenchApp {\n /**\n * Throws when the app exposes nothing (no entry, view, or service) — the\n * remote would have nothing to load. Gated before any prompt or API call.\n */\n assertDeployable(): void\n /**\n * Validates the app's declared views into the application-service payload.\n * Throws when a view declaration is malformed.\n */\n buildViewDeploymentPayload(applicationId: string): ViewDeploymentPayload\n /** Declares something to host as an application — an entry, view, or service. */\n hasInterfaces: boolean\n}\n\nexport function getWorkbench(\n cliConfig: CliConfig | null | undefined,\n): DeployableWorkbenchApp | null {\n const app = resolveWorkbenchApp(cliConfig)\n if (!app) return null\n\n const {entry, views, webWorkers} = app\n\n return {\n ...app,\n\n hasInterfaces: !!entry || views.length > 0 || webWorkers.length > 0,\n\n assertDeployable() {\n if (!entry && views.length === 0 && webWorkers.length === 0) {\n throw new Error(\n 'Nothing to deploy: the app declares no entry, views or web workers. ' +\n 'Add at least one to the app config.',\n )\n }\n },\n\n buildViewDeploymentPayload(applicationId) {\n return buildViewDeploymentPayload({applicationId, views})\n },\n }\n}\n"],"names":["resolveWorkbenchApp","buildViewDeploymentPayload","getWorkbench","cliConfig","app","entry","views","webWorkers","hasInterfaces","length","assertDeployable","Error","applicationId"],"mappings":"AAAA,6EAA6E;AAC7E,iFAAiF;AACjF,6EAA6E;AAC7E,oEAAoE;AAIpE,SAAmCA,mBAAmB,QAAO,+BAA8B;AAC3F,SAAQC,0BAA0B,QAAmC,sBAAqB;AAiB1F,OAAO,SAASC,aACdC,SAAuC;IAEvC,MAAMC,MAAMJ,oBAAoBG;IAChC,IAAI,CAACC,KAAK,OAAO;IAEjB,MAAM,EAACC,KAAK,EAAEC,KAAK,EAAEC,UAAU,EAAC,GAAGH;IAEnC,OAAO;QACL,GAAGA,GAAG;QAENI,eAAe,CAAC,CAACH,SAASC,MAAMG,MAAM,GAAG,KAAKF,WAAWE,MAAM,GAAG;QAElEC;YACE,IAAI,CAACL,SAASC,MAAMG,MAAM,KAAK,KAAKF,WAAWE,MAAM,KAAK,GAAG;gBAC3D,MAAM,IAAIE,MACR,yEACE;YAEN;QACF;QAEAV,4BAA2BW,aAAa;YACtC,OAAOX,2BAA2B;gBAACW;gBAAeN;YAAK;QACzD;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/deploy/getWorkbench.ts"],"sourcesContent":["// The deploy command's view of a workbench app: the resolved interfaces plus\n// the deploy-time guards that need the app's declarations. `sanity deploy` calls\n// `getWorkbench(config)` once and either gets `null` (plain project — normal\n// deploy) or an object it asks to validate the app before shipping.\n\nimport {type CliConfig} from '@sanity/cli-core'\n\nimport {type ResolvedWorkbenchApp, resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {buildViewDeploymentPayload, type ViewDeploymentPayload} from './viewDeployment.js'\n\nexport interface DeployableWorkbenchApp extends ResolvedWorkbenchApp {\n /**\n * Throws when the app exposes nothing (no entry, view, or web worker) — the\n * remote would have nothing to load. Gated before any prompt or API call.\n */\n assertDeployable(): void\n /**\n * Validates the app's declared views into the application-service payload.\n * Throws when a view declaration is malformed.\n */\n buildViewDeploymentPayload(applicationId: string): ViewDeploymentPayload\n /** Declares something to host as an application — an entry, view, or web worker. */\n hasInterfaces: boolean\n}\n\nexport function getWorkbench(\n cliConfig: CliConfig | null | undefined,\n): DeployableWorkbenchApp | null {\n const app = resolveWorkbenchApp(cliConfig)\n if (!app) return null\n\n const {entry, views, webWorkers} = app\n\n return {\n ...app,\n\n hasInterfaces: !!entry || views.length > 0 || webWorkers.length > 0,\n\n assertDeployable() {\n if (!entry && views.length === 0 && webWorkers.length === 0) {\n throw new Error(\n 'Nothing to deploy: the app declares no entry, views or web workers. ' +\n 'Add at least one to the app config.',\n )\n }\n },\n\n buildViewDeploymentPayload(applicationId) {\n return buildViewDeploymentPayload({applicationId, views})\n },\n }\n}\n"],"names":["resolveWorkbenchApp","buildViewDeploymentPayload","getWorkbench","cliConfig","app","entry","views","webWorkers","hasInterfaces","length","assertDeployable","Error","applicationId"],"mappings":"AAAA,6EAA6E;AAC7E,iFAAiF;AACjF,6EAA6E;AAC7E,oEAAoE;AAIpE,SAAmCA,mBAAmB,QAAO,+BAA8B;AAC3F,SAAQC,0BAA0B,QAAmC,sBAAqB;AAiB1F,OAAO,SAASC,aACdC,SAAuC;IAEvC,MAAMC,MAAMJ,oBAAoBG;IAChC,IAAI,CAACC,KAAK,OAAO;IAEjB,MAAM,EAACC,KAAK,EAAEC,KAAK,EAAEC,UAAU,EAAC,GAAGH;IAEnC,OAAO;QACL,GAAGA,GAAG;QAENI,eAAe,CAAC,CAACH,SAASC,MAAMG,MAAM,GAAG,KAAKF,WAAWE,MAAM,GAAG;QAElEC;YACE,IAAI,CAACL,SAASC,MAAMG,MAAM,KAAK,KAAKF,WAAWE,MAAM,KAAK,GAAG;gBAC3D,MAAM,IAAIE,MACR,yEACE;YAEN;QACF;QAEAV,4BAA2BW,aAAa;YACtC,OAAOX,2BAA2B;gBAACW;gBAAeN;YAAK;QACzD;IACF;AACF"}