@wildo-ai/wildo-cli 1.1.3 → 1.1.4
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/src/commands/context/__tests__/assurance-basis.command.test.d.ts +2 -0
- package/dist/src/commands/context/__tests__/assurance-basis.command.test.d.ts.map +1 -0
- package/dist/src/commands/context/__tests__/assurance-basis.command.test.js +63 -0
- package/dist/src/commands/context/__tests__/assurance-basis.command.test.js.map +1 -0
- package/dist/src/commands/context/assurance-basis.command.d.ts +61 -0
- package/dist/src/commands/context/assurance-basis.command.d.ts.map +1 -0
- package/dist/src/commands/context/assurance-basis.command.js +166 -0
- package/dist/src/commands/context/assurance-basis.command.js.map +1 -0
- package/dist/src/commands/dev/charts-audit.command.d.ts +5 -3
- package/dist/src/commands/dev/charts-audit.command.d.ts.map +1 -1
- package/dist/src/commands/dev/charts-audit.command.js +35 -6
- package/dist/src/commands/dev/charts-audit.command.js.map +1 -1
- package/dist/src/commands/fwk/generate-providers.command.d.ts.map +1 -1
- package/dist/src/commands/fwk/generate-providers.command.js +18 -2
- package/dist/src/commands/fwk/generate-providers.command.js.map +1 -1
- package/dist/src/commands/generate/email-preview.command.d.ts +8 -0
- package/dist/src/commands/generate/email-preview.command.d.ts.map +1 -1
- package/dist/src/commands/generate/email-preview.command.js +57 -0
- package/dist/src/commands/generate/email-preview.command.js.map +1 -1
- package/dist/src/commands/init.command.d.ts.map +1 -1
- package/dist/src/commands/init.command.js +32 -0
- package/dist/src/commands/init.command.js.map +1 -1
- package/dist/src/commands/lock/check.command.d.ts.map +1 -1
- package/dist/src/commands/lock/check.command.js +3 -2
- package/dist/src/commands/lock/check.command.js.map +1 -1
- package/dist/src/commands/registry/login.command.d.ts.map +1 -1
- package/dist/src/commands/registry/login.command.js +2 -0
- package/dist/src/commands/registry/login.command.js.map +1 -1
- package/dist/src/commands/registry/publish.command.d.ts.map +1 -1
- package/dist/src/commands/registry/publish.command.js +2 -0
- package/dist/src/commands/registry/publish.command.js.map +1 -1
- package/dist/src/commands/registry/registry-transport.constants.d.ts +33 -0
- package/dist/src/commands/registry/registry-transport.constants.d.ts.map +1 -0
- package/dist/src/commands/registry/registry-transport.constants.js +33 -0
- package/dist/src/commands/registry/registry-transport.constants.js.map +1 -0
- package/dist/src/commands/registry/whoami.command.d.ts.map +1 -1
- package/dist/src/commands/registry/whoami.command.js +2 -0
- package/dist/src/commands/registry/whoami.command.js.map +1 -1
- package/dist/src/modules/domain/credentials/__tests__/approver-user.module.test.d.ts +2 -0
- package/dist/src/modules/domain/credentials/__tests__/approver-user.module.test.d.ts.map +1 -0
- package/dist/src/modules/domain/credentials/__tests__/approver-user.module.test.js +146 -0
- package/dist/src/modules/domain/credentials/__tests__/approver-user.module.test.js.map +1 -0
- package/dist/src/modules/domain/credentials/approver-user.module.d.ts +85 -0
- package/dist/src/modules/domain/credentials/approver-user.module.d.ts.map +1 -0
- package/dist/src/modules/domain/credentials/approver-user.module.js +92 -0
- package/dist/src/modules/domain/credentials/approver-user.module.js.map +1 -0
- package/dist/src/services/application/__tests__/app-bootstrap.approving-administrator.test.d.ts +2 -0
- package/dist/src/services/application/__tests__/app-bootstrap.approving-administrator.test.d.ts.map +1 -0
- package/dist/src/services/application/__tests__/app-bootstrap.approving-administrator.test.js +111 -0
- package/dist/src/services/application/__tests__/app-bootstrap.approving-administrator.test.js.map +1 -0
- package/dist/src/services/application/__tests__/provider-package-links.service.test.js +68 -0
- package/dist/src/services/application/__tests__/provider-package-links.service.test.js.map +1 -1
- package/dist/src/services/application/app-bootstrap.service.d.ts +9 -0
- package/dist/src/services/application/app-bootstrap.service.d.ts.map +1 -1
- package/dist/src/services/application/app-bootstrap.service.js +30 -1
- package/dist/src/services/application/app-bootstrap.service.js.map +1 -1
- package/dist/src/services/application/application-runtime-bootstrap.service.d.ts +6 -0
- package/dist/src/services/application/application-runtime-bootstrap.service.d.ts.map +1 -1
- package/dist/src/services/application/application-runtime-bootstrap.service.js +41 -0
- package/dist/src/services/application/application-runtime-bootstrap.service.js.map +1 -1
- package/dist/src/services/application/provider-package-links.service.d.ts +30 -0
- package/dist/src/services/application/provider-package-links.service.d.ts.map +1 -1
- package/dist/src/services/application/provider-package-links.service.js +35 -3
- package/dist/src/services/application/provider-package-links.service.js.map +1 -1
- package/dist/src/services/application/provider-runtime-sync.service.d.ts.map +1 -1
- package/dist/src/services/application/provider-runtime-sync.service.js +4 -3
- package/dist/src/services/application/provider-runtime-sync.service.js.map +1 -1
- package/dist/src/services/application/saas-skeleton.service.d.ts.map +1 -1
- package/dist/src/services/application/saas-skeleton.service.js +22 -2
- package/dist/src/services/application/saas-skeleton.service.js.map +1 -1
- package/dist/src/services/companion/workbench-cli.service.js +10 -1
- package/dist/src/services/companion/workbench-cli.service.js.map +1 -1
- package/dist/src/services/credentials/__tests__/provider-contribution-registration.guard.test.d.ts +2 -0
- package/dist/src/services/credentials/__tests__/provider-contribution-registration.guard.test.d.ts.map +1 -0
- package/dist/src/services/credentials/__tests__/provider-contribution-registration.guard.test.js +94 -0
- package/dist/src/services/credentials/__tests__/provider-contribution-registration.guard.test.js.map +1 -0
- package/dist/src/services/credentials/ci-secrets-adapter.service.d.ts.map +1 -1
- package/dist/src/services/credentials/ci-secrets-adapter.service.js +16 -0
- package/dist/src/services/credentials/ci-secrets-adapter.service.js.map +1 -1
- package/dist/src/services/credentials/composed-provider-catalogue.d.ts +34 -0
- package/dist/src/services/credentials/composed-provider-catalogue.d.ts.map +1 -1
- package/dist/src/services/credentials/composed-provider-catalogue.js +35 -0
- package/dist/src/services/credentials/composed-provider-catalogue.js.map +1 -1
- package/dist/src/services/credentials/credentials.schemas.d.ts +27 -0
- package/dist/src/services/credentials/credentials.schemas.d.ts.map +1 -1
- package/dist/src/services/credentials/credentials.schemas.js +50 -0
- package/dist/src/services/credentials/credentials.schemas.js.map +1 -1
- package/dist/src/services/credentials/framework-managed-secrets.d.ts +1 -1
- package/dist/src/services/credentials/framework-managed-secrets.d.ts.map +1 -1
- package/dist/src/services/credentials/framework-managed-secrets.js +49 -8
- package/dist/src/services/credentials/framework-managed-secrets.js.map +1 -1
- package/dist/src/services/deployment/infra-writer.service.d.ts.map +1 -1
- package/dist/src/services/deployment/infra-writer.service.js +23 -4
- package/dist/src/services/deployment/infra-writer.service.js.map +1 -1
- package/dist/src/services/deployment/k8s/__tests__/k8s-bootstrap.service.test.js +45 -2
- package/dist/src/services/deployment/k8s/__tests__/k8s-bootstrap.service.test.js.map +1 -1
- package/dist/src/services/deployment/k8s/k8s-bootstrap.service.d.ts +23 -0
- package/dist/src/services/deployment/k8s/k8s-bootstrap.service.d.ts.map +1 -1
- package/dist/src/services/deployment/k8s/k8s-bootstrap.service.js +49 -6
- package/dist/src/services/deployment/k8s/k8s-bootstrap.service.js.map +1 -1
- package/dist/src/services/environment/env-vars-builder.service.d.ts.map +1 -1
- package/dist/src/services/environment/env-vars-builder.service.js +19 -0
- package/dist/src/services/environment/env-vars-builder.service.js.map +1 -1
- package/dist/src/services/framework/__tests__/engine-provider-specifications.reconciliation.test.js +8 -0
- package/dist/src/services/framework/__tests__/engine-provider-specifications.reconciliation.test.js.map +1 -1
- package/dist/src/services/framework/__tests__/framework-knowledge-audit.live.contract.test.js +17 -0
- package/dist/src/services/framework/__tests__/framework-knowledge-audit.live.contract.test.js.map +1 -1
- package/dist/src/services/framework/__tests__/framework-knowledge-audit.service.test.js +51 -0
- package/dist/src/services/framework/__tests__/framework-knowledge-audit.service.test.js.map +1 -1
- package/dist/src/services/framework/framework-knowledge-audit.service.d.ts +41 -1
- package/dist/src/services/framework/framework-knowledge-audit.service.d.ts.map +1 -1
- package/dist/src/services/framework/framework-knowledge-audit.service.js +90 -0
- package/dist/src/services/framework/framework-knowledge-audit.service.js.map +1 -1
- package/dist/src/services/framework/provider-transposition/__tests__/base-url-is-a-declared-env-slot.test.d.ts +2 -0
- package/dist/src/services/framework/provider-transposition/__tests__/base-url-is-a-declared-env-slot.test.d.ts.map +1 -0
- package/dist/src/services/framework/provider-transposition/__tests__/base-url-is-a-declared-env-slot.test.js +100 -0
- package/dist/src/services/framework/provider-transposition/__tests__/base-url-is-a-declared-env-slot.test.js.map +1 -0
- package/dist/src/services/framework/provider-transposition/__tests__/plan-matches-emit.test.js +55 -2
- package/dist/src/services/framework/provider-transposition/__tests__/plan-matches-emit.test.js.map +1 -1
- package/dist/src/services/framework/provider-transposition/provider-package.emitter.d.ts +9 -0
- package/dist/src/services/framework/provider-transposition/provider-package.emitter.d.ts.map +1 -1
- package/dist/src/services/framework/provider-transposition/provider-package.emitter.js +139 -19
- package/dist/src/services/framework/provider-transposition/provider-package.emitter.js.map +1 -1
- package/dist/src/services/frontend/cloudflare-cdn.service.d.ts.map +1 -1
- package/dist/src/services/frontend/cloudflare-cdn.service.js +33 -2
- package/dist/src/services/frontend/cloudflare-cdn.service.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +17 -17
- package/scripts/app-dependency-alignment/propagated-engine-overrides.json +13 -0
- package/templates/infra/docker-compose/docker-compose.wildo-platform.yml.hbs +64 -16
- package/templates/saas/engine-peer-closure.json +12 -0
- package/templates/saas/scenarios/add-provider/scenario.json +11 -11
- package/templates/saas/scenarios/add-technical-doc/files/technical-doc/docusaurus.config.ts.hbs +34 -0
- package/templates/saas/scenarios/add-technical-doc/files/technical-doc/src/pages/auth/exchange.tsx +24 -1
- package/templates/saas/scenarios/add-technical-doc/files/technical-doc/src/theme/Root.tsx +22 -2
- package/templates/saas/skeleton/backend-api/package.json.hbs +1 -1
- package/templates/saas/skeleton/backend-api/src/companion-exports.ts +13 -2
- package/wildo-framework.info.json +1 -1
- package/templates/saas/scenarios/add-backend-provider/scenario.json +0 -17
- package/templates/saas/skeleton/backend-api/src/provider-contributions.ts +0 -44
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"saas-skeleton.service.js","sourceRoot":"","sources":["../../../../src/services/application/saas-skeleton.service.ts"],"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OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAC7E,CAAC;CACF,CAAC","sourcesContent":["/**\n * SaasSkeletonService — materialize a full, bootable-after-setup application\n * skeleton from `templates/saas/skeleton/` (issue #51, T1–T10).\n *\n * The template tree carries three file classes:\n * - plain files, copied verbatim (`tsconfig.common.json`, package sources, …);\n * - `*.hbs` files, rendered through the shared Handlebars `TemplateProcessor`\n * with the app identity + ALLOCATED ports (D4: two applications sharing a\n * framework checkout must never collide on ports);\n * - `gitignore`, written as `.gitignore` (a literal dotfile inside the\n * template tree would make git ignore the template's own files).\n *\n * Two files are DERIVED rather than templated, per the T4 rule (\"derived from\n * the framework's current override set, never a frozen copy\"):\n * - the root `package.json` — its `pnpm.overrides` are computed live from\n * `scripts/app-dependency-alignment/propagated-engine-overrides.json`\n * (names) joined with the framework root's `pnpm.overrides` (versions),\n * plus, in framework-developer mode, `file:` links for every\n * `frameworkFileLinkPackages` entry resolved through the framework's own\n * pnpm-workspace;\n * - `.wildo-saas/dev-framework-scripts/run-dev-stack.sh` — its\n * `pnpm --filter` package lists are the scaffolded workspace members.\n *\n * DUAL MODE (D7 — both modes authored from the start). Both are live: the npm\n * publish lane put all twenty declared packages on the registry at 1.1.1 on\n * 2026-08-31, `@wildo-ai/dev-companion` among them, so app-creator mode installs\n * and delivers like any other consumer:\n * - `framework-dev`: `file:` overrides into the checkout, dev-framework\n * scripts installed, companion dist delivered via\n * `scripts/dev-orchestrator/dev-companion-deliver.mjs`;\n * - `app-creator`: `@wildo-ai/*` overrides pinned to the published framework\n * version; the companion drop is a re-export shim over the published\n * `@wildo-ai/dev-companion`, keeping the framework-dev entry layout.\n */\nimport { spawnSync } from 'child_process';\nimport { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, chmodSync } from 'fs';\nimport { dirname, join, relative } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport { TemplateProcessor } from '~wildo-cli/infrastructure/io/template-processor';\nimport { COMPANION_PORT_OFFSET, WORKBENCH_PORT_OFFSET } from '~wildo-cli/services/application/application-dev-port-offsets';\nimport {\n APPLICATION_DEPENDENCY_EXCLUSIONS_RELATIVE,\n ApplicationDependencyAlignmentService,\n} from '~wildo-cli/services/application/application-dependency-alignment.service';\nimport {\n ProviderPackageLinksService,\n readFrameworkWorkspacePackages,\n} from '~wildo-cli/services/application/provider-package-links.service';\nimport { resolveFrameworkRootManifestPath } from '~wildo-cli/services/framework/installed-framework-assets.service';\n\n/**\n * The two delivery modes every skeleton artifact is authored for (issue #51 D7).\n * The mode decides the root manifest's dependency story and which dev tooling\n * the scaffold materializes — it never changes the application's own sources.\n */\nexport enum SkeletonMode {\n /**\n * In-repo example app beside the framework checkout: `file:` overrides into\n * the checkout's workspace packages, dev-framework scripts installed, and the\n * companion dist delivered straight from the framework build.\n */\n FRAMEWORK_DEV = 'framework-dev',\n /**\n * Standalone app consuming published `@wildo-ai/*` versions. No framework\n * scripts; the companion arrives as a shim over the published\n * `@wildo-ai/dev-companion` rather than as a hard-linked build mirror. The\n * root `dev` script runs the workspace members' own dev scripts.\n */\n APP_CREATOR = 'app-creator',\n}\n\nexport interface SkeletonPorts {\n backend: number;\n app: number;\n companion: number;\n workbench: number;\n}\n\nexport interface SaasSkeletonOptions {\n name: string;\n frameworkPath: string | null;\n mode: SkeletonMode;\n portBase?: number;\n skipInstall?: boolean;\n log: { info(message: string): void; warn(message: string): void };\n}\n\nexport interface SaasSkeletonResult {\n slug: string;\n ports: SkeletonPorts;\n filesWritten: number;\n companionDelivered: boolean;\n installed: boolean;\n built: boolean;\n}\n\nconst SKELETON_TEMPLATE_RELATIVE = 'templates/saas/skeleton';\nconst OVERRIDES_MANIFEST_RELATIVE = 'scripts/app-dependency-alignment/propagated-engine-overrides.json';\nconst COMPANION_DELIVER_RELATIVE = 'scripts/dev-orchestrator/dev-companion-deliver.mjs';\n/**\n * The workspace members `buildWorkspaceYaml` declares, minus the two GENERATED drops (their\n * manifests are written by their own generators and would overwrite anything injected here).\n * Kept beside that function on purpose: the two lists describe the same scaffold and must move\n * together.\n */\nconst SCAFFOLDED_WORKSPACE_MEMBERS = ['.', 'specifications', 'shared-lib', 'backend-api', 'frontend'] as const;\n\nconst DEFAULT_PORT_BASE = 4241;\nconst PORT_BASE_STRIDE = 10;\n\nfunction toSlug(name: string): string {\n return name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\nfunction toDisplayName(name: string): string {\n return name\n .replace(/[-_]+/g, ' ')\n .replace(/\\b\\w/g, c => c.toUpperCase());\n}\n\n/**\n * Allocate the app's port base by scanning every sibling application's AUTHORED\n * port declarations under `<framework>/examples/*` (saas config `defaultPort:`\n * plus infra `port:` values). The next free `PORT_BASE_STRIDE` block above the\n * highest occupied one wins, so a second app lands at 4251 beside Wonder\n * Todos' 4241–4244 instead of silently colliding (the exact failure of the\n * 2026-08-25 hand bootstrap that T8/D4 records).\n */\nfunction allocatePortBase(frameworkPath: string | null): number {\n const used = collectUsedApplicationPorts(frameworkPath);\n // Walk stride-aligned bases upward until BOTH the service block (base..base+stride-1)\n // and the derived companion port (base+offset) are free of every scanned port.\n for (let base = DEFAULT_PORT_BASE; base < 5000; base += PORT_BASE_STRIDE) {\n if (portBlockIsFree(base, used)) {\n return base;\n }\n }\n // Exhaustion must REFUSE, not silently hand back the default base — returning\n // 4241 here would scaffold an app directly onto Wonder Todos' ports, which is\n // the exact collision this allocator exists to prevent.\n throw new Error(\n 'No free application port block found in the 4000-4999 tier (stride 10 + companion offset 100). '\n + 'Pass an explicit --port-base outside the scanned range, or retire an unused sibling application.',\n );\n}\n\n/** True when the whole service block AND both derived tool ports avoid every scanned port. */\nfunction portBlockIsFree(base: number, used: ReadonlySet<number>): boolean {\n const blockPorts = Array.from({ length: PORT_BASE_STRIDE }, (_, i) => base + i);\n return blockPorts.every((port) => !used.has(port))\n && !used.has(base + COMPANION_PORT_OFFSET)\n && !used.has(base + WORKBENCH_PORT_OFFSET);\n}\n\n/** Collect every authored sibling port (saas `defaultPort:` + infra `port:`) in the 4xxx tier. */\nfunction collectUsedApplicationPorts(frameworkPath: string | null): Set<number> {\n const usedPorts: number[] = [];\n if (frameworkPath) {\n const examplesHome = join(frameworkPath, 'examples');\n if (existsSync(examplesHome)) {\n for (const entry of readdirSync(examplesHome, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const appRoot = join(examplesHome, entry.name);\n for (const candidate of [\n join(appRoot, 'wildo.saas.config.ts'),\n join(appRoot, 'infrastructure/local/wildo.infra.local.config.ts'),\n ]) {\n if (!existsSync(candidate)) continue;\n const source = readFileSync(candidate, 'utf8');\n for (const match of source.matchAll(/(?:defaultPort|port)\\s*:\\s*(\\d{4,5})/g)) {\n usedPorts.push(Number(match[1]));\n }\n }\n }\n }\n }\n return new Set(usedPorts.filter((port) => port >= 4000 && port < 5000));\n}\n\n\ninterface OverridesManifest {\n propagatedOverrideKeys?: string[];\n frameworkFileLinkPackages?: string[];\n}\n\nfunction buildRootOverrides(input: {\n appRoot: string;\n frameworkPath: string;\n mode: SkeletonMode;\n}): Record<string, string> {\n const manifest = JSON.parse(\n readFileSync(join(input.frameworkPath, OVERRIDES_MANIFEST_RELATIVE), 'utf8'),\n ) as OverridesManifest;\n // Through the resolver, never `<root>/package.json`: in an INSTALLED framework-assets root that\n // file is the CLI's own manifest, and the framework root manifest ships beside it under another\n // name (`installed-framework-assets.service.ts`).\n const frameworkRootManifest = JSON.parse(\n readFileSync(resolveFrameworkRootManifestPath(input.frameworkPath), 'utf8'),\n ) as { version?: string; pnpm?: { overrides?: Record<string, string> } };\n const frameworkOverrides = frameworkRootManifest.pnpm?.overrides ?? {};\n const frameworkInfo = JSON.parse(\n readFileSync(join(input.frameworkPath, 'wildo-framework.info.json'), 'utf8'),\n ) as { version: string };\n\n const overrides: Record<string, string> = {};\n\n /*\n * The framework CORE — every application links all of it, so the authored list is the decision.\n * The PROVIDER packages are handled below and are demand-driven: see\n * `ProviderPackageLinksService`. Keeping the two apart is what stops a scaffolded application\n * carrying two hundred `file:` links to packages it never imports (plan D7, issue #334).\n */\n if (input.mode === SkeletonMode.FRAMEWORK_DEV) {\n const workspacePackages = readFrameworkWorkspacePackages(input.frameworkPath);\n for (const packageName of manifest.frameworkFileLinkPackages ?? []) {\n const workspacePackage = workspacePackages.get(packageName);\n if (!workspacePackage) {\n throw new Error(\n `frameworkFileLinkPackages names '${packageName}' but no framework workspace member carries that name — `\n + `fix ${OVERRIDES_MANIFEST_RELATIVE} or the workspace.`,\n );\n }\n overrides[packageName] = `file:${relative(input.appRoot, workspacePackage.root)}`;\n }\n } else {\n for (const packageName of manifest.frameworkFileLinkPackages ?? []) {\n overrides[packageName] = frameworkInfo.version;\n }\n }\n\n /*\n * Provider packages the application ALREADY declares. At `wildo init` this is empty by\n * construction — a fresh scaffold declares no provider — and that is the point: a provider link\n * appears only after `wildo compose add-provider` writes the dependency, and it appears for that\n * provider alone. The same resolution runs again after every `wildo compose`, which is what makes\n * the scenario a single command rather than a scenario plus a hand-written override.\n */\n const providerLinks = ProviderPackageLinksService.resolveProviderOverrides({\n applicationRoot: input.appRoot,\n frameworkWorkspacePackages: input.mode === SkeletonMode.FRAMEWORK_DEV\n ? readFrameworkWorkspacePackages(input.frameworkPath)\n : null,\n frameworkVersion: frameworkInfo.version,\n });\n for (const [packageName, overrideValue] of Object.entries(providerLinks.overrides)) {\n overrides[packageName] = overrideValue;\n }\n\n for (const key of manifest.propagatedOverrideKeys ?? []) {\n const version = frameworkOverrides[key];\n if (!version) {\n throw new Error(\n `propagatedOverrideKeys names '${key}' but the framework root pnpm.overrides carries no version for it.`,\n );\n }\n overrides[key] = version;\n }\n\n return Object.fromEntries(Object.entries(overrides).sort(([a], [b]) => a.localeCompare(b)));\n}\n\nfunction buildRootPackageJson(input: {\n slug: string;\n appRoot: string;\n frameworkPath: string | null;\n mode: SkeletonMode;\n}): string {\n const frameworkRootManifest = input.frameworkPath\n ? JSON.parse(readFileSync(resolveFrameworkRootManifestPath(input.frameworkPath), 'utf8')) as { packageManager?: string }\n : {};\n\n const manifest: Record<string, unknown> = {\n name: `@${input.slug}/root`,\n version: '1.0.0',\n private: true,\n ...(frameworkRootManifest.packageManager ? { packageManager: frameworkRootManifest.packageManager } : {}),\n scripts: {\n // `run-dev-stack.sh` is only WRITTEN in framework-dev mode; an app-creator\n // manifest pointing at it would ship a `pnpm dev` that fails on a missing\n // file. App-creator runs the workspace members' own dev scripts directly.\n ...(input.mode === SkeletonMode.FRAMEWORK_DEV\n ? {\n dev: 'bash .wildo-saas/dev-framework-scripts/run-dev-stack.sh full',\n 'dev:sync': 'bash .wildo-saas/dev-framework-scripts/sync-engine.sh',\n }\n : { dev: 'pnpm --parallel -r run dev' }),\n build: 'turbo build',\n clean: 'turbo run clean',\n },\n ...(input.frameworkPath\n ? { pnpm: { overrides: buildRootOverrides({ appRoot: input.appRoot, frameworkPath: input.frameworkPath, mode: input.mode }) } }\n : {}),\n devDependencies: {\n '@wildo-ai/external-connectors-models': '*',\n // The compiled agent knowledge (skills, rules, references) `wildo assets sync` delivers into\n // `.claude/` and `.wildo-saas/docs/`. Declared at the ROOT so the CLI resolves it from the\n // application without knowing which workspace member happens to depend on it transitively.\n '@wildo-ai/framework-knowledge': '*',\n '@wildo-ai/platform-config-lib': '*',\n '@wildo-ai/saas-models': '*',\n tsx: '^4.21.0',\n turbo: '^2.8.11',\n },\n };\n return `${JSON.stringify(manifest, null, 2)}\\n`;\n}\n\nfunction buildWorkspaceYaml(): string {\n return [\n 'packages:',\n \" - 'specifications'\",\n \" - 'shared-lib'\",\n \" - 'backend-api'\",\n \" - 'frontend'\",\n ' # The dev companion drop: a GENERATED dist-only delivery (see the app',\n ' # .gitignore); its manifest is a workspace member so its dependencies',\n ' # resolve like every other package.',\n \" - '.wildo-saas/wildo-dev-companion'\",\n ' # The application-creation workbench drop: a launcher, not a delivery. Unlike the',\n ' # companion it carries no dist — in framework-dev mode it runs Vite against the',\n ' # framework source. It is a workspace member so `pnpm --filter` can reach it from',\n ' # the app root, which is what puts it in the dev stack beside everything else.',\n ' #',\n ' # Listed unconditionally, though an APP-CREATOR install never materializes the',\n ' # directory (it has no framework source to run Vite against). That is safe, and',\n ' # measured rather than assumed: a `packages:` entry naming a directory that does',\n ' # not exist is silently ignored — `pnpm install` exits 0, reports no warning, and',\n ' # does not count it among the workspace projects. The companion entry above has',\n ' # relied on the same behaviour for as long as it has existed, since it too is',\n ' # absent until its dist is delivered.',\n \" - '.wildo-saas/application-creation-workbench'\",\n '',\n ].join('\\n');\n}\n\nfunction buildRunDevStack(slug: string): string {\n return `#!/bin/bash\n\n# GENERATED by \\`wildo init\\` (issue #51 T9) — the mode→package dispatch mirrors\n# this application's workspace members. Regenerate by re-running the scaffolder\n# rather than hand-editing the filter lists.\n#\n# \\`full\\` DERIVES its set rather than listing it, and that is the whole point of the\n# mode. An application GROWS workspace members after \\`wildo init\\` — \\`wildo compose\n# add-website\\`, \\`add-technical-doc\\`, \\`add-minion\\`, \\`add-worker-node\\` each append one\n# — and no scenario edits this file. A hand-written list here is therefore a second\n# enumeration of a population somebody else owns, and it drifted exactly that way: a\n# composed documentation portal was a declared service, a workspace member, and an\n# allocated port, and \\`full\\` never started it. Nothing reported that, because an\n# unlisted package simply does not appear.\n#\n# \\`pnpm -r\\` runs \\`dev\\` in every workspace package that HAS one, which is the honest\n# reading of \"the full stack\" and cannot fall behind a scenario. The narrow modes below\n# stay explicit: each names a deliberate subset, so listing is what they are for.\n\nset -u\nset -o pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nMODE=\"\\${1:-full}\"\n\ncase \"$MODE\" in\n full)\n STACK_COMMAND=(\n pnpm --parallel -r\n run dev\n )\n ;;\n backend)\n STACK_COMMAND=(\n pnpm --parallel\n --filter @${slug}/specifications\n --filter @${slug}/shared-lib\n --filter @${slug}/backend-api\n run dev\n )\n ;;\n companion)\n STACK_COMMAND=(\n pnpm --parallel\n --filter @${slug}/specifications\n --filter @${slug}/shared-lib\n --filter @wildo-ai/dev-companion\n run dev\n )\n ;;\n frontend)\n STACK_COMMAND=(\n pnpm --parallel\n --filter @${slug}/main-app\n run dev\n )\n ;;\n # The workbench ALONE, for iterating on the tool itself. It talks to a companion over HTTP\n # rather than importing it, so it runs perfectly well against a companion already started by\n # another mode — and starting it here does not drag the application's stack along.\n workbench)\n STACK_COMMAND=(\n pnpm --parallel\n --filter @wildo-ai/application-creation-workbench\n run dev\n )\n ;;\n *)\n echo \"[dev-stack] Unknown mode: $MODE\"\n echo \"[dev-stack] Expected one of: full, backend, companion, frontend, workbench\"\n exit 1\n ;;\nesac\n\nif [ -f \"$SCRIPT_DIR/sync-engine.sh\" ]; then\n \"$SCRIPT_DIR/sync-engine.sh\" &\n SYNC_PID=$!\n HAS_CLEANED_UP=0\n\n cleanup() {\n if [ \"$HAS_CLEANED_UP\" -eq 1 ]; then\n return\n fi\n HAS_CLEANED_UP=1\n if kill -0 \"$SYNC_PID\" 2>/dev/null; then\n kill \"$SYNC_PID\" 2>/dev/null || true\n wait \"$SYNC_PID\" 2>/dev/null || true\n fi\n }\n\n trap cleanup EXIT INT TERM\nfi\n\n\"\\${STACK_COMMAND[@]}\"\n`;\n}\n\n/**\n * Declare, in every scaffolded workspace package, the engine peers it must SUPPLY (issue #167).\n *\n * A pnpm override rewrites a specifier that some manifest wrote down; it never creates one. A peer\n * nobody declares therefore falls to `autoInstallPeers`, whose resolution is STICKY: correct on a\n * fresh lockfile, and frozen at whatever predates the override otherwise. So an application that\n * does not declare the engine's peers cannot receive a later pin bump — moving a root pin from `^6`\n * to `^7` leaves it on 6 with a warning and no remedy short of deleting its lockfile.\n *\n * Each name is written as `\"*\"`, never a version: the root `pnpm.overrides` block written beside it\n * already carries the pin, so a framework bump reaches the application with no edit here.\n *\n * The name set is READ from the generated `enginePeerClosure` rather than re-derived. That map is\n * produced and gated by `scripts/app-dependency-alignment.mjs`; only the trivial union lookup is\n * repeated here, because this service is compiled TypeScript in another package and cannot import\n * the repository's `.mjs` derivation.\n *\n * Nothing is ever removed — the same restraint the reconciler applies. A template-authored peer that\n * the closure does not require (`ufo`, today) is the application's own declaration, and a shared name\n * is not evidence of shared ownership.\n */\nfunction declareEnginePeersInScaffoldedPackages(input: { appRoot: string; frameworkPath: string }): void {\n const manifestPath = join(input.frameworkPath, OVERRIDES_MANIFEST_RELATIVE);\n if (!existsSync(manifestPath)) return;\n const { enginePeerClosure } = JSON.parse(readFileSync(manifestPath, 'utf8')) as {\n enginePeerClosure?: Record<string, string[]>;\n };\n if (!enginePeerClosure) return;\n\n for (const member of SCAFFOLDED_WORKSPACE_MEMBERS) {\n const packageJsonPath = join(input.appRoot, member, 'package.json');\n if (!existsSync(packageJsonPath)) continue;\n const manifest = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as Record<string, Record<string, string> | unknown>;\n\n const frameworkDependencies = new Set<string>();\n for (const field of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {\n for (const name of Object.keys((manifest[field] as Record<string, string> | undefined) ?? {})) {\n if (name.startsWith('@wildo-ai/')) frameworkDependencies.add(name);\n }\n }\n const required = new Set<string>();\n for (const dependencyName of frameworkDependencies) {\n for (const peerName of enginePeerClosure[dependencyName] ?? []) required.add(peerName);\n }\n // A name the package already declares as a real dependency needs no peer entry: the override\n // reaches it there.\n for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {\n for (const name of Object.keys((manifest[field] as Record<string, string> | undefined) ?? {})) required.delete(name);\n }\n if (required.size === 0) continue;\n\n const peers = { ...((manifest.peerDependencies as Record<string, string> | undefined) ?? {}) };\n for (const name of required) peers[name] = '*';\n manifest.peerDependencies = Object.fromEntries(Object.keys(peers).sort().map((name) => [name, peers[name]]));\n writeFileSync(packageJsonPath, `${JSON.stringify(manifest, null, 2)}\\n`, 'utf8');\n }\n}\n\n/**\n * Seed the application's dependency-exclusion list from the framework's own `deliberatelyExcluded`\n * (issue #222).\n *\n * The list names third-party packages that `wildo align-deps` must NEVER pin to the engine's version\n * because the application's own toolchain owns them — `esbuild` follows vite, `express` follows\n * webpack-dev-server, `mime` follows express, plus astro / docusaurus / jest / tailwindcss /\n * typescript. Each entry was measured against a real collision, not guessed.\n *\n * SEEDED, then APPLICATION-OWNED. The framework's copy is a judgement about a typical application's\n * stack; a real application knows its own better, and it is the one that breaks when the judgement is\n * wrong. The cost is that a later framework exclusion does not reach an existing application — which\n * is the right trade, because the conflict being described is the application's, not the framework's.\n */\nfunction seedDependencyExclusions(input: { appRoot: string; frameworkPath: string }): void {\n const excludedNames = ApplicationDependencyAlignmentService.readFrameworkExclusions(input.frameworkPath);\n if (Object.keys(excludedNames).length === 0) return;\n const targetPath = join(input.appRoot, APPLICATION_DEPENDENCY_EXCLUSIONS_RELATIVE);\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileSync(targetPath, `${JSON.stringify({\n 'purpose-note':\n 'Names `wildo align-deps` must never pin to the framework version, because THIS application\\'s '\n + 'toolchain owns them. Seeded at `wildo init` from the framework of the day and yours from here: '\n + 'edit it when your stack needs a major the framework does not pin. A key ending in `*` is a '\n + 'prefix match. The value is the reason, and is never read by any tool — it is for whoever '\n + 'reads this file next.',\n excludedNames,\n }, null, 2)}\\n`, 'utf8');\n}\n\n/** Recursively materialize the template tree into the app root. */\nfunction materializeTemplateTree(input: {\n templateRoot: string;\n appRoot: string;\n mode: SkeletonMode;\n variables: Record<string, unknown>;\n processor: TemplateProcessor;\n}): number {\n let written = 0;\n const walk = (relativeDir: string) => {\n for (const entry of readdirSync(join(input.templateRoot, relativeDir), { withFileTypes: true })) {\n const relativePath = relativeDir ? join(relativeDir, entry.name) : entry.name;\n if (entry.isDirectory()) {\n walk(relativePath);\n continue;\n }\n if (!entry.isFile()) continue;\n\n // Framework-checkout dev-loop files: an app-creator install has no framework\n // scripts to call into, so neither the dev-framework-scripts home nor the\n // supervised dev wrappers (frontend Vite+library watcher, backend-api\n // watcher+runtime supervisor) are materialized there.\n if (\n input.mode === SkeletonMode.APP_CREATOR\n && (\n relativePath.startsWith(join('.wildo-saas', 'dev-framework-scripts'))\n // The workbench drop launches Vite against FRAMEWORK SOURCE, which an app-creator\n // install does not have. Materializing it there would produce a dev-stack member that\n // exits with \"the workbench runs against framework source\" on every start.\n || relativePath.startsWith(join('.wildo-saas', 'application-creation-workbench'))\n || relativePath === join('frontend', 'scripts', 'dev-supervised.sh')\n || relativePath === join('backend-api', 'scripts', 'dev-supervised.sh.hbs')\n )\n ) {\n continue;\n }\n\n let targetRelative = relativePath;\n let content: string | null = null;\n if (entry.name.endsWith('.init.hbs')) {\n // `.init.hbs` marks the INIT-time variant of a file whose later evolution belongs to a\n // service or scenario (e.g. `wildo.saas.config.ts.init.hbs` — the config service owns\n // post-init parametrization). Rendered once here, then never re-templated.\n targetRelative = relativePath.slice(0, -'.init.hbs'.length);\n content = input.processor.processTemplate(relativePath, input.variables);\n } else if (entry.name.endsWith('.hbs')) {\n targetRelative = relativePath.slice(0, -'.hbs'.length);\n content = input.processor.processTemplate(relativePath, input.variables);\n } else if (entry.name === 'gitignore' && relativeDir === '') {\n targetRelative = '.gitignore';\n }\n\n const targetPath = join(input.appRoot, targetRelative);\n mkdirSync(dirname(targetPath), { recursive: true });\n if (content !== null) {\n writeFileSync(targetPath, content, 'utf8');\n } else {\n copyFileSync(join(input.templateRoot, relativePath), targetPath);\n }\n // Keyed on the RENDERED name so a future `*.sh.hbs` template still lands executable.\n if (targetRelative.endsWith('.sh')) chmodSync(targetPath, 0o755);\n written += 1;\n }\n };\n walk('');\n return written;\n}\n\nfunction runStep(input: {\n log: SaasSkeletonOptions['log'];\n label: string;\n command: string;\n args: string[];\n cwd: string;\n}): boolean {\n input.log.info(` ${input.label}…`);\n const result = spawnSync(input.command, input.args, { cwd: input.cwd, stdio: 'inherit' });\n if (result.status !== 0) {\n input.log.warn(` ${input.label} failed (exit ${result.status ?? 'signal'}). Fix and re-run manually.`);\n return false;\n }\n return true;\n}\n\n/**\n * Files the scaffold writes at the APP ROOT. Their presence in the target\n * directory means the scaffold would OVERWRITE an existing project — most\n * dangerously the framework checkout itself, whose root carries every one of\n * these names (`wildo init` run from the monorepo root would clobber the\n * framework's own package.json / pnpm-workspace.yaml / turbo.json).\n */\nconst ROOT_COLLISION_FILES = [\n 'package.json',\n 'pnpm-workspace.yaml',\n 'turbo.json',\n 'wildo.saas.config.ts',\n 'tsconfig.common.json',\n '.gitignore',\n] as const;\n\nexport const SaasSkeletonService = {\n allocatePortBase,\n collectUsedApplicationPorts,\n buildRootOverrides,\n\n scaffold(appRoot: string, options: SaasSkeletonOptions): SaasSkeletonResult {\n const safeName = options.name.replace(/['\"\\\\]/g, '');\n const slug = toSlug(safeName) || 'app';\n const displayName = toDisplayName(safeName || slug) || 'App';\n\n if (options.mode === SkeletonMode.FRAMEWORK_DEV && !options.frameworkPath) {\n throw new Error('framework-dev skeleton mode requires a resolved framework checkout.');\n }\n\n // Refuse a NON-EMPTY target before writing anything: the scaffold is a\n // whole-project materialization, not a merge. Fail-closed here protects the\n // framework checkout root (which carries all of these files) and any\n // half-scaffolded directory from a silent clobber.\n const collisions = ROOT_COLLISION_FILES.filter((file) => existsSync(join(appRoot, file)));\n if (collisions.length > 0) {\n throw new Error(\n `Target directory already contains ${collisions.join(', ')} — refusing to scaffold over an existing project. `\n + 'Run `wildo init` in an empty directory (or delete the partial scaffold first).',\n );\n }\n\n // An EXPLICIT --port-base is validated against the same sibling scan the\n // allocator uses — accepting a colliding base would recreate the exact\n // hand-bootstrap failure the allocator was built to prevent.\n if (options.portBase !== undefined) {\n const used = collectUsedApplicationPorts(options.frameworkPath);\n if (!portBlockIsFree(options.portBase, used)) {\n throw new Error(\n `--port-base ${options.portBase} collides with a sibling application's authored ports `\n + `(block ${options.portBase}-${options.portBase + PORT_BASE_STRIDE - 1} or companion port ${options.portBase + COMPANION_PORT_OFFSET}). `\n + `Next free base: ${allocatePortBase(options.frameworkPath)}.`,\n );\n }\n }\n const portBase = options.portBase ?? allocatePortBase(options.frameworkPath);\n const ports: SkeletonPorts = {\n backend: portBase,\n app: portBase + 1,\n companion: portBase + COMPANION_PORT_OFFSET,\n workbench: portBase + WORKBENCH_PORT_OFFSET,\n };\n\n const templateRoot = options.frameworkPath\n ? join(options.frameworkPath, SKELETON_TEMPLATE_RELATIVE)\n : null;\n if (!templateRoot || !existsSync(templateRoot)) {\n throw new Error(\n 'Application skeleton templates not found'\n + (templateRoot ? ` at ${templateRoot}` : ' (no framework-assets root resolved)')\n + '. The full-skeleton scaffold needs the framework templates: a framework checkout, or a `@wildo-ai/wildo-cli` '\n + 'installed from npm (which ships them). Use --config-only to write only wildo.saas.config.ts.',\n );\n }\n\n const variables = {\n slug,\n displayName,\n backendPort: ports.backend,\n appPort: ports.app,\n companionPort: ports.companion,\n workbenchPort: ports.workbench,\n // Mode conditionals inside `.hbs` templates ({{#if isFrameworkDev}}): framework-dev\n // renders engine-source aliasing/tsconfig-paths/dev-supervision; app-creator renders\n // the standalone shape (published packages, plain vite dev).\n isFrameworkDev: options.mode === SkeletonMode.FRAMEWORK_DEV,\n };\n\n const processor = new TemplateProcessor(templateRoot);\n let filesWritten = materializeTemplateTree({\n templateRoot,\n appRoot,\n mode: options.mode,\n variables,\n processor,\n });\n\n // `.claude/` is framework-delivered in framework-dev mode (materialized by `wildo fwk\n // dev-skills`, synchronized on framework update) — ignoring it avoids duplicating the\n // compiled knowledge product in git. App-creator applications COMMIT their `.claude`, so\n // the block is mode-conditional rather than part of the template gitignore.\n if (options.mode === SkeletonMode.FRAMEWORK_DEV) {\n appendFileSync(\n join(appRoot, '.gitignore'),\n '\\n# Framework-delivered agent knowledge (framework-dev mode only) — materialized by\\n'\n + '# `wildo fwk dev-skills`, synchronized on framework update; never commit in this mode.\\n'\n + '.claude/\\n',\n 'utf8',\n );\n }\n\n writeFileSync(join(appRoot, 'package.json'), buildRootPackageJson({\n slug,\n appRoot,\n frameworkPath: options.frameworkPath,\n mode: options.mode,\n }), 'utf8');\n writeFileSync(join(appRoot, 'pnpm-workspace.yaml'), buildWorkspaceYaml(), 'utf8');\n\n if (options.frameworkPath) {\n declareEnginePeersInScaffoldedPackages({ appRoot, frameworkPath: options.frameworkPath });\n seedDependencyExclusions({ appRoot, frameworkPath: options.frameworkPath });\n }\n\n // Deliver the engine EMAIL CANON (system + engine-resource templates) into the backend's\n // engine tree. System emails are runtime behavior — a fresh app without them has no welcome\n // email, no invitation email, etc. The canon at `templates/saas/i18n/email` is synced from\n // the dogfood (V2-P1 catch-up) and the app owns its copy from here (regenerated/extended by\n // `wildo generate email`).\n const emailCanonRoot = join(options.frameworkPath ?? '', 'templates', 'saas', 'i18n', 'email');\n if (options.frameworkPath && existsSync(emailCanonRoot)) {\n const emailTarget = join(appRoot, 'backend-api', 'src', 'engine', 'email');\n const copyTree = (relativeDir: string) => {\n for (const entry of readdirSync(join(emailCanonRoot, relativeDir), { withFileTypes: true })) {\n const entryRelative = relativeDir ? join(relativeDir, entry.name) : entry.name;\n if (entry.isDirectory()) {\n copyTree(entryRelative);\n } else if (entry.isFile()) {\n const targetPath = join(emailTarget, entryRelative);\n mkdirSync(dirname(targetPath), { recursive: true });\n copyFileSync(join(emailCanonRoot, entryRelative), targetPath);\n filesWritten += 1;\n }\n }\n };\n // The canon's own aggregator files are also shipped by the skeleton tree; the canon copy\n // wins nothing over them (byte-identical), so copying the whole tree is safe.\n copyTree('');\n } else {\n options.log.warn(' Email canon not found — backend system emails will be missing until delivered.');\n }\n const devScriptsDir = join(appRoot, '.wildo-saas', 'dev-framework-scripts');\n if (options.mode === SkeletonMode.FRAMEWORK_DEV) {\n mkdirSync(devScriptsDir, { recursive: true });\n const runDevStackPath = join(devScriptsDir, 'run-dev-stack.sh');\n writeFileSync(runDevStackPath, buildRunDevStack(slug), 'utf8');\n chmodSync(runDevStackPath, 0o755);\n filesWritten += 1;\n }\n filesWritten += 2;\n\n let companionDelivered = false;\n if (options.mode === SkeletonMode.FRAMEWORK_DEV && options.frameworkPath) {\n const deliverScript = join(options.frameworkPath, COMPANION_DELIVER_RELATIVE);\n const result = spawnSync(process.execPath, [\n deliverScript,\n '--framework-root', options.frameworkPath,\n '--app-root', appRoot,\n '--mode', SkeletonMode.FRAMEWORK_DEV,\n ], { stdio: 'inherit' });\n companionDelivered = result.status === 0;\n if (!companionDelivered) {\n options.log.warn(\n ' Companion delivery failed — build @wildo-ai/dev-companion in the framework, then re-run '\n + `node ${COMPANION_DELIVER_RELATIVE} --app-root ${appRoot}`,\n );\n }\n } else if (options.mode === SkeletonMode.APP_CREATOR) {\n /*\n * App-creator delivery is a SHIM, not a dist mirror.\n *\n * `dev-companion-deliver.mjs` hard-links the companion's `dist/` out of a local framework\n * checkout. An app-creator has no checkout — it has the published CLI and a registry — so that\n * path cannot serve this mode. What it CAN do is what every other package in the generated app\n * already does: declare a dependency and let `pnpm install` fetch it.\n *\n * The drop is a WORKSPACE MEMBER (see the `pnpm-workspace.yaml` this skeleton writes), so its\n * dependencies resolve exactly like `specifications/` or `backend-api/`.\n *\n * Why a re-export file rather than repointing `main` into `node_modules`: 31 files in this\n * repository address the drop through the fixed `dist/esm/index.js` layout. Keeping that layout\n * byte-for-byte means no consumer can tell the two delivery modes apart, which is the whole\n * point — a targeted shim beats a 31-file resolution refactor with no lasting architectural\n * gain.\n *\n * Location-sensitivity was ENUMERATED before trusting this, not assumed. The companion has six\n * `import.meta.url` sites; five resolve to files inside its own package and stay correct when\n * that package lives in `node_modules`. The sixth is `dotenv` looking for `../.env` from\n * `dist/esm`, i.e. `dist/.env` — which no delivered drop has ever contained (the drop's `.env`\n * sits at its root), so it is already a no-op and the shim does not regress it.\n */\n const companionVersion = options.frameworkPath !== null\n ? (JSON.parse(\n readFileSync(join(options.frameworkPath, 'wildo-framework.info.json'), 'utf8'),\n ) as { version: string }).version\n : null;\n\n if (companionVersion === null) {\n options.log.warn(\n ' Companion delivery skipped: no framework-assets root is reachable (neither a checkout nor an '\n + 'npm-installed `@wildo-ai/wildo-cli`), so the published `@wildo-ai/dev-companion` version to pin '\n + 'could not be determined.',\n );\n } else {\n const companionDropRoot = join(appRoot, '.wildo-saas', 'wildo-dev-companion');\n mkdirSync(join(companionDropRoot, 'dist', 'esm'), { recursive: true });\n writeFileSync(\n join(companionDropRoot, 'dist', 'esm', 'index.js'),\n [\n '// GENERATED by `wildo init` (app-creator mode). Do not edit.',\n '//',\n '// The companion itself is the published `@wildo-ai/dev-companion` package, installed as a',\n '// dependency of this workspace member. This file exists so the drop keeps the same entry',\n '// layout as a framework-dev delivery, where `dist/` is a hard-linked mirror instead.',\n '//',\n '// `export *` evaluates the module, which is what starts the companion when this file is',\n '// executed by the `start` script.',\n \"export * from '@wildo-ai/dev-companion';\",\n '',\n ].join('\\n'),\n 'utf8',\n );\n writeFileSync(\n join(companionDropRoot, 'package.json'),\n `${JSON.stringify({\n name: `@${slug}/wildo-dev-companion`,\n version: companionVersion,\n description:\n 'Wildo.ai Dev Companion — app-creator delivery. A shim over the published '\n + '@wildo-ai/dev-companion package; generated by `wildo init`, do not edit by hand.',\n private: true,\n type: 'module',\n main: 'dist/esm/index.js',\n scripts: {\n dev: 'bash scripts/dev-supervised.sh',\n start: 'node dist/esm/index.js',\n },\n dependencies: {\n '@wildo-ai/dev-companion': companionVersion,\n },\n }, null, 2)}\\n`,\n 'utf8',\n );\n filesWritten += 2;\n companionDelivered = true;\n }\n }\n\n let installed = false;\n let built = false;\n /*\n * App-creator mode INSTALLS. It used to refuse, because the `@wildo-ai/*` packages a generated\n * application depends on were not all on the registry — four of the thirteen declared for publish\n * had never landed, `saas-specifications` among them, which a generated `specifications/` package\n * depends on directly.\n *\n * All thirteen are published at 1.1.0 as of 2026-08-31 (#151), and the generated manifests pin\n * `*`, so they resolve to it. Measured BEFORE removing the refusal rather than after: a scaffolded\n * app-creator application installs in ~24s with every `@wildo-ai` dependency resolved from the\n * registry.\n *\n * A refusal that outlives its cause is worse than no refusal — it teaches an operator that a\n * working path is broken, and this one named packages that are now present.\n */\n if (options.skipInstall !== true) {\n installed = runStep({ log: options.log, label: 'pnpm install', command: 'pnpm', args: ['install'], cwd: appRoot });\n if (installed) {\n built = runStep({\n log: options.log,\n label: 'build specifications + backend-api',\n command: 'pnpm',\n args: ['--filter', `@${slug}/specifications`, '--filter', `@${slug}/shared-lib`, '--filter', `@${slug}/backend-api`, 'build'],\n cwd: appRoot,\n });\n }\n }\n\n return { slug, ports, filesWritten, companionDelivered, installed, built };\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"saas-skeleton.service.js","sourceRoot":"","sources":["../../../../src/services/application/saas-skeleton.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC9H,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AAE/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,iDAAiD,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,8DAA8D,CAAC;AAC5H,OAAO,EACL,0CAA0C,EAC1C,qCAAqC,GACtC,MAAM,0EAA0E,CAAC;AAClF,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,GAC/B,MAAM,gEAAgE,CAAC;AACxE,OAAO,EAAE,gCAAgC,EAAE,MAAM,kEAAkE,CAAC;AAEpH;;;;GAIG;AACH,MAAM,CAAN,IAAY,YAcX;AAdD,WAAY,YAAY;IACtB;;;;OAIG;IACH,+CAA+B,CAAA;IAC/B;;;;;OAKG;IACH,2CAA2B,CAAA;AAC7B,CAAC,EAdW,YAAY,KAAZ,YAAY,QAcvB;AA2BD,MAAM,0BAA0B,G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;YACnC,SAAS,GAAG,OAAO,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC;YACnH,IAAI,SAAS,EAAE,CAAC;gBACd,KAAK,GAAG,OAAO,CAAC;oBACd,GAAG,EAAE,OAAO,CAAC,GAAG;oBAChB,KAAK,EAAE,oCAAoC;oBAC3C,OAAO,EAAE,MAAM;oBACf,IAAI,EAAE,CAAC,UAAU,EAAE,IAAI,IAAI,iBAAiB,EAAE,UAAU,EAAE,IAAI,IAAI,aAAa,EAAE,UAAU,EAAE,IAAI,IAAI,cAAc,EAAE,OAAO,CAAC;oBAC7H,GAAG,EAAE,OAAO;iBACb,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAC7E,CAAC;CACF,CAAC","sourcesContent":["/**\n * SaasSkeletonService — materialize a full, bootable-after-setup application\n * skeleton from `templates/saas/skeleton/` (issue #51, T1–T10).\n *\n * The template tree carries three file classes:\n * - plain files, copied verbatim (`tsconfig.common.json`, package sources, …);\n * - `*.hbs` files, rendered through the shared Handlebars `TemplateProcessor`\n * with the app identity + ALLOCATED ports (D4: two applications sharing a\n * framework checkout must never collide on ports);\n * - `gitignore`, written as `.gitignore` (a literal dotfile inside the\n * template tree would make git ignore the template's own files).\n *\n * Two files are DERIVED rather than templated, per the T4 rule (\"derived from\n * the framework's current override set, never a frozen copy\"):\n * - the root `package.json` — its `pnpm.overrides` are computed live from\n * `scripts/app-dependency-alignment/propagated-engine-overrides.json`\n * (names) joined with the framework root's `pnpm.overrides` (versions),\n * plus, in framework-developer mode, `file:` links for every\n * `frameworkFileLinkPackages` entry resolved through the framework's own\n * pnpm-workspace;\n * - `.wildo-saas/dev-framework-scripts/run-dev-stack.sh` — its\n * `pnpm --filter` package lists are the scaffolded workspace members.\n *\n * DUAL MODE (D7 — both modes authored from the start). Both are live: the npm\n * publish lane put all twenty declared packages on the registry at 1.1.1 on\n * 2026-08-31, `@wildo-ai/dev-companion` among them, so app-creator mode installs\n * and delivers like any other consumer:\n * - `framework-dev`: `file:` overrides into the checkout, dev-framework\n * scripts installed, companion dist delivered via\n * `scripts/dev-orchestrator/dev-companion-deliver.mjs`;\n * - `app-creator`: `@wildo-ai/*` overrides pinned to the published framework\n * version; the companion drop is a re-export shim over the published\n * `@wildo-ai/dev-companion`, keeping the framework-dev entry layout.\n */\nimport { spawnSync } from 'child_process';\nimport { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, chmodSync } from 'fs';\nimport { dirname, join, relative } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport { TemplateProcessor } from '~wildo-cli/infrastructure/io/template-processor';\nimport { COMPANION_PORT_OFFSET, WORKBENCH_PORT_OFFSET } from '~wildo-cli/services/application/application-dev-port-offsets';\nimport {\n APPLICATION_DEPENDENCY_EXCLUSIONS_RELATIVE,\n ApplicationDependencyAlignmentService,\n} from '~wildo-cli/services/application/application-dependency-alignment.service';\nimport {\n ProviderPackageLinksService,\n readFrameworkWorkspacePackages,\n} from '~wildo-cli/services/application/provider-package-links.service';\nimport { resolveFrameworkRootManifestPath } from '~wildo-cli/services/framework/installed-framework-assets.service';\n\n/**\n * The two delivery modes every skeleton artifact is authored for (issue #51 D7).\n * The mode decides the root manifest's dependency story and which dev tooling\n * the scaffold materializes — it never changes the application's own sources.\n */\nexport enum SkeletonMode {\n /**\n * In-repo example app beside the framework checkout: `file:` overrides into\n * the checkout's workspace packages, dev-framework scripts installed, and the\n * companion dist delivered straight from the framework build.\n */\n FRAMEWORK_DEV = 'framework-dev',\n /**\n * Standalone app consuming published `@wildo-ai/*` versions. No framework\n * scripts; the companion arrives as a shim over the published\n * `@wildo-ai/dev-companion` rather than as a hard-linked build mirror. The\n * root `dev` script runs the workspace members' own dev scripts.\n */\n APP_CREATOR = 'app-creator',\n}\n\nexport interface SkeletonPorts {\n backend: number;\n app: number;\n companion: number;\n workbench: number;\n}\n\nexport interface SaasSkeletonOptions {\n name: string;\n frameworkPath: string | null;\n mode: SkeletonMode;\n portBase?: number;\n skipInstall?: boolean;\n log: { info(message: string): void; warn(message: string): void };\n}\n\nexport interface SaasSkeletonResult {\n slug: string;\n ports: SkeletonPorts;\n filesWritten: number;\n companionDelivered: boolean;\n installed: boolean;\n built: boolean;\n}\n\nconst SKELETON_TEMPLATE_RELATIVE = 'templates/saas/skeleton';\nconst OVERRIDES_MANIFEST_RELATIVE = 'scripts/app-dependency-alignment/propagated-engine-overrides.json';\nconst COMPANION_DELIVER_RELATIVE = 'scripts/dev-orchestrator/dev-companion-deliver.mjs';\n/**\n * The workspace members `buildWorkspaceYaml` declares, minus the two GENERATED drops (their\n * manifests are written by their own generators and would overwrite anything injected here).\n * Kept beside that function on purpose: the two lists describe the same scaffold and must move\n * together.\n */\nconst SCAFFOLDED_WORKSPACE_MEMBERS = ['.', 'specifications', 'shared-lib', 'backend-api', 'frontend'] as const;\n\nconst DEFAULT_PORT_BASE = 4241;\nconst PORT_BASE_STRIDE = 10;\n\nfunction toSlug(name: string): string {\n return name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\nfunction toDisplayName(name: string): string {\n return name\n .replace(/[-_]+/g, ' ')\n .replace(/\\b\\w/g, c => c.toUpperCase());\n}\n\n/**\n * Allocate the app's port base by scanning every sibling application's AUTHORED\n * port declarations under `<framework>/examples/*` (saas config `defaultPort:`\n * plus infra `port:` values). The next free `PORT_BASE_STRIDE` block above the\n * highest occupied one wins, so a second app lands at 4251 beside Wonder\n * Todos' 4241–4244 instead of silently colliding (the exact failure of the\n * 2026-08-25 hand bootstrap that T8/D4 records).\n */\nfunction allocatePortBase(frameworkPath: string | null): number {\n const used = collectUsedApplicationPorts(frameworkPath);\n // Walk stride-aligned bases upward until BOTH the service block (base..base+stride-1)\n // and the derived companion port (base+offset) are free of every scanned port.\n for (let base = DEFAULT_PORT_BASE; base < 5000; base += PORT_BASE_STRIDE) {\n if (portBlockIsFree(base, used)) {\n return base;\n }\n }\n // Exhaustion must REFUSE, not silently hand back the default base — returning\n // 4241 here would scaffold an app directly onto Wonder Todos' ports, which is\n // the exact collision this allocator exists to prevent.\n throw new Error(\n 'No free application port block found in the 4000-4999 tier (stride 10 + companion offset 100). '\n + 'Pass an explicit --port-base outside the scanned range, or retire an unused sibling application.',\n );\n}\n\n/** True when the whole service block AND both derived tool ports avoid every scanned port. */\nfunction portBlockIsFree(base: number, used: ReadonlySet<number>): boolean {\n const blockPorts = Array.from({ length: PORT_BASE_STRIDE }, (_, i) => base + i);\n return blockPorts.every((port) => !used.has(port))\n && !used.has(base + COMPANION_PORT_OFFSET)\n && !used.has(base + WORKBENCH_PORT_OFFSET);\n}\n\n/** Collect every authored sibling port (saas `defaultPort:` + infra `port:`) in the 4xxx tier. */\nfunction collectUsedApplicationPorts(frameworkPath: string | null): Set<number> {\n const usedPorts: number[] = [];\n if (frameworkPath) {\n const examplesHome = join(frameworkPath, 'examples');\n if (existsSync(examplesHome)) {\n for (const entry of readdirSync(examplesHome, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const appRoot = join(examplesHome, entry.name);\n for (const candidate of [\n join(appRoot, 'wildo.saas.config.ts'),\n join(appRoot, 'infrastructure/local/wildo.infra.local.config.ts'),\n ]) {\n if (!existsSync(candidate)) continue;\n const source = readFileSync(candidate, 'utf8');\n for (const match of source.matchAll(/(?:defaultPort|port)\\s*:\\s*(\\d{4,5})/g)) {\n usedPorts.push(Number(match[1]));\n }\n }\n }\n }\n }\n return new Set(usedPorts.filter((port) => port >= 4000 && port < 5000));\n}\n\n\ninterface OverridesManifest {\n propagatedOverrideKeys?: string[];\n frameworkFileLinkPackages?: string[];\n}\n\nfunction buildRootOverrides(input: {\n appRoot: string;\n frameworkPath: string;\n mode: SkeletonMode;\n}): Record<string, string> {\n const manifest = JSON.parse(\n readFileSync(join(input.frameworkPath, OVERRIDES_MANIFEST_RELATIVE), 'utf8'),\n ) as OverridesManifest;\n // Through the resolver, never `<root>/package.json`: in an INSTALLED framework-assets root that\n // file is the CLI's own manifest, and the framework root manifest ships beside it under another\n // name (`installed-framework-assets.service.ts`).\n const frameworkRootManifest = JSON.parse(\n readFileSync(resolveFrameworkRootManifestPath(input.frameworkPath), 'utf8'),\n ) as { version?: string; pnpm?: { overrides?: Record<string, string> } };\n const frameworkOverrides = frameworkRootManifest.pnpm?.overrides ?? {};\n const frameworkInfo = JSON.parse(\n readFileSync(join(input.frameworkPath, 'wildo-framework.info.json'), 'utf8'),\n ) as { version: string };\n\n const overrides: Record<string, string> = {};\n\n /*\n * The framework CORE — every application links all of it, so the authored list is the decision.\n * The PROVIDER packages are handled below and are demand-driven: see\n * `ProviderPackageLinksService`. Keeping the two apart is what stops a scaffolded application\n * carrying two hundred `file:` links to packages it never imports (plan D7, issue #334).\n */\n if (input.mode === SkeletonMode.FRAMEWORK_DEV) {\n const workspacePackages = readFrameworkWorkspacePackages(input.frameworkPath);\n for (const packageName of manifest.frameworkFileLinkPackages ?? []) {\n const workspacePackage = workspacePackages.get(packageName);\n if (!workspacePackage) {\n throw new Error(\n `frameworkFileLinkPackages names '${packageName}' but no framework workspace member carries that name — `\n + `fix ${OVERRIDES_MANIFEST_RELATIVE} or the workspace.`,\n );\n }\n overrides[packageName] = `file:${relative(input.appRoot, workspacePackage.root)}`;\n }\n } else {\n for (const packageName of manifest.frameworkFileLinkPackages ?? []) {\n overrides[packageName] = frameworkInfo.version;\n }\n }\n\n /*\n * Provider packages the application ALREADY declares. At `wildo init` this is empty by\n * construction — a fresh scaffold declares no provider — and that is the point: a provider link\n * appears only after `wildo compose add-provider` writes the dependency, and it appears for that\n * provider alone. The same resolution runs again after every `wildo compose`, which is what makes\n * the scenario a single command rather than a scenario plus a hand-written override.\n */\n const providerLinks = ProviderPackageLinksService.resolveProviderOverrides({\n applicationRoot: input.appRoot,\n frameworkWorkspacePackages: input.mode === SkeletonMode.FRAMEWORK_DEV\n ? readFrameworkWorkspacePackages(input.frameworkPath)\n : null,\n frameworkVersion: frameworkInfo.version,\n });\n for (const [packageName, overrideValue] of Object.entries(providerLinks.overrides)) {\n overrides[packageName] = overrideValue;\n }\n\n for (const key of manifest.propagatedOverrideKeys ?? []) {\n const version = frameworkOverrides[key];\n if (!version) {\n throw new Error(\n `propagatedOverrideKeys names '${key}' but the framework root pnpm.overrides carries no version for it.`,\n );\n }\n overrides[key] = version;\n }\n\n return Object.fromEntries(Object.entries(overrides).sort(([a], [b]) => a.localeCompare(b)));\n}\n\nfunction buildRootPackageJson(input: {\n slug: string;\n appRoot: string;\n frameworkPath: string | null;\n mode: SkeletonMode;\n}): string {\n const frameworkRootManifest = input.frameworkPath\n ? JSON.parse(readFileSync(resolveFrameworkRootManifestPath(input.frameworkPath), 'utf8')) as { packageManager?: string }\n : {};\n\n const manifest: Record<string, unknown> = {\n name: `@${input.slug}/root`,\n version: '1.0.0',\n private: true,\n ...(frameworkRootManifest.packageManager ? { packageManager: frameworkRootManifest.packageManager } : {}),\n scripts: {\n // `run-dev-stack.sh` is only WRITTEN in framework-dev mode; an app-creator\n // manifest pointing at it would ship a `pnpm dev` that fails on a missing\n // file. App-creator runs the workspace members' own dev scripts directly.\n ...(input.mode === SkeletonMode.FRAMEWORK_DEV\n ? {\n dev: 'bash .wildo-saas/dev-framework-scripts/run-dev-stack.sh full',\n 'dev:sync': 'bash .wildo-saas/dev-framework-scripts/sync-engine.sh',\n }\n : { dev: 'pnpm --parallel -r run dev' }),\n build: 'turbo build',\n clean: 'turbo run clean',\n },\n ...(input.frameworkPath\n ? { pnpm: { overrides: buildRootOverrides({ appRoot: input.appRoot, frameworkPath: input.frameworkPath, mode: input.mode }) } }\n : {}),\n devDependencies: {\n '@wildo-ai/external-connectors-models': '*',\n // The compiled agent knowledge (skills, rules, references) `wildo assets sync` delivers into\n // `.claude/` and `.wildo-saas/docs/`. Declared at the ROOT so the CLI resolves it from the\n // application without knowing which workspace member happens to depend on it transitively.\n '@wildo-ai/framework-knowledge': '*',\n '@wildo-ai/platform-config-lib': '*',\n '@wildo-ai/saas-models': '*',\n tsx: '^4.21.0',\n turbo: '^2.8.11',\n },\n };\n return `${JSON.stringify(manifest, null, 2)}\\n`;\n}\n\nfunction buildWorkspaceYaml(): string {\n return [\n 'packages:',\n \" - 'specifications'\",\n \" - 'shared-lib'\",\n \" - 'backend-api'\",\n \" - 'frontend'\",\n ' # The dev companion drop: a GENERATED dist-only delivery (see the app',\n ' # .gitignore); its manifest is a workspace member so its dependencies',\n ' # resolve like every other package.',\n \" - '.wildo-saas/wildo-dev-companion'\",\n ' # The application-creation workbench drop: a launcher, not a delivery. Unlike the',\n ' # companion it carries no dist — in framework-dev mode it runs Vite against the',\n ' # framework source. It is a workspace member so `pnpm --filter` can reach it from',\n ' # the app root, which is what puts it in the dev stack beside everything else.',\n ' #',\n ' # Listed unconditionally, though an APP-CREATOR install never materializes the',\n ' # directory (it has no framework source to run Vite against). That is safe, and',\n ' # measured rather than assumed: a `packages:` entry naming a directory that does',\n ' # not exist is silently ignored — `pnpm install` exits 0, reports no warning, and',\n ' # does not count it among the workspace projects. The companion entry above has',\n ' # relied on the same behaviour for as long as it has existed, since it too is',\n ' # absent until its dist is delivered.',\n \" - '.wildo-saas/application-creation-workbench'\",\n '',\n ].join('\\n');\n}\n\nfunction buildRunDevStack(slug: string): string {\n return `#!/bin/bash\n\n# GENERATED by \\`wildo init\\` (issue #51 T9) — the mode→package dispatch mirrors\n# this application's workspace members. Regenerate by re-running the scaffolder\n# rather than hand-editing the filter lists.\n#\n# \\`full\\` DERIVES its set rather than listing it, and that is the whole point of the\n# mode. An application GROWS workspace members after \\`wildo init\\` — \\`wildo compose\n# add-website\\`, \\`add-technical-doc\\`, \\`add-minion\\`, \\`add-worker-node\\` each append one\n# — and no scenario edits this file. A hand-written list here is therefore a second\n# enumeration of a population somebody else owns, and it drifted exactly that way: a\n# composed documentation portal was a declared service, a workspace member, and an\n# allocated port, and \\`full\\` never started it. Nothing reported that, because an\n# unlisted package simply does not appear.\n#\n# \\`pnpm -r\\` runs \\`dev\\` in every workspace package that HAS one, which is the honest\n# reading of \"the full stack\" and cannot fall behind a scenario. The narrow modes below\n# stay explicit: each names a deliberate subset, so listing is what they are for.\n\nset -u\nset -o pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nMODE=\"\\${1:-full}\"\n\ncase \"$MODE\" in\n full)\n STACK_COMMAND=(\n pnpm --parallel -r\n run dev\n )\n ;;\n backend)\n STACK_COMMAND=(\n pnpm --parallel\n --filter @${slug}/specifications\n --filter @${slug}/shared-lib\n --filter @${slug}/backend-api\n run dev\n )\n ;;\n companion)\n STACK_COMMAND=(\n pnpm --parallel\n --filter @${slug}/specifications\n --filter @${slug}/shared-lib\n --filter @wildo-ai/dev-companion\n run dev\n )\n ;;\n frontend)\n STACK_COMMAND=(\n pnpm --parallel\n --filter @${slug}/main-app\n run dev\n )\n ;;\n # The workbench ALONE, for iterating on the tool itself. It talks to a companion over HTTP\n # rather than importing it, so it runs perfectly well against a companion already started by\n # another mode — and starting it here does not drag the application's stack along.\n workbench)\n STACK_COMMAND=(\n pnpm --parallel\n --filter @wildo-ai/application-creation-workbench\n run dev\n )\n ;;\n *)\n echo \"[dev-stack] Unknown mode: $MODE\"\n echo \"[dev-stack] Expected one of: full, backend, companion, frontend, workbench\"\n exit 1\n ;;\nesac\n\nif [ -f \"$SCRIPT_DIR/sync-engine.sh\" ]; then\n \"$SCRIPT_DIR/sync-engine.sh\" &\n SYNC_PID=$!\n HAS_CLEANED_UP=0\n\n cleanup() {\n if [ \"$HAS_CLEANED_UP\" -eq 1 ]; then\n return\n fi\n HAS_CLEANED_UP=1\n if kill -0 \"$SYNC_PID\" 2>/dev/null; then\n kill \"$SYNC_PID\" 2>/dev/null || true\n wait \"$SYNC_PID\" 2>/dev/null || true\n fi\n }\n\n trap cleanup EXIT INT TERM\nfi\n\n\"\\${STACK_COMMAND[@]}\"\n`;\n}\n\n/**\n * Declare, in every scaffolded workspace package, the engine peers it must SUPPLY (issue #167).\n *\n * A pnpm override rewrites a specifier that some manifest wrote down; it never creates one. A peer\n * nobody declares therefore falls to `autoInstallPeers`, whose resolution is STICKY: correct on a\n * fresh lockfile, and frozen at whatever predates the override otherwise. So an application that\n * does not declare the engine's peers cannot receive a later pin bump — moving a root pin from `^6`\n * to `^7` leaves it on 6 with a warning and no remedy short of deleting its lockfile.\n *\n * Each name is written as `\"*\"`, never a version: the root `pnpm.overrides` block written beside it\n * already carries the pin, so a framework bump reaches the application with no edit here.\n *\n * The name set is READ from the generated `enginePeerClosure` rather than re-derived. That map is\n * produced and gated by `scripts/app-dependency-alignment.mjs`; only the trivial union lookup is\n * repeated here, because this service is compiled TypeScript in another package and cannot import\n * the repository's `.mjs` derivation.\n *\n * Nothing is ever removed — the same restraint the reconciler applies. A template-authored peer that\n * the closure does not require (`ufo`, today) is the application's own declaration, and a shared name\n * is not evidence of shared ownership.\n */\nfunction declareEnginePeersInScaffoldedPackages(input: { appRoot: string; frameworkPath: string }): void {\n const manifestPath = join(input.frameworkPath, OVERRIDES_MANIFEST_RELATIVE);\n if (!existsSync(manifestPath)) return;\n const { enginePeerClosure } = JSON.parse(readFileSync(manifestPath, 'utf8')) as {\n enginePeerClosure?: Record<string, string[]>;\n };\n if (!enginePeerClosure) return;\n\n for (const member of SCAFFOLDED_WORKSPACE_MEMBERS) {\n const packageJsonPath = join(input.appRoot, member, 'package.json');\n if (!existsSync(packageJsonPath)) continue;\n const manifest = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as Record<string, Record<string, string> | unknown>;\n\n const frameworkDependencies = new Set<string>();\n for (const field of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {\n for (const name of Object.keys((manifest[field] as Record<string, string> | undefined) ?? {})) {\n if (name.startsWith('@wildo-ai/')) frameworkDependencies.add(name);\n }\n }\n const required = new Set<string>();\n for (const dependencyName of frameworkDependencies) {\n for (const peerName of enginePeerClosure[dependencyName] ?? []) required.add(peerName);\n }\n // A name the package already declares as a real dependency needs no peer entry: the override\n // reaches it there.\n for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {\n for (const name of Object.keys((manifest[field] as Record<string, string> | undefined) ?? {})) required.delete(name);\n }\n if (required.size === 0) continue;\n\n const peers = { ...((manifest.peerDependencies as Record<string, string> | undefined) ?? {}) };\n for (const name of required) peers[name] = '*';\n manifest.peerDependencies = Object.fromEntries(Object.keys(peers).sort().map((name) => [name, peers[name]]));\n writeFileSync(packageJsonPath, `${JSON.stringify(manifest, null, 2)}\\n`, 'utf8');\n }\n}\n\n/**\n * Seed the application's dependency-exclusion list from the framework's own `deliberatelyExcluded`\n * (issue #222).\n *\n * The list names third-party packages that `wildo align-deps` must NEVER pin to the engine's version\n * because the application's own toolchain owns them — `esbuild` follows vite, `express` follows\n * webpack-dev-server, `mime` follows express, plus astro / docusaurus / jest / tailwindcss /\n * typescript. Each entry was measured against a real collision, not guessed.\n *\n * SEEDED, then APPLICATION-OWNED. The framework's copy is a judgement about a typical application's\n * stack; a real application knows its own better, and it is the one that breaks when the judgement is\n * wrong. The cost is that a later framework exclusion does not reach an existing application — which\n * is the right trade, because the conflict being described is the application's, not the framework's.\n */\nfunction seedDependencyExclusions(input: { appRoot: string; frameworkPath: string }): void {\n const excludedNames = ApplicationDependencyAlignmentService.readFrameworkExclusions(input.frameworkPath);\n if (Object.keys(excludedNames).length === 0) return;\n const targetPath = join(input.appRoot, APPLICATION_DEPENDENCY_EXCLUSIONS_RELATIVE);\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileSync(targetPath, `${JSON.stringify({\n 'purpose-note':\n 'Names `wildo align-deps` must never pin to the framework version, because THIS application\\'s '\n + 'toolchain owns them. Seeded at `wildo init` from the framework of the day and yours from here: '\n + 'edit it when your stack needs a major the framework does not pin. A key ending in `*` is a '\n + 'prefix match. The value is the reason, and is never read by any tool — it is for whoever '\n + 'reads this file next.',\n excludedNames,\n }, null, 2)}\\n`, 'utf8');\n}\n\n/** Recursively materialize the template tree into the app root. */\nfunction materializeTemplateTree(input: {\n templateRoot: string;\n appRoot: string;\n mode: SkeletonMode;\n variables: Record<string, unknown>;\n processor: TemplateProcessor;\n}): number {\n let written = 0;\n const walk = (relativeDir: string) => {\n for (const entry of readdirSync(join(input.templateRoot, relativeDir), { withFileTypes: true })) {\n const relativePath = relativeDir ? join(relativeDir, entry.name) : entry.name;\n if (entry.isDirectory()) {\n walk(relativePath);\n continue;\n }\n if (!entry.isFile()) continue;\n\n // Framework-checkout dev-loop files: an app-creator install has no framework\n // scripts to call into, so neither the dev-framework-scripts home nor the\n // supervised dev wrappers (frontend Vite+library watcher, backend-api\n // watcher+runtime supervisor) are materialized there.\n if (\n input.mode === SkeletonMode.APP_CREATOR\n && (\n relativePath.startsWith(join('.wildo-saas', 'dev-framework-scripts'))\n // The workbench drop launches Vite against FRAMEWORK SOURCE, which an app-creator\n // install does not have. Materializing it there would produce a dev-stack member that\n // exits with \"the workbench runs against framework source\" on every start.\n || relativePath.startsWith(join('.wildo-saas', 'application-creation-workbench'))\n || relativePath === join('frontend', 'scripts', 'dev-supervised.sh')\n || relativePath === join('backend-api', 'scripts', 'dev-supervised.sh.hbs')\n // The COMPANION's supervised wrapper, which this list was missing. Its two siblings were\n // excluded and it was not, so it shipped into every app-creator application and became\n // the drop's `dev` script — see the note on that manifest below.\n || relativePath === join('.wildo-saas', 'wildo-dev-companion', 'scripts', 'dev-supervised.sh')\n )\n ) {\n continue;\n }\n\n let targetRelative = relativePath;\n let content: string | null = null;\n if (entry.name.endsWith('.init.hbs')) {\n // `.init.hbs` marks the INIT-time variant of a file whose later evolution belongs to a\n // service or scenario (e.g. `wildo.saas.config.ts.init.hbs` — the config service owns\n // post-init parametrization). Rendered once here, then never re-templated.\n targetRelative = relativePath.slice(0, -'.init.hbs'.length);\n content = input.processor.processTemplate(relativePath, input.variables);\n } else if (entry.name.endsWith('.hbs')) {\n targetRelative = relativePath.slice(0, -'.hbs'.length);\n content = input.processor.processTemplate(relativePath, input.variables);\n } else if (entry.name === 'gitignore' && relativeDir === '') {\n targetRelative = '.gitignore';\n }\n\n const targetPath = join(input.appRoot, targetRelative);\n mkdirSync(dirname(targetPath), { recursive: true });\n if (content !== null) {\n writeFileSync(targetPath, content, 'utf8');\n } else {\n copyFileSync(join(input.templateRoot, relativePath), targetPath);\n }\n // Keyed on the RENDERED name so a future `*.sh.hbs` template still lands executable.\n if (targetRelative.endsWith('.sh')) chmodSync(targetPath, 0o755);\n written += 1;\n }\n };\n walk('');\n return written;\n}\n\nfunction runStep(input: {\n log: SaasSkeletonOptions['log'];\n label: string;\n command: string;\n args: string[];\n cwd: string;\n}): boolean {\n input.log.info(` ${input.label}…`);\n const result = spawnSync(input.command, input.args, { cwd: input.cwd, stdio: 'inherit' });\n if (result.status !== 0) {\n input.log.warn(` ${input.label} failed (exit ${result.status ?? 'signal'}). Fix and re-run manually.`);\n return false;\n }\n return true;\n}\n\n/**\n * Files the scaffold writes at the APP ROOT. Their presence in the target\n * directory means the scaffold would OVERWRITE an existing project — most\n * dangerously the framework checkout itself, whose root carries every one of\n * these names (`wildo init` run from the monorepo root would clobber the\n * framework's own package.json / pnpm-workspace.yaml / turbo.json).\n */\nconst ROOT_COLLISION_FILES = [\n 'package.json',\n 'pnpm-workspace.yaml',\n 'turbo.json',\n 'wildo.saas.config.ts',\n 'tsconfig.common.json',\n '.gitignore',\n] as const;\n\nexport const SaasSkeletonService = {\n allocatePortBase,\n collectUsedApplicationPorts,\n buildRootOverrides,\n\n scaffold(appRoot: string, options: SaasSkeletonOptions): SaasSkeletonResult {\n const safeName = options.name.replace(/['\"\\\\]/g, '');\n const slug = toSlug(safeName) || 'app';\n const displayName = toDisplayName(safeName || slug) || 'App';\n\n if (options.mode === SkeletonMode.FRAMEWORK_DEV && !options.frameworkPath) {\n throw new Error('framework-dev skeleton mode requires a resolved framework checkout.');\n }\n\n // Refuse a NON-EMPTY target before writing anything: the scaffold is a\n // whole-project materialization, not a merge. Fail-closed here protects the\n // framework checkout root (which carries all of these files) and any\n // half-scaffolded directory from a silent clobber.\n const collisions = ROOT_COLLISION_FILES.filter((file) => existsSync(join(appRoot, file)));\n if (collisions.length > 0) {\n throw new Error(\n `Target directory already contains ${collisions.join(', ')} — refusing to scaffold over an existing project. `\n + 'Run `wildo init` in an empty directory (or delete the partial scaffold first).',\n );\n }\n\n // An EXPLICIT --port-base is validated against the same sibling scan the\n // allocator uses — accepting a colliding base would recreate the exact\n // hand-bootstrap failure the allocator was built to prevent.\n if (options.portBase !== undefined) {\n const used = collectUsedApplicationPorts(options.frameworkPath);\n if (!portBlockIsFree(options.portBase, used)) {\n throw new Error(\n `--port-base ${options.portBase} collides with a sibling application's authored ports `\n + `(block ${options.portBase}-${options.portBase + PORT_BASE_STRIDE - 1} or companion port ${options.portBase + COMPANION_PORT_OFFSET}). `\n + `Next free base: ${allocatePortBase(options.frameworkPath)}.`,\n );\n }\n }\n const portBase = options.portBase ?? allocatePortBase(options.frameworkPath);\n const ports: SkeletonPorts = {\n backend: portBase,\n app: portBase + 1,\n companion: portBase + COMPANION_PORT_OFFSET,\n workbench: portBase + WORKBENCH_PORT_OFFSET,\n };\n\n const templateRoot = options.frameworkPath\n ? join(options.frameworkPath, SKELETON_TEMPLATE_RELATIVE)\n : null;\n if (!templateRoot || !existsSync(templateRoot)) {\n throw new Error(\n 'Application skeleton templates not found'\n + (templateRoot ? ` at ${templateRoot}` : ' (no framework-assets root resolved)')\n + '. The full-skeleton scaffold needs the framework templates: a framework checkout, or a `@wildo-ai/wildo-cli` '\n + 'installed from npm (which ships them). Use --config-only to write only wildo.saas.config.ts.',\n );\n }\n\n const variables = {\n slug,\n displayName,\n backendPort: ports.backend,\n appPort: ports.app,\n companionPort: ports.companion,\n workbenchPort: ports.workbench,\n // Mode conditionals inside `.hbs` templates ({{#if isFrameworkDev}}): framework-dev\n // renders engine-source aliasing/tsconfig-paths/dev-supervision; app-creator renders\n // the standalone shape (published packages, plain vite dev).\n isFrameworkDev: options.mode === SkeletonMode.FRAMEWORK_DEV,\n };\n\n const processor = new TemplateProcessor(templateRoot);\n let filesWritten = materializeTemplateTree({\n templateRoot,\n appRoot,\n mode: options.mode,\n variables,\n processor,\n });\n\n // `.claude/` is framework-delivered in framework-dev mode (materialized by `wildo fwk\n // dev-skills`, synchronized on framework update) — ignoring it avoids duplicating the\n // compiled knowledge product in git. App-creator applications COMMIT their `.claude`, so\n // the block is mode-conditional rather than part of the template gitignore.\n if (options.mode === SkeletonMode.FRAMEWORK_DEV) {\n appendFileSync(\n join(appRoot, '.gitignore'),\n '\\n# Framework-delivered agent knowledge (framework-dev mode only) — materialized by\\n'\n + '# `wildo fwk dev-skills`, synchronized on framework update; never commit in this mode.\\n'\n + '.claude/\\n',\n 'utf8',\n );\n }\n\n writeFileSync(join(appRoot, 'package.json'), buildRootPackageJson({\n slug,\n appRoot,\n frameworkPath: options.frameworkPath,\n mode: options.mode,\n }), 'utf8');\n writeFileSync(join(appRoot, 'pnpm-workspace.yaml'), buildWorkspaceYaml(), 'utf8');\n\n if (options.frameworkPath) {\n declareEnginePeersInScaffoldedPackages({ appRoot, frameworkPath: options.frameworkPath });\n seedDependencyExclusions({ appRoot, frameworkPath: options.frameworkPath });\n }\n\n // Deliver the engine EMAIL CANON (system + engine-resource templates) into the backend's\n // engine tree. System emails are runtime behavior — a fresh app without them has no welcome\n // email, no invitation email, etc. The canon at `templates/saas/i18n/email` is synced from\n // the dogfood (V2-P1 catch-up) and the app owns its copy from here (regenerated/extended by\n // `wildo generate email`).\n const emailCanonRoot = join(options.frameworkPath ?? '', 'templates', 'saas', 'i18n', 'email');\n if (options.frameworkPath && existsSync(emailCanonRoot)) {\n const emailTarget = join(appRoot, 'backend-api', 'src', 'engine', 'email');\n const copyTree = (relativeDir: string) => {\n for (const entry of readdirSync(join(emailCanonRoot, relativeDir), { withFileTypes: true })) {\n const entryRelative = relativeDir ? join(relativeDir, entry.name) : entry.name;\n if (entry.isDirectory()) {\n copyTree(entryRelative);\n } else if (entry.isFile()) {\n const targetPath = join(emailTarget, entryRelative);\n mkdirSync(dirname(targetPath), { recursive: true });\n copyFileSync(join(emailCanonRoot, entryRelative), targetPath);\n filesWritten += 1;\n }\n }\n };\n // The canon's own aggregator files are also shipped by the skeleton tree; the canon copy\n // wins nothing over them (byte-identical), so copying the whole tree is safe.\n copyTree('');\n } else {\n options.log.warn(' Email canon not found — backend system emails will be missing until delivered.');\n }\n const devScriptsDir = join(appRoot, '.wildo-saas', 'dev-framework-scripts');\n if (options.mode === SkeletonMode.FRAMEWORK_DEV) {\n mkdirSync(devScriptsDir, { recursive: true });\n const runDevStackPath = join(devScriptsDir, 'run-dev-stack.sh');\n writeFileSync(runDevStackPath, buildRunDevStack(slug), 'utf8');\n chmodSync(runDevStackPath, 0o755);\n filesWritten += 1;\n }\n filesWritten += 2;\n\n let companionDelivered = false;\n if (options.mode === SkeletonMode.FRAMEWORK_DEV && options.frameworkPath) {\n const deliverScript = join(options.frameworkPath, COMPANION_DELIVER_RELATIVE);\n const result = spawnSync(process.execPath, [\n deliverScript,\n '--framework-root', options.frameworkPath,\n '--app-root', appRoot,\n '--mode', SkeletonMode.FRAMEWORK_DEV,\n ], { stdio: 'inherit' });\n companionDelivered = result.status === 0;\n if (!companionDelivered) {\n options.log.warn(\n ' Companion delivery failed — build @wildo-ai/dev-companion in the framework, then re-run '\n + `node ${COMPANION_DELIVER_RELATIVE} --app-root ${appRoot}`,\n );\n }\n } else if (options.mode === SkeletonMode.APP_CREATOR) {\n /*\n * App-creator delivery is a SHIM, not a dist mirror.\n *\n * `dev-companion-deliver.mjs` hard-links the companion's `dist/` out of a local framework\n * checkout. An app-creator has no checkout — it has the published CLI and a registry — so that\n * path cannot serve this mode. What it CAN do is what every other package in the generated app\n * already does: declare a dependency and let `pnpm install` fetch it.\n *\n * The drop is a WORKSPACE MEMBER (see the `pnpm-workspace.yaml` this skeleton writes), so its\n * dependencies resolve exactly like `specifications/` or `backend-api/`.\n *\n * Why a re-export file rather than repointing `main` into `node_modules`: 31 files in this\n * repository address the drop through the fixed `dist/esm/index.js` layout. Keeping that layout\n * byte-for-byte means no consumer can tell the two delivery modes apart, which is the whole\n * point — a targeted shim beats a 31-file resolution refactor with no lasting architectural\n * gain.\n *\n * Location-sensitivity was ENUMERATED before trusting this, not assumed. The companion has six\n * `import.meta.url` sites; five resolve to files inside its own package and stay correct when\n * that package lives in `node_modules`. The sixth is `dotenv` looking for `../.env` from\n * `dist/esm`, i.e. `dist/.env` — which no delivered drop has ever contained (the drop's `.env`\n * sits at its root), so it is already a no-op and the shim does not regress it.\n */\n const companionVersion = options.frameworkPath !== null\n ? (JSON.parse(\n readFileSync(join(options.frameworkPath, 'wildo-framework.info.json'), 'utf8'),\n ) as { version: string }).version\n : null;\n\n if (companionVersion === null) {\n options.log.warn(\n ' Companion delivery skipped: no framework-assets root is reachable (neither a checkout nor an '\n + 'npm-installed `@wildo-ai/wildo-cli`), so the published `@wildo-ai/dev-companion` version to pin '\n + 'could not be determined.',\n );\n } else {\n const companionDropRoot = join(appRoot, '.wildo-saas', 'wildo-dev-companion');\n mkdirSync(join(companionDropRoot, 'dist', 'esm'), { recursive: true });\n writeFileSync(\n join(companionDropRoot, 'dist', 'esm', 'index.js'),\n [\n '// GENERATED by `wildo init` (app-creator mode). Do not edit.',\n '//',\n '// The companion itself is the published `@wildo-ai/dev-companion` package, installed as a',\n '// dependency of this workspace member. This file exists so the drop keeps the same entry',\n '// layout as a framework-dev delivery, where `dist/` is a hard-linked mirror instead.',\n '//',\n '// `export *` evaluates the module, which is what starts the companion when this file is',\n '// executed by the `start` script.',\n \"export * from '@wildo-ai/dev-companion';\",\n '',\n ].join('\\n'),\n 'utf8',\n );\n writeFileSync(\n join(companionDropRoot, 'package.json'),\n `${JSON.stringify({\n name: `@${slug}/wildo-dev-companion`,\n version: companionVersion,\n description:\n 'Wildo.ai Dev Companion — app-creator delivery. A shim over the published '\n + '@wildo-ai/dev-companion package; generated by `wildo init`, do not edit by hand.',\n private: true,\n type: 'module',\n main: 'dist/esm/index.js',\n scripts: {\n /*\n * `dev` is the SAME as `start` here, and that is the point of an app-creator drop.\n *\n * `scripts/dev-supervised.sh` is a framework-developer script: it resolves\n * `framework.repositoryRoot` and supervises a watcher that recompiles the companion\n * from framework source. An app creator has neither — this drop is a shim over the\n * PUBLISHED `@wildo-ai/dev-companion`, already built, with nothing to watch.\n *\n * Pointing `dev` at it was fatal rather than merely useless, because the application\n * root's `dev` is `pnpm --parallel -r run dev`: the companion exited 1 and\n * `--parallel` tore down the backend, frontend and specifications watchers with it,\n * so `wildo local dev` started NO application runtime at all. Measured 2026-09-10 —\n * first \"Missing resolve-home-path helper\", then, once that was in place,\n * `Resolved home field \"framework.repositoryRoot\" is missing or empty`. Two symptoms,\n * one cause: a framework-only script on an app-creator install.\n */\n dev: 'node dist/esm/index.js',\n start: 'node dist/esm/index.js',\n },\n dependencies: {\n '@wildo-ai/dev-companion': companionVersion,\n },\n }, null, 2)}\\n`,\n 'utf8',\n );\n filesWritten += 2;\n companionDelivered = true;\n }\n }\n\n let installed = false;\n let built = false;\n /*\n * App-creator mode INSTALLS. It used to refuse, because the `@wildo-ai/*` packages a generated\n * application depends on were not all on the registry — four of the thirteen declared for publish\n * had never landed, `saas-specifications` among them, which a generated `specifications/` package\n * depends on directly.\n *\n * All thirteen are published at 1.1.0 as of 2026-08-31 (#151), and the generated manifests pin\n * `*`, so they resolve to it. Measured BEFORE removing the refusal rather than after: a scaffolded\n * app-creator application installs in ~24s with every `@wildo-ai` dependency resolved from the\n * registry.\n *\n * A refusal that outlives its cause is worse than no refusal — it teaches an operator that a\n * working path is broken, and this one named packages that are now present.\n */\n if (options.skipInstall !== true) {\n installed = runStep({ log: options.log, label: 'pnpm install', command: 'pnpm', args: ['install'], cwd: appRoot });\n if (installed) {\n built = runStep({\n log: options.log,\n label: 'build specifications + backend-api',\n command: 'pnpm',\n args: ['--filter', `@${slug}/specifications`, '--filter', `@${slug}/shared-lib`, '--filter', `@${slug}/backend-api`, 'build'],\n cwd: appRoot,\n });\n }\n }\n\n return { slug, ports, filesWritten, companionDelivered, installed, built };\n },\n};\n"]}
|
|
@@ -55,6 +55,15 @@ export const WorkbenchCliService = {
|
|
|
55
55
|
return `${deriveWorkbenchOrigin(target.origin)}/`;
|
|
56
56
|
},
|
|
57
57
|
};
|
|
58
|
+
/**
|
|
59
|
+
* One workbench origin probe.
|
|
60
|
+
*
|
|
61
|
+
* 5s, because this answers a `status` command and the answer is only useful while the operator is
|
|
62
|
+
* still looking at their terminal. The function already treats a refusal as status 0 rather than an
|
|
63
|
+
* error — a dev server that accepts the socket and then says nothing deserves the same treatment,
|
|
64
|
+
* and without a deadline it instead hangs the command that exists to report on it.
|
|
65
|
+
*/
|
|
66
|
+
const WORKBENCH_PROBE_TIMEOUT_MS = 5_000;
|
|
58
67
|
/**
|
|
59
68
|
* Probe the workbench's own origin.
|
|
60
69
|
*
|
|
@@ -64,7 +73,7 @@ export const WorkbenchCliService = {
|
|
|
64
73
|
*/
|
|
65
74
|
async function probeWorkbench(origin) {
|
|
66
75
|
try {
|
|
67
|
-
const response = await fetch(`${origin}/`, { method: 'GET', redirect: 'manual' });
|
|
76
|
+
const response = await fetch(`${origin}/`, { method: 'GET', redirect: 'manual', signal: AbortSignal.timeout(WORKBENCH_PROBE_TIMEOUT_MS) });
|
|
68
77
|
return { status: response.status };
|
|
69
78
|
}
|
|
70
79
|
catch {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workbench-cli.service.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"workbench-cli.service.js","sourceRoot":"","sources":["../../../../src/services/companion/workbench-cli.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eA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AK,GAAG;YACvC,cAAc,EAAE,SAAS,CAAC,MAAM,KAAK,GAAG;SACzC,CAAC;IACJ,CAAC;IAED,yFAAyF;IACzF,KAAK,CAAC,UAAU,CAAC,GAAmB;QAClC,MAAM,MAAM,GAAG,MAAM,2BAA2B,CAAC,GAAG,CAAC,CAAC;QACtD,OAAO,GAAG,qBAAqB,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IACpD,CAAC;CACF,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,0BAA0B,GAAG,KAAK,CAAC;AAEzC;;;;;;GAMG;AACH,KAAK,UAAU,cAAc,CAAC,MAAc;IAC1C,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,GAAG,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,0BAA0B,CAAC,EAAE,CAAC,CAAC;QAC3I,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["import type { CommandContext } from '~wildo-cli/kernel/types';\nimport { CompanionClient } from '~wildo-cli/services/companion/companion-client.service';\nimport { CompanionRequestRetryPolicy } from '~wildo-cli/services/companion/companion.schemas';\nimport { resolveLocalCompanionTarget } from '~wildo-cli/services/companion/local-companion-authority.service';\nimport { WORKBENCH_PORT_OFFSET_FROM_COMPANION } from '~wildo-cli/services/application/application-dev-port-offsets';\n\n/**\n * The workbench is its OWN origin, derived from the companion's.\n *\n * It used to be `'/workbench/'` ON the companion, from a design in which the companion served the\n * bundle. That design was rejected — an operator surface must not die with the thing it observes,\n * and no static file serving exists in the companion at all — so the route was deleted. The path\n * constant outlived it, which meant `status` reported `workbenchReady: false` unconditionally and\n * `open` opened a 404 page. Measured 2026-08-30 against a healthy companion: `/health/ready` 200,\n * an introspection resource route 200, `HEAD /workbench/` **404**.\n *\n * Deriving from the companion rather than reading a second address is deliberate: the workbench is\n * the companion's surface, they are allocated as a pair, and a caller that has resolved one has\n * already done the work of finding the application.\n */\nfunction deriveWorkbenchOrigin(companionOrigin: string): string {\n const companionUrl = new URL(companionOrigin);\n const workbenchUrl = new URL(companionUrl.toString());\n workbenchUrl.port = String(Number(companionUrl.port) + WORKBENCH_PORT_OFFSET_FROM_COMPANION);\n return workbenchUrl.origin;\n}\n\n/**\n * Open and inspect the local application-creation workbench.\n *\n * ## Why there is no launch ticket\n *\n * This used to mint a one-use secret, hand it to the browser in a URL fragment, and exchange it for an\n * `HttpOnly` session cookie with a CSRF token — about 1,500 lines of companion code plus a launch-ticket\n * and operator-session contract.\n *\n * The workbench is a LOCAL development surface bound to loopback, whose purpose is to show a creator what\n * their application-creation run is doing and take their feedback. Access is free by design. A credential\n * exchange between a developer's own CLI and their own companion, on their own machine, protected nothing\n * an attacker who already has that machine could not take anyway — and it cost a whole subsystem plus a\n * contract asserting its own trustworthiness in literals nothing read.\n *\n * If this surface is ever exposed beyond loopback, that is a real authentication problem and needs a real\n * answer (the application's own auth), not a ticket handshake reinstated here.\n */\nexport interface WorkbenchCliStatusV1 {\n readonly companionOrigin: string;\n /** Where the workbench dev server is expected — derived from {@link companionOrigin}. */\n readonly workbenchOrigin: string;\n readonly semanticReadinessStatus: number;\n /**\n * HTTP status from the workbench's own origin, or `0` when the connection was refused.\n *\n * Named `workbenchStaticStatus` until 2026-08-30, from the design in which the companion served a\n * STATIC bundle. Nothing static is served anywhere now, so the old name described a mechanism that\n * had been deleted — and it is a field a reader uses to decide what to check next.\n */\n readonly workbenchStatus: number;\n readonly semanticReady: boolean;\n readonly workbenchReady: boolean;\n}\n\nexport const WorkbenchCliService = {\n async status(ctx: CommandContext): Promise<WorkbenchCliStatusV1> {\n const target = await resolveLocalCompanionTarget(ctx);\n const workbenchOrigin = deriveWorkbenchOrigin(target.origin);\n\n /*\n * Two DIFFERENT processes, so two independent probes — and reporting them separately is the\n * point of this command. The companion can be healthy while the workbench is not started, and\n * the workbench can be serving while the companion is mid-restart; collapsing them into one\n * \"ready\" would hide exactly the state an operator is asking about.\n *\n * The workbench probe is a plain fetch rather than `CompanionClient`: that client carries the\n * companion's retry policy and authority assumptions, and the workbench is a Vite dev server\n * that owes it neither.\n */\n const [readiness, workbench] = await Promise.all([\n CompanionClient.request('/health/ready', { method: 'GET', redirect: 'manual' }, target.clientOptions, CompanionRequestRetryPolicy.SAFE_READ),\n probeWorkbench(workbenchOrigin),\n ]);\n return {\n companionOrigin: target.origin,\n workbenchOrigin,\n semanticReadinessStatus: readiness.status,\n workbenchStatus: workbench.status,\n semanticReady: readiness.status === 200,\n workbenchReady: workbench.status === 200,\n };\n },\n\n /** Where the workbench lives. There is nothing to issue — it is opened, not unlocked. */\n async resolveUrl(ctx: CommandContext): Promise<string> {\n const target = await resolveLocalCompanionTarget(ctx);\n return `${deriveWorkbenchOrigin(target.origin)}/`;\n },\n};\n\n/**\n * One workbench origin probe.\n *\n * 5s, because this answers a `status` command and the answer is only useful while the operator is\n * still looking at their terminal. The function already treats a refusal as status 0 rather than an\n * error — a dev server that accepts the socket and then says nothing deserves the same treatment,\n * and without a deadline it instead hangs the command that exists to report on it.\n */\nconst WORKBENCH_PROBE_TIMEOUT_MS = 5_000;\n\n/**\n * Probe the workbench's own origin.\n *\n * A connection refusal is the ORDINARY answer when the dev server is not started, so it is reported\n * as status 0 rather than thrown: `status` exists to tell an operator which of the two processes is\n * up, and a command that throws when one is down cannot answer its own question.\n */\nasync function probeWorkbench(origin: string): Promise<{ status: number }> {\n try {\n const response = await fetch(`${origin}/`, { method: 'GET', redirect: 'manual', signal: AbortSignal.timeout(WORKBENCH_PROBE_TIMEOUT_MS) });\n return { status: response.status };\n } catch {\n return { status: 0 };\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-contribution-registration.guard.test.d.ts","sourceRoot":"","sources":["../../../../../src/services/credentials/__tests__/provider-contribution-registration.guard.test.ts"],"names":[],"mappings":""}
|
package/dist/src/services/credentials/__tests__/provider-contribution-registration.guard.test.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Discovery must REGISTER what it resolves, and every CLI caller must go through the paired door.
|
|
3
|
+
*
|
|
4
|
+
* ## The gap these pins close, and why a green suite hid it (2026-09-09)
|
|
5
|
+
*
|
|
6
|
+
* `composed-provider-secrets.guard.test.ts` proves the DERIVATION: once a package-shipped
|
|
7
|
+
* provider's contribution is registered, its secret is classified, prompted for, and confined.
|
|
8
|
+
* Every pin there plants the contribution by calling `registerDiscoveredProviderContributions`
|
|
9
|
+
* directly — deliberately, so the guard does not drift with a real package's contents.
|
|
10
|
+
*
|
|
11
|
+
* That left the other half unproven, and it was the half that was broken: NOTHING in the CLI ever
|
|
12
|
+
* called that function. Three sites resolved contributions from disk and none registered them, so
|
|
13
|
+
* `getComposedProviderSecretsCatalogue()` was engine-tier only in every CLI process, and
|
|
14
|
+
* `filterProviderEnvToScope` dropped every catalogue provider's authored key as belonging to "no
|
|
15
|
+
* provider the CLI can see" — while naming that provider in the runtime's own scope list.
|
|
16
|
+
*
|
|
17
|
+
* So the suite was green because the test planted the state that production never created. The
|
|
18
|
+
* first pin below asserts the pairing; the second asserts that no future caller can take the
|
|
19
|
+
* unpaired door, which is the failure mode that produced three wrong sites in the first place.
|
|
20
|
+
*/
|
|
21
|
+
import { readFileSync, readdirSync } from 'fs';
|
|
22
|
+
import { join, sep } from 'path';
|
|
23
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
24
|
+
const resolveValidatedSaasProviderContributions = vi.hoisted(() => vi.fn());
|
|
25
|
+
vi.mock('@wildo-ai/platform-config-lib', async (importOriginal) => ({
|
|
26
|
+
...(await importOriginal()),
|
|
27
|
+
resolveValidatedSaasProviderContributions,
|
|
28
|
+
}));
|
|
29
|
+
const CLI_SOURCE_ROOT = join(__dirname, '..', '..', '..');
|
|
30
|
+
const PAIRED_DOOR_MODULE = join('services', 'credentials', 'composed-provider-catalogue.ts');
|
|
31
|
+
function everyTypescriptSourceFile(directory) {
|
|
32
|
+
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
33
|
+
const entryPath = join(directory, entry.name);
|
|
34
|
+
if (entry.isDirectory())
|
|
35
|
+
return everyTypescriptSourceFile(entryPath);
|
|
36
|
+
return entry.isFile() && entry.name.endsWith('.ts') ? [entryPath] : [];
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
describe('provider contribution registration', () => {
|
|
40
|
+
afterEach(() => {
|
|
41
|
+
vi.resetModules();
|
|
42
|
+
vi.clearAllMocks();
|
|
43
|
+
});
|
|
44
|
+
it('registers into the composed catalogue what discovery resolved', async () => {
|
|
45
|
+
const { ProviderOriginKind, ProviderTier } = await import('@wildo-ai/saas-models');
|
|
46
|
+
const contribution = {
|
|
47
|
+
ref: 'guard-only-vendor',
|
|
48
|
+
identity: {
|
|
49
|
+
packageName: '@wildo-ai/providers',
|
|
50
|
+
tier: ProviderTier.CATALOGUE,
|
|
51
|
+
vendor: 'guard-only-vendor',
|
|
52
|
+
origin: { kind: ProviderOriginKind.GENERATED },
|
|
53
|
+
},
|
|
54
|
+
secretsContractShape: [
|
|
55
|
+
{
|
|
56
|
+
slug: 'clientId',
|
|
57
|
+
envVarName: 'GUARD_ONLY_VENDOR_CLIENT_ID',
|
|
58
|
+
required: true,
|
|
59
|
+
description: 'OAuth2 client id.',
|
|
60
|
+
},
|
|
61
|
+
],
|
|
62
|
+
runtimeTargets: [{ kind: 'backend' }],
|
|
63
|
+
};
|
|
64
|
+
resolveValidatedSaasProviderContributions.mockResolvedValue([contribution]);
|
|
65
|
+
const catalogue = await import('../../../services/credentials/composed-provider-catalogue.js');
|
|
66
|
+
catalogue.resetDiscoveredProviderContributions();
|
|
67
|
+
// Before: discovery has not run, so the catalogue cannot see the vendor. This is the state the
|
|
68
|
+
// CLI was permanently in, and it is asserted so the pin cannot pass on a pre-seeded catalogue.
|
|
69
|
+
expect(catalogue.getComposedProviderEntry('guard-only-vendor')).toBeUndefined();
|
|
70
|
+
await catalogue.resolveAndRegisterSaasProviderContributions({
|
|
71
|
+
saasRoot: '/does-not-matter',
|
|
72
|
+
saasConfig: {},
|
|
73
|
+
});
|
|
74
|
+
const entry = catalogue.getComposedProviderEntry('guard-only-vendor');
|
|
75
|
+
expect(entry?.secrets.map((secret) => secret.envVarName)).toEqual([
|
|
76
|
+
'GUARD_ONLY_VENDOR_CLIENT_ID',
|
|
77
|
+
]);
|
|
78
|
+
catalogue.resetDiscoveredProviderContributions();
|
|
79
|
+
});
|
|
80
|
+
it('leaves no CLI caller on the unpaired resolver', () => {
|
|
81
|
+
const offenders = everyTypescriptSourceFile(CLI_SOURCE_ROOT)
|
|
82
|
+
.filter((path) => !path.endsWith(PAIRED_DOOR_MODULE))
|
|
83
|
+
// A test may name the raw resolver — this file mocks it. The rule is about PRODUCTION
|
|
84
|
+
// callers, and excluding verification code here is what keeps the pin from failing on
|
|
85
|
+
// itself rather than a measured exemption of a population.
|
|
86
|
+
.filter((path) => !path.includes(`${sep}__tests__${sep}`))
|
|
87
|
+
.filter((path) => readFileSync(path, 'utf8').includes('resolveValidatedSaasProviderContributions'));
|
|
88
|
+
// Guards the guard: a walk that found nothing would report a clean tree exactly as a correct
|
|
89
|
+
// one does, so assert the paired door itself is reachable and really names the raw resolver.
|
|
90
|
+
expect(readFileSync(join(CLI_SOURCE_ROOT, PAIRED_DOOR_MODULE), 'utf8')).toContain('resolveValidatedSaasProviderContributions');
|
|
91
|
+
expect(offenders).toEqual([]);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
//# sourceMappingURL=provider-contribution-registration.guard.test.js.map
|
package/dist/src/services/credentials/__tests__/provider-contribution-registration.guard.test.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-contribution-registration.guard.test.js","sourceRoot":"","sources":["../../../../../src/services/credentials/__tests__/provider-contribution-registration.guard.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,IAAI,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAE7D,MAAM,yCAAyC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;AAE5E,EAAE,CAAC,IAAI,CAAC,+BAA+B,EAAE,KAAK,EAAE,cAAc,EAAE,EAAE,CAAC,CAAC;IAClE,GAAG,CAAC,MAAM,cAAc,EAA2B,CAAC;IACpD,yCAAyC;CAC1C,CAAC,CAAC,CAAC;AAEJ,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC1D,MAAM,kBAAkB,GAAG,IAAI,CAC7B,UAAU,EAAE,aAAa,EAAE,gCAAgC,CAC5D,CAAC;AAEF,SAAS,yBAAyB,CAAC,SAAiB;IAClD,OAAO,WAAW,CAAC,SAAS,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvE,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QAC9C,IAAI,KAAK,CAAC,WAAW,EAAE;YAAE,OAAO,yBAAyB,CAAC,SAAS,CAAC,CAAC;QACrE,OAAO,KAAK,CAAC,MAAM,EAAE,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,SA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;QAEZ,MAAM,KAAK,GAAG,SAAS,CAAC,wBAAwB,CAAC,mBAAmB,CAAC,CAAC;QACtE,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC;YAChE,6BAA6B;SAC9B,CAAC,CAAC;QAEH,SAAS,CAAC,oCAAoC,EAAE,CAAC;IACnD,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,+CAA+C,EAAE,GAAG,EAAE;QACvD,MAAM,SAAS,GAAG,yBAAyB,CAAC,eAAe,CAAC;aACzD,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC;YACrD,sFAAsF;YACtF,sFAAsF;YACtF,2DAA2D;aAC1D,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,GAAG,YAAY,GAAG,EAAE,CAAC,CAAC;aACzD,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,QAAQ,CACnD,2CAA2C,CAC5C,CAAC,CAAC;QAEL,6FAA6F;QAC7F,6FAA6F;QAC7F,MAAM,CACJ,YAAY,CAAC,IAAI,CAAC,eAAe,EAAE,kBAAkB,CAAC,EAAE,MAAM,CAAC,CAChE,CAAC,SAAS,CAAC,2CAA2C,CAAC,CAAC;QAEzD,MAAM,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["/**\n * Discovery must REGISTER what it resolves, and every CLI caller must go through the paired door.\n *\n * ## The gap these pins close, and why a green suite hid it (2026-09-09)\n *\n * `composed-provider-secrets.guard.test.ts` proves the DERIVATION: once a package-shipped\n * provider's contribution is registered, its secret is classified, prompted for, and confined.\n * Every pin there plants the contribution by calling `registerDiscoveredProviderContributions`\n * directly — deliberately, so the guard does not drift with a real package's contents.\n *\n * That left the other half unproven, and it was the half that was broken: NOTHING in the CLI ever\n * called that function. Three sites resolved contributions from disk and none registered them, so\n * `getComposedProviderSecretsCatalogue()` was engine-tier only in every CLI process, and\n * `filterProviderEnvToScope` dropped every catalogue provider's authored key as belonging to \"no\n * provider the CLI can see\" — while naming that provider in the runtime's own scope list.\n *\n * So the suite was green because the test planted the state that production never created. The\n * first pin below asserts the pairing; the second asserts that no future caller can take the\n * unpaired door, which is the failure mode that produced three wrong sites in the first place.\n */\nimport { readFileSync, readdirSync } from 'fs';\nimport { join, sep } from 'path';\n\nimport { afterEach, describe, expect, it, vi } from 'vitest';\n\nconst resolveValidatedSaasProviderContributions = vi.hoisted(() => vi.fn());\n\nvi.mock('@wildo-ai/platform-config-lib', async (importOriginal) => ({\n ...(await importOriginal<Record<string, unknown>>()),\n resolveValidatedSaasProviderContributions,\n}));\n\nconst CLI_SOURCE_ROOT = join(__dirname, '..', '..', '..');\nconst PAIRED_DOOR_MODULE = join(\n 'services', 'credentials', 'composed-provider-catalogue.ts',\n);\n\nfunction everyTypescriptSourceFile(directory: string): string[] {\n return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {\n const entryPath = join(directory, entry.name);\n if (entry.isDirectory()) return everyTypescriptSourceFile(entryPath);\n return entry.isFile() && entry.name.endsWith('.ts') ? [entryPath] : [];\n });\n}\n\ndescribe('provider contribution registration', () => {\n afterEach(() => {\n vi.resetModules();\n vi.clearAllMocks();\n });\n\n it('registers into the composed catalogue what discovery resolved', async () => {\n const { ProviderOriginKind, ProviderTier } = await import('@wildo-ai/saas-models');\n const contribution = {\n ref: 'guard-only-vendor',\n identity: {\n packageName: '@wildo-ai/providers',\n tier: ProviderTier.CATALOGUE,\n vendor: 'guard-only-vendor',\n origin: { kind: ProviderOriginKind.GENERATED },\n },\n secretsContractShape: [\n {\n slug: 'clientId',\n envVarName: 'GUARD_ONLY_VENDOR_CLIENT_ID',\n required: true,\n description: 'OAuth2 client id.',\n },\n ],\n runtimeTargets: [{ kind: 'backend' }],\n };\n resolveValidatedSaasProviderContributions.mockResolvedValue([contribution]);\n\n const catalogue = await import('~wildo-cli/services/credentials/composed-provider-catalogue');\n catalogue.resetDiscoveredProviderContributions();\n\n // Before: discovery has not run, so the catalogue cannot see the vendor. This is the state the\n // CLI was permanently in, and it is asserted so the pin cannot pass on a pre-seeded catalogue.\n expect(catalogue.getComposedProviderEntry('guard-only-vendor')).toBeUndefined();\n\n await catalogue.resolveAndRegisterSaasProviderContributions({\n saasRoot: '/does-not-matter',\n saasConfig: {},\n } as never);\n\n const entry = catalogue.getComposedProviderEntry('guard-only-vendor');\n expect(entry?.secrets.map((secret) => secret.envVarName)).toEqual([\n 'GUARD_ONLY_VENDOR_CLIENT_ID',\n ]);\n\n catalogue.resetDiscoveredProviderContributions();\n });\n\n it('leaves no CLI caller on the unpaired resolver', () => {\n const offenders = everyTypescriptSourceFile(CLI_SOURCE_ROOT)\n .filter((path) => !path.endsWith(PAIRED_DOOR_MODULE))\n // A test may name the raw resolver — this file mocks it. The rule is about PRODUCTION\n // callers, and excluding verification code here is what keeps the pin from failing on\n // itself rather than a measured exemption of a population.\n .filter((path) => !path.includes(`${sep}__tests__${sep}`))\n .filter((path) => readFileSync(path, 'utf8').includes(\n 'resolveValidatedSaasProviderContributions',\n ));\n\n // Guards the guard: a walk that found nothing would report a clean tree exactly as a correct\n // one does, so assert the paired door itself is reachable and really names the raw resolver.\n expect(\n readFileSync(join(CLI_SOURCE_ROOT, PAIRED_DOOR_MODULE), 'utf8'),\n ).toContain('resolveValidatedSaasProviderContributions');\n\n expect(offenders).toEqual([]);\n });\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ci-secrets-adapter.service.d.ts","sourceRoot":"","sources":["../../../../src/services/credentials/ci-secrets-adapter.service.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qDAAqD,CAAC;
|
|
1
|
+
{"version":3,"file":"ci-secrets-adapter.service.d.ts","sourceRoot":"","sources":["../../../../src/services/credentials/ci-secrets-adapter.service.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qDAAqD,CAAC;AA0FlG,MAAM,WAAW,sBAAsB;IACrC,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,wBAAgB,iCAAiC,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAKpF;AAeD;;;;;;;;;;;;GAYG;AACH,wBAAgB,yBAAyB,CACvC,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GACpD,sBAAsB,CAuBxB;AAuDD;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACxC,oBAAoB,GAAE,KAAK,CAAC,MAAM,GAAG,sBAAsB,CAAM,GAChE;IAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAkB5C"}
|
|
@@ -18,6 +18,22 @@ const OPERATOR_TYPED_SECRET_PATHS = [
|
|
|
18
18
|
'admin.email',
|
|
19
19
|
'admin.firstName',
|
|
20
20
|
'admin.lastName',
|
|
21
|
+
/*
|
|
22
|
+
* The SECOND administrator, who approves an application-wide access grant (#575).
|
|
23
|
+
*
|
|
24
|
+
* All four, INCLUDING the password, unlike the first administrator. The password is here rather
|
|
25
|
+
* than derived from the registry because the approver block is `.optional()` and a framework-
|
|
26
|
+
* managed key must always exist after provisioning — so `ADMIN_PASSWORD` fills the approver's
|
|
27
|
+
* password without declaring it. Remotely it is operator-typed anyway, which is exactly what this
|
|
28
|
+
* list is for.
|
|
29
|
+
*
|
|
30
|
+
* A CI-reconstructed `secrets.json` missing these rebuilds a platform with ONE administrator —
|
|
31
|
+
* a platform whose widest read refuses for want of anybody able to approve the grant.
|
|
32
|
+
*/
|
|
33
|
+
'approver.email',
|
|
34
|
+
'approver.firstName',
|
|
35
|
+
'approver.lastName',
|
|
36
|
+
'approver.password',
|
|
21
37
|
'atlas.apiPublicKey',
|
|
22
38
|
'atlas.apiPrivateKey',
|
|
23
39
|
'github.orgUrl',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ci-secrets-adapter.service.js","sourceRoot":"","sources":["../../../../src/services/credentials/ci-secrets-adapter.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AAEpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2DAA2D,CAAC;AAE/G;;;GAGG;AACH,MAAM,MAAM,GAAG,eAAe,CAAC;AAE/B;;;;;;;;GAQG;AACH,MAAM,2BAA2B,GAAsB;IACrD,aAAa;IACb,iBAAiB;IACjB,gBAAgB;IAChB,oBAAoB;IACpB,qBAAqB;IACrB,eAAe;IACf,kBAAkB;IAClB,mBAAmB;CACpB,CAAC;AAEF;;;;;;;GAOG;AACH,SAAS,yBAAyB,CAAC,OAAe;IAChD,OAAO,OAAO;SACX,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC;SAC9E,IAAI,CAAC,GAAG,CAAC,CAAC;AACf,CAAC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,cAAc,GAA6C;IAC/D,GAAG,kCAAkC,CAAC,OAAO,CAC3C,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,GAAG,QAAQ,CAAC,YAAY,EAAE,GAAG,QAAQ,CAAC,UAAU,CAAC,CACjE;IACD,GAAG,2BAA2B;CAC/B,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC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CAAC;IAE3C,KAAK,MAAM,KAAK,IAAI,oBAAoB,EAAE,CAAC;QACzC,MAAM,UAAU,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC;QACxE,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI;YACjE,CAAC,CAAC,QAAQ;YACV,CAAC,CAAC,QAAQ,CAAC;QACb,MAAM,CAAC,IAAI,CAAC,GAAG,mBAAmB,GAAG,UAAU,EAAE,CAAC,CAAC;IACrD,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import { z } from 'zod';\n\nimport { PlatformEnvSecretsJson_Schema } from '~wildo-cli/services/credentials/credentials.schemas';\nimport type { PlatformEnvSecretsJson } from '~wildo-cli/services/credentials/credentials.schemas';\nimport { FRAMEWORK_MANAGED_SECRET_MATERIALS } from '~wildo-cli/services/credentials/framework-managed-secrets';\n\n/**\n * Prefix for all CI secret env vars.\n * GitHub Secrets are mapped to `WILDO_SECRET_*` env vars in the workflow.\n */\nconst PREFIX = 'WILDO_SECRET_';\n\n/**\n * `secrets.json` paths an OPERATOR types — the only half of the mapping that can legitimately be\n * hand-listed here, because no registry owns them.\n *\n * Everything else is FRAMEWORK-GENERATED material and is derived from\n * {@link FRAMEWORK_MANAGED_SECRET_MATERIALS} below. The admin IDENTITY fields are here while\n * `admin.password` is not, mirroring the registry's own split: the framework mints the password when\n * the operator does not supply one, and never invents an identity.\n */\nconst OPERATOR_TYPED_SECRET_PATHS: readonly string[] = [\n 'admin.email',\n 'admin.firstName',\n 'admin.lastName',\n 'atlas.apiPublicKey',\n 'atlas.apiPrivateKey',\n 'github.orgUrl',\n 'github.adminUser',\n 'github.adminToken',\n];\n\n/**\n * `mongodb.rootUser` → `MONGODB_ROOT_USER`.\n *\n * The env-var name is DERIVED from the secrets path rather than paired with it by hand, and every\n * one of the 16 framework-managed suffixes this replaced comes back byte-identical — which is what\n * makes the derivation admissible rather than a rename disguised as a refactor (pinned in\n * `ci-secrets-mapping.test.ts`).\n */\nfunction envVarSuffixForSecretPath(dotPath: string): string {\n return dotPath\n .split('.')\n .map((segment) => segment.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase())\n .join('_');\n}\n\n/**\n * Mapping from flat env var suffixes to the structured `PlatformEnvSecretsJson` paths.\n * Each entry is `[ENV_VAR_SUFFIX, dotPath]`.\n *\n * ## Why this is derived and no longer written out\n *\n * This was a hand-kept list restating a population {@link FRAMEWORK_MANAGED_SECRET_MATERIALS} owns,\n * with no mechanical link to it — and it had drifted by THREE materials: the\n * crontabs-batches-manager signing keypair, the immudb state-signing keypair and the mongot\n * sync-source credential. Each is minted on a developer machine and each was silently absent from a\n * CI-reconstructed `secrets.json`, so a pipeline-built deployment ran with the exact degradations\n * those materials exist to prevent: crontabs signing every scheduled tick with a fallback key,\n * immudb running without `--signingKey`, and mongot with no credential to authenticate to mongod.\n *\n * Deriving it means a material added to the registry tomorrow is a GitHub Secret the generated\n * workflow asks for, with no second edit to remember. The registry is itself compile-time-asserted\n * total over `FrameworkManagedSecretMaterialRef`, so the chain has no hand-maintained link left in\n * it. Identity keys are included alongside secret keys because CI must reconstruct the WHOLE\n * material — a password whose username never arrived is not a credential.\n */\nconst FIXED_MAPPINGS: ReadonlyArray<readonly [string, string]> = [\n ...FRAMEWORK_MANAGED_SECRET_MATERIALS.flatMap(\n (material) => [...material.identityKeys, ...material.secretKeys],\n ),\n ...OPERATOR_TYPED_SECRET_PATHS,\n].map((dotPath) => [envVarSuffixForSecretPath(dotPath), dotPath] as const);\n\n/** Protocol-aware provider env var prefix: `WILDO_SECRET_PROVIDER_ENV_<ENV_VAR_NAME>` */\nconst PROVIDER_ENV_PREFIX = `${PREFIX}PROVIDER_ENV_`;\n\nexport interface ProviderCiSecretEnvKey {\n envVarName: string;\n required?: boolean;\n}\n\nexport function normalizePotentialMultilineSecret(key: string, value: string): string {\n if (!/(PRIVATE_KEY|PUBLIC_KEY|PEM|CERTIFICATE)/.test(key)) {\n return value;\n }\n return value.replace(/\\\\n/g, '\\n');\n}\n\nfunction setNestedValue(obj: Record<string, unknown>, dotPath: string, value: string): void {\n const parts = dotPath.split('.');\n let current = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n if (!(key in current) || typeof current[key] !== 'object' || current[key] === null) {\n current[key] = {};\n }\n current = current[key] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]] = value;\n}\n\n/**\n * Reconstructs a `PlatformEnvSecretsJson` from flat environment variables.\n *\n * In CI, secrets are stored in GitHub Secrets and injected as env vars\n * with the `WILDO_SECRET_` prefix. This adapter reads them from `process.env`\n * (or a provided record) and reconstructs the structured object that\n * `PlatformEnvVarsBuilder` and `generateK8sSecrets()` expect.\n *\n * Provider secrets use the protocol-aware convention\n * `WILDO_SECRET_PROVIDER_ENV_<ENV_VAR_NAME>`.\n *\n * @throws {ZodError} if the reconstructed object doesn't pass schema validation\n */\nexport function reconstructSecretsFromEnv(\n env: Record<string, string | undefined> = process.env,\n): PlatformEnvSecretsJson {\n const raw: Record<string, unknown> = {};\n\n for (const [suffix, dotPath] of FIXED_MAPPINGS) {\n const envKey = `${PREFIX}${suffix}`;\n const value = env[envKey];\n if (value !== undefined && value !== '') {\n setNestedValue(raw, dotPath, normalizePotentialMultilineSecret(suffix, value));\n }\n }\n\n const providerEnv: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n if (key.startsWith(PROVIDER_ENV_PREFIX) && value) {\n const envVarName = key.slice(PROVIDER_ENV_PREFIX.length);\n providerEnv[envVarName] = normalizePotentialMultilineSecret(envVarName, value);\n }\n }\n if (Object.keys(providerEnv).length > 0) {\n raw.providerEnv = providerEnv;\n }\n\n return PlatformEnvSecretsJson_Schema.parse(raw);\n}\n\n/**\n * Is this secrets path optional according to `PlatformEnvSecretsJson_Schema`?\n *\n * ## Why it is ASKED rather than listed\n *\n * The list this replaced described itself as \"suffixes that map to `.optional()` sections in\n * `PlatformEnvSecretsJson_Schema`\" — i.e. it was already a hand-kept restatement of an answer the\n * schema gives, one file away, and it had no way to notice a section flipping optional. Asking the\n * schema reproduces every one of its nine entries and extends for free to the three materials it\n * never knew about, all of which are `.optional()` branches: `platform.crontabsBatchesManager`,\n * `immudb` and `mongot`.\n *\n * That answer is also what makes adding them SAFE. A pipeline that is green today declares none of\n * the three; classifying them REQUIRED would have made the generated workflow demand three GitHub\n * Secrets that no existing repository has. Optional is not a hedge here — it is what the schema\n * already says, and `reconstructSecretsFromEnv` parses a payload without them today.\n *\n * A path the schema does not describe THROWS rather than defaulting either way: that means the\n * registry and the schema have drifted, and guessing would put a material into a pipeline under a\n * name nothing will ever read back.\n */\nfunction isOptionalSecretPath(dotPath: string): boolean {\n let node: z.ZodType = PlatformEnvSecretsJson_Schema;\n let optional = false;\n\n for (const segment of dotPath.split('.')) {\n // Unwrap every optional/nullable/default wrapper before looking for a shape: optionality\n // ANYWHERE on the path makes the leaf optional, because the whole branch may be absent.\n while (node.def.type === 'optional' || node.def.type === 'nullable' || node.def.type === 'default') {\n optional = true;\n node = (node.def as unknown as { innerType: z.ZodType }).innerType;\n }\n\n if (node.def.type !== 'object') {\n throw new Error(\n `Secrets path '${dotPath}' is not describable by PlatformEnvSecretsJson_Schema: `\n + `'${segment}' has no object to look in. The secret registry and the schema have drifted.`,\n );\n }\n\n const next = (node as z.ZodObject<Record<string, z.ZodType>>).shape[segment];\n if (!next) {\n throw new Error(\n `Secrets path '${dotPath}' is not declared by PlatformEnvSecretsJson_Schema (missing '${segment}'). `\n + `The secret registry and the schema have drifted.`,\n );\n }\n node = next;\n }\n\n return optional || node.def.type === 'optional';\n}\n\n/**\n * Returns the list of env var names that a CI pipeline should configure\n * as GitHub Secrets. Consumed by `wildo config sync --domain cicd` (via\n * `ci-workflow-generator.service.ts:buildSecretsEnvBlock`) to inject the\n * `${{ secrets.X }}` env block into the generated deploy workflows.\n */\nexport function getRequiredCiSecretEnvVars(\n extraProviderEnvKeys: Array<string | ProviderCiSecretEnvKey> = [],\n): { required: string[]; optional: string[] } {\n const required = FIXED_MAPPINGS\n .filter(([, dotPath]) => !isOptionalSecretPath(dotPath))\n .map(([suffix]) => `${PREFIX}${suffix}`);\n\n const optional = FIXED_MAPPINGS\n .filter(([, dotPath]) => isOptionalSecretPath(dotPath))\n .map(([suffix]) => `${PREFIX}${suffix}`);\n\n for (const entry of extraProviderEnvKeys) {\n const envVarName = typeof entry === 'string' ? entry : entry.envVarName;\n const target = typeof entry === 'string' || entry.required === true\n ? required\n : optional;\n target.push(`${PROVIDER_ENV_PREFIX}${envVarName}`);\n }\n\n return { required, optional };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ci-secrets-adapter.service.js","sourceRoot":"","sources":["../../../../src/services/credentials/ci-secrets-adapter.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AAEpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2DAA2D,CAAC;AAE/G;;;GAGG;AACH,MAAM,MAAM,GAAG,eAAe,CAAC;AAE/B;;;;;;;;GAQG;AACH,MAAM,2BAA2B,GAAsB;IACrD,aAAa;IACb,iBAAiB;IACjB,gBAAgB;IAChB;;;;;;;;;;;OAWG;IACH,gBAAgB;IAChB,oBAAoB;IACpB,mBAAmB;IACnB,mBAAmB;IACnB,oBAAoB;IACpB,qBAAqB;IACrB,eAAe;IACf,kBAAkB;IAClB,mBAAmB;CACpB,CAAC;AAEF;;;;;;;GAOG;AACH,SAAS,yBAAyB,CAAC,OAAe;IAChD,OAAO,OAAO;SACX,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC;SAC9E,IAAI,CAAC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,CAAC,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,GAAG,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;IAE3C,MAAM,QAAQ,GAAG,cAAc;SAC5B,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;SACtD,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,GAAG,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;IAE3C,KAAK,MAAM,KAAK,IAAI,oBAAoB,EAAE,CAAC;QACzC,MAAM,UAAU,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC;QACxE,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI;YACjE,CAAC,CAAC,QAAQ;YACV,CAAC,CAAC,QAAQ,CAAC;QACb,MAAM,CAAC,IAAI,CAAC,GAAG,mBAAmB,GAAG,UAAU,EAAE,CAAC,CAAC;IACrD,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import { z } from 'zod';\n\nimport { PlatformEnvSecretsJson_Schema } from '~wildo-cli/services/credentials/credentials.schemas';\nimport type { PlatformEnvSecretsJson } from '~wildo-cli/services/credentials/credentials.schemas';\nimport { FRAMEWORK_MANAGED_SECRET_MATERIALS } from '~wildo-cli/services/credentials/framework-managed-secrets';\n\n/**\n * Prefix for all CI secret env vars.\n * GitHub Secrets are mapped to `WILDO_SECRET_*` env vars in the workflow.\n */\nconst PREFIX = 'WILDO_SECRET_';\n\n/**\n * `secrets.json` paths an OPERATOR types — the only half of the mapping that can legitimately be\n * hand-listed here, because no registry owns them.\n *\n * Everything else is FRAMEWORK-GENERATED material and is derived from\n * {@link FRAMEWORK_MANAGED_SECRET_MATERIALS} below. The admin IDENTITY fields are here while\n * `admin.password` is not, mirroring the registry's own split: the framework mints the password when\n * the operator does not supply one, and never invents an identity.\n */\nconst OPERATOR_TYPED_SECRET_PATHS: readonly string[] = [\n 'admin.email',\n 'admin.firstName',\n 'admin.lastName',\n /*\n * The SECOND administrator, who approves an application-wide access grant (#575).\n *\n * All four, INCLUDING the password, unlike the first administrator. The password is here rather\n * than derived from the registry because the approver block is `.optional()` and a framework-\n * managed key must always exist after provisioning — so `ADMIN_PASSWORD` fills the approver's\n * password without declaring it. Remotely it is operator-typed anyway, which is exactly what this\n * list is for.\n *\n * A CI-reconstructed `secrets.json` missing these rebuilds a platform with ONE administrator —\n * a platform whose widest read refuses for want of anybody able to approve the grant.\n */\n 'approver.email',\n 'approver.firstName',\n 'approver.lastName',\n 'approver.password',\n 'atlas.apiPublicKey',\n 'atlas.apiPrivateKey',\n 'github.orgUrl',\n 'github.adminUser',\n 'github.adminToken',\n];\n\n/**\n * `mongodb.rootUser` → `MONGODB_ROOT_USER`.\n *\n * The env-var name is DERIVED from the secrets path rather than paired with it by hand, and every\n * one of the 16 framework-managed suffixes this replaced comes back byte-identical — which is what\n * makes the derivation admissible rather than a rename disguised as a refactor (pinned in\n * `ci-secrets-mapping.test.ts`).\n */\nfunction envVarSuffixForSecretPath(dotPath: string): string {\n return dotPath\n .split('.')\n .map((segment) => segment.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase())\n .join('_');\n}\n\n/**\n * Mapping from flat env var suffixes to the structured `PlatformEnvSecretsJson` paths.\n * Each entry is `[ENV_VAR_SUFFIX, dotPath]`.\n *\n * ## Why this is derived and no longer written out\n *\n * This was a hand-kept list restating a population {@link FRAMEWORK_MANAGED_SECRET_MATERIALS} owns,\n * with no mechanical link to it — and it had drifted by THREE materials: the\n * crontabs-batches-manager signing keypair, the immudb state-signing keypair and the mongot\n * sync-source credential. Each is minted on a developer machine and each was silently absent from a\n * CI-reconstructed `secrets.json`, so a pipeline-built deployment ran with the exact degradations\n * those materials exist to prevent: crontabs signing every scheduled tick with a fallback key,\n * immudb running without `--signingKey`, and mongot with no credential to authenticate to mongod.\n *\n * Deriving it means a material added to the registry tomorrow is a GitHub Secret the generated\n * workflow asks for, with no second edit to remember. The registry is itself compile-time-asserted\n * total over `FrameworkManagedSecretMaterialRef`, so the chain has no hand-maintained link left in\n * it. Identity keys are included alongside secret keys because CI must reconstruct the WHOLE\n * material — a password whose username never arrived is not a credential.\n */\nconst FIXED_MAPPINGS: ReadonlyArray<readonly [string, string]> = [\n ...FRAMEWORK_MANAGED_SECRET_MATERIALS.flatMap(\n (material) => [...material.identityKeys, ...material.secretKeys],\n ),\n ...OPERATOR_TYPED_SECRET_PATHS,\n].map((dotPath) => [envVarSuffixForSecretPath(dotPath), dotPath] as const);\n\n/** Protocol-aware provider env var prefix: `WILDO_SECRET_PROVIDER_ENV_<ENV_VAR_NAME>` */\nconst PROVIDER_ENV_PREFIX = `${PREFIX}PROVIDER_ENV_`;\n\nexport interface ProviderCiSecretEnvKey {\n envVarName: string;\n required?: boolean;\n}\n\nexport function normalizePotentialMultilineSecret(key: string, value: string): string {\n if (!/(PRIVATE_KEY|PUBLIC_KEY|PEM|CERTIFICATE)/.test(key)) {\n return value;\n }\n return value.replace(/\\\\n/g, '\\n');\n}\n\nfunction setNestedValue(obj: Record<string, unknown>, dotPath: string, value: string): void {\n const parts = dotPath.split('.');\n let current = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n if (!(key in current) || typeof current[key] !== 'object' || current[key] === null) {\n current[key] = {};\n }\n current = current[key] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]] = value;\n}\n\n/**\n * Reconstructs a `PlatformEnvSecretsJson` from flat environment variables.\n *\n * In CI, secrets are stored in GitHub Secrets and injected as env vars\n * with the `WILDO_SECRET_` prefix. This adapter reads them from `process.env`\n * (or a provided record) and reconstructs the structured object that\n * `PlatformEnvVarsBuilder` and `generateK8sSecrets()` expect.\n *\n * Provider secrets use the protocol-aware convention\n * `WILDO_SECRET_PROVIDER_ENV_<ENV_VAR_NAME>`.\n *\n * @throws {ZodError} if the reconstructed object doesn't pass schema validation\n */\nexport function reconstructSecretsFromEnv(\n env: Record<string, string | undefined> = process.env,\n): PlatformEnvSecretsJson {\n const raw: Record<string, unknown> = {};\n\n for (const [suffix, dotPath] of FIXED_MAPPINGS) {\n const envKey = `${PREFIX}${suffix}`;\n const value = env[envKey];\n if (value !== undefined && value !== '') {\n setNestedValue(raw, dotPath, normalizePotentialMultilineSecret(suffix, value));\n }\n }\n\n const providerEnv: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n if (key.startsWith(PROVIDER_ENV_PREFIX) && value) {\n const envVarName = key.slice(PROVIDER_ENV_PREFIX.length);\n providerEnv[envVarName] = normalizePotentialMultilineSecret(envVarName, value);\n }\n }\n if (Object.keys(providerEnv).length > 0) {\n raw.providerEnv = providerEnv;\n }\n\n return PlatformEnvSecretsJson_Schema.parse(raw);\n}\n\n/**\n * Is this secrets path optional according to `PlatformEnvSecretsJson_Schema`?\n *\n * ## Why it is ASKED rather than listed\n *\n * The list this replaced described itself as \"suffixes that map to `.optional()` sections in\n * `PlatformEnvSecretsJson_Schema`\" — i.e. it was already a hand-kept restatement of an answer the\n * schema gives, one file away, and it had no way to notice a section flipping optional. Asking the\n * schema reproduces every one of its nine entries and extends for free to the three materials it\n * never knew about, all of which are `.optional()` branches: `platform.crontabsBatchesManager`,\n * `immudb` and `mongot`.\n *\n * That answer is also what makes adding them SAFE. A pipeline that is green today declares none of\n * the three; classifying them REQUIRED would have made the generated workflow demand three GitHub\n * Secrets that no existing repository has. Optional is not a hedge here — it is what the schema\n * already says, and `reconstructSecretsFromEnv` parses a payload without them today.\n *\n * A path the schema does not describe THROWS rather than defaulting either way: that means the\n * registry and the schema have drifted, and guessing would put a material into a pipeline under a\n * name nothing will ever read back.\n */\nfunction isOptionalSecretPath(dotPath: string): boolean {\n let node: z.ZodType = PlatformEnvSecretsJson_Schema;\n let optional = false;\n\n for (const segment of dotPath.split('.')) {\n // Unwrap every optional/nullable/default wrapper before looking for a shape: optionality\n // ANYWHERE on the path makes the leaf optional, because the whole branch may be absent.\n while (node.def.type === 'optional' || node.def.type === 'nullable' || node.def.type === 'default') {\n optional = true;\n node = (node.def as unknown as { innerType: z.ZodType }).innerType;\n }\n\n if (node.def.type !== 'object') {\n throw new Error(\n `Secrets path '${dotPath}' is not describable by PlatformEnvSecretsJson_Schema: `\n + `'${segment}' has no object to look in. The secret registry and the schema have drifted.`,\n );\n }\n\n const next = (node as z.ZodObject<Record<string, z.ZodType>>).shape[segment];\n if (!next) {\n throw new Error(\n `Secrets path '${dotPath}' is not declared by PlatformEnvSecretsJson_Schema (missing '${segment}'). `\n + `The secret registry and the schema have drifted.`,\n );\n }\n node = next;\n }\n\n return optional || node.def.type === 'optional';\n}\n\n/**\n * Returns the list of env var names that a CI pipeline should configure\n * as GitHub Secrets. Consumed by `wildo config sync --domain cicd` (via\n * `ci-workflow-generator.service.ts:buildSecretsEnvBlock`) to inject the\n * `${{ secrets.X }}` env block into the generated deploy workflows.\n */\nexport function getRequiredCiSecretEnvVars(\n extraProviderEnvKeys: Array<string | ProviderCiSecretEnvKey> = [],\n): { required: string[]; optional: string[] } {\n const required = FIXED_MAPPINGS\n .filter(([, dotPath]) => !isOptionalSecretPath(dotPath))\n .map(([suffix]) => `${PREFIX}${suffix}`);\n\n const optional = FIXED_MAPPINGS\n .filter(([, dotPath]) => isOptionalSecretPath(dotPath))\n .map(([suffix]) => `${PREFIX}${suffix}`);\n\n for (const entry of extraProviderEnvKeys) {\n const envVarName = typeof entry === 'string' ? entry : entry.envVarName;\n const target = typeof entry === 'string' || entry.required === true\n ? required\n : optional;\n target.push(`${PROVIDER_ENV_PREFIX}${envVarName}`);\n }\n\n return { required, optional };\n}\n"]}
|