@fluid-app/fluid-cli-portal 0.1.132 → 0.1.134

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.
@@ -1,4 +1,4 @@
1
- import { P as __exportAll } from "./pull-C9a0z-7O.mjs";
1
+ import { P as __exportAll } from "./pull-C0FfNCju.mjs";
2
2
  //#region src/vite-plugin/backend-dev-plugin.ts
3
3
  var backend_dev_plugin_exports = /* @__PURE__ */ __exportAll({ backendDevPlugin: () => backendDevPlugin });
4
4
  /**
@@ -62,4 +62,4 @@ function serve(res, contentType, body) {
62
62
  //#endregion
63
63
  export { backend_dev_plugin_exports as n, backendDevPlugin as t };
64
64
 
65
- //# sourceMappingURL=backend-dev-plugin-B7rf1lmf.mjs.map
65
+ //# sourceMappingURL=backend-dev-plugin-D6TO2XUQ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"backend-dev-plugin-B7rf1lmf.mjs","names":[],"sources":["../src/vite-plugin/backend-dev-plugin.ts"],"sourcesContent":["import type { Plugin } from \"vite\";\n\nexport interface BackendDevPluginOptions {\n /** Entry module path relative to project root. @default \"/src/main.tsx\" */\n entry?: string;\n /** Production chunk filenames to stub as empty ES modules. */\n chunks?: string[];\n}\n\n/**\n * Serves dev-compatible responses at production asset paths so the Rails\n * backend can point `PORTAL_CDN_BASE` at `http://localhost:5173` and get\n * HMR + live source without any template changes.\n *\n * Handles:\n * - `/portal.js` → ESM shim that loads `@vite/client` + the real entry\n * - `/portal.css` → empty (Vite injects CSS via JS in dev)\n * - `/vendor.js`, `/query.js` → empty ES modules (no chunks in dev)\n */\nexport function backendDevPlugin(options?: BackendDevPluginOptions): Plugin {\n const entry = options?.entry ?? \"/src/main.tsx\";\n const chunks = options?.chunks ?? [\"vendor.js\", \"query.js\"];\n\n return {\n name: \"fluid-backend-dev\",\n apply: \"serve\",\n\n // Register BEFORE Vite's SPA fallback so these paths don't\n // get caught by the index.html catch-all.\n configureServer(server) {\n // Idempotency guard: the CLI injects this plugin and a vite.config may\n // also wire it — only register the middleware once.\n const flagged = server as unknown as { __fluidBackendDevWired?: boolean };\n if (flagged.__fluidBackendDevWired) return;\n flagged.__fluidBackendDevWired = true;\n\n server.middlewares.use((req, res, next) => {\n const raw = req.url ?? \"\";\n const qIndex = raw.indexOf(\"?\");\n const url = qIndex === -1 ? raw : raw.slice(0, qIndex);\n\n if (url === \"/portal.js\") {\n serve(\n res,\n \"application/javascript\",\n [\n `globalThis.__FLUID_PORTAL_DEV_ORIGIN__ = new URL(import.meta.url).origin;`,\n `import RefreshRuntime from \"/@react-refresh\";`,\n `import \"/@vite/client\";`,\n `RefreshRuntime.injectIntoGlobalHook(window);`,\n `window.$RefreshReg$ = () => {};`,\n `window.$RefreshSig$ = () => (type) => type;`,\n `window.__vite_plugin_react_preamble_installed__ = true;`,\n `await import(\"${entry}\");`,\n ].join(\"\\n\"),\n );\n return;\n }\n\n if (url === \"/portal.css\") {\n serve(res, \"text/css\", \"/* dev: CSS injected via JS */\");\n return;\n }\n\n const chunkName = url.startsWith(\"/\") ? url.slice(1) : url;\n if (chunks.includes(chunkName)) {\n serve(res, \"application/javascript\", \"export {};\");\n return;\n }\n\n next();\n });\n },\n };\n}\n\nfunction serve(\n res: import(\"http\").ServerResponse,\n contentType: string,\n body: string,\n) {\n res.setHeader(\"Content-Type\", `${contentType}; charset=utf-8`);\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.statusCode = 200;\n res.end(body);\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,SAAgB,iBAAiB,SAA2C;CAC1E,MAAM,QAAQ,SAAS,SAAS;CAChC,MAAM,SAAS,SAAS,UAAU,CAAC,aAAa,WAAW;AAE3D,QAAO;EACL,MAAM;EACN,OAAO;EAIP,gBAAgB,QAAQ;GAGtB,MAAM,UAAU;AAChB,OAAI,QAAQ,uBAAwB;AACpC,WAAQ,yBAAyB;AAEjC,UAAO,YAAY,KAAK,KAAK,KAAK,SAAS;IACzC,MAAM,MAAM,IAAI,OAAO;IACvB,MAAM,SAAS,IAAI,QAAQ,IAAI;IAC/B,MAAM,MAAM,WAAW,KAAK,MAAM,IAAI,MAAM,GAAG,OAAO;AAEtD,QAAI,QAAQ,cAAc;AACxB,WACE,KACA,0BACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA,iBAAiB,MAAM;MACxB,CAAC,KAAK,KAAK,CACb;AACD;;AAGF,QAAI,QAAQ,eAAe;AACzB,WAAM,KAAK,YAAY,iCAAiC;AACxD;;IAGF,MAAM,YAAY,IAAI,WAAW,IAAI,GAAG,IAAI,MAAM,EAAE,GAAG;AACvD,QAAI,OAAO,SAAS,UAAU,EAAE;AAC9B,WAAM,KAAK,0BAA0B,aAAa;AAClD;;AAGF,UAAM;KACN;;EAEL;;AAGH,SAAS,MACP,KACA,aACA,MACA;AACA,KAAI,UAAU,gBAAgB,GAAG,YAAY,iBAAiB;AAC9D,KAAI,UAAU,iBAAiB,WAAW;AAC1C,KAAI,UAAU,+BAA+B,IAAI;AACjD,KAAI,aAAa;AACjB,KAAI,IAAI,KAAK"}
1
+ {"version":3,"file":"backend-dev-plugin-D6TO2XUQ.mjs","names":[],"sources":["../src/vite-plugin/backend-dev-plugin.ts"],"sourcesContent":["import type { Plugin } from \"vite\";\n\nexport interface BackendDevPluginOptions {\n /** Entry module path relative to project root. @default \"/src/main.tsx\" */\n entry?: string;\n /** Production chunk filenames to stub as empty ES modules. */\n chunks?: string[];\n}\n\n/**\n * Serves dev-compatible responses at production asset paths so the Rails\n * backend can point `PORTAL_CDN_BASE` at `http://localhost:5173` and get\n * HMR + live source without any template changes.\n *\n * Handles:\n * - `/portal.js` → ESM shim that loads `@vite/client` + the real entry\n * - `/portal.css` → empty (Vite injects CSS via JS in dev)\n * - `/vendor.js`, `/query.js` → empty ES modules (no chunks in dev)\n */\nexport function backendDevPlugin(options?: BackendDevPluginOptions): Plugin {\n const entry = options?.entry ?? \"/src/main.tsx\";\n const chunks = options?.chunks ?? [\"vendor.js\", \"query.js\"];\n\n return {\n name: \"fluid-backend-dev\",\n apply: \"serve\",\n\n // Register BEFORE Vite's SPA fallback so these paths don't\n // get caught by the index.html catch-all.\n configureServer(server) {\n // Idempotency guard: the CLI injects this plugin and a vite.config may\n // also wire it — only register the middleware once.\n const flagged = server as unknown as { __fluidBackendDevWired?: boolean };\n if (flagged.__fluidBackendDevWired) return;\n flagged.__fluidBackendDevWired = true;\n\n server.middlewares.use((req, res, next) => {\n const raw = req.url ?? \"\";\n const qIndex = raw.indexOf(\"?\");\n const url = qIndex === -1 ? raw : raw.slice(0, qIndex);\n\n if (url === \"/portal.js\") {\n serve(\n res,\n \"application/javascript\",\n [\n `globalThis.__FLUID_PORTAL_DEV_ORIGIN__ = new URL(import.meta.url).origin;`,\n `import RefreshRuntime from \"/@react-refresh\";`,\n `import \"/@vite/client\";`,\n `RefreshRuntime.injectIntoGlobalHook(window);`,\n `window.$RefreshReg$ = () => {};`,\n `window.$RefreshSig$ = () => (type) => type;`,\n `window.__vite_plugin_react_preamble_installed__ = true;`,\n `await import(\"${entry}\");`,\n ].join(\"\\n\"),\n );\n return;\n }\n\n if (url === \"/portal.css\") {\n serve(res, \"text/css\", \"/* dev: CSS injected via JS */\");\n return;\n }\n\n const chunkName = url.startsWith(\"/\") ? url.slice(1) : url;\n if (chunks.includes(chunkName)) {\n serve(res, \"application/javascript\", \"export {};\");\n return;\n }\n\n next();\n });\n },\n };\n}\n\nfunction serve(\n res: import(\"http\").ServerResponse,\n contentType: string,\n body: string,\n) {\n res.setHeader(\"Content-Type\", `${contentType}; charset=utf-8`);\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.statusCode = 200;\n res.end(body);\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,SAAgB,iBAAiB,SAA2C;CAC1E,MAAM,QAAQ,SAAS,SAAS;CAChC,MAAM,SAAS,SAAS,UAAU,CAAC,aAAa,WAAW;AAE3D,QAAO;EACL,MAAM;EACN,OAAO;EAIP,gBAAgB,QAAQ;GAGtB,MAAM,UAAU;AAChB,OAAI,QAAQ,uBAAwB;AACpC,WAAQ,yBAAyB;AAEjC,UAAO,YAAY,KAAK,KAAK,KAAK,SAAS;IACzC,MAAM,MAAM,IAAI,OAAO;IACvB,MAAM,SAAS,IAAI,QAAQ,IAAI;IAC/B,MAAM,MAAM,WAAW,KAAK,MAAM,IAAI,MAAM,GAAG,OAAO;AAEtD,QAAI,QAAQ,cAAc;AACxB,WACE,KACA,0BACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA,iBAAiB,MAAM;MACxB,CAAC,KAAK,KAAK,CACb;AACD;;AAGF,QAAI,QAAQ,eAAe;AACzB,WAAM,KAAK,YAAY,iCAAiC;AACxD;;IAGF,MAAM,YAAY,IAAI,WAAW,IAAI,GAAG,IAAI,MAAM,EAAE,GAAG;AACvD,QAAI,OAAO,SAAS,UAAU,EAAE;AAC9B,WAAM,KAAK,0BAA0B,aAAa;AAClD;;AAGF,UAAM;KACN;;EAEL;;AAGH,SAAS,MACP,KACA,aACA,MACA;AACA,KAAI,UAAU,gBAAgB,GAAG,YAAY,iBAAiB;AAC9D,KAAI,UAAU,iBAAiB,WAAW;AAC1C,KAAI,UAAU,+BAA+B,IAAI;AACjD,KAAI,aAAa;AACjB,KAAI,IAAI,KAAK"}
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { A as fluidOsApi, C as removeMapping, D as writeMappings, E as updateMapping, M as createFluidOsHeyApiClient, N as ApiError, O as atomicWriteFile, S as readMappings, T as resolveSlugToId, _ as diffAgainstSnapshot, a as buildNavigationIdToSlugMap, b as writeSnapshot, c as transformNavigation, d as transformScreen, f as transformTheme, g as computeFileHash, h as collectWidgetCapabilityGrants, i as buildIdToSlugMap, j as toFluidOsDynamicObject, k as createFluidOsClient, l as transformNavigationItems, m as collectSnapshotWidgetCapabilityGrants, o as buildThemeIdToSlugMap, p as buildSnapshot, r as validatePortalResource, s as deriveScreenSlug, t as pullCommand, u as transformProfile, v as readSnapshot, w as resolveIdToSlug, x as deriveSlug, y as selectLegacyNetworkWidgetGrants } from "./pull-C9a0z-7O.mjs";
2
- import { l as fluidOsV0DefinitionGitCredentialCreate } from "./sdk.gen-VRGYiLVJ.mjs";
3
- import { a as resolvePublishVersion, d as isRemoteDomWidgetPackageDescriptor, i as readCompanyWidgetPackages, n as preflightCompanyPackage, o as loadAndValidateWidgetPackage, r as readCompanyWidgetPackage, s as publishWidgetPackage, t as formatPackageKeyMismatch } from "./src-BuSYN4Co.mjs";
1
+ import { A as fluidOsApi, C as removeMapping, D as writeMappings, E as updateMapping, M as createFluidOsHeyApiClient, N as ApiError, O as atomicWriteFile, S as readMappings, T as resolveSlugToId, _ as diffAgainstSnapshot, a as buildNavigationIdToSlugMap, b as writeSnapshot, c as transformNavigation, d as transformScreen, f as transformTheme, g as computeFileHash, h as collectWidgetCapabilityGrants, i as buildIdToSlugMap, j as toFluidOsDynamicObject, k as createFluidOsClient, l as transformNavigationItems, m as collectSnapshotWidgetCapabilityGrants, o as buildThemeIdToSlugMap, p as buildSnapshot, r as validatePortalResource, s as deriveScreenSlug, t as pullCommand, u as transformProfile, v as readSnapshot, w as resolveIdToSlug, x as deriveSlug, y as selectLegacyNetworkWidgetGrants } from "./pull-C0FfNCju.mjs";
2
+ import { l as fluidOsV0DefinitionGitCredentialCreate } from "./sdk.gen-qjewNLc_.mjs";
3
+ import { a as resolvePublishVersion, d as isRemoteDomWidgetPackageDescriptor, i as readCompanyWidgetPackages, n as preflightCompanyPackage, o as loadAndValidateWidgetPackage, r as readCompanyWidgetPackage, s as publishWidgetPackage, t as formatPackageKeyMismatch } from "./src-Dz9-qBBA.mjs";
4
4
  import { Command } from "commander";
5
5
  import chalk from "chalk";
6
6
  import ora from "ora";
@@ -96,9 +96,9 @@ async function promptProjectConfig(projectName, options) {
96
96
  //#endregion
97
97
  //#region src/utils/file-system.ts
98
98
  const _currentDir$1 = dirname(fileURLToPath(import.meta.url));
99
- const EMBEDDED_PORTAL_SDK_VERSION = "0.1.534";
100
- const EMBEDDED_CLI_CORE_VERSION = "0.1.35";
101
- const EMBEDDED_CLI_PORTAL_VERSION = "0.1.132";
99
+ const EMBEDDED_PORTAL_SDK_VERSION = "0.1.535";
100
+ const EMBEDDED_CLI_CORE_VERSION = "0.1.36";
101
+ const EMBEDDED_CLI_PORTAL_VERSION = "0.1.134";
102
102
  /**
103
103
  * Find the package root by walking up from the current directory to the nearest package.json.
104
104
  * Works whether running from dist/ (bundled) or src/utils/ (tsx dev mode).
@@ -1666,7 +1666,7 @@ async function autoPull(cwd) {
1666
1666
  console.log(chalk.yellow("No portal/ directory found.") + " Attempting to pull content...");
1667
1667
  console.log();
1668
1668
  try {
1669
- const { pullCommand } = await import("./pull-C9a0z-7O.mjs").then((n) => n.n);
1669
+ const { pullCommand } = await import("./pull-C0FfNCju.mjs").then((n) => n.n);
1670
1670
  await pullCommand.parseAsync([], { from: "user" });
1671
1671
  return hasPortalContent(cwd);
1672
1672
  } catch (err) {
@@ -1719,9 +1719,9 @@ const devCommand = new Command("dev").description("Start the development server
1719
1719
  const port = Number.isFinite(parsedPort) ? parsedPort : 5173;
1720
1720
  try {
1721
1721
  const { createServer } = await import("vite");
1722
- const { portalDevPlugin } = await import("./portal-dev-plugin-uSNQdb4E.mjs").then((n) => n.n);
1723
- const { backendDevPlugin } = await import("./backend-dev-plugin-B7rf1lmf.mjs").then((n) => n.n);
1724
- const { portalWidgetDevPlugin } = await import("./portal-widget-dev-plugin-rJTEEYgh.mjs").then((n) => n.n);
1722
+ const { portalDevPlugin } = await import("./portal-dev-plugin-Dj0r6n7v.mjs").then((n) => n.n);
1723
+ const { backendDevPlugin } = await import("./backend-dev-plugin-D6TO2XUQ.mjs").then((n) => n.n);
1724
+ const { portalWidgetDevPlugin } = await import("./portal-widget-dev-plugin-BjXiFpX5.mjs").then((n) => n.n);
1725
1725
  const server = await createServer({
1726
1726
  configFile: viteConfigPath,
1727
1727
  envPrefix: ["VITE_", "NEXT_PUBLIC_"],
@@ -1,4 +1,4 @@
1
- import { P as __exportAll } from "./pull-C9a0z-7O.mjs";
1
+ import { P as __exportAll } from "./pull-C0FfNCju.mjs";
2
2
  import { buildManifestFromLocalFiles } from "./build-manifest.mjs";
3
3
  import { join, resolve, sep } from "node:path";
4
4
  import { existsSync, readFileSync } from "node:fs";
@@ -228,4 +228,4 @@ function portalDevPlugin(options) {
228
228
  //#endregion
229
229
  export { portal_dev_plugin_exports as n, portalDevPlugin as t };
230
230
 
231
- //# sourceMappingURL=portal-dev-plugin-uSNQdb4E.mjs.map
231
+ //# sourceMappingURL=portal-dev-plugin-Dj0r6n7v.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"portal-dev-plugin-uSNQdb4E.mjs","names":[],"sources":["../src/vite-plugin/portal-dev-plugin.ts"],"sourcesContent":["/**\n * Vite plugin for local portal content development.\n *\n * Intercepts the manifest API request and serves content assembled from the\n * local `portal/` directory. Watches portal files for changes and triggers a\n * full page reload.\n *\n * The manifest is intercepted on BOTH paths the SDK has used across versions\n * (`/api/app/manifest` since portal-sdk 0.1.4xx, `/api/fluid_os/definitions/\n * active` before that) so a newer SDK against an older-generation app — or\n * vice versa — still gets the local draft.\n */\n\nimport { join, resolve, sep } from \"node:path\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { getAuthToken, getFluidApiBase } from \"@fluid-app/fluid-cli\";\nimport { buildManifestFromLocalFiles } from \"./build-manifest.js\";\n\n/** Options for the portal dev plugin. */\nexport interface PortalDevPluginOptions {\n portalDir?: string;\n /**\n * When true (default), dev-server requests are forced same-origin: the\n * plugin blanks `import.meta.env.VITE_API_URL` in serve mode and proxies\n * `/api` to the configured Fluid host instead. Without this, a `.env`\n * pointing VITE_API_URL at a remote API makes the SPA fetch its manifest\n * cross-origin — silently bypassing this plugin and rendering the remote\n * app instead of the local `portal/` draft. Set false to opt out and let\n * the SPA call the remote API directly.\n */\n sameOriginDev?: boolean;\n /**\n * Override the `/api` dev-proxy target. Defaults to VITE_API_URL from the\n * process env / .env files, then the authenticated company's\n * `<subdomain>.portal.fluid.app` tenant BFF, then https://api.fluid.app.\n */\n apiProxyTarget?: string;\n /**\n * Override tenant-target discovery. Primarily useful to keep embedded plugin\n * integrations and tests deterministic.\n */\n resolveTenantApiTarget?: () => Promise<string | undefined>;\n}\n\nconst DEBOUNCE_MS = 100;\n\n/** Manifest endpoints across SDK generations — all serve the local draft. */\nconst MANIFEST_PATHS = [\n \"/api/app/manifest\",\n \"/api/fluid_os/definitions/active\",\n];\n\nconst DEFAULT_API_URL = \"https://api.fluid.app\";\nconst TENANT_LOOKUP_TIMEOUT_MS = 3_000;\nconst tenantTargetPromises = new WeakMap<\n () => Promise<string | undefined>,\n Promise<string | undefined>\n>();\n\ninterface CompanyMeResponse {\n data?: {\n company?: {\n subdomain?: unknown;\n };\n };\n}\n\nexport interface TenantApiTargetDependencies {\n token?: string | null;\n apiBase?: string;\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n}\n\n/**\n * Resolve the portal tenant BFF for the CLI's project-aware Fluid profile.\n *\n * Portal member APIs do not live on api.fluid.app or `<tenant>.fluid.app`.\n * Their OpenAPI server is `<tenant>.portal.fluid.app`, and using either of\n * the former hosts produces a wall of unrelated 404s in otherwise-valid\n * local portals.\n */\nexport async function resolvePortalTenantApiTarget(\n dependencies: TenantApiTargetDependencies = {},\n): Promise<string | undefined> {\n const token =\n dependencies.token !== undefined ? dependencies.token : getAuthToken();\n if (!token) return undefined;\n\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(),\n dependencies.timeoutMs ?? TENANT_LOOKUP_TIMEOUT_MS,\n );\n\n try {\n const response = await (dependencies.fetchImpl ?? fetch)(\n `${(dependencies.apiBase ?? getFluidApiBase()).replace(/\\/+$/, \"\")}/api/company/v1/companies/me`,\n {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: \"application/json\",\n },\n signal: controller.signal,\n },\n );\n if (!response.ok) return undefined;\n\n const body = (await response.json()) as CompanyMeResponse;\n const subdomain = body.data?.company?.subdomain;\n if (\n typeof subdomain !== \"string\" ||\n !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(subdomain)\n ) {\n return undefined;\n }\n\n return `https://${subdomain}.portal.fluid.app`;\n } catch {\n return undefined;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Fallback .env reader for VITE_API_URL, used only when vite's `loadEnv`\n * can't be imported (it's a declared dependency, so this is defensive — but\n * a broken install must degrade to \"wrong host\" rather than \"dev server\n * won't boot\"). Mirrors the basic lookup order: live env > .env.local >\n * .env. Unlike loadEnv it ignores .env.[mode] files and variable expansion.\n */\nfunction readViteApiUrlFallback(root: string): string | undefined {\n if (process.env.VITE_API_URL) return process.env.VITE_API_URL;\n if (process.env.NEXT_PUBLIC_API_BASE_URL) {\n return process.env.NEXT_PUBLIC_API_BASE_URL;\n }\n for (const file of [\".env.local\", \".env\"]) {\n const path = join(root, file);\n if (!existsSync(path)) continue;\n for (const line of readFileSync(path, \"utf8\").split(\"\\n\")) {\n // Quoted values stop at the closing `\"`; unquoted values stop before\n // an inline ` # comment` tail (dotenv semantics — a trailing comment\n // must not leak into the proxy target URL).\n const match =\n /^\\s*VITE_API_URL\\s*=\\s*(?:\"([^\"]*)\"|(.*?))\\s*(?:#.*)?$/.exec(line);\n const value = match?.[1] ?? match?.[2];\n if (value) return value;\n }\n }\n return undefined;\n}\n\nfunction storefrontSubdomainFromTarget(target: string): string | undefined {\n try {\n const hostname = new URL(target).hostname;\n const match = /^([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\\.fluid\\.app$/.exec(\n hostname,\n );\n const subdomain = match?.[1];\n if (\n !subdomain ||\n [\"admin\", \"api\", \"app\", \"docs\", \"portal\", \"upload\"].includes(subdomain)\n ) {\n return undefined;\n }\n return subdomain;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve VITE_API_URL the way vite itself would — `loadEnv` honors\n * .env.[mode], .env.[mode].local, envDir, and variable expansion, which the\n * fallback parser does not (a mode-specific staging API must not silently\n * fall back to production).\n */\nasync function resolveViteApiUrl(\n root: string,\n mode: string,\n envDir: string | undefined,\n): Promise<string | undefined> {\n try {\n const { loadEnv } = await import(\"vite\");\n const env = loadEnv(mode, envDir ?? root, [\"VITE_\", \"NEXT_PUBLIC_\"]);\n return (\n env.VITE_API_URL ||\n process.env.VITE_API_URL ||\n // Portals migrated from Next.js conventions configure the API host as\n // NEXT_PUBLIC_API_BASE_URL — honored by `fluid portal dev` since it\n // was introduced, so it stays a recognized source here.\n env.NEXT_PUBLIC_API_BASE_URL ||\n process.env.NEXT_PUBLIC_API_BASE_URL ||\n undefined\n );\n } catch {\n return readViteApiUrlFallback(root);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function portalDevPlugin(options?: PortalDevPluginOptions): any {\n let portalDir: string;\n let cachedManifest: string | null = null;\n let buildInFlight: Promise<string> | null = null;\n /** Bumped on every watched file change. A build carries the value it\n * started under; if it no longer matches when the build resolves, the\n * build read pre-edit state and must not be cached. */\n let manifestGeneration = 0;\n const resolveTenantTarget =\n options?.resolveTenantApiTarget ?? resolvePortalTenantApiTarget;\n\n return {\n name: \"fluid-portal-dev\",\n enforce: \"pre\" as const,\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async config(config: any, env: any) {\n if (env?.command !== \"serve\" || options?.sameOriginDev === false) {\n return {};\n }\n\n const root: string = config.root ?? process.cwd();\n const appDefinesProxy = config.server?.proxy?.[\"/api\"] !== undefined;\n const configuredTarget =\n options?.apiProxyTarget || appDefinesProxy\n ? undefined\n : await resolveViteApiUrl(\n root,\n env?.mode ?? \"development\",\n config.envDir,\n );\n const tenantTarget =\n options?.apiProxyTarget || appDefinesProxy || configuredTarget\n ? undefined\n : await (() => {\n const existing = tenantTargetPromises.get(resolveTenantTarget);\n if (existing) return existing;\n\n const pending = resolveTenantTarget();\n tenantTargetPromises.set(resolveTenantTarget, pending);\n return pending;\n })();\n const target =\n options?.apiProxyTarget ??\n configuredTarget ??\n tenantTarget ??\n DEFAULT_API_URL;\n const storefrontSubdomain = storefrontSubdomainFromTarget(target);\n\n if (tenantTarget) {\n console.log(`[fluid-portal-dev] Tenant API proxy: ${tenantTarget}`);\n console.log(\n \"[fluid-portal-dev] Member data still requires a portal handoff session; localhost requests may return 401.\",\n );\n } else if (\n !options?.apiProxyTarget &&\n !appDefinesProxy &&\n !configuredTarget\n ) {\n console.warn(\n `[fluid-portal-dev] Could not resolve the company tenant API; falling back to ${DEFAULT_API_URL}. ` +\n \"Built-in member screens may not load. Set VITE_API_URL explicitly or sign in with the project's Fluid profile.\",\n );\n } else if (storefrontSubdomain) {\n console.warn(\n `[fluid-portal-dev] ${target} is the storefront host, not the Portal tenant BFF. ` +\n `Built-in member APIs live at https://${storefrontSubdomain}.portal.fluid.app; remove the override to let the CLI resolve it.`,\n );\n }\n\n // Vite merges a plugin's returned config OVER the user config, so an\n // app's own explicit define / /api proxy is only preserved by checking\n // for it and yielding here. BOTH API-host env vars must be blanked:\n // dev.ts's envPrefix exposes NEXT_PUBLIC_API_BASE_URL to the SPA too,\n // so leaving it defined would recreate the exact cross-origin bypass\n // this hook exists to prevent, just for Next.js-migrated portals.\n const defines: Record<string, string> = {};\n for (const key of [\n \"import.meta.env.VITE_API_URL\",\n \"import.meta.env.NEXT_PUBLIC_API_BASE_URL\",\n ]) {\n if (config.define?.[key] === undefined) {\n defines[key] = JSON.stringify(\"\");\n }\n }\n const proxy = !appDefinesProxy\n ? { \"/api\": { target, changeOrigin: true } }\n : {};\n\n return {\n define: defines,\n server: { proxy },\n };\n },\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configResolved(config: any) {\n const root: string = config.root ?? process.cwd();\n portalDir = options?.portalDir\n ? resolve(root, options.portalDir)\n : join(root, \"portal\");\n },\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configureServer(server: any) {\n // Idempotency: `fluid portal dev` injects this plugin, and a portal's\n // own vite.config may also wire it. Only the first instance registers\n // the watcher + middleware so we don't double-reload or double-serve.\n if (server.__fluidPortalDevWired) return;\n server.__fluidPortalDevWired = true;\n\n const watchDir = portalDir;\n\n // Registered unconditionally: `portal/` need not exist when the server\n // boots. `fluid portal dev --skip-pull` is exactly that case, and the\n // manifest middleware below re-checks existence per request, so it\n // starts serving local content the moment the directory appears.\n // Gating the watcher on startup existence left that flow serving the\n // very first build forever — no invalidation, no reload, no error.\n server.watcher.add(watchDir);\n\n let reloadTimer: ReturnType<typeof setTimeout> | null = null;\n\n const watchDirPrefix = watchDir.endsWith(sep) ? watchDir : watchDir + sep;\n\n const onFileChange = (filePath: string) => {\n // A separator boundary is required. A bare prefix test also matches\n // siblings that merely start with the same characters, so editing\n // `<root>/portal-backup/x.json` or `<root>/portal.config.ts` used to\n // drop the manifest cache and force a full page reload.\n if (filePath !== watchDir && !filePath.startsWith(watchDirPrefix)) {\n return;\n }\n\n cachedManifest = null;\n buildInFlight = null;\n manifestGeneration += 1;\n\n console.log(\n `[fluid-portal-dev] File changed: ${filePath.replace(watchDirPrefix, \"\")}`,\n );\n\n if (reloadTimer) clearTimeout(reloadTimer);\n reloadTimer = setTimeout(() => {\n reloadTimer = null;\n server.ws.send({ type: \"full-reload\", path: \"*\" });\n }, DEBOUNCE_MS);\n };\n\n server.watcher.on(\"change\", onFileChange);\n server.watcher.on(\"add\", onFileChange);\n server.watcher.on(\"unlink\", onFileChange);\n\n // ── Middleware to intercept manifest requests ───────────────────\n // Every MANIFEST_PATHS route returns the SAME `{ manifest }` payload:\n // the portal-tenant BFF route the current SDK runtime fetches\n // (useFluidApp → app_manifest_show) and the legacy FluidOS route, so\n // the local portal/ draft feeds the running app regardless of which\n // runtime generation it uses (the SDK adapter reads\n // `response.manifest`, matching buildManifestFromLocalFiles' output).\n server.middlewares.use(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (req: any, res: any, next: () => void) => {\n const url: string | undefined = req.url;\n\n if (!url || !MANIFEST_PATHS.some((path) => url.includes(path))) {\n next();\n return;\n }\n\n (async () => {\n try {\n if (!existsSync(portalDir)) {\n // Fall through to the Vite proxy so requests reach the real\n // API when local portal content is unavailable (e.g. --skip-pull).\n next();\n return;\n }\n\n let manifestJson = cachedManifest;\n if (manifestJson == null) {\n if (!buildInFlight) {\n // Stamp the build with the generation it was started\n // under. onFileChange bumps that counter, so a build\n // whose inputs changed underneath it can be recognized\n // when it finally resolves.\n const generation = manifestGeneration;\n buildInFlight = buildManifestFromLocalFiles(portalDir)\n .then((m) => {\n const json = JSON.stringify(m);\n // Only a build still current may populate the\n // cache. Caching a superseded one pinned the\n // pre-edit snapshot permanently: a non-null cache\n // means no later request ever rebuilds, so the\n // edit stayed invisible until some unrelated file\n // happened to change outside a build window.\n if (generation === manifestGeneration) {\n cachedManifest = json;\n buildInFlight = null;\n }\n return json;\n })\n .catch((err) => {\n // Same guard: a superseded build must not clear a\n // newer one's handle.\n if (generation === manifestGeneration) {\n buildInFlight = null; // allow retry on next request\n }\n throw err;\n });\n }\n // This response serves what was built for it, which is\n // correct even when superseded — the request predates\n // the edit. The point is that the NEXT one rebuilds.\n manifestJson = await buildInFlight;\n }\n\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"X-Portal-Dev-Mode\": \"true\",\n \"Cache-Control\": \"no-store\",\n });\n res.end(manifestJson);\n } catch (err) {\n console.error(\"[fluid-portal-dev] Error building manifest:\", err);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error:\n err instanceof Error\n ? err.message\n : \"Failed to build manifest from local files\",\n }),\n );\n }\n })();\n },\n );\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,cAAc;;AAGpB,MAAM,iBAAiB,CACrB,qBACA,mCACD;AAED,MAAM,kBAAkB;AACxB,MAAM,2BAA2B;AACjC,MAAM,uCAAuB,IAAI,SAG9B;;;;;;;;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AAI;AAEpC,QAAI,CAAC,OAAO,CAAC,eAAe,MAAM,SAAS,IAAI,SAAS,KAAK,CAAC,EAAE;AAC9D,WAAM;AACN;;AAGF,KAAC,YAAY;AACX,SAAI;AACF,UAAI,CAAC,WAAW,UAAU,EAAE;AAG1B,aAAM;AACN;;MAGF,IAAI,eAAe;AACnB,UAAI,gBAAgB,MAAM;AACxB,WAAI,CAAC,eAAe;QAKlB,MAAM,aAAa;AACnB,wBAAgB,4BAA4B,UAAU,CACnD,MAAM,MAAM;SACX,MAAM,OAAO,KAAK,UAAU,EAAE;AAO9B,aAAI,eAAe,oBAAoB;AACrC,2BAAiB;AACjB,0BAAgB;;AAElB,gBAAO;UACP,CACD,OAAO,QAAQ;AAGd,aAAI,eAAe,mBACjB,iBAAgB;AAElB,eAAM;UACN;;AAKN,sBAAe,MAAM;;AAGvB,UAAI,UAAU,KAAK;OACjB,gBAAgB;OAChB,qBAAqB;OACrB,iBAAiB;OAClB,CAAC;AACF,UAAI,IAAI,aAAa;cACd,KAAK;AACZ,cAAQ,MAAM,+CAA+C,IAAI;AACjE,UAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,UAAI,IACF,KAAK,UAAU,EACb,OACE,eAAe,QACX,IAAI,UACJ,6CACP,CAAC,CACH;;QAED;KAEP;;EAEJ"}
1
+ {"version":3,"file":"portal-dev-plugin-Dj0r6n7v.mjs","names":[],"sources":["../src/vite-plugin/portal-dev-plugin.ts"],"sourcesContent":["/**\n * Vite plugin for local portal content development.\n *\n * Intercepts the manifest API request and serves content assembled from the\n * local `portal/` directory. Watches portal files for changes and triggers a\n * full page reload.\n *\n * The manifest is intercepted on BOTH paths the SDK has used across versions\n * (`/api/app/manifest` since portal-sdk 0.1.4xx, `/api/fluid_os/definitions/\n * active` before that) so a newer SDK against an older-generation app — or\n * vice versa — still gets the local draft.\n */\n\nimport { join, resolve, sep } from \"node:path\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { getAuthToken, getFluidApiBase } from \"@fluid-app/fluid-cli\";\nimport { buildManifestFromLocalFiles } from \"./build-manifest.js\";\n\n/** Options for the portal dev plugin. */\nexport interface PortalDevPluginOptions {\n portalDir?: string;\n /**\n * When true (default), dev-server requests are forced same-origin: the\n * plugin blanks `import.meta.env.VITE_API_URL` in serve mode and proxies\n * `/api` to the configured Fluid host instead. Without this, a `.env`\n * pointing VITE_API_URL at a remote API makes the SPA fetch its manifest\n * cross-origin — silently bypassing this plugin and rendering the remote\n * app instead of the local `portal/` draft. Set false to opt out and let\n * the SPA call the remote API directly.\n */\n sameOriginDev?: boolean;\n /**\n * Override the `/api` dev-proxy target. Defaults to VITE_API_URL from the\n * process env / .env files, then the authenticated company's\n * `<subdomain>.portal.fluid.app` tenant BFF, then https://api.fluid.app.\n */\n apiProxyTarget?: string;\n /**\n * Override tenant-target discovery. Primarily useful to keep embedded plugin\n * integrations and tests deterministic.\n */\n resolveTenantApiTarget?: () => Promise<string | undefined>;\n}\n\nconst DEBOUNCE_MS = 100;\n\n/** Manifest endpoints across SDK generations — all serve the local draft. */\nconst MANIFEST_PATHS = [\n \"/api/app/manifest\",\n \"/api/fluid_os/definitions/active\",\n];\n\nconst DEFAULT_API_URL = \"https://api.fluid.app\";\nconst TENANT_LOOKUP_TIMEOUT_MS = 3_000;\nconst tenantTargetPromises = new WeakMap<\n () => Promise<string | undefined>,\n Promise<string | undefined>\n>();\n\ninterface CompanyMeResponse {\n data?: {\n company?: {\n subdomain?: unknown;\n };\n };\n}\n\nexport interface TenantApiTargetDependencies {\n token?: string | null;\n apiBase?: string;\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n}\n\n/**\n * Resolve the portal tenant BFF for the CLI's project-aware Fluid profile.\n *\n * Portal member APIs do not live on api.fluid.app or `<tenant>.fluid.app`.\n * Their OpenAPI server is `<tenant>.portal.fluid.app`, and using either of\n * the former hosts produces a wall of unrelated 404s in otherwise-valid\n * local portals.\n */\nexport async function resolvePortalTenantApiTarget(\n dependencies: TenantApiTargetDependencies = {},\n): Promise<string | undefined> {\n const token =\n dependencies.token !== undefined ? dependencies.token : getAuthToken();\n if (!token) return undefined;\n\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(),\n dependencies.timeoutMs ?? TENANT_LOOKUP_TIMEOUT_MS,\n );\n\n try {\n const response = await (dependencies.fetchImpl ?? fetch)(\n `${(dependencies.apiBase ?? getFluidApiBase()).replace(/\\/+$/, \"\")}/api/company/v1/companies/me`,\n {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: \"application/json\",\n },\n signal: controller.signal,\n },\n );\n if (!response.ok) return undefined;\n\n const body = (await response.json()) as CompanyMeResponse;\n const subdomain = body.data?.company?.subdomain;\n if (\n typeof subdomain !== \"string\" ||\n !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(subdomain)\n ) {\n return undefined;\n }\n\n return `https://${subdomain}.portal.fluid.app`;\n } catch {\n return undefined;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Fallback .env reader for VITE_API_URL, used only when vite's `loadEnv`\n * can't be imported (it's a declared dependency, so this is defensive — but\n * a broken install must degrade to \"wrong host\" rather than \"dev server\n * won't boot\"). Mirrors the basic lookup order: live env > .env.local >\n * .env. Unlike loadEnv it ignores .env.[mode] files and variable expansion.\n */\nfunction readViteApiUrlFallback(root: string): string | undefined {\n if (process.env.VITE_API_URL) return process.env.VITE_API_URL;\n if (process.env.NEXT_PUBLIC_API_BASE_URL) {\n return process.env.NEXT_PUBLIC_API_BASE_URL;\n }\n for (const file of [\".env.local\", \".env\"]) {\n const path = join(root, file);\n if (!existsSync(path)) continue;\n for (const line of readFileSync(path, \"utf8\").split(\"\\n\")) {\n // Quoted values stop at the closing `\"`; unquoted values stop before\n // an inline ` # comment` tail (dotenv semantics — a trailing comment\n // must not leak into the proxy target URL).\n const match =\n /^\\s*VITE_API_URL\\s*=\\s*(?:\"([^\"]*)\"|(.*?))\\s*(?:#.*)?$/.exec(line);\n const value = match?.[1] ?? match?.[2];\n if (value) return value;\n }\n }\n return undefined;\n}\n\nfunction storefrontSubdomainFromTarget(target: string): string | undefined {\n try {\n const hostname = new URL(target).hostname;\n const match = /^([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\\.fluid\\.app$/.exec(\n hostname,\n );\n const subdomain = match?.[1];\n if (\n !subdomain ||\n [\"admin\", \"api\", \"app\", \"docs\", \"portal\", \"upload\"].includes(subdomain)\n ) {\n return undefined;\n }\n return subdomain;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve VITE_API_URL the way vite itself would — `loadEnv` honors\n * .env.[mode], .env.[mode].local, envDir, and variable expansion, which the\n * fallback parser does not (a mode-specific staging API must not silently\n * fall back to production).\n */\nasync function resolveViteApiUrl(\n root: string,\n mode: string,\n envDir: string | undefined,\n): Promise<string | undefined> {\n try {\n const { loadEnv } = await import(\"vite\");\n const env = loadEnv(mode, envDir ?? root, [\"VITE_\", \"NEXT_PUBLIC_\"]);\n return (\n env.VITE_API_URL ||\n process.env.VITE_API_URL ||\n // Portals migrated from Next.js conventions configure the API host as\n // NEXT_PUBLIC_API_BASE_URL — honored by `fluid portal dev` since it\n // was introduced, so it stays a recognized source here.\n env.NEXT_PUBLIC_API_BASE_URL ||\n process.env.NEXT_PUBLIC_API_BASE_URL ||\n undefined\n );\n } catch {\n return readViteApiUrlFallback(root);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function portalDevPlugin(options?: PortalDevPluginOptions): any {\n let portalDir: string;\n let cachedManifest: string | null = null;\n let buildInFlight: Promise<string> | null = null;\n /** Bumped on every watched file change. A build carries the value it\n * started under; if it no longer matches when the build resolves, the\n * build read pre-edit state and must not be cached. */\n let manifestGeneration = 0;\n const resolveTenantTarget =\n options?.resolveTenantApiTarget ?? resolvePortalTenantApiTarget;\n\n return {\n name: \"fluid-portal-dev\",\n enforce: \"pre\" as const,\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async config(config: any, env: any) {\n if (env?.command !== \"serve\" || options?.sameOriginDev === false) {\n return {};\n }\n\n const root: string = config.root ?? process.cwd();\n const appDefinesProxy = config.server?.proxy?.[\"/api\"] !== undefined;\n const configuredTarget =\n options?.apiProxyTarget || appDefinesProxy\n ? undefined\n : await resolveViteApiUrl(\n root,\n env?.mode ?? \"development\",\n config.envDir,\n );\n const tenantTarget =\n options?.apiProxyTarget || appDefinesProxy || configuredTarget\n ? undefined\n : await (() => {\n const existing = tenantTargetPromises.get(resolveTenantTarget);\n if (existing) return existing;\n\n const pending = resolveTenantTarget();\n tenantTargetPromises.set(resolveTenantTarget, pending);\n return pending;\n })();\n const target =\n options?.apiProxyTarget ??\n configuredTarget ??\n tenantTarget ??\n DEFAULT_API_URL;\n const storefrontSubdomain = storefrontSubdomainFromTarget(target);\n\n if (tenantTarget) {\n console.log(`[fluid-portal-dev] Tenant API proxy: ${tenantTarget}`);\n console.log(\n \"[fluid-portal-dev] Member data still requires a portal handoff session; localhost requests may return 401.\",\n );\n } else if (\n !options?.apiProxyTarget &&\n !appDefinesProxy &&\n !configuredTarget\n ) {\n console.warn(\n `[fluid-portal-dev] Could not resolve the company tenant API; falling back to ${DEFAULT_API_URL}. ` +\n \"Built-in member screens may not load. Set VITE_API_URL explicitly or sign in with the project's Fluid profile.\",\n );\n } else if (storefrontSubdomain) {\n console.warn(\n `[fluid-portal-dev] ${target} is the storefront host, not the Portal tenant BFF. ` +\n `Built-in member APIs live at https://${storefrontSubdomain}.portal.fluid.app; remove the override to let the CLI resolve it.`,\n );\n }\n\n // Vite merges a plugin's returned config OVER the user config, so an\n // app's own explicit define / /api proxy is only preserved by checking\n // for it and yielding here. BOTH API-host env vars must be blanked:\n // dev.ts's envPrefix exposes NEXT_PUBLIC_API_BASE_URL to the SPA too,\n // so leaving it defined would recreate the exact cross-origin bypass\n // this hook exists to prevent, just for Next.js-migrated portals.\n const defines: Record<string, string> = {};\n for (const key of [\n \"import.meta.env.VITE_API_URL\",\n \"import.meta.env.NEXT_PUBLIC_API_BASE_URL\",\n ]) {\n if (config.define?.[key] === undefined) {\n defines[key] = JSON.stringify(\"\");\n }\n }\n const proxy = !appDefinesProxy\n ? { \"/api\": { target, changeOrigin: true } }\n : {};\n\n return {\n define: defines,\n server: { proxy },\n };\n },\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configResolved(config: any) {\n const root: string = config.root ?? process.cwd();\n portalDir = options?.portalDir\n ? resolve(root, options.portalDir)\n : join(root, \"portal\");\n },\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configureServer(server: any) {\n // Idempotency: `fluid portal dev` injects this plugin, and a portal's\n // own vite.config may also wire it. Only the first instance registers\n // the watcher + middleware so we don't double-reload or double-serve.\n if (server.__fluidPortalDevWired) return;\n server.__fluidPortalDevWired = true;\n\n const watchDir = portalDir;\n\n // Registered unconditionally: `portal/` need not exist when the server\n // boots. `fluid portal dev --skip-pull` is exactly that case, and the\n // manifest middleware below re-checks existence per request, so it\n // starts serving local content the moment the directory appears.\n // Gating the watcher on startup existence left that flow serving the\n // very first build forever — no invalidation, no reload, no error.\n server.watcher.add(watchDir);\n\n let reloadTimer: ReturnType<typeof setTimeout> | null = null;\n\n const watchDirPrefix = watchDir.endsWith(sep) ? watchDir : watchDir + sep;\n\n const onFileChange = (filePath: string) => {\n // A separator boundary is required. A bare prefix test also matches\n // siblings that merely start with the same characters, so editing\n // `<root>/portal-backup/x.json` or `<root>/portal.config.ts` used to\n // drop the manifest cache and force a full page reload.\n if (filePath !== watchDir && !filePath.startsWith(watchDirPrefix)) {\n return;\n }\n\n cachedManifest = null;\n buildInFlight = null;\n manifestGeneration += 1;\n\n console.log(\n `[fluid-portal-dev] File changed: ${filePath.replace(watchDirPrefix, \"\")}`,\n );\n\n if (reloadTimer) clearTimeout(reloadTimer);\n reloadTimer = setTimeout(() => {\n reloadTimer = null;\n server.ws.send({ type: \"full-reload\", path: \"*\" });\n }, DEBOUNCE_MS);\n };\n\n server.watcher.on(\"change\", onFileChange);\n server.watcher.on(\"add\", onFileChange);\n server.watcher.on(\"unlink\", onFileChange);\n\n // ── Middleware to intercept manifest requests ───────────────────\n // Every MANIFEST_PATHS route returns the SAME `{ manifest }` payload:\n // the portal-tenant BFF route the current SDK runtime fetches\n // (useFluidApp → app_manifest_show) and the legacy FluidOS route, so\n // the local portal/ draft feeds the running app regardless of which\n // runtime generation it uses (the SDK adapter reads\n // `response.manifest`, matching buildManifestFromLocalFiles' output).\n server.middlewares.use(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (req: any, res: any, next: () => void) => {\n const url: string | undefined = req.url;\n\n if (!url || !MANIFEST_PATHS.some((path) => url.includes(path))) {\n next();\n return;\n }\n\n (async () => {\n try {\n if (!existsSync(portalDir)) {\n // Fall through to the Vite proxy so requests reach the real\n // API when local portal content is unavailable (e.g. --skip-pull).\n next();\n return;\n }\n\n let manifestJson = cachedManifest;\n if (manifestJson == null) {\n if (!buildInFlight) {\n // Stamp the build with the generation it was started\n // under. onFileChange bumps that counter, so a build\n // whose inputs changed underneath it can be recognized\n // when it finally resolves.\n const generation = manifestGeneration;\n buildInFlight = buildManifestFromLocalFiles(portalDir)\n .then((m) => {\n const json = JSON.stringify(m);\n // Only a build still current may populate the\n // cache. Caching a superseded one pinned the\n // pre-edit snapshot permanently: a non-null cache\n // means no later request ever rebuilds, so the\n // edit stayed invisible until some unrelated file\n // happened to change outside a build window.\n if (generation === manifestGeneration) {\n cachedManifest = json;\n buildInFlight = null;\n }\n return json;\n })\n .catch((err) => {\n // Same guard: a superseded build must not clear a\n // newer one's handle.\n if (generation === manifestGeneration) {\n buildInFlight = null; // allow retry on next request\n }\n throw err;\n });\n }\n // This response serves what was built for it, which is\n // correct even when superseded — the request predates\n // the edit. The point is that the NEXT one rebuilds.\n manifestJson = await buildInFlight;\n }\n\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"X-Portal-Dev-Mode\": \"true\",\n \"Cache-Control\": \"no-store\",\n });\n res.end(manifestJson);\n } catch (err) {\n console.error(\"[fluid-portal-dev] Error building manifest:\", err);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error:\n err instanceof Error\n ? err.message\n : \"Failed to build manifest from local files\",\n }),\n );\n }\n })();\n },\n );\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,cAAc;;AAGpB,MAAM,iBAAiB,CACrB,qBACA,mCACD;AAED,MAAM,kBAAkB;AACxB,MAAM,2BAA2B;AACjC,MAAM,uCAAuB,IAAI,SAG9B;;;;;;;;;AAyBH,eAAsB,6BACpB,eAA4C,EAAE,EACjB;CAC7B,MAAM,QACJ,aAAa,UAAU,KAAA,IAAY,aAAa,QAAQ,cAAc;AACxE,KAAI,CAAC,MAAO,QAAO,KAAA;CAEnB,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,QAAQ,iBACN,WAAW,OAAO,EACxB,aAAa,aAAa,yBAC3B;AAED,KAAI;EACF,MAAM,WAAW,OAAO,aAAa,aAAa,OAChD,IAAI,aAAa,WAAW,iBAAiB,EAAE,QAAQ,QAAQ,GAAG,CAAC,+BACnE;GACE,SAAS;IACP,eAAe,UAAU;IACzB,QAAQ;IACT;GACD,QAAQ,WAAW;GACpB,CACF;AACD,MAAI,CAAC,SAAS,GAAI,QAAO,KAAA;EAGzB,MAAM,aADQ,MAAM,SAAS,MAAM,EACZ,MAAM,SAAS;AACtC,MACE,OAAO,cAAc,YACrB,CAAC,yCAAyC,KAAK,UAAU,CAEzD;AAGF,SAAO,WAAW,UAAU;SACtB;AACN;WACQ;AACR,eAAa,MAAM;;;;;;;;;;AAWvB,SAAS,uBAAuB,MAAkC;AAChE,KAAI,QAAQ,IAAI,aAAc,QAAO,QAAQ,IAAI;AACjD,KAAI,QAAQ,IAAI,yBACd,QAAO,QAAQ,IAAI;AAErB,MAAK,MAAM,QAAQ,CAAC,cAAc,OAAO,EAAE;EACzC,MAAM,OAAO,KAAK,MAAM,KAAK;AAC7B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js";
2
- import { c as fluidWidgetDevPlugin, l as handleOptions, u as setCorsHeaders } from "./src-BuSYN4Co.mjs";
1
+ import { P as __exportAll } from "./pull-C0FfNCju.mjs";
2
+ import { c as fluidWidgetDevPlugin, l as handleOptions, u as setCorsHeaders } from "./src-Dz9-qBBA.mjs";
3
3
  import path from "node:path";
4
4
  import { existsSync } from "node:fs";
5
5
  //#region src/vite-plugin/portal-widget-dev-plugin.ts
@@ -161,4 +161,4 @@ if (widgetPackage) {
161
161
  //#endregion
162
162
  export { portal_widget_dev_plugin_exports as n, portalWidgetDevPlugin as t };
163
163
 
164
- //# sourceMappingURL=portal-widget-dev-plugin-rJTEEYgh.mjs.map
164
+ //# sourceMappingURL=portal-widget-dev-plugin-BjXiFpX5.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"portal-widget-dev-plugin-rJTEEYgh.mjs","names":[],"sources":["../src/vite-plugin/portal-widget-dev-plugin.ts"],"sourcesContent":["/**\n * Dev routes that let a portal preview render the project's own widgets before\n * they are published.\n *\n * A portal keeps company-owned widget sources in `src/widgets.config.ts` and\n * publishes them with `fluid portal deploy`. Until that deploy runs, the widget\n * exists only on disk — the catalog has never heard of it, so a preview could\n * not show it and the only way to see your work was to publish it. Publishing\n * is not a safe iteration loop: a deploy is live immediately, there is no\n * rollback, and a duplicate `packageId@version` is ignored so every attempt\n * needs a version bump.\n *\n * These routes close that gap by serving the same two endpoints a standalone\n * widget project serves — `/__widget-packages__` (a canonical package\n * descriptor) and `/__runtime-entry__` (the worker bootstrap). A host that can\n * already render published packages needs no new code to render a local one:\n * the descriptor shape is identical, so it merges straight into the catalog\n * array.\n *\n * The route implementations are reused wholesale from\n * `@fluid-app/fluid-cli-widget-tooling`. Its bootstrap script in particular is\n * load-bearing — it exists to fix a message-buffer race that silently strands\n * worker mounts — and must not be reimplemented here.\n *\n * Imported from widget-tooling rather than from the widget CLI deliberately:\n * this package lists widget-tooling in its tsdown `alwaysBundle`, so the routes\n * compile into the portal dist. An import across published CLIs stays external\n * and resolves to un-built TypeScript at runtime.\n *\n * Two things differ from a standalone project, and both are passed as options:\n * the package source lives at `src/widgets.config.ts` rather than\n * `fluid.widget.config.ts`, and it is owned by `company` rather than `droplet`.\n * A portal also has no `startWidgetPackage()` module of its own, so this plugin\n * generates one.\n */\n\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n fluidWidgetDevPlugin,\n handleOptions,\n setCorsHeaders,\n} from \"@fluid-app/fluid-cli-widget-tooling\";\nimport type { Plugin } from \"vite\";\n\n/** Package source, relative to the Vite root. */\nconst WIDGET_CONFIG_MODULE_PATH = \"/src/widgets.config.ts\";\n\n/**\n * Generated worker entry. Requestable (no `\\0` prefix) because the bootstrap\n * script imports it by URL from the dev server rather than through Vite's\n * module graph.\n */\nconst VIRTUAL_ENTRY_PATH = \"/@fluid-portal-widget-entry.js\";\n\n/** Must match the module URL used by widget-tooling's worker bootstrap. */\nconst WORKER_SDK_MODULE_PATH = \"/@id/@fluid-app/portal-sdk/widgets/worker\";\n\nconst WIDGET_PACKAGES_ROUTES = new Set([\n \"/__widget-packages__\",\n \"/__widget-packages__/\",\n]);\nconst RUNTIME_ENTRY_ROUTES = new Set([\n \"/__runtime-entry__\",\n \"/__runtime-entry__/\",\n]);\n\nexport function portalWidgetDevPlugin(): Plugin[] {\n return [\n missingConfigGuardPlugin(),\n virtualWorkerEntryPlugin(),\n fluidWidgetDevPlugin({\n entryModulePath: VIRTUAL_ENTRY_PATH,\n configModulePath: WIDGET_CONFIG_MODULE_PATH,\n owner: \"company\",\n // A portal with no custom widget yet is the normal case, not a fault.\n allowNoPackages: true,\n }),\n ];\n}\n\n/**\n * Short-circuits both routes when the project has no `src/widgets.config.ts`.\n *\n * Most portals never gain one. Without this the delegated routes would try to\n * load a module that does not exist and log a resolution failure on every poll\n * — the preview polls continuously — so the expected case would be the noisiest\n * thing in the log. Registered before the delegated plugin so its middleware\n * runs first.\n */\nfunction missingConfigGuardPlugin(): Plugin {\n let configFilePath = \"\";\n\n return {\n name: \"fluid-portal-widget-dev-missing-config-guard\",\n apply: \"serve\",\n config() {\n // The worker entry contains ordered Remote DOM polyfill side effects.\n // Serving the linked SDK directly preserves ESM evaluation order; Vite's\n // dependency prebundler can otherwise flatten and reverse those imports.\n return {\n optimizeDeps: {\n exclude: [\"@fluid-app/portal-sdk\", \"@fluid-app/widget-runtime\"],\n },\n };\n },\n configResolved(config) {\n configFilePath = path.join(\n config.root,\n WIDGET_CONFIG_MODULE_PATH.replace(/^\\//, \"\"),\n );\n },\n configureServer(server) {\n server.middlewares.use((request, response, next): void => {\n const pathname = (request.url ?? \"\").split(\"?\")[0] ?? \"\";\n const isWidgetRoute =\n WIDGET_PACKAGES_ROUTES.has(pathname) ||\n RUNTIME_ENTRY_ROUTES.has(pathname);\n if (!isWidgetRoute) {\n next();\n return;\n }\n // Checked per request, not at startup: `fluid portal widget create`\n // can add the file while the dev server is already running.\n if (existsSync(configFilePath)) {\n next();\n return;\n }\n\n // Answer a preflight exactly as the delegated routes do. Two\n // implementations of the same route disagreeing is bad enough; the\n // guard is the one that runs in the common case, since most portals\n // never gain a widget config, so the divergence would have been the\n // DEFAULT path rather than the edge.\n if (handleOptions(request, response)) return;\n setCorsHeaders(response);\n if (WIDGET_PACKAGES_ROUTES.has(pathname)) {\n response.setHeader(\"Content-Type\", \"application/json\");\n response.statusCode = 200;\n response.end(\"[]\");\n return;\n }\n response.setHeader(\"Content-Type\", \"text/javascript\");\n response.statusCode = 200;\n response.end(\"// No portal widget package in this project.\\n\");\n });\n },\n };\n}\n\n/**\n * Serves the worker entry a portal project does not have.\n *\n * A standalone widget project ships `src/index.ts` calling\n * `startWidgetPackage()`. A portal's `src/widgets.config.ts` only declares the\n * package, so this module supplies the missing call. Export precedence matches\n * the shared descriptor builder's, so the worker starts the same package the\n * descriptor advertises.\n */\nfunction virtualWorkerEntryPlugin(): Plugin {\n const buildSource = (): string =>\n `import { startWidgetPackage } from \"${WORKER_SDK_MODULE_PATH}\";\n\nconst source = await import(\"${WIDGET_CONFIG_MODULE_PATH}\");\n\nconst packages = source.widgetPackages;\nconst widgetPackage =\n (Array.isArray(packages) && packages.length > 0 ? packages[0] : undefined) ??\n source.widgetPackage ??\n source.default;\n\nif (widgetPackage) {\n startWidgetPackage(widgetPackage);\n}\n`;\n\n return {\n name: \"fluid-portal-widget-dev-entry\",\n apply: \"serve\",\n resolveId(id) {\n return id === VIRTUAL_ENTRY_PATH ? id : null;\n },\n load(id) {\n if (id !== VIRTUAL_ENTRY_PATH) return null;\n return buildSource();\n },\n configureServer(server) {\n // Serve this module before Vite's import analysis. The bootstrap applies\n // the network guard through this exact SDK URL; allowing Vite to rewrite\n // it would create a second module instance that cannot recognize the\n // already wrapped, non-configurable fetch global.\n server.middlewares.use((request, response, next): void => {\n const pathname = (request.url ?? \"\").split(\"?\")[0] ?? \"\";\n if (pathname !== VIRTUAL_ENTRY_PATH) {\n next();\n return;\n }\n if (handleOptions(request, response)) return;\n setCorsHeaders(response);\n response.setHeader(\"Content-Type\", \"text/javascript\");\n response.statusCode = 200;\n response.end(buildSource());\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,4BAA4B;;;;;;AAOlC,MAAM,qBAAqB;;AAG3B,MAAM,yBAAyB;AAE/B,MAAM,yBAAyB,IAAI,IAAI,CACrC,wBACA,wBACD,CAAC;AACF,MAAM,uBAAuB,IAAI,IAAI,CACnC,sBACA,sBACD,CAAC;AAEF,SAAgB,wBAAkC;AAChD,QAAO;EACL,0BAA0B;EAC1B,0BAA0B;EAC1B,qBAAqB;GACnB,iBAAiB;GACjB,kBAAkB;GAClB,OAAO;GAEP,iBAAiB;GAClB,CAAC;EACH;;;;;;;;;;;AAYH,SAAS,2BAAmC;CAC1C,IAAI,iBAAiB;AAErB,QAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;AAIP,UAAO,EACL,cAAc,EACZ,SAAS,CAAC,yBAAy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portal-widget-dev-plugin-BjXiFpX5.mjs","names":[],"sources":["../src/vite-plugin/portal-widget-dev-plugin.ts"],"sourcesContent":["/**\n * Dev routes that let a portal preview render the project's own widgets before\n * they are published.\n *\n * A portal keeps company-owned widget sources in `src/widgets.config.ts` and\n * publishes them with `fluid portal deploy`. Until that deploy runs, the widget\n * exists only on disk — the catalog has never heard of it, so a preview could\n * not show it and the only way to see your work was to publish it. Publishing\n * is not a safe iteration loop: a deploy is live immediately, there is no\n * rollback, and a duplicate `packageId@version` is ignored so every attempt\n * needs a version bump.\n *\n * These routes close that gap by serving the same two endpoints a standalone\n * widget project serves — `/__widget-packages__` (a canonical package\n * descriptor) and `/__runtime-entry__` (the worker bootstrap). A host that can\n * already render published packages needs no new code to render a local one:\n * the descriptor shape is identical, so it merges straight into the catalog\n * array.\n *\n * The route implementations are reused wholesale from\n * `@fluid-app/fluid-cli-widget-tooling`. Its bootstrap script in particular is\n * load-bearing — it exists to fix a message-buffer race that silently strands\n * worker mounts — and must not be reimplemented here.\n *\n * Imported from widget-tooling rather than from the widget CLI deliberately:\n * this package lists widget-tooling in its tsdown `alwaysBundle`, so the routes\n * compile into the portal dist. An import across published CLIs stays external\n * and resolves to un-built TypeScript at runtime.\n *\n * Two things differ from a standalone project, and both are passed as options:\n * the package source lives at `src/widgets.config.ts` rather than\n * `fluid.widget.config.ts`, and it is owned by `company` rather than `droplet`.\n * A portal also has no `startWidgetPackage()` module of its own, so this plugin\n * generates one.\n */\n\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n fluidWidgetDevPlugin,\n handleOptions,\n setCorsHeaders,\n} from \"@fluid-app/fluid-cli-widget-tooling\";\nimport type { Plugin } from \"vite\";\n\n/** Package source, relative to the Vite root. */\nconst WIDGET_CONFIG_MODULE_PATH = \"/src/widgets.config.ts\";\n\n/**\n * Generated worker entry. Requestable (no `\\0` prefix) because the bootstrap\n * script imports it by URL from the dev server rather than through Vite's\n * module graph.\n */\nconst VIRTUAL_ENTRY_PATH = \"/@fluid-portal-widget-entry.js\";\n\n/** Must match the module URL used by widget-tooling's worker bootstrap. */\nconst WORKER_SDK_MODULE_PATH = \"/@id/@fluid-app/portal-sdk/widgets/worker\";\n\nconst WIDGET_PACKAGES_ROUTES = new Set([\n \"/__widget-packages__\",\n \"/__widget-packages__/\",\n]);\nconst RUNTIME_ENTRY_ROUTES = new Set([\n \"/__runtime-entry__\",\n \"/__runtime-entry__/\",\n]);\n\nexport function portalWidgetDevPlugin(): Plugin[] {\n return [\n missingConfigGuardPlugin(),\n virtualWorkerEntryPlugin(),\n fluidWidgetDevPlugin({\n entryModulePath: VIRTUAL_ENTRY_PATH,\n configModulePath: WIDGET_CONFIG_MODULE_PATH,\n owner: \"company\",\n // A portal with no custom widget yet is the normal case, not a fault.\n allowNoPackages: true,\n }),\n ];\n}\n\n/**\n * Short-circuits both routes when the project has no `src/widgets.config.ts`.\n *\n * Most portals never gain one. Without this the delegated routes would try to\n * load a module that does not exist and log a resolution failure on every poll\n * — the preview polls continuously — so the expected case would be the noisiest\n * thing in the log. Registered before the delegated plugin so its middleware\n * runs first.\n */\nfunction missingConfigGuardPlugin(): Plugin {\n let configFilePath = \"\";\n\n return {\n name: \"fluid-portal-widget-dev-missing-config-guard\",\n apply: \"serve\",\n config() {\n // The worker entry contains ordered Remote DOM polyfill side effects.\n // Serving the linked SDK directly preserves ESM evaluation order; Vite's\n // dependency prebundler can otherwise flatten and reverse those imports.\n return {\n optimizeDeps: {\n exclude: [\"@fluid-app/portal-sdk\", \"@fluid-app/widget-runtime\"],\n },\n };\n },\n configResolved(config) {\n configFilePath = path.join(\n config.root,\n WIDGET_CONFIG_MODULE_PATH.replace(/^\\//, \"\"),\n );\n },\n configureServer(server) {\n server.middlewares.use((request, response, next): void => {\n const pathname = (request.url ?? \"\").split(\"?\")[0] ?? \"\";\n const isWidgetRoute =\n WIDGET_PACKAGES_ROUTES.has(pathname) ||\n RUNTIME_ENTRY_ROUTES.has(pathname);\n if (!isWidgetRoute) {\n next();\n return;\n }\n // Checked per request, not at startup: `fluid portal widget create`\n // can add the file while the dev server is already running.\n if (existsSync(configFilePath)) {\n next();\n return;\n }\n\n // Answer a preflight exactly as the delegated routes do. Two\n // implementations of the same route disagreeing is bad enough; the\n // guard is the one that runs in the common case, since most portals\n // never gain a widget config, so the divergence would have been the\n // DEFAULT path rather than the edge.\n if (handleOptions(request, response)) return;\n setCorsHeaders(response);\n if (WIDGET_PACKAGES_ROUTES.has(pathname)) {\n response.setHeader(\"Content-Type\", \"application/json\");\n response.statusCode = 200;\n response.end(\"[]\");\n return;\n }\n response.setHeader(\"Content-Type\", \"text/javascript\");\n response.statusCode = 200;\n response.end(\"// No portal widget package in this project.\\n\");\n });\n },\n };\n}\n\n/**\n * Serves the worker entry a portal project does not have.\n *\n * A standalone widget project ships `src/index.ts` calling\n * `startWidgetPackage()`. A portal's `src/widgets.config.ts` only declares the\n * package, so this module supplies the missing call. Export precedence matches\n * the shared descriptor builder's, so the worker starts the same package the\n * descriptor advertises.\n */\nfunction virtualWorkerEntryPlugin(): Plugin {\n const buildSource = (): string =>\n `import { startWidgetPackage } from \"${WORKER_SDK_MODULE_PATH}\";\n\nconst source = await import(\"${WIDGET_CONFIG_MODULE_PATH}\");\n\nconst packages = source.widgetPackages;\nconst widgetPackage =\n (Array.isArray(packages) && packages.length > 0 ? packages[0] : undefined) ??\n source.widgetPackage ??\n source.default;\n\nif (widgetPackage) {\n startWidgetPackage(widgetPackage);\n}\n`;\n\n return {\n name: \"fluid-portal-widget-dev-entry\",\n apply: \"serve\",\n resolveId(id) {\n return id === VIRTUAL_ENTRY_PATH ? id : null;\n },\n load(id) {\n if (id !== VIRTUAL_ENTRY_PATH) return null;\n return buildSource();\n },\n configureServer(server) {\n // Serve this module before Vite's import analysis. The bootstrap applies\n // the network guard through this exact SDK URL; allowing Vite to rewrite\n // it would create a second module instance that cannot recognize the\n // already wrapped, non-configurable fetch global.\n server.middlewares.use((request, response, next): void => {\n const pathname = (request.url ?? \"\").split(\"?\")[0] ?? \"\";\n if (pathname !== VIRTUAL_ENTRY_PATH) {\n next();\n return;\n }\n if (handleOptions(request, response)) return;\n setCorsHeaders(response);\n response.setHeader(\"Content-Type\", \"text/javascript\");\n response.statusCode = 200;\n response.end(buildSource());\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,4BAA4B;;;;;;AAOlC,MAAM,qBAAqB;;AAG3B,MAAM,yBAAyB;AAE/B,MAAM,yBAAyB,IAAI,IAAI,CACrC,wBACA,wBACD,CAAC;AACF,MAAM,uBAAuB,IAAI,IAAI,CACnC,sBACA,sBACD,CAAC;AAEF,SAAgB,wBAAkC;AAChD,QAAO;EACL,0BAA0B;EAC1B,0BAA0B;EAC1B,qBAAqB;GACnB,iBAAiB;GACjB,kBAAkB;GAClB,OAAO;GAEP,iBAAiB;GAClB,CAAC;EACH;;;;;;;;;;;AAYH,SAAS,2BAAmC;CAC1C,IAAI,iBAAiB;AAErB,QAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;AAIP,UAAO,EACL,cAAc,EACZ,SAAS,CAAC,yBAAyB,4BAA4B,EAChE,EACF;;EAEH,eAAe,QAAQ;AACrB,oBAAiB,KAAK,KACpB,OAAO,MACP,0BAA0B,QAAQ,OAAO,GAAG,CAC7C;;EAEH,gBAAgB,QAAQ;AACtB,UAAO,YAAY,KAAK,SAAS,UAAU,SAAe;IACxD,MAAM,YAAY,QAAQ,OAAO,IAAI,MAAM,IAAI,CAAC,MAAM;AAItD,QAAI,EAFF,uBAAuB,IAAI,SAAS,IACpC,qBAAqB,IAAI,SAAS,GAChB;AAClB,WAAM;AACN;;AAIF,QAAI,WAAW,eAAe,EAAE;AAC9B,WAAM;AACN;;AAQF,QAAI,cAAc,SAAS,SAAS,CAAE;AACtC,mBAAe,SAAS;AACxB,QAAI,uBAAuB,IAAI,SAAS,EAAE;AACxC,cAAS,UAAU,gBAAgB,mBAAmB;AACtD,cAAS,aAAa;AACtB,cAAS,IAAI,KAAK;AAClB;;AAEF,aAAS,UAAU,gBAAgB,kBAAkB;AACrD,aAAS,aAAa;AACtB,aAAS,IAAI,iDAAiD;KAC9D;;EAEL;;;;;;;;;;;AAYH,SAAS,2BAAmC;CAC1C,MAAM,oBACJ,uCAAuC,uBAAuB;;+BAEnC,0BAA0B;;;;;;;;;;;;AAavD,QAAO;EACL,MAAM;EACN,OAAO;EACP,UAAU,IAAI;AACZ,UAAO,OAAO,qBAAqB,KAAK;;EAE1C,KAAK,IAAI;AACP,OAAI,OAAO,mBAAoB,QAAO;AACtC,UAAO,aAAa;;EAEtB,gBAAgB,QAAQ;AAKtB,UAAO,YAAY,KAAK,SAAS,UAAU,SAAe;AAExD,UADkB,QAAQ,OAAO,IAAI,MAAM,IAAI,CAAC,MAAM,QACrC,oBAAoB;AACnC,WAAM;AACN;;AAEF,QAAI,cAAc,SAAS,SAAS,CAAE;AACtC,mBAAe,SAAS;AACxB,aAAS,UAAU,gBAAgB,kBAAkB;AACrD,aAAS,aAAa;AACtB,aAAS,IAAI,aAAa,CAAC;KAC3B;;EAEL"}
@@ -1,4 +1,4 @@
1
- import { C as fluidOsV0ListWidgetPackages, D as fluidOsV0UpdateFluidOsscreen, E as fluidOsV0UpdateFluidOsprofile, O as fluidOsV0UpdateFluidOstheme, S as fluidOsV0ListFluidOsversions, T as fluidOsV0UpdateFluidOsnavigationItem, _ as fluidOsV0ListFluidOsnavigationItems, a as fluidOsV0CreateFluidOsscreen, b as fluidOsV0ListFluidOsscreens, d as fluidOsV0DeleteFluidOsnavigationItem, f as fluidOsV0DeleteFluidOsprofile, g as fluidOsV0ListFluidOsdefinitions, h as fluidOsV0GetFluidOsscreen, i as fluidOsV0CreateFluidOsprofile, k as fluidOsV0UpdateFluidOsversion, m as fluidOsV0DeleteFluidOstheme, n as fluidOsV0CreateFluidOsnavigation, o as fluidOsV0CreateFluidOstheme, p as fluidOsV0DeleteFluidOsscreen, r as fluidOsV0CreateFluidOsnavigationItem, s as fluidOsV0CreateFluidOsversion, u as fluidOsV0DeleteFluidOsnavigation, v as fluidOsV0ListFluidOsnavigations, w as fluidOsV0UpdateFluidOsnavigation, x as fluidOsV0ListFluidOsthemes, y as fluidOsV0ListFluidOsprofiles } from "./sdk.gen-VRGYiLVJ.mjs";
1
+ import { C as fluidOsV0ListWidgetPackages, D as fluidOsV0UpdateFluidOsscreen, E as fluidOsV0UpdateFluidOsprofile, O as fluidOsV0UpdateFluidOstheme, S as fluidOsV0ListFluidOsversions, T as fluidOsV0UpdateFluidOsnavigationItem, _ as fluidOsV0ListFluidOsnavigationItems, a as fluidOsV0CreateFluidOsscreen, b as fluidOsV0ListFluidOsscreens, d as fluidOsV0DeleteFluidOsnavigationItem, f as fluidOsV0DeleteFluidOsprofile, g as fluidOsV0ListFluidOsdefinitions, h as fluidOsV0GetFluidOsscreen, i as fluidOsV0CreateFluidOsprofile, k as fluidOsV0UpdateFluidOsversion, m as fluidOsV0DeleteFluidOstheme, n as fluidOsV0CreateFluidOsnavigation, o as fluidOsV0CreateFluidOstheme, p as fluidOsV0DeleteFluidOsscreen, r as fluidOsV0CreateFluidOsnavigationItem, s as fluidOsV0CreateFluidOsversion, u as fluidOsV0DeleteFluidOsnavigation, v as fluidOsV0ListFluidOsnavigations, w as fluidOsV0UpdateFluidOsnavigation, x as fluidOsV0ListFluidOsthemes, y as fluidOsV0ListFluidOsprofiles } from "./sdk.gen-qjewNLc_.mjs";
2
2
  import "node:module";
3
3
  import { Command } from "commander";
4
4
  import chalk from "chalk";
@@ -21652,4 +21652,4 @@ const pullCommand = new Command("pull").description("Pull a Fluid OS definition'
21652
21652
  //#endregion
21653
21653
  export { fluidOsApi as A, removeMapping as C, writeMappings as D, updateMapping as E, createFluidOsHeyApiClient as M, ApiError as N, atomicWriteFile as O, __exportAll as P, readMappings as S, resolveSlugToId as T, diffAgainstSnapshot as _, buildNavigationIdToSlugMap as a, writeSnapshot as b, transformNavigation as c, transformScreen as d, transformTheme as f, computeFileHash as g, collectWidgetCapabilityGrants as h, buildIdToSlugMap as i, toFluidOsDynamicObject as j, createFluidOsClient as k, transformNavigationItems as l, collectSnapshotWidgetCapabilityGrants as m, pull_exports as n, buildThemeIdToSlugMap as o, buildSnapshot as p, validatePortalResource as r, deriveScreenSlug as s, pullCommand as t, transformProfile as u, readSnapshot as v, resolveIdToSlug as w, deriveSlug as x, selectLegacyNetworkWidgetGrants as y };
21654
21654
 
21655
- //# sourceMappingURL=pull-C9a0z-7O.mjs.map
21655
+ //# sourceMappingURL=pull-C0FfNCju.mjs.map