@sanity/workbench-cli 1.1.0-beta.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Sanity.io
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,40 +1,23 @@
1
+ import { CliConfig } from "@sanity/cli-core";
2
+ import { Output } from "@sanity/cli-core";
3
+ import { ViteDevServer } from "vite";
1
4
  import { z } from "zod/mini";
2
5
 
3
6
  /**
4
- * Attempt to acquire an exclusive lock for the workbench process.
5
- * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one
6
- * process can create the file.
7
- *
8
- * The lock stores `{pid, host, port}` so other processes can find the
9
- * running workbench. Call `updatePort` after the Vite server starts to
10
- * write the actual port (Vite may pick a different one).
11
- *
12
- * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another
13
- * live process already holds it.
14
- */
15
- export declare function acquireWorkbenchLock(
16
- info: {
17
- host: string;
18
- port: number;
19
- },
20
- retries?: number,
21
- ): WorkbenchLock | undefined;
22
-
23
- /**
24
- * Resolve a directory to its canonical (long) form before handing it to
25
- * `fs.watch`.
26
- *
27
- * On Windows, `fs.watch` aborts with a libuv assertion
28
- * (`!_wcsnicmp(filename, dir, dirlen)` in `fs-event.c`) when the watched path
29
- * is an 8.3 short name — e.g. temp dirs under `RUNNER~1` — because the OS
30
- * reports long-form filenames that fail libuv's prefix check.
31
- * `realpathSync.native` expands short names to their long form so the
32
- * prefixes match.
33
- *
34
- * Falls back to the original path when it can't be resolved (e.g. it doesn't
35
- * exist yet), which is no worse than watching it directly.
7
+ * Minimal shape the supervisor needs back from a started app/studio dev server.
8
+ * The not-started arm is reserved for expected early exits the server already
9
+ * reported (e.g. a missing organization id) — a failure to *boot* still throws.
36
10
  */
37
- export declare function canonicalizeWatchDir(dir: string): string;
11
+ declare type AppServerResult =
12
+ | {
13
+ close: () => Promise<void>;
14
+ server: ViteDevServer;
15
+ started: true;
16
+ }
17
+ | {
18
+ reason: string;
19
+ started: false;
20
+ };
38
21
 
39
22
  /**
40
23
  * A manifest describing a running dev server process (studio or app).
@@ -43,7 +26,7 @@ export declare function canonicalizeWatchDir(dir: string): string;
43
26
  * The workbench singleton is tracked separately via the lock file — see
44
27
  * `acquireWorkbenchLock` and `readWorkbenchLock` below.
45
28
  */
46
- export declare type DevServerManifest = z.infer<typeof devServerManifestSchema>;
29
+ declare type DevServerManifest = z.infer<typeof devServerManifestSchema>;
47
30
 
48
31
  declare const devServerManifestSchema: z.ZodMiniObject<
49
32
  {
@@ -93,74 +76,47 @@ declare const devServerManifestSchema: z.ZodMiniObject<
93
76
  z.core.$strip
94
77
  >;
95
78
 
96
- declare interface DevServerRegistration {
97
- /** Remove the registry entry. */
98
- release: () => void;
99
- /**
100
- * Rewrite the registry entry with partial updates merged in. Also bumps the
101
- * file's mtime, which fires `watchRegistry` in any workbench process and
102
- * triggers a rebroadcast to connected clients.
103
- */
104
- update: (
105
- patch: Partial<Omit<DevServerManifest, "pid" | "startedAt" | "version">>,
106
- ) => void;
107
- }
108
-
109
- /**
110
- * Read all manifest files from the registry, prune stale entries (dead PIDs),
111
- * and return the live ones.
112
- */
113
- export declare function getRegisteredServers(): DevServerManifest[];
114
-
115
- /**
116
- * Read the workbench lock file and return its contents if the holding
117
- * process is still alive. Prunes stale locks from crashed processes.
118
- */
119
- export declare function readWorkbenchLock():
120
- | z.infer<typeof workbenchLockSchema>
121
- | undefined;
122
-
123
79
  /**
124
- * Write a manifest file for the current process and return a handle with a
125
- * `release` function that removes it plus an `update` function for patching
126
- * fields post-registration. Uses synchronous I/O so the file exists before
127
- * any signal handler could fire.
128
- */
129
- export declare function registerDevServer(
130
- manifest: Omit<DevServerManifest, "pid" | "startedAt" | "version">,
131
- ): DevServerRegistration;
132
-
133
- declare interface RegistryWatcher {
134
- close(): void;
135
- }
136
-
137
- /**
138
- * Watch the registry directory for changes and invoke the callback with the
139
- * current list of live servers whenever a change is detected.
80
+ * Orchestrate the dev servers a workbench project needs: a singleton workbench
81
+ * Vite server plus the app/studio dev server it renders, wired to the dev-server
82
+ * registry so view/service edits re-sync live.
140
83
  *
141
- * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a
142
- * server starting and writing its manifest triggers multiple FS events).
84
+ * A running workbench claims the configured port, so the app server binds the
85
+ * next one. If the workbench can't start (package or port unavailable), the app
86
+ * server falls back to the configured port and announces its own URL, exactly as
87
+ * a plain `sanity dev` would.
143
88
  */
144
- export declare function watchRegistry(
145
- callback: (servers: DevServerManifest[]) => void,
146
- ): RegistryWatcher;
89
+ export declare function startWorkbenchDev(
90
+ options: StartWorkbenchDevOptions,
91
+ ): Promise<{
92
+ close: () => Promise<void>;
93
+ }>;
147
94
 
148
- declare interface WorkbenchLock {
149
- /** Release the lock file. */
150
- release: () => void;
151
- /** Update the lock with the actual port after the server starts listening. */
152
- updatePort: (port: number) => void;
95
+ export declare interface StartWorkbenchDevOptions {
96
+ /** Resolved app id for the registry entry (the CLI owns id resolution). */
97
+ appId: string | undefined;
98
+ /** Directory for the workbench Vite server's dependency cache. */
99
+ cacheDir: string;
100
+ /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */
101
+ checkForDeprecatedAppId: () => void;
102
+ cliConfig: CliConfig;
103
+ /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */
104
+ extractManifest: (params: {
105
+ configPath: string;
106
+ workDir: string;
107
+ }) => Promise<DevServerManifest["manifest"]>;
108
+ httpHost: string | undefined;
109
+ httpPort: number;
110
+ isApp: boolean;
111
+ output: Output;
112
+ reactStrictMode: boolean;
113
+ /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */
114
+ startAppServer: (params: {
115
+ announceUrl: boolean;
116
+ cliConfig: CliConfig;
117
+ httpPort: number;
118
+ }) => Promise<AppServerResult>;
119
+ workDir: string;
153
120
  }
154
121
 
155
- declare const workbenchLockSchema: z.ZodMiniObject<
156
- {
157
- host: z.ZodMiniString<string>;
158
- pid: z.ZodMiniNumber<number>;
159
- port: z.ZodMiniNumber<number>;
160
- startedAt: z.ZodMiniString<string>;
161
- version: z.ZodMiniLiteral<1>;
162
- },
163
- z.core.$strip
164
- >;
165
-
166
122
  export {};
@@ -1,10 +1,3 @@
1
- // Node-only dev entry: the workbench dev-server registry the CLI's dev
2
- // orchestration drives. It tracks running studio/app dev servers (single
3
- // instance via a lock + PID-liveness), and the workbench host watches it to
4
- // render local panels/services without a deploy. The CLI owns the orchestration
5
- // (starting servers, extracting manifests); this package owns the registry it
6
- // registers into and watches.
7
- export { canonicalizeWatchDir } from '../actions/dev/canonicalizeWatchDir.js';
8
- export { acquireWorkbenchLock, getRegisteredServers, readWorkbenchLock, registerDevServer, watchRegistry } from '../actions/dev/registry.js';
1
+ export { startWorkbenchDev } from '../actions/dev/startWorkbenchDev.js';
9
2
 
10
3
  //# sourceMappingURL=dev.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/dev.ts"],"sourcesContent":["// Node-only dev entry: the workbench dev-server registry the CLI's dev\n// orchestration drives. It tracks running studio/app dev servers (single\n// instance via a lock + PID-liveness), and the workbench host watches it to\n// render local panels/services without a deploy. The CLI owns the orchestration\n// (starting servers, extracting manifests); this package owns the registry it\n// registers into and watches.\nexport {canonicalizeWatchDir} from '../actions/dev/canonicalizeWatchDir.js'\nexport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n readWorkbenchLock,\n registerDevServer,\n watchRegistry,\n} from '../actions/dev/registry.js'\n"],"names":["canonicalizeWatchDir","acquireWorkbenchLock","getRegisteredServers","readWorkbenchLock","registerDevServer","watchRegistry"],"mappings":"AAAA,uEAAuE;AACvE,yEAAyE;AACzE,4EAA4E;AAC5E,gFAAgF;AAChF,8EAA8E;AAC9E,8BAA8B;AAC9B,SAAQA,oBAAoB,QAAO,yCAAwC;AAC3E,SACEC,oBAAoB,EAEpBC,oBAAoB,EACpBC,iBAAiB,EACjBC,iBAAiB,EACjBC,aAAa,QACR,6BAA4B"}
1
+ {"version":3,"sources":["../../src/_exports/dev.ts"],"sourcesContent":["export {startWorkbenchDev, type StartWorkbenchDevOptions} from '../actions/dev/startWorkbenchDev.js'\n"],"names":["startWorkbenchDev"],"mappings":"AAAA,SAAQA,iBAAiB,QAAsC,sCAAqC"}
@@ -0,0 +1,66 @@
1
+ import { getCliConfigUncached } from '@sanity/cli-core';
2
+ const noop = async ()=>{};
3
+ /**
4
+ * Own the app/studio dev server's lifecycle behind the dev-server registry seam.
5
+ *
6
+ * Adding or removing a view/service rebuilds the federation remote: its
7
+ * module-federation `exposes` map and codegen artifacts are computed once at
8
+ * server start, so a newly-declared interface has no expose until the server is
9
+ * recreated — `server.restart()` can't do it (it reuses the inline config).
10
+ * `rebuild` therefore tears the server down and starts a fresh one with a
11
+ * reloaded config; the registry watcher calls it when the interface set changes.
12
+ *
13
+ * Returns the not-started result verbatim when the initial boot is an expected
14
+ * early exit, so the caller can skip the rest of the orchestration.
15
+ */ export async function startAppServerSupervisor(options) {
16
+ const { cliConfig, start, workDir } = options;
17
+ const initial = await start(cliConfig);
18
+ if (!initial.started) return {
19
+ reason: initial.reason,
20
+ started: false
21
+ };
22
+ // `closeCurrent` repoints at the replacement only once a rebuild succeeds, so a
23
+ // failed rebuild (old server already closed) leaves nothing for close() to re-close.
24
+ let server = initial.server;
25
+ let closeCurrent = initial.close;
26
+ let closed = false;
27
+ // close() waits on this so a rebuild racing teardown can't orphan the replacement.
28
+ // Rejections are the watcher's (warn + retry); the tracked copy is swallowed.
29
+ let rebuildInFlight = Promise.resolve();
30
+ const runRebuild = async ()=>{
31
+ // Refuse once shutting down — a config save in the teardown window must not
32
+ // boot a replacement nobody owns.
33
+ if (closed) throw new Error('Dev server is shutting down');
34
+ const freshConfig = await getCliConfigUncached(workDir);
35
+ await closeCurrent();
36
+ closeCurrent = noop;
37
+ const result = await start(freshConfig);
38
+ if (!result.started) {
39
+ // The server already reported why (e.g. organizationId was removed).
40
+ throw new Error('Dev server did not restart after the view/service change');
41
+ }
42
+ server = result.server;
43
+ closeCurrent = result.close;
44
+ return server;
45
+ };
46
+ return {
47
+ started: true,
48
+ supervisor: {
49
+ async close () {
50
+ closed = true;
51
+ await rebuildInFlight;
52
+ await closeCurrent();
53
+ },
54
+ rebuild () {
55
+ const rebuild = runRebuild();
56
+ rebuildInFlight = rebuild.catch(()=>{});
57
+ return rebuild;
58
+ },
59
+ get server () {
60
+ return server;
61
+ }
62
+ }
63
+ };
64
+ }
65
+
66
+ //# sourceMappingURL=appServerSupervisor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/dev/appServerSupervisor.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\n/**\n * Minimal shape the supervisor needs back from a started app/studio dev server.\n * The not-started arm is reserved for expected early exits the server already\n * reported (e.g. a missing organization id) — a failure to *boot* still throws.\n */\nexport type AppServerResult =\n | {close: () => Promise<void>; server: ViteDevServer; started: true}\n | {reason: string; started: false}\n\n/** Start the app/studio dev server for a given config (port + URL intent baked in by the caller). */\nexport type StartAppServer = (cliConfig: CliConfig) => Promise<AppServerResult>\n\nconst noop = async () => {}\n\nexport interface AppServerSupervisor {\n /** Stop the server once, waiting out any rebuild already in flight. */\n close: () => Promise<void>\n /** Tear down the running server and bring it back up with a freshly-loaded config. */\n rebuild: () => Promise<ViteDevServer>\n /** The currently-live dev server; re-points after a rebuild. */\n readonly server: ViteDevServer\n}\n\n/**\n * Own the app/studio dev server's lifecycle behind the dev-server registry seam.\n *\n * Adding or removing a view/service rebuilds the federation remote: its\n * module-federation `exposes` map and codegen artifacts are computed once at\n * server start, so a newly-declared interface has no expose until the server is\n * recreated — `server.restart()` can't do it (it reuses the inline config).\n * `rebuild` therefore tears the server down and starts a fresh one with a\n * reloaded config; the registry watcher calls it when the interface set changes.\n *\n * Returns the not-started result verbatim when the initial boot is an expected\n * early exit, so the caller can skip the rest of the orchestration.\n */\nexport async function startAppServerSupervisor(options: {\n cliConfig: CliConfig\n start: StartAppServer\n workDir: string\n}): Promise<{reason: string; started: false} | {started: true; supervisor: AppServerSupervisor}> {\n const {cliConfig, start, workDir} = options\n\n const initial = await start(cliConfig)\n if (!initial.started) return {reason: initial.reason, started: false}\n\n // `closeCurrent` repoints at the replacement only once a rebuild succeeds, so a\n // failed rebuild (old server already closed) leaves nothing for close() to re-close.\n let server = initial.server\n let closeCurrent = initial.close\n let closed = false\n // close() waits on this so a rebuild racing teardown can't orphan the replacement.\n // Rejections are the watcher's (warn + retry); the tracked copy is swallowed.\n let rebuildInFlight: Promise<unknown> = Promise.resolve()\n\n const runRebuild = async (): Promise<ViteDevServer> => {\n // Refuse once shutting down — a config save in the teardown window must not\n // boot a replacement nobody owns.\n if (closed) throw new Error('Dev server is shutting down')\n const freshConfig = await getCliConfigUncached(workDir)\n await closeCurrent()\n closeCurrent = noop\n const result = await start(freshConfig)\n if (!result.started) {\n // The server already reported why (e.g. organizationId was removed).\n throw new Error('Dev server did not restart after the view/service change')\n }\n server = result.server\n closeCurrent = result.close\n return server\n }\n\n return {\n started: true,\n supervisor: {\n async close() {\n closed = true\n await rebuildInFlight\n await closeCurrent()\n },\n rebuild() {\n const rebuild = runRebuild()\n rebuildInFlight = rebuild.catch(() => {})\n return rebuild\n },\n get server() {\n return server\n },\n },\n }\n}\n"],"names":["getCliConfigUncached","noop","startAppServerSupervisor","options","cliConfig","start","workDir","initial","started","reason","server","closeCurrent","close","closed","rebuildInFlight","Promise","resolve","runRebuild","Error","freshConfig","result","supervisor","rebuild","catch"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAO,mBAAkB;AAerE,MAAMC,OAAO,WAAa;AAW1B;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,yBAAyBC,OAI9C;IACC,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGH;IAEpC,MAAMI,UAAU,MAAMF,MAAMD;IAC5B,IAAI,CAACG,QAAQC,OAAO,EAAE,OAAO;QAACC,QAAQF,QAAQE,MAAM;QAAED,SAAS;IAAK;IAEpE,gFAAgF;IAChF,qFAAqF;IACrF,IAAIE,SAASH,QAAQG,MAAM;IAC3B,IAAIC,eAAeJ,QAAQK,KAAK;IAChC,IAAIC,SAAS;IACb,mFAAmF;IACnF,8EAA8E;IAC9E,IAAIC,kBAAoCC,QAAQC,OAAO;IAEvD,MAAMC,aAAa;QACjB,4EAA4E;QAC5E,kCAAkC;QAClC,IAAIJ,QAAQ,MAAM,IAAIK,MAAM;QAC5B,MAAMC,cAAc,MAAMnB,qBAAqBM;QAC/C,MAAMK;QACNA,eAAeV;QACf,MAAMmB,SAAS,MAAMf,MAAMc;QAC3B,IAAI,CAACC,OAAOZ,OAAO,EAAE;YACnB,qEAAqE;YACrE,MAAM,IAAIU,MAAM;QAClB;QACAR,SAASU,OAAOV,MAAM;QACtBC,eAAeS,OAAOR,KAAK;QAC3B,OAAOF;IACT;IAEA,OAAO;QACLF,SAAS;QACTa,YAAY;YACV,MAAMT;gBACJC,SAAS;gBACT,MAAMC;gBACN,MAAMH;YACR;YACAW;gBACE,MAAMA,UAAUL;gBAChBH,kBAAkBQ,QAAQC,KAAK,CAAC,KAAO;gBACvC,OAAOD;YACT;YACA,IAAIZ,UAAS;gBACX,OAAOA;YACT;QACF;IACF;AACF"}
@@ -0,0 +1,34 @@
1
+ import { isWorkbenchApp } from '@sanity/cli-core';
2
+ /**
3
+ * Map an app's `unstable_defineApp` config to the interface records forwarded on
4
+ * its registry entry: `views` → panels, `services` → workers, `entry` → the
5
+ * navigable `app` view (`entry_point` is the raw `src`, not a resolved URL).
6
+ * `undefined` for a non-branded app; a studio that declares `entry` is rejected
7
+ * (studio app views are not implemented yet).
8
+ */ export function deriveInterfaces(app, options) {
9
+ if (!isWorkbenchApp(app)) return undefined;
10
+ if (!options.isApp && app.entry !== undefined) {
11
+ throw new Error('App views for studios are not implemented yet');
12
+ }
13
+ return [
14
+ ...app.views?.map((view)=>({
15
+ entry_point: view.src,
16
+ interface_type: view.type,
17
+ name: view.name
18
+ })) ?? [],
19
+ ...app.services?.map((service)=>({
20
+ entry_point: service.src,
21
+ interface_type: service.type,
22
+ name: service.name
23
+ })) ?? [],
24
+ ...app.entry === undefined ? [] : [
25
+ {
26
+ entry_point: app.entry,
27
+ interface_type: 'app',
28
+ name: app.name
29
+ }
30
+ ]
31
+ ];
32
+ }
33
+
34
+ //# sourceMappingURL=deriveInterfaces.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/dev/deriveInterfaces.ts"],"sourcesContent":["import {type CliConfig, isWorkbenchApp} from '@sanity/cli-core'\n\nimport {type DevServerManifest} from './registry.js'\n\n/** One forwarded interface record on the dev-server registry entry. */\nexport type DevServerInterface = NonNullable<DevServerManifest['interfaces']>[number]\n\n/**\n * Map an app's `unstable_defineApp` config to the interface records forwarded on\n * its registry entry: `views` → panels, `services` → workers, `entry` → the\n * navigable `app` view (`entry_point` is the raw `src`, not a resolved URL).\n * `undefined` for a non-branded app; a studio that declares `entry` is rejected\n * (studio app views are not implemented yet).\n */\nexport function deriveInterfaces(\n app: CliConfig['app'],\n options: {isApp: boolean},\n): DevServerInterface[] | undefined {\n if (!isWorkbenchApp(app)) return undefined\n\n if (!options.isApp && app.entry !== undefined) {\n throw new Error('App views for studios are not implemented yet')\n }\n\n return [\n ...(app.views?.map((view) => ({\n entry_point: view.src,\n interface_type: view.type,\n name: view.name,\n })) ?? []),\n ...(app.services?.map((service) => ({\n entry_point: service.src,\n interface_type: service.type,\n name: service.name,\n })) ?? []),\n ...(app.entry === undefined\n ? []\n : [{entry_point: app.entry, interface_type: 'app' as const, name: app.name}]),\n ]\n}\n"],"names":["isWorkbenchApp","deriveInterfaces","app","options","undefined","isApp","entry","Error","views","map","view","entry_point","src","interface_type","type","name","services","service"],"mappings":"AAAA,SAAwBA,cAAc,QAAO,mBAAkB;AAO/D;;;;;;CAMC,GACD,OAAO,SAASC,iBACdC,GAAqB,EACrBC,OAAyB;IAEzB,IAAI,CAACH,eAAeE,MAAM,OAAOE;IAEjC,IAAI,CAACD,QAAQE,KAAK,IAAIH,IAAII,KAAK,KAAKF,WAAW;QAC7C,MAAM,IAAIG,MAAM;IAClB;IAEA,OAAO;WACDL,IAAIM,KAAK,EAAEC,IAAI,CAACC,OAAU,CAAA;gBAC5BC,aAAaD,KAAKE,GAAG;gBACrBC,gBAAgBH,KAAKI,IAAI;gBACzBC,MAAML,KAAKK,IAAI;YACjB,CAAA,MAAO,EAAE;WACLb,IAAIc,QAAQ,EAAEP,IAAI,CAACQ,UAAa,CAAA;gBAClCN,aAAaM,QAAQL,GAAG;gBACxBC,gBAAgBI,QAAQH,IAAI;gBAC5BC,MAAME,QAAQF,IAAI;YACpB,CAAA,MAAO,EAAE;WACLb,IAAII,KAAK,KAAKF,YACd,EAAE,GACF;YAAC;gBAACO,aAAaT,IAAII,KAAK;gBAAEO,gBAAgB;gBAAgBE,MAAMb,IAAIa,IAAI;YAAA;SAAE;KAC/E;AACH"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Order-independent identity of an app's interface set. Reordering
3
+ * `views`/`services` keeps the same id (not a change); adding, removing,
4
+ * renaming, or repointing one changes it. `undefined` ids to the empty set.
5
+ */ export function interfaceSetId(interfaces) {
6
+ if (!interfaces || interfaces.length === 0) return '';
7
+ return interfaces.map((iface)=>[
8
+ iface.interface_type,
9
+ iface.name,
10
+ iface.entry_point
11
+ ].join('::')).toSorted().join('|');
12
+ }
13
+ /**
14
+ * Tracks one app's interface set across config reloads. `changed` and `commit`
15
+ * are split so the caller commits only after the rebuild that depends on the new
16
+ * set succeeds — a thrown rebuild leaves it uncommitted, so the next save retries
17
+ * instead of skipping. Seed with the initially registered set.
18
+ */ export function trackInterfaceSet(initial) {
19
+ let lastId = interfaceSetId(initial);
20
+ return {
21
+ changed: (interfaces)=>interfaceSetId(interfaces) !== lastId,
22
+ commit: (interfaces)=>{
23
+ lastId = interfaceSetId(interfaces);
24
+ }
25
+ };
26
+ }
27
+ const serverKey = (server)=>`${server.id ?? ''}@${server.host ?? ''}:${server.port}`;
28
+ /**
29
+ * Tracks every registered app's interface set across registry snapshots (the
30
+ * multi-app counterpart to {@link trackInterfaceSet}). `hasChanged` is true when
31
+ * a *known* app's set changed since the last call — its remote was rebuilt with
32
+ * new exposes, so the workbench must full-reload to drop the stale remote-entry.
33
+ * A new/removed app or manifest-only edit isn't a rebuild.
34
+ */ export function createInterfacesTracker() {
35
+ let known = new Map();
36
+ return {
37
+ hasChanged (servers) {
38
+ const rebuilt = servers.some((server)=>{
39
+ const key = serverKey(server);
40
+ return known.has(key) && known.get(key) !== interfaceSetId(server.interfaces);
41
+ });
42
+ known = new Map(servers.map((server)=>[
43
+ serverKey(server),
44
+ interfaceSetId(server.interfaces)
45
+ ]));
46
+ return rebuilt;
47
+ }
48
+ };
49
+ }
50
+
51
+ //# sourceMappingURL=interfaceSetId.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/dev/interfaceSetId.ts"],"sourcesContent":["import {type DevServerInterface} from './deriveInterfaces.js'\nimport {type DevServerManifest} from './registry.js'\n\n/**\n * Order-independent identity of an app's interface set. Reordering\n * `views`/`services` keeps the same id (not a change); adding, removing,\n * renaming, or repointing one changes it. `undefined` ids to the empty set.\n */\nexport function interfaceSetId(interfaces: readonly DevServerInterface[] | undefined): string {\n if (!interfaces || interfaces.length === 0) return ''\n return interfaces\n .map((iface) => [iface.interface_type, iface.name, iface.entry_point].join('::'))\n .toSorted()\n .join('|')\n}\n\n/**\n * Tracks one app's interface set across config reloads. `changed` and `commit`\n * are split so the caller commits only after the rebuild that depends on the new\n * set succeeds — a thrown rebuild leaves it uncommitted, so the next save retries\n * instead of skipping. Seed with the initially registered set.\n */\nexport function trackInterfaceSet(initial: readonly DevServerInterface[] | undefined): {\n changed: (interfaces: readonly DevServerInterface[] | undefined) => boolean\n commit: (interfaces: readonly DevServerInterface[] | undefined) => void\n} {\n let lastId = interfaceSetId(initial)\n return {\n changed: (interfaces) => interfaceSetId(interfaces) !== lastId,\n commit: (interfaces) => {\n lastId = interfaceSetId(interfaces)\n },\n }\n}\n\nconst serverKey = (server: DevServerManifest): string =>\n `${server.id ?? ''}@${server.host ?? ''}:${server.port}`\n\n/**\n * Tracks every registered app's interface set across registry snapshots (the\n * multi-app counterpart to {@link trackInterfaceSet}). `hasChanged` is true when\n * a *known* app's set changed since the last call — its remote was rebuilt with\n * new exposes, so the workbench must full-reload to drop the stale remote-entry.\n * A new/removed app or manifest-only edit isn't a rebuild.\n */\nexport function createInterfacesTracker(): {\n hasChanged: (servers: readonly DevServerManifest[]) => boolean\n} {\n let known = new Map<string, string>()\n return {\n hasChanged(servers) {\n const rebuilt = servers.some((server) => {\n const key = serverKey(server)\n return known.has(key) && known.get(key) !== interfaceSetId(server.interfaces)\n })\n known = new Map(\n servers.map((server) => [serverKey(server), interfaceSetId(server.interfaces)]),\n )\n return rebuilt\n },\n }\n}\n"],"names":["interfaceSetId","interfaces","length","map","iface","interface_type","name","entry_point","join","toSorted","trackInterfaceSet","initial","lastId","changed","commit","serverKey","server","id","host","port","createInterfacesTracker","known","Map","hasChanged","servers","rebuilt","some","key","has","get"],"mappings":"AAGA;;;;CAIC,GACD,OAAO,SAASA,eAAeC,UAAqD;IAClF,IAAI,CAACA,cAAcA,WAAWC,MAAM,KAAK,GAAG,OAAO;IACnD,OAAOD,WACJE,GAAG,CAAC,CAACC,QAAU;YAACA,MAAMC,cAAc;YAAED,MAAME,IAAI;YAAEF,MAAMG,WAAW;SAAC,CAACC,IAAI,CAAC,OAC1EC,QAAQ,GACRD,IAAI,CAAC;AACV;AAEA;;;;;CAKC,GACD,OAAO,SAASE,kBAAkBC,OAAkD;IAIlF,IAAIC,SAASZ,eAAeW;IAC5B,OAAO;QACLE,SAAS,CAACZ,aAAeD,eAAeC,gBAAgBW;QACxDE,QAAQ,CAACb;YACPW,SAASZ,eAAeC;QAC1B;IACF;AACF;AAEA,MAAMc,YAAY,CAACC,SACjB,GAAGA,OAAOC,EAAE,IAAI,GAAG,CAAC,EAAED,OAAOE,IAAI,IAAI,GAAG,CAAC,EAAEF,OAAOG,IAAI,EAAE;AAE1D;;;;;;CAMC,GACD,OAAO,SAASC;IAGd,IAAIC,QAAQ,IAAIC;IAChB,OAAO;QACLC,YAAWC,OAAO;YAChB,MAAMC,UAAUD,QAAQE,IAAI,CAAC,CAACV;gBAC5B,MAAMW,MAAMZ,UAAUC;gBACtB,OAAOK,MAAMO,GAAG,CAACD,QAAQN,MAAMQ,GAAG,CAACF,SAAS3B,eAAegB,OAAOf,UAAU;YAC9E;YACAoB,QAAQ,IAAIC,IACVE,QAAQrB,GAAG,CAAC,CAACa,SAAW;oBAACD,UAAUC;oBAAShB,eAAegB,OAAOf,UAAU;iBAAE;YAEhF,OAAOwB;QACT;IACF;AACF"}
@@ -0,0 +1,104 @@
1
+ import { watch } from 'node:fs';
2
+ import { basename, dirname } from 'node:path';
3
+ import { findProjectRoot, subdebug } from '@sanity/cli-core';
4
+ import { canonicalizeWatchDir } from './canonicalizeWatchDir.js';
5
+ const devDebug = subdebug('dev');
6
+ /**
7
+ * Debounce window between config file events and the next manifest
8
+ * regeneration. Coalesces rapid saves (e.g. editor auto-save) and
9
+ * atomic-rename bursts emitted by tools like VS Code.
10
+ */ const DEBOUNCE_MS = 250;
11
+ /**
12
+ * Generate the project manifest once and then keep it in sync with the
13
+ * project's config file (`sanity.config.(ts|js)` for studios,
14
+ * `sanity.cli.(ts|js)` for core-apps) on disk. The initial generation runs
15
+ * fire-and-forget so it doesn't block dev-server startup; subsequent
16
+ * file-system events are coalesced behind it, so the extractor never has
17
+ * overlapping writes to its shared output directory. Each successful
18
+ * regeneration inlines the new manifest into the registry via the `update`
19
+ * callback, so any running workbench rebroadcasts to its clients.
20
+ *
21
+ * Errors during extraction are logged as warnings and do not crash the dev
22
+ * server — the previously extracted manifest (if any) stays in the
23
+ * registry.
24
+ */ export async function startDevManifestWatcher({ extract, extraWatchFilenames, output, update, workDir }) {
25
+ const projectRoot = await findProjectRoot(workDir);
26
+ const configPath = projectRoot.path;
27
+ let running = false;
28
+ let pending = false;
29
+ let closed = false;
30
+ const regenerate = async ()=>{
31
+ if (closed) return;
32
+ if (running) {
33
+ pending = true;
34
+ return;
35
+ }
36
+ running = true;
37
+ try {
38
+ const { interfaces, manifest } = await extract({
39
+ configPath,
40
+ workDir
41
+ });
42
+ if (closed) return;
43
+ await update({
44
+ interfaces,
45
+ manifest,
46
+ manifestUpdatedAt: new Date().toISOString()
47
+ });
48
+ } catch (err) {
49
+ // Extractors print their own spinner failure; log the reason here so
50
+ // the user sees what went wrong alongside the spinner indicator.
51
+ devDebug('Manifest regeneration failed: %O', err);
52
+ output.warn(`Could not extract manifest for workbench: ${err instanceof Error ? err.message : String(err)}`);
53
+ } finally{
54
+ running = false;
55
+ if (pending && !closed) {
56
+ pending = false;
57
+ void regenerate();
58
+ }
59
+ }
60
+ };
61
+ // Route the initial extraction through `regenerate` too, so file-system
62
+ // events arriving before it finishes get coalesced rather than racing it
63
+ // for the shared output directory.
64
+ void regenerate();
65
+ // Watch the config file's parent directory and filter by filename.
66
+ // Watching the file itself is unreliable across editors that perform
67
+ // atomic-save (delete + rename) — the watcher loses its target once the
68
+ // inode changes. Directory watches survive those transitions.
69
+ // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows
70
+ // short-path dirs. See `canonicalizeWatchDir`.
71
+ const configDir = canonicalizeWatchDir(dirname(configPath));
72
+ const watchFilenames = new Set([
73
+ basename(configPath),
74
+ ...extraWatchFilenames ?? []
75
+ ]);
76
+ let debounceTimer;
77
+ const onEvent = (_event, filename)=>{
78
+ if (!filename) return;
79
+ const name = typeof filename === 'string' ? filename : filename.toString('utf8');
80
+ if (!watchFilenames.has(name)) return;
81
+ clearTimeout(debounceTimer);
82
+ debounceTimer = setTimeout(()=>{
83
+ void regenerate();
84
+ }, DEBOUNCE_MS);
85
+ };
86
+ const watcher = watch(configDir, onEvent);
87
+ watcher.on('error', (err)=>{
88
+ devDebug('Config watcher error: %O', err);
89
+ output.warn(`Manifest watcher error: ${err instanceof Error ? err.message : String(err)}`);
90
+ });
91
+ return {
92
+ // Idempotent — a repeat close (e.g. a signal handler racing an explicit
93
+ // close) is a no-op, so we never clear an already-cleared timer or
94
+ // double-close the underlying watcher.
95
+ close: async ()=>{
96
+ if (closed) return;
97
+ closed = true;
98
+ clearTimeout(debounceTimer);
99
+ watcher.close();
100
+ }
101
+ };
102
+ }
103
+
104
+ //# sourceMappingURL=startDevManifestWatcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/dev/startDevManifestWatcher.ts"],"sourcesContent":["import {watch} from 'node:fs'\nimport {basename, dirname} from 'node:path'\n\nimport {findProjectRoot, type Output, subdebug} from '@sanity/cli-core'\n\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {type DevServerInterface} from './deriveInterfaces.js'\n\nconst devDebug = subdebug('dev')\n\n/**\n * Debounce window between config file events and the next manifest\n * regeneration. Coalesces rapid saves (e.g. editor auto-save) and\n * atomic-rename bursts emitted by tools like VS Code.\n */\nconst DEBOUNCE_MS = 250\n\ninterface DevManifestWatcher {\n close: () => Promise<void>\n}\n\n/** Subset of registry fields the watcher is allowed to update. */\ninterface ManifestPatch<T> {\n manifest: T | undefined\n manifestUpdatedAt: string\n\n /**\n * Workbench interfaces (views/services/app view) re-derived from the config\n * on each change, so editing `views`/`services`/`entry` in `sanity.cli.ts`\n * re-syncs live like `title`/`icon`. `undefined` only for\n * non-branded configs — the registry patch is a shallow merge, so extractors\n * must re-derive rather than omit, or the registered set gets wiped.\n */\n interfaces?: DevServerInterface[] | undefined\n}\n\ninterface StartDevManifestWatcherOptions<T> {\n /**\n * Run the project-specific extraction and resolve to the inlined manifest\n * plus the workbench `interfaces[]` (when the project declares them).\n * Receives the resolved config path (e.g. `sanity.config.ts` for studios,\n * `sanity.cli.ts` for core-apps) and the working directory.\n */\n extract: (params: {\n configPath: string\n workDir: string\n }) => Promise<{interfaces?: DevServerInterface[] | undefined; manifest: T | undefined}>\n output: Output\n /**\n * Called after every successful extraction with the inlined manifest +\n * interfaces. Awaited, so an interface-set change can rebuild the federation\n * remote before the registry is patched (which is what reloads the workbench).\n */\n update: (patch: ManifestPatch<T>) => Promise<void> | void\n workDir: string\n\n /**\n * Extra config filenames (basenames in the project root directory) that also\n * trigger a regeneration. Studios resolve their project root via\n * `sanity.config.*` but declare workbench interfaces in `sanity.cli.*`, so\n * their watcher needs to react to both files.\n */\n extraWatchFilenames?: readonly string[]\n}\n\n/**\n * Generate the project manifest once and then keep it in sync with the\n * project's config file (`sanity.config.(ts|js)` for studios,\n * `sanity.cli.(ts|js)` for core-apps) on disk. The initial generation runs\n * fire-and-forget so it doesn't block dev-server startup; subsequent\n * file-system events are coalesced behind it, so the extractor never has\n * overlapping writes to its shared output directory. Each successful\n * regeneration inlines the new manifest into the registry via the `update`\n * callback, so any running workbench rebroadcasts to its clients.\n *\n * Errors during extraction are logged as warnings and do not crash the dev\n * server — the previously extracted manifest (if any) stays in the\n * registry.\n */\nexport async function startDevManifestWatcher<T>({\n extract,\n extraWatchFilenames,\n output,\n update,\n workDir,\n}: StartDevManifestWatcherOptions<T>): Promise<DevManifestWatcher> {\n const projectRoot = await findProjectRoot(workDir)\n const configPath = projectRoot.path\n\n let running = false\n let pending = false\n let closed = false\n\n const regenerate = async () => {\n if (closed) return\n if (running) {\n pending = true\n return\n }\n running = true\n try {\n const {interfaces, manifest} = await extract({configPath, workDir})\n if (closed) return\n await update({interfaces, manifest, manifestUpdatedAt: new Date().toISOString()})\n } catch (err) {\n // Extractors print their own spinner failure; log the reason here so\n // the user sees what went wrong alongside the spinner indicator.\n devDebug('Manifest regeneration failed: %O', err)\n output.warn(\n `Could not extract manifest for workbench: ${err instanceof Error ? err.message : String(err)}`,\n )\n } finally {\n running = false\n if (pending && !closed) {\n pending = false\n void regenerate()\n }\n }\n }\n\n // Route the initial extraction through `regenerate` too, so file-system\n // events arriving before it finishes get coalesced rather than racing it\n // for the shared output directory.\n void regenerate()\n\n // Watch the config file's parent directory and filter by filename.\n // Watching the file itself is unreliable across editors that perform\n // atomic-save (delete + rename) — the watcher loses its target once the\n // inode changes. Directory watches survive those transitions.\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const configDir = canonicalizeWatchDir(dirname(configPath))\n const watchFilenames = new Set([basename(configPath), ...(extraWatchFilenames ?? [])])\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const onEvent = (_event: string, filename: Buffer | string | null) => {\n if (!filename) return\n const name = typeof filename === 'string' ? filename : filename.toString('utf8')\n if (!watchFilenames.has(name)) return\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n void regenerate()\n }, DEBOUNCE_MS)\n }\n\n const watcher = watch(configDir, onEvent)\n\n watcher.on('error', (err) => {\n devDebug('Config watcher error: %O', err)\n output.warn(`Manifest watcher error: ${err instanceof Error ? err.message : String(err)}`)\n })\n\n return {\n // Idempotent — a repeat close (e.g. a signal handler racing an explicit\n // close) is a no-op, so we never clear an already-cleared timer or\n // double-close the underlying watcher.\n close: async () => {\n if (closed) return\n closed = true\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n"],"names":["watch","basename","dirname","findProjectRoot","subdebug","canonicalizeWatchDir","devDebug","DEBOUNCE_MS","startDevManifestWatcher","extract","extraWatchFilenames","output","update","workDir","projectRoot","configPath","path","running","pending","closed","regenerate","interfaces","manifest","manifestUpdatedAt","Date","toISOString","err","warn","Error","message","String","configDir","watchFilenames","Set","debounceTimer","onEvent","_event","filename","name","toString","has","clearTimeout","setTimeout","watcher","on","close"],"mappings":"AAAA,SAAQA,KAAK,QAAO,UAAS;AAC7B,SAAQC,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAE3C,SAAQC,eAAe,EAAeC,QAAQ,QAAO,mBAAkB;AAEvE,SAAQC,oBAAoB,QAAO,4BAA2B;AAG9D,MAAMC,WAAWF,SAAS;AAE1B;;;;CAIC,GACD,MAAMG,cAAc;AAkDpB;;;;;;;;;;;;;CAaC,GACD,OAAO,eAAeC,wBAA2B,EAC/CC,OAAO,EACPC,mBAAmB,EACnBC,MAAM,EACNC,MAAM,EACNC,OAAO,EAC2B;IAClC,MAAMC,cAAc,MAAMX,gBAAgBU;IAC1C,MAAME,aAAaD,YAAYE,IAAI;IAEnC,IAAIC,UAAU;IACd,IAAIC,UAAU;IACd,IAAIC,SAAS;IAEb,MAAMC,aAAa;QACjB,IAAID,QAAQ;QACZ,IAAIF,SAAS;YACXC,UAAU;YACV;QACF;QACAD,UAAU;QACV,IAAI;YACF,MAAM,EAACI,UAAU,EAAEC,QAAQ,EAAC,GAAG,MAAMb,QAAQ;gBAACM;gBAAYF;YAAO;YACjE,IAAIM,QAAQ;YACZ,MAAMP,OAAO;gBAACS;gBAAYC;gBAAUC,mBAAmB,IAAIC,OAAOC,WAAW;YAAE;QACjF,EAAE,OAAOC,KAAK;YACZ,qEAAqE;YACrE,iEAAiE;YACjEpB,SAAS,oCAAoCoB;YAC7Cf,OAAOgB,IAAI,CACT,CAAC,0CAA0C,EAAED,eAAeE,QAAQF,IAAIG,OAAO,GAAGC,OAAOJ,MAAM;QAEnG,SAAU;YACRT,UAAU;YACV,IAAIC,WAAW,CAACC,QAAQ;gBACtBD,UAAU;gBACV,KAAKE;YACP;QACF;IACF;IAEA,wEAAwE;IACxE,yEAAyE;IACzE,mCAAmC;IACnC,KAAKA;IAEL,mEAAmE;IACnE,qEAAqE;IACrE,wEAAwE;IACxE,8DAA8D;IAC9D,4EAA4E;IAC5E,+CAA+C;IAC/C,MAAMW,YAAY1B,qBAAqBH,QAAQa;IAC/C,MAAMiB,iBAAiB,IAAIC,IAAI;QAAChC,SAASc;WAAiBL,uBAAuB,EAAE;KAAE;IAErF,IAAIwB;IAEJ,MAAMC,UAAU,CAACC,QAAgBC;QAC/B,IAAI,CAACA,UAAU;QACf,MAAMC,OAAO,OAAOD,aAAa,WAAWA,WAAWA,SAASE,QAAQ,CAAC;QACzE,IAAI,CAACP,eAAeQ,GAAG,CAACF,OAAO;QAC/BG,aAAaP;QACbA,gBAAgBQ,WAAW;YACzB,KAAKtB;QACP,GAAGb;IACL;IAEA,MAAMoC,UAAU3C,MAAM+B,WAAWI;IAEjCQ,QAAQC,EAAE,CAAC,SAAS,CAAClB;QACnBpB,SAAS,4BAA4BoB;QACrCf,OAAOgB,IAAI,CAAC,CAAC,wBAAwB,EAAED,eAAeE,QAAQF,IAAIG,OAAO,GAAGC,OAAOJ,MAAM;IAC3F;IAEA,OAAO;QACL,wEAAwE;QACxE,mEAAmE;QACnE,uCAAuC;QACvCmB,OAAO;YACL,IAAI1B,QAAQ;YACZA,SAAS;YACTsB,aAAaP;YACbS,QAAQE,KAAK;QACf;IACF;AACF"}
@@ -0,0 +1,78 @@
1
+ import { getCliConfigUncached } from '@sanity/cli-core';
2
+ import { deriveInterfaces } from './deriveInterfaces.js';
3
+ import { trackInterfaceSet } from './interfaceSetId.js';
4
+ import { registerDevServer } from './registry.js';
5
+ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
6
+ /** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */ function serverAddress(server) {
7
+ const resolvedHost = server.config.server.host;
8
+ const addr = server.httpServer?.address();
9
+ return {
10
+ host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',
11
+ port: typeof addr === 'object' && addr ? addr.port : server.config.server.port
12
+ };
13
+ }
14
+ /**
15
+ * Register the dev server in the registry and watch its config for manifest +
16
+ * interface changes. The workbench reads the entry to locate and render the
17
+ * server; the watcher keeps it current as `sanity.cli.ts` is edited.
18
+ */ export async function startDevServerRegistration(options) {
19
+ const { appId, cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir } = options;
20
+ const { host: appHost, port: appPort } = serverAddress(server);
21
+ // Forwarded alongside (not inside) the manifest so the workbench renders local
22
+ // panels/workers without a deploy; the watcher re-derives them on each edit.
23
+ const interfaces = deriveInterfaces(cliConfig.app, {
24
+ isApp
25
+ });
26
+ const registration = registerDevServer({
27
+ host: appHost,
28
+ id: appId,
29
+ interfaces,
30
+ port: appPort,
31
+ projectId: cliConfig?.api?.projectId,
32
+ type: isApp ? 'coreApp' : 'studio',
33
+ workDir
34
+ });
35
+ const interfaceSet = trackInterfaceSet(interfaces);
36
+ const watcher = await startDevManifestWatcher({
37
+ // Re-derive interfaces every pass (don't omit): the registry patch is a
38
+ // shallow merge, so omitting would wipe the registered set.
39
+ extract: async (params)=>({
40
+ interfaces: deriveInterfaces((await getCliConfigUncached(params.workDir)).app, {
41
+ isApp
42
+ }),
43
+ manifest: await extractManifest(params)
44
+ }),
45
+ // A studio's root resolves to `sanity.config.*` but its interfaces live in
46
+ // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.
47
+ extraWatchFilenames: isApp ? undefined : [
48
+ 'sanity.cli.js',
49
+ 'sanity.cli.ts'
50
+ ],
51
+ output,
52
+ update: async (patch)=>{
53
+ if (!interfaceSet.changed(patch.interfaces)) {
54
+ registration.update(patch);
55
+ return;
56
+ }
57
+ // Rebuild the remote *before* patching the registry — the patch reloads the
58
+ // page, which must re-fetch a remote that already exposes the new interface.
59
+ const rebuiltServer = await onInterfaceSetChange?.();
60
+ // Commit only after a successful rebuild, so a thrown one retries next pass.
61
+ interfaceSet.commit(patch.interfaces);
62
+ // The recreated server can bind a different port (non-strict ports).
63
+ registration.update(rebuiltServer ? {
64
+ ...patch,
65
+ ...serverAddress(rebuiltServer)
66
+ } : patch);
67
+ },
68
+ workDir
69
+ });
70
+ return {
71
+ close: async ()=>{
72
+ registration.release();
73
+ await watcher.close();
74
+ }
75
+ };
76
+ }
77
+
78
+ //# sourceMappingURL=startDevServerRegistration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {deriveInterfaces} from './deriveInterfaces.js'\nimport {trackInterfaceSet} from './interfaceSetId.js'\nimport {type DevServerManifest, registerDevServer} from './registry.js'\nimport {startDevManifestWatcher} from './startDevManifestWatcher.js'\n\ninterface DevServerRegistrationOptions {\n /** Resolved app id for the registry entry; the caller owns id resolution and the deprecation check. */\n appId: string | undefined\n cliConfig: CliConfig\n /**\n * Extract the project manifest to inline into the registry. The caller owns the\n * studio-vs-app split (manifest formats are CLI-domain); registration re-derives\n * the interface set alongside it.\n */\n extractManifest: (params: {\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n isApp: boolean\n output: Output\n server: ViteDevServer\n workDir: string\n\n /**\n * Rebuild the app's federation remote when its interface set changes, awaited\n * *before* the registry patch — the patch reloads the workbench page, which must\n * re-fetch a remote that already exposes the new interface. Resolves with the\n * recreated server so the entry gets its actual address (non-strict ports may\n * shift it); must reject if the restart produces no server, so the set stays\n * uncommitted and the next save retries instead of advertising a dead port.\n */\n onInterfaceSetChange?: () => Promise<ViteDevServer>\n}\n\ninterface DevServerRegistrationHandle {\n close: () => Promise<void>\n}\n\n/** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */\nfunction serverAddress(server: ViteDevServer) {\n const resolvedHost = server.config.server.host\n const addr = server.httpServer?.address()\n return {\n host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',\n port: typeof addr === 'object' && addr ? addr.port : server.config.server.port,\n }\n}\n\n/**\n * Register the dev server in the registry and watch its config for manifest +\n * interface changes. The workbench reads the entry to locate and render the\n * server; the watcher keeps it current as `sanity.cli.ts` is edited.\n */\nexport async function startDevServerRegistration(\n options: DevServerRegistrationOptions,\n): Promise<DevServerRegistrationHandle> {\n const {appId, cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir} =\n options\n\n const {host: appHost, port: appPort} = serverAddress(server)\n\n // Forwarded alongside (not inside) the manifest so the workbench renders local\n // panels/workers without a deploy; the watcher re-derives them on each edit.\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n\n const registration = registerDevServer({\n host: appHost,\n id: appId,\n interfaces,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n\n const interfaceSet = trackInterfaceSet(interfaces)\n\n const watcher = await startDevManifestWatcher({\n // Re-derive interfaces every pass (don't omit): the registry patch is a\n // shallow merge, so omitting would wipe the registered set.\n extract: async (params) => ({\n interfaces: deriveInterfaces((await getCliConfigUncached(params.workDir)).app, {isApp}),\n manifest: await extractManifest(params),\n }),\n // A studio's root resolves to `sanity.config.*` but its interfaces live in\n // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.\n extraWatchFilenames: isApp ? undefined : ['sanity.cli.js', 'sanity.cli.ts'],\n output,\n update: async (patch) => {\n if (!interfaceSet.changed(patch.interfaces)) {\n registration.update(patch)\n return\n }\n // Rebuild the remote *before* patching the registry — the patch reloads the\n // page, which must re-fetch a remote that already exposes the new interface.\n const rebuiltServer = await onInterfaceSetChange?.()\n // Commit only after a successful rebuild, so a thrown one retries next pass.\n interfaceSet.commit(patch.interfaces)\n // The recreated server can bind a different port (non-strict ports).\n registration.update(rebuiltServer ? {...patch, ...serverAddress(rebuiltServer)} : patch)\n },\n workDir,\n })\n\n return {\n close: async () => {\n registration.release()\n await watcher.close()\n },\n }\n}\n"],"names":["getCliConfigUncached","deriveInterfaces","trackInterfaceSet","registerDevServer","startDevManifestWatcher","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","port","startDevServerRegistration","options","appId","cliConfig","extractManifest","isApp","onInterfaceSetChange","output","workDir","appHost","appPort","interfaces","app","registration","id","projectId","api","type","interfaceSet","watcher","extract","params","manifest","extraWatchFilenames","undefined","update","patch","changed","rebuiltServer","commit","close","release"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,iBAAiB,QAAO,sBAAqB;AACrD,SAAgCC,iBAAiB,QAAO,gBAAe;AACvE,SAAQC,uBAAuB,QAAO,+BAA8B;AAmCpE,+HAA+H,GAC/H,SAASC,cAAcC,MAAqB;IAC1C,MAAMC,eAAeD,OAAOE,MAAM,CAACF,MAAM,CAACG,IAAI;IAC9C,MAAMC,OAAOJ,OAAOK,UAAU,EAAEC;IAChC,OAAO;QACLH,MAAM,OAAOF,iBAAiB,WAAWA,eAAe;QACxDM,MAAM,OAAOH,SAAS,YAAYA,OAAOA,KAAKG,IAAI,GAAGP,OAAOE,MAAM,CAACF,MAAM,CAACO,IAAI;IAChF;AACF;AAEA;;;;CAIC,GACD,OAAO,eAAeC,2BACpBC,OAAqC;IAErC,MAAM,EAACC,KAAK,EAAEC,SAAS,EAAEC,eAAe,EAAEC,KAAK,EAAEC,oBAAoB,EAAEC,MAAM,EAAEf,MAAM,EAAEgB,OAAO,EAAC,GAC7FP;IAEF,MAAM,EAACN,MAAMc,OAAO,EAAEV,MAAMW,OAAO,EAAC,GAAGnB,cAAcC;IAErD,+EAA+E;IAC/E,6EAA6E;IAC7E,MAAMmB,aAAaxB,iBAAiBgB,UAAUS,GAAG,EAAE;QAACP;IAAK;IAEzD,MAAMQ,eAAexB,kBAAkB;QACrCM,MAAMc;QACNK,IAAIZ;QACJS;QACAZ,MAAMW;QACNK,WAAWZ,WAAWa,KAAKD;QAC3BE,MAAMZ,QAAQ,YAAY;QAC1BG;IACF;IAEA,MAAMU,eAAe9B,kBAAkBuB;IAEvC,MAAMQ,UAAU,MAAM7B,wBAAwB;QAC5C,wEAAwE;QACxE,4DAA4D;QAC5D8B,SAAS,OAAOC,SAAY,CAAA;gBAC1BV,YAAYxB,iBAAiB,AAAC,CAAA,MAAMD,qBAAqBmC,OAAOb,OAAO,CAAA,EAAGI,GAAG,EAAE;oBAACP;gBAAK;gBACrFiB,UAAU,MAAMlB,gBAAgBiB;YAClC,CAAA;QACA,2EAA2E;QAC3E,wEAAwE;QACxEE,qBAAqBlB,QAAQmB,YAAY;YAAC;YAAiB;SAAgB;QAC3EjB;QACAkB,QAAQ,OAAOC;YACb,IAAI,CAACR,aAAaS,OAAO,CAACD,MAAMf,UAAU,GAAG;gBAC3CE,aAAaY,MAAM,CAACC;gBACpB;YACF;YACA,4EAA4E;YAC5E,6EAA6E;YAC7E,MAAME,gBAAgB,MAAMtB;YAC5B,6EAA6E;YAC7EY,aAAaW,MAAM,CAACH,MAAMf,UAAU;YACpC,qEAAqE;YACrEE,aAAaY,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGnC,cAAcqC,cAAc;YAAA,IAAIF;QACpF;QACAlB;IACF;IAEA,OAAO;QACLsB,OAAO;YACLjB,aAAakB,OAAO;YACpB,MAAMZ,QAAQW,KAAK;QACrB;IACF;AACF"}