@sanity/workbench-cli 2.8.4 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/_exports/_internal_worker_bus.d.ts +29 -0
  2. package/dist/_exports/_internal_worker_bus.js +3 -0
  3. package/dist/_exports/_internal_worker_bus.js.map +1 -0
  4. package/dist/_exports/build.d.ts +2 -2
  5. package/dist/_exports/build.js +1 -1
  6. package/dist/_exports/build.js.map +1 -1
  7. package/dist/_exports/contract-D_HnLQtT.d.ts +197 -0
  8. package/dist/_exports/defineApp-4hImcIIe.d.ts +182 -0
  9. package/dist/_exports/defineService-C1MhDwmh.d.ts +74 -0
  10. package/dist/_exports/deploy.d.ts +11 -3
  11. package/dist/_exports/index.d.ts +4 -50
  12. package/dist/_exports/index.js.map +1 -1
  13. package/dist/_exports/{resolveWorkbenchConfig-KhXnVKZ6.d.ts → resolveWorkbenchConfig-DEttN7ks.d.ts} +9 -3
  14. package/dist/_exports/{summarizeInterfaces-noqbAtVC.d.ts → summarizeInterfaces-Co97VU2z.d.ts} +4 -4
  15. package/dist/_exports/undeploy.d.ts +2 -2
  16. package/dist/actions/build/artifact.js +3 -3
  17. package/dist/actions/build/artifact.js.map +1 -1
  18. package/dist/actions/build/configs/artifact.js +70 -5
  19. package/dist/actions/build/configs/artifact.js.map +1 -1
  20. package/dist/actions/build/configs/configApp.js +15 -0
  21. package/dist/actions/build/configs/configApp.js.map +1 -0
  22. package/dist/actions/build/configs/mediaLibraryIslandRuntime.js +25 -0
  23. package/dist/actions/build/configs/mediaLibraryIslandRuntime.js.map +1 -0
  24. package/dist/actions/build/services/artifact.js +13 -3
  25. package/dist/actions/build/services/artifact.js.map +1 -1
  26. package/dist/actions/build/services/workerBus.js +159 -0
  27. package/dist/actions/build/services/workerBus.js.map +1 -0
  28. package/dist/actions/build/vite/optimize-deps.js +11 -1
  29. package/dist/actions/build/vite/optimize-deps.js.map +1 -1
  30. package/dist/actions/build/vite/plugin.js +15 -1
  31. package/dist/actions/build/vite/plugin.js.map +1 -1
  32. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js +17 -0
  33. package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js.map +1 -1
  34. package/dist/actions/build/vite/plugins/plugin-strip-sui-global-reset.js +82 -0
  35. package/dist/actions/build/vite/plugins/plugin-strip-sui-global-reset.js.map +1 -0
  36. package/dist/actions/build/vite/workbench-vite-plugins.js +13 -2
  37. package/dist/actions/build/vite/workbench-vite-plugins.js.map +1 -1
  38. package/dist/actions/deploy/checkBuiltOutput.js +10 -2
  39. package/dist/actions/deploy/checkBuiltOutput.js.map +1 -1
  40. package/dist/actions/deploy/deployWorkbenchApp.js +10 -3
  41. package/dist/actions/deploy/deployWorkbenchApp.js.map +1 -1
  42. package/dist/defineService.js +11 -2
  43. package/dist/defineService.js.map +1 -1
  44. package/dist/resolveWorkbenchApp.js +16 -0
  45. package/dist/resolveWorkbenchApp.js.map +1 -1
  46. package/dist/services/applications.js +20 -8
  47. package/dist/services/applications.js.map +1 -1
  48. package/package.json +9 -4
  49. package/dist/_exports/defineApp-DOJE2kjo.d.ts +0 -376
@@ -1,4 +1,5 @@
1
- import { A as WorkbenchConfigValue, t as DefineAppInput } from "./defineApp-DOJE2kjo.js";
1
+ import { b as WorkbenchConfigValue } from "./contract-D_HnLQtT.js";
2
+ import { t as DefineAppInput } from "./defineApp-4hImcIIe.js";
2
3
  import { AppVisibility, CliConfig } from "@sanity/cli-core";
3
4
  /**
4
5
  * Bundled so adding a declaration family touches this type and the artifact
@@ -36,6 +37,11 @@ interface ResolvedWorkbenchApp {
36
37
  /** Dashboard visibility declared by the app; `undefined` when unset. */
37
38
  readonly visibility?: AppVisibility;
38
39
  }
40
+ /**
41
+ * The module behind the app's `./App` expose. `entry` is shorthand for a window view.
42
+ * @internal
43
+ */
44
+ declare function resolveAppEntry(app: CliConfig['app']): string | undefined;
39
45
  /**
40
46
  * Resolve the workbench app for a CLI config, or `null` for a plain project or a
41
47
  * config (which is not an app — read it with `resolveWorkbenchConfig`).
@@ -58,5 +64,5 @@ interface ResolvedMediaLibraryConfig {
58
64
  * @public
59
65
  */
60
66
  declare function resolveWorkbenchConfig(cliConfig: CliConfig | null | undefined): ResolvedMediaLibraryConfig | null;
61
- export { resolveWorkbenchApp as a, WorkbenchExposes as i, resolveWorkbenchConfig as n, ResolvedWorkbenchApp as r, ResolvedMediaLibraryConfig as t };
62
- //# sourceMappingURL=resolveWorkbenchConfig-KhXnVKZ6.d.ts.map
67
+ export { resolveAppEntry as a, WorkbenchExposes as i, resolveWorkbenchConfig as n, resolveWorkbenchApp as o, ResolvedWorkbenchApp as r, ResolvedMediaLibraryConfig as t };
68
+ //# sourceMappingURL=resolveWorkbenchConfig-DEttN7ks.d.ts.map
@@ -1,7 +1,7 @@
1
- import { D as ViewSurface, b as ServiceType } from "./defineApp-DOJE2kjo.js";
2
- import { i as WorkbenchExposes, r as ResolvedWorkbenchApp } from "./resolveWorkbenchConfig-KhXnVKZ6.js";
3
- import { CliConfig } from "@sanity/cli-core";
1
+ import { _ as ViewSurface, u as ServiceType } from "./contract-D_HnLQtT.js";
2
+ import { i as WorkbenchExposes, r as ResolvedWorkbenchApp } from "./resolveWorkbenchConfig-DEttN7ks.js";
4
3
  import { z } from "zod/mini";
4
+ import { CliConfig } from "@sanity/cli-core";
5
5
  /**
6
6
  * Payload registering an app's views with the application service on deploy.
7
7
  *
@@ -62,4 +62,4 @@ declare function summarizeInterfaces({ views, webWorkers }: WorkbenchExposes): {
62
62
  views: DeployedView[];
63
63
  };
64
64
  export { DeployableWorkbenchApp as a, summarizeInterfaces as i, DeployedView as n, getWorkbench as o, DeployedWebWorker as r, DeployedInterface as t };
65
- //# sourceMappingURL=summarizeInterfaces-noqbAtVC.d.ts.map
65
+ //# sourceMappingURL=summarizeInterfaces-Co97VU2z.d.ts.map
@@ -1,5 +1,5 @@
1
- import { t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-KhXnVKZ6.js";
2
- import { a as DeployableWorkbenchApp, n as DeployedView, r as DeployedWebWorker } from "./summarizeInterfaces-noqbAtVC.js";
1
+ import { t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-DEttN7ks.js";
2
+ import { a as DeployableWorkbenchApp, n as DeployedView, r as DeployedWebWorker } from "./summarizeInterfaces-Co97VU2z.js";
3
3
  import "node:zlib";
4
4
  import { UndeployAdapter, UndeployApplicationTarget, UndeployConfigTarget } from "@sanity/cli-core/undeploy";
5
5
  interface ConfigSnapshot {
@@ -1,4 +1,4 @@
1
- import { configArtifacts } from './configs/artifact.js';
1
+ import { mediaLibraryConfigArtifacts } from './configs/artifact.js';
2
2
  import { serviceArtifacts } from './services/artifact.js';
3
3
  import { viewArtifacts } from './views/artifact.js';
4
4
  /**
@@ -19,11 +19,11 @@ import { viewArtifacts } from './views/artifact.js';
19
19
  * Expand what the app exposes into the flat artifact set the federation build
20
20
  * writes — the single place that composes the per-type expanders, so the expose
21
21
  * mapping and the file writing read from one expansion.
22
- */ export function workbenchArtifacts(exposes) {
22
+ */ export function workbenchArtifacts(exposes, configOptions = {}) {
23
23
  return [
24
24
  ...viewArtifacts(exposes.views ?? []),
25
25
  ...serviceArtifacts(exposes.webWorkers ?? []),
26
- ...configArtifacts(exposes.config)
26
+ ...mediaLibraryConfigArtifacts(exposes.config, configOptions)
27
27
  ];
28
28
  }
29
29
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/artifact.ts"],"sourcesContent":["import {type WorkbenchExposes} from '../../resolveWorkbenchApp.js'\nimport {configArtifacts} from './configs/artifact.js'\nimport {serviceArtifacts} from './services/artifact.js'\nimport {viewArtifacts} from './views/artifact.js'\n\n/**\n * What a {@link GeneratedArtifact.source} builder receives from the build — the\n * one thing it can't compute on its own, since only the build knows where the\n * runtime dir sits relative to the app's `src`.\n */\ninterface ArtifactContext {\n /** Import specifier for an app `src` file, relative to this artifact. */\n resolveImport: (src: string) => string\n\n isolateStyles?: boolean\n}\n\n/**\n * One file the federation build generates into the runtime dir for a declared\n * interface. Each interface type — views, web workers — expands its declarations\n * into a flat list of these; the build then writes them and maps the ones the\n * host loads directly into the module-federation manifest.\n *\n * Adding an interface type is adding a builder that returns\n * `GeneratedArtifact[]` — the write loop and the expose mapping never change.\n */\nexport interface GeneratedArtifact {\n /** Path relative to the federation runtime dir, e.g. `views/feed/panel.js`. */\n path: string\n /** Build the file's contents. */\n source: (context: ArtifactContext) => string\n\n /**\n * Module-federation expose key when the host loads this artifact directly —\n * a view component `./views/feed/panel`, a service loader `./services/unread`.\n * Omitted for a file the host never loads on its own, like a worker bundle\n * (reached through its sibling loader).\n */\n expose?: string\n}\n\n/**\n * Map the artifacts the host loads directly (those with an `expose`) to their\n * runtime-dir paths, for the module-federation `exposes` field. `toExposePath`\n * turns a runtime-relative artifact path into the value federation wants — the\n * caller owns the runtime-dir location and any entry resolution.\n */\nexport function artifactExposes(\n artifacts: readonly GeneratedArtifact[],\n toExposePath: (artifactPath: string) => string,\n): Record<string, string> {\n const exposes: Record<string, string> = {}\n for (const artifact of artifacts) {\n if (artifact.expose) {\n exposes[artifact.expose] = toExposePath(artifact.path)\n }\n }\n return exposes\n}\n\n/**\n * Expand what the app exposes into the flat artifact set the federation build\n * writes — the single place that composes the per-type expanders, so the expose\n * mapping and the file writing read from one expansion.\n */\nexport function workbenchArtifacts(exposes: WorkbenchExposes): GeneratedArtifact[] {\n return [\n ...viewArtifacts(exposes.views ?? []),\n ...serviceArtifacts(exposes.webWorkers ?? []),\n ...configArtifacts(exposes.config),\n ]\n}\n"],"names":["configArtifacts","serviceArtifacts","viewArtifacts","artifactExposes","artifacts","toExposePath","exposes","artifact","expose","path","workbenchArtifacts","views","webWorkers","config"],"mappings":"AACA,SAAQA,eAAe,QAAO,wBAAuB;AACrD,SAAQC,gBAAgB,QAAO,yBAAwB;AACvD,SAAQC,aAAa,QAAO,sBAAqB;AAsCjD;;;;;CAKC,GACD,OAAO,SAASC,gBACdC,SAAuC,EACvCC,YAA8C;IAE9C,MAAMC,UAAkC,CAAC;IACzC,KAAK,MAAMC,YAAYH,UAAW;QAChC,IAAIG,SAASC,MAAM,EAAE;YACnBF,OAAO,CAACC,SAASC,MAAM,CAAC,GAAGH,aAAaE,SAASE,IAAI;QACvD;IACF;IACA,OAAOH;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASI,mBAAmBJ,OAAyB;IAC1D,OAAO;WACFJ,cAAcI,QAAQK,KAAK,IAAI,EAAE;WACjCV,iBAAiBK,QAAQM,UAAU,IAAI,EAAE;WACzCZ,gBAAgBM,QAAQO,MAAM;KAClC;AACH"}
1
+ {"version":3,"sources":["../../../src/actions/build/artifact.ts"],"sourcesContent":["import {type WorkbenchExposes} from '../../resolveWorkbenchApp.js'\nimport {\n type MediaLibraryConfigArtifactOptions,\n mediaLibraryConfigArtifacts,\n} from './configs/artifact.js'\nimport {serviceArtifacts} from './services/artifact.js'\nimport {viewArtifacts} from './views/artifact.js'\n\n/**\n * What a {@link GeneratedArtifact.source} builder receives from the build — the\n * one thing it can't compute on its own, since only the build knows where the\n * runtime dir sits relative to the app's `src`.\n */\ninterface ArtifactContext {\n /** Import specifier for an app `src` file, relative to this artifact. */\n resolveImport: (src: string) => string\n\n isolateStyles?: boolean\n}\n\n/**\n * One file the federation build generates into the runtime dir for a declared\n * interface. Each interface type — views, web workers — expands its declarations\n * into a flat list of these; the build then writes them and maps the ones the\n * host loads directly into the module-federation manifest.\n *\n * Adding an interface type is adding a builder that returns\n * `GeneratedArtifact[]` — the write loop and the expose mapping never change.\n */\nexport interface GeneratedArtifact {\n /** Path relative to the federation runtime dir, e.g. `views/feed/panel.js`. */\n path: string\n /** Build the file's contents. */\n source: (context: ArtifactContext) => string\n\n /**\n * Module-federation expose key when the host loads this artifact directly —\n * a view component `./views/feed/panel`, a service loader `./services/unread`.\n * Omitted for a file the host never loads on its own, like a worker bundle\n * (reached through its sibling loader).\n */\n expose?: string\n}\n\n/**\n * Map the artifacts the host loads directly (those with an `expose`) to their\n * runtime-dir paths, for the module-federation `exposes` field. `toExposePath`\n * turns a runtime-relative artifact path into the value federation wants — the\n * caller owns the runtime-dir location and any entry resolution.\n */\nexport function artifactExposes(\n artifacts: readonly GeneratedArtifact[],\n toExposePath: (artifactPath: string) => string,\n): Record<string, string> {\n const exposes: Record<string, string> = {}\n for (const artifact of artifacts) {\n if (artifact.expose) {\n exposes[artifact.expose] = toExposePath(artifact.path)\n }\n }\n return exposes\n}\n\n/**\n * Expand what the app exposes into the flat artifact set the federation build\n * writes — the single place that composes the per-type expanders, so the expose\n * mapping and the file writing read from one expansion.\n */\nexport function workbenchArtifacts(\n exposes: WorkbenchExposes,\n configOptions: MediaLibraryConfigArtifactOptions = {},\n): GeneratedArtifact[] {\n return [\n ...viewArtifacts(exposes.views ?? []),\n ...serviceArtifacts(exposes.webWorkers ?? []),\n ...mediaLibraryConfigArtifacts(exposes.config, configOptions),\n ]\n}\n"],"names":["mediaLibraryConfigArtifacts","serviceArtifacts","viewArtifacts","artifactExposes","artifacts","toExposePath","exposes","artifact","expose","path","workbenchArtifacts","configOptions","views","webWorkers","config"],"mappings":"AACA,SAEEA,2BAA2B,QACtB,wBAAuB;AAC9B,SAAQC,gBAAgB,QAAO,yBAAwB;AACvD,SAAQC,aAAa,QAAO,sBAAqB;AAsCjD;;;;;CAKC,GACD,OAAO,SAASC,gBACdC,SAAuC,EACvCC,YAA8C;IAE9C,MAAMC,UAAkC,CAAC;IACzC,KAAK,MAAMC,YAAYH,UAAW;QAChC,IAAIG,SAASC,MAAM,EAAE;YACnBF,OAAO,CAACC,SAASC,MAAM,CAAC,GAAGH,aAAaE,SAASE,IAAI;QACvD;IACF;IACA,OAAOH;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASI,mBACdJ,OAAyB,EACzBK,gBAAmD,CAAC,CAAC;IAErD,OAAO;WACFT,cAAcI,QAAQM,KAAK,IAAI,EAAE;WACjCX,iBAAiBK,QAAQO,UAAU,IAAI,EAAE;WACzCb,4BAA4BM,QAAQQ,MAAM,EAAEH;KAChD;AACH"}
@@ -1,6 +1,15 @@
1
1
  import { INSTALLATION_CONFIG_TYPE, MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION } from '../../../contract.js';
2
+ import { MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE } from './mediaLibraryIslandRuntime.js';
2
3
  const CONFIGS_DIR_NAME = 'configs';
3
- /** Expand the config into one federation module aggregating all fields, so the host imports one live config value. */ export function configArtifacts(config) {
4
+ /**
5
+ * Expand the Media Library config into its federation modules: one aggregating
6
+ * all fields (so the host imports one live config value), plus — when the
7
+ * installed `sanity` ships it — the island-mount runtime the host uses to
8
+ * render custom field inputs in isolated React roots.
9
+ *
10
+ * Everything here is Media Library-specific (the one config type today);
11
+ * a second config type gets its own expander next to this one.
12
+ */ export function mediaLibraryConfigArtifacts(config, options = {}) {
4
13
  if (!config) return [];
5
14
  return [
6
15
  {
@@ -10,7 +19,14 @@ const CONFIGS_DIR_NAME = 'configs';
10
19
  config,
11
20
  resolveImport
12
21
  })
13
- }
22
+ },
23
+ ...options.islandRuntime ? [
24
+ {
25
+ expose: './media-library-island-runtime',
26
+ path: `${CONFIGS_DIR_NAME}/media_library_island_runtime.js`,
27
+ source: ()=>mediaLibraryIslandRuntimeSource()
28
+ }
29
+ ] : []
14
30
  ];
15
31
  }
16
32
  /**
@@ -34,11 +50,60 @@ ${entries}
34
50
  ],
35
51
  }
36
52
 
53
+ // Dev-only HMR handle. In dev the Media Library host loads this module into
54
+ // its own page through Module Federation, which keeps returning the first
55
+ // evaluation — the host cannot re-import its way to fresh code. So the host
56
+ // registers a listener here instead: on every hot update the outgoing module
57
+ // hands its live listener set to the incoming module, then replays the
58
+ // listeners with the fresh namespace, and the host re-applies the field
59
+ // config in place (the same pattern view remotes use). When nobody is
60
+ // listening — or a listener fails to apply — invalidate() escalates to
61
+ // Vite's native full reload, so the page can never keep rendering from
62
+ // stale config.
63
+ let listeners = new Set()
64
+ export function subscribe(listener) {
65
+ listeners.add(listener)
66
+ return () => listeners.delete(listener)
67
+ }
68
+ // Internal to the hot chain: the set object travels across updates so the
69
+ // unsubscribe closures handed out by any module generation keep deleting
70
+ // from the one live set (a copy would orphan them after the first update).
71
+ export function _adoptListeners(shared) {
72
+ listeners = shared
73
+ }
74
+
37
75
  if (import.meta.hot) {
38
- // A config is data, not a rendered island with a live root to remount —
39
- // self-accept so a field edit swaps the module in place; the host re-reads it.
40
- import.meta.hot.accept()
76
+ import.meta.hot.accept((next) => {
77
+ if (!next || typeof next._adoptListeners !== 'function' || listeners.size === 0) {
78
+ import.meta.hot.invalidate()
79
+ return
80
+ }
81
+ try {
82
+ next._adoptListeners(listeners)
83
+ // Notify a snapshot: a listener may unsubscribe and re-subscribe on the
84
+ // fresh namespace, which (post-adoption) mutates this very set — and a
85
+ // Set iterator revisits re-added entries, so iterating live would loop
86
+ // forever. Entries added mid-loop subscribed to the already-current
87
+ // namespace and need no notification for this update.
88
+ for (const listener of [...listeners]) {
89
+ listener(next)
90
+ }
91
+ } catch {
92
+ import.meta.hot.invalidate()
93
+ }
94
+ })
95
+ }
96
+ `;
41
97
  }
98
+ /**
99
+ * One line on purpose: the runtime implementation lives in the `sanity`
100
+ * package and is bundled into the remote from the app's own install, so the
101
+ * runtime always matches the `sanity` version field modules compile against.
102
+ */ function mediaLibraryIslandRuntimeSource() {
103
+ return `\
104
+ // This file is auto-generated on 'sanity build' / 'sanity dev'
105
+ // Modifications to this file are automatically discarded
106
+ export * from ${JSON.stringify(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE)}
42
107
  `;
43
108
  }
44
109
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/configs/artifact.ts"],"sourcesContent":["import {INSTALLATION_CONFIG_TYPE, MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION} from '../../../contract.js'\nimport {type GeneratedArtifact} from '../artifact.js'\n\nconst CONFIGS_DIR_NAME = 'configs'\n\n/**\n * The config to generate a module for.\n * @internal\n */\nexport interface ConfigArtifact {\n fields: {name: string; public?: boolean; src: string; title: string}[]\n}\n\n/** Expand the config into one federation module aggregating all fields, so the host imports one live config value. */\nexport function configArtifacts(config: ConfigArtifact | undefined): GeneratedArtifact[] {\n if (!config) return []\n return [\n {\n expose: `./${CONFIGS_DIR_NAME}/${INSTALLATION_CONFIG_TYPE}`,\n path: `${CONFIGS_DIR_NAME}/${INSTALLATION_CONFIG_TYPE}.js`,\n source: ({resolveImport}) => mediaLibraryConfigSource({config, resolveImport}),\n },\n ]\n}\n\n/**\n * Emits `export const config`: each field's serializable `{name, title, public}`\n * plus its live `defineField` value, the one thing the wire can't carry.\n * `appType` stays off the module — the host assigns it from the wire record.\n */\nfunction mediaLibraryConfigSource(input: {\n config: ConfigArtifact\n resolveImport: (src: string) => string\n}): string {\n const {config, resolveImport} = input\n const imports = config.fields\n .map((field, index) => `import field_${index} from ${JSON.stringify(resolveImport(field.src))}`)\n .join('\\n')\n const entries = config.fields\n .map(\n (field, index) =>\n ` {name: ${JSON.stringify(field.name)}, title: ${JSON.stringify(field.title)}, ` +\n `public: ${JSON.stringify(Boolean(field.public))}, config: field_${index}},`,\n )\n .join('\\n')\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\n${imports}\n\nexport const type = ${JSON.stringify(INSTALLATION_CONFIG_TYPE)}\nexport const version = ${MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION}\nexport const config = {\n fields: [\n${entries}\n ],\n}\n\nif (import.meta.hot) {\n // A config is data, not a rendered island with a live root to remount —\n // self-accept so a field edit swaps the module in place; the host re-reads it.\n import.meta.hot.accept()\n}\n`\n}\n"],"names":["INSTALLATION_CONFIG_TYPE","MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION","CONFIGS_DIR_NAME","configArtifacts","config","expose","path","source","resolveImport","mediaLibraryConfigSource","input","imports","fields","map","field","index","JSON","stringify","src","join","entries","name","title","Boolean","public"],"mappings":"AAAA,SAAQA,wBAAwB,EAAEC,qCAAqC,QAAO,uBAAsB;AAGpG,MAAMC,mBAAmB;AAUzB,oHAAoH,GACpH,OAAO,SAASC,gBAAgBC,MAAkC;IAChE,IAAI,CAACA,QAAQ,OAAO,EAAE;IACtB,OAAO;QACL;YACEC,QAAQ,CAAC,EAAE,EAAEH,iBAAiB,CAAC,EAAEF,0BAA0B;YAC3DM,MAAM,GAAGJ,iBAAiB,CAAC,EAAEF,yBAAyB,GAAG,CAAC;YAC1DO,QAAQ,CAAC,EAACC,aAAa,EAAC,GAAKC,yBAAyB;oBAACL;oBAAQI;gBAAa;QAC9E;KACD;AACH;AAEA;;;;CAIC,GACD,SAASC,yBAAyBC,KAGjC;IACC,MAAM,EAACN,MAAM,EAAEI,aAAa,EAAC,GAAGE;IAChC,MAAMC,UAAUP,OAAOQ,MAAM,CAC1BC,GAAG,CAAC,CAACC,OAAOC,QAAU,CAAC,aAAa,EAAEA,MAAM,MAAM,EAAEC,KAAKC,SAAS,CAACT,cAAcM,MAAMI,GAAG,IAAI,EAC9FC,IAAI,CAAC;IACR,MAAMC,UAAUhB,OAAOQ,MAAM,CAC1BC,GAAG,CACF,CAACC,OAAOC,QACN,CAAC,WAAW,EAAEC,KAAKC,SAAS,CAACH,MAAMO,IAAI,EAAE,SAAS,EAAEL,KAAKC,SAAS,CAACH,MAAMQ,KAAK,EAAE,EAAE,CAAC,GACnF,CAAC,QAAQ,EAAEN,KAAKC,SAAS,CAACM,QAAQT,MAAMU,MAAM,GAAG,gBAAgB,EAAET,MAAM,EAAE,CAAC,EAE/EI,IAAI,CAAC;IACR,OAAO,CAAC;;;AAGV,EAAER,QAAQ;;oBAEU,EAAEK,KAAKC,SAAS,CAACjB,0BAA0B;uBACxC,EAAEC,sCAAsC;;;AAG/D,EAAEmB,QAAQ;;;;;;;;;AASV,CAAC;AACD"}
1
+ {"version":3,"sources":["../../../../src/actions/build/configs/artifact.ts"],"sourcesContent":["import {INSTALLATION_CONFIG_TYPE, MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION} from '../../../contract.js'\nimport {type GeneratedArtifact} from '../artifact.js'\nimport {MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE} from './mediaLibraryIslandRuntime.js'\n\nconst CONFIGS_DIR_NAME = 'configs'\n\n/**\n * The Media Library config to generate a module for.\n * @internal\n */\nexport interface MediaLibraryConfigArtifact {\n fields: {name: string; public?: boolean; src: string; title: string}[]\n}\n\n/** Build-time capabilities that gate optional Media Library config artifacts. */\nexport interface MediaLibraryConfigArtifactOptions {\n /**\n * Whether the app's installed `sanity` ships the Media Library island-mount\n * runtime ({@link MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE}). Gates the\n * `./media-library-island-runtime` expose — emitting it against an older\n * `sanity` would fail the build on an unresolvable import.\n */\n islandRuntime?: boolean\n}\n\n/**\n * Expand the Media Library config into its federation modules: one aggregating\n * all fields (so the host imports one live config value), plus — when the\n * installed `sanity` ships it — the island-mount runtime the host uses to\n * render custom field inputs in isolated React roots.\n *\n * Everything here is Media Library-specific (the one config type today);\n * a second config type gets its own expander next to this one.\n */\nexport function mediaLibraryConfigArtifacts(\n config: MediaLibraryConfigArtifact | undefined,\n options: MediaLibraryConfigArtifactOptions = {},\n): GeneratedArtifact[] {\n if (!config) return []\n return [\n {\n expose: `./${CONFIGS_DIR_NAME}/${INSTALLATION_CONFIG_TYPE}`,\n path: `${CONFIGS_DIR_NAME}/${INSTALLATION_CONFIG_TYPE}.js`,\n source: ({resolveImport}) => mediaLibraryConfigSource({config, resolveImport}),\n },\n ...(options.islandRuntime\n ? [\n {\n expose: './media-library-island-runtime',\n path: `${CONFIGS_DIR_NAME}/media_library_island_runtime.js`,\n source: () => mediaLibraryIslandRuntimeSource(),\n },\n ]\n : []),\n ]\n}\n\n/**\n * Emits `export const config`: each field's serializable `{name, title, public}`\n * plus its live `defineField` value, the one thing the wire can't carry.\n * `appType` stays off the module — the host assigns it from the wire record.\n */\nfunction mediaLibraryConfigSource(input: {\n config: MediaLibraryConfigArtifact\n resolveImport: (src: string) => string\n}): string {\n const {config, resolveImport} = input\n const imports = config.fields\n .map((field, index) => `import field_${index} from ${JSON.stringify(resolveImport(field.src))}`)\n .join('\\n')\n const entries = config.fields\n .map(\n (field, index) =>\n ` {name: ${JSON.stringify(field.name)}, title: ${JSON.stringify(field.title)}, ` +\n `public: ${JSON.stringify(Boolean(field.public))}, config: field_${index}},`,\n )\n .join('\\n')\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\n${imports}\n\nexport const type = ${JSON.stringify(INSTALLATION_CONFIG_TYPE)}\nexport const version = ${MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION}\nexport const config = {\n fields: [\n${entries}\n ],\n}\n\n// Dev-only HMR handle. In dev the Media Library host loads this module into\n// its own page through Module Federation, which keeps returning the first\n// evaluation — the host cannot re-import its way to fresh code. So the host\n// registers a listener here instead: on every hot update the outgoing module\n// hands its live listener set to the incoming module, then replays the\n// listeners with the fresh namespace, and the host re-applies the field\n// config in place (the same pattern view remotes use). When nobody is\n// listening — or a listener fails to apply — invalidate() escalates to\n// Vite's native full reload, so the page can never keep rendering from\n// stale config.\nlet listeners = new Set()\nexport function subscribe(listener) {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n// Internal to the hot chain: the set object travels across updates so the\n// unsubscribe closures handed out by any module generation keep deleting\n// from the one live set (a copy would orphan them after the first update).\nexport function _adoptListeners(shared) {\n listeners = shared\n}\n\nif (import.meta.hot) {\n import.meta.hot.accept((next) => {\n if (!next || typeof next._adoptListeners !== 'function' || listeners.size === 0) {\n import.meta.hot.invalidate()\n return\n }\n try {\n next._adoptListeners(listeners)\n // Notify a snapshot: a listener may unsubscribe and re-subscribe on the\n // fresh namespace, which (post-adoption) mutates this very set — and a\n // Set iterator revisits re-added entries, so iterating live would loop\n // forever. Entries added mid-loop subscribed to the already-current\n // namespace and need no notification for this update.\n for (const listener of [...listeners]) {\n listener(next)\n }\n } catch {\n import.meta.hot.invalidate()\n }\n })\n}\n`\n}\n\n/**\n * One line on purpose: the runtime implementation lives in the `sanity`\n * package and is bundled into the remote from the app's own install, so the\n * runtime always matches the `sanity` version field modules compile against.\n */\nfunction mediaLibraryIslandRuntimeSource(): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nexport * from ${JSON.stringify(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE)}\n`\n}\n"],"names":["INSTALLATION_CONFIG_TYPE","MEDIA_LIBRARY_CONFIG_CONTRACT_VERSION","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","CONFIGS_DIR_NAME","mediaLibraryConfigArtifacts","config","options","expose","path","source","resolveImport","mediaLibraryConfigSource","islandRuntime","mediaLibraryIslandRuntimeSource","input","imports","fields","map","field","index","JSON","stringify","src","join","entries","name","title","Boolean","public"],"mappings":"AAAA,SAAQA,wBAAwB,EAAEC,qCAAqC,QAAO,uBAAsB;AAEpG,SAAQC,mCAAmC,QAAO,iCAAgC;AAElF,MAAMC,mBAAmB;AAqBzB;;;;;;;;CAQC,GACD,OAAO,SAASC,4BACdC,MAA8C,EAC9CC,UAA6C,CAAC,CAAC;IAE/C,IAAI,CAACD,QAAQ,OAAO,EAAE;IACtB,OAAO;QACL;YACEE,QAAQ,CAAC,EAAE,EAAEJ,iBAAiB,CAAC,EAAEH,0BAA0B;YAC3DQ,MAAM,GAAGL,iBAAiB,CAAC,EAAEH,yBAAyB,GAAG,CAAC;YAC1DS,QAAQ,CAAC,EAACC,aAAa,EAAC,GAAKC,yBAAyB;oBAACN;oBAAQK;gBAAa;QAC9E;WACIJ,QAAQM,aAAa,GACrB;YACE;gBACEL,QAAQ;gBACRC,MAAM,GAAGL,iBAAiB,gCAAgC,CAAC;gBAC3DM,QAAQ,IAAMI;YAChB;SACD,GACD,EAAE;KACP;AACH;AAEA;;;;CAIC,GACD,SAASF,yBAAyBG,KAGjC;IACC,MAAM,EAACT,MAAM,EAAEK,aAAa,EAAC,GAAGI;IAChC,MAAMC,UAAUV,OAAOW,MAAM,CAC1BC,GAAG,CAAC,CAACC,OAAOC,QAAU,CAAC,aAAa,EAAEA,MAAM,MAAM,EAAEC,KAAKC,SAAS,CAACX,cAAcQ,MAAMI,GAAG,IAAI,EAC9FC,IAAI,CAAC;IACR,MAAMC,UAAUnB,OAAOW,MAAM,CAC1BC,GAAG,CACF,CAACC,OAAOC,QACN,CAAC,WAAW,EAAEC,KAAKC,SAAS,CAACH,MAAMO,IAAI,EAAE,SAAS,EAAEL,KAAKC,SAAS,CAACH,MAAMQ,KAAK,EAAE,EAAE,CAAC,GACnF,CAAC,QAAQ,EAAEN,KAAKC,SAAS,CAACM,QAAQT,MAAMU,MAAM,GAAG,gBAAgB,EAAET,MAAM,EAAE,CAAC,EAE/EI,IAAI,CAAC;IACR,OAAO,CAAC;;;AAGV,EAAER,QAAQ;;oBAEU,EAAEK,KAAKC,SAAS,CAACrB,0BAA0B;uBACxC,EAAEC,sCAAsC;;;AAG/D,EAAEuB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CV,CAAC;AACD;AAEA;;;;CAIC,GACD,SAASX;IACP,OAAO,CAAC;;;cAGI,EAAEO,KAAKC,SAAS,CAACnB,qCAAqC;AACpE,CAAC;AACD"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Whether this build is a Media Library config app — an app whose manifest
3
+ * declares a `config` expose of `appType: 'media-library'` (aspect field
4
+ * definitions the Media Library host loads through Module Federation).
5
+ *
6
+ * The one predicate the shared build code branches on for Media Library
7
+ * behavior (the island-runtime expose, the sui reset strip, fields HMR);
8
+ * everything behind the branch lives under `configs/`. Keyed on the config's
9
+ * `appType` discriminant, so a future second config type adds its own
10
+ * predicate instead of silently matching this one.
11
+ */ export function isMediaLibraryConfigApp(exposes) {
12
+ return exposes?.config?.appType === 'media-library';
13
+ }
14
+
15
+ //# sourceMappingURL=configApp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/actions/build/configs/configApp.ts"],"sourcesContent":["import {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\n\n/**\n * Whether this build is a Media Library config app — an app whose manifest\n * declares a `config` expose of `appType: 'media-library'` (aspect field\n * definitions the Media Library host loads through Module Federation).\n *\n * The one predicate the shared build code branches on for Media Library\n * behavior (the island-runtime expose, the sui reset strip, fields HMR);\n * everything behind the branch lives under `configs/`. Keyed on the config's\n * `appType` discriminant, so a future second config type adds its own\n * predicate instead of silently matching this one.\n */\nexport function isMediaLibraryConfigApp(exposes: WorkbenchExposes | undefined): boolean {\n return exposes?.config?.appType === 'media-library'\n}\n"],"names":["isMediaLibraryConfigApp","exposes","config","appType"],"mappings":"AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASA,wBAAwBC,OAAqC;IAC3E,OAAOA,SAASC,QAAQC,YAAY;AACtC"}
@@ -0,0 +1,25 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
3
+ /**
4
+ * The `sanity` package entry carrying the Media Library island-mount runtime
5
+ * (`mountIsland`). The generated `./media-library-island-runtime` federation
6
+ * expose re-exports it, so the runtime is bundled into the config app's
7
+ * remote from the app's own `sanity` install — whichever version the app
8
+ * installs brings a matching runtime.
9
+ */ export const MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE = 'sanity/media-library-island-runtime';
10
+ /**
11
+ * Whether the config app's installed `sanity` ships the island runtime entry.
12
+ * Older `sanity` versions don't; exposing a module whose import can never
13
+ * resolve would fail the whole build, so the expose is skipped (with a
14
+ * warning) and the Media Library host falls back to its degraded rendering
15
+ * for custom inputs.
16
+ */ export function hasMediaLibraryIslandRuntime(appRoot) {
17
+ try {
18
+ createRequire(path.join(appRoot, 'package.json')).resolve(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE);
19
+ return true;
20
+ } catch {
21
+ return false;
22
+ }
23
+ }
24
+
25
+ //# sourceMappingURL=mediaLibraryIslandRuntime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/actions/build/configs/mediaLibraryIslandRuntime.ts"],"sourcesContent":["import {createRequire} from 'node:module'\nimport path from 'node:path'\n\n/**\n * The `sanity` package entry carrying the Media Library island-mount runtime\n * (`mountIsland`). The generated `./media-library-island-runtime` federation\n * expose re-exports it, so the runtime is bundled into the config app's\n * remote from the app's own `sanity` install — whichever version the app\n * installs brings a matching runtime.\n */\nexport const MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE = 'sanity/media-library-island-runtime'\n\n/**\n * Whether the config app's installed `sanity` ships the island runtime entry.\n * Older `sanity` versions don't; exposing a module whose import can never\n * resolve would fail the whole build, so the expose is skipped (with a\n * warning) and the Media Library host falls back to its degraded rendering\n * for custom inputs.\n */\nexport function hasMediaLibraryIslandRuntime(appRoot: string): boolean {\n try {\n createRequire(path.join(appRoot, 'package.json')).resolve(MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE)\n return true\n } catch {\n return false\n }\n}\n"],"names":["createRequire","path","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","hasMediaLibraryIslandRuntime","appRoot","join","resolve"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AACzC,OAAOC,UAAU,YAAW;AAE5B;;;;;;CAMC,GACD,OAAO,MAAMC,sCAAsC,sCAAqC;AAExF;;;;;;CAMC,GACD,OAAO,SAASC,6BAA6BC,OAAe;IAC1D,IAAI;QACFJ,cAAcC,KAAKI,IAAI,CAACD,SAAS,iBAAiBE,OAAO,CAACJ;QAC1D,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
@@ -1,4 +1,5 @@
1
1
  import { SERVICE_CONTRACT_VERSION } from '../../../contract.js';
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';
2
3
  /** Subdirectory under the federation runtime dir where service artifacts live. */ const SERVICES_DIR_NAME = 'services';
3
4
  const SERVICE_TYPES = [
4
5
  'worker'
@@ -33,7 +34,8 @@ const SERVICE_TYPES = [
33
34
  * Source for one service's **worker** bundle — the Web Worker entry. Imports
34
35
  * the user's `unstable_defineService` result and runs its callback with the
35
36
  * service's own declaration (mirroring how a view component receives its
36
- * `view`), then wires the returned disposer to the host's terminate message.
37
+ * `view`) and a message bus client (`workerBus.ts`), then wires the returned
38
+ * disposer to the host's terminate message.
37
39
  * Crashes — and the worker's `console.*`, which is patched to forward to the
38
40
  * host — are surfaced through the host logger (the host owns logging; a worker's
39
41
  * own console isn't visible in the page DevTools anyway).
@@ -42,6 +44,7 @@ const SERVICE_TYPES = [
42
44
  // This file is auto-generated on 'sanity build' / 'sanity dev'
43
45
  // Modifications to this file are automatically discarded
44
46
  import service from ${JSON.stringify(input.importPath)}
47
+ import { createWorkerBus } from ${JSON.stringify(WORKER_BUS_ENTRY)}
45
48
 
46
49
  const SERVICE = { type: ${JSON.stringify(input.service.type)}, name: ${JSON.stringify(input.service.name)} }
47
50
 
@@ -63,17 +66,24 @@ for (const __level of ['log', 'info', 'warn', 'error', 'debug']) {
63
66
  }
64
67
  }
65
68
 
69
+ const { bus, close: closeBus, receive: receiveBus } = createWorkerBus()
70
+
66
71
  let dispose
67
72
  try {
68
- const result = service.run({ service: SERVICE })
73
+ const result = service.run({ bus, service: SERVICE })
69
74
  if (typeof result === 'function') dispose = result
70
75
  } catch (error) {
71
76
  self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(error) } })
72
77
  }
73
78
 
74
79
  self.addEventListener('message', (event) => {
75
- if (event.data && event.data.kind === 'workbench.worker.terminate') {
80
+ if (!event.data) return
81
+ if (event.data.kind === 'workbench.worker.terminate') {
82
+ // Close the bus first: the host has disconnected, so the disposer's bus calls must fail at once.
83
+ closeBus()
76
84
  try { dispose && dispose() } finally { self.close() }
85
+ } else {
86
+ receiveBus(event.data)
77
87
  }
78
88
  })
79
89
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/services/artifact.ts"],"sourcesContent":["import {SERVICE_CONTRACT_VERSION, type ServiceType} from '../../../contract.js'\nimport {type GeneratedArtifact} from '../artifact.js'\n\n/** Subdirectory under the federation runtime dir where service artifacts live. */\nconst SERVICES_DIR_NAME = 'services'\n\nconst SERVICE_TYPES: readonly ServiceType[] = ['worker']\n\n/**\n * A service to generate a worker artifact for. The `src` file default-exports\n * an `unstable_defineService(...)` result; the build emits a self-contained Web\n * Worker bundle plus a loader module that hands the host its URL.\n * @internal\n */\nexport interface ServiceArtifact {\n /** Service name, unique within the app. */\n name: string\n /** Path to the service `src` file, relative to the app root (or absolute). */\n src: string\n /** Service type, e.g. `\"worker\"`. */\n type: string\n}\n\n/**\n * Expand each service 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 serviceArtifacts(services: readonly ServiceArtifact[]): GeneratedArtifact[] {\n return services\n .filter((service) => (SERVICE_TYPES as readonly string[]).includes(service.type))\n .flatMap((service): GeneratedArtifact[] => {\n const dir = `${SERVICES_DIR_NAME}/${service.name}`\n return [\n {\n path: `${dir}/worker.js`,\n source: ({resolveImport}) =>\n serviceWorkerArtifactSource({\n importPath: resolveImport(service.src),\n service,\n }),\n },\n {\n expose: `./${dir}`,\n path: `${dir}/index.js`,\n source: () => serviceLoaderArtifactSource({service}),\n },\n ]\n })\n}\n\n/**\n * Source for one service's **worker** bundle — the Web Worker entry. Imports\n * the user's `unstable_defineService` result and runs its callback with the\n * service's own declaration (mirroring how a view component receives its\n * `view`), then wires the returned 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 serviceWorkerArtifactSource(input: {\n importPath: string\n service: {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 service from ${JSON.stringify(input.importPath)}\n\nconst SERVICE = { type: ${JSON.stringify(input.service.type)}, name: ${JSON.stringify(input.service.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// service (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\nlet dispose\ntry {\n const result = service.run({ service: SERVICE })\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 && event.data.kind === 'workbench.worker.terminate') {\n try { dispose && dispose() } finally { self.close() }\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 service's **loader** — the module-federation expose. Hands the\n * host the worker bundle's URL (via Vite `?worker&url`) plus the service'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 serviceLoaderArtifactSource(input: {service: {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/** Service type and contract version, surfaced for the host to dispatch on. */\nexport const type = ${JSON.stringify(input.service.type)}\nexport const name = ${JSON.stringify(input.service.name)}\nexport const version = ${SERVICE_CONTRACT_VERSION}\n`\n}\n"],"names":["SERVICE_CONTRACT_VERSION","SERVICES_DIR_NAME","SERVICE_TYPES","serviceArtifacts","services","filter","service","includes","type","flatMap","dir","name","path","source","resolveImport","serviceWorkerArtifactSource","importPath","src","expose","serviceLoaderArtifactSource","input","JSON","stringify"],"mappings":"AAAA,SAAQA,wBAAwB,QAAyB,uBAAsB;AAG/E,gFAAgF,GAChF,MAAMC,oBAAoB;AAE1B,MAAMC,gBAAwC;IAAC;CAAS;AAiBxD;;;;;CAKC,GACD,OAAO,SAASC,iBAAiBC,QAAoC;IACnE,OAAOA,SACJC,MAAM,CAAC,CAACC,UAAY,AAACJ,cAAoCK,QAAQ,CAACD,QAAQE,IAAI,GAC9EC,OAAO,CAAC,CAACH;QACR,MAAMI,MAAM,GAAGT,kBAAkB,CAAC,EAAEK,QAAQK,IAAI,EAAE;QAClD,OAAO;YACL;gBACEC,MAAM,GAAGF,IAAI,UAAU,CAAC;gBACxBG,QAAQ,CAAC,EAACC,aAAa,EAAC,GACtBC,4BAA4B;wBAC1BC,YAAYF,cAAcR,QAAQW,GAAG;wBACrCX;oBACF;YACJ;YACA;gBACEY,QAAQ,CAAC,EAAE,EAAER,KAAK;gBAClBE,MAAM,GAAGF,IAAI,SAAS,CAAC;gBACvBG,QAAQ,IAAMM,4BAA4B;wBAACb;oBAAO;YACpD;SACD;IACH;AACJ;AAEA;;;;;;;;CAQC,GACD,SAASS,4BAA4BK,KAGpC;IACC,OAAO,CAAC;;;oBAGU,EAAEC,KAAKC,SAAS,CAACF,MAAMJ,UAAU,EAAE;;wBAE/B,EAAEK,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE,QAAQ,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C1G,CAAC;AACD;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAASQ,4BAA4BC,KAA8C;IACjF,OAAO,CAAC;;;;;;;;oBAQU,EAAEC,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE;oBACrC,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;uBAClC,EAAEX,yBAAyB;AAClD,CAAC;AACD"}
1
+ {"version":3,"sources":["../../../../src/actions/build/services/artifact.ts"],"sourcesContent":["import {SERVICE_CONTRACT_VERSION, type ServiceType} 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 where service artifacts live. */\nconst SERVICES_DIR_NAME = 'services'\n\nconst SERVICE_TYPES: readonly ServiceType[] = ['worker']\n\n/**\n * A service to generate a worker artifact for. The `src` file default-exports\n * an `unstable_defineService(...)` result; the build emits a self-contained Web\n * Worker bundle plus a loader module that hands the host its URL.\n * @internal\n */\nexport interface ServiceArtifact {\n /** Service name, unique within the app. */\n name: string\n /** Path to the service `src` file, relative to the app root (or absolute). */\n src: string\n /** Service type, e.g. `\"worker\"`. */\n type: string\n}\n\n/**\n * Expand each service 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 serviceArtifacts(services: readonly ServiceArtifact[]): GeneratedArtifact[] {\n return services\n .filter((service) => (SERVICE_TYPES as readonly string[]).includes(service.type))\n .flatMap((service): GeneratedArtifact[] => {\n const dir = `${SERVICES_DIR_NAME}/${service.name}`\n return [\n {\n path: `${dir}/worker.js`,\n source: ({resolveImport}) =>\n serviceWorkerArtifactSource({\n importPath: resolveImport(service.src),\n service,\n }),\n },\n {\n expose: `./${dir}`,\n path: `${dir}/index.js`,\n source: () => serviceLoaderArtifactSource({service}),\n },\n ]\n })\n}\n\n/**\n * Source for one service's **worker** bundle — the Web Worker entry. Imports\n * the user's `unstable_defineService` result and runs its callback with the\n * service'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 serviceWorkerArtifactSource(input: {\n importPath: string\n service: {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 service from ${JSON.stringify(input.importPath)}\nimport { createWorkerBus } from ${JSON.stringify(WORKER_BUS_ENTRY)}\n\nconst SERVICE = { type: ${JSON.stringify(input.service.type)}, name: ${JSON.stringify(input.service.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// service (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 const result = service.run({ bus, service: SERVICE })\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 service's **loader** — the module-federation expose. Hands the\n * host the worker bundle's URL (via Vite `?worker&url`) plus the service'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 serviceLoaderArtifactSource(input: {service: {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/** Service type and contract version, surfaced for the host to dispatch on. */\nexport const type = ${JSON.stringify(input.service.type)}\nexport const name = ${JSON.stringify(input.service.name)}\nexport const version = ${SERVICE_CONTRACT_VERSION}\n`\n}\n"],"names":["SERVICE_CONTRACT_VERSION","WORKER_BUS_ENTRY","SERVICES_DIR_NAME","SERVICE_TYPES","serviceArtifacts","services","filter","service","includes","type","flatMap","dir","name","path","source","resolveImport","serviceWorkerArtifactSource","importPath","src","expose","serviceLoaderArtifactSource","input","JSON","stringify"],"mappings":"AAAA,SAAQA,wBAAwB,QAAyB,uBAAsB;AAG/E,yGAAyG,GACzG,OAAO,MAAMC,mBAAmB,6CAA4C;AAE5E,gFAAgF,GAChF,MAAMC,oBAAoB;AAE1B,MAAMC,gBAAwC;IAAC;CAAS;AAiBxD;;;;;CAKC,GACD,OAAO,SAASC,iBAAiBC,QAAoC;IACnE,OAAOA,SACJC,MAAM,CAAC,CAACC,UAAY,AAACJ,cAAoCK,QAAQ,CAACD,QAAQE,IAAI,GAC9EC,OAAO,CAAC,CAACH;QACR,MAAMI,MAAM,GAAGT,kBAAkB,CAAC,EAAEK,QAAQK,IAAI,EAAE;QAClD,OAAO;YACL;gBACEC,MAAM,GAAGF,IAAI,UAAU,CAAC;gBACxBG,QAAQ,CAAC,EAACC,aAAa,EAAC,GACtBC,4BAA4B;wBAC1BC,YAAYF,cAAcR,QAAQW,GAAG;wBACrCX;oBACF;YACJ;YACA;gBACEY,QAAQ,CAAC,EAAE,EAAER,KAAK;gBAClBE,MAAM,GAAGF,IAAI,SAAS,CAAC;gBACvBG,QAAQ,IAAMM,4BAA4B;wBAACb;oBAAO;YACpD;SACD;IACH;AACJ;AAEA;;;;;;;;;CASC,GACD,SAASS,4BAA4BK,KAGpC;IACC,OAAO,CAAC;;;oBAGU,EAAEC,KAAKC,SAAS,CAACF,MAAMJ,UAAU,EAAE;gCACvB,EAAEK,KAAKC,SAAS,CAACtB,kBAAkB;;wBAE3C,EAAEqB,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE,QAAQ,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoD1G,CAAC;AACD;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAASQ,4BAA4BC,KAA8C;IACjF,OAAO,CAAC;;;;;;;;oBAQU,EAAEC,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE;oBACrC,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;uBAClC,EAAEZ,yBAAyB;AAClD,CAAC;AACD"}
@@ -0,0 +1,159 @@
1
+ // Runs inside the service's Web Worker, bundled by Vite from the generated
2
+ // `worker.js`. Keep it free of Node and of runtime imports: `@sanity/sdk` is
3
+ // only ever imported for types.
4
+ const DEFAULT_TIMEOUT_MS = 5000;
5
+ // Mirrors the SDK's MessageBusError: importing the class would pull the SDK
6
+ // runtime into the worker bundle.
7
+ const busError = (code, message)=>Object.assign(new Error(message || code), {
8
+ code,
9
+ name: 'MessageBusError'
10
+ });
11
+ /**
12
+ * The worker's side of the `workbench.bus.*` wire contract. The host relays
13
+ * each request to the Dashboard bus and stamps it with the worker's identity,
14
+ * so the client only tracks ids.
15
+ * @internal
16
+ */ export function createWorkerBus() {
17
+ const pending = new Map();
18
+ const subscriptions = new Map();
19
+ let nextId = 0;
20
+ let closed = false;
21
+ // Posts a request and returns a function that creates its promise on first
22
+ // call. Until then a reply, even an error, is only held: a rejected promise
23
+ // nobody awaits would reach the worker's 'unhandledrejection' forwarder as a crash.
24
+ function request(message, options = {}) {
25
+ const { signal, timeout } = options;
26
+ const id = ++nextId;
27
+ let outcome;
28
+ let onOutcome;
29
+ let timer;
30
+ const settle = (result)=>{
31
+ if (outcome) return;
32
+ outcome = result;
33
+ clearTimeout(timer);
34
+ pending.delete(id);
35
+ signal?.removeEventListener('abort', onAbort);
36
+ onOutcome?.(result);
37
+ };
38
+ const onAbort = ()=>{
39
+ self.postMessage({
40
+ id,
41
+ kind: 'workbench.bus.abort'
42
+ });
43
+ settle({
44
+ error: busError('ABORTED'),
45
+ ok: false
46
+ });
47
+ };
48
+ if (closed || signal?.aborted) {
49
+ outcome = {
50
+ error: busError('ABORTED'),
51
+ ok: false
52
+ };
53
+ } else {
54
+ // An omitted timeout must stay absent on the wire, so the host applies its default.
55
+ self.postMessage(timeout === undefined ? {
56
+ ...message,
57
+ id
58
+ } : {
59
+ ...message,
60
+ id,
61
+ timeout
62
+ });
63
+ pending.set(id, settle);
64
+ // A host that predates the bus never replies; time out here too so the call still settles.
65
+ if (timeout !== null) {
66
+ timer = setTimeout(()=>settle({
67
+ error: busError('TIMEOUT'),
68
+ ok: false
69
+ }), timeout ?? DEFAULT_TIMEOUT_MS);
70
+ }
71
+ signal?.addEventListener('abort', onAbort, {
72
+ once: true
73
+ });
74
+ }
75
+ let promise;
76
+ return ()=>promise ??= new Promise((resolve, reject)=>{
77
+ onOutcome = (result)=>result.ok ? resolve(result.value) : reject(result.error);
78
+ if (outcome) onOutcome(outcome);
79
+ });
80
+ }
81
+ const bus = {
82
+ emit: (topic, payload, options)=>{
83
+ const awaitReply = request({
84
+ kind: 'workbench.bus.emit',
85
+ payload,
86
+ topic
87
+ }, options);
88
+ const result = {
89
+ catch: (onRejected)=>awaitReply().then(undefined, onRejected),
90
+ finally: (onFinally)=>awaitReply().finally(onFinally),
91
+ // eslint-disable-next-line unicorn/no-thenable -- awaiting arms reply failure handling; fire-and-forget does not.
92
+ then: (onFulfilled, onRejected)=>awaitReply().then(onFulfilled, onRejected)
93
+ };
94
+ return result;
95
+ },
96
+ query: (topic, options)=>request({
97
+ kind: 'workbench.bus.query',
98
+ topic
99
+ }, options)(),
100
+ subscribe: (topic, handler, options)=>{
101
+ if (closed) throw busError('ABORTED');
102
+ const signal = options?.signal;
103
+ if (signal?.aborted) return;
104
+ const id = ++nextId;
105
+ self.postMessage({
106
+ id,
107
+ kind: 'workbench.bus.subscribe',
108
+ topic
109
+ });
110
+ subscriptions.set(id, handler);
111
+ signal?.addEventListener('abort', ()=>{
112
+ if (subscriptions.delete(id)) self.postMessage({
113
+ id,
114
+ kind: 'workbench.bus.abort'
115
+ });
116
+ }, {
117
+ once: true
118
+ });
119
+ }
120
+ };
121
+ return {
122
+ // The topic generics only exist at the call site; the wire carries plain strings.
123
+ bus: bus,
124
+ close: ()=>{
125
+ closed = true;
126
+ subscriptions.clear();
127
+ for (const settle of pending.values())settle({
128
+ error: busError('ABORTED'),
129
+ ok: false
130
+ });
131
+ },
132
+ receive: (data)=>{
133
+ const message = data;
134
+ if (message.kind === 'workbench.bus.value') {
135
+ subscriptions.get(message.id)?.(message.value);
136
+ } else if (message.kind === 'workbench.bus.reply') {
137
+ const settle = pending.get(message.id);
138
+ if (message.ok) {
139
+ settle?.({
140
+ ok: true,
141
+ value: message.value
142
+ });
143
+ return;
144
+ }
145
+ // A refused subscription has no promise to reject, so tell the author through the host logger.
146
+ if (subscriptions.delete(message.id)) {
147
+ // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger
148
+ console.error(`Message bus subscription refused: ${message.error.code}: ${message.error.message}`);
149
+ }
150
+ settle?.({
151
+ error: busError(message.error.code, message.error.message),
152
+ ok: false
153
+ });
154
+ }
155
+ }
156
+ };
157
+ }
158
+
159
+ //# sourceMappingURL=workerBus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/actions/build/services/workerBus.ts"],"sourcesContent":["// Runs inside the service'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 {type MessageBusEmitResult, type MessageBusErrorCode} from '@sanity/sdk/dashboard'\n\nimport {type ServiceBus} from '../../../defineService.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 HostMessage =\n | {\n error: {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// Mirrors the SDK's MessageBusError: importing the class would pull the SDK\n// runtime into the worker bundle.\nconst busError = (code: MessageBusErrorCode, message?: string): Error =>\n Object.assign(new Error(message || code), {code, name: 'MessageBusError'})\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 service 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: ServiceBus\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 const subscriptions = new Map<number, (value: unknown) => void>()\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 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) => void, 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 ServiceBus,\n close: () => {\n closed = true\n subscriptions.clear()\n for (const settle of pending.values()) settle({error: busError('ABORTED'), ok: false})\n },\n receive: (data) => {\n const message = data as HostMessage\n if (message.kind === 'workbench.bus.value') {\n subscriptions.get(message.id)?.(message.value)\n } else if (message.kind === '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, so tell the author through the host logger.\n if (subscriptions.delete(message.id)) {\n // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger\n console.error(\n `Message bus subscription refused: ${message.error.code}: ${message.error.message}`,\n )\n }\n settle?.({error: busError(message.error.code, message.error.message), ok: false})\n }\n },\n }\n}\n"],"names":["DEFAULT_TIMEOUT_MS","busError","code","message","Object","assign","Error","name","createWorkerBus","pending","Map","subscriptions","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","bus","emit","topic","payload","awaitReply","catch","onRejected","then","finally","onFinally","onFulfilled","query","subscribe","handler","close","clear","values","receive","data","get","console"],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,gCAAgC;AAKhC,MAAMA,qBAAqB;AAmB3B,4EAA4E;AAC5E,kCAAkC;AAClC,MAAMC,WAAW,CAACC,MAA2BC,UAC3CC,OAAOC,MAAM,CAAC,IAAIC,MAAMH,WAAWD,OAAO;QAACA;QAAMK,MAAM;IAAiB;AAE1E;;;;;CAKC,GACD,OAAO,SAASC;IAoBd,MAAMC,UAAU,IAAIC;IACpB,MAAMC,gBAAgB,IAAID;IAC1B,IAAIE,SAAS;IACb,IAAIC,SAAS;IAEb,2EAA2E;IAC3E,4EAA4E;IAC5E,oFAAoF;IACpF,SAASC,QAAQX,OAAgC,EAAEY,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;YACbZ,QAAQgB,MAAM,CAACP;YACfF,QAAQU,oBAAoB,SAASC;YACrCP,YAAYG;QACd;QACA,MAAMI,UAAU;YACdC,KAAKC,WAAW,CAAC;gBAACX;gBAAIY,MAAM;YAAqB;YACjDR,OAAO;gBAACS,OAAO9B,SAAS;gBAAY+B,IAAI;YAAK;QAC/C;QAEA,IAAInB,UAAUG,QAAQiB,SAAS;YAC7Bd,UAAU;gBAACY,OAAO9B,SAAS;gBAAY+B,IAAI;YAAK;QAClD,OAAO;YACL,oFAAoF;YACpFJ,KAAKC,WAAW,CAACZ,YAAYiB,YAAY;gBAAC,GAAG/B,OAAO;gBAAEe;YAAE,IAAI;gBAAC,GAAGf,OAAO;gBAAEe;gBAAID;YAAO;YACpFR,QAAQ0B,GAAG,CAACjB,IAAII;YAChB,2FAA2F;YAC3F,IAAIL,YAAY,MAAM;gBACpBI,QAAQe,WACN,IAAMd,OAAO;wBAACS,OAAO9B,SAAS;wBAAY+B,IAAI;oBAAK,IACnDf,WAAWjB;YAEf;YACAgB,QAAQqB,iBAAiB,SAASV,SAAS;gBAACW,MAAM;YAAI;QACxD;QAEA,IAAIC;QACJ,OAAO,IACJA,YAAY,IAAIC,QAAQ,CAACC,SAASC;gBACjCtB,YAAY,CAACG,SAAYA,OAAOS,EAAE,GAAGS,QAAQlB,OAAOoB,KAAK,IAAID,OAAOnB,OAAOQ,KAAK;gBAChF,IAAIZ,SAASC,UAAUD;YACzB;IACJ;IAEA,MAAMyB,MAAM;QACVC,MAAM,CAACC,OAAeC,SAAmBhC;YACvC,MAAMiC,aAAalC,QAAQ;gBAACgB,MAAM;gBAAsBiB;gBAASD;YAAK,GAAG/B;YACzE,MAAMQ,SAAwC;gBAC5C0B,OAAO,CAACC,aAAeF,aAAaG,IAAI,CAACjB,WAAWgB;gBACpDE,SAAS,CAACC,YAAcL,aAAaI,OAAO,CAACC;gBAC7C,kHAAkH;gBAClHF,MAAM,CAACG,aAAaJ,aAAeF,aAAaG,IAAI,CAACG,aAAaJ;YACpE;YACA,OAAO3B;QACT;QACAgC,OAAO,CAACT,OAAe/B,UACrBD,QAAQ;gBAACgB,MAAM;gBAAuBgB;YAAK,GAAG/B;QAChDyC,WAAW,CAACV,OAAeW,SAAmC1C;YAC5D,IAAIF,QAAQ,MAAMZ,SAAS;YAC3B,MAAMe,SAASD,SAASC;YACxB,IAAIA,QAAQiB,SAAS;YACrB,MAAMf,KAAK,EAAEN;YACbgB,KAAKC,WAAW,CAAC;gBAACX;gBAAIY,MAAM;gBAA2BgB;YAAK;YAC5DnC,cAAcwB,GAAG,CAACjB,IAAIuC;YACtBzC,QAAQqB,iBACN,SACA;gBACE,IAAI1B,cAAcc,MAAM,CAACP,KAAKU,KAAKC,WAAW,CAAC;oBAACX;oBAAIY,MAAM;gBAAqB;YACjF,GACA;gBAACQ,MAAM;YAAI;QAEf;IACF;IAEA,OAAO;QACL,kFAAkF;QAClFM,KAAKA;QACLc,OAAO;YACL7C,SAAS;YACTF,cAAcgD,KAAK;YACnB,KAAK,MAAMrC,UAAUb,QAAQmD,MAAM,GAAItC,OAAO;gBAACS,OAAO9B,SAAS;gBAAY+B,IAAI;YAAK;QACtF;QACA6B,SAAS,CAACC;YACR,MAAM3D,UAAU2D;YAChB,IAAI3D,QAAQ2B,IAAI,KAAK,uBAAuB;gBAC1CnB,cAAcoD,GAAG,CAAC5D,QAAQe,EAAE,IAAIf,QAAQwC,KAAK;YAC/C,OAAO,IAAIxC,QAAQ2B,IAAI,KAAK,uBAAuB;gBACjD,MAAMR,SAASb,QAAQsD,GAAG,CAAC5D,QAAQe,EAAE;gBACrC,IAAIf,QAAQ6B,EAAE,EAAE;oBACdV,SAAS;wBAACU,IAAI;wBAAMW,OAAOxC,QAAQwC,KAAK;oBAAA;oBACxC;gBACF;gBACA,+FAA+F;gBAC/F,IAAIhC,cAAcc,MAAM,CAACtB,QAAQe,EAAE,GAAG;oBACpC,4FAA4F;oBAC5F8C,QAAQjC,KAAK,CACX,CAAC,kCAAkC,EAAE5B,QAAQ4B,KAAK,CAAC7B,IAAI,CAAC,EAAE,EAAEC,QAAQ4B,KAAK,CAAC5B,OAAO,EAAE;gBAEvF;gBACAmB,SAAS;oBAACS,OAAO9B,SAASE,QAAQ4B,KAAK,CAAC7B,IAAI,EAAEC,QAAQ4B,KAAK,CAAC5B,OAAO;oBAAG6B,IAAI;gBAAK;YACjF;QACF;IACF;AACF"}
@@ -1,5 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { isMediaLibraryConfigApp } from '../configs/configApp.js';
4
+ import { hasMediaLibraryIslandRuntime, MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE } from '../configs/mediaLibraryIslandRuntime.js';
3
5
  /**
4
6
  * React APIs only the generated render-contract modules import — the SPA
5
7
  * bootstrap (`getEntryModule`) and every render artifact (`renderRemote`)
@@ -71,12 +73,20 @@ import path from 'node:path';
71
73
  const resolved = resolveSourceFile(absPath);
72
74
  return path.relative(cwd, resolved).split(path.sep).join('/');
73
75
  });
76
+ // The generated `./island-runtime` expose imports this entry, but the file is
77
+ // codegen (never in `entries`), so the startup scan misses it. Only when the
78
+ // installed `sanity` ships the entry — an unresolvable `include` name crashes
79
+ // the dev server, and the expose is skipped in that case anyway.
80
+ const islandRuntimeDeps = isMediaLibraryConfigApp(exposes) && hasMediaLibraryIslandRuntime(cwd) ? [
81
+ MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE
82
+ ] : [];
74
83
  return {
75
84
  entries: [
76
85
  ...new Set(entries)
77
86
  ],
78
87
  include: [
79
- ...RENDER_CONTRACT_DEPS
88
+ ...RENDER_CONTRACT_DEPS,
89
+ ...islandRuntimeDeps
80
90
  ]
81
91
  };
82
92
  }
@@ -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'\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 return {\n entries: [...new Set(entries)],\n include: [...RENDER_CONTRACT_DEPS],\n }\n}\n"],"names":["fs","path","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","Set","include"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAI5B;;;;;;;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,IAAIL,GAAGM,UAAU,CAACD,YAAYL,GAAGO,QAAQ,CAACF,SAASG,MAAM,IAAI,OAAOH;IACpE,KAAK,MAAMI,aAAaN,kBAAmB;QACzC,IAAIH,GAAGM,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,MAAQlB,KAAKwB,OAAO,CAACZ,KAAKM;IAEjC,MAAMO,UAAU;WAAId;WAAeG;KAAiB,CAACE,GAAG,CAAC,CAACZ;QACxD,MAAMsB,WAAWvB,kBAAkBC;QACnC,OAAOJ,KAAK2B,QAAQ,CAACf,KAAKc,UAAUE,KAAK,CAAC5B,KAAK6B,GAAG,EAAEC,IAAI,CAAC;IAC3D;IAEA,OAAO;QACLL,SAAS;eAAI,IAAIM,IAAIN;SAAS;QAC9BO,SAAS;eAAI/B;SAAqB;IACpC;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 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","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"}