@sanity/workbench-cli 2.8.0 → 2.8.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/dist/actions/build/render-remote.js +13 -1
- package/dist/actions/build/render-remote.js.map +1 -1
- package/dist/actions/dev/registry.js +52 -21
- package/dist/actions/dev/registry.js.map +1 -1
- package/dist/actions/dev/startWorkbenchDev.js +1 -6
- package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
- package/dist/actions/dev/startWorkbenchDevServer.js +7 -20
- package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
- package/package.json +5 -5
|
@@ -40,7 +40,17 @@ const ModuleContext = moduleSlot.get(React.createContext)
|
|
|
40
40
|
const rootMap = new Map()
|
|
41
41
|
// A shared default sheet can overwrite another app's global rules; each root needs its own sheet.
|
|
42
42
|
const styleTargets = new Map()
|
|
43
|
+
const stylisPlugins = new Map()
|
|
43
44
|
const renderArgs = new Map()
|
|
45
|
+
// On globalThis: every module embeds its own copy of this harness, and names must be page-unique.
|
|
46
|
+
const stylisPluginCount = Symbol.for('sanity.os.stylisPluginCount')
|
|
47
|
+
|
|
48
|
+
// Identical CSS gets an identical class in every sheet, so a later sheet overrides earlier rules.
|
|
49
|
+
// StyleSheetManager hashes stylis plugin names into class names: a uniquely named no-op isolates a root.
|
|
50
|
+
function uniqueStylisPlugin() {
|
|
51
|
+
globalThis[stylisPluginCount] = (globalThis[stylisPluginCount] ?? 0) + 1
|
|
52
|
+
return Object.defineProperty(() => {}, 'name', { value: 'sanity-root-' + globalThis[stylisPluginCount] })
|
|
53
|
+
}
|
|
44
54
|
|
|
45
55
|
function mount(rootElement, args) {
|
|
46
56
|
let root = rootMap.get(rootElement)
|
|
@@ -52,10 +62,11 @@ function mount(rootElement, args) {
|
|
|
52
62
|
// React can replace the mount node's contents; keep its stylesheet outside that node.
|
|
53
63
|
rootElement.ownerDocument.head.appendChild(target)
|
|
54
64
|
styleTargets.set(rootElement, target)
|
|
65
|
+
stylisPlugins.set(rootElement, [uniqueStylisPlugin()])
|
|
55
66
|
}
|
|
56
67
|
}
|
|
57
68
|
let element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))
|
|
58
|
-
if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement) }, element)
|
|
69
|
+
if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement), stylisPlugins: stylisPlugins.get(rootElement) }, element)
|
|
59
70
|
// The host's React can't pause this root, so the host pauses the app through this Activity.
|
|
60
71
|
// Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.
|
|
61
72
|
element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)
|
|
@@ -78,6 +89,7 @@ export function render(rootElement, props, renderOptions) {
|
|
|
78
89
|
// Unmount first so effect cleanup can still reach this root's stylesheet.
|
|
79
90
|
styleTargets.get(rootElement)?.remove()
|
|
80
91
|
styleTargets.delete(rootElement)
|
|
92
|
+
stylisPlugins.delete(rootElement)
|
|
81
93
|
},
|
|
82
94
|
setLifecycle(state) {
|
|
83
95
|
const current = renderArgs.get(rootElement)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every generated entry (studio, SDK app, view artifacts) shares one render body\n * so the host can drive them all the same way; only the `App` they bind differs.\n * The workbench host depends on `render`'s signature and return shape, so change\n * them together.\n */\n\n// Re-renders through the new module so edits apply without a page reload. The\n// new module mounts in the foreground, so reapply the host's lifecycle. The host\n// still holds this module's controller, so it forwards to the new one.\nconst HMR_REMOUNT = `if (import.meta.hot) {\n import.meta.hot.accept((next) => {\n if (!next) return\n for (const [rootElement, args] of renderArgs) {\n rootMap.get(rootElement)?.unmount()\n rootMap.delete(rootElement)\n args.next = next.render(rootElement, args.props, args.renderOptions)\n args.next.setLifecycle(args.lifecycle)\n }\n })\n}`\n\n/**\n * - `app`: omit when the preamble imports `App` itself (the SDK-app entry).\n * - `version`: lets the host check view/service contract compatibility.\n */\nexport function renderRemote({\n app,\n hmr = false,\n isolateStyles = false,\n preamble,\n version,\n}: {\n app?: string\n hmr?: boolean\n isolateStyles?: boolean\n preamble: string\n version?: string\n}): string {\n // Keep apps without styled-components buildable; the unused branch is removed from their bundle.\n const stylesheetImport = isolateStyles\n ? \"import { StyleSheetManager } from 'styled-components'\"\n : 'const StyleSheetManager = undefined'\n\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport * as React from 'react'\nimport { createRoot } from 'react-dom/client'\n${stylesheetImport}\n${preamble}\n${app ? `\\nconst App = ${app}\\n` : ''}${version ? `\\nexport const version = ${version}\\n` : ''}\n// The SDK reads this slot via getDashboardModuleContext(), so its symbol, key and\n// value are a contract. Keyed by createContext, not the React namespace: Vite dev\n// pre-bundling can give two importers of one React copy different namespaces.\nconst moduleSlot = (globalThis[Symbol.for('sanity.os.module')] ??= new WeakMap())\nif (!moduleSlot.has(React.createContext)) moduleSlot.set(React.createContext, React.createContext(undefined))\nconst ModuleContext = moduleSlot.get(React.createContext)\nconst rootMap = new Map()\n// A shared default sheet can overwrite another app's global rules; each root needs its own sheet.\nconst styleTargets = new Map()\nconst renderArgs = new Map()\n\nfunction mount(rootElement, args) {\n let root = rootMap.get(rootElement)\n if (!root) {\n root = createRoot(rootElement, args?.renderOptions?.rootOptions)\n rootMap.set(rootElement, root)\n if (StyleSheetManager) {\n const target = rootElement.ownerDocument.createElement('sanity-styles')\n // React can replace the mount node's contents; keep its stylesheet outside that node.\n rootElement.ownerDocument.head.appendChild(target)\n styleTargets.set(rootElement, target)\n }\n }\n let element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))\n if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement) }, element)\n // The host's React can't pause this root, so the host pauses the app through this Activity.\n // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.\n element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)\n if (args?.renderOptions?.reactStrictMode) element = React.createElement(React.StrictMode, null, element)\n root.render(element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { lifecycle: 'foreground', props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return {\n dispose() {\n const current = renderArgs.get(rootElement)\n renderArgs.delete(rootElement)\n if (current?.next) return current.next.dispose()\n const root = rootMap.get(rootElement)\n rootMap.delete(rootElement)\n root?.unmount()\n // Unmount first so effect cleanup can still reach this root's stylesheet.\n styleTargets.get(rootElement)?.remove()\n styleTargets.delete(rootElement)\n },\n setLifecycle(state) {\n const current = renderArgs.get(rootElement)\n if (!current) return\n if (current.next) return current.next.setLifecycle(state)\n current.lifecycle = state\n mount(rootElement, current)\n },\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","isolateStyles","preamble","version","stylesheetImport"],"mappings":"AAAA;;;;;CAKC,GAED,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,MAAMA,cAAc,CAAC;;;;;;;;;;CAUpB,CAAC;AAEF;;;CAGC,GACD,OAAO,SAASC,aAAa,EAC3BC,GAAG,EACHC,MAAM,KAAK,EACXC,gBAAgB,KAAK,EACrBC,QAAQ,EACRC,OAAO,EAOR;IACC,iGAAiG;IACjG,MAAMC,mBAAmBH,gBACrB,0DACA;IAEJ,OAAO,CAAC;;;;;AAKV,EAAEG,iBAAiB;AACnB,EAAEF,SAAS;AACX,EAAEH,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,KAAKI,UAAU,CAAC,yBAAyB,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/render-remote.ts"],"sourcesContent":["/**\n * Every generated entry (studio, SDK app, view artifacts) shares one render body\n * so the host can drive them all the same way; only the `App` they bind differs.\n * The workbench host depends on `render`'s signature and return shape, so change\n * them together.\n */\n\n// Re-renders through the new module so edits apply without a page reload. The\n// new module mounts in the foreground, so reapply the host's lifecycle. The host\n// still holds this module's controller, so it forwards to the new one.\nconst HMR_REMOUNT = `if (import.meta.hot) {\n import.meta.hot.accept((next) => {\n if (!next) return\n for (const [rootElement, args] of renderArgs) {\n rootMap.get(rootElement)?.unmount()\n rootMap.delete(rootElement)\n args.next = next.render(rootElement, args.props, args.renderOptions)\n args.next.setLifecycle(args.lifecycle)\n }\n })\n}`\n\n/**\n * - `app`: omit when the preamble imports `App` itself (the SDK-app entry).\n * - `version`: lets the host check view/service contract compatibility.\n */\nexport function renderRemote({\n app,\n hmr = false,\n isolateStyles = false,\n preamble,\n version,\n}: {\n app?: string\n hmr?: boolean\n isolateStyles?: boolean\n preamble: string\n version?: string\n}): string {\n // Keep apps without styled-components buildable; the unused branch is removed from their bundle.\n const stylesheetImport = isolateStyles\n ? \"import { StyleSheetManager } from 'styled-components'\"\n : 'const StyleSheetManager = undefined'\n\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport * as React from 'react'\nimport { createRoot } from 'react-dom/client'\n${stylesheetImport}\n${preamble}\n${app ? `\\nconst App = ${app}\\n` : ''}${version ? `\\nexport const version = ${version}\\n` : ''}\n// The SDK reads this slot via getDashboardModuleContext(), so its symbol, key and\n// value are a contract. Keyed by createContext, not the React namespace: Vite dev\n// pre-bundling can give two importers of one React copy different namespaces.\nconst moduleSlot = (globalThis[Symbol.for('sanity.os.module')] ??= new WeakMap())\nif (!moduleSlot.has(React.createContext)) moduleSlot.set(React.createContext, React.createContext(undefined))\nconst ModuleContext = moduleSlot.get(React.createContext)\nconst rootMap = new Map()\n// A shared default sheet can overwrite another app's global rules; each root needs its own sheet.\nconst styleTargets = new Map()\nconst stylisPlugins = new Map()\nconst renderArgs = new Map()\n// On globalThis: every module embeds its own copy of this harness, and names must be page-unique.\nconst stylisPluginCount = Symbol.for('sanity.os.stylisPluginCount')\n\n// Identical CSS gets an identical class in every sheet, so a later sheet overrides earlier rules.\n// StyleSheetManager hashes stylis plugin names into class names: a uniquely named no-op isolates a root.\nfunction uniqueStylisPlugin() {\n globalThis[stylisPluginCount] = (globalThis[stylisPluginCount] ?? 0) + 1\n return Object.defineProperty(() => {}, 'name', { value: 'sanity-root-' + globalThis[stylisPluginCount] })\n}\n\nfunction mount(rootElement, args) {\n let root = rootMap.get(rootElement)\n if (!root) {\n root = createRoot(rootElement, args?.renderOptions?.rootOptions)\n rootMap.set(rootElement, root)\n if (StyleSheetManager) {\n const target = rootElement.ownerDocument.createElement('sanity-styles')\n // React can replace the mount node's contents; keep its stylesheet outside that node.\n rootElement.ownerDocument.head.appendChild(target)\n styleTargets.set(rootElement, target)\n stylisPlugins.set(rootElement, [uniqueStylisPlugin()])\n }\n }\n let element = React.createElement(ModuleContext.Provider, { value: args?.renderOptions?.moduleId }, React.createElement(App, args.props))\n if (StyleSheetManager) element = React.createElement(StyleSheetManager, { target: styleTargets.get(rootElement), stylisPlugins: stylisPlugins.get(rootElement) }, element)\n // The host's React can't pause this root, so the host pauses the app through this Activity.\n // Keep it inside StrictMode: outside, it stops StrictMode double-invoking effects.\n element = React.createElement(React.Activity, { mode: args.lifecycle === 'background' ? 'hidden' : 'visible' }, element)\n if (args?.renderOptions?.reactStrictMode) element = React.createElement(React.StrictMode, null, element)\n root.render(element)\n}\n\nexport function render(rootElement, props, renderOptions) {\n const args = { lifecycle: 'foreground', props, renderOptions }\n renderArgs.set(rootElement, args)\n mount(rootElement, args)\n return {\n dispose() {\n const current = renderArgs.get(rootElement)\n renderArgs.delete(rootElement)\n if (current?.next) return current.next.dispose()\n const root = rootMap.get(rootElement)\n rootMap.delete(rootElement)\n root?.unmount()\n // Unmount first so effect cleanup can still reach this root's stylesheet.\n styleTargets.get(rootElement)?.remove()\n styleTargets.delete(rootElement)\n stylisPlugins.delete(rootElement)\n },\n setLifecycle(state) {\n const current = renderArgs.get(rootElement)\n if (!current) return\n if (current.next) return current.next.setLifecycle(state)\n current.lifecycle = state\n mount(rootElement, current)\n },\n }\n}${hmr ? `\\n\\n${HMR_REMOUNT}` : ''}\n`\n}\n"],"names":["HMR_REMOUNT","renderRemote","app","hmr","isolateStyles","preamble","version","stylesheetImport"],"mappings":"AAAA;;;;;CAKC,GAED,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,MAAMA,cAAc,CAAC;;;;;;;;;;CAUpB,CAAC;AAEF;;;CAGC,GACD,OAAO,SAASC,aAAa,EAC3BC,GAAG,EACHC,MAAM,KAAK,EACXC,gBAAgB,KAAK,EACrBC,QAAQ,EACRC,OAAO,EAOR;IACC,iGAAiG;IACjG,MAAMC,mBAAmBH,gBACrB,0DACA;IAEJ,OAAO,CAAC;;;;;AAKV,EAAEG,iBAAiB;AACnB,EAAEF,SAAS;AACX,EAAEH,MAAM,CAAC,cAAc,EAAEA,IAAI,EAAE,CAAC,GAAG,KAAKI,UAAU,CAAC,yBAAyB,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqE9F,EAAEH,MAAM,CAAC,IAAI,EAAEH,aAAa,GAAG,GAAG;AACnC,CAAC;AACD"}
|
|
@@ -297,6 +297,7 @@ const workbenchLockSchema = z.object({
|
|
|
297
297
|
host: z.string(),
|
|
298
298
|
pid: z.number(),
|
|
299
299
|
port: z.number(),
|
|
300
|
+
ready: z.optional(z.boolean()),
|
|
300
301
|
startedAt: z.string(),
|
|
301
302
|
version: z.literal(REGISTRY_VERSION)
|
|
302
303
|
});
|
|
@@ -304,34 +305,66 @@ const workbenchLockSchema = z.object({
|
|
|
304
305
|
* Read the workbench lock file and return its contents if the holding
|
|
305
306
|
* process is still alive. Prunes stale locks from crashed processes.
|
|
306
307
|
*/ export function readWorkbenchLock() {
|
|
307
|
-
const
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
contents = readFileSync(lockPath, 'utf8');
|
|
311
|
-
} catch {
|
|
312
|
-
// File doesn't exist — nothing to prune, nothing to return
|
|
313
|
-
return undefined;
|
|
314
|
-
}
|
|
308
|
+
const file = readLockFile();
|
|
309
|
+
// File doesn't exist — nothing to prune, nothing to return
|
|
310
|
+
if (!file) return undefined;
|
|
315
311
|
// Past this point the file exists. Anything that isn't a live, valid lock
|
|
316
312
|
// (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be
|
|
317
313
|
// pruned — otherwise the next `acquireWorkbenchLock` call is blocked by
|
|
318
314
|
// EEXIST forever and `sanity dev` silently no-ops the workbench server.
|
|
319
|
-
const data =
|
|
315
|
+
const { data } = file;
|
|
320
316
|
devDebug('Read workbench lock: %o', data);
|
|
321
317
|
if (data && isOurProcess(data.pid, data.startedAt)) {
|
|
322
318
|
devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port);
|
|
323
319
|
return data;
|
|
324
320
|
}
|
|
325
|
-
pruneWorkbenchLock(
|
|
321
|
+
pruneWorkbenchLock(getLockPath());
|
|
326
322
|
return undefined;
|
|
327
323
|
}
|
|
328
|
-
|
|
324
|
+
const LOCK_READY_TIMEOUT_MS = 10_000;
|
|
325
|
+
const LOCK_READY_POLL_MS = 50;
|
|
326
|
+
/**
|
|
327
|
+
* Read the workbench lock once its holder's shell is listening, so the port is
|
|
328
|
+
* the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.
|
|
329
|
+
*/ export async function waitForWorkbenchLock() {
|
|
330
|
+
const deadline = Date.now() + LOCK_READY_TIMEOUT_MS;
|
|
331
|
+
let lock = readWorkbenchLock();
|
|
332
|
+
// Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call
|
|
333
|
+
// and deletes a lock it catches half-written by `updatePort`.
|
|
334
|
+
while(lock?.ready === false && Date.now() < deadline){
|
|
335
|
+
await new Promise((resolve)=>setTimeout(resolve, LOCK_READY_POLL_MS));
|
|
336
|
+
const file = readLockFile();
|
|
337
|
+
if (!file) break;
|
|
338
|
+
lock = file.data ?? lock;
|
|
339
|
+
}
|
|
340
|
+
if (lock?.ready === false && Date.now() >= deadline) {
|
|
341
|
+
devDebug('Workbench lock not ready after %d ms, using port %d', LOCK_READY_TIMEOUT_MS, lock.port);
|
|
342
|
+
}
|
|
343
|
+
return readWorkbenchLock();
|
|
344
|
+
}
|
|
345
|
+
const getLockPath = ()=>join(getRegistryDir(), 'workbench.lock');
|
|
346
|
+
/**
|
|
347
|
+
* Read the lock file with no liveness check and no pruning. `undefined` when
|
|
348
|
+
* there is no file; `data` is `undefined` when its contents don't parse.
|
|
349
|
+
*/ function readLockFile() {
|
|
350
|
+
let contents;
|
|
329
351
|
try {
|
|
330
|
-
|
|
331
|
-
return success ? data : undefined;
|
|
352
|
+
contents = readFileSync(getLockPath(), 'utf8');
|
|
332
353
|
} catch {
|
|
333
354
|
return undefined;
|
|
334
355
|
}
|
|
356
|
+
let json;
|
|
357
|
+
try {
|
|
358
|
+
json = JSON.parse(contents);
|
|
359
|
+
} catch {
|
|
360
|
+
return {
|
|
361
|
+
data: undefined
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
const { data, success } = workbenchLockSchema.safeParse(json);
|
|
365
|
+
return {
|
|
366
|
+
data: success ? data : undefined
|
|
367
|
+
};
|
|
335
368
|
}
|
|
336
369
|
function pruneWorkbenchLock(lockPath) {
|
|
337
370
|
try {
|
|
@@ -358,12 +391,13 @@ function pruneWorkbenchLock(lockPath) {
|
|
|
358
391
|
mkdirSync(registryDir, {
|
|
359
392
|
recursive: true
|
|
360
393
|
});
|
|
361
|
-
const lockPath =
|
|
394
|
+
const lockPath = getLockPath();
|
|
362
395
|
const startedAt = ownStartedAt();
|
|
363
396
|
const lockData = {
|
|
364
397
|
host: info.host,
|
|
365
398
|
pid: process.pid,
|
|
366
399
|
port: info.port,
|
|
400
|
+
ready: false,
|
|
367
401
|
startedAt,
|
|
368
402
|
version: REGISTRY_VERSION
|
|
369
403
|
};
|
|
@@ -378,12 +412,8 @@ function pruneWorkbenchLock(lockPath) {
|
|
|
378
412
|
// it after our own release must not be clobbered.
|
|
379
413
|
const detachExitCleanup = unlinkOnProcessExit(lockPath, ()=>{
|
|
380
414
|
if (released) return false;
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
return disk?.pid === process.pid && disk.startedAt === startedAt;
|
|
384
|
-
} catch {
|
|
385
|
-
return false;
|
|
386
|
-
}
|
|
415
|
+
const disk = readLockFile()?.data;
|
|
416
|
+
return disk?.pid === process.pid && disk.startedAt === startedAt;
|
|
387
417
|
});
|
|
388
418
|
return {
|
|
389
419
|
release () {
|
|
@@ -398,7 +428,8 @@ function pruneWorkbenchLock(lockPath) {
|
|
|
398
428
|
updatePort (port) {
|
|
399
429
|
writeFileSync(lockPath, JSON.stringify({
|
|
400
430
|
...lockData,
|
|
401
|
-
port
|
|
431
|
+
port,
|
|
432
|
+
ready: true
|
|
402
433
|
}));
|
|
403
434
|
}
|
|
404
435
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/registry.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n watch,\n writeFileSync,\n} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {\n coreAppManifestSchema,\n getSanityDataDir,\n studioManifestSchema,\n subdebug,\n} from '@sanity/cli-core'\nimport {z} from 'zod/mini'\n\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\n/**\n * The dev-server registry: how a running `sanity dev` / `sanity start` process\n * advertises itself so the workbench on this machine can find and load it.\n *\n * Two kinds of file under `~/.sanity/dev-servers/` do the coordinating:\n *\n * - `<pid>.json` — one per running app/studio server, holding where it's served\n * plus its inlined manifest and interfaces. The workbench reads these to\n * discover and render local apps. Written by `registerDevServer`, watched by\n * `watchRegistry`.\n * - `workbench.lock` — a single machine-wide lock, so only one workbench shell\n * runs at a time and later `dev`s register into it instead of starting their\n * own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.\n *\n * Both files belong to the process that created them and must not outlive it.\n * Three things keep that true: an explicit `release()` on clean shutdown, an\n * `exit` backstop for abrupt exits (`unlinkOnProcessExit`), and a dead-pid prune\n * on read (`isOurProcess`) that clears whatever a crashed process left behind.\n */\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 2\n\n/**\n * The current process's start time as reported by the OS, for the `startedAt`\n * that `isOurProcess` checks on re-read. Falls back to now when the OS time is\n * unavailable — `new Date()` alone records the write time, which drifts from\n * process start by enough to look stale and get pruned right after writing.\n */\nfunction ownStartedAt(): string {\n return (getProcessStartTime(process.pid) ?? new Date()).toISOString()\n}\n\nconst interfaceBaseFields = {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n /** Raw source vite serves; a deployed interface carries only the `moduleId`. */\n src: z.string(),\n title: z.string(),\n version: z.optional(z.string()),\n}\n\n/**\n * A forwarded interface. Kept outside the manifest so\n * the workbench renders local panels and runs workers without a deploy.\n */\nconst devServerInterfaceSchema = z.union([\n z.discriminatedUnion('surface', [\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('window'),\n }),\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('panel'),\n }),\n z.object({...interfaceBaseFields, metadata: z.null(), surface: z.literal('asset_source')}),\n z.object({\n ...interfaceBaseFields,\n metadata: TileInterfaceMetadataSchema,\n surface: z.literal('tile'),\n }),\n ]),\n z.object({...interfaceBaseFields, metadata: z.null(), type: z.literal('worker')}),\n])\n\n// Exported so test fixtures can validate against the same schema the registry\n// parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.\nexport const devServerManifestSchema = z.object({\n /**\n * Field schema *values* load from the federation module; each field's `src`\n * rides along so a repoint bumps the exposes-set id and forces a rebuild.\n * Lenient — the workbench is the authority.\n */\n configs: z.optional(\n z.array(\n z.object({\n // Identifies the owning app when it has no app id (singletons).\n appType: z.optional(z.string()),\n fields: z.array(\n z.object({\n name: z.string(),\n public: z.optional(z.boolean()),\n src: z.string(),\n title: z.string(),\n }),\n ),\n // Content hash of the config — the workbench's change-detection key\n // (see deriveConfigs).\n id: z.string(),\n // The app's `defineApplication` slug — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // The version the workbench federates this config's module under —\n // a string, like the one Brett returns on a deployed `activeConfig`.\n version: z.string(),\n }),\n ),\n ),\n host: z.string(),\n id: z.optional(z.string()),\n interfaces: z.optional(z.array(devServerInterfaceSchema)),\n /**\n * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},\n * validated against the shared cli-core schemas. The registry stores and\n * rebroadcasts it; the CLI is what extracts and writes it.\n */\n manifest: z.optional(z.union([studioManifestSchema, coreAppManifestSchema])),\n /**\n * ISO timestamp of the most recent successful manifest extraction. Bumped\n * on every regeneration so re-writing this registry entry triggers the\n * workbench `watchRegistry` watcher and forces a rebroadcast to clients.\n */\n manifestUpdatedAt: z.optional(z.string()),\n // Stable identity + qualified reference, composed by the CLI (the authority for\n // local apps, which never reach brett) and read straight by the workbench.\n name: z.optional(z.string()),\n organizationId: z.optional(z.string()),\n pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n reference: z.optional(z.string()),\n slug: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\n visibility: z.optional(z.enum(['default', 'unlisted', 'disabled'])),\n workDir: z.string(),\n})\n/**\n * A manifest describing a running dev server process (studio or app).\n * Stored as `~/.sanity/dev-servers/<pid>.json`.\n *\n * The workbench singleton is tracked separately via the lock file — see\n * `acquireWorkbenchLock` and `readWorkbenchLock` below.\n */\nexport type DevServerManifest = z.infer<typeof devServerManifestSchema>\n\n/**\n * A config-only server carries configs but no interfaces — e.g. a\n * media-library config app under development. The workbench never routes it\n * as an app; only its configs are published. It therefore plays a different\n * role than an app server, and the two may share a slug (a config app\n * developed alongside the locally served singleton it configures).\n */\nexport function isConfigOnlyServer(\n server: Pick<DevServerManifest, 'configs' | 'interfaces'>,\n): boolean {\n return Boolean(server.configs?.length) && !server.interfaces?.length\n}\n\n/**\n * Path to the dev server registry directory. Lives under the shared Sanity\n * config directory to stay consistent with other CLI paths.\n */\nfunction getRegistryDir(): string {\n return join(getSanityDataDir(), 'dev-servers')\n}\n\n// One shared `exit` listener drives every registered cleanup, so N locks/entries\n// don't each add a listener and trip Node's MaxListeners warning.\nconst exitCleanups = new Set<() => void>()\nlet exitListenerInstalled = false\n\nfunction runExitCleanups(): void {\n for (const cleanup of exitCleanups) cleanup()\n}\n\n/** Exercise the exit backstop in tests without terminating the process; not part\n * of the package's public surface. */\nexport const runRegistryExitCleanupForTesting = runExitCleanups\n\n/**\n * Delete a registry file synchronously on process exit, as a backstop for abrupt\n * termination. Vite installs its own SIGTERM handler that calls `process.exit()`,\n * which can outrun the async server teardown and leave the lock or registry entry\n * behind — a stray dev-server that lingers until the dead-pid prune clears it. The\n * `exit` event only runs synchronous work, hence `unlinkSync`. `ownedByUs` guards\n * the shared lock so a successor that reacquired it isn't wiped. Returns a\n * detacher to call after a clean release.\n */\nfunction unlinkOnProcessExit(filePath: string, ownedByUs: () => boolean): () => void {\n const cleanup = () => {\n if (!ownedByUs()) return\n try {\n unlinkSync(filePath)\n } catch {\n // The file may already have been removed during shutdown.\n }\n }\n exitCleanups.add(cleanup)\n\n if (!exitListenerInstalled) {\n exitListenerInstalled = true\n process.once('exit', runExitCleanups)\n }\n\n return () => exitCleanups.delete(cleanup)\n}\n\ninterface DevServerRegistration {\n /** Remove the registry entry. */\n release: () => void\n /**\n * Rewrite the registry entry with partial updates merged in. Also bumps the\n * file's mtime, which fires `watchRegistry` in any workbench process and\n * triggers a rebroadcast to connected clients.\n */\n update: (patch: Partial<Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>>) => void\n}\n\n/**\n * Write a manifest file for the current process and return a handle with a\n * `release` function that removes it plus an `update` function for patching\n * fields post-registration. Uses synchronous I/O so the file exists before\n * any signal handler could fire.\n */\nexport function registerDevServer(\n manifest: Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>,\n): DevServerRegistration {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per machine\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(): z.infer<typeof workbenchLockSchema> | undefined {\n const lockPath = join(getRegistryDir(), 'workbench.lock')\n\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8')\n } catch {\n // File doesn't exist — nothing to prune, nothing to return\n return undefined\n }\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const data = parseLockContents(contents)\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(lockPath)\n return undefined\n}\n\nfunction parseLockContents(contents: string): z.infer<typeof workbenchLockSchema> | undefined {\n try {\n const {data, success} = workbenchLockSchema.safeParse(JSON.parse(contents))\n return success ? data : undefined\n } catch {\n return undefined\n }\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = join(registryDir, 'workbench.lock')\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx'})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n try {\n const disk = parseLockContents(readFileSync(lockPath, 'utf8'))\n return disk?.pid === process.pid && disk.startedAt === startedAt\n } catch {\n return false\n }\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port}))\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock()\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","configs","array","appType","fields","public","boolean","moduleName","host","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","readWorkbenchLock","lockPath","contents","undefined","parseLockContents","pruneWorkbenchLock","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,KAAK,EACLC,aAAa,QACR,UAAS;AAChB,SAAQC,IAAI,QAAO,YAAW;AAE9B,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,oBAAoB,EACpBC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,2BAA2B,EAAEC,2BAA2B,QAAO,oBAAmB;AAC1F,SAAQC,oBAAoB,QAAO,4BAA2B;AAC9D,SAAQC,mBAAmB,EAAEC,YAAY,QAAO,uBAAsB;AAEtE;;;;;;;;;;;;;;;;;;CAkBC,GAED,MAAMC,WAAWP,SAAS;AAE1B,iEAAiE,GACjE,MAAMQ,mBAAmB;AAEzB;;;;;CAKC,GACD,SAASC;IACP,OAAO,AAACJ,CAAAA,oBAAoBK,QAAQC,GAAG,KAAK,IAAIC,MAAK,EAAGC,WAAW;AACrE;AAEA,MAAMC,sBAAsB;IAC1B,6EAA6E,GAC7EC,IAAId,EAAEe,MAAM;IACZC,UAAUhB,EAAEe,MAAM;IAClBE,MAAMjB,EAAEe,MAAM;IACd,8EAA8E,GAC9EG,KAAKlB,EAAEe,MAAM;IACbI,OAAOnB,EAAEe,MAAM;IACfK,SAASpB,EAAEqB,QAAQ,CAACrB,EAAEe,MAAM;AAC9B;AAEA;;;CAGC,GACD,MAAMO,2BAA2BtB,EAAEuB,KAAK,CAAC;IACvCvB,EAAEwB,kBAAkB,CAAC,WAAW;QAC9BxB,EAAEyB,MAAM,CAAC;YACP,GAAGZ,mBAAmB;YACtBa,UAAU1B,EAAE2B,QAAQ,CAACzB;YACrB0B,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,WAAW;QACf,8EAA8E;QAC9E,kDAAkD;QAClD,MAAMC,oBAAoBb,oBAAoByC,UAAU;YACtD,IAAI7B,UAAU,OAAO;YACrB,IAAI;gBACF,MAAMuC,OAAOP,kBAAkBtH,aAAamH,UAAU;gBACtD,OAAOU,MAAM1G,QAAQD,QAAQC,GAAG,IAAI0G,KAAKlE,SAAS,KAAKA;YACzD,EAAE,OAAM;gBACN,OAAO;YACT;QACF;QAEA,OAAO;YACL6B;gBACEF,WAAW;gBACXC;gBACA,IAAI;oBACFtF,WAAWkH;gBACb,EAAE,OAAM;gBACN,qBAAqB;gBACvB;YACF;YACAW,YAAWvE,IAAY;gBACrBpD,cAAcgH,UAAU/B,KAAKC,SAAS,CAAC;oBAAC,GAAGsC,QAAQ;oBAAEpE;gBAAI;YAC3D;QACF;IACF,EAAE,OAAOwE,KAAc;QACrBhH,SACE,wCACAgH,eAAeC,QAAQD,IAAIE,OAAO,GAAGC,OAAOH;QAE9C,IAAI,CAACI,YAAYJ,QAAQA,IAAIK,IAAI,KAAK,UAAU,OAAOf;QAEvD,mDAAmD;QACnD,MAAMgB,WAAWnB;QACjB,IAAImB,UAAU,OAAOhB;QAErB,6FAA6F;QAC7F,IAAIK,WAAW,GAAG,OAAOL;QACzB,OAAOG,qBAAqBC,MAAMC,UAAU;IAC9C;AACF;AAEA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/registry.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n watch,\n writeFileSync,\n} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {\n coreAppManifestSchema,\n getSanityDataDir,\n studioManifestSchema,\n subdebug,\n} from '@sanity/cli-core'\nimport {z} from 'zod/mini'\n\nimport {TileInterfaceMetadataSchema, ViewPlacementMetadataSchema} from '../../contract.js'\nimport {canonicalizeWatchDir} from './canonicalizeWatchDir.js'\nimport {getProcessStartTime, isOurProcess} from './processLiveness.js'\n\n/**\n * The dev-server registry: how a running `sanity dev` / `sanity start` process\n * advertises itself so the workbench on this machine can find and load it.\n *\n * Two kinds of file under `~/.sanity/dev-servers/` do the coordinating:\n *\n * - `<pid>.json` — one per running app/studio server, holding where it's served\n * plus its inlined manifest and interfaces. The workbench reads these to\n * discover and render local apps. Written by `registerDevServer`, watched by\n * `watchRegistry`.\n * - `workbench.lock` — a single machine-wide lock, so only one workbench shell\n * runs at a time and later `dev`s register into it instead of starting their\n * own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.\n *\n * Both files belong to the process that created them and must not outlive it.\n * Three things keep that true: an explicit `release()` on clean shutdown, an\n * `exit` backstop for abrupt exits (`unlinkOnProcessExit`), and a dead-pid prune\n * on read (`isOurProcess`) that clears whatever a crashed process left behind.\n */\n\nconst devDebug = subdebug('dev')\n\n/** Bump when the manifest/lock shape changes in a breaking way. */\nconst REGISTRY_VERSION = 2\n\n/**\n * The current process's start time as reported by the OS, for the `startedAt`\n * that `isOurProcess` checks on re-read. Falls back to now when the OS time is\n * unavailable — `new Date()` alone records the write time, which drifts from\n * process start by enough to look stale and get pruned right after writing.\n */\nfunction ownStartedAt(): string {\n return (getProcessStartTime(process.pid) ?? new Date()).toISOString()\n}\n\nconst interfaceBaseFields = {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n /** Raw source vite serves; a deployed interface carries only the `moduleId`. */\n src: z.string(),\n title: z.string(),\n version: z.optional(z.string()),\n}\n\n/**\n * A forwarded interface. Kept outside the manifest so\n * the workbench renders local panels and runs workers without a deploy.\n */\nconst devServerInterfaceSchema = z.union([\n z.discriminatedUnion('surface', [\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('window'),\n }),\n z.object({\n ...interfaceBaseFields,\n metadata: z.nullable(ViewPlacementMetadataSchema),\n surface: z.literal('panel'),\n }),\n z.object({...interfaceBaseFields, metadata: z.null(), surface: z.literal('asset_source')}),\n z.object({\n ...interfaceBaseFields,\n metadata: TileInterfaceMetadataSchema,\n surface: z.literal('tile'),\n }),\n ]),\n z.object({...interfaceBaseFields, metadata: z.null(), type: z.literal('worker')}),\n])\n\n// Exported so test fixtures can validate against the same schema the registry\n// parses with — see `aDevServerManifest`. Used internally by `getRegisteredServers`.\nexport const devServerManifestSchema = z.object({\n /**\n * Field schema *values* load from the federation module; each field's `src`\n * rides along so a repoint bumps the exposes-set id and forces a rebuild.\n * Lenient — the workbench is the authority.\n */\n configs: z.optional(\n z.array(\n z.object({\n // Identifies the owning app when it has no app id (singletons).\n appType: z.optional(z.string()),\n fields: z.array(\n z.object({\n name: z.string(),\n public: z.optional(z.boolean()),\n src: z.string(),\n title: z.string(),\n }),\n ),\n // Content hash of the config — the workbench's change-detection key\n // (see deriveConfigs).\n id: z.string(),\n // The app's `defineApplication` slug — the module-federation alias the\n // workbench loads this config's live values from.\n moduleName: z.optional(z.string()),\n // The version the workbench federates this config's module under —\n // a string, like the one Brett returns on a deployed `activeConfig`.\n version: z.string(),\n }),\n ),\n ),\n host: z.string(),\n id: z.optional(z.string()),\n interfaces: z.optional(z.array(devServerInterfaceSchema)),\n /**\n * Inlined manifest — either a {@link StudioManifest} or {@link CoreAppManifest},\n * validated against the shared cli-core schemas. The registry stores and\n * rebroadcasts it; the CLI is what extracts and writes it.\n */\n manifest: z.optional(z.union([studioManifestSchema, coreAppManifestSchema])),\n /**\n * ISO timestamp of the most recent successful manifest extraction. Bumped\n * on every regeneration so re-writing this registry entry triggers the\n * workbench `watchRegistry` watcher and forces a rebroadcast to clients.\n */\n manifestUpdatedAt: z.optional(z.string()),\n // Stable identity + qualified reference, composed by the CLI (the authority for\n // local apps, which never reach brett) and read straight by the workbench.\n name: z.optional(z.string()),\n organizationId: z.optional(z.string()),\n pid: z.number(),\n port: z.number(),\n projectId: z.optional(z.string()),\n reference: z.optional(z.string()),\n slug: z.optional(z.string()),\n startedAt: z.string(),\n type: z.enum(['coreApp', 'studio']),\n version: z.literal(REGISTRY_VERSION),\n visibility: z.optional(z.enum(['default', 'unlisted', 'disabled'])),\n workDir: z.string(),\n})\n/**\n * A manifest describing a running dev server process (studio or app).\n * Stored as `~/.sanity/dev-servers/<pid>.json`.\n *\n * The workbench singleton is tracked separately via the lock file — see\n * `acquireWorkbenchLock` and `readWorkbenchLock` below.\n */\nexport type DevServerManifest = z.infer<typeof devServerManifestSchema>\n\n/**\n * A config-only server carries configs but no interfaces — e.g. a\n * media-library config app under development. The workbench never routes it\n * as an app; only its configs are published. It therefore plays a different\n * role than an app server, and the two may share a slug (a config app\n * developed alongside the locally served singleton it configures).\n */\nexport function isConfigOnlyServer(\n server: Pick<DevServerManifest, 'configs' | 'interfaces'>,\n): boolean {\n return Boolean(server.configs?.length) && !server.interfaces?.length\n}\n\n/**\n * Path to the dev server registry directory. Lives under the shared Sanity\n * config directory to stay consistent with other CLI paths.\n */\nfunction getRegistryDir(): string {\n return join(getSanityDataDir(), 'dev-servers')\n}\n\n// One shared `exit` listener drives every registered cleanup, so N locks/entries\n// don't each add a listener and trip Node's MaxListeners warning.\nconst exitCleanups = new Set<() => void>()\nlet exitListenerInstalled = false\n\nfunction runExitCleanups(): void {\n for (const cleanup of exitCleanups) cleanup()\n}\n\n/** Exercise the exit backstop in tests without terminating the process; not part\n * of the package's public surface. */\nexport const runRegistryExitCleanupForTesting = runExitCleanups\n\n/**\n * Delete a registry file synchronously on process exit, as a backstop for abrupt\n * termination. Vite installs its own SIGTERM handler that calls `process.exit()`,\n * which can outrun the async server teardown and leave the lock or registry entry\n * behind — a stray dev-server that lingers until the dead-pid prune clears it. The\n * `exit` event only runs synchronous work, hence `unlinkSync`. `ownedByUs` guards\n * the shared lock so a successor that reacquired it isn't wiped. Returns a\n * detacher to call after a clean release.\n */\nfunction unlinkOnProcessExit(filePath: string, ownedByUs: () => boolean): () => void {\n const cleanup = () => {\n if (!ownedByUs()) return\n try {\n unlinkSync(filePath)\n } catch {\n // The file may already have been removed during shutdown.\n }\n }\n exitCleanups.add(cleanup)\n\n if (!exitListenerInstalled) {\n exitListenerInstalled = true\n process.once('exit', runExitCleanups)\n }\n\n return () => exitCleanups.delete(cleanup)\n}\n\ninterface DevServerRegistration {\n /** Remove the registry entry. */\n release: () => void\n /**\n * Rewrite the registry entry with partial updates merged in. Also bumps the\n * file's mtime, which fires `watchRegistry` in any workbench process and\n * triggers a rebroadcast to connected clients.\n */\n update: (patch: Partial<Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>>) => void\n}\n\n/**\n * Write a manifest file for the current process and return a handle with a\n * `release` function that removes it plus an `update` function for patching\n * fields post-registration. Uses synchronous I/O so the file exists before\n * any signal handler could fire.\n */\nexport function registerDevServer(\n manifest: Omit<DevServerManifest, 'pid' | 'startedAt' | 'version'>,\n): DevServerRegistration {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n let current: DevServerManifest = {\n ...manifest,\n pid: process.pid,\n startedAt: ownStartedAt(),\n version: REGISTRY_VERSION,\n }\n\n const filePath = join(registryDir, `${process.pid}.json`)\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n\n // Guard against late updates from background tasks (e.g. the initial\n // manifest extraction) landing after `release()` has deleted the file —\n // without this, the update would re-create the registry entry and leak.\n let released = false\n\n // The file is pid-named, so it's always ours to remove on exit.\n const detachExitCleanup = unlinkOnProcessExit(filePath, () => !released)\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(filePath)\n } catch {\n // ENOENT is fine — already cleaned up\n }\n },\n update(patch) {\n if (released) return\n current = {...current, ...patch}\n writeFileSync(filePath, JSON.stringify(current, null, 2))\n },\n }\n}\n\n/**\n * Read all manifest files from the registry, prune stale entries (dead PIDs),\n * and return the live ones.\n */\nexport function getRegisteredServers(): DevServerManifest[] {\n const registryDir = getRegistryDir()\n\n if (!existsSync(registryDir)) {\n return []\n }\n\n const files = readdirSync(registryDir).filter((f) => f.endsWith('.json'))\n const servers: DevServerManifest[] = []\n\n for (const file of files) {\n const filePath = join(registryDir, file)\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(filePath, 'utf8'))\n } catch {\n continue\n }\n\n const {data, success} = devServerManifestSchema.safeParse(raw)\n if (!success) continue\n\n if (isOurProcess(data.pid, data.startedAt)) {\n servers.push(data)\n } else {\n try {\n unlinkSync(filePath)\n } catch {\n // Ignore — another process may have already cleaned it up\n }\n }\n }\n\n return servers\n}\n\ninterface RegistryWatcher {\n close(): void\n}\n\n/**\n * Watch the registry directory for changes and invoke the callback with the\n * current list of live servers whenever a change is detected.\n *\n * Uses `fs.watch` with a debounce to coalesce rapid file changes (e.g. a\n * server starting and writing its manifest triggers multiple FS events).\n */\nexport function watchRegistry(callback: (servers: DevServerManifest[]) => void): RegistryWatcher {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n // Canonicalize to the real long path so `fs.watch` doesn't abort on Windows\n // short-path dirs. See `canonicalizeWatchDir`.\n const watchDir = canonicalizeWatchDir(registryDir)\n\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n\n const notify = () => {\n clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n callback(getRegisteredServers())\n }, 50)\n }\n\n const watcher = watch(watchDir, notify)\n\n return {\n close() {\n clearTimeout(debounceTimer)\n watcher.close()\n },\n }\n}\n\n// The workbench singleton lock — \"one workbench per machine\". Lives in the same\n// registry dir and shares the liveness/prune model: a stale lock left by a\n// crashed process is pruned on read so the next acquire isn't blocked forever.\n\nconst workbenchLockSchema = z.object({\n host: z.string(),\n pid: z.number(),\n port: z.number(),\n ready: z.optional(z.boolean()),\n startedAt: z.string(),\n version: z.literal(REGISTRY_VERSION),\n})\n\n/**\n * Read the workbench lock file and return its contents if the holding\n * process is still alive. Prunes stale locks from crashed processes.\n */\nexport function readWorkbenchLock(): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile()\n // File doesn't exist — nothing to prune, nothing to return\n if (!file) return undefined\n\n // Past this point the file exists. Anything that isn't a live, valid lock\n // (unparsable JSON, schema mismatch, dead/reused PID) is stale and must be\n // pruned — otherwise the next `acquireWorkbenchLock` call is blocked by\n // EEXIST forever and `sanity dev` silently no-ops the workbench server.\n const {data} = file\n devDebug('Read workbench lock: %o', data)\n if (data && isOurProcess(data.pid, data.startedAt)) {\n devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port)\n return data\n }\n\n pruneWorkbenchLock(getLockPath())\n return undefined\n}\n\nconst LOCK_READY_TIMEOUT_MS = 10_000\nconst LOCK_READY_POLL_MS = 50\n\n/**\n * Read the workbench lock once its holder's shell is listening, so the port is\n * the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.\n */\nexport async function waitForWorkbenchLock(): Promise<\n z.infer<typeof workbenchLockSchema> | undefined\n> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock()\n // Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call\n // and deletes a lock it catches half-written by `updatePort`.\n while (lock?.ready === false && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, LOCK_READY_POLL_MS))\n const file = readLockFile()\n if (!file) break\n lock = file.data ?? lock\n }\n if (lock?.ready === false && Date.now() >= deadline) {\n devDebug(\n 'Workbench lock not ready after %d ms, using port %d',\n LOCK_READY_TIMEOUT_MS,\n lock.port,\n )\n }\n return readWorkbenchLock()\n}\n\nconst getLockPath = () => join(getRegistryDir(), 'workbench.lock')\n\n/**\n * Read the lock file with no liveness check and no pruning. `undefined` when\n * there is no file; `data` is `undefined` when its contents don't parse.\n */\nfunction readLockFile(): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(), 'utf8')\n } catch {\n return undefined\n }\n let json: unknown\n try {\n json = JSON.parse(contents)\n } catch {\n return {data: undefined}\n }\n const {data, success} = workbenchLockSchema.safeParse(json)\n return {data: success ? data : undefined}\n}\n\nfunction pruneWorkbenchLock(lockPath: string): void {\n try {\n devDebug('Removing stale workbench lock')\n unlinkSync(lockPath)\n devDebug('Stale workbench lock removed')\n } catch {\n // Another process may have already cleaned it up\n }\n}\n\ninterface WorkbenchLock {\n /** Release the lock file. */\n release: () => void\n /** Update the lock with the actual port after the server starts listening. */\n updatePort: (port: number) => void\n}\n\n/**\n * Attempt to acquire an exclusive lock for the workbench process.\n * Uses `O_EXCL` (the `wx` flag) which is atomic at the OS level — only one\n * process can create the file.\n *\n * The lock stores `{pid, host, port}` so other processes can find the\n * running workbench. Call `updatePort` after the Vite server starts to\n * write the actual port (Vite may pick a different one).\n *\n * @returns A {@link WorkbenchLock} if acquired, or `undefined` if another\n * live process already holds it.\n */\nexport function acquireWorkbenchLock(\n info: {host: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = getLockPath()\n const startedAt = ownStartedAt()\n const lockData = {\n host: info.host,\n pid: process.pid,\n port: info.port,\n ready: false,\n startedAt,\n version: REGISTRY_VERSION,\n }\n\n devDebug('Acquiring workbench lock at %s', lockPath)\n\n try {\n writeFileSync(lockPath, JSON.stringify(lockData), {flag: 'wx'})\n devDebug('Workbench lock acquired')\n\n let released = false\n // Only wipe the lock on exit if it's still ours — a successor that reacquired\n // it after our own release must not be clobbered.\n const detachExitCleanup = unlinkOnProcessExit(lockPath, () => {\n if (released) return false\n const disk = readLockFile()?.data\n return disk?.pid === process.pid && disk.startedAt === startedAt\n })\n\n return {\n release() {\n released = true\n detachExitCleanup()\n try {\n unlinkSync(lockPath)\n } catch {\n // Already cleaned up\n }\n },\n updatePort(port: number) {\n writeFileSync(lockPath, JSON.stringify({...lockData, port, ready: true}))\n },\n }\n } catch (err: unknown) {\n devDebug(\n 'Failed to acquire workbench lock: %s',\n err instanceof Error ? err.message : String(err),\n )\n if (!isNodeError(err) || err.code !== 'EEXIST') return undefined\n\n // Lock exists — check if the holder is still alive\n const existing = readWorkbenchLock()\n if (existing) return undefined\n\n // Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)\n if (retries <= 0) return undefined\n return acquireWorkbenchLock(info, retries - 1)\n }\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return err instanceof Error && 'code' in err\n}\n"],"names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","watch","writeFileSync","join","coreAppManifestSchema","getSanityDataDir","studioManifestSchema","subdebug","z","TileInterfaceMetadataSchema","ViewPlacementMetadataSchema","canonicalizeWatchDir","getProcessStartTime","isOurProcess","devDebug","REGISTRY_VERSION","ownStartedAt","process","pid","Date","toISOString","interfaceBaseFields","id","string","moduleId","name","src","title","version","optional","devServerInterfaceSchema","union","discriminatedUnion","object","metadata","nullable","surface","literal","null","type","devServerManifestSchema","configs","array","appType","fields","public","boolean","moduleName","host","interfaces","manifest","manifestUpdatedAt","organizationId","number","port","projectId","reference","slug","startedAt","enum","visibility","workDir","isConfigOnlyServer","server","Boolean","length","getRegistryDir","exitCleanups","Set","exitListenerInstalled","runExitCleanups","cleanup","runRegistryExitCleanupForTesting","unlinkOnProcessExit","filePath","ownedByUs","add","once","delete","registerDevServer","registryDir","recursive","current","JSON","stringify","released","detachExitCleanup","release","update","patch","getRegisteredServers","files","filter","f","endsWith","servers","file","raw","parse","data","success","safeParse","push","watchRegistry","callback","watchDir","debounceTimer","notify","clearTimeout","setTimeout","watcher","close","workbenchLockSchema","ready","readWorkbenchLock","readLockFile","undefined","pruneWorkbenchLock","getLockPath","LOCK_READY_TIMEOUT_MS","LOCK_READY_POLL_MS","waitForWorkbenchLock","deadline","now","lock","Promise","resolve","contents","json","lockPath","acquireWorkbenchLock","info","retries","lockData","flag","disk","updatePort","err","Error","message","String","isNodeError","code","existing"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,KAAK,EAC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,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
|
|
@@ -15,8 +15,7 @@ import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './star
|
|
|
15
15
|
*/ export async function startWorkbenchDev(options) {
|
|
16
16
|
const { cacheDir, checkForDeprecatedAppId, cliConfig, extractManifest, httpHost, httpPort, isApp, output, reactStrictMode, startAppServer, workDir } = options;
|
|
17
17
|
// The remote can't render itself, so it runs as a plain app server (not the
|
|
18
|
-
// shell) that still
|
|
19
|
-
// `sanity dev`s register into it.
|
|
18
|
+
// shell) that still bridges the registry.
|
|
20
19
|
if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {
|
|
21
20
|
const remote = await startAppServer({
|
|
22
21
|
announceUrl: true,
|
|
@@ -26,11 +25,7 @@ import { startWorkbenchDevServer, startWorkbenchRemoteCoordinator } from './star
|
|
|
26
25
|
if (!remote.started) return {
|
|
27
26
|
close: async ()=>{}
|
|
28
27
|
};
|
|
29
|
-
const addr = remote.server.httpServer?.address();
|
|
30
|
-
const port = (typeof addr === 'object' && addr ? addr.port : remote.server.config.server.port) ?? httpPort;
|
|
31
28
|
const coordinator = startWorkbenchRemoteCoordinator({
|
|
32
|
-
httpHost,
|
|
33
|
-
port,
|
|
34
29
|
server: remote.server
|
|
35
30
|
});
|
|
36
31
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n announceUrl: boolean\n cliConfig: CliConfig\n httpPort: number\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/service edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n announceUrl: boolean\n cliConfig: CliConfig\n httpPort: number\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/service edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still bridges the registry.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({announceUrl: true, cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const coordinator = startWorkbenchRemoteCoordinator({server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n const announceUrl = !workbench.workbenchAvailable\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config) => startAppServer({announceUrl, cliConfig: config, httpPort: appPort}),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\n await close()\n throw err\n }\n\n if (workbench.workbenchAvailable) {\n const workbenchUrl = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}`\n const addr = supervisor.server.httpServer?.address()\n const port = typeof addr === 'object' && addr ? addr.port : supervisor.server.config.server.port\n output.log(\n `Workbench dev server started at ${styleText(['blue', 'underline'], workbenchUrl)} (app on port ${port})`,\n )\n }\n\n installSignalHandlers()\n\n return {close}\n}\n"],"names":["styleText","createServerLifecycle","toDisplayHost","startAppServerSupervisor","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","announceUrl","started","close","coordinator","server","closers","installSignalHandlers","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","config","catch","err","supervisor","registration","onInterfaceSetChange","rebuild","workbenchU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from '../../defineApp.js';
|
|
8
8
|
import { createExposesTracker } from './exposesSetId.js';
|
|
9
|
-
import { acquireWorkbenchLock, getRegisteredServers, isConfigOnlyServer,
|
|
9
|
+
import { acquireWorkbenchLock, getRegisteredServers, isConfigOnlyServer, waitForWorkbenchLock, watchRegistry } from './registry.js';
|
|
10
10
|
import { toWireInterface } from './toWireInterface.js';
|
|
11
11
|
import { writeWorkbenchRuntime } from './writeWorkbenchRuntime.js';
|
|
12
12
|
const devDebug = subdebug('dev');
|
|
@@ -67,26 +67,13 @@ const toApplicationsPayload = (servers)=>({
|
|
|
67
67
|
return ()=>registryWatcher.close();
|
|
68
68
|
}
|
|
69
69
|
/**
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* and
|
|
73
|
-
* is already held.
|
|
70
|
+
* Bridge the registry into the workbench remote's HMR channel. The remote never
|
|
71
|
+
* claims the workbench lock: a held lock tells the next `sanity dev` a shell is
|
|
72
|
+
* running, and the remote only renders inside that shell.
|
|
74
73
|
*/ export function startWorkbenchRemoteCoordinator(options) {
|
|
75
|
-
const
|
|
76
|
-
const lock = acquireWorkbenchLock({
|
|
77
|
-
host: httpHost || 'localhost',
|
|
78
|
-
port
|
|
79
|
-
});
|
|
80
|
-
if (!lock) {
|
|
81
|
-
const existing = readWorkbenchLock();
|
|
82
|
-
devDebug('Workbench lock already held by pid %d on port %d; bridging the registry without claiming it', existing?.pid, existing?.port);
|
|
83
|
-
}
|
|
84
|
-
const detachBridge = attachViteDevServerBridge(server);
|
|
74
|
+
const detachBridge = attachViteDevServerBridge(options.server);
|
|
85
75
|
return {
|
|
86
|
-
close: async ()=>
|
|
87
|
-
detachBridge();
|
|
88
|
-
lock?.release();
|
|
89
|
-
}
|
|
76
|
+
close: async ()=>detachBridge()
|
|
90
77
|
};
|
|
91
78
|
}
|
|
92
79
|
export async function startWorkbenchDevServer(options) {
|
|
@@ -111,7 +98,7 @@ export async function startWorkbenchDevServer(options) {
|
|
|
111
98
|
port: workbenchPort
|
|
112
99
|
});
|
|
113
100
|
if (!workbenchLock) {
|
|
114
|
-
const existing =
|
|
101
|
+
const existing = await waitForWorkbenchLock();
|
|
115
102
|
devDebug('Workbench already running at pid %d on port %d, skipping', existing?.pid, existing?.port);
|
|
116
103
|
return {
|
|
117
104
|
close: noop,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\n\nimport {type CliConfig, type Output, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n readWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {toWireInterface} from './toWireInterface.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\nconst renderDashboardEntry = '@sanity/workbench-cli/_internal_render'\nconst renderDashboardPath = fileURLToPath(\n new URL('../../_exports/_internal_render.js', import.meta.url),\n)\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => !isConfigOnlyServer(server))\n .map(\n ({\n host,\n id,\n interfaces,\n manifest,\n name,\n organizationId,\n port,\n projectId,\n reference,\n slug,\n type,\n visibility,\n }) => ({\n host,\n id,\n // Views cross to the remote keyed on `type`, never the internal `surface`.\n interfaces: interfaces?.map((iface) => toWireInterface(iface)),\n manifest,\n name,\n port,\n projectId,\n reference,\n type,\n ...(organizationId && slug && visibility ? {organizationId, slug, visibility} : {}),\n }),\n ),\n configs: servers.flatMap(({configs, host, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `http://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer): () => void {\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(getRegisteredServers()),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((servers) => {\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Make the workbench remote act as the machine's workbench: claim the singleton\n * lock so app `sanity dev`s register into it instead of each starting their own,\n * and bridge the registry so the remote shows the local apps. No-op lock if one\n * is already held.\n */\nexport function startWorkbenchRemoteCoordinator(options: {\n httpHost: string | undefined\n port: number\n server: ViteDevServer\n}): {close: () => Promise<void>} {\n const {httpHost, port, server} = options\n\n const lock = acquireWorkbenchLock({host: httpHost || 'localhost', port})\n if (!lock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench lock already held by pid %d on port %d; bridging the registry without claiming it',\n existing?.pid,\n existing?.port,\n )\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n close: async () => {\n detachBridge()\n lock?.release()\n },\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into by a `defineApplication` app or a config-only\n // `unstable_defineMediaLibrary` config — the latter still needs the shell to\n // render it.\n if (!isWorkbenchApp(cliConfig?.app) && !isWorkbenchConfig(cliConfig?.app)) {\n devDebug('Not a workbench app or config, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n // Acquire an exclusive lock — only one workbench per machine.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({host: httpHost || 'localhost', port: workbenchPort})\n if (!workbenchLock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n cliConfig,\n httpHost,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable: true,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, cliConfig, httpHost, output, reactStrictMode, workbenchPort, workDir} = options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Keep this entry out of pre-bundling so Vite injects its HMR context.\n exclude: [renderDashboardEntry],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {\n // The generated Vite root cannot reliably resolve this package.\n alias: {[renderDashboardEntry]: renderDashboardPath},\n dedupe: ['react', 'react-dom'],\n },\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Workbench dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `defineApplication`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'Workbench requires an organization ID. Pass \"organizationId\" to defineApplication() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["fileURLToPath","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","isWorkbenchConfig","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","readWorkbenchLock","watchRegistry","toWireInterface","writeWorkbenchRuntime","devDebug","renderDashboardEntry","renderDashboardPath","URL","url","noop","toApplicationsPayload","servers","applications","filter","server","map","host","id","interfaces","manifest","name","organizationId","port","projectId","reference","slug","type","visibility","iface","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ws","on","_","client","send","setTracker","registryWatcher","hasChanged","close","startWorkbenchRemoteCoordinator","options","httpHost","lock","existing","pid","detachBridge","release","startWorkbenchDevServer","cacheDir","cliConfig","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","workbenchLock","result","createWorkbenchViteServer","err","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","resolveOrganizationId","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","mode","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","undefined","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader"],"mappings":"AAAA,SAAQA,a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C,CAAC;gBAC5E;gBACAsD;YACF;QACF;QACAxG,MAAM;IACR;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\n\nimport {type CliConfig, type Output, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n waitForWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {toWireInterface} from './toWireInterface.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\nconst renderDashboardEntry = '@sanity/workbench-cli/_internal_render'\nconst renderDashboardPath = fileURLToPath(\n new URL('../../_exports/_internal_render.js', import.meta.url),\n)\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => !isConfigOnlyServer(server))\n .map(\n ({\n host,\n id,\n interfaces,\n manifest,\n name,\n organizationId,\n port,\n projectId,\n reference,\n slug,\n type,\n visibility,\n }) => ({\n host,\n id,\n // Views cross to the remote keyed on `type`, never the internal `surface`.\n interfaces: interfaces?.map((iface) => toWireInterface(iface)),\n manifest,\n name,\n port,\n projectId,\n reference,\n type,\n ...(organizationId && slug && visibility ? {organizationId, slug, visibility} : {}),\n }),\n ),\n configs: servers.flatMap(({configs, host, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `http://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer): () => void {\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(getRegisteredServers()),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((servers) => {\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Bridge the registry into the workbench remote's HMR channel. The remote never\n * claims the workbench lock: a held lock tells the next `sanity dev` a shell is\n * running, and the remote only renders inside that shell.\n */\nexport function startWorkbenchRemoteCoordinator(options: {server: ViteDevServer}): {\n close: () => Promise<void>\n} {\n const detachBridge = attachViteDevServerBridge(options.server)\n\n return {\n close: async () => detachBridge(),\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into by a `defineApplication` app or a config-only\n // `unstable_defineMediaLibrary` config — the latter still needs the shell to\n // render it.\n if (!isWorkbenchApp(cliConfig?.app) && !isWorkbenchConfig(cliConfig?.app)) {\n devDebug('Not a workbench app or config, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n // Acquire an exclusive lock — only one workbench per machine.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({host: httpHost || 'localhost', port: workbenchPort})\n if (!workbenchLock) {\n const existing = await waitForWorkbenchLock()\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n cliConfig,\n httpHost,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable: true,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, cliConfig, httpHost, output, reactStrictMode, workbenchPort, workDir} = options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Keep this entry out of pre-bundling so Vite injects its HMR context.\n exclude: [renderDashboardEntry],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {\n // The generated Vite root cannot reliably resolve this package.\n alias: {[renderDashboardEntry]: renderDashboardPath},\n dedupe: ['react', 'react-dom'],\n },\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Workbench dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `defineApplication`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'Workbench requires an organization ID. Pass \"organizationId\" to defineApplication() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["fileURLToPath","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","isWorkbenchConfig","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","waitForWorkbenchLock","watchRegistry","toWireInterface","writeWorkbenchRuntime","devDebug","renderDashboardEntry","renderDashboardPath","URL","url","noop","toApplicationsPayload","servers","applications","filter","server","map","host","id","interfaces","manifest","name","organizationId","port","projectId","reference","slug","type","visibility","iface","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ws","on","_","client","send","setTracker","registryWatcher","hasChanged","close","startWorkbenchRemoteCoordinator","options","detachBridge","startWorkbenchDevServer","cacheDir","cliConfig","httpHost","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","workbenchLock","existing","pid","result","createWorkbenchViteServer","err","release","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","resolveOrganizationId","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","mode","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","undefined","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AAEtC,SAAqCC,QAAQ,QAAO,mBAAkB;AACtE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,eAAe,uBAAsB;AAC5C,SAAQC,YAAY,QAA2D,OAAM;AACrF,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,oBAAoB,QAAO,oBAAmB;AACtD,SACEC,oBAAoB,EAEpBC,oBAAoB,EACpBC,kBAAkB,EAClBC,oBAAoB,EACpBC,aAAa,QACR,gBAAe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,WAAW;IAAMC,UAAU;AAAU;AAEpE,SAAS1C,eAAe2C,KAAyB;IAC/C,IAAI,CAACA,OAAO,OAAOb;IAEnB,MAAMrC,SAAS+C,gBAAgBI,SAAS,CAACD;IAEzC,IAAI,CAAClD,OAAOoD,OAAO,EAAE;QACnB,MAAM,IAAIlB,MACR,CAAC,8CAA8C,EAAEgB,MAAM,yBAAyB,CAAC;IAErF;IAEA,OAAOlD,OAAOqD,IAAI;AACpB;AAEA;;;;;;CAMC,GACD,SAAS5B,kCAAkCnB,SAAiB;IAC1D,OAAO;QACLgD,OAAO;QACPC,iBAAgBxG,MAAM;YACpBA,OAAOyG,WAAW,CAACC,GAAG,CAAC,CAACC,KAAKC,KAAKC;gBAChC,MAAMC,WAAW,AAACH,CAAAA,IAAIjH,GAAG,IAAI,GAAE,EAAGqH,KAAK,CAAC,IAAI,CAAC,EAAE;gBAC/C,IAAID,aAAa,OAAOA,aAAa,eAAe;oBAClDF,IAAII,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAEzD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAsD;YACF;QACF;QACAvG,MAAM;IACR;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/workbench-cli",
|
|
3
|
-
"version": "2.8.
|
|
3
|
+
"version": "2.8.1",
|
|
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",
|
|
@@ -57,9 +57,9 @@
|
|
|
57
57
|
"access": "public"
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@module-federation/runtime": "2.9.
|
|
61
|
-
"@module-federation/vite": "1.
|
|
62
|
-
"@sanity/cli-core": "^3.8.
|
|
60
|
+
"@module-federation/runtime": "2.9.2",
|
|
61
|
+
"@module-federation/vite": "1.23.0",
|
|
62
|
+
"@sanity/cli-core": "^3.8.2",
|
|
63
63
|
"@sanity/types": "^6.15.0",
|
|
64
64
|
"@vitejs/plugin-react": "^6.1.1",
|
|
65
65
|
"form-data": "^4.0.5",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"@eslint/compat": "^2.1.0",
|
|
74
74
|
"@repo/package.config": "0.0.1",
|
|
75
75
|
"@repo/tsconfig": "3.70.0",
|
|
76
|
-
"@sanity/cli-test": "18.0.
|
|
76
|
+
"@sanity/cli-test": "18.0.2",
|
|
77
77
|
"@sanity/eslint-config-cli": "^1.1.3",
|
|
78
78
|
"@sanity/pkg-utils": "^12.3.4",
|
|
79
79
|
"@swc/cli": "^0.8.1",
|