@sanity/workbench-cli 2.11.0 → 2.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_exports/build.d.ts +7 -1
- package/dist/_exports/build.js +1 -0
- package/dist/_exports/build.js.map +1 -1
- package/dist/_exports/deploy.d.ts +5 -13
- package/dist/_exports/deploy.js +0 -1
- package/dist/_exports/deploy.js.map +1 -1
- package/dist/actions/{deploy/checkBuiltOutput.js → build/readBuiltManifest.js} +12 -9
- package/dist/actions/build/readBuiltManifest.js.map +1 -0
- package/dist/actions/deploy/deployWorkbenchApp.js +4 -7
- package/dist/actions/deploy/deployWorkbenchApp.js.map +1 -1
- package/dist/actions/dev/registry.js +17 -17
- package/dist/actions/dev/registry.js.map +1 -1
- package/dist/actions/dev/startDevServerRegistration.js +4 -3
- package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
- package/dist/actions/dev/startWorkbenchDevServer.js +12 -9
- package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
- package/dist/actions/preview/serveBuiltApplication.js +3 -3
- package/dist/actions/preview/serveBuiltApplication.js.map +1 -1
- package/dist/services/applications.js +2 -2
- package/dist/services/applications.js.map +1 -1
- package/package.json +4 -4
- package/dist/actions/deploy/checkBuiltOutput.js.map +0 -1
package/dist/_exports/build.d.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import { a as resolveAppEntry, i as WorkbenchExposes, n as resolveWorkbenchConfig, o as resolveWorkbenchApp, r as ResolvedWorkbenchApp, t as ResolvedMediaLibraryConfig } from "./resolveWorkbenchConfig-DEttN7ks.js";
|
|
2
2
|
import { InlineConfig, PluginOption } from "vite";
|
|
3
|
+
/**
|
|
4
|
+
* Resolves to the parsed federation manifest in `sourceDir`. A workbench build
|
|
5
|
+
* may also emit a standalone `index.html`, so the manifest, not `index.html`,
|
|
6
|
+
* is the marker that `sanity build` produced a federation build.
|
|
7
|
+
*/
|
|
8
|
+
declare function readBuiltManifest(sourceDir: string): Promise<Record<string, unknown>>;
|
|
3
9
|
/**
|
|
4
10
|
* Resource bindings ride in a dedicated module in the app's bundle rather than an
|
|
5
11
|
* index.html script tag, so both standalone studios and federated apps resolve
|
|
@@ -114,5 +120,5 @@ declare function workbenchVitePlugins(options: WorkbenchViteOptions): Promise<Pl
|
|
|
114
120
|
* its own id from the applications API.
|
|
115
121
|
*/
|
|
116
122
|
declare function buildAppId(app: ResolvedWorkbenchApp): Promise<string>;
|
|
117
|
-
export { RESOURCE_BINDINGS_CHUNK_NAME, RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE, RESOURCE_BINDINGS_TOKEN, type ResolvedMediaLibraryConfig, type WorkbenchExposes, buildAppId, buildFederatedApp, resolveAppEntry, resolveWorkbenchApp, resolveWorkbenchConfig, resourceBindingsChunkFileName, resourceBindingsCodeSplittingGroup, workbenchOptimizeDeps, workbenchVitePlugins };
|
|
123
|
+
export { RESOURCE_BINDINGS_CHUNK_NAME, RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE, RESOURCE_BINDINGS_TOKEN, type ResolvedMediaLibraryConfig, type WorkbenchExposes, buildAppId, buildFederatedApp, readBuiltManifest, resolveAppEntry, resolveWorkbenchApp, resolveWorkbenchConfig, resourceBindingsChunkFileName, resourceBindingsCodeSplittingGroup, workbenchOptimizeDeps, workbenchVitePlugins };
|
|
118
124
|
//# sourceMappingURL=build.d.ts.map
|
package/dist/_exports/build.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// resolver the build reads declared views/web workers from. The build needs no
|
|
4
4
|
// deploy-time guards, so it takes the bare `resolveWorkbenchApp` — the guarded
|
|
5
5
|
// view (`getWorkbench`) is the deploy entry's export.
|
|
6
|
+
export { readBuiltManifest } from '../actions/build/readBuiltManifest.js';
|
|
6
7
|
export { RESOURCE_BINDINGS_CHUNK_NAME, RESOURCE_BINDINGS_ENTRY_IMPORT, RESOURCE_BINDINGS_FILENAME, RESOURCE_BINDINGS_MODULE_SOURCE, RESOURCE_BINDINGS_TOKEN, resourceBindingsChunkFileName, resourceBindingsCodeSplittingGroup } from '../actions/build/resource-bindings.js';
|
|
7
8
|
export { buildFederatedApp } from '../actions/build/vite/discover-shared-dependencies.js';
|
|
8
9
|
export { workbenchOptimizeDeps } from '../actions/build/vite/optimize-deps.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/_exports/build.ts"],"sourcesContent":["// Node-only build entry: the module-federation Vite plugins that\n// `@sanity/cli-build`'s `getViteConfig` swaps in for a workbench app, plus the\n// resolver the build reads declared views/web workers from. The build needs no\n// deploy-time guards, so it takes the bare `resolveWorkbenchApp` — the guarded\n// view (`getWorkbench`) is the deploy entry's export.\n\nexport {\n RESOURCE_BINDINGS_CHUNK_NAME,\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n RESOURCE_BINDINGS_TOKEN,\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../actions/build/resource-bindings.js'\nexport {buildFederatedApp} from '../actions/build/vite/discover-shared-dependencies.js'\nexport {workbenchOptimizeDeps} from '../actions/build/vite/optimize-deps.js'\nexport {workbenchVitePlugins} from '../actions/build/vite/workbench-vite-plugins.js'\nexport {buildAppId} from '../appId.js'\nexport {\n resolveAppEntry,\n resolveWorkbenchApp,\n type WorkbenchExposes,\n} from '../resolveWorkbenchApp.js'\nexport {type ResolvedMediaLibraryConfig, resolveWorkbenchConfig} from '../resolveWorkbenchConfig.js'\n"],"names":["RESOURCE_BINDINGS_CHUNK_NAME","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","RESOURCE_BINDINGS_TOKEN","resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","buildFederatedApp","workbenchOptimizeDeps","workbenchVitePlugins","buildAppId","resolveAppEntry","resolveWorkbenchApp","resolveWorkbenchConfig"],"mappings":"AAAA,iEAAiE;AACjE,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,sDAAsD;AAEtD,
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/build.ts"],"sourcesContent":["// Node-only build entry: the module-federation Vite plugins that\n// `@sanity/cli-build`'s `getViteConfig` swaps in for a workbench app, plus the\n// resolver the build reads declared views/web workers from. The build needs no\n// deploy-time guards, so it takes the bare `resolveWorkbenchApp` — the guarded\n// view (`getWorkbench`) is the deploy entry's export.\n\nexport {readBuiltManifest} from '../actions/build/readBuiltManifest.js'\nexport {\n RESOURCE_BINDINGS_CHUNK_NAME,\n RESOURCE_BINDINGS_ENTRY_IMPORT,\n RESOURCE_BINDINGS_FILENAME,\n RESOURCE_BINDINGS_MODULE_SOURCE,\n RESOURCE_BINDINGS_TOKEN,\n resourceBindingsChunkFileName,\n resourceBindingsCodeSplittingGroup,\n} from '../actions/build/resource-bindings.js'\nexport {buildFederatedApp} from '../actions/build/vite/discover-shared-dependencies.js'\nexport {workbenchOptimizeDeps} from '../actions/build/vite/optimize-deps.js'\nexport {workbenchVitePlugins} from '../actions/build/vite/workbench-vite-plugins.js'\nexport {buildAppId} from '../appId.js'\nexport {\n resolveAppEntry,\n resolveWorkbenchApp,\n type WorkbenchExposes,\n} from '../resolveWorkbenchApp.js'\nexport {type ResolvedMediaLibraryConfig, resolveWorkbenchConfig} from '../resolveWorkbenchConfig.js'\n"],"names":["readBuiltManifest","RESOURCE_BINDINGS_CHUNK_NAME","RESOURCE_BINDINGS_ENTRY_IMPORT","RESOURCE_BINDINGS_FILENAME","RESOURCE_BINDINGS_MODULE_SOURCE","RESOURCE_BINDINGS_TOKEN","resourceBindingsChunkFileName","resourceBindingsCodeSplittingGroup","buildFederatedApp","workbenchOptimizeDeps","workbenchVitePlugins","buildAppId","resolveAppEntry","resolveWorkbenchApp","resolveWorkbenchConfig"],"mappings":"AAAA,iEAAiE;AACjE,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,sDAAsD;AAEtD,SAAQA,iBAAiB,QAAO,wCAAuC;AACvE,SACEC,4BAA4B,EAC5BC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,+BAA+B,EAC/BC,uBAAuB,EACvBC,6BAA6B,EAC7BC,kCAAkC,QAC7B,wCAAuC;AAC9C,SAAQC,iBAAiB,QAAO,wDAAuD;AACvF,SAAQC,qBAAqB,QAAO,yCAAwC;AAC5E,SAAQC,oBAAoB,QAAO,kDAAiD;AACpF,SAAQC,UAAU,QAAO,cAAa;AACtC,SACEC,eAAe,EACfC,mBAAmB,QAEd,4BAA2B;AAClC,SAAyCC,sBAAsB,QAAO,+BAA8B"}
|
|
@@ -3,14 +3,6 @@ import { n as resolveWorkbenchConfig, t as ResolvedMediaLibraryConfig } from "./
|
|
|
3
3
|
import { a as DeployableWorkbenchApp, i as summarizeInterfaces, n as DeployedView, o as getWorkbench, r as DeployedWebWorker, t as DeployedInterface } from "./summarizeInterfaces-Co97VU2z.js";
|
|
4
4
|
import { AppVisibility, CliConfig, Output } from "@sanity/cli-core";
|
|
5
5
|
import "node:zlib";
|
|
6
|
-
/**
|
|
7
|
-
* Throws unless `sourceDir` is a directory holding a federation build.
|
|
8
|
-
* A workbench build always emits a module-federation remote, and may
|
|
9
|
-
* additionally emit a standalone `index.html` SPA (workbench remotes). Either
|
|
10
|
-
* way `mf-manifest.json` is the reliable marker that `sanity build` produced a
|
|
11
|
-
* federation build, so that — not `index.html` — is what we check for.
|
|
12
|
-
*/
|
|
13
|
-
declare function checkBuiltOutput(sourceDir: string): Promise<void>;
|
|
14
6
|
/**
|
|
15
7
|
* The org's active installation for an app type, or `undefined` when none is
|
|
16
8
|
* installed. Read-only, so `--dry-run` can report deployability.
|
|
@@ -101,7 +93,7 @@ interface BrettWorkspace {
|
|
|
101
93
|
}
|
|
102
94
|
declare function getWorkbenchUrl(organizationId: string): string;
|
|
103
95
|
/** Where a deployed application is served on its organization's workbench. */
|
|
104
|
-
declare function getApplicationUrl(application: Pick<Application, 'id' | 'organizationId' | 'type'>): string;
|
|
96
|
+
declare function getApplicationUrl(application: Pick<Application, 'id' | 'organizationId' | 'slug' | 'type'>): string;
|
|
105
97
|
declare function getApplication(applicationId: string): Promise<Application | null>;
|
|
106
98
|
/** Every application in an organization, in one page (`limit=none`). */
|
|
107
99
|
declare function listApplications(organizationId: string): Promise<Application[]>;
|
|
@@ -149,9 +141,8 @@ declare function createStudio(options: {
|
|
|
149
141
|
* sync — so a caller can disarm a create-time rollback that must not delete an
|
|
150
142
|
* application once it has an active deployment.
|
|
151
143
|
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
* registered origin.
|
|
144
|
+
* `isExternal` skips the tarball: the customer serves the build from the
|
|
145
|
+
* application's registered origin.
|
|
155
146
|
* @internal
|
|
156
147
|
*/
|
|
157
148
|
declare function deployWorkbenchApp(options: {
|
|
@@ -163,6 +154,7 @@ declare function deployWorkbenchApp(options: {
|
|
|
163
154
|
isAutoUpdating: boolean;
|
|
164
155
|
isExternal?: boolean;
|
|
165
156
|
label?: string;
|
|
157
|
+
mfManifest: Record<string, unknown>;
|
|
166
158
|
onDeployed?: () => void;
|
|
167
159
|
/**
|
|
168
160
|
* The address from config. Only `createApplication` used to send it, so an
|
|
@@ -175,5 +167,5 @@ declare function deployWorkbenchApp(options: {
|
|
|
175
167
|
visibility?: AppVisibility;
|
|
176
168
|
workspaces?: readonly BrettWorkspace[];
|
|
177
169
|
}): Promise<void>;
|
|
178
|
-
export { type Application, type BrettAccess, type BrettWorkspace, type CreatedApplication, type DeployedInterface, type DeployedView, type DeployedWebWorker, type ResolvedMediaLibraryConfig, type WorkbenchDeployPayload,
|
|
170
|
+
export { type Application, type BrettAccess, type BrettWorkspace, type CreatedApplication, type DeployedInterface, type DeployedView, type DeployedWebWorker, type ResolvedMediaLibraryConfig, type WorkbenchDeployPayload, createCoreApp, createStudio, deployConfig, deployWorkbenchApp, getApplication, getApplicationUrl, getWorkbench, getWorkbenchUrl, listApplications, resolveInstallationId, resolveWorkbenchConfig, summarizeConfig, summarizeInterfaces, toWorkbenchPayload };
|
|
179
171
|
//# sourceMappingURL=deploy.d.ts.map
|
package/dist/_exports/deploy.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
export { checkBuiltOutput } from '../actions/deploy/checkBuiltOutput.js';
|
|
2
1
|
export { deployConfig, resolveInstallationId, summarizeConfig } from '../actions/deploy/deployConfig.js';
|
|
3
2
|
export { toWorkbenchPayload } from '../actions/deploy/deployPayload.js';
|
|
4
3
|
export { createCoreApp, createStudio, deployWorkbenchApp } from '../actions/deploy/deployWorkbenchApp.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/_exports/deploy.ts"],"sourcesContent":["export {
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/deploy.ts"],"sourcesContent":["export {\n deployConfig,\n resolveInstallationId,\n summarizeConfig,\n} from '../actions/deploy/deployConfig.js'\nexport {toWorkbenchPayload, type WorkbenchDeployPayload} from '../actions/deploy/deployPayload.js'\nexport {\n createCoreApp,\n type CreatedApplication,\n createStudio,\n deployWorkbenchApp,\n} from '../actions/deploy/deployWorkbenchApp.js'\nexport {getWorkbench} from '../actions/deploy/getWorkbench.js'\nexport {\n type DeployedInterface,\n type DeployedView,\n type DeployedWebWorker,\n summarizeInterfaces,\n} from '../actions/deploy/summarizeInterfaces.js'\nexport {type ResolvedMediaLibraryConfig, resolveWorkbenchConfig} from '../resolveWorkbenchConfig.js'\nexport {\n type Application,\n type BrettAccess,\n type BrettWorkspace,\n getApplication,\n getApplicationUrl,\n getWorkbenchUrl,\n listApplications,\n} from '../services/applications.js'\n"],"names":["deployConfig","resolveInstallationId","summarizeConfig","toWorkbenchPayload","createCoreApp","createStudio","deployWorkbenchApp","getWorkbench","summarizeInterfaces","resolveWorkbenchConfig","getApplication","getApplicationUrl","getWorkbenchUrl","listApplications"],"mappings":"AAAA,SACEA,YAAY,EACZC,qBAAqB,EACrBC,eAAe,QACV,oCAAmC;AAC1C,SAAQC,kBAAkB,QAAoC,qCAAoC;AAClG,SACEC,aAAa,EAEbC,YAAY,EACZC,kBAAkB,QACb,0CAAyC;AAChD,SAAQC,YAAY,QAAO,oCAAmC;AAC9D,SAIEC,mBAAmB,QACd,2CAA0C;AACjD,SAAyCC,sBAAsB,QAAO,+BAA8B;AACpG,SAIEC,cAAc,EACdC,iBAAiB,EACjBC,eAAe,EACfC,gBAAgB,QACX,8BAA6B"}
|
|
@@ -11,12 +11,10 @@ import { join } from 'node:path';
|
|
|
11
11
|
return error;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
|
|
18
|
-
* federation build, so that — not `index.html` — is what we check for.
|
|
19
|
-
*/ export async function checkBuiltOutput(sourceDir) {
|
|
14
|
+
* Resolves to the parsed federation manifest in `sourceDir`. A workbench build
|
|
15
|
+
* may also emit a standalone `index.html`, so the manifest, not `index.html`,
|
|
16
|
+
* is the marker that `sanity build` produced a federation build.
|
|
17
|
+
*/ export async function readBuiltManifest(sourceDir) {
|
|
20
18
|
try {
|
|
21
19
|
const stats = await stat(sourceDir);
|
|
22
20
|
if (!stats.isDirectory()) {
|
|
@@ -32,17 +30,22 @@ import { join } from 'node:path';
|
|
|
32
30
|
manifest = await readFile(manifestPath, 'utf8');
|
|
33
31
|
} catch (err) {
|
|
34
32
|
if (err.code === 'ENOENT') {
|
|
35
|
-
throw buildNotFound(`"${manifestPath}" does not exist
|
|
33
|
+
throw buildNotFound(`"${manifestPath}" does not exist; a federation build created with "sanity build" writes it.`);
|
|
36
34
|
}
|
|
37
35
|
throw err;
|
|
38
36
|
}
|
|
39
37
|
// Every deploy sends this file to the API, so a corrupt one must fail here
|
|
40
38
|
// rather than after the application is created.
|
|
39
|
+
let parsed;
|
|
41
40
|
try {
|
|
42
|
-
JSON.parse(manifest);
|
|
41
|
+
parsed = JSON.parse(manifest);
|
|
43
42
|
} catch {
|
|
44
43
|
throw new Error(`"${manifestPath}" is not valid JSON. Run "sanity build" again to regenerate it.`);
|
|
45
44
|
}
|
|
45
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
46
|
+
throw new Error(`"${manifestPath}" is not a JSON object. Run "sanity build" again to regenerate it.`);
|
|
47
|
+
}
|
|
48
|
+
return parsed;
|
|
46
49
|
}
|
|
47
50
|
|
|
48
|
-
//# sourceMappingURL=
|
|
51
|
+
//# sourceMappingURL=readBuiltManifest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/readBuiltManifest.ts"],"sourcesContent":["import {readFile, stat} from 'node:fs/promises'\nimport {join} from 'node:path'\n\n/**\n * A genuinely-missing-build error, named so callers can offer the \"run sanity\n * build\" hint (the `preview` command keys off this name, matching how the studio\n * path keys off a missing `index.html`). Only the missing cases get it — real\n * I/O failures keep their own name so they surface as themselves.\n */\nfunction buildNotFound(message: string): Error {\n const error = new Error(message)\n error.name = 'BUILD_NOT_FOUND'\n return error\n}\n\n/**\n * Resolves to the parsed federation manifest in `sourceDir`. A workbench build\n * may also emit a standalone `index.html`, so the manifest, not `index.html`,\n * is the marker that `sanity build` produced a federation build.\n */\nexport async function readBuiltManifest(sourceDir: string): Promise<Record<string, unknown>> {\n try {\n const stats = await stat(sourceDir)\n if (!stats.isDirectory()) {\n throw new Error(`\"${sourceDir}\" is not a directory`)\n }\n } catch (err) {\n if (err.code === 'ENOENT') throw buildNotFound(`Directory \"${sourceDir}\" does not exist`)\n throw err\n }\n\n const manifestPath = join(sourceDir, 'mf-manifest.json')\n let manifest: string\n try {\n manifest = await readFile(manifestPath, 'utf8')\n } catch (err) {\n if (err.code === 'ENOENT') {\n throw buildNotFound(\n `\"${manifestPath}\" does not exist; a federation build created with \"sanity build\" writes it.`,\n )\n }\n throw err\n }\n\n // Every deploy sends this file to the API, so a corrupt one must fail here\n // rather than after the application is created.\n let parsed: unknown\n try {\n parsed = JSON.parse(manifest)\n } catch {\n throw new Error(\n `\"${manifestPath}\" is not valid JSON. Run \"sanity build\" again to regenerate it.`,\n )\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error(\n `\"${manifestPath}\" is not a JSON object. Run \"sanity build\" again to regenerate it.`,\n )\n }\n return parsed as Record<string, unknown>\n}\n"],"names":["readFile","stat","join","buildNotFound","message","error","Error","name","readBuiltManifest","sourceDir","stats","isDirectory","err","code","manifestPath","manifest","parsed","JSON","parse","Array","isArray"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,IAAI,QAAO,mBAAkB;AAC/C,SAAQC,IAAI,QAAO,YAAW;AAE9B;;;;;CAKC,GACD,SAASC,cAAcC,OAAe;IACpC,MAAMC,QAAQ,IAAIC,MAAMF;IACxBC,MAAME,IAAI,GAAG;IACb,OAAOF;AACT;AAEA;;;;CAIC,GACD,OAAO,eAAeG,kBAAkBC,SAAiB;IACvD,IAAI;QACF,MAAMC,QAAQ,MAAMT,KAAKQ;QACzB,IAAI,CAACC,MAAMC,WAAW,IAAI;YACxB,MAAM,IAAIL,MAAM,CAAC,CAAC,EAAEG,UAAU,oBAAoB,CAAC;QACrD;IACF,EAAE,OAAOG,KAAK;QACZ,IAAIA,IAAIC,IAAI,KAAK,UAAU,MAAMV,cAAc,CAAC,WAAW,EAAEM,UAAU,gBAAgB,CAAC;QACxF,MAAMG;IACR;IAEA,MAAME,eAAeZ,KAAKO,WAAW;IACrC,IAAIM;IACJ,IAAI;QACFA,WAAW,MAAMf,SAASc,cAAc;IAC1C,EAAE,OAAOF,KAAK;QACZ,IAAIA,IAAIC,IAAI,KAAK,UAAU;YACzB,MAAMV,cACJ,CAAC,CAAC,EAAEW,aAAa,2EAA2E,CAAC;QAEjG;QACA,MAAMF;IACR;IAEA,2EAA2E;IAC3E,gDAAgD;IAChD,IAAII;IACJ,IAAI;QACFA,SAASC,KAAKC,KAAK,CAACH;IACtB,EAAE,OAAM;QACN,MAAM,IAAIT,MACR,CAAC,CAAC,EAAEQ,aAAa,+DAA+D,CAAC;IAErF;IACA,IAAI,OAAOE,WAAW,YAAYA,WAAW,QAAQG,MAAMC,OAAO,CAACJ,SAAS;QAC1E,MAAM,IAAIV,MACR,CAAC,CAAC,EAAEQ,aAAa,kEAAkE,CAAC;IAExF;IACA,OAAOE;AACT"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { basename, dirname, join } from 'node:path';
|
|
1
|
+
import { basename, dirname } from 'node:path';
|
|
3
2
|
import { createGzip } from 'node:zlib';
|
|
4
3
|
import { getErrorMessage } from '@sanity/cli-core/errors';
|
|
5
4
|
import { spinner } from '@sanity/cli-core/ux';
|
|
@@ -102,13 +101,11 @@ function toBrettInterface(iface, version) {
|
|
|
102
101
|
* sync — so a caller can disarm a create-time rollback that must not delete an
|
|
103
102
|
* application once it has an active deployment.
|
|
104
103
|
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
* registered origin.
|
|
104
|
+
* `isExternal` skips the tarball: the customer serves the build from the
|
|
105
|
+
* application's registered origin.
|
|
108
106
|
* @internal
|
|
109
107
|
*/ export async function deployWorkbenchApp(options) {
|
|
110
|
-
const { access, app, applicationId, icon, isApp, isAutoUpdating, isExternal = false, label = 'Deploying...', onDeployed, slug, sourceDir, title, version, visibility, workspaces } = options;
|
|
111
|
-
const mfManifest = JSON.parse(await readFile(join(sourceDir, 'mf-manifest.json'), 'utf8'));
|
|
108
|
+
const { access, app, applicationId, icon, isApp, isAutoUpdating, isExternal = false, label = 'Deploying...', mfManifest, onDeployed, slug, sourceDir, title, version, visibility, workspaces } = options;
|
|
112
109
|
const tarball = isExternal ? undefined : createTar({
|
|
113
110
|
cwd: dirname(sourceDir)
|
|
114
111
|
}, [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/deploy/deployWorkbenchApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {type AppVisibility, type CliConfig} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {c as createTar} from 'tar'\n\nimport {type DerivedInterface, deriveInterfaces} from '../../deriveInterfaces.js'\nimport {\n type Application,\n type BrettAccess,\n type BrettInterface,\n type BrettWorkspace,\n createApplication,\n createDeployment,\n deleteApplication,\n updateApplication,\n} from '../../services/applications.js'\n\n/**\n * `rollback` undoes the creation, so a later failure leaves no record stranded at the slug.\n * @internal\n */\nexport interface CreatedApplication {\n application: Application\n rollback: () => Promise<void>\n}\n\nfunction toBrettInterface(iface: DerivedInterface, version: string): BrettInterface {\n const {id: _id, src: _src, ...declaration} = iface\n if ('type' in declaration) return {...declaration, version}\n\n switch (declaration.surface) {\n case 'asset_source': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'panel': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'tile': {\n const {surface, ...view} = declaration\n return {...view, type: surface, version}\n }\n case 'window': {\n const {surface, ...view} = declaration\n return {...view, type: 'app', version}\n }\n }\n}\n\n/**\n * Create a coreApp record (no deployment), so the CLI can build with its id\n * before shipping the first deployment. First deploy only.\n * @internal\n */\nexport async function createCoreApp(options: {\n isSingleton?: boolean\n name?: string\n organizationId: string\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating application...').start()\n try {\n const application = await createApplication({...options, type: 'coreApp'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Create a studio record (no deployment).\n * @internal\n */\nexport async function createStudio(options: {\n externalUrl?: string\n name?: string\n organizationId: string\n projectId: string | undefined\n slug: string\n title: string\n visibility?: AppVisibility\n}): Promise<CreatedApplication> {\n const spin = spinner('Creating studio...').start()\n try {\n const application = await createApplication({...options, type: 'studio'})\n spin.succeed()\n return {application, rollback: () => deleteApplication(application.id)}\n } catch (error) {\n spin.fail()\n throw error\n }\n}\n\n/**\n * Ship a deployment to an already-created (or `deployment.appId`) application,\n * then sync its mutable metadata (`title`, and `icon`/`slug`/`visibility` when\n * set) from config. The deploy endpoint ignores these, so a redeploy patches\n * them here alongside the new deployment.\n *\n * `onDeployed` fires the instant the deployment is live, before the metadata\n * sync — so a caller can disarm a create-time rollback that must not delete an\n * application once it has an active deployment.\n *\n * `isExternal` skips the tarball: the customer serves the build from the\n * application's registered origin.\n * @internal\n */\nexport async function deployWorkbenchApp(options: {\n access?: readonly BrettAccess[]\n app: CliConfig['app']\n applicationId: string\n icon?: string\n isApp: boolean\n isAutoUpdating: boolean\n isExternal?: boolean\n label?: string\n mfManifest: Record<string, unknown>\n onDeployed?: () => void\n /**\n * The address from config. Only `createApplication` used to send it, so an\n * app with a `deployment.appId` kept whatever slug it was created at.\n */\n slug?: string\n sourceDir: string\n title: string\n version: string\n visibility?: AppVisibility\n workspaces?: readonly BrettWorkspace[]\n}): Promise<void> {\n const {\n access,\n app,\n applicationId,\n icon,\n isApp,\n isAutoUpdating,\n isExternal = false,\n label = 'Deploying...',\n mfManifest,\n onDeployed,\n slug,\n sourceDir,\n title,\n version,\n visibility,\n workspaces,\n } = options\n const tarball = isExternal\n ? undefined\n : createTar({cwd: dirname(sourceDir)}, [basename(sourceDir)]).pipe(createGzip())\n\n const spin = spinner(label).start()\n try {\n await createDeployment({\n access,\n applicationId,\n // Brett assigns the id and resolves modules by `moduleId`, so neither travels.\n interfaces: deriveInterfaces(app, {appTitle: title, isApp}).map((iface) =>\n toBrettInterface(iface, version),\n ),\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n })\n onDeployed?.()\n try {\n await updateApplication(applicationId, {\n title,\n ...(icon ? {icon} : {}),\n ...(slug ? {slug} : {}),\n ...(visibility ? {visibility} : {}),\n })\n } catch (error) {\n throw toSlugRejection(error, slug)\n }\n spin.succeed()\n } catch (error) {\n spin.clear()\n throw error\n }\n}\n\n/**\n * The slug is the one synced field the server validates — it must be free\n * within the organization, and a singleton app only accepts its reserved\n * identifiers — so a 4xx on the metadata patch is a rejected rename. Name the\n * slug and the server's reason; anything else propagates untouched.\n */\nfunction toSlugRejection(error: unknown, slug: string | undefined): unknown {\n const statusCode = (error as {statusCode?: number})?.statusCode\n if (!slug || statusCode === undefined || statusCode < 400 || statusCode >= 500) return error\n return new Error(\n `Slug \"${slug}\" was rejected: ${getErrorMessage(error)}. The deployment is live at the application's previous slug — change \\`app.slug\\` in sanity.cli.ts and deploy again.`,\n {cause: error},\n )\n}\n"],"names":["basename","dirname","createGzip","getErrorMessage","spinner","c","createTar","deriveInterfaces","createApplication","createDeployment","deleteApplication","updateApplication","toBrettInterface","iface","version","id","_id","src","_src","declaration","surface","view","type","createCoreApp","options","spin","start","application","succeed","rollback","error","fail","createStudio","deployWorkbenchApp","access","app","applicationId","icon","isApp","isAutoUpdating","isExternal","label","mfManifest","onDeployed","slug","sourceDir","title","visibility","workspaces","tarball","undefined","cwd","pipe","interfaces","appTitle","map","toSlugRejection","clear","statusCode","Error","cause"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,UAAU,QAAO,YAAW;AAGpC,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAKC,SAAS,QAAO,MAAK;AAElC,SAA+BC,gBAAgB,QAAO,4BAA2B;AACjF,SAKEC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,iCAAgC;AAWvC,SAASC,iBAAiBC,KAAuB,EAAEC,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IACR;AACF;AAEA;;;;;CAKC,GACD,SAAS0B,gBAAgB1B,KAAc,EAAEc,IAAwB;IAC/D,MAAMc,aAAc5B,OAAiC4B;IACrD,IAAI,CAACd,QAAQc,eAAeR,aAAaQ,aAAa,OAAOA,cAAc,KAAK,OAAO5B;IACvF,OAAO,IAAI6B,MACT,CAAC,MAAM,EAAEf,KAAK,gBAAgB,EAAEzC,gBAAgB2B,OAAO,oHAAoH,CAAC,EAC5K;QAAC8B,OAAO9B;IAAK;AAEjB"}
|
|
@@ -15,9 +15,9 @@ import { getProcessStartTime, isOurProcess } from './processLiveness.js';
|
|
|
15
15
|
* plus its inlined manifest and interfaces. The workbench reads these to
|
|
16
16
|
* discover and render local apps. Written by `registerDevServer`, watched by
|
|
17
17
|
* `watchRegistry`.
|
|
18
|
-
* - `workbench
|
|
19
|
-
* runs at a time and later `dev`s register into it
|
|
20
|
-
* own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.
|
|
18
|
+
* - `workbench-<organizationId>.lock` — one lock per organization, so only one
|
|
19
|
+
* workbench shell per org runs at a time and later `dev`s register into it
|
|
20
|
+
* instead of starting their own. Managed by `acquireWorkbenchLock` / `readWorkbenchLock`.
|
|
21
21
|
*
|
|
22
22
|
* Both files belong to the process that created them and must not outlive it.
|
|
23
23
|
* Three things keep that true: an explicit `release()` on clean shutdown, an
|
|
@@ -299,7 +299,7 @@ function runExitCleanups() {
|
|
|
299
299
|
}
|
|
300
300
|
};
|
|
301
301
|
}
|
|
302
|
-
// The workbench singleton lock — "one workbench per
|
|
302
|
+
// The workbench singleton lock — "one workbench per organization". Lives in the same
|
|
303
303
|
// registry dir and shares the liveness/prune model: a stale lock left by a
|
|
304
304
|
// crashed process is pruned on read so the next acquire isn't blocked forever.
|
|
305
305
|
const workbenchLockSchema = z.object({
|
|
@@ -313,8 +313,8 @@ const workbenchLockSchema = z.object({
|
|
|
313
313
|
/**
|
|
314
314
|
* Read the workbench lock file and return its contents if the holding
|
|
315
315
|
* process is still alive. Prunes stale locks from crashed processes.
|
|
316
|
-
*/ export function readWorkbenchLock() {
|
|
317
|
-
const file = readLockFile();
|
|
316
|
+
*/ export function readWorkbenchLock(organizationId) {
|
|
317
|
+
const file = readLockFile(organizationId);
|
|
318
318
|
// File doesn't exist — nothing to prune, nothing to return
|
|
319
319
|
if (!file) return undefined;
|
|
320
320
|
// Past this point the file exists. Anything that isn't a live, valid lock
|
|
@@ -327,7 +327,7 @@ const workbenchLockSchema = z.object({
|
|
|
327
327
|
devDebug('Workbench process is alive at pid %d on port %d', data.pid, data.port);
|
|
328
328
|
return data;
|
|
329
329
|
}
|
|
330
|
-
pruneWorkbenchLock(getLockPath());
|
|
330
|
+
pruneWorkbenchLock(getLockPath(organizationId));
|
|
331
331
|
return undefined;
|
|
332
332
|
}
|
|
333
333
|
const LOCK_READY_TIMEOUT_MS = 10_000;
|
|
@@ -335,30 +335,30 @@ const LOCK_READY_POLL_MS = 50;
|
|
|
335
335
|
/**
|
|
336
336
|
* Read the workbench lock once its holder's shell is listening, so the port is
|
|
337
337
|
* the bound one. Returns the lock as-is after {@link LOCK_READY_TIMEOUT_MS}.
|
|
338
|
-
*/ export async function waitForWorkbenchLock() {
|
|
338
|
+
*/ export async function waitForWorkbenchLock(organizationId) {
|
|
339
339
|
const deadline = Date.now() + LOCK_READY_TIMEOUT_MS;
|
|
340
|
-
let lock = readWorkbenchLock();
|
|
340
|
+
let lock = readWorkbenchLock(organizationId);
|
|
341
341
|
// Read the raw file here: `readWorkbenchLock` spawns `ps`/PowerShell per call
|
|
342
342
|
// and deletes a lock it catches half-written by `updatePort`.
|
|
343
343
|
while(lock?.ready === false && Date.now() < deadline){
|
|
344
344
|
await new Promise((resolve)=>setTimeout(resolve, LOCK_READY_POLL_MS));
|
|
345
|
-
const file = readLockFile();
|
|
345
|
+
const file = readLockFile(organizationId);
|
|
346
346
|
if (!file) break;
|
|
347
347
|
lock = file.data ?? lock;
|
|
348
348
|
}
|
|
349
349
|
if (lock?.ready === false && Date.now() >= deadline) {
|
|
350
350
|
devDebug('Workbench lock not ready after %d ms, using port %d', LOCK_READY_TIMEOUT_MS, lock.port);
|
|
351
351
|
}
|
|
352
|
-
return readWorkbenchLock();
|
|
352
|
+
return readWorkbenchLock(organizationId);
|
|
353
353
|
}
|
|
354
|
-
const getLockPath = ()=>join(getRegistryDir(),
|
|
354
|
+
const getLockPath = (organizationId)=>join(getRegistryDir(), `workbench-${organizationId}.lock`);
|
|
355
355
|
/**
|
|
356
356
|
* Read the lock file with no liveness check and no pruning. `undefined` when
|
|
357
357
|
* there is no file; `data` is `undefined` when its contents don't parse.
|
|
358
|
-
*/ function readLockFile() {
|
|
358
|
+
*/ function readLockFile(organizationId) {
|
|
359
359
|
let contents;
|
|
360
360
|
try {
|
|
361
|
-
contents = readFileSync(getLockPath(), 'utf8');
|
|
361
|
+
contents = readFileSync(getLockPath(organizationId), 'utf8');
|
|
362
362
|
} catch {
|
|
363
363
|
return undefined;
|
|
364
364
|
}
|
|
@@ -400,7 +400,7 @@ function pruneWorkbenchLock(lockPath) {
|
|
|
400
400
|
mkdirSync(registryDir, {
|
|
401
401
|
recursive: true
|
|
402
402
|
});
|
|
403
|
-
const lockPath = getLockPath();
|
|
403
|
+
const lockPath = getLockPath(info.organizationId);
|
|
404
404
|
const startedAt = ownStartedAt();
|
|
405
405
|
const lockData = {
|
|
406
406
|
host: info.host,
|
|
@@ -421,7 +421,7 @@ function pruneWorkbenchLock(lockPath) {
|
|
|
421
421
|
// it after our own release must not be clobbered.
|
|
422
422
|
const detachExitCleanup = unlinkOnProcessExit(lockPath, ()=>{
|
|
423
423
|
if (released) return false;
|
|
424
|
-
const disk = readLockFile()?.data;
|
|
424
|
+
const disk = readLockFile(info.organizationId)?.data;
|
|
425
425
|
return disk?.pid === process.pid && disk.startedAt === startedAt;
|
|
426
426
|
});
|
|
427
427
|
return {
|
|
@@ -446,7 +446,7 @@ function pruneWorkbenchLock(lockPath) {
|
|
|
446
446
|
devDebug('Failed to acquire workbench lock: %s', err instanceof Error ? err.message : String(err));
|
|
447
447
|
if (!isNodeError(err) || err.code !== 'EEXIST') return undefined;
|
|
448
448
|
// Lock exists — check if the holder is still alive
|
|
449
|
-
const existing = readWorkbenchLock();
|
|
449
|
+
const existing = readWorkbenchLock(info.organizationId);
|
|
450
450
|
if (existing) return undefined;
|
|
451
451
|
// Stale lock was pruned by readWorkbenchLock — retry (with guard against infinite recursion)
|
|
452
452
|
if (retries <= 0) return undefined;
|
|
@@ -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 * Where the Dashboard shell opens a registered server: `/local/<id>`, only when\n * it has an id and a `surface: 'window'` interface. That interface is the app\n * view the shell's `/local/:applicationId` route renders (see toWireInterface);\n * studios always get one, configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n return server.id && hasAppView ? `/local/${encodeURIComponent(server.id)}` : undefined\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","dashboardPath","hasAppView","some","iface","encodeURIComponent","undefined","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","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,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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AAOlE;QACzB,OAAOgE,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-<organizationId>.lock` — one lock per organization, so only one\n * workbench shell per org runs at a time and later `dev`s register into it\n * instead of starting their 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 * Where the Dashboard shell opens a registered server: `/local/<id>`, only when\n * it has an id and a `surface: 'window'` interface. That interface is the app\n * view the shell's `/local/:applicationId` route renders (see toWireInterface);\n * studios always get one, configs and panel-only apps don't, so they'd 404.\n */\nexport function dashboardPath(\n server: Pick<DevServerManifest, 'id' | 'interfaces'>,\n): string | undefined {\n const hasAppView = (server.interfaces ?? []).some(\n (iface) => 'surface' in iface && iface.surface === 'window',\n )\n return server.id && hasAppView ? `/local/${encodeURIComponent(server.id)}` : undefined\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 organization\". 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(\n organizationId: string,\n): z.infer<typeof workbenchLockSchema> | undefined {\n const file = readLockFile(organizationId)\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(organizationId))\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(\n organizationId: string,\n): Promise<z.infer<typeof workbenchLockSchema> | undefined> {\n const deadline = Date.now() + LOCK_READY_TIMEOUT_MS\n let lock = readWorkbenchLock(organizationId)\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(organizationId)\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(organizationId)\n}\n\nconst getLockPath = (organizationId: string) =>\n join(getRegistryDir(), `workbench-${organizationId}.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(\n organizationId: string,\n): {data: z.infer<typeof workbenchLockSchema> | undefined} | undefined {\n let contents: string\n try {\n contents = readFileSync(getLockPath(organizationId), '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; organizationId: string; port: number},\n retries = 1,\n): WorkbenchLock | undefined {\n const registryDir = getRegistryDir()\n mkdirSync(registryDir, {recursive: true})\n\n const lockPath = getLockPath(info.organizationId)\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(info.organizationId)?.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(info.organizationId)\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","dashboardPath","hasAppView","some","iface","encodeURIComponent","undefined","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","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,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,E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,QAAQA,IAAIK,IAAI,KAAK,UAAU,OAAO5E;QAEvD,mDAAmD;QACnD,MAAM6E,WAAW5B,kBAAkBgB,KAAKpF,cAAc;QACtD,IAAIgG,UAAU,OAAO7E;QAErB,6FAA6F;QAC7F,IAAIkE,WAAW,GAAG,OAAOlE;QACzB,OAAOgE,qBAAqBC,MAAMC,UAAU;IAC9C;AACF;AAEA,SAASS,YAAYJ,GAAY;IAC/B,OAAOA,eAAeC,SAAS,UAAUD;AAC3C"}
|
|
@@ -57,8 +57,9 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
|
|
|
57
57
|
organizationId: workbenchApp.organizationId
|
|
58
58
|
}) : undefined;
|
|
59
59
|
// Separate namespaces mean a shared id is a genuine duplicate, so the gate is
|
|
60
|
-
//
|
|
61
|
-
const
|
|
60
|
+
// an id match within the org — no config-vs-app role left to reconcile.
|
|
61
|
+
const organizationId = cliConfig.app?.organizationId;
|
|
62
|
+
const devServer = id ? getRegisteredServers().find((server)=>server.id === id && server.organizationId === organizationId) : undefined;
|
|
62
63
|
if (id && devServer) {
|
|
63
64
|
output.error(`"${id}" is already served by another dev server running on port ${devServer.port}, ` + "so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.", {
|
|
64
65
|
exit: false
|
|
@@ -73,7 +74,7 @@ import { startDevManifestWatcher } from './startDevManifestWatcher.js';
|
|
|
73
74
|
id,
|
|
74
75
|
interfaces,
|
|
75
76
|
name,
|
|
76
|
-
organizationId
|
|
77
|
+
organizationId,
|
|
77
78
|
port: appPort,
|
|
78
79
|
projectId: cliConfig?.api?.projectId,
|
|
79
80
|
reference,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {applicationReference} from '../../applicationReference.js'\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from '../../validateWorkbenchApp.js'\nimport {deriveConfigs} from './deriveConfigs.js'\nimport {trackExposesSet} from './exposesSetId.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n getRegisteredServers,\n registerDevServer,\n} from './registry.js'\nimport {startDevManifestWatcher} from './startDevManifestWatcher.js'\n\ninterface DevServerRegistrationOptions {\n cliConfig: CliConfig\n /**\n * Extract the project manifest to inline into the registry. The caller owns the\n * studio-vs-app split (manifest formats are CLI-domain); registration re-derives\n * the interface set alongside it.\n */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n isApp: boolean\n output: Output\n server: ViteDevServer\n workDir: string\n\n /**\n * Rebuild the app's federation remote when its interface set changes, awaited\n * *before* the registry patch — the patch reloads the workbench page, which must\n * re-fetch a remote that already exposes the new interface. Resolves with the\n * recreated server so the entry gets its actual address (non-strict ports may\n * shift it); must reject if the restart produces no server, so the set stays\n * uncommitted and the next save retries instead of advertising a dead port.\n */\n onInterfaceSetChange?: () => Promise<ViteDevServer>\n}\n\ninterface DevServerRegistrationHandle {\n close: () => Promise<void>\n\n /** Where the Dashboard opens this server; unset when it can't open it there. */\n path?: string\n}\n\n/**\n * Log any app validation errors without aborting. Unlike build and deploy, dev\n * stays up on an invalid app so the author sees the errors and fixes them live on\n * the next save. A config is not an app — it isn't validated by the app schema\n * (which would spuriously demand a slug/title), so skip it here.\n */\nfunction reportConfigErrors(app: CliConfig['app'], output: Output): void {\n if (isWorkbenchConfig(app)) return\n const errors = validateWorkbenchApp(app)\n if (errors.length === 0) return\n output.warn(formatWorkbenchAppErrors(errors))\n}\n\n/** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */\nfunction serverAddress(server: ViteDevServer) {\n const resolvedHost = server.config.server.host\n const addr = server.httpServer?.address()\n return {\n host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',\n port: typeof addr === 'object' && addr ? addr.port : server.config.server.port,\n }\n}\n\n/**\n * Register the dev server in the registry and watch its config for manifest +\n * interface changes. The workbench reads the entry to locate and render the\n * server; the watcher keeps it current as `sanity.cli.ts` is edited.\n */\nexport async function startDevServerRegistration(\n options: DevServerRegistrationOptions,\n): Promise<DevServerRegistrationHandle> {\n const {cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir} = options\n\n const {host: appHost, port: appPort} = serverAddress(server)\n\n reportConfigErrors(cliConfig.app, output)\n\n // Forwarded alongside (not inside) the manifest so the workbench renders local\n // panels/workers and reads the configs without a deploy.\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const configs = await deriveConfigs(cliConfig)\n\n const workbenchApp = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const config = resolveWorkbenchConfig(cliConfig)\n // A config runs alongside the app it configures, so give it its own id\n // namespace — sharing the app's slug would make the two indistinguishable here.\n const id = config ? `config:${config.appType}` : workbenchApp?.slug\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them. Name defaults to the\n // slug, mirroring brett.\n const name = workbenchApp?.name ?? workbenchApp?.slug\n const reference =\n workbenchApp && name\n ? // No workbench app is a singleton now that the only one (the Media Library)\n // is a config, not an app — so its reference is always `<org>/<name>`.\n applicationReference({\n isSingleton: false,\n name,\n organizationId: workbenchApp.organizationId,\n })\n : undefined\n\n // Separate namespaces mean a shared id is a genuine duplicate, so the gate is\n // a plain id match — no config-vs-app role left to reconcile.\n const devServer = id ? getRegisteredServers().find((server) => server.id === id) : undefined\n\n if (id && devServer) {\n output.error(\n `\"${id}\" is already served by another dev server running on port ${devServer.port}, ` +\n \"so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.\",\n {exit: false},\n )\n return {close: async () => {}}\n }\n\n const registration = registerDevServer({\n configs,\n host: appHost,\n id,\n interfaces,\n name,\n organizationId: workbenchApp?.organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n reference,\n slug: workbenchApp?.slug,\n type: isApp ? 'coreApp' : 'studio',\n visibility: workbenchApp ? (workbenchApp.visibility ?? 'default') : undefined,\n workDir,\n })\n\n const exposesSet = trackExposesSet({configs, interfaces})\n\n const watcher = await startDevManifestWatcher({\n // Re-derive every pass (don't omit): the registry patch is a shallow merge,\n // so omitting would wipe the registered set.\n extract: async (params) => {\n const nextConfig = await getCliConfigUncached(params.workDir)\n reportConfigErrors(nextConfig.app, output)\n return {\n configs: await deriveConfigs(nextConfig),\n interfaces: deriveInterfaces(nextConfig.app, {isApp}),\n manifest: await extractManifest({...params, applicationId: id}),\n }\n },\n // A studio's root resolves to `sanity.config.*` but its interfaces live in\n // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.\n extraWatchFilenames: isApp ? undefined : ['sanity.cli.js', 'sanity.cli.ts'],\n output,\n update: async (patch) => {\n if (\n !exposesSet.changed({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n ) {\n registration.update(patch)\n return\n }\n // Rebuild the remote *before* patching the registry — the patch reloads the\n // page, which must re-fetch a remote that already exposes the new interface.\n const rebuiltServer = await onInterfaceSetChange?.()\n // Commit only after a successful rebuild, so a thrown one retries next pass.\n exposesSet.commit({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n // The recreated server can bind a different port (non-strict ports).\n registration.update(rebuiltServer ? {...patch, ...serverAddress(rebuiltServer)} : patch)\n },\n workDir,\n })\n\n return {\n close: async () => {\n registration.release()\n await watcher.close()\n },\n path: dashboardPath({id, interfaces}),\n }\n}\n"],"names":["getCliConfigUncached","applicationReference","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","name","reference","isSingleton","organizationId","devServer","find","error","exit","close","registration","projectId","api","type","visibility","exposesSet","watcher","extract","params","nextConfig","manifest","applicationId","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,oBAAoB,QAAO,gCAA+B;AAClE,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,gCAA+B;AAC5F,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,eAAe,QAAO,oBAAmB;AACjD,SACEC,aAAa,EAEbC,oBAAoB,EACpBC,iBAAiB,QACZ,gBAAe;AACtB,SAAQC,uBAAuB,QAAO,+BAA8B;AAqCpE;;;;;CAKC,GACD,SAASC,mBAAmBC,GAAqB,EAAEC,MAAc;IAC/D,IAAIb,kBAAkBY,MAAM;IAC5B,MAAME,SAASV,qBAAqBQ;IACpC,IAAIE,OAAOC,MAAM,KAAK,GAAG;IACzBF,OAAOG,IAAI,CAACb,yBAAyBW;AACvC;AAEA,+HAA+H,GAC/H,SAASG,cAAcC,MAAqB;IAC1C,MAAMC,eAAeD,OAAOE,MAAM,CAACF,MAAM,CAACG,IAAI;IAC9C,MAAMC,OAAOJ,OAAOK,UAAU,EAAEC;IAChC,OAAO;QACLH,MAAM,OAAOF,iBAAiB,WAAWA,eAAe;QACxDM,MAAM,OAAOH,SAAS,YAAYA,OAAOA,KAAKG,IAAI,GAAGP,OAAOE,MAAM,CAACF,MAAM,CAACO,IAAI;IAChF;AACF;AAEA;;;;CAIC,GACD,OAAO,eAAeC,2BACpBC,OAAqC;IAErC,MAAM,EAACC,SAAS,EAA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cAAc;YAACgC;YAAIJ;QAAU;IACrC;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {applicationReference} from '../../applicationReference.js'\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchConfig} from '../../resolveWorkbenchConfig.js'\nimport {formatWorkbenchAppErrors, validateWorkbenchApp} from '../../validateWorkbenchApp.js'\nimport {deriveConfigs} from './deriveConfigs.js'\nimport {trackExposesSet} from './exposesSetId.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n getRegisteredServers,\n registerDevServer,\n} from './registry.js'\nimport {startDevManifestWatcher} from './startDevManifestWatcher.js'\n\ninterface DevServerRegistrationOptions {\n cliConfig: CliConfig\n /**\n * Extract the project manifest to inline into the registry. The caller owns the\n * studio-vs-app split (manifest formats are CLI-domain); registration re-derives\n * the interface set alongside it.\n */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n isApp: boolean\n output: Output\n server: ViteDevServer\n workDir: string\n\n /**\n * Rebuild the app's federation remote when its interface set changes, awaited\n * *before* the registry patch — the patch reloads the workbench page, which must\n * re-fetch a remote that already exposes the new interface. Resolves with the\n * recreated server so the entry gets its actual address (non-strict ports may\n * shift it); must reject if the restart produces no server, so the set stays\n * uncommitted and the next save retries instead of advertising a dead port.\n */\n onInterfaceSetChange?: () => Promise<ViteDevServer>\n}\n\ninterface DevServerRegistrationHandle {\n close: () => Promise<void>\n\n /** Where the Dashboard opens this server; unset when it can't open it there. */\n path?: string\n}\n\n/**\n * Log any app validation errors without aborting. Unlike build and deploy, dev\n * stays up on an invalid app so the author sees the errors and fixes them live on\n * the next save. A config is not an app — it isn't validated by the app schema\n * (which would spuriously demand a slug/title), so skip it here.\n */\nfunction reportConfigErrors(app: CliConfig['app'], output: Output): void {\n if (isWorkbenchConfig(app)) return\n const errors = validateWorkbenchApp(app)\n if (errors.length === 0) return\n output.warn(formatWorkbenchAppErrors(errors))\n}\n\n/** The address the server actually bound — the live socket, which can differ from the configured port under non-strict ports. */\nfunction serverAddress(server: ViteDevServer) {\n const resolvedHost = server.config.server.host\n const addr = server.httpServer?.address()\n return {\n host: typeof resolvedHost === 'string' ? resolvedHost : 'localhost',\n port: typeof addr === 'object' && addr ? addr.port : server.config.server.port,\n }\n}\n\n/**\n * Register the dev server in the registry and watch its config for manifest +\n * interface changes. The workbench reads the entry to locate and render the\n * server; the watcher keeps it current as `sanity.cli.ts` is edited.\n */\nexport async function startDevServerRegistration(\n options: DevServerRegistrationOptions,\n): Promise<DevServerRegistrationHandle> {\n const {cliConfig, extractManifest, isApp, onInterfaceSetChange, output, server, workDir} = options\n\n const {host: appHost, port: appPort} = serverAddress(server)\n\n reportConfigErrors(cliConfig.app, output)\n\n // Forwarded alongside (not inside) the manifest so the workbench renders local\n // panels/workers and reads the configs without a deploy.\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const configs = await deriveConfigs(cliConfig)\n\n const workbenchApp = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const config = resolveWorkbenchConfig(cliConfig)\n // A config runs alongside the app it configures, so give it its own id\n // namespace — sharing the app's slug would make the two indistinguishable here.\n const id = config ? `config:${config.appType}` : workbenchApp?.slug\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them. Name defaults to the\n // slug, mirroring brett.\n const name = workbenchApp?.name ?? workbenchApp?.slug\n const reference =\n workbenchApp && name\n ? // No workbench app is a singleton now that the only one (the Media Library)\n // is a config, not an app — so its reference is always `<org>/<name>`.\n applicationReference({\n isSingleton: false,\n name,\n organizationId: workbenchApp.organizationId,\n })\n : undefined\n\n // Separate namespaces mean a shared id is a genuine duplicate, so the gate is\n // an id match within the org — no config-vs-app role left to reconcile.\n const organizationId = cliConfig.app?.organizationId\n const devServer = id\n ? getRegisteredServers().find(\n (server) => server.id === id && server.organizationId === organizationId,\n )\n : undefined\n\n if (id && devServer) {\n output.error(\n `\"${id}\" is already served by another dev server running on port ${devServer.port}, ` +\n \"so the Dashboard can't tell them apart and this one stays out of it. Stop that server first.\",\n {exit: false},\n )\n return {close: async () => {}}\n }\n\n const registration = registerDevServer({\n configs,\n host: appHost,\n id,\n interfaces,\n name,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n reference,\n slug: workbenchApp?.slug,\n type: isApp ? 'coreApp' : 'studio',\n visibility: workbenchApp ? (workbenchApp.visibility ?? 'default') : undefined,\n workDir,\n })\n\n const exposesSet = trackExposesSet({configs, interfaces})\n\n const watcher = await startDevManifestWatcher({\n // Re-derive every pass (don't omit): the registry patch is a shallow merge,\n // so omitting would wipe the registered set.\n extract: async (params) => {\n const nextConfig = await getCliConfigUncached(params.workDir)\n reportConfigErrors(nextConfig.app, output)\n return {\n configs: await deriveConfigs(nextConfig),\n interfaces: deriveInterfaces(nextConfig.app, {isApp}),\n manifest: await extractManifest({...params, applicationId: id}),\n }\n },\n // A studio's root resolves to `sanity.config.*` but its interfaces live in\n // `sanity.cli.*` — watch that too. Apps already root at `sanity.cli.*`.\n extraWatchFilenames: isApp ? undefined : ['sanity.cli.js', 'sanity.cli.ts'],\n output,\n update: async (patch) => {\n if (\n !exposesSet.changed({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n ) {\n registration.update(patch)\n return\n }\n // Rebuild the remote *before* patching the registry — the patch reloads the\n // page, which must re-fetch a remote that already exposes the new interface.\n const rebuiltServer = await onInterfaceSetChange?.()\n // Commit only after a successful rebuild, so a thrown one retries next pass.\n exposesSet.commit({\n configs: patch.configs,\n interfaces: patch.interfaces,\n })\n // The recreated server can bind a different port (non-strict ports).\n registration.update(rebuiltServer ? {...patch, ...serverAddress(rebuiltServer)} : patch)\n },\n workDir,\n })\n\n return {\n close: async () => {\n registration.release()\n await watcher.close()\n },\n path: dashboardPath({id, interfaces}),\n }\n}\n"],"names":["getCliConfigUncached","applicationReference","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","name","reference","isSingleton","organizationId","devServer","find","error","exit","close","registration","projectId","api","type","visibility","exposesSet","watcher","extract","params","nextConfig","manifest","applicationId","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,oBAAoB,QAAO,gCAA+B;AAClE,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAAQC,wBAAwB,EAAEC,oBAAoB,QAAO,gCAA+B;AAC5F,SAAQC,aAAa,QAAO,qBAAoB;AAChD,SAAQC,eAAe,QAAO,oBAAmB;AACjD,SACEC,aAAa,EAEbC,oBAAoB,EACpBC,iBAAiB,QACZ,gBAAe;AACtB,SAAQC,uBAAuB,QAAO,+BAA8B;AAqCpE;;;;;CAKC,GACD,SAASC,mBAAmBC,GAAqB,EAAEC,MAAc;IAC/D,IAAIb,kBAAkBY,MAAM;IAC5B,MAAME,SAASV,qBAAqBQ;IACpC,IAAIE,OAAOC,MAAM,KAAK,GAAG;IACzBF,OAAOG,IAAI,CAACb,yBAAyBW;AACvC;AAEA,+HAA+H,GAC/H,SAASG,cAAcC,MAAqB;IAC1C,MAAMC,eAAeD,OAAOE,MAAM,CAACF,MAAM,CAACG,I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C;YAC5B,6EAA6E;YAC7EyB,WAAWY,MAAM,CAAC;gBAChBhC,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B;YACA,qEAAqE;YACrEgB,aAAaa,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGhD,cAAckD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLkB,OAAO;YACLC,aAAakB,OAAO;YACpB,MAAMZ,QAAQP,KAAK;QACrB;QACAoB,MAAM/D,cAAc;YAACgC;YAAIJ;QAAU;IACrC;AACF"}
|
|
@@ -50,12 +50,14 @@ const toApplicationsPayload = (servers)=>({
|
|
|
50
50
|
* the page tracks apps as they come and go. A changed interface set means a
|
|
51
51
|
* rebuilt remote — full-reload to drop the stale remote-entry; otherwise
|
|
52
52
|
* rebroadcast for a soft reconcile. Returns a detach fn.
|
|
53
|
-
*/ function attachViteDevServerBridge(server) {
|
|
53
|
+
*/ function attachViteDevServerBridge(server, organizationId) {
|
|
54
|
+
const ownServers = (servers)=>organizationId ? servers.filter((entry)=>entry.organizationId === organizationId) : servers;
|
|
54
55
|
server.ws.on('sanity:workbench:get-local-applications', (_, client)=>{
|
|
55
|
-
client.send('sanity:workbench:local-applications', toApplicationsPayload(getRegisteredServers()));
|
|
56
|
+
client.send('sanity:workbench:local-applications', toApplicationsPayload(ownServers(getRegisteredServers())));
|
|
56
57
|
});
|
|
57
58
|
const setTracker = createExposesTracker();
|
|
58
|
-
const registryWatcher = watchRegistry((
|
|
59
|
+
const registryWatcher = watchRegistry((allServers)=>{
|
|
60
|
+
const servers = ownServers(allServers);
|
|
59
61
|
if (setTracker.hasChanged(servers)) {
|
|
60
62
|
server.ws.send({
|
|
61
63
|
type: 'full-reload'
|
|
@@ -90,15 +92,17 @@ export async function startWorkbenchDevServer(options) {
|
|
|
90
92
|
workbenchPort
|
|
91
93
|
};
|
|
92
94
|
}
|
|
93
|
-
|
|
95
|
+
const organizationId = resolveOrganizationId(cliConfig);
|
|
96
|
+
// Acquire an exclusive lock — only one workbench per organization.
|
|
94
97
|
// Uses O_EXCL which is atomic at the OS level, preventing races when
|
|
95
98
|
// multiple `sanity dev` processes start simultaneously (e.g. via turbo).
|
|
96
99
|
const workbenchLock = acquireWorkbenchLock({
|
|
97
100
|
host: httpHost || 'localhost',
|
|
101
|
+
organizationId,
|
|
98
102
|
port: workbenchPort
|
|
99
103
|
});
|
|
100
104
|
if (!workbenchLock) {
|
|
101
|
-
const existing = await waitForWorkbenchLock();
|
|
105
|
+
const existing = await waitForWorkbenchLock(organizationId);
|
|
102
106
|
devDebug('Workbench already running at pid %d on port %d, skipping', existing?.pid, existing?.port);
|
|
103
107
|
return {
|
|
104
108
|
close: noop,
|
|
@@ -114,8 +118,8 @@ export async function startWorkbenchDevServer(options) {
|
|
|
114
118
|
try {
|
|
115
119
|
result = await createWorkbenchViteServer({
|
|
116
120
|
cacheDir,
|
|
117
|
-
cliConfig,
|
|
118
121
|
httpHost,
|
|
122
|
+
organizationId,
|
|
119
123
|
output,
|
|
120
124
|
reactStrictMode,
|
|
121
125
|
workbenchPort,
|
|
@@ -147,9 +151,8 @@ export async function startWorkbenchDevServer(options) {
|
|
|
147
151
|
};
|
|
148
152
|
}
|
|
149
153
|
async function createWorkbenchViteServer(options) {
|
|
150
|
-
const { cacheDir,
|
|
154
|
+
const { cacheDir, httpHost, organizationId, output, reactStrictMode, workbenchPort, workDir } = options;
|
|
151
155
|
const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL);
|
|
152
|
-
const organizationId = resolveOrganizationId(cliConfig);
|
|
153
156
|
devDebug('Writing workbench runtime files');
|
|
154
157
|
const root = await writeWorkbenchRuntime({
|
|
155
158
|
cwd: workDir,
|
|
@@ -226,7 +229,7 @@ async function createWorkbenchViteServer(options) {
|
|
|
226
229
|
fetch(remoteUrl).then((r)=>r.body?.cancel()).catch(()=>{});
|
|
227
230
|
devDebug('Warming workbench remote at %s', remoteUrl);
|
|
228
231
|
}
|
|
229
|
-
const detachBridge = attachViteDevServerBridge(server);
|
|
232
|
+
const detachBridge = attachViteDevServerBridge(server, organizationId);
|
|
230
233
|
return {
|
|
231
234
|
actualPort,
|
|
232
235
|
close: async ()=>{
|
|
@@ -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 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 `Dashboard 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 'The Dashboard 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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AAUO,GAAG,CAACrC,cAAc;IACrC;IAEA,MAAM,IAAI4E,MACR;AAEJ;AAEA,4EAA4E;AAC5E,0CAA0C;AAC1C,MAAMa,kBAAkBrH,EAAEe,GAAG,CAAC;IAACuG,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"}
|
|
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, organizationId?: string): () => void {\n const ownServers = (servers: DevServerManifest[]) =>\n organizationId ? servers.filter((entry) => entry.organizationId === organizationId) : servers\n\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(ownServers(getRegisteredServers())),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((allServers) => {\n const servers = ownServers(allServers)\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 const organizationId = resolveOrganizationId(cliConfig)\n\n // Acquire an exclusive lock — only one workbench per organization.\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({\n host: httpHost || 'localhost',\n organizationId,\n port: workbenchPort,\n })\n if (!workbenchLock) {\n const existing = await waitForWorkbenchLock(organizationId)\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 httpHost,\n organizationId,\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 httpHost: string | undefined\n organizationId: string\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, httpHost, organizationId, output, reactStrictMode, workbenchPort, workDir} =\n options\n\n const remoteUrl = parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\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 `Dashboard 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, organizationId)\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 'The Dashboard 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","ownServers","entry","ws","on","_","client","send","setTracker","registryWatcher","allServers","hasChanged","close","startWorkbenchRemoteCoordinator","options","detachBridge","startWorkbenchDevServer","cacheDir","cliConfig","httpHost","httpPort","workbenchPort","output","reactStrictMode","workDir","app","workbenchAvailable","resolveOrganizationId","workbenchLock","existing","pid","result","createWorkbenchViteServer","err","release","actualPort","updatePort","remoteUrl","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","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;AACtB,SAAQC,eAAe,QAAO,uBAAsB;AACpD,SAAQC,qBAAqB,QAAO,6BAA4B;AAEhE,MAAMC,WAAWf,SAAS;AAC1B,MAAMgB,uBAAuB;AAC7B,MAAMC,sBAAsBlB,cAC1B,IAAImB,IAAI,sCAAsC,YAAYC,GAAG;AAG/D,MAAMC,OAAO,WAAa;AAE1B,kEAAkE;AAClE,qFAAqF;AACrF,MAAMC,wBAAwB,CAACC,UAAkC,CAAA;QA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,SAAS8C,gBAAgBI,SAAS,CAACD;IAEzC,IAAI,CAACjD,OAAOmD,OAAO,EAAE;QACnB,MAAM,IAAIlB,MACR,CAAC,8CAA8C,EAAEgB,MAAM,yBAAyB,CAAC;IAErF;IAEA,OAAOjD,OAAOoD,IAAI;AACpB;AAEA;;;;;;CAMC,GACD,SAAS5B,kCAAkClB,SAAiB;IAC1D,OAAO;QACL+C,OAAO;QACPC,iBAAgB3G,MAAM;YACpBA,OAAO4G,WAAW,CAACC,GAAG,CAAC,CAACC,KAAKC,KAAKC;gBAChC,MAAMC,WAAW,AAACH,CAAAA,IAAIpH,GAAG,IAAI,GAAE,EAAGwH,KAAK,CAAC,IAAI,CAAC,EAAE;gBAC/C,IAAID,aAAa,OAAOA,aAAa,eAAe;oBAClDF,IAAII,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAExD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAqD;YACF;QACF;QACA1G,MAAM;IACR;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { subdebug } from '@sanity/cli-core';
|
|
2
2
|
import { preview } from 'vite';
|
|
3
|
-
import {
|
|
3
|
+
import { readBuiltManifest } from '../build/readBuiltManifest.js';
|
|
4
4
|
const previewDebug = subdebug('preview');
|
|
5
5
|
/**
|
|
6
6
|
* Serve a built workbench app's `dist` as static files over a Vite `preview`
|
|
@@ -8,11 +8,11 @@ const previewDebug = subdebug('preview');
|
|
|
8
8
|
* a live `sanity dev` remote would be — the workbench then federates it in.
|
|
9
9
|
*
|
|
10
10
|
* A missing federation build surfaces as `BUILD_NOT_FOUND` (from
|
|
11
|
-
* `
|
|
11
|
+
* `readBuiltManifest`) so the command shows the same "run sanity build" hint the
|
|
12
12
|
* studio preview path does; real I/O errors surface as themselves.
|
|
13
13
|
*/ export async function serveBuiltApplication(options) {
|
|
14
14
|
const { cacheDir, httpHost, httpPort, outDir, workDir } = options;
|
|
15
|
-
await
|
|
15
|
+
await readBuiltManifest(outDir);
|
|
16
16
|
const config = {
|
|
17
17
|
// Serve at the root so `mf-manifest.json` and its `publicPath: 'auto'` chunks
|
|
18
18
|
// resolve under the registered remote URL.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/preview/serveBuiltApplication.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\nimport {type InlineConfig, preview} from 'vite'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/preview/serveBuiltApplication.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\nimport {type InlineConfig, preview} from 'vite'\n\nimport {readBuiltManifest} from '../build/readBuiltManifest.js'\n\nconst previewDebug = subdebug('preview')\n\nexport interface BuiltApplicationServer {\n close: () => Promise<void>\n /** Routable host the remote is reachable at, for the registry's remote URL. */\n host: string\n /** Port Vite bound — may differ from the requested one under non-strict ports. */\n port: number\n}\n\n/**\n * Serve a built workbench app's `dist` as static files over a Vite `preview`\n * server, so its manifest and referenced assets are reachable exactly as\n * a live `sanity dev` remote would be — the workbench then federates it in.\n *\n * A missing federation build surfaces as `BUILD_NOT_FOUND` (from\n * `readBuiltManifest`) so the command shows the same \"run sanity build\" hint the\n * studio preview path does; real I/O errors surface as themselves.\n */\nexport async function serveBuiltApplication(options: {\n cacheDir: string\n httpHost: string\n httpPort: number\n outDir: string\n workDir: string\n}): Promise<BuiltApplicationServer> {\n const {cacheDir, httpHost, httpPort, outDir, workDir} = options\n\n await readBuiltManifest(outDir)\n\n const config: InlineConfig = {\n // Serve at the root so `mf-manifest.json` and its `publicPath: 'auto'` chunks\n // resolve under the registered remote URL.\n base: '/',\n // Needed for vite to serve `outDir` itself rather than `outDir/dist`.\n build: {outDir},\n cacheDir,\n configFile: false,\n logLevel: 'warn',\n mode: 'production',\n preview: {host: httpHost, port: httpPort, strictPort: false},\n root: workDir,\n }\n\n previewDebug('Serving built remote from %s', outDir)\n const server = await preview(config)\n\n const addr = server.httpServer.address()\n const port = typeof addr === 'object' && addr ? addr.port : httpPort\n\n return {\n // Drop idle keep-alive sockets so shutdown doesn't stall on a browser that\n // kept the connection open — otherwise `close` waits out the teardown grace.\n // `closeAllConnections` isn't on Vite's `HttpServer` type, but is on the\n // underlying node server (18.2+); the optional call tolerates its absence.\n close: () =>\n new Promise((resolve, reject) => {\n server.httpServer.close((err) => (err ? reject(err) : resolve()))\n ;(server.httpServer as {closeAllConnections?: () => void}).closeAllConnections?.()\n }),\n host: httpHost,\n port,\n }\n}\n"],"names":["subdebug","preview","readBuiltManifest","previewDebug","serveBuiltApplication","options","cacheDir","httpHost","httpPort","outDir","workDir","config","base","build","configFile","logLevel","mode","host","port","strictPort","root","server","addr","httpServer","address","close","Promise","resolve","reject","err","closeAllConnections"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,SAA2BC,OAAO,QAAO,OAAM;AAE/C,SAAQC,iBAAiB,QAAO,gCAA+B;AAE/D,MAAMC,eAAeH,SAAS;AAU9B;;;;;;;;CAQC,GACD,OAAO,eAAeI,sBAAsBC,OAM3C;IACC,MAAM,EAACC,QAAQ,EAAEC,QAAQ,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,OAAO,EAAC,GAAGL;IAExD,MAAMH,kBAAkBO;IAExB,MAAME,SAAuB;QAC3B,8EAA8E;QAC9E,2CAA2C;QAC3CC,MAAM;QACN,sEAAsE;QACtEC,OAAO;YAACJ;QAAM;QACdH;QACAQ,YAAY;QACZC,UAAU;QACVC,MAAM;QACNf,SAAS;YAACgB,MAAMV;YAAUW,MAAMV;YAAUW,YAAY;QAAK;QAC3DC,MAAMV;IACR;IAEAP,aAAa,gCAAgCM;IAC7C,MAAMY,SAAS,MAAMpB,QAAQU;IAE7B,MAAMW,OAAOD,OAAOE,UAAU,CAACC,OAAO;IACtC,MAAMN,OAAO,OAAOI,SAAS,YAAYA,OAAOA,KAAKJ,IAAI,GAAGV;IAE5D,OAAO;QACL,2EAA2E;QAC3E,6EAA6E;QAC7E,yEAAyE;QACzE,2EAA2E;QAC3EiB,OAAO,IACL,IAAIC,QAAQ,CAACC,SAASC;gBACpBP,OAAOE,UAAU,CAACE,KAAK,CAAC,CAACI,MAASA,MAAMD,OAAOC,OAAOF;gBACpDN,OAAOE,UAAU,CAAwCO,mBAAmB;YAChF;QACFb,MAAMV;QACNW;IACF;AACF"}
|
|
@@ -8,7 +8,7 @@ export function getWorkbenchUrl(organizationId) {
|
|
|
8
8
|
}
|
|
9
9
|
/** Where a deployed application is served on its organization's workbench. */ export function getApplicationUrl(application) {
|
|
10
10
|
const segment = application.type === 'studio' ? 'studios' : 'applications';
|
|
11
|
-
return `${getWorkbenchUrl(application.organizationId)}/${segment}/${application.id}`;
|
|
11
|
+
return `${getWorkbenchUrl(application.organizationId)}/${segment}/${application.slug ?? application.id}`;
|
|
12
12
|
}
|
|
13
13
|
async function getClient() {
|
|
14
14
|
return getGlobalCliClient({
|
|
@@ -89,7 +89,7 @@ export async function updateApplication(applicationId, update) {
|
|
|
89
89
|
}
|
|
90
90
|
/**
|
|
91
91
|
* Deploy a new active version to an existing application. `mfManifest` is the
|
|
92
|
-
* build's
|
|
92
|
+
* build's federation manifest; `tarball` is omitted for an external application,
|
|
93
93
|
* whose build the customer serves themselves.
|
|
94
94
|
*/ export async function createDeployment(options) {
|
|
95
95
|
const { access, applicationId, interfaces, isAutoUpdating, mfManifest, tarball, version, workspaces } = options;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/applications.ts"],"sourcesContent":["import {PassThrough} from 'node:stream'\nimport {type Gzip} from 'node:zlib'\n\nimport {type AppVisibility, getGlobalCliClient} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport FormData from 'form-data'\n\nimport {type TileInterfaceMetadata, type ViewPlacementMetadata} from '../contract.js'\nimport {APP_WORKBENCH_API_VERSION} from './apiVersion.js'\n\nexport type ApplicationType = 'coreApp' | 'studio'\n\nexport interface Application {\n id: string\n organizationId: string\n slug: string | null\n title: string\n type: ApplicationType\n\n /** Set when the customer serves the build; such an application never receives a tarball. */\n externalUrl?: string\n}\n\ninterface BrettInterfaceBase {\n moduleId: string\n name: string\n title: string\n version: string\n}\n\n/**\n * An interface as Brett stores it, discriminated on `type`. `moduleId` is\n * remote-relative — the host prepends the app's id. Brett assigns the id.\n * @internal\n */\nexport type BrettInterface =\n | (BrettInterfaceBase & {metadata: null; type: 'asset_source'})\n | (BrettInterfaceBase & {metadata: null; type: 'worker'})\n | (BrettInterfaceBase & {metadata: TileInterfaceMetadata; type: 'tile'})\n | (BrettInterfaceBase & {metadata: ViewPlacementMetadata | null; type: 'app'})\n | (BrettInterfaceBase & {metadata: ViewPlacementMetadata | null; type: 'panel'})\n\n/**\n * A resource a deployment may interact with, as Brett stores it. Per-deployment\n * and forbidden for singletons (the server 400s).\n */\nexport interface BrettAccess {\n resourceId: string\n resourceType: 'canvas' | 'dashboard' | 'dataset' | 'media-library'\n}\n\n/** A studio workspace as Brett stores it. */\nexport interface BrettWorkspace {\n dataset: string\n projectId: string\n /** Lexicon schema descriptor id; Brett requires one per workspace. */\n schemaDescriptorId: string\n\n basePath?: string\n icon?: string\n name?: string\n subtitle?: string\n title?: string\n}\n\nexport function getWorkbenchUrl(organizationId: string): string {\n return `https://${organizationId}.${isStaging() ? 'run.sanity.work' : 'sanity.run'}`\n}\n\n/** Where a deployed application is served on its organization's workbench. */\nexport function getApplicationUrl(\n application: Pick<Application, 'id' | 'organizationId' | 'type'>,\n): string {\n const segment = application.type === 'studio' ? 'studios' : 'applications'\n return `${getWorkbenchUrl(application.organizationId)}/${segment}/${application.id}`\n}\n\nasync function getClient() {\n return getGlobalCliClient({apiVersion: APP_WORKBENCH_API_VERSION, requireUser: true})\n}\n\nexport async function getApplication(applicationId: string): Promise<Application | null> {\n const client = await getClient()\n try {\n return await client.request({url: `/applications/${applicationId}`})\n } catch (err) {\n if ((err as {statusCode?: number})?.statusCode === 404) return null\n throw err\n }\n}\n\n/** Every application in an organization, in one page (`limit=none`). */\nexport async function listApplications(organizationId: string): Promise<Application[]> {\n const client = await getClient()\n const {data}: {data: Application[]} = await client.request({\n query: {limit: 'none', organizationId},\n url: '/applications',\n })\n return data\n}\n\n/**\n * Create an application record (no deployment), so the CLI can build with the\n * returned id, then ship it via {@link createDeployment}.\n */\nexport async function createApplication(options: {\n /** The origin a customer serves the build from; Brett then never hosts a bundle for it. */\n externalUrl?: string\n isSingleton?: boolean\n name?: string\n organizationId: string\n projectId?: string\n slug: string\n title: string\n type: ApplicationType\n visibility?: AppVisibility\n}): Promise<Application> {\n const {externalUrl, isSingleton, name, organizationId, projectId, slug, title, type, visibility} =\n options\n const client = await getClient()\n return client.request({\n body: {\n organizationId,\n slug,\n title,\n type,\n // Identity, distinct from the slug address. Omitted → Brett defaults it to slug.\n ...(name ? {name} : {}),\n // Brett requires `isSingleton` on `POST /applications`, so the request\n // builder keeps forwarding it even though the CLI itself never sets it.\n ...(isSingleton === undefined ? {} : {isSingleton}),\n ...(visibility ? {visibility} : {}),\n ...(externalUrl ? {externalUrl} : {}),\n // Studio config is set once, at create — it's immutable on redeploy.\n ...(projectId ? {config: {studio: {projectId}}} : {}),\n },\n method: 'POST',\n url: `/applications`,\n })\n}\n\n/** Mutable application fields the deploy flow patches after create. */\nexport interface ApplicationUpdate {\n icon?: string | null\n /** The address the application is served at; renaming moves it. */\n slug?: string\n title?: string\n visibility?: AppVisibility\n}\n\n// Patch an application's mutable fields.\nexport async function updateApplication(\n applicationId: string,\n update: ApplicationUpdate,\n): Promise<void> {\n const client = await getClient()\n await client.request({body: update, method: 'PATCH', url: `/applications/${applicationId}`})\n}\n\n/**\n * Deploy a new active version to an existing application. `mfManifest` is the\n * build's `mf-manifest.json`; `tarball` is omitted for an external application,\n * whose build the customer serves themselves.\n */\nexport async function createDeployment(options: {\n access?: readonly BrettAccess[]\n applicationId: string\n interfaces: readonly BrettInterface[]\n isAutoUpdating: boolean\n mfManifest: unknown\n tarball?: Gzip\n version: string\n workspaces?: readonly BrettWorkspace[]\n}): Promise<{id: string}> {\n const {\n access,\n applicationId,\n interfaces,\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n } = options\n const formData = new FormData()\n formData.append('isAutoUpdating', isAutoUpdating.toString())\n appendDeploymentParts(formData, {access, interfaces, mfManifest, tarball, version, workspaces})\n return request(`/applications/${applicationId}/deployments`, formData)\n}\n\n/** Soft-deletes the application and all its deployments; already deleted counts as done. */\nexport async function deleteApplication(applicationId: string): Promise<void> {\n const client = await getClient()\n try {\n await client.request({method: 'DELETE', url: `/applications/${applicationId}`})\n } catch (err) {\n if ((err as {statusCode?: number})?.statusCode !== 404) throw err\n }\n}\n\nfunction appendDeploymentParts(\n formData: FormData,\n {\n access,\n interfaces,\n mfManifest,\n tarball,\n version,\n workspaces,\n }: {\n access?: readonly BrettAccess[]\n interfaces: readonly BrettInterface[]\n mfManifest: unknown\n tarball?: Gzip\n version: string\n workspaces?: readonly BrettWorkspace[]\n },\n): void {\n formData.append('version', version)\n appendJson(formData, 'interfaces', interfaces)\n // Studio-only — the server rejects a workspaces part on non-studio types.\n if (workspaces?.length) appendJson(formData, 'workspaces', workspaces)\n // Per-deployment; forbidden for singletons, so callers omit it there.\n if (access?.length) appendJson(formData, 'access', access)\n appendJson(formData, 'mfManifest', mfManifest)\n // Last: the server requires every field part to precede the tarball.\n if (tarball) {\n formData.append('tarball', tarball, {contentType: 'application/gzip', filename: 'app.tar.gz'})\n }\n}\n\n/** Structured parts must arrive as JSON so the server parses them. */\nfunction appendJson(formData: FormData, name: string, value: unknown): void {\n formData.append(name, JSON.stringify(value), {contentType: 'application/json'})\n}\n\nasync function request<T>(url: string, formData: FormData): Promise<T> {\n const client = await getClient()\n return client.request({\n body: formData.pipe(new PassThrough()),\n headers: formData.getHeaders(),\n method: 'POST',\n url,\n })\n}\n"],"names":["PassThrough","getGlobalCliClient","isStaging","FormData","APP_WORKBENCH_API_VERSION","getWorkbenchUrl","organizationId","getApplicationUrl","application","segment","type","id","getClient","apiVersion","requireUser","getApplication","applicationId","client","request","url","err","statusCode","listApplications","data","query","limit","createApplication","options","externalUrl","isSingleton","name","projectId","slug","title","visibility","body","undefined","config","studio","method","updateApplication","update","createDeployment","access","interfaces","isAutoUpdating","mfManifest","tarball","version","workspaces","formData","append","toString","appendDeploymentParts","deleteApplication","appendJson","length","contentType","filename","value","JSON","stringify","pipe","headers","getHeaders"],"mappings":"AAAA,SAAQA,WAAW,QAAO,cAAa;AAGvC,SAA4BC,kBAAkB,QAAO,mBAAkB;AACvE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,cAAc,YAAW;AAGhC,SAAQC,yBAAyB,QAAO,kBAAiB;AAyDzD,OAAO,SAASC,gBAAgBC,cAAsB;IACpD,OAAO,CAAC,QAAQ,EAAEA,eAAe,CAAC,EAAEJ,cAAc,oBAAoB,cAAc;AACtF;AAEA,4EAA4E,GAC5E,OAAO,SAASK,kBACdC,WAAgE;IAEhE,MAAMC,UAAUD,YAAYE,IAAI,KAAK,WAAW,YAAY;IAC5D,OAAO,GAAGL,gBAAgBG,YAAYF,cAAc,EAAE,CAAC,EAAEG,QAAQ,CAAC,EAAED,YAAYG,EAAE,EAAE;AACtF;AAEA,eAAeC;IACb,OAAOX,mBAAmB;QAACY,YAAYT;QAA2BU,aAAa;IAAI;AACrF;AAEA,OAAO,eAAeC,eAAeC,aAAqB;IACxD,MAAMC,SAAS,MAAML;IACrB,IAAI;QACF,OAAO,MAAMK,OAAOC,OAAO,CAAC;YAACC,KAAK,CAAC,cAAc,EAAEH,eAAe;QAAA;IACpE,EAAE,OAAOI,KAAK;QACZ,IAAI,AAACA,KAA+BC,eAAe,KAAK,OAAO;QAC/D,MAAMD;IACR;AACF;AAEA,sEAAsE,GACtE,OAAO,eAAeE,iBAAiBhB,cAAsB;IAC3D,MAAMW,SAAS,MAAML;IACrB,MAAM,EAACW,IAAI,EAAC,GAA0B,MAAMN,OAAOC,OAAO,CAAC;QACzDM,OAAO;YAACC,OAAO;YAAQnB;QAA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../src/services/applications.ts"],"sourcesContent":["import {PassThrough} from 'node:stream'\nimport {type Gzip} from 'node:zlib'\n\nimport {type AppVisibility, getGlobalCliClient} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport FormData from 'form-data'\n\nimport {type TileInterfaceMetadata, type ViewPlacementMetadata} from '../contract.js'\nimport {APP_WORKBENCH_API_VERSION} from './apiVersion.js'\n\nexport type ApplicationType = 'coreApp' | 'studio'\n\nexport interface Application {\n id: string\n organizationId: string\n slug: string | null\n title: string\n type: ApplicationType\n\n /** Set when the customer serves the build; such an application never receives a tarball. */\n externalUrl?: string\n}\n\ninterface BrettInterfaceBase {\n moduleId: string\n name: string\n title: string\n version: string\n}\n\n/**\n * An interface as Brett stores it, discriminated on `type`. `moduleId` is\n * remote-relative — the host prepends the app's id. Brett assigns the id.\n * @internal\n */\nexport type BrettInterface =\n | (BrettInterfaceBase & {metadata: null; type: 'asset_source'})\n | (BrettInterfaceBase & {metadata: null; type: 'worker'})\n | (BrettInterfaceBase & {metadata: TileInterfaceMetadata; type: 'tile'})\n | (BrettInterfaceBase & {metadata: ViewPlacementMetadata | null; type: 'app'})\n | (BrettInterfaceBase & {metadata: ViewPlacementMetadata | null; type: 'panel'})\n\n/**\n * A resource a deployment may interact with, as Brett stores it. Per-deployment\n * and forbidden for singletons (the server 400s).\n */\nexport interface BrettAccess {\n resourceId: string\n resourceType: 'canvas' | 'dashboard' | 'dataset' | 'media-library'\n}\n\n/** A studio workspace as Brett stores it. */\nexport interface BrettWorkspace {\n dataset: string\n projectId: string\n /** Lexicon schema descriptor id; Brett requires one per workspace. */\n schemaDescriptorId: string\n\n basePath?: string\n icon?: string\n name?: string\n subtitle?: string\n title?: string\n}\n\nexport function getWorkbenchUrl(organizationId: string): string {\n return `https://${organizationId}.${isStaging() ? 'run.sanity.work' : 'sanity.run'}`\n}\n\n/** Where a deployed application is served on its organization's workbench. */\nexport function getApplicationUrl(\n application: Pick<Application, 'id' | 'organizationId' | 'slug' | 'type'>,\n): string {\n const segment = application.type === 'studio' ? 'studios' : 'applications'\n return `${getWorkbenchUrl(application.organizationId)}/${segment}/${application.slug ?? application.id}`\n}\n\nasync function getClient() {\n return getGlobalCliClient({apiVersion: APP_WORKBENCH_API_VERSION, requireUser: true})\n}\n\nexport async function getApplication(applicationId: string): Promise<Application | null> {\n const client = await getClient()\n try {\n return await client.request({url: `/applications/${applicationId}`})\n } catch (err) {\n if ((err as {statusCode?: number})?.statusCode === 404) return null\n throw err\n }\n}\n\n/** Every application in an organization, in one page (`limit=none`). */\nexport async function listApplications(organizationId: string): Promise<Application[]> {\n const client = await getClient()\n const {data}: {data: Application[]} = await client.request({\n query: {limit: 'none', organizationId},\n url: '/applications',\n })\n return data\n}\n\n/**\n * Create an application record (no deployment), so the CLI can build with the\n * returned id, then ship it via {@link createDeployment}.\n */\nexport async function createApplication(options: {\n /** The origin a customer serves the build from; Brett then never hosts a bundle for it. */\n externalUrl?: string\n isSingleton?: boolean\n name?: string\n organizationId: string\n projectId?: string\n slug: string\n title: string\n type: ApplicationType\n visibility?: AppVisibility\n}): Promise<Application> {\n const {externalUrl, isSingleton, name, organizationId, projectId, slug, title, type, visibility} =\n options\n const client = await getClient()\n return client.request({\n body: {\n organizationId,\n slug,\n title,\n type,\n // Identity, distinct from the slug address. Omitted → Brett defaults it to slug.\n ...(name ? {name} : {}),\n // Brett requires `isSingleton` on `POST /applications`, so the request\n // builder keeps forwarding it even though the CLI itself never sets it.\n ...(isSingleton === undefined ? {} : {isSingleton}),\n ...(visibility ? {visibility} : {}),\n ...(externalUrl ? {externalUrl} : {}),\n // Studio config is set once, at create — it's immutable on redeploy.\n ...(projectId ? {config: {studio: {projectId}}} : {}),\n },\n method: 'POST',\n url: `/applications`,\n })\n}\n\n/** Mutable application fields the deploy flow patches after create. */\nexport interface ApplicationUpdate {\n icon?: string | null\n /** The address the application is served at; renaming moves it. */\n slug?: string\n title?: string\n visibility?: AppVisibility\n}\n\n// Patch an application's mutable fields.\nexport async function updateApplication(\n applicationId: string,\n update: ApplicationUpdate,\n): Promise<void> {\n const client = await getClient()\n await client.request({body: update, method: 'PATCH', url: `/applications/${applicationId}`})\n}\n\n/**\n * Deploy a new active version to an existing application. `mfManifest` is the\n * build's federation manifest; `tarball` is omitted for an external application,\n * whose build the customer serves themselves.\n */\nexport async function createDeployment(options: {\n access?: readonly BrettAccess[]\n applicationId: string\n interfaces: readonly BrettInterface[]\n isAutoUpdating: boolean\n mfManifest: Record<string, unknown>\n tarball?: Gzip\n version: string\n workspaces?: readonly BrettWorkspace[]\n}): Promise<{id: string}> {\n const {\n access,\n applicationId,\n interfaces,\n isAutoUpdating,\n mfManifest,\n tarball,\n version,\n workspaces,\n } = options\n const formData = new FormData()\n formData.append('isAutoUpdating', isAutoUpdating.toString())\n appendDeploymentParts(formData, {access, interfaces, mfManifest, tarball, version, workspaces})\n return request(`/applications/${applicationId}/deployments`, formData)\n}\n\n/** Soft-deletes the application and all its deployments; already deleted counts as done. */\nexport async function deleteApplication(applicationId: string): Promise<void> {\n const client = await getClient()\n try {\n await client.request({method: 'DELETE', url: `/applications/${applicationId}`})\n } catch (err) {\n if ((err as {statusCode?: number})?.statusCode !== 404) throw err\n }\n}\n\nfunction appendDeploymentParts(\n formData: FormData,\n {\n access,\n interfaces,\n mfManifest,\n tarball,\n version,\n workspaces,\n }: {\n access?: readonly BrettAccess[]\n interfaces: readonly BrettInterface[]\n mfManifest: Record<string, unknown>\n tarball?: Gzip\n version: string\n workspaces?: readonly BrettWorkspace[]\n },\n): void {\n formData.append('version', version)\n appendJson(formData, 'interfaces', interfaces)\n // Studio-only — the server rejects a workspaces part on non-studio types.\n if (workspaces?.length) appendJson(formData, 'workspaces', workspaces)\n // Per-deployment; forbidden for singletons, so callers omit it there.\n if (access?.length) appendJson(formData, 'access', access)\n appendJson(formData, 'mfManifest', mfManifest)\n // Last: the server requires every field part to precede the tarball.\n if (tarball) {\n formData.append('tarball', tarball, {contentType: 'application/gzip', filename: 'app.tar.gz'})\n }\n}\n\n/** Structured parts must arrive as JSON so the server parses them. */\nfunction appendJson(formData: FormData, name: string, value: unknown): void {\n formData.append(name, JSON.stringify(value), {contentType: 'application/json'})\n}\n\nasync function request<T>(url: string, formData: FormData): Promise<T> {\n const client = await getClient()\n return client.request({\n body: formData.pipe(new PassThrough()),\n headers: formData.getHeaders(),\n method: 'POST',\n url,\n })\n}\n"],"names":["PassThrough","getGlobalCliClient","isStaging","FormData","APP_WORKBENCH_API_VERSION","getWorkbenchUrl","organizationId","getApplicationUrl","application","segment","type","slug","id","getClient","apiVersion","requireUser","getApplication","applicationId","client","request","url","err","statusCode","listApplications","data","query","limit","createApplication","options","externalUrl","isSingleton","name","projectId","title","visibility","body","undefined","config","studio","method","updateApplication","update","createDeployment","access","interfaces","isAutoUpdating","mfManifest","tarball","version","workspaces","formData","append","toString","appendDeploymentParts","deleteApplication","appendJson","length","contentType","filename","value","JSON","stringify","pipe","headers","getHeaders"],"mappings":"AAAA,SAAQA,WAAW,QAAO,cAAa;AAGvC,SAA4BC,kBAAkB,QAAO,mBAAkB;AACvE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,cAAc,YAAW;AAGhC,SAAQC,yBAAyB,QAAO,kBAAiB;AAyDzD,OAAO,SAASC,gBAAgBC,cAAsB;IACpD,OAAO,CAAC,QAAQ,EAAEA,eAAe,CAAC,EAAEJ,cAAc,oBAAoB,cAAc;AACtF;AAEA,4EAA4E,GAC5E,OAAO,SAASK,kBACdC,WAAyE;IAEzE,MAAMC,UAAUD,YAAYE,IAAI,KAAK,WAAW,YAAY;IAC5D,OAAO,GAAGL,gBAAgBG,YAAYF,cAAc,EAAE,CAAC,EAAEG,QAAQ,CAAC,EAAED,YAAYG,IAAI,IAAIH,YAAYI,EAAE,EAAE;AAC1G;AAEA,eAAeC;IACb,OAAOZ,mBAAmB;QAACa,YAAYV;QAA2BW,aAAa;IAAI;AACrF;AAEA,OAAO,eAAeC,eAAeC,aAAqB;IACxD,MAA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EAAoE,GACpE,SAASH,WAAWL,QAAkB,EAAEnB,IAAY,EAAE4B,KAAc;IAClET,SAASC,MAAM,CAACpB,MAAM6B,KAAKC,SAAS,CAACF,QAAQ;QAACF,aAAa;IAAkB;AAC/E;AAEA,eAAetC,QAAWC,GAAW,EAAE8B,QAAkB;IACvD,MAAMhC,SAAS,MAAML;IACrB,OAAOK,OAAOC,OAAO,CAAC;QACpBgB,MAAMe,SAASY,IAAI,CAAC,IAAI9D;QACxB+D,SAASb,SAASc,UAAU;QAC5BzB,QAAQ;QACRnB;IACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/workbench-cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.12.0",
|
|
4
4
|
"description": "Internal implementation detail of the Sanity CLI's unstable workbench support. Not intended for direct use.",
|
|
5
5
|
"homepage": "https://github.com/sanity-io/cli",
|
|
6
6
|
"bugs": "https://github.com/sanity-io/cli/issues",
|
|
@@ -62,8 +62,8 @@
|
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"@module-federation/runtime": "2.9.2",
|
|
65
|
-
"@module-federation/vite": "1.23.
|
|
66
|
-
"@sanity/cli-core": "^3.
|
|
65
|
+
"@module-federation/vite": "1.23.5",
|
|
66
|
+
"@sanity/cli-core": "^3.11.0",
|
|
67
67
|
"@sanity/sdk": "^3.8.0",
|
|
68
68
|
"@sanity/types": "^6.17.0",
|
|
69
69
|
"@vitejs/plugin-react": "^6.1.2",
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
"@eslint/compat": "^2.1.0",
|
|
79
79
|
"@repo/package.config": "0.0.1",
|
|
80
80
|
"@repo/tsconfig": "3.70.0",
|
|
81
|
-
"@sanity/cli-test": "
|
|
81
|
+
"@sanity/cli-test": "21.0.0",
|
|
82
82
|
"@sanity/eslint-config-cli": "^1.1.3",
|
|
83
83
|
"@sanity/pkg-utils": "^12.3.4",
|
|
84
84
|
"@swc/cli": "^0.8.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/deploy/checkBuiltOutput.ts"],"sourcesContent":["import {readFile, stat} from 'node:fs/promises'\nimport {join} from 'node:path'\n\n/**\n * A genuinely-missing-build error, named so callers can offer the \"run sanity\n * build\" hint (the `preview` command keys off this name, matching how the studio\n * path keys off a missing `index.html`). Only the missing cases get it — real\n * I/O failures keep their own name so they surface as themselves.\n */\nfunction buildNotFound(message: string): Error {\n const error = new Error(message)\n error.name = 'BUILD_NOT_FOUND'\n return error\n}\n\n/**\n * Throws unless `sourceDir` is a directory holding a federation build.\n * A workbench build always emits a module-federation remote, and may\n * additionally emit a standalone `index.html` SPA (workbench remotes). Either\n * way `mf-manifest.json` is the reliable marker that `sanity build` produced a\n * federation build, so that — not `index.html` — is what we check for.\n */\nexport async function checkBuiltOutput(sourceDir: string): Promise<void> {\n try {\n const stats = await stat(sourceDir)\n if (!stats.isDirectory()) {\n throw new Error(`\"${sourceDir}\" is not a directory`)\n }\n } catch (err) {\n if (err.code === 'ENOENT') throw buildNotFound(`Directory \"${sourceDir}\" does not exist`)\n throw err\n }\n\n const manifestPath = join(sourceDir, 'mf-manifest.json')\n let manifest: string\n try {\n manifest = await readFile(manifestPath, 'utf8')\n } catch (err) {\n if (err.code === 'ENOENT') {\n throw buildNotFound(\n `\"${manifestPath}\" does not exist. ` +\n 'The deploy directory must contain a federation build created with \"sanity build\".',\n )\n }\n throw err\n }\n\n // Every deploy sends this file to the API, so a corrupt one must fail here\n // rather than after the application is created.\n try {\n JSON.parse(manifest)\n } catch {\n throw new Error(\n `\"${manifestPath}\" is not valid JSON. Run \"sanity build\" again to regenerate it.`,\n )\n }\n}\n"],"names":["readFile","stat","join","buildNotFound","message","error","Error","name","checkBuiltOutput","sourceDir","stats","isDirectory","err","code","manifestPath","manifest","JSON","parse"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,IAAI,QAAO,mBAAkB;AAC/C,SAAQC,IAAI,QAAO,YAAW;AAE9B;;;;;CAKC,GACD,SAASC,cAAcC,OAAe;IACpC,MAAMC,QAAQ,IAAIC,MAAMF;IACxBC,MAAME,IAAI,GAAG;IACb,OAAOF;AACT;AAEA;;;;;;CAMC,GACD,OAAO,eAAeG,iBAAiBC,SAAiB;IACtD,IAAI;QACF,MAAMC,QAAQ,MAAMT,KAAKQ;QACzB,IAAI,CAACC,MAAMC,WAAW,IAAI;YACxB,MAAM,IAAIL,MAAM,CAAC,CAAC,EAAEG,UAAU,oBAAoB,CAAC;QACrD;IACF,EAAE,OAAOG,KAAK;QACZ,IAAIA,IAAIC,IAAI,KAAK,UAAU,MAAMV,cAAc,CAAC,WAAW,EAAEM,UAAU,gBAAgB,CAAC;QACxF,MAAMG;IACR;IAEA,MAAME,eAAeZ,KAAKO,WAAW;IACrC,IAAIM;IACJ,IAAI;QACFA,WAAW,MAAMf,SAASc,cAAc;IAC1C,EAAE,OAAOF,KAAK;QACZ,IAAIA,IAAIC,IAAI,KAAK,UAAU;YACzB,MAAMV,cACJ,CAAC,CAAC,EAAEW,aAAa,kBAAkB,CAAC,GAClC;QAEN;QACA,MAAMF;IACR;IAEA,2EAA2E;IAC3E,gDAAgD;IAChD,IAAI;QACFI,KAAKC,KAAK,CAACF;IACb,EAAE,OAAM;QACN,MAAM,IAAIT,MACR,CAAC,CAAC,EAAEQ,aAAa,+DAA+D,CAAC;IAErF;AACF"}
|