@sanity/workbench-cli 2.18.0 → 2.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_exports/_internal_worker_bus.d.ts +2 -2
- package/dist/_exports/build.d.ts +1 -1
- package/dist/_exports/{defineApp-vbUu_rBA.d.ts → defineApp-9ppP3UQR.d.ts} +2 -2
- package/dist/_exports/deploy.d.ts +23 -7
- package/dist/_exports/deploy.js +1 -0
- package/dist/_exports/deploy.js.map +1 -1
- package/dist/_exports/dev.d.ts +3 -1
- package/dist/_exports/index.d.ts +68 -3
- package/dist/_exports/preview.d.ts +3 -1
- package/dist/_exports/{registry-CbruhmxE.d.ts → registry-DZWnj09G.d.ts} +2 -2
- package/dist/_exports/{resolveWorkbenchConfig-JRi01VJM.d.ts → resolveWorkbenchConfig-_iD6fVUH.d.ts} +2 -2
- package/dist/_exports/{summarizeInterfaces-CpCUSMrz.d.ts → summarizeInterfaces-AM-QbtIA.d.ts} +3 -3
- package/dist/_exports/undeploy.d.ts +2 -2
- package/dist/actions/build/autoUpdatesLoader.js +3 -1
- package/dist/actions/build/autoUpdatesLoader.js.map +1 -1
- package/dist/actions/build/webWorkers/workerBus.js.map +1 -1
- package/dist/actions/deploy/deployWorkbenchApp.js +21 -7
- package/dist/actions/deploy/deployWorkbenchApp.js.map +1 -1
- package/dist/actions/dev/deriveConfigs.js +1 -1
- package/dist/actions/dev/deriveConfigs.js.map +1 -1
- package/dist/actions/dev/startDevServerRegistration.js +16 -1
- package/dist/actions/dev/startDevServerRegistration.js.map +1 -1
- package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
- package/dist/actions/preview/serveBuiltApplication.js +12 -1
- package/dist/actions/preview/serveBuiltApplication.js.map +1 -1
- package/dist/actions/preview/startWorkbenchPreview.js +11 -0
- package/dist/actions/preview/startWorkbenchPreview.js.map +1 -1
- package/dist/appId.js +1 -1
- package/dist/appId.js.map +1 -1
- package/dist/defineApp.js +4 -3
- package/dist/defineApp.js.map +1 -1
- package/dist/readAppIcon.js +31 -0
- package/dist/readAppIcon.js.map +1 -0
- package/dist/services/applications.js +18 -0
- package/dist/services/applications.js.map +1 -1
- package/dist/webWorker.js.map +1 -1
- package/package.json +12 -13
- package/dist/_exports/webWorker-TWUbh0uo.d.ts +0 -123
|
@@ -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 {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 localAppIdentity,\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 https: Boolean(server.config.server.https),\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, https, 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 const applicationId = workbenchApp ? cliConfig.deployment?.appId : undefined\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them.\n const identity = workbenchApp ? localAppIdentity(workbenchApp) : undefined\n\n // The Dashboard tells local apps apart by their bus id and by the application\n // they stand in for.\n const organizationId = cliConfig.app?.organizationId\n const devServer = getRegisteredServers().find(\n (server) =>\n server.organizationId === organizationId &&\n (server.id === id || (applicationId && server.applicationId === applicationId)),\n )\n\n if (id && devServer) {\n const served =\n devServer.id === id\n ? `\"${id}\" is already served`\n : `\"${id}\" is the same application as \"${devServer.id}\", served`\n output.error(\n `${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 applicationId,\n configs,\n host: appHost,\n https,\n id,\n interfaces,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n ...identity,\n type: isApp ? 'coreApp' : 'studio',\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({\n id,\n interfaces,\n slug: identity?.slug,\n type: isApp ? 'coreApp' : 'studio',\n }),\n }\n}\n"],"names":["getCliConfigUncached","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","localAppIdentity","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","https","Boolean","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","applicationId","deployment","appId","identity","organizationId","devServer","find","served","error","exit","close","registration","projectId","api","type","exposesSet","watcher","extract","params","nextConfig","manifest","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAwBA,oBAAoB,QAAoB,mBAAkB;AAGlF,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,gBAAgB,EAChBC,iBAAiB,QACZ,gBAAe;AACtB,SAAQC,uBAAuB,QAAO,+BAA8B;AAqCpE;;;;;CAKC,GACD,SAASC,mBAAmBC,GAAqB,EAAEC,MAAc;IAC/D,IAAId,kBAAkBa,MAAM;IAC5B,MAAME,SAASX,qBAAqBS;IACpC,IAAIE,OAAOC,MAAM,KAAK,GAAG;IACzBF,OAAOG,IAAI,CAACd,yBAAyBY;AACvC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gB;QAC3E3B;QACAqD,QAAQ,OAAOC;YACb,IACE,CAACR,WAAWS,OAAO,CAAC;gBAClB9B,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B,IACA;gBACAkB,aAAaW,MAAM,CAACC;gBACpB;YACF;YACA,4EAA4E;YAC5E,6EAA6E;YAC7E,MAAME,gBAAgB,MAAMpC;YAC5B,6EAA6E;YAC7E0B,WAAWW,MAAM,CAAC;gBAChBhC,SAAS6B,MAAM7B,OAAO;gBACtBD,YAAY8B,MAAM9B,UAAU;YAC9B;YACA,qEAAqE;YACrEkB,aAAaW,MAAM,CAACG,gBAAgB;gBAAC,GAAGF,KAAK;gBAAE,GAAGlD,cAAcoD,cAAc;YAAA,IAAIF;QACpF;QACAjC;IACF;IAEA,OAAO;QACLoB,OAAO;YACLC,aAAagB,OAAO;YACpB,MAAMX,QAAQN,KAAK;QACrB;QACAkB,MAAMlE,cAAc;YAClBmC;YACAJ;YACAM,MAAMI,UAAUJ;YAChBe,MAAM1B,QAAQ,YAAY;QAC5B;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startDevServerRegistration.ts"],"sourcesContent":["import {relative} from 'node:path'\n\nimport {type CliConfig, getCliConfigUncached, type Output} from '@sanity/cli-core'\nimport {type ViteDevServer} from 'vite'\n\nimport {isWorkbenchApp, isWorkbenchConfig} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {readAppIcon, toUrlPath} from '../../readAppIcon.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 localAppIdentity,\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 /** Where this server serves the app's icon. */\n iconUrl?: 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 https: Boolean(server.config.server.https),\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, https, 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 const applicationId = workbenchApp ? cliConfig.deployment?.appId : undefined\n // Identity is resolved and the reference composed here, so the workbench reads\n // both off the registry entry instead of recomposing them.\n const identity = workbenchApp ? localAppIdentity(workbenchApp) : undefined\n\n // The Dashboard tells local apps apart by their bus id and by the application\n // they stand in for.\n const organizationId = cliConfig.app?.organizationId\n const devServer = getRegisteredServers().find(\n (server) =>\n server.organizationId === organizationId &&\n (server.id === id || (applicationId && server.applicationId === applicationId)),\n )\n\n if (id && devServer) {\n const served =\n devServer.id === id\n ? `\"${id}\" is already served`\n : `\"${id}\" is the same application as \"${devServer.id}\", served`\n output.error(\n `${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 applicationId,\n configs,\n host: appHost,\n https,\n id,\n interfaces,\n organizationId,\n port: appPort,\n projectId: cliConfig?.api?.projectId,\n ...identity,\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n\n const exposesSet = trackExposesSet({configs, interfaces})\n let liveServer = server\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\n let iconUrl: string | undefined\n if (isApp && isWorkbenchApp(nextConfig.app) && nextConfig.app.icon) {\n // Read in full so an image a deploy would reject warns here, while editing.\n const {file} = await readAppIcon(workDir, nextConfig.app.icon)\n // Vite serves `public/` at the root, and warns on every request for `/public/...`.\n const {base, publicDir, root} = liveServer.config\n const inPublicDir = Boolean(publicDir) && !relative(publicDir, file).startsWith('..')\n const {host, https, port} = serverAddress(liveServer)\n iconUrl = `${https ? 'https' : 'http'}://${host}:${port}${base}${toUrlPath(inPublicDir ? publicDir : root, file)}`\n }\n\n return {\n configs: await deriveConfigs(nextConfig),\n interfaces: deriveInterfaces(nextConfig.app, {isApp}),\n manifest: await extractManifest({...params, applicationId: id, iconUrl}),\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 if (rebuiltServer) liveServer = rebuiltServer\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({\n id,\n interfaces,\n slug: identity?.slug,\n type: isApp ? 'coreApp' : 'studio',\n }),\n }\n}\n"],"names":["relative","getCliConfigUncached","isWorkbenchApp","isWorkbenchConfig","deriveInterfaces","readAppIcon","toUrlPath","resolveWorkbenchConfig","formatWorkbenchAppErrors","validateWorkbenchApp","deriveConfigs","trackExposesSet","dashboardPath","getRegisteredServers","localAppIdentity","registerDevServer","startDevManifestWatcher","reportConfigErrors","app","output","errors","length","warn","serverAddress","server","resolvedHost","config","host","addr","httpServer","address","https","Boolean","port","startDevServerRegistration","options","cliConfig","extractManifest","isApp","onInterfaceSetChange","workDir","appHost","appPort","interfaces","configs","workbenchApp","undefined","id","appType","slug","applicationId","deployment","appId","identity","organizationId","devServer","find","served","error","exit","close","registration","projectId","api","type","exposesSet","liveServer","watcher","extract","params","nextConfig","iconUrl","icon","file","base","publicDir","root","inPublicDir","startsWith","manifest","extraWatchFilenames","update","patch","changed","rebuiltServer","commit","release","path"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,YAAW;AAElC,SAAwBC,oBAAoB,QAAoB,mBAAkB;AAGlF,SAAQC,cAAc,EAAEC,iBAAiB,QAAO,qBAAoB;AACpE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,WAAW,EAAEC,SAAS,QAAO,uBAAsB;AAC3D,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,gBAAgB,EAChBC,iBAAiB,QACZ,gBAAe;AACtB,SAAQC,uBAAuB,QAAO,+BAA8B;AAuCpE;;;;;CAKC,GACD,SAASC,mBAAmBC,GAAqB,EAAEC,MAAc;IAC/D,IAAIhB,kBAAkBe,MAAM;IAC5B,MAAME,SAASX,qBAAqBS;IACpC,IAAIE,OAAOC,MAAM,KAAK,GAAG;IACzBF,OAAOG,IAAI,CAACd,yBAAyBY;AACvC;AAEA,+HAA+H,GAC/H,SAASG,cAAcC,MAAqB;IAC1C,MAAMC,eAAeD,OAAOE,MAAM,CAACF,MAAM,CAACG,IAAI;IAC9C,MAAMC,OAAOJ,OAAOK,UAAU,EAAE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version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {isWorkbenchApp} from '../../defineApp.js'\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {formatSummary} from '../summary.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {bindDevShortcuts} from './bindDevShortcuts.js'\nimport {fetchDevSummaryDetails, waitForDevSummaryDetails} from './devSummary.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n cliConfig: CliConfig\n httpPort: number\n isRestarting?: boolean\n quiet?: boolean\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/web worker edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still bridges the registry.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const coordinator = startWorkbenchRemoteCoordinator({server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n const startedAt = Date.now()\n const app = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const organizationId = cliConfig.app?.organizationId\n const details = fetchDevSummaryDetails({\n idOrSlug: app && (cliConfig.deployment?.appId ?? app.slug),\n organizationId,\n })\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config, {isRestarting} = {}) =>\n startAppServer({\n cliConfig: config,\n httpPort: appPort,\n isRestarting,\n quiet: workbench.workbenchAvailable,\n }),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n let dashboardAppPath: string | undefined\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n dashboardAppPath = registration.path\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\n await close()\n throw err\n }\n\n const durationMs = Date.now() - startedAt\n const {deployment, organizationName} = workbench.workbenchAvailable\n ? await waitForDevSummaryDetails(details)\n : {}\n\n installSignalHandlers()\n\n if (workbench.workbenchAvailable) {\n const url = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}${dashboardAppPath ?? ''}`\n let version = ''\n\n if (deployment) {\n const date = new Date(deployment.createdAt).toLocaleDateString('en-US', {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n })\n const by = deployment.deployedBy ? ` by ${deployment.deployedBy}` : ''\n version = `local preview ${styleText('dim', `· deployed ${date}${by}`)}`\n } else if (deployment === null) {\n version = `local preview ${styleText('dim', '· not deployed')}`\n }\n\n output.log(\n formatSummary({\n durationMs,\n heading: 'Sanity Dashboard ready',\n isApp,\n organization: organizationName ?? organizationId,\n title: app?.title,\n url,\n version,\n }),\n )\n\n const quit = () => void close().then(() => process.exit(0))\n closers.push(bindDevShortcuts({output, quit, url}))\n }\n\n return {close}\n}\n"],"names":["styleText","isWorkbenchApp","createServerLifecycle","toDisplayHost","formatSummary","startAppServerSupervisor","bindDevShortcuts","fetchDevSummaryDetails","waitForDevSummaryDetails","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","started","close","coordinator","server","closers","installSignalHandlers","startedAt","Date","now","app","undefined","organizationId","details","idOrSlug","deployment","appId","slug","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","config","isRestarting","quiet","catch","err","supervisor","dashboardAppPath","registration","onInterfaceSetChange","rebuild","path","durationMs","organizationName","url","version","date","createdAt","toLocaleDateString","day","month","year","by","deployedBy","log","heading","organization","title","quit","then","exit"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAInC,SAAQC,cAAc,QAAO,qBAAoB;AACjD,SAAQC,qBAAqB,EAAEC,aAAa,QAAO,oCAAmC;AACtF,SAAQC,aAAa,QAAO,gBAAe;AAC3C,SAA8BC,wBAAwB,QAAO,2BAA0B;AACvF,SAAQC,gBAAgB,QAAO,wBAAuB;AACtD,SAAQC,sBAAsB,EAAEC,wBAAwB,QAAO,kBAAiB;AAEhF,SAAQC,0BAA0B,QAAO,kCAAiC;AAC1E,SACEC,uBAAuB,EACvBC,+BAA+B,QAC1B,+BAA8B;AA6BrC;;;;;;;;;CASC,GACD,OAAO,eAAeC,kBACpBC,OAAiC;IAEjC,MAAM,EACJC,QAAQ,EACRC,uBAAuB,EACvBC,SAAS,EACTC,eAAe,EACfC,QAAQ,EACRC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,eAAe,EACfC,cAAc,EACdC,OAAO,EACR,GAAGX;IAEJ,4EAA4E;IAC5E,0CAA0C;IAC1C,IAAIY,QAAQC,GAAG,CAACC,mCAAmC,KAAK,QAAQ;QAC9D,MAAMC,SAAS,MAAML,eAAe;YAACP;YAAWG;QAAQ;QACxD,IAAI,CAACS,OAAOC,OAAO,EAAE,OAAO;YAACC,OAAO,WAAa;QAAC;QAElD,MAAMC,cAAcpB,gCAAgC;YAACqB,QAAQJ,OAAOI,MAAM;QAAA;QAE1E,OAAO;YACLF,OAAO;gBACL,MAAMC,YAAYD,KAAK;gBACvB,MAAMF,OAAOE,KAAK;YACpB;QACF;IACF;IAEA,4EAA4E;IAC5E,qEAAqE;IACrE,MAAM,EAACA,KAAK,EAAEG,OAAO,EAAEC,qBAAqB,EAAC,GAAGhC;IAChD,MAAMiC,YAAYC,KAAKC,GAAG;IAC1B,MAAMC,MAAMrC,eAAee,UAAUsB,GAAG,IAAItB,UAAUsB,GAAG,GAAGC;IAC5D,MA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C,MAAM,EAACQ,UAAU,EAAEsB,gBAAgB,EAAC,GAAGnB,UAAUG,kBAAkB,GAC/D,MAAMzC,yBAAyBiC,WAC/B,CAAC;IAELP;IAEA,IAAIY,UAAUG,kBAAkB,EAAE;QAChC,MAAMiB,MAAM,CAAC,OAAO,EAAE/D,cAAc2C,UAAU5B,QAAQ,EAAE,CAAC,EAAE4B,UAAUI,aAAa,GAAGS,oBAAoB,IAAI;QAC7G,IAAIQ,UAAU;QAEd,IAAIxB,YAAY;YACd,MAAMyB,OAAO,IAAIhC,KAAKO,WAAW0B,SAAS,EAAEC,kBAAkB,CAAC,SAAS;gBACtEC,KAAK;gBACLC,OAAO;gBACPC,MAAM;YACR;YACA,MAAMC,KAAK/B,WAAWgC,UAAU,GAAG,CAAC,IAAI,EAAEhC,WAAWgC,UAAU,EAAE,GAAG;YACpER,UAAU,CAAC,cAAc,EAAEnE,UAAU,OAAO,CAAC,WAAW,EAAEoE,OAAOM,IAAI,GAAG;QAC1E,OAAO,IAAI/B,eAAe,MAAM;YAC9BwB,UAAU,CAAC,cAAc,EAAEnE,UAAU,OAAO,mBAAmB;QACjE;QAEAqB,OAAOuD,GAAG,CACRxE,cAAc;YACZ4D;YACAa,SAAS;YACTzD;YACA0D,cAAcb,oBAAoBzB;YAClCuC,OAAOzC,KAAKyC;YACZb;YACAC;QACF;QAGF,MAAMa,OAAO,IAAM,KAAKlD,QAAQmD,IAAI,CAAC,IAAMxD,QAAQyD,IAAI,CAAC;QACxDjD,QAAQc,IAAI,CAACzC,iBAAiB;YAACe;YAAQ2D;YAAMd;QAAG;IAClD;IAEA,OAAO;QAACpC;IAAK;AACf"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startWorkbenchDev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type CliConfig, type Output} from '@sanity/cli-core'\n\nimport {isWorkbenchApp} from '../../defineApp.js'\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {formatSummary} from '../summary.js'\nimport {type AppServerResult, startAppServerSupervisor} from './appServerSupervisor.js'\nimport {bindDevShortcuts} from './bindDevShortcuts.js'\nimport {fetchDevSummaryDetails, waitForDevSummaryDetails} from './devSummary.js'\nimport {type DevServerManifest} from './registry.js'\nimport {startDevServerRegistration} from './startDevServerRegistration.js'\nimport {\n startWorkbenchDevServer,\n startWorkbenchRemoteCoordinator,\n} from './startWorkbenchDevServer.js'\n\nexport interface StartWorkbenchDevOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n /** Where the app server serves the app's icon. */\n iconUrl?: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string | undefined\n httpPort: number\n isApp: boolean\n output: Output\n reactStrictMode: boolean\n /** Start the app/studio dev server — the CLI owns the server, this orchestrates it. */\n startAppServer: (params: {\n cliConfig: CliConfig\n httpPort: number\n isRestarting?: boolean\n quiet?: boolean\n }) => Promise<AppServerResult>\n workDir: string\n}\n\n/**\n * Orchestrate the dev servers a workbench project needs: a singleton workbench\n * Vite server plus the app/studio dev server it renders, wired to the dev-server\n * registry so view/web worker edits re-sync live.\n *\n * A running workbench claims the configured port, so the app server binds the\n * next one. If the workbench can't start (package or port unavailable), the app\n * server falls back to the configured port and announces its own URL, exactly as\n * a plain `sanity dev` would.\n */\nexport async function startWorkbenchDev(\n options: StartWorkbenchDevOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n output,\n reactStrictMode,\n startAppServer,\n workDir,\n } = options\n\n // The remote can't render itself, so it runs as a plain app server (not the\n // shell) that still bridges the registry.\n if (process.env.SANITY_INTERNAL_IS_WORKBENCH_REMOTE === 'true') {\n const remote = await startAppServer({cliConfig, httpPort})\n if (!remote.started) return {close: async () => {}}\n\n const coordinator = startWorkbenchRemoteCoordinator({server: remote.server})\n\n return {\n close: async () => {\n await coordinator.close()\n await remote.close()\n },\n }\n }\n\n // Unwound in reverse on any failure or on close(): the watcher stops before\n // the app server, and the supervisor waits out an in-flight rebuild.\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n const startedAt = Date.now()\n const app = isWorkbenchApp(cliConfig.app) ? cliConfig.app : undefined\n const organizationId = cliConfig.app?.organizationId\n const details = fetchDevSummaryDetails({\n idOrSlug: app && (cliConfig.deployment?.appId ?? app.slug),\n organizationId,\n })\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n // A running workbench owns the configured port; the app server takes the next.\n // Without one it claims the configured port and announces its own URL.\n const appPort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n\n const supervised = await startAppServerSupervisor({\n cliConfig,\n start: (config, {isRestarting} = {}) =>\n startAppServer({\n cliConfig: config,\n httpPort: appPort,\n isRestarting,\n quiet: workbench.workbenchAvailable,\n }),\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n\n if (!supervised.started) {\n // The app server already reported why (e.g. missing organization id). Hand\n // back a close that releases the workbench lock; nothing else came up.\n return {close}\n }\n const {supervisor} = supervised\n closers.push(supervisor.close)\n\n let dashboardAppPath: string | undefined\n try {\n // The deprecated-id check and manifest extractor are CLI-domain, injected here.\n checkForDeprecatedAppId()\n const registration = await startDevServerRegistration({\n cliConfig,\n extractManifest,\n isApp,\n onInterfaceSetChange: () => supervisor.rebuild(),\n output,\n server: supervisor.server,\n workDir,\n })\n closers.push(registration.close)\n dashboardAppPath = registration.path\n } catch (err) {\n // Registration runs after both servers are up; a failure here would leak the\n // workbench lock and dev servers without this teardown.\n await close()\n throw err\n }\n\n const durationMs = Date.now() - startedAt\n const {deployment, organizationName} = workbench.workbenchAvailable\n ? await waitForDevSummaryDetails(details)\n : {}\n\n installSignalHandlers()\n\n if (workbench.workbenchAvailable) {\n const url = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}${dashboardAppPath ?? ''}`\n let version = ''\n\n if (deployment) {\n const date = new Date(deployment.createdAt).toLocaleDateString('en-US', {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n })\n const by = deployment.deployedBy ? ` by ${deployment.deployedBy}` : ''\n version = `local preview ${styleText('dim', `· deployed ${date}${by}`)}`\n } else if (deployment === null) {\n version = `local preview ${styleText('dim', '· not deployed')}`\n }\n\n output.log(\n formatSummary({\n durationMs,\n heading: 'Sanity Dashboard ready',\n isApp,\n organization: organizationName ?? organizationId,\n title: app?.title,\n url,\n version,\n }),\n )\n\n const quit = () => void close().then(() => process.exit(0))\n closers.push(bindDevShortcuts({output, quit, url}))\n }\n\n return {close}\n}\n"],"names":["styleText","isWorkbenchApp","createServerLifecycle","toDisplayHost","formatSummary","startAppServerSupervisor","bindDevShortcuts","fetchDevSummaryDetails","waitForDevSummaryDetails","startDevServerRegistration","startWorkbenchDevServer","startWorkbenchRemoteCoordinator","startWorkbenchDev","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","output","reactStrictMode","startAppServer","workDir","process","env","SANITY_INTERNAL_IS_WORKBENCH_REMOTE","remote","started","close","coordinator","server","closers","installSignalHandlers","startedAt","Date","now","app","undefined","organizationId","details","idOrSlug","deployment","appId","slug","workbench","push","appPort","workbenchAvailable","workbenchPort","supervised","start","config","isRestarting","quiet","catch","err","supervisor","dashboardAppPath","registration","onInterfaceSetChange","rebuild","path","durationMs","organizationName","url","version","date","createdAt","toLocaleDateString","day","month","year","by","deployedBy","log","heading","organization","title","quit","then","exit"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAInC,SAAQC,cAAc,QAAO,qBAAoB;AACjD,SAAQC,qBAAqB,EAAEC,aA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,MAAM,CAAC,OAAO,EAAE/D,cAAc2C,UAAU5B,QAAQ,EAAE,CAAC,EAAE4B,UAAUI,aAAa,GAAGS,oBAAoB,IAAI;QAC7G,IAAIQ,UAAU;QAEd,IAAIxB,YAAY;YACd,MAAMyB,OAAO,IAAIhC,KAAKO,WAAW0B,SAAS,EAAEC,kBAAkB,CAAC,SAAS;gBACtEC,KAAK;gBACLC,OAAO;gBACPC,MAAM;YACR;YACA,MAAMC,KAAK/B,WAAWgC,UAAU,GAAG,CAAC,IAAI,EAAEhC,WAAWgC,UAAU,EAAE,GAAG;YACpER,UAAU,CAAC,cAAc,EAAEnE,UAAU,OAAO,CAAC,WAAW,EAAEoE,OAAOM,IAAI,GAAG;QAC1E,OAAO,IAAI/B,eAAe,MAAM;YAC9BwB,UAAU,CAAC,cAAc,EAAEnE,UAAU,OAAO,mBAAmB;QACjE;QAEAqB,OAAOuD,GAAG,CACRxE,cAAc;YACZ4D;YACAa,SAAS;YACTzD;YACA0D,cAAcb,oBAAoBzB;YAClCuC,OAAOzC,KAAKyC;YACZb;YACAC;QACF;QAGF,MAAMa,OAAO,IAAM,KAAKlD,QAAQmD,IAAI,CAAC,IAAMxD,QAAQyD,IAAI,CAAC;QACxDjD,QAAQc,IAAI,CAACzC,iBAAiB;YAACe;YAAQ2D;YAAMd;QAAG;IAClD;IAEA,OAAO;QAACpC;IAAK;AACf"}
|
|
@@ -11,7 +11,7 @@ const previewDebug = subdebug('preview');
|
|
|
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
|
-
const { cacheDir, httpHost, httpPort, outDir, workDir } = options;
|
|
14
|
+
const { cacheDir, httpHost, httpPort, icon, outDir, workDir } = options;
|
|
15
15
|
await readBuiltManifest(outDir);
|
|
16
16
|
const config = {
|
|
17
17
|
// Serve at the root so `mf-manifest.json` and its `publicPath: 'auto'` chunks
|
|
@@ -25,6 +25,17 @@ const previewDebug = subdebug('preview');
|
|
|
25
25
|
configFile: false,
|
|
26
26
|
logLevel: 'warn',
|
|
27
27
|
mode: 'production',
|
|
28
|
+
plugins: icon ? [
|
|
29
|
+
{
|
|
30
|
+
configurePreviewServer (server) {
|
|
31
|
+
server.middlewares.use(icon.path, (_req, res)=>{
|
|
32
|
+
res.setHeader('Content-Type', icon.contentType);
|
|
33
|
+
res.end(icon.image);
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
name: 'sanity:app-icon'
|
|
37
|
+
}
|
|
38
|
+
] : [],
|
|
28
39
|
preview: {
|
|
29
40
|
host: httpHost,
|
|
30
41
|
port: httpPort,
|
|
@@ -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 {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","
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/preview/serveBuiltApplication.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\nimport {type ImageFile} from '@sanity/cli-core/images'\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 /** The app's icon, served at `path`: it lives in the project, not in `outDir`. */\n icon?: ImageFile & {path: string}\n outDir: string\n workDir: string\n}): Promise<BuiltApplicationServer> {\n const {cacheDir, httpHost, httpPort, icon, 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 plugins: icon\n ? [\n {\n configurePreviewServer(server) {\n server.middlewares.use(icon.path, (_req, res) => {\n res.setHeader('Content-Type', icon.contentType)\n res.end(icon.image)\n })\n },\n name: 'sanity:app-icon',\n },\n ]\n : [],\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","icon","outDir","workDir","config","base","build","configFile","logLevel","mode","plugins","configurePreviewServer","server","middlewares","use","path","_req","res","setHeader","contentType","end","image","name","host","port","strictPort","root","addr","httpServer","address","close","Promise","resolve","reject","err","closeAllConnections"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,SAA2BC,OAAO,QAAO,OAAM;AAE/C,SAAQC,iBAAiB,QAAO,gCAA+B;AAE/D,MAA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4
|
import { findProjectRoot } from '@sanity/cli-core';
|
|
5
5
|
import { buildAppId, SANITY_APP_ID_FILE } from '../../appId.js';
|
|
6
|
+
import { isWorkbenchApp } from '../../defineApp.js';
|
|
6
7
|
import { deriveInterfaces } from '../../deriveInterfaces.js';
|
|
8
|
+
import { readAppIcon, toUrlPath } from '../../readAppIcon.js';
|
|
7
9
|
import { resolveWorkbenchApp } from '../../resolveWorkbenchApp.js';
|
|
8
10
|
import { createServerLifecycle, toDisplayHost } from '../../util/serverOrchestration.js';
|
|
9
11
|
import { deriveConfigs } from '../dev/deriveConfigs.js';
|
|
@@ -22,6 +24,13 @@ import { serveBuiltApplication } from './serveBuiltApplication.js';
|
|
|
22
24
|
* own URL.
|
|
23
25
|
*/ export async function startWorkbenchPreview(options) {
|
|
24
26
|
const { cacheDir, checkForDeprecatedAppId, cliConfig, extractManifest, httpHost, httpPort, isApp, outDir, output, reactStrictMode, workDir } = options;
|
|
27
|
+
// Read before any server starts, so a bad icon path fails with nothing to tear down.
|
|
28
|
+
const iconPath = isApp && isWorkbenchApp(cliConfig.app) ? cliConfig.app.icon : undefined;
|
|
29
|
+
const icon = iconPath ? await readAppIcon(workDir, iconPath) : undefined;
|
|
30
|
+
const servedIcon = icon && {
|
|
31
|
+
...icon,
|
|
32
|
+
path: `/${toUrlPath(workDir, icon.file)}`
|
|
33
|
+
};
|
|
25
34
|
const { close, closers, installSignalHandlers } = createServerLifecycle();
|
|
26
35
|
const workbench = await startWorkbenchDevServer({
|
|
27
36
|
cacheDir,
|
|
@@ -38,6 +47,7 @@ import { serveBuiltApplication } from './serveBuiltApplication.js';
|
|
|
38
47
|
cacheDir,
|
|
39
48
|
httpHost,
|
|
40
49
|
httpPort: remotePort,
|
|
50
|
+
icon: servedIcon,
|
|
41
51
|
outDir,
|
|
42
52
|
workDir
|
|
43
53
|
}).catch(async (err)=>{
|
|
@@ -70,6 +80,7 @@ import { serveBuiltApplication } from './serveBuiltApplication.js';
|
|
|
70
80
|
manifest: await extractManifest({
|
|
71
81
|
applicationId: id,
|
|
72
82
|
configPath,
|
|
83
|
+
iconUrl: servedIcon && `http://${remote.host}:${remote.port}${servedIcon.path}`,
|
|
73
84
|
workDir
|
|
74
85
|
}),
|
|
75
86
|
manifestUpdatedAt: new Date().toISOString(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/preview/startWorkbenchPreview.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type CliConfig, findProjectRoot, type Output} from '@sanity/cli-core'\n\nimport {buildAppId, SANITY_APP_ID_FILE} from '../../appId.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {deriveConfigs} from '../dev/deriveConfigs.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n localAppIdentity,\n registerDevServer,\n} from '../dev/registry.js'\nimport {startWorkbenchDevServer} from '../dev/startWorkbenchDevServer.js'\nimport {serveBuiltApplication} from './serveBuiltApplication.js'\n\nexport interface StartWorkbenchPreviewOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string\n httpPort: number\n isApp: boolean\n /** The built `dist` directory to serve as the federation remote. */\n outDir: string\n output: Output\n reactStrictMode: boolean\n workDir: string\n}\n\n/**\n * `sanity start` for a workbench app: serve a production build the way dev serves\n * a live one. The same singleton workbench shell renders it and the same registry\n * advertises it — only the remote differs, static files from the build output\n * instead of a live Vite dev server. There's no config watcher or rebuild: a\n * build is fixed, so nothing re-syncs.\n *\n * A running workbench claims the configured port, so the built remote binds the\n * next one. Without one the remote takes the configured port and announces its\n * own URL.\n */\nexport async function startWorkbenchPreview(\n options: StartWorkbenchPreviewOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n const remotePort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n\n const remote = await serveBuiltApplication({\n cacheDir,\n httpHost,\n httpPort: remotePort,\n outDir,\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n closers.push(remote.close)\n\n let dashboardAppPath: string | undefined\n try {\n // Callers provide CLI-only validation and manifest extraction to keep them\n // out of workbench-cli.\n checkForDeprecatedAppId()\n const configPath = (await findProjectRoot(workDir)).path\n const workbench = resolveWorkbenchApp(cliConfig)\n\n if (!workbench) {\n throw new Error(\n '`sanity start` was invoked in an application that is not set up for the Dashboard',\n )\n }\n const inlinedId = await readInlinedAppId(outDir)\n const configs = await deriveConfigs(cliConfig)\n const id = inlinedId ?? (await buildAppId(workbench))\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const registration = registerDevServer({\n applicationId: cliConfig.deployment?.appId,\n configs,\n host: remote.host,\n id,\n interfaces,\n manifest: await extractManifest({applicationId: id
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/preview/startWorkbenchPreview.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type CliConfig, findProjectRoot, type Output} from '@sanity/cli-core'\n\nimport {buildAppId, SANITY_APP_ID_FILE} from '../../appId.js'\nimport {isWorkbenchApp} from '../../defineApp.js'\nimport {deriveInterfaces} from '../../deriveInterfaces.js'\nimport {readAppIcon, toUrlPath} from '../../readAppIcon.js'\nimport {resolveWorkbenchApp} from '../../resolveWorkbenchApp.js'\nimport {createServerLifecycle, toDisplayHost} from '../../util/serverOrchestration.js'\nimport {deriveConfigs} from '../dev/deriveConfigs.js'\nimport {\n dashboardPath,\n type DevServerManifest,\n localAppIdentity,\n registerDevServer,\n} from '../dev/registry.js'\nimport {startWorkbenchDevServer} from '../dev/startWorkbenchDevServer.js'\nimport {serveBuiltApplication} from './serveBuiltApplication.js'\n\nexport interface StartWorkbenchPreviewOptions {\n /** Directory for the workbench Vite server's dependency cache. */\n cacheDir: string\n /** CLI-domain `app.id`/`deployment.appId` deprecation check, run before registering. */\n checkForDeprecatedAppId: () => void\n cliConfig: CliConfig\n /** Extract the project manifest to inline into the registry (studio-vs-app handled by the CLI). */\n extractManifest: (params: {\n applicationId?: string\n configPath: string\n /** Where the preview serves the app's icon. */\n iconUrl?: string\n workDir: string\n }) => Promise<DevServerManifest['manifest']>\n httpHost: string\n httpPort: number\n isApp: boolean\n /** The built `dist` directory to serve as the federation remote. */\n outDir: string\n output: Output\n reactStrictMode: boolean\n workDir: string\n}\n\n/**\n * `sanity start` for a workbench app: serve a production build the way dev serves\n * a live one. The same singleton workbench shell renders it and the same registry\n * advertises it — only the remote differs, static files from the build output\n * instead of a live Vite dev server. There's no config watcher or rebuild: a\n * build is fixed, so nothing re-syncs.\n *\n * A running workbench claims the configured port, so the built remote binds the\n * next one. Without one the remote takes the configured port and announces its\n * own URL.\n */\nexport async function startWorkbenchPreview(\n options: StartWorkbenchPreviewOptions,\n): Promise<{close: () => Promise<void>}> {\n const {\n cacheDir,\n checkForDeprecatedAppId,\n cliConfig,\n extractManifest,\n httpHost,\n httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Read before any server starts, so a bad icon path fails with nothing to tear down.\n const iconPath = isApp && isWorkbenchApp(cliConfig.app) ? cliConfig.app.icon : undefined\n const icon = iconPath ? await readAppIcon(workDir, iconPath) : undefined\n const servedIcon = icon && {...icon, path: `/${toUrlPath(workDir, icon.file)}`}\n\n const {close, closers, installSignalHandlers} = createServerLifecycle()\n\n const workbench = await startWorkbenchDevServer({\n cacheDir,\n cliConfig,\n httpHost,\n httpPort,\n output,\n reactStrictMode,\n workDir,\n })\n closers.push(workbench.close)\n\n const remotePort = workbench.workbenchAvailable ? workbench.workbenchPort + 1 : httpPort\n\n const remote = await serveBuiltApplication({\n cacheDir,\n httpHost,\n httpPort: remotePort,\n icon: servedIcon,\n outDir,\n workDir,\n }).catch(async (err) => {\n await close()\n throw err\n })\n closers.push(remote.close)\n\n let dashboardAppPath: string | undefined\n try {\n // Callers provide CLI-only validation and manifest extraction to keep them\n // out of workbench-cli.\n checkForDeprecatedAppId()\n const configPath = (await findProjectRoot(workDir)).path\n const workbench = resolveWorkbenchApp(cliConfig)\n\n if (!workbench) {\n throw new Error(\n '`sanity start` was invoked in an application that is not set up for the Dashboard',\n )\n }\n const inlinedId = await readInlinedAppId(outDir)\n const configs = await deriveConfigs(cliConfig)\n const id = inlinedId ?? (await buildAppId(workbench))\n const interfaces = deriveInterfaces(cliConfig.app, {isApp})\n const registration = registerDevServer({\n applicationId: cliConfig.deployment?.appId,\n configs,\n host: remote.host,\n id,\n interfaces,\n manifest: await extractManifest({\n applicationId: id,\n configPath,\n iconUrl: servedIcon && `http://${remote.host}:${remote.port}${servedIcon.path}`,\n workDir,\n }),\n manifestUpdatedAt: new Date().toISOString(),\n port: remote.port,\n projectId: cliConfig?.api?.projectId,\n ...localAppIdentity(workbench),\n type: isApp ? 'coreApp' : 'studio',\n workDir,\n })\n closers.push(async () => registration.release())\n dashboardAppPath = dashboardPath({\n id,\n interfaces,\n slug: workbench.slug,\n type: isApp ? 'coreApp' : 'studio',\n })\n } catch (err) {\n await close()\n throw err\n }\n\n if (workbench.workbenchAvailable) {\n const appUrl = `http://${toDisplayHost(workbench.httpHost)}:${workbench.workbenchPort}${dashboardAppPath ?? ''}`\n output.log(`Dashboard preview server started at ${styleText(['blue', 'underline'], appUrl)}`)\n } else {\n const remoteUrl = `http://${toDisplayHost(remote.host)}:${remote.port}`\n output.log(`Serving build at ${styleText(['blue', 'underline'], remoteUrl)}`)\n }\n\n installSignalHandlers()\n\n return {close}\n}\n\n/** The id the build inlined into its bundle, or undefined when absent. */\nasync function readInlinedAppId(outDir: string): Promise<string | undefined> {\n try {\n return (await readFile(path.join(outDir, SANITY_APP_ID_FILE), 'utf8')).trim() || undefined\n } catch {\n return undefined\n }\n}\n"],"names":["readFile","path","styleText","findProjectRoot","buildAppId","SANITY_APP_ID_FILE","isWorkbenchApp","deriveInterfaces","readAppIcon","toUrlPath","resolveWorkbenchApp","createServerLifecycle","toDisplayHost","deriveConfigs","dashboardPath","localAppIdentity","registerDevServer","startWorkbenchDevServer","serveBuiltApplication","startWorkbenchPreview","options","cacheDir","checkForDeprecatedAppId","cliConfig","extractManifest","httpHost","httpPort","isApp","outDir","output","reactStrictMode","workDir","iconPath","app","icon","undefined","servedIcon","file","close","closers","installSignalHandlers","workbench","push","remotePort","workbenchAvailable","workbenchPort","remote","catch","err","dashboardAppPath","configPath","Error","inlinedId","readInlinedAppId","configs","id","interfaces","registration","applicationId","deployment","appId","host","manifest","iconUrl","port","manifestUpdatedAt","Date","toISOString","projectId","api","type","release","slug","appUrl","log","remoteUrl","join","trim"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAwBC,eAAe,QAAoB,mBAAkB;AAE7E,SAAQC,UAAU,EAAEC,kBAAkB,QAAO,iBAAgB;AAC7D,SAAQC,cAAc,QAAO,qBAAoB;AACjD,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,WAAW,EAAEC,SAAS,QAAO,uBAAsB;AAC3D,SAAQC,mBAAmB,QAAO,+BAA8B;AAChE,SAAQ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AExE,UAAU;YAAC;YAAQ;SAAY,EAAEuE,SAAS;IAC9F,OAAO;QACL,MAAME,YAAY,CAAC,OAAO,EAAE/D,cAAckC,OAAOe,IAAI,EAAE,CAAC,EAAEf,OAAOkB,IAAI,EAAE;QACvEnC,OAAO6C,GAAG,CAAC,CAAC,iBAAiB,EAAExE,UAAU;YAAC;YAAQ;SAAY,EAAEyE,YAAY;IAC9E;IAEAnC;IAEA,OAAO;QAACF;IAAK;AACf;AAEA,wEAAwE,GACxE,eAAee,iBAAiBzB,MAAc;IAC5C,IAAI;QACF,OAAO,AAAC,CAAA,MAAM5B,SAASC,KAAK2E,IAAI,CAAChD,QAAQvB,qBAAqB,OAAM,EAAGwE,IAAI,MAAM1C;IACnF,EAAE,OAAM;QACN,OAAOA;IACT;AACF"}
|
package/dist/appId.js
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
view.src
|
|
27
27
|
]).toSorted()
|
|
28
28
|
});
|
|
29
|
-
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- the Web Crypto global is available on our Node target and in the browser
|
|
29
|
+
// eslint-disable-next-line n-js/no-unsupported-features/node-builtins -- the Web Crypto global is available on our Node target and in the browser
|
|
30
30
|
const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(shape));
|
|
31
31
|
return Array.from(new Uint8Array(digest), (byte)=>byte.toString(16).padStart(2, '0')).join('');
|
|
32
32
|
}
|
package/dist/appId.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/appId.ts"],"sourcesContent":["import {type ResolvedWorkbenchApp} from './resolveWorkbenchApp.js'\n\n/**\n * File the build writes into its output, carrying the id compiled into the\n * bundle. `sanity start` serves a build without recompiling, so it reads this\n * instead of recomputing — a deploy inlines the API id, not the shape hash.\n */\nexport const SANITY_APP_ID_FILE = 'sanity-app-id.txt'\n\n/**\n * The `build`/`start` id — a hash of the app's declared shape (its identity, not\n * its code), so the bundle inlined by `sanity build` and the registry entry\n * advertised by `sanity start` resolve to the same id. `sanity deploy` resolves\n * its own id from the applications API.\n */\nexport async function buildAppId(app: ResolvedWorkbenchApp): Promise<string> {\n const shape = JSON.stringify({\n entry: app.entry ?? null,\n // Identity, not address: the id keys on `name` (which defaults to `slug`). The\n // address (`slug`) is deliberately absent, so renaming it never shifts the id.\n name: app.name,\n organizationId: app.organizationId,\n services: app.webWorkers\n .map((webWorker): [string, string, string] => [webWorker.type, webWorker.name, webWorker.src])\n .toSorted(),\n views: app.views\n .map((view): [string, string, string] => [view.surface, view.name, view.src])\n .toSorted(),\n })\n // eslint-disable-next-line n/no-unsupported-features/node-builtins -- the Web Crypto global is available on our Node target and in the browser\n const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(shape))\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n"],"names":["SANITY_APP_ID_FILE","buildAppId","app","shape","JSON","stringify","entry","name","organizationId","services","webWorkers","map","webWorker","type","src","toSorted","views","view","surface","digest","globalThis","crypto","subtle","TextEncoder","encode","Array","from","Uint8Array","byte","toString","padStart","join"],"mappings":"AAEA;;;;CAIC,GACD,OAAO,MAAMA,qBAAqB,oBAAmB;AAErD;;;;;CAKC,GACD,OAAO,eAAeC,WAAWC,GAAyB;IACxD,MAAMC,QAAQC,KAAKC,SAAS,CAAC;QAC3BC,OAAOJ,IAAII,KAAK,IAAI;QACpB,+EAA+E;QAC/E,+EAA+E;QAC/EC,MAAML,IAAIK,IAAI;QACdC,gBAAgBN,IAAIM,cAAc;QAClCC,UAAUP,IAAIQ,UAAU,CACrBC,GAAG,CAAC,CAACC,YAAwC;gBAACA,UAAUC,IAAI;gBAAED,UAAUL,IAAI;gBAAEK,UAAUE,GAAG;aAAC,EAC5FC,QAAQ;QACXC,OAAOd,IAAIc,KAAK,CACbL,GAAG,CAAC,CAACM,OAAmC;gBAACA,KAAKC,OAAO;gBAAED,KAAKV,IAAI;gBAAEU,KAAKH,GAAG;aAAC,EAC3EC,QAAQ;IACb;IACA
|
|
1
|
+
{"version":3,"sources":["../src/appId.ts"],"sourcesContent":["import {type ResolvedWorkbenchApp} from './resolveWorkbenchApp.js'\n\n/**\n * File the build writes into its output, carrying the id compiled into the\n * bundle. `sanity start` serves a build without recompiling, so it reads this\n * instead of recomputing — a deploy inlines the API id, not the shape hash.\n */\nexport const SANITY_APP_ID_FILE = 'sanity-app-id.txt'\n\n/**\n * The `build`/`start` id — a hash of the app's declared shape (its identity, not\n * its code), so the bundle inlined by `sanity build` and the registry entry\n * advertised by `sanity start` resolve to the same id. `sanity deploy` resolves\n * its own id from the applications API.\n */\nexport async function buildAppId(app: ResolvedWorkbenchApp): Promise<string> {\n const shape = JSON.stringify({\n entry: app.entry ?? null,\n // Identity, not address: the id keys on `name` (which defaults to `slug`). The\n // address (`slug`) is deliberately absent, so renaming it never shifts the id.\n name: app.name,\n organizationId: app.organizationId,\n services: app.webWorkers\n .map((webWorker): [string, string, string] => [webWorker.type, webWorker.name, webWorker.src])\n .toSorted(),\n views: app.views\n .map((view): [string, string, string] => [view.surface, view.name, view.src])\n .toSorted(),\n })\n // eslint-disable-next-line n-js/no-unsupported-features/node-builtins -- the Web Crypto global is available on our Node target and in the browser\n const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(shape))\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n"],"names":["SANITY_APP_ID_FILE","buildAppId","app","shape","JSON","stringify","entry","name","organizationId","services","webWorkers","map","webWorker","type","src","toSorted","views","view","surface","digest","globalThis","crypto","subtle","TextEncoder","encode","Array","from","Uint8Array","byte","toString","padStart","join"],"mappings":"AAEA;;;;CAIC,GACD,OAAO,MAAMA,qBAAqB,oBAAmB;AAErD;;;;;CAKC,GACD,OAAO,eAAeC,WAAWC,GAAyB;IACxD,MAAMC,QAAQC,KAAKC,SAAS,CAAC;QAC3BC,OAAOJ,IAAII,KAAK,IAAI;QACpB,+EAA+E;QAC/E,+EAA+E;QAC/EC,MAAML,IAAIK,IAAI;QACdC,gBAAgBN,IAAIM,cAAc;QAClCC,UAAUP,IAAIQ,UAAU,CACrBC,GAAG,CAAC,CAACC,YAAwC;gBAACA,UAAUC,IAAI;gBAAED,UAAUL,IAAI;gBAAEK,UAAUE,GAAG;aAAC,EAC5FC,QAAQ;QACXC,OAAOd,IAAIc,KAAK,CACbL,GAAG,CAAC,CAACM,OAAmC;gBAACA,KAAKC,OAAO;gBAAED,KAAKV,IAAI;gBAAEU,KAAKH,GAAG;aAAC,EAC3EC,QAAQ;IACb;IACA,kJAAkJ;IAClJ,MAAMI,SAAS,MAAMC,WAAWC,MAAM,CAACC,MAAM,CAACH,MAAM,CAAC,WAAW,IAAII,cAAcC,MAAM,CAACrB;IACzF,OAAOsB,MAAMC,IAAI,CAAC,IAAIC,WAAWR,SAAS,CAACS,OAASA,KAAKC,QAAQ,CAAC,IAAIC,QAAQ,CAAC,GAAG,MAAMC,IAAI,CAAC;AAC/F"}
|
package/dist/defineApp.js
CHANGED
|
@@ -35,9 +35,10 @@ import { DockSchema, InterfaceDeclarationSchema, WebWorkerDeclarationSchema } fr
|
|
|
35
35
|
* on a studio is rejected (studio app views are not yet implemented).
|
|
36
36
|
*/ entry: z.optional(z.string("must be a path to the app's entry file")),
|
|
37
37
|
/**
|
|
38
|
-
* Path to
|
|
39
|
-
*
|
|
40
|
-
|
|
38
|
+
* Path to the app's icon, relative to the project root: a PNG, JPEG, GIF,
|
|
39
|
+
* WebP, SVG, BMP, TIFF, HEIF or AVIF image of at most 5 MB. Wins over
|
|
40
|
+
* manifest/studio icon.
|
|
41
|
+
*/ icon: z.optional(z.string()),
|
|
41
42
|
/** Sanity-owned app deployed once and installed per org. @internal */ isSingleton: z.optional(z.boolean()),
|
|
42
43
|
/**
|
|
43
44
|
* Stable identity, distinct from the `slug` address. Defaults to `slug` when
|
package/dist/defineApp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/defineApp.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\nimport {APP_SLUG_PATTERN} from './appSlug.js'\nimport {DockSchema, InterfaceDeclarationSchema, WebWorkerDeclarationSchema} from './contract.js'\n\n/**\n * Dashboard visibility values. Mirrors `APP_VISIBILITIES` in `@sanity/cli-core`\n * (which can't be imported here — pulling the barrel into this lean module bloats\n * the config-load path). Kept in sync by a type test in `defineApp.test.ts`.\n */\nconst APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n\n/**\n * Internal application discriminator. Sanity-owned singleton apps only;\n * validated by the schema but excluded from the public `DefineAppInput` type.\n */\nconst ApplicationType = z.enum(['coreApp', 'studio', 'canvas', 'dashboard'])\n\n/**\n * Runtime-validation schema for `defineApplication`.\n * @internal\n */\nexport const DefineAppInputSchema = z\n .object({\n /**\n * Internal — Sanity-owned singleton apps only. Validated here but excluded\n * from the public `DefineAppInput` type.\n * @internal\n */\n applicationType: z.optional(ApplicationType),\n /** Default placement inherited by window views. */\n dock: z.optional(DockSchema),\n /**\n * App entrypoint module. Defaults to `./src/App.tsx` when omitted. The build\n * derives the app's navigable `app` view from it. SDK apps only — setting it\n * on a studio is rejected (studio app views are not yet implemented).\n */\n entry: z.optional(z.string(\"must be a path to the app's entry file\")),\n /**\n * Path to an `.svg` file, relative to the project root. Other file types are\n * rejected. Wins over manifest/studio icon.\n */\n icon: z.optional(\n z.string().check(z.regex(/\\.svg$/i, 'App `icon` must be a path to an .svg file')),\n ),\n /** Sanity-owned app deployed once and installed per org. @internal */\n isSingleton: z.optional(z.boolean()),\n /**\n * Stable identity, distinct from the `slug` address. Defaults to `slug` when\n * omitted. Identity keys — the build id and derived interface ids — are built\n * from this, so renaming the slug no longer changes identity.\n */\n name: z.optional(\n z\n .string()\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `name` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n ),\n /** Organization that owns the app — it runs in and deploys to this organization's Dashboard. */\n organizationId: z.string(\n \"App `organizationId` is required — pass the owning organization's ID to `defineApplication`\",\n ),\n slug: z\n .string('App `slug` is required — the hostname the application is created at on deploy')\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `slug` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n /** User-facing app title. Wins over studio.config.ts title on merge. */\n title: z.string(),\n /** Views the app exposes (e.g. a window, dock panels, and tiles). */\n views: z.optional(z.array(InterfaceDeclarationSchema, 'must be an array of views')),\n /** Dashboard visibility of the app. Defaults to `default` when omitted. */\n visibility: z.optional(z.enum(APP_VISIBILITIES)),\n /** Background web workers the app runs. */\n webWorkers: z.optional(z.array(WebWorkerDeclarationSchema, 'must be an array of web workers')),\n })\n .check(\n z.refine((input) => {\n const names = [\n ...(input.entry === undefined ? [] : [input.name ?? input.slug]),\n ...(input.views ?? []).map((view) => view.name),\n ...(input.webWorkers ?? []).map((webWorker) => webWorker.name),\n ]\n return new Set(names).size === names.length\n }, '`name` must be unique across views and web workers. Rename one of the duplicates.'),\n // Studio app views are not implemented yet. A studio that declares `entry`\n // (the SDK app-view entrypoint) is rejected here rather than silently\n // generating one; studios keep navigating via their existing render path.\n z.refine((input) => !(input.applicationType === 'studio' && input.entry !== undefined), {\n error: 'App views for studios are not implemented yet',\n path: ['entry'],\n }),\n )\n\n/**\n * User-facing input for `defineApplication`. Excludes the internal\n * `applicationType` and `isSingleton`.\n * @public\n */\nexport type DefineAppInput = Omit<\n z.output<typeof DefineAppInputSchema>,\n 'applicationType' | 'isSingleton'\n>\n\n/**\n * Nominal brand the CLI discriminates on to enable the workbench build/deploy\n * codepath. Registered via `Symbol.for` so the marker survives module-realm\n * boundaries — `@sanity/cli-core` re-derives the same global symbol with\n * `Symbol.for` rather than importing it, so it stays internal to this module.\n */\nconst WORKBENCH_APP: unique symbol = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * The branded result of `defineApplication`. Carries the same fields as the\n * input plus the internal brand — users only ever see `DefineAppInput`.\n * @public\n */\nexport type DefineAppResult = DefineAppInput & {readonly [WORKBENCH_APP]: true}\n\n/**\n * A branded app as the CLI reads it — the full schema shape, including the\n * internal fields `DefineAppInput` omits. Schema-derived so the narrowing\n * can't drift from what the schema validates.\n * @public\n */\nexport type WorkbenchApp = DefineAppResult & z.output<typeof DefineAppInputSchema>\n\n/**\n * Whether `app` is a branded `defineApplication(...)` result — the sole\n * workbench opt-in.\n * @public\n */\nexport function isWorkbenchApp(app: unknown): app is WorkbenchApp {\n return typeof app === 'object' && app !== null && WORKBENCH_APP in app\n}\n\n/**\n * Declare a Sanity Dashboard application. Identity at runtime — returns the same\n * object reference, tagged with the Dashboard brand. Field validation (the\n * `slug` pattern etc.) runs at build time in the CLI via `DefineAppInputSchema`;\n * this helper stays a thin, pure identity wrapper.\n * @public\n */\nexport function defineApplication(input: DefineAppInput): DefineAppResult {\n return Object.defineProperty(input, WORKBENCH_APP, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n }) as DefineAppResult\n}\n\n/**\n * One custom field a media library exposes. `src` default-exports a `defineField(...)` schema type.\n * @public\n */\nexport interface MediaLibraryField {\n /** Unique within the media library. */\n name: string\n src: string\n title: string\n\n /** Readable outside the owning organization. */\n public?: boolean\n}\n\n/**\n * Sanity-owned singleton, so authors don't name or title the app — only `organizationId` is required.\n * @public\n */\nexport interface DefineMediaLibraryInput {\n /** Organization that owns the media library — the CLI runs and deploys against it. */\n organizationId: string\n\n fields?: MediaLibraryField[]\n}\n\n/**\n * Nominal brand the CLI discriminates a config on. A config is *not* an app: it\n * carries no `slug`/`title`/application identity, only a target `appType`, its\n * owning `organizationId`, and its `fields`. Registered via `Symbol.for` so the\n * marker survives module-realm boundaries — `@sanity/cli-core` re-derives the\n * same global symbol rather than importing it.\n */\nconst WORKBENCH_CONFIG: unique symbol = Symbol.for('sanity.workbench.defineConfig')\n\n/**\n * A branded workbench config as the CLI reads it: bound to its target app by\n * `appType`, not carrying its own app identity. The deploy/undeploy/build paths\n * discriminate it via {@link isWorkbenchConfig}.\n * @public\n */\nexport interface WorkbenchConfig {\n appType: 'media-library'\n fields: MediaLibraryField[]\n organizationId: string\n readonly [WORKBENCH_CONFIG]: true\n}\n\n/**\n * Whether `app` is a branded `unstable_defineMediaLibrary(...)` config — a\n * config-carrier rather than an app. Configs live in `cliConfig.app` alongside\n * apps but resolve through `resolveWorkbenchConfig`, not `resolveWorkbenchApp`.\n * @public\n */\nexport function isWorkbenchConfig(app: unknown): app is WorkbenchConfig {\n return typeof app === 'object' && app !== null && WORKBENCH_CONFIG in app\n}\n\n/**\n * Declare the Sanity Media Library config. The Media Library is a Sanity-owned\n * singleton, so this is not an app — it carries no slug or title, only the\n * target `appType`, its owning organization, and the `fields` it contributes to\n * the installation's config.\n * @public\n */\nexport function unstable_defineMediaLibrary(input: DefineMediaLibraryInput): WorkbenchConfig {\n return Object.defineProperty(\n {appType: 'media-library', fields: input.fields ?? [], organizationId: input.organizationId},\n WORKBENCH_CONFIG,\n {configurable: false, enumerable: false, value: true, writable: false},\n ) as WorkbenchConfig\n}\n"],"names":["z","APP_SLUG_PATTERN","DockSchema","InterfaceDeclarationSchema","WebWorkerDeclarationSchema","APP_VISIBILITIES","ApplicationType","enum","DefineAppInputSchema","object","applicationType","optional","dock","entry","string","icon","check","regex","isSingleton","boolean","name","organizationId","slug","title","views","array","visibility","webWorkers","refine","input","names","undefined","map","view","webWorker","Set","size","length","error","path","WORKBENCH_APP","Symbol","for","isWorkbenchApp","app","defineApplication","Object","defineProperty","configurable","enumerable","value","writable","WORKBENCH_CONFIG","isWorkbenchConfig","unstable_defineMediaLibrary","appType","fields"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,SAAQC,gBAAgB,QAAO,eAAc;AAC7C,SAAQC,UAAU,EAAEC,0BAA0B,EAAEC,0BAA0B,QAAO,gBAAe;AAEhG;;;;CAIC,GACD,MAAMC,mBAAmB;IAAC;IAAW;IAAY;CAAW;AAE5D;;;CAG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/defineApp.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\nimport {APP_SLUG_PATTERN} from './appSlug.js'\nimport {DockSchema, InterfaceDeclarationSchema, WebWorkerDeclarationSchema} from './contract.js'\n\n/**\n * Dashboard visibility values. Mirrors `APP_VISIBILITIES` in `@sanity/cli-core`\n * (which can't be imported here — pulling the barrel into this lean module bloats\n * the config-load path). Kept in sync by a type test in `defineApp.test.ts`.\n */\nconst APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n\n/**\n * Internal application discriminator. Sanity-owned singleton apps only;\n * validated by the schema but excluded from the public `DefineAppInput` type.\n */\nconst ApplicationType = z.enum(['coreApp', 'studio', 'canvas', 'dashboard'])\n\n/**\n * Runtime-validation schema for `defineApplication`.\n * @internal\n */\nexport const DefineAppInputSchema = z\n .object({\n /**\n * Internal — Sanity-owned singleton apps only. Validated here but excluded\n * from the public `DefineAppInput` type.\n * @internal\n */\n applicationType: z.optional(ApplicationType),\n /** Default placement inherited by window views. */\n dock: z.optional(DockSchema),\n /**\n * App entrypoint module. Defaults to `./src/App.tsx` when omitted. The build\n * derives the app's navigable `app` view from it. SDK apps only — setting it\n * on a studio is rejected (studio app views are not yet implemented).\n */\n entry: z.optional(z.string(\"must be a path to the app's entry file\")),\n /**\n * Path to the app's icon, relative to the project root: a PNG, JPEG, GIF,\n * WebP, SVG, BMP, TIFF, HEIF or AVIF image of at most 5 MB. Wins over\n * manifest/studio icon.\n */\n icon: z.optional(z.string()),\n /** Sanity-owned app deployed once and installed per org. @internal */\n isSingleton: z.optional(z.boolean()),\n /**\n * Stable identity, distinct from the `slug` address. Defaults to `slug` when\n * omitted. Identity keys — the build id and derived interface ids — are built\n * from this, so renaming the slug no longer changes identity.\n */\n name: z.optional(\n z\n .string()\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `name` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n ),\n /** Organization that owns the app — it runs in and deploys to this organization's Dashboard. */\n organizationId: z.string(\n \"App `organizationId` is required — pass the owning organization's ID to `defineApplication`\",\n ),\n slug: z\n .string('App `slug` is required — the hostname the application is created at on deploy')\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `slug` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n /** User-facing app title. Wins over studio.config.ts title on merge. */\n title: z.string(),\n /** Views the app exposes (e.g. a window, dock panels, and tiles). */\n views: z.optional(z.array(InterfaceDeclarationSchema, 'must be an array of views')),\n /** Dashboard visibility of the app. Defaults to `default` when omitted. */\n visibility: z.optional(z.enum(APP_VISIBILITIES)),\n /** Background web workers the app runs. */\n webWorkers: z.optional(z.array(WebWorkerDeclarationSchema, 'must be an array of web workers')),\n })\n .check(\n z.refine((input) => {\n const names = [\n ...(input.entry === undefined ? [] : [input.name ?? input.slug]),\n ...(input.views ?? []).map((view) => view.name),\n ...(input.webWorkers ?? []).map((webWorker) => webWorker.name),\n ]\n return new Set(names).size === names.length\n }, '`name` must be unique across views and web workers. Rename one of the duplicates.'),\n // Studio app views are not implemented yet. A studio that declares `entry`\n // (the SDK app-view entrypoint) is rejected here rather than silently\n // generating one; studios keep navigating via their existing render path.\n z.refine((input) => !(input.applicationType === 'studio' && input.entry !== undefined), {\n error: 'App views for studios are not implemented yet',\n path: ['entry'],\n }),\n )\n\n/**\n * User-facing input for `defineApplication`. Excludes the internal\n * `applicationType` and `isSingleton`.\n * @public\n */\nexport type DefineAppInput = Omit<\n z.output<typeof DefineAppInputSchema>,\n 'applicationType' | 'isSingleton'\n>\n\n/**\n * Nominal brand the CLI discriminates on to enable the workbench build/deploy\n * codepath. Registered via `Symbol.for` so the marker survives module-realm\n * boundaries — `@sanity/cli-core` re-derives the same global symbol with\n * `Symbol.for` rather than importing it, so it stays internal to this module.\n */\nconst WORKBENCH_APP: unique symbol = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * The branded result of `defineApplication`. Carries the same fields as the\n * input plus the internal brand — users only ever see `DefineAppInput`.\n * @public\n */\nexport type DefineAppResult = {\n [K in keyof DefineAppInput]: Exclude<DefineAppInput[K], undefined>\n} & {readonly [WORKBENCH_APP]: true}\n\n/**\n * A branded app as the CLI reads it — the full schema shape, including the\n * internal fields `DefineAppInput` omits. Schema-derived so the narrowing\n * can't drift from what the schema validates.\n * @public\n */\nexport type WorkbenchApp = DefineAppResult & z.output<typeof DefineAppInputSchema>\n\n/**\n * Whether `app` is a branded `defineApplication(...)` result — the sole\n * workbench opt-in.\n * @public\n */\nexport function isWorkbenchApp(app: unknown): app is WorkbenchApp {\n return typeof app === 'object' && app !== null && WORKBENCH_APP in app\n}\n\n/**\n * Declare a Sanity Dashboard application. Identity at runtime — returns the same\n * object reference, tagged with the Dashboard brand. Field validation (the\n * `slug` pattern etc.) runs at build time in the CLI via `DefineAppInputSchema`;\n * this helper stays a thin, pure identity wrapper.\n * @public\n */\nexport function defineApplication(input: DefineAppInput): DefineAppResult {\n return Object.defineProperty(input, WORKBENCH_APP, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n }) as DefineAppResult\n}\n\n/**\n * One custom field a media library exposes. `src` default-exports a `defineField(...)` schema type.\n * @public\n */\nexport interface MediaLibraryField {\n /** Unique within the media library. */\n name: string\n src: string\n title: string\n\n /** Readable outside the owning organization. */\n public?: boolean\n}\n\n/**\n * Sanity-owned singleton, so authors don't name or title the app — only `organizationId` is required.\n * @public\n */\nexport interface DefineMediaLibraryInput {\n /** Organization that owns the media library — the CLI runs and deploys against it. */\n organizationId: string\n\n fields?: MediaLibraryField[]\n}\n\n/**\n * Nominal brand the CLI discriminates a config on. A config is *not* an app: it\n * carries no `slug`/`title`/application identity, only a target `appType`, its\n * owning `organizationId`, and its `fields`. Registered via `Symbol.for` so the\n * marker survives module-realm boundaries — `@sanity/cli-core` re-derives the\n * same global symbol rather than importing it.\n */\nconst WORKBENCH_CONFIG: unique symbol = Symbol.for('sanity.workbench.defineConfig')\n\n/**\n * A branded workbench config as the CLI reads it: bound to its target app by\n * `appType`, not carrying its own app identity. The deploy/undeploy/build paths\n * discriminate it via {@link isWorkbenchConfig}.\n * @public\n */\nexport interface WorkbenchConfig {\n appType: 'media-library'\n fields: MediaLibraryField[]\n organizationId: string\n readonly [WORKBENCH_CONFIG]: true\n}\n\n/**\n * Whether `app` is a branded `unstable_defineMediaLibrary(...)` config — a\n * config-carrier rather than an app. Configs live in `cliConfig.app` alongside\n * apps but resolve through `resolveWorkbenchConfig`, not `resolveWorkbenchApp`.\n * @public\n */\nexport function isWorkbenchConfig(app: unknown): app is WorkbenchConfig {\n return typeof app === 'object' && app !== null && WORKBENCH_CONFIG in app\n}\n\n/**\n * Declare the Sanity Media Library config. The Media Library is a Sanity-owned\n * singleton, so this is not an app — it carries no slug or title, only the\n * target `appType`, its owning organization, and the `fields` it contributes to\n * the installation's config.\n * @public\n */\nexport function unstable_defineMediaLibrary(input: DefineMediaLibraryInput): WorkbenchConfig {\n return Object.defineProperty(\n {appType: 'media-library', fields: input.fields ?? [], organizationId: input.organizationId},\n WORKBENCH_CONFIG,\n {configurable: false, enumerable: false, value: true, writable: false},\n ) as WorkbenchConfig\n}\n"],"names":["z","APP_SLUG_PATTERN","DockSchema","InterfaceDeclarationSchema","WebWorkerDeclarationSchema","APP_VISIBILITIES","ApplicationType","enum","DefineAppInputSchema","object","applicationType","optional","dock","entry","string","icon","isSingleton","boolean","name","check","regex","organizationId","slug","title","views","array","visibility","webWorkers","refine","input","names","undefined","map","view","webWorker","Set","size","length","error","path","WORKBENCH_APP","Symbol","for","isWorkbenchApp","app","defineApplication","Object","defineProperty","configurable","enumerable","value","writable","WORKBENCH_CONFIG","isWorkbenchConfig","unstable_defineMediaLibrary","appType","fields"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,SAAQC,gBAAgB,QAAO,eAAc;AAC7C,SAAQC,UAAU,EAAEC,0BAA0B,EAAEC,0BAA0B,QAAO,gBAAe;AAEhG;;;;CAIC,GACD,MAAMC,mBAAmB;I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+
import { relative, resolve, sep } from 'node:path';
|
|
2
|
+
import { getErrorMessage } from '@sanity/cli-core/errors';
|
|
3
|
+
import { readImageFile } from '@sanity/cli-core/images';
|
|
4
|
+
/**
|
|
5
|
+
* Read the image `app.icon` points at. The path is relative to the project
|
|
6
|
+
* root and must stay inside it.
|
|
7
|
+
* @internal
|
|
8
|
+
*/ export async function readAppIcon(workDir, iconPath) {
|
|
9
|
+
const file = resolve(workDir, iconPath);
|
|
10
|
+
if (relative(workDir, file).startsWith('..')) {
|
|
11
|
+
throw new Error(`App icon "${iconPath}" is outside the project directory. Move the image into the project and update \`app.icon\` in sanity.cli.ts.`);
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
return {
|
|
15
|
+
...await readImageFile(file),
|
|
16
|
+
file
|
|
17
|
+
};
|
|
18
|
+
} catch (err) {
|
|
19
|
+
throw new Error(`Can't use app icon "${iconPath}": ${getErrorMessage(err)}`, {
|
|
20
|
+
cause: err
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The URL path a server rooted at `dir` serves `file` at, without a leading slash.
|
|
26
|
+
* @internal
|
|
27
|
+
*/ export function toUrlPath(dir, file) {
|
|
28
|
+
return relative(dir, file).split(sep).map((segment)=>encodeURIComponent(segment)).join('/');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=readAppIcon.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/readAppIcon.ts"],"sourcesContent":["import {relative, resolve, sep} from 'node:path'\n\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {type ImageFile, readImageFile} from '@sanity/cli-core/images'\n\n/**\n * An app's `icon` image, read from its project.\n * @internal\n */\nexport interface AppIcon extends ImageFile {\n /** Absolute path to the file. */\n file: string\n}\n\n/**\n * Read the image `app.icon` points at. The path is relative to the project\n * root and must stay inside it.\n * @internal\n */\nexport async function readAppIcon(workDir: string, iconPath: string): Promise<AppIcon> {\n const file = resolve(workDir, iconPath)\n if (relative(workDir, file).startsWith('..')) {\n throw new Error(\n `App icon \"${iconPath}\" is outside the project directory. Move the image into the project and update \\`app.icon\\` in sanity.cli.ts.`,\n )\n }\n\n try {\n return {...(await readImageFile(file)), file}\n } catch (err) {\n throw new Error(`Can't use app icon \"${iconPath}\": ${getErrorMessage(err)}`, {cause: err})\n }\n}\n\n/**\n * The URL path a server rooted at `dir` serves `file` at, without a leading slash.\n * @internal\n */\nexport function toUrlPath(dir: string, file: string): string {\n return relative(dir, file)\n .split(sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')\n}\n"],"names":["relative","resolve","sep","getErrorMessage","readImageFile","readAppIcon","workDir","iconPath","file","startsWith","Error","err","cause","toUrlPath","dir","split","map","segment","encodeURIComponent","join"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,EAAEC,GAAG,QAAO,YAAW;AAEhD,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAwBC,aAAa,QAAO,0BAAyB;AAWrE;;;;CAIC,GACD,OAAO,eAAeC,YAAYC,OAAe,EAAEC,QAAgB;IACjE,MAAMC,OAAOP,QAAQK,SAASC;IAC9B,IAAIP,SAASM,SAASE,MAAMC,UAAU,CAAC,OAAO;QAC5C,MAAM,IAAIC,MACR,CAAC,UAAU,EAAEH,SAAS,6GAA6G,CAAC;IAExI;IAEA,IAAI;QACF,OAAO;YAAC,GAAI,MAAMH,cAAcI,KAAK;YAAGA;QAAI;IAC9C,EAAE,OAAOG,KAAK;QACZ,MAAM,IAAID,MAAM,CAAC,oBAAoB,EAAEH,SAAS,GAAG,EAAEJ,gBAAgBQ,MAAM,EAAE;YAACC,OAAOD;QAAG;IAC1F;AACF;AAEA;;;CAGC,GACD,OAAO,SAASE,UAAUC,GAAW,EAAEN,IAAY;IACjD,OAAOR,SAASc,KAAKN,MAClBO,KAAK,CAACb,KACNc,GAAG,CAAC,CAACC,UAAYC,mBAAmBD,UACpCE,IAAI,CAAC;AACV"}
|
|
@@ -109,6 +109,24 @@ export async function updateApplication(applicationId, update) {
|
|
|
109
109
|
url: `/applications/${applicationId}`
|
|
110
110
|
});
|
|
111
111
|
}
|
|
112
|
+
/** Upload the application's icon, replacing any it has. */ export async function setApplicationIcon(applicationId, icon) {
|
|
113
|
+
const client = await getClient();
|
|
114
|
+
await client.request({
|
|
115
|
+
body: icon.image,
|
|
116
|
+
headers: {
|
|
117
|
+
'Content-Type': icon.contentType
|
|
118
|
+
},
|
|
119
|
+
method: 'PUT',
|
|
120
|
+
url: `/applications/${applicationId}/icon`
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/** Remove the application's icon; removing one that isn't set changes nothing. */ export async function removeApplicationIcon(applicationId) {
|
|
124
|
+
const client = await getClient();
|
|
125
|
+
await client.request({
|
|
126
|
+
method: 'DELETE',
|
|
127
|
+
url: `/applications/${applicationId}/icon`
|
|
128
|
+
});
|
|
129
|
+
}
|
|
112
130
|
/**
|
|
113
131
|
* Deploy a new active version to an existing application. `mfManifest` is the
|
|
114
132
|
* build's federation manifest; `tarball` is omitted for an external application,
|
|
@@ -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' | '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\nexport async function getOrganizationApplication(\n organizationId: string,\n idOrSlug: string,\n signal?: AbortSignal,\n): Promise<\n (Application & {activeDeployment: {createdAt: string; deployedBy: string} | null}) | null\n> {\n const client = await getGlobalCliClient({\n apiVersion: APP_WORKBENCH_API_VERSION,\n ignoreWarnings: ['This is an experimental API version', 'which will change without warning'],\n requireUser: true,\n })\n try {\n return await client.request({\n query: {include: 'activeDeployment'},\n signal,\n url: `/organizations/${organizationId}/applications/${idOrSlug}`,\n })\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","getOrganizationApplication","idOrSlug","signal","ignoreWarnings","query","include","listApplications","data","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,MAAMC,SAAS,MAAML;IACrB,IAAI;QACF,OAAO,MAAMK,OAAOC,OAAO,CAAC;YAACC,KAAK,CAAC,cAAc,EAAE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ASC,MAAM,CAAC,WAAWH;IAC3BO,WAAWL,UAAU,cAAcN;IACnC,0EAA0E;IAC1E,IAAIK,YAAYO,QAAQD,WAAWL,UAAU,cAAcD;IAC3D,sEAAsE;IACtE,IAAIN,QAAQa,QAAQD,WAAWL,UAAU,UAAUP;IACnDY,WAAWL,UAAU,cAAcJ;IACnC,qEAAqE;IACrE,IAAIC,SAAS;QACXG,SAASC,MAAM,CAAC,WAAWJ,SAAS;YAACU,aAAa;YAAoBC,UAAU;QAAY;IAC9F;AACF;AAEA,oEAAoE,GACpE,SAASH,WAAWL,QAAkB,EAAEnB,IAAY,EAAE4B,KAAc;IAClET,SAASC,MAAM,CAACpB,MAAM6B,KAAKC,SAAS,CAACF,QAAQ;QAACF,aAAa;IAAkB;AAC/E;AAEA,eAAe3C,QAAWC,GAAW,EAAEmC,QAAkB;IACvD,MAAMrC,SAAS,MAAML;IACrB,OAAOK,OAAOC,OAAO,CAAC;QACpBqB,MAAMe,SAASY,IAAI,CAAC,IAAInE;QACxBoE,SAASb,SAASc,UAAU;QAC5BzB,QAAQ;QACRxB;IACF;AACF"}
|
|
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 {type ImageFile} from '@sanity/cli-core/images'\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\nexport async function getOrganizationApplication(\n organizationId: string,\n idOrSlug: string,\n signal?: AbortSignal,\n): Promise<\n (Application & {activeDeployment: {createdAt: string; deployedBy: string} | null}) | null\n> {\n const client = await getGlobalCliClient({\n apiVersion: APP_WORKBENCH_API_VERSION,\n ignoreWarnings: ['This is an experimental API version', 'which will change without warning'],\n requireUser: true,\n })\n try {\n return await client.request({\n query: {include: 'activeDeployment'},\n signal,\n url: `/organizations/${organizationId}/applications/${idOrSlug}`,\n })\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 /** 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/** Upload the application's icon, replacing any it has. */\nexport async function setApplicationIcon(applicationId: string, icon: ImageFile): Promise<void> {\n const client = await getClient()\n await client.request({\n body: icon.image,\n headers: {'Content-Type': icon.contentType},\n method: 'PUT',\n url: `/applications/${applicationId}/icon`,\n })\n}\n\n/** Remove the application's icon; removing one that isn't set changes nothing. */\nexport async function removeApplicationIcon(applicationId: string): Promise<void> {\n const client = await getClient()\n await client.request({method: 'DELETE', url: `/applications/${applicationId}/icon`})\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","getOrganizationApplication","idOrSlug","signal","ignoreWarnings","query","include","listApplications","data","limit","createApplication","options","externalUrl","isSingleton","name","projectId","title","visibility","body","undefined","config","studio","method","updateApplication","update","setApplicationIcon","icon","image","headers","contentType","removeApplicationIcon","createDeployment","access","interfaces","isAutoUpdating","mfManifest","tarball","version","workspaces","formData","append","toString","appendDeploymentParts","deleteApplication","appendJson","length","filename","value","JSON","stringify","pipe","getHeaders"],"mappings":"AAAA,SAAQA,WAAW,QAAO,cAAa;AAGvC,SAA4BC,kBAAkB,QAAO,mBAAkB;AAEvE,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,GAA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AAKC,SAAS,CAACF,QAAQ;QAAClB,aAAa;IAAkB;AAC/E;AAEA,eAAehC,QAAWC,GAAW,EAAEyC,QAAkB;IACvD,MAAM3C,SAAS,MAAML;IACrB,OAAOK,OAAOC,OAAO,CAAC;QACpBqB,MAAMqB,SAASW,IAAI,CAAC,IAAIxE;QACxBkD,SAASW,SAASY,UAAU;QAC5B7B,QAAQ;QACRxB;IACF;AACF"}
|
package/dist/webWorker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webWorker.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../src/webWorker.ts"],"sourcesContent":["import {type WebWorkerProps} from '@sanity/sdk/dashboard'\n\nimport {WEB_WORKER_CONTRACT_VERSION, type WebWorkerType} from './contract.js'\n\nexport type {WebWorkerProps} from '@sanity/sdk/dashboard'\n\n/**\n * @deprecated Use `WebWorkerProps['worker']`.\n * @public\n */\nexport type WebWorkerInfo = WebWorkerProps['worker']\n\n/**\n * @deprecated Use `WebWorkerProps['bus']`.\n * @public\n */\nexport type WebWorkerBus = WebWorkerProps['bus']\n\n/**\n * Context every service callback receives when its worker starts. Mirrors how a\n * view component receives its `view` — the service receives its own `service`.\n * @deprecated Use {@link WebWorkerProps}.\n * @public\n */\nexport interface ServiceContext {\n readonly bus: WebWorkerProps['bus']\n readonly service: WebWorkerProps['worker']\n}\n\n/**\n * A service callback. Runs once inside the worker on start; returns an optional\n * disposer the host calls before terminating the worker.\n * @deprecated Default-export a plain function that receives {@link WebWorkerProps} instead.\n * @public\n */\nexport type ServiceCallback = (context: ServiceContext) => (() => void) | void\n\n/** The callback shape each service type defines, keyed by type. */\ninterface ServiceCallbacksByType {\n worker: ServiceCallback\n}\n\n/**\n * The result of `unstable_defineService`: the author's callback, the service\n * type, and the internal contract version the worker artifact targets.\n * @deprecated Default-export a plain function that receives {@link WebWorkerProps} instead.\n * @public\n */\nexport interface DefinedService<TType extends WebWorkerType = WebWorkerType> {\n readonly run: ServiceCallbacksByType[TType]\n readonly type: TType\n /** @internal */\n readonly version: typeof WEB_WORKER_CONTRACT_VERSION\n}\n\n/**\n * Define a Sanity Dashboard background service. The first argument narrows the\n * callback shape — `\"worker\"` runs the callback inside a Web Worker with the\n * bus described on {@link WebWorkerProps}.\n *\n * Identity at runtime: returns the callback tagged with its type and the contract\n * version, for the CLI build to generate a worker artifact from. Used as the\n * default export of a service's `src` file.\n * @deprecated Default-export a plain function that receives {@link WebWorkerProps} from the web worker's `src` file instead.\n * @public\n */\nexport function unstable_defineService<TType extends WebWorkerType>(\n type: TType,\n run: ServiceCallbacksByType[TType],\n): DefinedService<TType> {\n return {run, type, version: WEB_WORKER_CONTRACT_VERSION}\n}\n\n/**\n * @deprecated Use `WebWorkerProps['bus']`.\n * @public\n */\nexport type ServiceBus = WebWorkerProps['bus']\n\n/**\n * @deprecated Use `WebWorkerProps['worker']`.\n * @public\n */\nexport type ServiceInfo = WebWorkerProps['worker']\n"],"names":["WEB_WORKER_CONTRACT_VERSION","unstable_defineService","type","run","version"],"mappings":"AAEA,SAAQA,2BAA2B,QAA2B,gBAAe;AAqD7E;;;;;;;;;;CAUC,GACD,OAAO,SAASC,uBACdC,IAAW,EACXC,GAAkC;IAElC,OAAO;QAACA;QAAKD;QAAME,SAASJ;IAA2B;AACzD"}
|