@sanity/workbench-cli 2.9.0 → 2.11.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 (33) hide show
  1. package/dist/_exports/_internal_worker_bus.d.ts +1 -1
  2. package/dist/_exports/build.d.ts +2 -2
  3. package/dist/_exports/build.js +1 -1
  4. package/dist/_exports/build.js.map +1 -1
  5. package/dist/_exports/{defineService-C1MhDwmh.d.ts → defineService-DUaxVpWq.d.ts} +32 -10
  6. package/dist/_exports/deploy.d.ts +2 -2
  7. package/dist/_exports/index.d.ts +1 -1
  8. package/dist/_exports/{resolveWorkbenchConfig-s3msa3Hu.d.ts → resolveWorkbenchConfig-DEttN7ks.d.ts} +7 -2
  9. package/dist/_exports/{summarizeInterfaces-C0TCOa0J.d.ts → summarizeInterfaces-Co97VU2z.d.ts} +2 -2
  10. package/dist/_exports/undeploy.d.ts +2 -2
  11. package/dist/actions/build/artifact.js +3 -3
  12. package/dist/actions/build/artifact.js.map +1 -1
  13. package/dist/actions/build/configs/artifact.js +70 -5
  14. package/dist/actions/build/configs/artifact.js.map +1 -1
  15. package/dist/actions/build/configs/configApp.js +15 -0
  16. package/dist/actions/build/configs/configApp.js.map +1 -0
  17. package/dist/actions/build/configs/mediaLibraryIslandRuntime.js +25 -0
  18. package/dist/actions/build/configs/mediaLibraryIslandRuntime.js.map +1 -0
  19. package/dist/actions/build/services/workerBus.js +98 -20
  20. package/dist/actions/build/services/workerBus.js.map +1 -1
  21. package/dist/actions/build/vite/optimize-deps.js +11 -1
  22. package/dist/actions/build/vite/optimize-deps.js.map +1 -1
  23. package/dist/actions/build/vite/plugin.js +15 -1
  24. package/dist/actions/build/vite/plugin.js.map +1 -1
  25. package/dist/actions/build/vite/plugins/plugin-strip-sui-global-reset.js +82 -0
  26. package/dist/actions/build/vite/plugins/plugin-strip-sui-global-reset.js.map +1 -0
  27. package/dist/actions/build/vite/workbench-vite-plugins.js +13 -2
  28. package/dist/actions/build/vite/workbench-vite-plugins.js.map +1 -1
  29. package/dist/defineService.js +24 -3
  30. package/dist/defineService.js.map +1 -1
  31. package/dist/resolveWorkbenchApp.js +16 -0
  32. package/dist/resolveWorkbenchApp.js.map +1 -1
  33. package/package.json +3 -3
@@ -1,4 +1,4 @@
1
- import { n as ServiceBus } from "./defineService-C1MhDwmh.js";
1
+ import { n as ServiceBus } from "./defineService-DUaxVpWq.js";
2
2
  /**
3
3
  * The worker's side of the `workbench.bus.*` wire contract. The host relays
4
4
  * each request to the Dashboard bus and stamps it with the worker's identity,
@@ -1,4 +1,4 @@
1
- import { a as resolveWorkbenchApp, i as WorkbenchExposes, n as resolveWorkbenchConfig, r as ResolvedWorkbenchApp, t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-s3msa3Hu.js";
1
+ import { a as resolveAppEntry, i as WorkbenchExposes, n as resolveWorkbenchConfig, o as resolveWorkbenchApp, r as ResolvedWorkbenchApp, t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-DEttN7ks.js";
2
2
  import { InlineConfig, PluginOption } from "vite";
3
3
  /**
4
4
  * Resource bindings ride in a dedicated module in the app's bundle rather than an
@@ -114,5 +114,5 @@ declare function workbenchVitePlugins(options: WorkbenchViteOptions): Promise<Pl
114
114
  * its own id from the applications API.
115
115
  */
116
116
  declare function buildAppId(app: ResolvedWorkbenchApp): Promise<string>;
117
- export { RESOURCE_BINDINGS_CHUNK_NAME, RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE, RESOURCE_BINDINGS_TOKEN, type ResolvedMediaLibraryConfig, type WorkbenchExposes, buildAppId, buildFederatedApp, resolveWorkbenchApp, resolveWorkbenchConfig, resourceBindingsChunkFileName, resourceBindingsCodeSplittingGroup, workbenchOptimizeDeps, workbenchVitePlugins };
117
+ export { RESOURCE_BINDINGS_CHUNK_NAME, RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE, RESOURCE_BINDINGS_TOKEN, type ResolvedMediaLibraryConfig, type WorkbenchExposes, buildAppId, buildFederatedApp, resolveAppEntry, resolveWorkbenchApp, resolveWorkbenchConfig, resourceBindingsChunkFileName, resourceBindingsCodeSplittingGroup, workbenchOptimizeDeps, workbenchVitePlugins };
118
118
  //# sourceMappingURL=build.d.ts.map
@@ -8,7 +8,7 @@ export { buildFederatedApp } from '../actions/build/vite/discover-shared-depende
8
8
  export { workbenchOptimizeDeps } from '../actions/build/vite/optimize-deps.js';
9
9
  export { workbenchVitePlugins } from '../actions/build/vite/workbench-vite-plugins.js';
10
10
  export { buildAppId } from '../appId.js';
11
- export { resolveWorkbenchApp } from '../resolveWorkbenchApp.js';
11
+ export { resolveAppEntry, resolveWorkbenchApp } from '../resolveWorkbenchApp.js';
12
12
  export { resolveWorkbenchConfig } from '../resolveWorkbenchConfig.js';
13
13
 
14
14
  //# sourceMappingURL=build.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/build.ts"],"sourcesContent":["// Node-only build entry: the module-federation Vite plugins that\n// `@sanity/cli-build`'s `getViteConfig` swaps in for a workbench app, plus the\n// resolver the build reads declared views/web workers from. The build needs no\n// deploy-time guards, so it takes the bare `resolveWorkbenchApp` — the guarded\n// view (`getWorkbench`) is the deploy entry's export.\n\nexport {\n RESOURCE_BINDINGS_CHUNK_NAME,\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n RESOURCE_BINDINGS_TOKEN,\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../actions/build/resource-bindings.js'\nexport {buildFederatedApp} from '../actions/build/vite/discover-shared-dependencies.js'\nexport {workbenchOptimizeDeps} from '../actions/build/vite/optimize-deps.js'\nexport {workbenchVitePlugins} from '../actions/build/vite/workbench-vite-plugins.js'\nexport {buildAppId} from '../appId.js'\nexport {resolveWorkbenchApp, type WorkbenchExposes} from '../resolveWorkbenchApp.js'\nexport {type ResolvedMediaLibraryConfig, resolveWorkbenchConfig} from '../resolveWorkbenchConfig.js'\n"],"names":["RESOURCE_BINDINGS_CHUNK_NAME","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","RESOURCE_BINDINGS_TOKEN","resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","buildFederatedApp","workbenchOptimizeDeps","workbenchVitePlugins","buildAppId","resolveWorkbenchApp","resolveWorkbenchConfig"],"mappings":"AAAA,iEAAiE;AACjE,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,sDAAsD;AAEtD,SACEA,4BAA4B,EAC5BC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,EAC/BC,uBAAuB,EACvBC,6BAA6B,EAC7BC,kCAAkC,QAC7B,wCAAuC;AAC9C,SAAQC,iBAAiB,QAAO,wDAAuD;AACvF,SAAQC,qBAAqB,QAAO,yCAAwC;AAC5E,SAAQC,oBAAoB,QAAO,kDAAiD;AACpF,SAAQC,UAAU,QAAO,cAAa;AACtC,SAAQC,mBAAmB,QAA8B,4BAA2B;AACpF,SAAyCC,sBAAsB,QAAO,+BAA8B"}
1
+ {"version":3,"sources":["../../src/_exports/build.ts"],"sourcesContent":["// Node-only build entry: the module-federation Vite plugins that\n// `@sanity/cli-build`'s `getViteConfig` swaps in for a workbench app, plus the\n// resolver the build reads declared views/web workers from. The build needs no\n// deploy-time guards, so it takes the bare `resolveWorkbenchApp` — the guarded\n// view (`getWorkbench`) is the deploy entry's export.\n\nexport {\n RESOURCE_BINDINGS_CHUNK_NAME,\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n RESOURCE_BINDINGS_TOKEN,\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../actions/build/resource-bindings.js'\nexport {buildFederatedApp} from '../actions/build/vite/discover-shared-dependencies.js'\nexport {workbenchOptimizeDeps} from '../actions/build/vite/optimize-deps.js'\nexport {workbenchVitePlugins} from '../actions/build/vite/workbench-vite-plugins.js'\nexport {buildAppId} from '../appId.js'\nexport {\n resolveAppEntry,\n resolveWorkbenchApp,\n type WorkbenchExposes,\n} from '../resolveWorkbenchApp.js'\nexport {type ResolvedMediaLibraryConfig, resolveWorkbenchConfig} from '../resolveWorkbenchConfig.js'\n"],"names":["RESOURCE_BINDINGS_CHUNK_NAME","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","RESOURCE_BINDINGS_TOKEN","resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","buildFederatedApp","workbenchOptimizeDeps","workbenchVitePlugins","buildAppId","resolveAppEntry","resolveWorkbenchApp","resolveWorkbenchConfig"],"mappings":"AAAA,iEAAiE;AACjE,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,sDAAsD;AAEtD,SACEA,4BAA4B,EAC5BC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,EAC/BC,uBAAuB,EACvBC,6BAA6B,EAC7BC,kCAAkC,QAC7B,wCAAuC;AAC9C,SAAQC,iBAAiB,QAAO,wDAAuD;AACvF,SAAQC,qBAAqB,QAAO,yCAAwC;AAC5E,SAAQC,oBAAoB,QAAO,kDAAiD;AACpF,SAAQC,UAAU,QAAO,cAAa;AACtC,SACEC,eAAe,EACfC,mBAAmB,QAEd,4BAA2B;AAClC,SAAyCC,sBAAsB,QAAO,+BAA8B"}
@@ -1,5 +1,5 @@
1
1
  import { l as SERVICE_CONTRACT_VERSION, u as ServiceType } from "./contract-D_HnLQtT.js";
2
- import { MessageBus, MessageBusAbortOptions, StateTopic, ValueOf } from "@sanity/sdk/dashboard";
2
+ import { EventTopic, MessageBus, MessageBusAbortOptions, MessageBusMessage, PayloadOf, ReplyOf, StateTopic, ValueOf } from "@sanity/sdk/dashboard";
3
3
  /**
4
4
  * The service's own declaration, surfaced to the callback.
5
5
  * @public
@@ -9,14 +9,15 @@ interface ServiceInfo {
9
9
  readonly type: string;
10
10
  }
11
11
  /**
12
- * The message bus as a service sees it: `emit` and `query` as in the SDK, and
13
- * `subscribe` for state topics only. Only Dashboard can respond to its event
14
- * topics, so a service has no reason to subscribe to them. There is no
15
- * `disconnect`: Dashboard owns the connection and ends it when it stops the
16
- * worker.
12
+ * The message bus as a service sees it: the SDK's `MessageBus` without the
13
+ * `subscribe` forms that return observables, which would make the service's
14
+ * project install rxjs. There is no `disconnect`: Dashboard owns the connection
15
+ * and ends it when it stops the worker.
17
16
  * @public
18
17
  */
19
18
  interface ServiceBus extends Omit<MessageBus, 'subscribe'> {
19
+ /** Runs a responder for each event until its signal aborts. */
20
+ subscribe<K extends EventTopic>(type: K, handler: (message: MessageBusMessage<PayloadOf<K>, ReplyOf<K>, K>) => void, options?: MessageBusAbortOptions): void;
20
21
  /** Runs a handler for each state value until its signal aborts. */
21
22
  subscribe<K extends StateTopic>(type: K, handler: (value: ValueOf<K>) => void, options?: MessageBusAbortOptions): void;
22
23
  }
@@ -57,9 +58,30 @@ interface DefinedService<TType extends ServiceType = ServiceType> {
57
58
  * The callback receives `bus`, its connection to the Dashboard message bus:
58
59
  * `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the
59
60
  * current value of a state topic, and `bus.subscribe` runs a handler on each
60
- * new value of a state topic until its `signal` aborts. A refused, unanswered
61
- * or timed-out request rejects with an `Error` named `MessageBusError` whose
62
- * `code` says why; it is not an instance of the SDK's `MessageBusError` class.
61
+ * new value of a state topic, or on each event of an event topic, until its
62
+ * `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects
63
+ * with an `Error` named `MessageBusError` whose `code` says why; it is not an
64
+ * instance of the SDK's `MessageBusError` class.
65
+ *
66
+ * An event handler answers the sender with `message.reply(value)` or refuses
67
+ * with `message.reject(reason)`; one that throws refuses with code
68
+ * `HANDLER_THREW`. For example, a service that keeps a snapshot for its app's
69
+ * views, which listen with `useWorker` first and then post to it. A view's post
70
+ * arrives on `workers.post` as `{name, payload}`, and `workers.message` reaches
71
+ * only this app's views:
72
+ *
73
+ * ```ts
74
+ * export default unstable_defineService('worker', ({bus}) => {
75
+ * const controller = new AbortController()
76
+ * bus.subscribe('workers.post', (message) => message.reply(snapshot), {
77
+ * signal: controller.signal,
78
+ * })
79
+ * // Views that are already listening post again.
80
+ * bus.emit('workers.message', {type: 'welcome'})
81
+ * return () => controller.abort()
82
+ * })
83
+ * ```
84
+ *
63
85
  * The callback can return a disposer, which runs when Dashboard stops the
64
86
  * worker. By then the bus is closed: subscriptions have ended, `emit` and
65
87
  * `query` reject with code `ABORTED`, and `subscribe` throws that error.
@@ -71,4 +93,4 @@ interface DefinedService<TType extends ServiceType = ServiceType> {
71
93
  */
72
94
  declare function unstable_defineService<TType extends ServiceType>(type: TType, run: ServiceCallbacksByType[TType]): DefinedService<TType>;
73
95
  export { ServiceInfo as a, ServiceContext as i, ServiceBus as n, unstable_defineService as o, ServiceCallback as r, DefinedService as t };
74
- //# sourceMappingURL=defineService-C1MhDwmh.d.ts.map
96
+ //# sourceMappingURL=defineService-DUaxVpWq.d.ts.map
@@ -1,6 +1,6 @@
1
1
  import "./contract-D_HnLQtT.js";
2
- import { n as resolveWorkbenchConfig, t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-s3msa3Hu.js";
3
- import { a as DeployableWorkbenchApp, i as summarizeInterfaces, n as DeployedView, o as getWorkbench, r as DeployedWebWorker, t as DeployedInterface } from "./summarizeInterfaces-C0TCOa0J.js";
2
+ import { n as resolveWorkbenchConfig, t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-DEttN7ks.js";
3
+ import { a as DeployableWorkbenchApp, i as summarizeInterfaces, n as DeployedView, o as getWorkbench, r as DeployedWebWorker, t as DeployedInterface } from "./summarizeInterfaces-Co97VU2z.js";
4
4
  import { AppVisibility, CliConfig, Output } from "@sanity/cli-core";
5
5
  import "node:zlib";
6
6
  /**
@@ -1,5 +1,5 @@
1
1
  import { C as defineTileView, S as definePanelView, T as defineWindowView, _ as ViewSurface, a as DefineWebWorkerInput, c as PanelView, d as TileSize, f as TileView, g as ViewDeclaration, h as ViewComponentBaseProps, i as DefineTileViewInput, m as ViewComponent, n as DefineAssetSourceViewInput, o as DefineWindowViewInput, p as VIEW_CONTRACT_VERSION, r as DefinePanelViewInput, s as DockGroup, t as AssetSourceView, u as ServiceType, v as WebWorker, w as defineWebWorker, x as defineAssetSourceView, y as WindowView } from "./contract-D_HnLQtT.js";
2
- import { a as ServiceInfo, i as ServiceContext, n as ServiceBus, o as unstable_defineService, r as ServiceCallback, t as DefinedService } from "./defineService-C1MhDwmh.js";
2
+ import { a as ServiceInfo, i as ServiceContext, n as ServiceBus, o as unstable_defineService, r as ServiceCallback, t as DefinedService } from "./defineService-DUaxVpWq.js";
3
3
  import { a as WorkbenchApp, c as isWorkbenchApp, i as MediaLibraryField, l as isWorkbenchConfig, n as DefineAppResult, o as WorkbenchConfig, r as DefineMediaLibraryInput, s as defineApplication, t as DefineAppInput, u as unstable_defineMediaLibrary } from "./defineApp-4hImcIIe.js";
4
4
  import { AssetSourceComponentProps } from "@sanity/types";
5
5
  /** @public */
@@ -37,6 +37,11 @@ interface ResolvedWorkbenchApp {
37
37
  /** Dashboard visibility declared by the app; `undefined` when unset. */
38
38
  readonly visibility?: AppVisibility;
39
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;
40
45
  /**
41
46
  * Resolve the workbench app for a CLI config, or `null` for a plain project or a
42
47
  * config (which is not an app — read it with `resolveWorkbenchConfig`).
@@ -59,5 +64,5 @@ interface ResolvedMediaLibraryConfig {
59
64
  * @public
60
65
  */
61
66
  declare function resolveWorkbenchConfig(cliConfig: CliConfig | null | undefined): ResolvedMediaLibraryConfig | null;
62
- export { resolveWorkbenchApp as a, WorkbenchExposes as i, resolveWorkbenchConfig as n, ResolvedWorkbenchApp as r, ResolvedMediaLibraryConfig as t };
63
- //# sourceMappingURL=resolveWorkbenchConfig-s3msa3Hu.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,5 +1,5 @@
1
1
  import { _ as ViewSurface, u as ServiceType } from "./contract-D_HnLQtT.js";
2
- import { i as WorkbenchExposes, r as ResolvedWorkbenchApp } from "./resolveWorkbenchConfig-s3msa3Hu.js";
2
+ import { i as WorkbenchExposes, r as ResolvedWorkbenchApp } from "./resolveWorkbenchConfig-DEttN7ks.js";
3
3
  import { z } from "zod/mini";
4
4
  import { CliConfig } from "@sanity/cli-core";
5
5
  /**
@@ -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-C0TCOa0J.d.ts.map
65
+ //# sourceMappingURL=summarizeInterfaces-Co97VU2z.d.ts.map
@@ -1,5 +1,5 @@
1
- import { t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-s3msa3Hu.js";
2
- import { a as DeployableWorkbenchApp, n as DeployedView, r as DeployedWebWorker } from "./summarizeInterfaces-C0TCOa0J.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"}
@@ -15,7 +15,10 @@ const busError = (code, message)=>Object.assign(new Error(message || code), {
15
15
  * @internal
16
16
  */ export function createWorkerBus() {
17
17
  const pending = new Map();
18
+ // The worker can't tell a state topic from an event topic, so it stores every
19
+ // handler alike; the host's `value` or `message` decides how it is called.
18
20
  const subscriptions = new Map();
21
+ const inFlight = new Map();
19
22
  let nextId = 0;
20
23
  let closed = false;
21
24
  // Posts a request and returns a function that creates its promise on first
@@ -78,6 +81,56 @@ const busError = (code, message)=>Object.assign(new Error(message || code), {
78
81
  if (outcome) onOutcome(outcome);
79
82
  });
80
83
  }
84
+ // Matches the SDK's `invokeResponder`, so a responder behaves the same in a
85
+ // worker as on the page.
86
+ function respond(handler, { messageId, meta, payload, type }) {
87
+ const controller = new AbortController();
88
+ inFlight.set(messageId, controller);
89
+ const answer = (result)=>{
90
+ if (inFlight.get(messageId) !== controller) return false;
91
+ inFlight.delete(messageId);
92
+ self.postMessage({
93
+ ...result,
94
+ kind: 'workbench.bus.answer',
95
+ messageId
96
+ });
97
+ return true;
98
+ };
99
+ const warnIfIgnored = (answered, action)=>{
100
+ if (answered) return;
101
+ // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger
102
+ console.warn(`Message bus ${action} ignored for "${type}": no waiting caller or already replied`);
103
+ };
104
+ const fail = ()=>answer({
105
+ error: {
106
+ code: 'HANDLER_THREW',
107
+ message: 'HANDLER_THREW'
108
+ },
109
+ ok: false
110
+ });
111
+ try {
112
+ const result = handler({
113
+ meta,
114
+ payload,
115
+ reject: (reason)=>warnIfIgnored(answer({
116
+ error: {
117
+ code: 'REFUSED',
118
+ message: reason ?? 'REFUSED'
119
+ },
120
+ ok: false
121
+ }), 'reject'),
122
+ reply: (value)=>warnIfIgnored(answer({
123
+ ok: true,
124
+ value
125
+ }), 'reply'),
126
+ signal: controller.signal,
127
+ type
128
+ });
129
+ if (result instanceof Promise) result.catch(fail);
130
+ } catch {
131
+ fail();
132
+ }
133
+ }
81
134
  const bus = {
82
135
  emit: (topic, payload, options)=>{
83
136
  const awaitReply = request({
@@ -124,6 +177,11 @@ const busError = (code, message)=>Object.assign(new Error(message || code), {
124
177
  close: ()=>{
125
178
  closed = true;
126
179
  subscriptions.clear();
180
+ const controllers = [
181
+ ...inFlight.values()
182
+ ];
183
+ inFlight.clear();
184
+ for (const controller of controllers)controller.abort();
127
185
  for (const settle of pending.values())settle({
128
186
  error: busError('ABORTED'),
129
187
  ok: false
@@ -131,26 +189,46 @@ const busError = (code, message)=>Object.assign(new Error(message || code), {
131
189
  },
132
190
  receive: (data)=>{
133
191
  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
- });
192
+ switch(message.kind){
193
+ case 'workbench.bus.cancel':
194
+ {
195
+ const controller = inFlight.get(message.messageId);
196
+ // Forget it first so an abort listener's reply is ignored.
197
+ inFlight.delete(message.messageId);
198
+ controller?.abort();
199
+ return;
200
+ }
201
+ case 'workbench.bus.message':
202
+ {
203
+ const handler = subscriptions.get(message.id);
204
+ if (handler) respond(handler, message);
205
+ return;
206
+ }
207
+ case 'workbench.bus.reply':
208
+ {
209
+ const settle = pending.get(message.id);
210
+ if (message.ok) {
211
+ settle?.({
212
+ ok: true,
213
+ value: message.value
214
+ });
215
+ return;
216
+ }
217
+ // A refused subscription has no promise to reject, so tell the author through the host logger.
218
+ if (subscriptions.delete(message.id)) {
219
+ // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger
220
+ console.error(`Message bus subscription refused: ${message.error.code}: ${message.error.message}`);
221
+ }
222
+ settle?.({
223
+ error: busError(message.error.code, message.error.message),
224
+ ok: false
225
+ });
226
+ return;
227
+ }
228
+ case 'workbench.bus.value':
229
+ {
230
+ subscriptions.get(message.id)?.(message.value);
231
+ }
154
232
  }
155
233
  }
156
234
  };
@@ -1 +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":"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"}
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 {\n type MessageBusEmitResult,\n type MessageBusErrorCode,\n type MessageBusMessage,\n type MessageBusMeta,\n} 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 Answer =\n | {error: {code: 'HANDLER_THREW' | 'REFUSED'; message: string}; ok: false}\n | {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 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): 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 // 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 ServiceBus,\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, 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 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","Object","assign","Error","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":"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"}
@@ -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"}
@@ -1,5 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { artifactExposes, workbenchArtifacts } from '../artifact.js';
3
+ import { isMediaLibraryConfigApp } from '../configs/configApp.js';
4
+ import { hasMediaLibraryIslandRuntime, MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE } from '../configs/mediaLibraryIslandRuntime.js';
3
5
  import { FEDERATION_FILE_NAME, RUNTIME_DIR } from './constants.js';
4
6
  import { sanityFederationHost } from './plugins/plugin-federation-host.js';
5
7
  import { sanityModuleFederation } from './plugins/plugin-module-federation.js';
@@ -26,11 +28,23 @@ import { sanityFederationRuntime } from './plugins/plugin-sanity-federation-runt
26
28
  return resolvedPath;
27
29
  }
28
30
  const entryPath = resolveEntryPath(generatedEntry);
31
+ // A Media Library config's `./island-runtime` expose re-exports the mount
32
+ // runtime from the app's installed `sanity`; skip it (the host falls back to
33
+ // degraded rendering for custom inputs) when that version predates the entry,
34
+ // since an unresolvable import would fail the whole build.
35
+ const isConfigApp = isMediaLibraryConfigApp(exposes);
36
+ const islandRuntime = isConfigApp && hasMediaLibraryIslandRuntime(workDir);
37
+ if (isConfigApp && !islandRuntime) {
38
+ // eslint-disable-next-line no-console -- build-time warning for the app developer
39
+ 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.');
40
+ }
29
41
  // Each view component (`./views/<view>/<component>`) and each service loader
30
42
  // (`./services/<name>`) is exposed straight to the host, pointing at the file
31
43
  // the extension-artifacts plugin generates under RUNTIME_DIR. A service's
32
44
  // worker bundle carries no expose — the host reaches it through its loader.
33
- const artifacts = workbenchArtifacts(exposes ?? {});
45
+ const artifacts = workbenchArtifacts(exposes ?? {}, {
46
+ islandRuntime
47
+ });
34
48
  const artifactModuleExposes = artifactExposes(artifacts, (artifactPath)=>resolveEntryPath(`./${RUNTIME_DIR}/${artifactPath}`));
35
49
  // A dock-only app (`isApp` with no `appEntry`) has no navigable full-page
36
50
  // view, so it exposes no `./App` — only its views. Studios and apps with an
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/vite/plugin.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type ModuleFederationOptions} from '@module-federation/vite'\nimport {type PackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {artifactExposes, workbenchArtifacts} from '../artifact.js'\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './constants.js'\nimport {sanityFederationHost} from './plugins/plugin-federation-host.js'\nimport {type FederationOptions, sanityModuleFederation} from './plugins/plugin-module-federation.js'\nimport {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // Each view component (`./views/<view>/<component>`) and each service loader\n // (`./services/<name>`) is exposed straight to the host, pointing at the file\n // the extension-artifacts plugin generates under RUNTIME_DIR. A service's\n // worker bundle carries no expose — the host reaches it through its loader.\n const artifacts = workbenchArtifacts(exposes ?? {})\n const artifactModuleExposes = artifactExposes(artifacts, (artifactPath) =>\n resolveEntryPath(`./${RUNTIME_DIR}/${artifactPath}`),\n )\n\n // A dock-only app (`isApp` with no `appEntry`) has no navigable full-page\n // view, so it exposes no `./App` — only its views. Studios and apps with an\n // entry expose `./App` (the generated render entry).\n const exposesApp = !options.isApp || options.appEntry !== undefined\n\n const federationExposes: NonNullable<ModuleFederationOptions['exposes']> = {\n ...(exposesApp ? {'./App': entryPath} : {}),\n ...artifactModuleExposes,\n }\n\n const runtimeOptions: FederationRuntimeOptions = options.isApp\n ? {appEntry: options.appEntry, isApp: true, isBlueprints}\n : {isApp: false, isBlueprints, studioConfigPath: options.studioConfigPath}\n\n // Every federated app and studio also serves itself standalone. Whenever there's\n // an `./App` to mount (never for a dock-only app), build the SPA client\n // environment from the runtime bootstrap cli-build writes.\n const clientInput = exposesApp ? path.join(workDir, '.sanity', 'runtime', 'app.js') : undefined\n\n return [\n sanityEnvironmentPlugin({clientInput, input: entryPath, isBlueprints}),\n sanityFederationRuntime(runtimeOptions),\n sanityExtensionArtifacts({artifacts}),\n sanityModuleFederation({exposes: federationExposes, name}),\n sanityFederationHost(),\n ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityFederationHost","sanityModuleFederation","sanityEnvironmentPlugin","sanityExtensionArtifacts","sanityFederationRuntime","federation","options","exposes","isBlueprints","name","defaultName","pkgJson","workDir","process","cwd","Error","generatedEntry","resolveEntryPath","entry","resolvedPath","resolve","entryPath","artifacts","artifactModuleExposes","artifactPath","exposesApp","isApp","appEntry","undefined","federationExposes","runtimeOptions","studioConfigPath","clientInput","join","input"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC,eAAe,EAAEC,kBAAkB,QAAO,iBAAgB;AAClE,SAAQC,oBAAoB,EAAEC,WAAW,QAAO,iBAAgB;AAChE,SAAQC,oBAAoB,QAAO,sCAAqC;AACxE,SAAgCC,sBAAsB,QAAO,wCAAuC;AACpG,SAAQC,uBAAuB,QAAO,yCAAwC;AAC9E,SAAQC,wBAAwB,QAAO,iDAAgD;AACvF,SAEEC,uBAAuB,QAClB,gDAA+C;AA6CtD;;CAEC,GACD,OAAO,MAAMC,aAAa,CAACC;IACzB,MAAM,EAACC,OAAO,EAAEC,YAAY,EAAEC,MAAMC,WAAW,EAAEC,OAAO,EAAEC,UAAUC,QAAQC,GAAG,EAAE,EAAC,GAAGR;IAErF,IAAIG,OAAOC;IAEX,IAAI,CAACD,MAAM;QACTA,OAAOE,SAASF;IAClB;IAEA,IAAI,CAACA,MAAM;QACT,MAAM,IAAIM,MAAM;IAClB;IAEA,MAAMC,iBAAiB,CAAC,EAAE,EAAEjB,YAAY,CAAC,EAAED,qBAAqB,IAAI,CAAC;IAErE,SAASmB,iBAAiBC,KAAa;QACrC,MAAMC,eAAexB,KAAKyB,OAAO,CAACR,SAASM;QAE3C,IAAI,CAACC,cAAc;YACjB,MAAM,IAAIJ,MACR,CAAC,kCAAkC,EAAEG,MAAM,6DAA6D,CAAC;QAE7G;QAEA,OAAOC;IACT;IAEA,MAAME,YAAYJ,iBAAiBD;IAEnC,6EAA6E;IAC7E,8EAA8E;IAC9E,0EAA0E;IAC1E,4EAA4E;IAC5E,MAAMM,YAAYzB,mBAAmBU,WAAW,CAAC;IACjD,MAAMgB,wBAAwB3B,gBAAgB0B,WAAW,CAACE,eACxDP,iBAAiB,CAAC,EAAE,EAAElB,YAAY,CAAC,EAAEyB,cAAc;IAGrD,0EAA0E;IAC1E,4EAA4E;IAC5E,qDAAqD;IACrD,MAAMC,aAAa,CAACnB,QAAQoB,KAAK,IAAIpB,QAAQqB,QAAQ,KAAKC;IAE1D,MAAMC,oBAAqE;QACzE,GAAIJ,aAAa;YAAC,SAASJ;QAAS,IAAI,CAAC,CAAC;QAC1C,GAAGE,qBAAqB;IAC1B;IAEA,MAAMO,iBAA2CxB,QAAQoB,KAAK,GAC1D;QAACC,UAAUrB,QAAQqB,QAAQ;QAAED,OAAO;QAAMlB;IAAY,IACtD;QAACkB,OAAO;QAAOlB;QAAcuB,kBAAkBzB,QAAQyB,gBAAgB;IAAA;IAE3E,iFAAiF;IACjF,wEAAwE;IACxE,2DAA2D;IAC3D,MAAMC,cAAcP,aAAa9B,KAAKsC,IAAI,CAACrB,SAAS,WAAW,WAAW,YAAYgB;IAEtF,OAAO;QACL1B,wBAAwB;YAAC8B;YAAaE,OAAOb;YAAWb;QAAY;QACpEJ,wBAAwB0B;QACxB3B,yBAAyB;YAACmB;QAAS;QACnCrB,uBAAuB;YAACM,SAASsB;YAAmBpB;QAAI;QACxDT;KACD;AACH,EAAC"}
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 {sanityEnvironmentPlugin} from './plugins/plugin-sanity-environment.js'\nimport {sanityExtensionArtifacts} from './plugins/plugin-sanity-extension-artifacts.js'\nimport {\n type FederationRuntimeOptions,\n sanityFederationRuntime,\n} from './plugins/plugin-sanity-federation-runtime.js'\n\ninterface FederationPluginOptionsBase extends Omit<Partial<FederationOptions>, 'exposes'> {\n exposes?: WorkbenchExposes\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n pkgJson?: PackageJson\n /**\n * Current working directory to read package.json from, defaults to process.cwd()\n */\n workDir?: string\n}\n\ninterface AppFederationPluginOptions extends FederationPluginOptionsBase {\n isApp: true\n\n /**\n * Relative path to the App entry from the runtime directory, e.g.\n * `../../src/App.tsx`. Omit it for a dock-only app that declares no `entry`:\n * no `./App` is exposed and the remote serves only its views.\n */\n appEntry?: string\n studioConfigPath?: never\n}\n\ninterface StudioFederationPluginOptions extends FederationPluginOptionsBase {\n /** relative path to the Studio config file from the runtime directory (e.g. `../../sanity.config.ts`). */\n studioConfigPath: string\n\n appEntry?: never\n /** @defaultValue false */\n isApp?: false\n}\n\n/**\n * Plugin options for the federation vite plugin.\n *\n * Discriminated on `isApp`:\n * - `isApp: true` → requires `appEntry`\n * - `isApp: false` (default) → requires `studioConfigPath`\n *\n * @internal\n */\ntype FederationPluginOptions = AppFederationPluginOptions | StudioFederationPluginOptions\n\n/**\n * @internal\n */\nexport const federation = (options: FederationPluginOptions): PluginOption => {\n const {exposes, isBlueprints, name: defaultName, pkgJson, workDir = process.cwd()} = options\n\n let name = defaultName\n\n if (!name) {\n name = pkgJson?.name\n }\n\n if (!name) {\n throw new Error('\"name\" option is required but could not be inferred from package.json')\n }\n\n const generatedEntry = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\n function resolveEntryPath(entry: string) {\n const resolvedPath = path.resolve(workDir, entry)\n\n if (!resolvedPath) {\n throw new Error(\n `Could not resolve path for entry \"${entry}\". Please check that the file exists and the path is correct.`,\n )\n }\n\n return resolvedPath\n }\n\n const entryPath = resolveEntryPath(generatedEntry)\n\n // 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 ]\n}\n"],"names":["path","artifactExposes","workbenchArtifacts","isMediaLibraryConfigApp","hasMediaLibraryIslandRuntime","MEDIA_LIBRARY_ISLAND_RUNTIME_MODULE","FEDERATION_FILE_NAME","RUNTIME_DIR","sanityFederationHost","sanityModuleFederation","sanityEnvironmentPlugin","sanityExtensionArtifacts","sanityFederationRuntime","federation","options","exposes","isBlueprints","name","defaultName","pkgJson","workDir","process","cwd","Error","generatedEntry","resolveEntryPath","entry","resolvedPath","resolve","entryPath","isConfigApp","islandRuntime","console","warn","artifacts","artifactModuleExposes","artifactPath","exposesApp","isApp","appEntry","undefined","federationExposes","runtimeOptions","studioConfigPath","clientInput","join","input"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAO5B,SAAQC,eAAe,EAAEC,kBAAkB,QAAO,iBAAgB;AAClE,SAAQC,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,SAAQC,uBAAuB,QAAO,yCAAwC;AAC9E,SAAQC,wBAAwB,QAAO,iDAAgD;AACvF,SAEEC,uBAAuB,QAClB,gDAA+C;AA6CtD;;CAEC,GACD,OAAO,MAAMC,aAAa,CAACC;IACzB,MAAM,EAACC,OAAO,EAAEC,YAAY,EAAEC,MAAMC,WAAW,EAAEC,OAAO,EAAEC,UAAUC,QAAQC,GAAG,EAAE,EAAC,GAAGR;IAErF,IAAIG,OAAOC;IAEX,IAAI,CAACD,MAAM;QACTA,OAAOE,SAASF;IAClB;IAEA,IAAI,CAACA,MAAM;QACT,MAAM,IAAIM,MAAM;IAClB;IAEA,MAAMC,iBAAiB,CAAC,EAAE,EAAEjB,YAAY,CAAC,EAAED,qBAAqB,IAAI,CAAC;IAErE,SAASmB,iBAAiBC,KAAa;QACrC,MAAMC,eAAe3B,KAAK4B,OAAO,CAACR,SAASM;QAE3C,IAAI,CAACC,cAAc;YACjB,MAAM,IAAIJ,MACR,CAAC,kCAAkC,EAAEG,MAAM,6DAA6D,CAAC;QAE7G;QAEA,OAAOC;IACT;IAEA,MAAME,YAAYJ,iBAAiBD;IAEnC,0EAA0E;IAC1E,6EAA6E;IAC7E,8EAA8E;IAC9E,2DAA2D;IAC3D,MAAMM,cAAc3B,wBAAwBY;IAC5C,MAAMgB,gBAAgBD,eAAe1B,6BAA6BgB;IAClE,IAAIU,eAAe,CAACC,eAAe;QACjC,kFAAkF;QAClFC,QAAQC,IAAI,CACV,CAAC,2CAA2C,EAAE5B,oCAAoC,EAAE,CAAC,GACnF;IAEN;IAEA,6EAA6E;IAC7E,8EAA8E;IAC9E,0EAA0E;IAC1E,4EAA4E;IAC5E,MAAM6B,YAAYhC,mBAAmBa,WAAW,CAAC,GAAG;QAACgB;IAAa;IAClE,MAAMI,wBAAwBlC,gBAAgBiC,WAAW,CAACE,eACxDX,iBAAiB,CAAC,EAAE,EAAElB,YAAY,CAAC,EAAE6B,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,aAAarC,KAAK6C,IAAI,CAACzB,SAAS,WAAW,WAAW,YAAYoB;IAEtF,OAAO;QACL9B,wBAAwB;YAACkC;YAAaE,OAAOjB;YAAWb;QAAY;QACpEJ,wBAAwB8B;QACxB/B,yBAAyB;YAACuB;QAAS;QACnCzB,uBAAuB;YAACM,SAAS0B;YAAmBxB;QAAI;QACxDT;KACD;AACH,EAAC"}
@@ -0,0 +1,82 @@
1
+ /**
2
+ * `@sanity/ui` v5's cascade-layer namespace. Its stylesheet (which the
3
+ * `sanity` root barrel side-effect imports under the `ui5` npm alias) keeps
4
+ * all component styles in class-scoped rules under `@layer sui`, and its
5
+ * document-wide reset (`*{margin:0;padding:0;...}` and friends) in
6
+ * `@layer sui.global` blocks.
7
+ */ const SUI_GLOBAL_LAYER = '@layer sui.global';
8
+ /**
9
+ * Remove every `@layer sui.global { ... }` block, keeping the rest of the
10
+ * stylesheet. Layer *statements* (`@layer sui;` / `@layer sui.global;`),
11
+ * which only declare ordering, are left alone.
12
+ *
13
+ * The scanner brace-counts from each block's opening brace; it does not
14
+ * tokenize strings/urls, which is fine for the known content of these blocks
15
+ * (a reset and a font-face) — and a miscount would only under- or over-strip
16
+ * dev styling, never break the build.
17
+ */ export function stripSuiGlobalLayer(css) {
18
+ let out = css;
19
+ let from = 0;
20
+ for(;;){
21
+ const at = out.indexOf(SUI_GLOBAL_LAYER, from);
22
+ if (at === -1) return out;
23
+ // The layer name must end here (not `sui.globalish`), and the at-rule
24
+ // must open a block — otherwise it is an ordering statement; skip it.
25
+ let cursor = at + SUI_GLOBAL_LAYER.length;
26
+ while(cursor < out.length && /\s/.test(out[cursor]))cursor += 1;
27
+ const boundary = out[at + SUI_GLOBAL_LAYER.length];
28
+ if (out[cursor] !== '{' || boundary !== undefined && !/[\s{,;]/.test(boundary)) {
29
+ from = at + SUI_GLOBAL_LAYER.length;
30
+ continue;
31
+ }
32
+ let depth = 0;
33
+ let end = -1;
34
+ for(let index = cursor; index < out.length; index += 1){
35
+ if (out[index] === '{') depth += 1;
36
+ else if (out[index] === '}') {
37
+ depth -= 1;
38
+ if (depth === 0) {
39
+ end = index;
40
+ break;
41
+ }
42
+ }
43
+ }
44
+ if (end === -1) return out // unbalanced: leave the rest untouched
45
+ ;
46
+ out = out.slice(0, at) + out.slice(end + 1);
47
+ from = at;
48
+ }
49
+ }
50
+ /**
51
+ * Why strip anything: Media Library config apps bundle the `sanity` barrel
52
+ * (field modules and the island runtime import it), and the barrel
53
+ * side-effect imports `@sanity/ui` v5's stylesheet. Its `@layer sui.global`
54
+ * reset is document-wide, and in dev the config app's modules execute inside
55
+ * the Media Library host's page — so the reset restyles the host (strips
56
+ * body padding etc.). The class-scoped component styles in the same file are
57
+ * harmless to the host and *needed* by islands: `renderDefault` leaf inputs
58
+ * render Studio components that increasingly carry `sui-*` classes. So keep
59
+ * the component styles, drop only the global layer.
60
+ *
61
+ * Why match on content (the `@layer sui.global` marker) rather than the
62
+ * import specifier or file path: the `ui5` alias is the `sanity` package's
63
+ * internal name for `@sanity/ui` v5 and can be renamed or re-pathed in any
64
+ * sanity release; the layer name is the stylesheet's own public CSS surface
65
+ * and travels with the file wherever it resolves from.
66
+ */ export function stripSuiGlobalReset() {
67
+ return {
68
+ enforce: 'pre',
69
+ name: 'sanity/strip-sui-global-reset',
70
+ transform (code, id) {
71
+ if (!id.split('?', 1)[0].endsWith('.css')) return null;
72
+ if (!code.includes(SUI_GLOBAL_LAYER)) return null;
73
+ const next = stripSuiGlobalLayer(code);
74
+ return next === code ? null : {
75
+ code: next,
76
+ map: null
77
+ };
78
+ }
79
+ };
80
+ }
81
+
82
+ //# sourceMappingURL=plugin-strip-sui-global-reset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-strip-sui-global-reset.ts"],"sourcesContent":["import {type Plugin} from 'vite'\n\n/**\n * `@sanity/ui` v5's cascade-layer namespace. Its stylesheet (which the\n * `sanity` root barrel side-effect imports under the `ui5` npm alias) keeps\n * all component styles in class-scoped rules under `@layer sui`, and its\n * document-wide reset (`*{margin:0;padding:0;...}` and friends) in\n * `@layer sui.global` blocks.\n */\nconst SUI_GLOBAL_LAYER = '@layer sui.global'\n\n/**\n * Remove every `@layer sui.global { ... }` block, keeping the rest of the\n * stylesheet. Layer *statements* (`@layer sui;` / `@layer sui.global;`),\n * which only declare ordering, are left alone.\n *\n * The scanner brace-counts from each block's opening brace; it does not\n * tokenize strings/urls, which is fine for the known content of these blocks\n * (a reset and a font-face) — and a miscount would only under- or over-strip\n * dev styling, never break the build.\n */\nexport function stripSuiGlobalLayer(css: string): string {\n let out = css\n let from = 0\n for (;;) {\n const at = out.indexOf(SUI_GLOBAL_LAYER, from)\n if (at === -1) return out\n // The layer name must end here (not `sui.globalish`), and the at-rule\n // must open a block — otherwise it is an ordering statement; skip it.\n let cursor = at + SUI_GLOBAL_LAYER.length\n while (cursor < out.length && /\\s/.test(out[cursor])) cursor += 1\n const boundary = out[at + SUI_GLOBAL_LAYER.length]\n if (out[cursor] !== '{' || (boundary !== undefined && !/[\\s{,;]/.test(boundary))) {\n from = at + SUI_GLOBAL_LAYER.length\n continue\n }\n let depth = 0\n let end = -1\n for (let index = cursor; index < out.length; index += 1) {\n if (out[index] === '{') depth += 1\n else if (out[index] === '}') {\n depth -= 1\n if (depth === 0) {\n end = index\n break\n }\n }\n }\n if (end === -1) return out // unbalanced: leave the rest untouched\n out = out.slice(0, at) + out.slice(end + 1)\n from = at\n }\n}\n\n/**\n * Why strip anything: Media Library config apps bundle the `sanity` barrel\n * (field modules and the island runtime import it), and the barrel\n * side-effect imports `@sanity/ui` v5's stylesheet. Its `@layer sui.global`\n * reset is document-wide, and in dev the config app's modules execute inside\n * the Media Library host's page — so the reset restyles the host (strips\n * body padding etc.). The class-scoped component styles in the same file are\n * harmless to the host and *needed* by islands: `renderDefault` leaf inputs\n * render Studio components that increasingly carry `sui-*` classes. So keep\n * the component styles, drop only the global layer.\n *\n * Why match on content (the `@layer sui.global` marker) rather than the\n * import specifier or file path: the `ui5` alias is the `sanity` package's\n * internal name for `@sanity/ui` v5 and can be renamed or re-pathed in any\n * sanity release; the layer name is the stylesheet's own public CSS surface\n * and travels with the file wherever it resolves from.\n */\nexport function stripSuiGlobalReset(): Plugin {\n return {\n enforce: 'pre',\n name: 'sanity/strip-sui-global-reset',\n transform(code, id) {\n if (!id.split('?', 1)[0].endsWith('.css')) return null\n if (!code.includes(SUI_GLOBAL_LAYER)) return null\n const next = stripSuiGlobalLayer(code)\n return next === code ? null : {code: next, map: null}\n },\n }\n}\n"],"names":["SUI_GLOBAL_LAYER","stripSuiGlobalLayer","css","out","from","at","indexOf","cursor","length","test","boundary","undefined","depth","end","index","slice","stripSuiGlobalReset","enforce","name","transform","code","id","split","endsWith","includes","next","map"],"mappings":"AAEA;;;;;;CAMC,GACD,MAAMA,mBAAmB;AAEzB;;;;;;;;;CASC,GACD,OAAO,SAASC,oBAAoBC,GAAW;IAC7C,IAAIC,MAAMD;IACV,IAAIE,OAAO;IACX,OAAS;QACP,MAAMC,KAAKF,IAAIG,OAAO,CAACN,kBAAkBI;QACzC,IAAIC,OAAO,CAAC,GAAG,OAAOF;QACtB,sEAAsE;QACtE,sEAAsE;QACtE,IAAII,SAASF,KAAKL,iBAAiBQ,MAAM;QACzC,MAAOD,SAASJ,IAAIK,MAAM,IAAI,KAAKC,IAAI,CAACN,GAAG,CAACI,OAAO,EAAGA,UAAU;QAChE,MAAMG,WAAWP,GAAG,CAACE,KAAKL,iBAAiBQ,MAAM,CAAC;QAClD,IAAIL,GAAG,CAACI,OAAO,KAAK,OAAQG,aAAaC,aAAa,CAAC,UAAUF,IAAI,CAACC,WAAY;YAChFN,OAAOC,KAAKL,iBAAiBQ,MAAM;YACnC;QACF;QACA,IAAII,QAAQ;QACZ,IAAIC,MAAM,CAAC;QACX,IAAK,IAAIC,QAAQP,QAAQO,QAAQX,IAAIK,MAAM,EAAEM,SAAS,EAAG;YACvD,IAAIX,GAAG,CAACW,MAAM,KAAK,KAAKF,SAAS;iBAC5B,IAAIT,GAAG,CAACW,MAAM,KAAK,KAAK;gBAC3BF,SAAS;gBACT,IAAIA,UAAU,GAAG;oBACfC,MAAMC;oBACN;gBACF;YACF;QACF;QACA,IAAID,QAAQ,CAAC,GAAG,OAAOV,IAAI,uCAAuC;;QAClEA,MAAMA,IAAIY,KAAK,CAAC,GAAGV,MAAMF,IAAIY,KAAK,CAACF,MAAM;QACzCT,OAAOC;IACT;AACF;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASW;IACd,OAAO;QACLC,SAAS;QACTC,MAAM;QACNC,WAAUC,IAAI,EAAEC,EAAE;YAChB,IAAI,CAACA,GAAGC,KAAK,CAAC,KAAK,EAAE,CAAC,EAAE,CAACC,QAAQ,CAAC,SAAS,OAAO;YAClD,IAAI,CAACH,KAAKI,QAAQ,CAACxB,mBAAmB,OAAO;YAC7C,MAAMyB,OAAOxB,oBAAoBmB;YACjC,OAAOK,SAASL,OAAO,OAAO;gBAACA,MAAMK;gBAAMC,KAAK;YAAI;QACtD;IACF;AACF"}
@@ -6,8 +6,10 @@
6
6
  // live here next to `federation` — the build package just hands over its inputs.
7
7
  import path from 'node:path';
8
8
  import { readPackageJson } from '@sanity/cli-core';
9
+ import { isMediaLibraryConfigApp } from '../configs/configApp.js';
9
10
  import { federation } from './plugin.js';
10
11
  import { sanityAppId } from './plugins/plugin-sanity-app-id.js';
12
+ import { stripSuiGlobalReset } from './plugins/plugin-strip-sui-global-reset.js';
11
13
  /**
12
14
  * A workbench studio renders from its `sanity.config.*`, so the build needs one.
13
15
  * An explicit `applicationType: 'studio'` wins over detection, so a studio can
@@ -39,9 +41,18 @@ import { sanityAppId } from './plugins/plugin-sanity-app-id.js';
39
41
  pkgJson,
40
42
  workDir: cwd
41
43
  });
42
- return appId === undefined ? federationPlugin : [
44
+ // Media Library config apps run their modules inside the host's page, so
45
+ // the `sanity` barrel's document-wide CSS reset must not travel with the
46
+ // bundle (see the plugin for the full why).
47
+ const configAppPlugins = isMediaLibraryConfigApp(exposes) ? [
48
+ stripSuiGlobalReset()
49
+ ] : [];
50
+ return [
51
+ ...configAppPlugins,
43
52
  federationPlugin,
44
- sanityAppId(appId)
53
+ ...appId === undefined ? [] : [
54
+ sanityAppId(appId)
55
+ ]
45
56
  ];
46
57
  }
47
58
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/actions/build/vite/workbench-vite-plugins.ts"],"sourcesContent":["// The build-facing entry of the workbench federation stack: turn a workbench\n// app's build inputs into the Vite plugins that produce its module-federation\n// remote. `@sanity/cli-build`'s `getViteConfig` calls this instead of\n// assembling `federation`'s options itself, so the discriminated app-vs-studio\n// option shape, the no-app-view rule, and the studio-config requirement all\n// live here next to `federation` — the build package just hands over its inputs.\n\nimport path from 'node:path'\n\nimport {readPackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {federation} from './plugin.js'\nimport {sanityAppId} from './plugins/plugin-sanity-app-id.js'\n\ninterface WorkbenchViteOptions {\n /** Project root — read for the federation remote name, and the plugin workDir. */\n cwd: string\n /**\n * Build entry paths relative to the federation runtime dir. `relativeEntry` is\n * the app's `entry` (null for a dock-only app with no app view);\n * `relativeConfigLocation` is the studio's `sanity.config.*` (null when absent).\n */\n entries: {relativeConfigLocation: string | null; relativeEntry: string | null}\n\n /** The app's bus identity, stamped into its modules for `@sanity/runtime`. */\n appId?: string\n\n exposes?: WorkbenchExposes\n /** App (vs studio) build — selects the discriminated federation option shape. */\n isApp?: boolean\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\n/**\n * A workbench studio renders from its `sanity.config.*`, so the build needs one.\n * An explicit `applicationType: 'studio'` wins over detection, so a studio can\n * reach here with no config file — fail with the fix rather than a cryptic build\n * error downstream.\n */\nfunction requireStudioConfigPath(relativeConfigLocation: string | null): string {\n if (relativeConfigLocation === null) {\n throw new Error(\n 'Dashboard studios need a sanity.config.js or sanity.config.ts file. ' +\n \"Add one, or remove `applicationType: 'studio'` from `defineApplication` \" +\n 'to let the CLI infer the application type.',\n )\n }\n return relativeConfigLocation\n}\n\n/** Build the Vite plugins for a workbench app's module-federation remote. */\nexport async function workbenchVitePlugins(options: WorkbenchViteOptions): Promise<PluginOption> {\n const {appId, cwd, entries, exposes, isApp, isBlueprints} = options\n const pkgJson = await readPackageJson(path.join(cwd, 'package.json'))\n\n const federationPlugin = federation({\n ...(isApp\n ? {\n // `null` relativeEntry (a branded app with no `entry`) → omit `appEntry`,\n // so the remote exposes no `./App`, only its views.\n ...(entries.relativeEntry ? {appEntry: entries.relativeEntry} : {}),\n isApp: true as const,\n }\n : {\n isApp: false as const,\n studioConfigPath: requireStudioConfigPath(entries.relativeConfigLocation),\n }),\n exposes,\n isBlueprints,\n pkgJson,\n workDir: cwd,\n })\n\n return appId === undefined ? federationPlugin : [federationPlugin, sanityAppId(appId)]\n}\n"],"names":["path","readPackageJson","federation","sanityAppId","requireStudioConfigPath","relativeConfigLocation","Error","workbenchVitePlugins","options","appId","cwd","entries","exposes","isApp","isBlueprints","pkgJson","join","federationPlugin","relativeEntry","appEntry","studioConfigPath","workDir","undefined"],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,sEAAsE;AACtE,+EAA+E;AAC/E,4EAA4E;AAC5E,iFAAiF;AAEjF,OAAOA,UAAU,YAAW;AAE5B,SAAQC,eAAe,QAAO,mBAAkB;AAIhD,SAAQC,UAAU,QAAO,cAAa;AACtC,SAAQC,WAAW,QAAO,oCAAmC;AAsB7D;;;;;CAKC,GACD,SAASC,wBAAwBC,sBAAqC;IACpE,IAAIA,2BAA2B,MAAM;QACnC,MAAM,IAAIC,MACR,yEACE,6EACA;IAEN;IACA,OAAOD;AACT;AAEA,2EAA2E,GAC3E,OAAO,eAAeE,qBAAqBC,OAA6B;IACtE,MAAM,EAACC,KAAK,EAAEC,GAAG,EAAEC,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGN;IAC5D,MAAMO,UAAU,MAAMd,gBAAgBD,KAAKgB,IAAI,CAACN,KAAK;IAErD,MAAMO,mBAAmBf,WAAW;QAClC,GAAIW,QACA;YACE,0EAA0E;YAC1E,oDAAoD;YACpD,GAAIF,QAAQO,aAAa,GAAG;gBAACC,UAAUR,QAAQO,aAAa;YAAA,IAAI,CAAC,CAAC;YAClEL,OAAO;QACT,IACA;YACEA,OAAO;YACPO,kBAAkBhB,wBAAwBO,QAAQN,sBAAsB;QAC1E,CAAC;QACLO;QACAE;QACAC;QACAM,SAASX;IACX;IAEA,OAAOD,UAAUa,YAAYL,mBAAmB;QAACA;QAAkBd,YAAYM;KAAO;AACxF"}
1
+ {"version":3,"sources":["../../../../src/actions/build/vite/workbench-vite-plugins.ts"],"sourcesContent":["// The build-facing entry of the workbench federation stack: turn a workbench\n// app's build inputs into the Vite plugins that produce its module-federation\n// remote. `@sanity/cli-build`'s `getViteConfig` calls this instead of\n// assembling `federation`'s options itself, so the discriminated app-vs-studio\n// option shape, the no-app-view rule, and the studio-config requirement all\n// live here next to `federation` — the build package just hands over its inputs.\n\nimport path from 'node:path'\n\nimport {readPackageJson} from '@sanity/cli-core'\nimport {type PluginOption} from 'vite'\n\nimport {type WorkbenchExposes} from '../../../resolveWorkbenchApp.js'\nimport {isMediaLibraryConfigApp} from '../configs/configApp.js'\nimport {federation} from './plugin.js'\nimport {sanityAppId} from './plugins/plugin-sanity-app-id.js'\nimport {stripSuiGlobalReset} from './plugins/plugin-strip-sui-global-reset.js'\n\ninterface WorkbenchViteOptions {\n /** Project root — read for the federation remote name, and the plugin workDir. */\n cwd: string\n /**\n * Build entry paths relative to the federation runtime dir. `relativeEntry` is\n * the app's `entry` (null for a dock-only app with no app view);\n * `relativeConfigLocation` is the studio's `sanity.config.*` (null when absent).\n */\n entries: {relativeConfigLocation: string | null; relativeEntry: string | null}\n\n /** The app's bus identity, stamped into its modules for `@sanity/runtime`. */\n appId?: string\n\n exposes?: WorkbenchExposes\n /** App (vs studio) build — selects the discriminated federation option shape. */\n isApp?: boolean\n /** Blueprints build (via `@sanity/runtime-cli`) — emit the resource-bindings module. */\n isBlueprints?: boolean\n}\n\n/**\n * A workbench studio renders from its `sanity.config.*`, so the build needs one.\n * An explicit `applicationType: 'studio'` wins over detection, so a studio can\n * reach here with no config file — fail with the fix rather than a cryptic build\n * error downstream.\n */\nfunction requireStudioConfigPath(relativeConfigLocation: string | null): string {\n if (relativeConfigLocation === null) {\n throw new Error(\n 'Dashboard studios need a sanity.config.js or sanity.config.ts file. ' +\n \"Add one, or remove `applicationType: 'studio'` from `defineApplication` \" +\n 'to let the CLI infer the application type.',\n )\n }\n return relativeConfigLocation\n}\n\n/** Build the Vite plugins for a workbench app's module-federation remote. */\nexport async function workbenchVitePlugins(options: WorkbenchViteOptions): Promise<PluginOption> {\n const {appId, cwd, entries, exposes, isApp, isBlueprints} = options\n const pkgJson = await readPackageJson(path.join(cwd, 'package.json'))\n\n const federationPlugin = federation({\n ...(isApp\n ? {\n // `null` relativeEntry (a branded app with no `entry`) → omit `appEntry`,\n // so the remote exposes no `./App`, only its views.\n ...(entries.relativeEntry ? {appEntry: entries.relativeEntry} : {}),\n isApp: true as const,\n }\n : {\n isApp: false as const,\n studioConfigPath: requireStudioConfigPath(entries.relativeConfigLocation),\n }),\n exposes,\n isBlueprints,\n pkgJson,\n workDir: cwd,\n })\n\n // Media Library config apps run their modules inside the host's page, so\n // the `sanity` barrel's document-wide CSS reset must not travel with the\n // bundle (see the plugin for the full why).\n const configAppPlugins: PluginOption[] = isMediaLibraryConfigApp(exposes)\n ? [stripSuiGlobalReset()]\n : []\n\n return [\n ...configAppPlugins,\n federationPlugin,\n ...(appId === undefined ? [] : [sanityAppId(appId)]),\n ]\n}\n"],"names":["path","readPackageJson","isMediaLibraryConfigApp","federation","sanityAppId","stripSuiGlobalReset","requireStudioConfigPath","relativeConfigLocation","Error","workbenchVitePlugins","options","appId","cwd","entries","exposes","isApp","isBlueprints","pkgJson","join","federationPlugin","relativeEntry","appEntry","studioConfigPath","workDir","configAppPlugins","undefined"],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,sEAAsE;AACtE,+EAA+E;AAC/E,4EAA4E;AAC5E,iFAAiF;AAEjF,OAAOA,UAAU,YAAW;AAE5B,SAAQC,eAAe,QAAO,mBAAkB;AAIhD,SAAQC,uBAAuB,QAAO,0BAAyB;AAC/D,SAAQC,UAAU,QAAO,cAAa;AACtC,SAAQC,WAAW,QAAO,oCAAmC;AAC7D,SAAQC,mBAAmB,QAAO,6CAA4C;AAsB9E;;;;;CAKC,GACD,SAASC,wBAAwBC,sBAAqC;IACpE,IAAIA,2BAA2B,MAAM;QACnC,MAAM,IAAIC,MACR,yEACE,6EACA;IAEN;IACA,OAAOD;AACT;AAEA,2EAA2E,GAC3E,OAAO,eAAeE,qBAAqBC,OAA6B;IACtE,MAAM,EAACC,KAAK,EAAEC,GAAG,EAAEC,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAEC,YAAY,EAAC,GAAGN;IAC5D,MAAMO,UAAU,MAAMhB,gBAAgBD,KAAKkB,IAAI,CAACN,KAAK;IAErD,MAAMO,mBAAmBhB,WAAW;QAClC,GAAIY,QACA;YACE,0EAA0E;YAC1E,oDAAoD;YACpD,GAAIF,QAAQO,aAAa,GAAG;gBAACC,UAAUR,QAAQO,aAAa;YAAA,IAAI,CAAC,CAAC;YAClEL,OAAO;QACT,IACA;YACEA,OAAO;YACPO,kBAAkBhB,wBAAwBO,QAAQN,sBAAsB;QAC1E,CAAC;QACLO;QACAE;QACAC;QACAM,SAASX;IACX;IAEA,yEAAyE;IACzE,yEAAyE;IACzE,4CAA4C;IAC5C,MAAMY,mBAAmCtB,wBAAwBY,WAC7D;QAACT;KAAsB,GACvB,EAAE;IAEN,OAAO;WACFmB;QACHL;WACIR,UAAUc,YAAY,EAAE,GAAG;YAACrB,YAAYO;SAAO;KACpD;AACH"}
@@ -6,9 +6,30 @@ import { SERVICE_CONTRACT_VERSION } from './contract.js';
6
6
  * The callback receives `bus`, its connection to the Dashboard message bus:
7
7
  * `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the
8
8
  * current value of a state topic, and `bus.subscribe` runs a handler on each
9
- * new value of a state topic until its `signal` aborts. A refused, unanswered
10
- * or timed-out request rejects with an `Error` named `MessageBusError` whose
11
- * `code` says why; it is not an instance of the SDK's `MessageBusError` class.
9
+ * new value of a state topic, or on each event of an event topic, until its
10
+ * `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects
11
+ * with an `Error` named `MessageBusError` whose `code` says why; it is not an
12
+ * instance of the SDK's `MessageBusError` class.
13
+ *
14
+ * An event handler answers the sender with `message.reply(value)` or refuses
15
+ * with `message.reject(reason)`; one that throws refuses with code
16
+ * `HANDLER_THREW`. For example, a service that keeps a snapshot for its app's
17
+ * views, which listen with `useWorker` first and then post to it. A view's post
18
+ * arrives on `workers.post` as `{name, payload}`, and `workers.message` reaches
19
+ * only this app's views:
20
+ *
21
+ * ```ts
22
+ * export default unstable_defineService('worker', ({bus}) => {
23
+ * const controller = new AbortController()
24
+ * bus.subscribe('workers.post', (message) => message.reply(snapshot), {
25
+ * signal: controller.signal,
26
+ * })
27
+ * // Views that are already listening post again.
28
+ * bus.emit('workers.message', {type: 'welcome'})
29
+ * return () => controller.abort()
30
+ * })
31
+ * ```
32
+ *
12
33
  * The callback can return a disposer, which runs when Dashboard stops the
13
34
  * worker. By then the bus is closed: subscriptions have ended, `emit` and
14
35
  * `query` reject with code `ABORTED`, and `subscribe` throws that error.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/defineService.ts"],"sourcesContent":["import {\n type MessageBus,\n type MessageBusAbortOptions,\n type StateTopic,\n type ValueOf,\n} from '@sanity/sdk/dashboard'\n\nimport {SERVICE_CONTRACT_VERSION, type ServiceType} from './contract.js'\n\n/**\n * The service's own declaration, surfaced to the callback.\n * @public\n */\nexport interface ServiceInfo {\n readonly name: string\n readonly type: string\n}\n\n/**\n * The message bus as a service sees it: `emit` and `query` as in the SDK, and\n * `subscribe` for state topics only. Only Dashboard can respond to its event\n * topics, so a service has no reason to subscribe to them. There is no\n * `disconnect`: Dashboard owns the connection and ends it when it stops the\n * worker.\n * @public\n */\nexport interface ServiceBus extends Omit<MessageBus, 'subscribe'> {\n /** Runs a handler for each state value until its signal aborts. */\n subscribe<K extends StateTopic>(\n type: K,\n handler: (value: ValueOf<K>) => void,\n options?: MessageBusAbortOptions,\n ): void\n}\n\n/**\n * Context every service callback receives when its worker starts. Mirrors how a\n * view component receives its `view` — the service receives its own `service`.\n * @public\n */\nexport interface ServiceContext {\n readonly bus: ServiceBus\n readonly service: ServiceInfo\n}\n\n/**\n * A service callback. Runs once inside the worker on start; returns an optional\n * disposer the host calls before terminating the worker.\n * @public\n */\nexport type ServiceCallback = (context: ServiceContext) => (() => void) | void\n\n/** The callback shape each service type defines, keyed by type. */\ninterface ServiceCallbacksByType {\n worker: ServiceCallback\n}\n\n/**\n * The result of `unstable_defineService`: the author's callback, the service\n * type, and the internal contract version the worker artifact targets.\n * @public\n */\nexport interface DefinedService<TType extends ServiceType = ServiceType> {\n readonly run: ServiceCallbacksByType[TType]\n readonly type: TType\n /** @internal */\n readonly version: typeof SERVICE_CONTRACT_VERSION\n}\n\n/**\n * Define a Sanity Dashboard background service. The first argument narrows the\n * callback shape — `\"worker\"` runs the callback inside a Web Worker.\n *\n * The callback receives `bus`, its connection to the Dashboard message bus:\n * `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the\n * current value of a state topic, and `bus.subscribe` runs a handler on each\n * new value of a state topic until its `signal` aborts. A refused, unanswered\n * or timed-out request rejects with an `Error` named `MessageBusError` whose\n * `code` says why; it is not an instance of the SDK's `MessageBusError` class.\n * The callback can return a disposer, which runs when Dashboard stops the\n * worker. By then the bus is closed: subscriptions have ended, `emit` and\n * `query` reject with code `ABORTED`, and `subscribe` throws that error.\n *\n * Identity at runtime: returns the callback tagged with its type and the contract\n * version, for the CLI build to generate a worker artifact from. Used as the\n * default export of a service's `src` file.\n * @public\n */\nexport function unstable_defineService<TType extends ServiceType>(\n type: TType,\n run: ServiceCallbacksByType[TType],\n): DefinedService<TType> {\n return {run, type, version: SERVICE_CONTRACT_VERSION}\n}\n"],"names":["SERVICE_CONTRACT_VERSION","unstable_defineService","type","run","version"],"mappings":"AAOA,SAAQA,wBAAwB,QAAyB,gBAAe;AA8DxE;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,uBACdC,IAAW,EACXC,GAAkC;IAElC,OAAO;QAACA;QAAKD;QAAME,SAASJ;IAAwB;AACtD"}
1
+ {"version":3,"sources":["../src/defineService.ts"],"sourcesContent":["import {\n type EventTopic,\n type MessageBus,\n type MessageBusAbortOptions,\n type MessageBusMessage,\n type PayloadOf,\n type ReplyOf,\n type StateTopic,\n type ValueOf,\n} from '@sanity/sdk/dashboard'\n\nimport {SERVICE_CONTRACT_VERSION, type ServiceType} from './contract.js'\n\n/**\n * The service's own declaration, surfaced to the callback.\n * @public\n */\nexport interface ServiceInfo {\n readonly name: string\n readonly type: string\n}\n\n/**\n * The message bus as a service sees it: the SDK's `MessageBus` without the\n * `subscribe` forms that return observables, which would make the service's\n * project install rxjs. There is no `disconnect`: Dashboard owns the connection\n * and ends it when it stops the worker.\n * @public\n */\nexport interface ServiceBus extends Omit<MessageBus, 'subscribe'> {\n /** Runs a responder for each event until its signal aborts. */\n subscribe<K extends EventTopic>(\n type: K,\n handler: (message: MessageBusMessage<PayloadOf<K>, ReplyOf<K>, K>) => void,\n options?: MessageBusAbortOptions,\n ): void\n /** Runs a handler for each state value until its signal aborts. */\n subscribe<K extends StateTopic>(\n type: K,\n handler: (value: ValueOf<K>) => void,\n options?: MessageBusAbortOptions,\n ): void\n}\n\n/**\n * Context every service callback receives when its worker starts. Mirrors how a\n * view component receives its `view` — the service receives its own `service`.\n * @public\n */\nexport interface ServiceContext {\n readonly bus: ServiceBus\n readonly service: ServiceInfo\n}\n\n/**\n * A service callback. Runs once inside the worker on start; returns an optional\n * disposer the host calls before terminating the worker.\n * @public\n */\nexport type ServiceCallback = (context: ServiceContext) => (() => void) | void\n\n/** The callback shape each service type defines, keyed by type. */\ninterface ServiceCallbacksByType {\n worker: ServiceCallback\n}\n\n/**\n * The result of `unstable_defineService`: the author's callback, the service\n * type, and the internal contract version the worker artifact targets.\n * @public\n */\nexport interface DefinedService<TType extends ServiceType = ServiceType> {\n readonly run: ServiceCallbacksByType[TType]\n readonly type: TType\n /** @internal */\n readonly version: typeof SERVICE_CONTRACT_VERSION\n}\n\n/**\n * Define a Sanity Dashboard background service. The first argument narrows the\n * callback shape — `\"worker\"` runs the callback inside a Web Worker.\n *\n * The callback receives `bus`, its connection to the Dashboard message bus:\n * `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the\n * current value of a state topic, and `bus.subscribe` runs a handler on each\n * new value of a state topic, or on each event of an event topic, until its\n * `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects\n * with an `Error` named `MessageBusError` whose `code` says why; it is not an\n * instance of the SDK's `MessageBusError` class.\n *\n * An event handler answers the sender with `message.reply(value)` or refuses\n * with `message.reject(reason)`; one that throws refuses with code\n * `HANDLER_THREW`. For example, a service that keeps a snapshot for its app's\n * views, which listen with `useWorker` first and then post to it. A view's post\n * arrives on `workers.post` as `{name, payload}`, and `workers.message` reaches\n * only this app's views:\n *\n * ```ts\n * export default unstable_defineService('worker', ({bus}) => {\n * const controller = new AbortController()\n * bus.subscribe('workers.post', (message) => message.reply(snapshot), {\n * signal: controller.signal,\n * })\n * // Views that are already listening post again.\n * bus.emit('workers.message', {type: 'welcome'})\n * return () => controller.abort()\n * })\n * ```\n *\n * The callback can return a disposer, which runs when Dashboard stops the\n * worker. By then the bus is closed: subscriptions have ended, `emit` and\n * `query` reject with code `ABORTED`, and `subscribe` throws that error.\n *\n * Identity at runtime: returns the callback tagged with its type and the contract\n * version, for the CLI build to generate a worker artifact from. Used as the\n * default export of a service's `src` file.\n * @public\n */\nexport function unstable_defineService<TType extends ServiceType>(\n type: TType,\n run: ServiceCallbacksByType[TType],\n): DefinedService<TType> {\n return {run, type, version: SERVICE_CONTRACT_VERSION}\n}\n"],"names":["SERVICE_CONTRACT_VERSION","unstable_defineService","type","run","version"],"mappings":"AAWA,SAAQA,wBAAwB,QAAyB,gBAAe;AAmExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,SAASC,uBACdC,IAAW,EACXC,GAAkC;IAElC,OAAO;QAACA;QAAKD;QAAME,SAASJ;IAAwB;AACtD"}
@@ -4,8 +4,24 @@
4
4
  // is not an app. The build and deploy accessors (actions/build, actions/deploy)
5
5
  // each build their command-specific view on top of this one brand-check +
6
6
  // extraction, so the discrimination lives in exactly one place.
7
+ import { defineWindowView } from './contract.js';
7
8
  import { isWorkbenchApp } from './defineApp.js';
8
9
  import { formatWorkbenchAppErrors, validateWorkbenchApp } from './validateWorkbenchApp.js';
10
+ /**
11
+ * The module behind the app's `./App` expose. `entry` is shorthand for a window view.
12
+ * @internal
13
+ */ export function resolveAppEntry(app) {
14
+ if (!isWorkbenchApp(app)) return app?.entry;
15
+ const views = app.entry === undefined ? app.views ?? [] : [
16
+ defineWindowView({
17
+ name: app.name ?? app.slug,
18
+ src: app.entry,
19
+ title: app.title
20
+ }),
21
+ ...app.views ?? []
22
+ ];
23
+ return views.find((view)=>view.surface === 'window')?.src;
24
+ }
9
25
  /**
10
26
  * Resolve the workbench app for a CLI config, or `null` for a plain project or a
11
27
  * config (which is not an app — read it with `resolveWorkbenchConfig`).
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/resolveWorkbenchApp.ts"],"sourcesContent":["// Package-internal shared resolver: turn a CLI config's branded\n// `defineApplication` app into its declared interfaces, or `null` for a plain\n// project — and for a config (a branded `unstable_defineMediaLibrary`), which\n// is not an app. The build and deploy accessors (actions/build, actions/deploy)\n// each build their command-specific view on top of this one brand-check +\n// extraction, so the discrimination lives in exactly one place.\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\n\nimport {type WorkbenchConfigValue} from './contract.js'\nimport {type DefineAppInput, isWorkbenchApp} from './defineApp.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from './validateWorkbenchApp.js'\n\n/**\n * Bundled so adding a declaration family touches this type and the artifact\n * expanders, not every hop of build/dev plumbing in between. `config` is sourced\n * from `resolveWorkbenchConfig` (a config is not an app), not from this resolver.\n * @internal\n */\nexport interface WorkbenchExposes {\n config?: WorkbenchConfigValue\n views?: DefineAppInput['views']\n webWorkers?: DefineAppInput['webWorkers']\n}\n\n/** @public */\nexport interface ResolvedWorkbenchApp {\n /**\n * Stable identity, distinct from the `slug` address. Defaults to `slug`, and is\n * what every identity key (build id, interface ids) is built from.\n */\n readonly name: string\n /** Organization that owns the app — part of its build-id identity. */\n readonly organizationId: string\n readonly slug: string\n\n /** Views the app declares. */\n readonly views: NonNullable<DefineAppInput['views']>\n\n /** Background web workers the app declares. */\n readonly webWorkers: NonNullable<DefineAppInput['webWorkers']>\n\n /** Resolved app kind — `studio` or one of the SDK app types. */\n readonly applicationType?: string\n /** SDK app-view entrypoint, when declared. */\n readonly entry?: string\n /** Path to the app's icon SVG, resolved and shipped to Brett on deploy. */\n readonly icon?: string\n /** Explicit singleton flag for Sanity-owned apps. */\n readonly isSingleton?: boolean\n /** Dashboard visibility declared by the app; `undefined` when unset. */\n readonly visibility?: AppVisibility\n}\n\n/**\n * Resolve the workbench app for a CLI config, or `null` for a plain project or a\n * config (which is not an app — read it with `resolveWorkbenchConfig`).\n * @public\n */\nexport function resolveWorkbenchApp(\n cliConfig: CliConfig | null | undefined,\n): ResolvedWorkbenchApp | null {\n const app = cliConfig?.app\n // A config carries a distinct brand, so `isWorkbenchApp` is false for it — it\n // resolves to `null` here, like a plain project.\n if (!isWorkbenchApp(app)) return null\n\n const errors = validateWorkbenchApp(app)\n if (errors.length > 0) throw new Error(formatWorkbenchAppErrors(errors))\n\n return {\n applicationType: app.applicationType,\n entry: app.entry,\n icon: app.icon,\n ...(app.isSingleton === undefined ? {} : {isSingleton: app.isSingleton}),\n // Identity defaults to the address, so existing apps behave identically.\n name: app.name ?? app.slug,\n organizationId: app.organizationId,\n slug: app.slug,\n views: app.views ?? [],\n visibility: app.visibility,\n webWorkers: app.webWorkers ?? [],\n }\n}\n"],"names":["isWorkbenchApp","formatWorkbenchAppErrors","validateWorkbenchApp","resolveWorkbenchApp","cliConfig","app","errors","length","Error","applicationType","entry","icon","isSingleton","undefined","name","slug","organizationId","views","visibility","webWorkers"],"mappings":"AAAA,gEAAgE;AAChE,8EAA8E;AAC9E,8EAA8E;AAC9E,gFAAgF;AAChF,0EAA0E;AAC1E,gEAAgE;AAKhE,SAA6BA,cAAc,QAAO,iBAAgB;AAClE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,4BAA2B;AA2CxF;;;;CAIC,GACD,OAAO,SAASC,oBACdC,SAAuC;IAEvC,MAAMC,MAAMD,WAAWC;IACvB,8EAA8E;IAC9E,iDAAiD;IACjD,IAAI,CAACL,eAAeK,MAAM,OAAO;IAEjC,MAAMC,SAASJ,qBAAqBG;IACpC,IAAIC,OAAOC,MAAM,GAAG,GAAG,MAAM,IAAIC,MAAMP,yBAAyBK;IAEhE,OAAO;QACLG,iBAAiBJ,IAAII,eAAe;QACpCC,OAAOL,IAAIK,KAAK;QAChBC,MAAMN,IAAIM,IAAI;QACd,GAAIN,IAAIO,WAAW,KAAKC,YAAY,CAAC,IAAI;YAACD,aAAaP,IAAIO,WAAW;QAAA,CAAC;QACvE,yEAAyE;QACzEE,MAAMT,IAAIS,IAAI,IAAIT,IAAIU,IAAI;QAC1BC,gBAAgBX,IAAIW,cAAc;QAClCD,MAAMV,IAAIU,IAAI;QACdE,OAAOZ,IAAIY,KAAK,IAAI,EAAE;QACtBC,YAAYb,IAAIa,UAAU;QAC1BC,YAAYd,IAAIc,UAAU,IAAI,EAAE;IAClC;AACF"}
1
+ {"version":3,"sources":["../src/resolveWorkbenchApp.ts"],"sourcesContent":["// Package-internal shared resolver: turn a CLI config's branded\n// `defineApplication` app into its declared interfaces, or `null` for a plain\n// project — and for a config (a branded `unstable_defineMediaLibrary`), which\n// is not an app. The build and deploy accessors (actions/build, actions/deploy)\n// each build their command-specific view on top of this one brand-check +\n// extraction, so the discrimination lives in exactly one place.\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\n\nimport {defineWindowView, type WorkbenchConfigValue} from './contract.js'\nimport {type DefineAppInput, isWorkbenchApp} from './defineApp.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from './validateWorkbenchApp.js'\n\n/**\n * Bundled so adding a declaration family touches this type and the artifact\n * expanders, not every hop of build/dev plumbing in between. `config` is sourced\n * from `resolveWorkbenchConfig` (a config is not an app), not from this resolver.\n * @internal\n */\nexport interface WorkbenchExposes {\n config?: WorkbenchConfigValue\n views?: DefineAppInput['views']\n webWorkers?: DefineAppInput['webWorkers']\n}\n\n/** @public */\nexport interface ResolvedWorkbenchApp {\n /**\n * Stable identity, distinct from the `slug` address. Defaults to `slug`, and is\n * what every identity key (build id, interface ids) is built from.\n */\n readonly name: string\n /** Organization that owns the app — part of its build-id identity. */\n readonly organizationId: string\n readonly slug: string\n\n /** Views the app declares. */\n readonly views: NonNullable<DefineAppInput['views']>\n\n /** Background web workers the app declares. */\n readonly webWorkers: NonNullable<DefineAppInput['webWorkers']>\n\n /** Resolved app kind — `studio` or one of the SDK app types. */\n readonly applicationType?: string\n /** SDK app-view entrypoint, when declared. */\n readonly entry?: string\n /** Path to the app's icon SVG, resolved and shipped to Brett on deploy. */\n readonly icon?: string\n /** Explicit singleton flag for Sanity-owned apps. */\n readonly isSingleton?: boolean\n /** Dashboard visibility declared by the app; `undefined` when unset. */\n readonly visibility?: AppVisibility\n}\n\n/**\n * The module behind the app's `./App` expose. `entry` is shorthand for a window view.\n * @internal\n */\nexport function resolveAppEntry(app: CliConfig['app']): string | undefined {\n if (!isWorkbenchApp(app)) return app?.entry\n\n const views =\n app.entry === undefined\n ? (app.views ?? [])\n : [\n defineWindowView({name: app.name ?? app.slug, src: app.entry, title: app.title}),\n ...(app.views ?? []),\n ]\n\n return views.find((view) => view.surface === 'window')?.src\n}\n\n/**\n * Resolve the workbench app for a CLI config, or `null` for a plain project or a\n * config (which is not an app — read it with `resolveWorkbenchConfig`).\n * @public\n */\nexport function resolveWorkbenchApp(\n cliConfig: CliConfig | null | undefined,\n): ResolvedWorkbenchApp | null {\n const app = cliConfig?.app\n // A config carries a distinct brand, so `isWorkbenchApp` is false for it — it\n // resolves to `null` here, like a plain project.\n if (!isWorkbenchApp(app)) return null\n\n const errors = validateWorkbenchApp(app)\n if (errors.length > 0) throw new Error(formatWorkbenchAppErrors(errors))\n\n return {\n applicationType: app.applicationType,\n entry: app.entry,\n icon: app.icon,\n ...(app.isSingleton === undefined ? {} : {isSingleton: app.isSingleton}),\n // Identity defaults to the address, so existing apps behave identically.\n name: app.name ?? app.slug,\n organizationId: app.organizationId,\n slug: app.slug,\n views: app.views ?? [],\n visibility: app.visibility,\n webWorkers: app.webWorkers ?? [],\n }\n}\n"],"names":["defineWindowView","isWorkbenchApp","formatWorkbenchAppErrors","validateWorkbenchApp","resolveAppEntry","app","entry","views","undefined","name","slug","src","title","find","view","surface","resolveWorkbenchApp","cliConfig","errors","length","Error","applicationType","icon","isSingleton","organizationId","visibility","webWorkers"],"mappings":"AAAA,gEAAgE;AAChE,8EAA8E;AAC9E,8EAA8E;AAC9E,gFAAgF;AAChF,0EAA0E;AAC1E,gEAAgE;AAIhE,SAAQA,gBAAgB,QAAkC,gBAAe;AACzE,SAA6BC,cAAc,QAAO,iBAAgB;AAClE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,4BAA2B;AA2CxF;;;CAGC,GACD,OAAO,SAASC,gBAAgBC,GAAqB;IACnD,IAAI,CAACJ,eAAeI,MAAM,OAAOA,KAAKC;IAEtC,MAAMC,QACJF,IAAIC,KAAK,KAAKE,YACTH,IAAIE,KAAK,IAAI,EAAE,GAChB;QACEP,iBAAiB;YAACS,MAAMJ,IAAII,IAAI,IAAIJ,IAAIK,IAAI;YAAEC,KAAKN,IAAIC,KAAK;YAAEM,OAAOP,IAAIO,KAAK;QAAA;WAC1EP,IAAIE,KAAK,IAAI,EAAE;KACpB;IAEP,OAAOA,MAAMM,IAAI,CAAC,CAACC,OAASA,KAAKC,OAAO,KAAK,WAAWJ;AAC1D;AAEA;;;;CAIC,GACD,OAAO,SAASK,oBACdC,SAAuC;IAEvC,MAAMZ,MAAMY,WAAWZ;IACvB,8EAA8E;IAC9E,iDAAiD;IACjD,IAAI,CAACJ,eAAeI,MAAM,OAAO;IAEjC,MAAMa,SAASf,qBAAqBE;IACpC,IAAIa,OAAOC,MAAM,GAAG,GAAG,MAAM,IAAIC,MAAMlB,yBAAyBgB;IAEhE,OAAO;QACLG,iBAAiBhB,IAAIgB,eAAe;QACpCf,OAAOD,IAAIC,KAAK;QAChBgB,MAAMjB,IAAIiB,IAAI;QACd,GAAIjB,IAAIkB,WAAW,KAAKf,YAAY,CAAC,IAAI;YAACe,aAAalB,IAAIkB,WAAW;QAAA,CAAC;QACvE,yEAAyE;QACzEd,MAAMJ,IAAII,IAAI,IAAIJ,IAAIK,IAAI;QAC1Bc,gBAAgBnB,IAAImB,cAAc;QAClCd,MAAML,IAAIK,IAAI;QACdH,OAAOF,IAAIE,KAAK,IAAI,EAAE;QACtBkB,YAAYpB,IAAIoB,UAAU;QAC1BC,YAAYrB,IAAIqB,UAAU,IAAI,EAAE;IAClC;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/workbench-cli",
3
- "version": "2.9.0",
3
+ "version": "2.11.0",
4
4
  "description": "Internal implementation detail of the Sanity CLI's unstable workbench support. Not intended for direct use.",
5
5
  "homepage": "https://github.com/sanity-io/cli",
6
6
  "bugs": "https://github.com/sanity-io/cli/issues",
@@ -63,7 +63,7 @@
63
63
  "dependencies": {
64
64
  "@module-federation/runtime": "2.9.2",
65
65
  "@module-federation/vite": "1.23.4",
66
- "@sanity/cli-core": "^3.9.1",
66
+ "@sanity/cli-core": "^3.9.2",
67
67
  "@sanity/sdk": "^3.8.0",
68
68
  "@sanity/types": "^6.17.0",
69
69
  "@vitejs/plugin-react": "^6.1.2",
@@ -78,7 +78,7 @@
78
78
  "@eslint/compat": "^2.1.0",
79
79
  "@repo/package.config": "0.0.1",
80
80
  "@repo/tsconfig": "3.70.0",
81
- "@sanity/cli-test": "19.0.1",
81
+ "@sanity/cli-test": "19.0.2",
82
82
  "@sanity/eslint-config-cli": "^1.1.3",
83
83
  "@sanity/pkg-utils": "^12.3.4",
84
84
  "@swc/cli": "^0.8.1",