UNPKG

everything-dev

Version:

A consolidated product package for building Module Federation apps with oRPC APIs.

1 lines 67.6 kB
{"version":3,"file":"init.cjs","names":["require","resolveExtendsRef","fetchBosConfigFromFastKv","saveBosConfig","loadManifestNormalizationSpec","normalizePackageManifestsInTree","writeSnapshot"],"sources":["../../src/cli/init.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { execa } from \"execa\";\nimport { glob } from \"glob\";\nimport type { OverrideSection } from \"../contract\";\nimport { fetchBosConfigFromFastKv } from \"../fastkv\";\nimport {\n loadManifestNormalizationSpec,\n normalizePackageManifestsInTree,\n} from \"../internal/manifest-normalizer\";\nimport { resolveExtendsRef } from \"../merge\";\nimport type { BosConfig, BosConfigInput } from \"../types\";\nimport { saveBosConfig } from \"../utils/save-config\";\nimport { writeSnapshot } from \"./snapshot\";\n\nconst require = createRequire(import.meta.url);\n\nexport const INIT_ROOT_PATTERNS = [\n \"bos.config.json\",\n \"package.json\",\n \".env.example\",\n \".gitignore\",\n \"biome.json\",\n \"bunfig.toml\",\n \"Dockerfile\",\n \"railway.json\",\n \"railway.toml\",\n \"AGENTS.md\",\n \".changeset/config.json\",\n \".changeset/README.md\",\n \"README.md\",\n \"CONTRIBUTING.md\",\n \".github/templates/**\",\n] as const;\n\nconst OVERRIDE_WORKSPACE_MAP: Record<OverrideSection, string[]> = {\n ui: [\"ui\"],\n api: [\"api\"],\n host: [\"host\"],\n plugins: [],\n};\n\ninterface SourceResult {\n sourceDir: string;\n parentConfig: BosConfig;\n cleanup: () => Promise<void>;\n}\n\nexport interface CatalogChainSource {\n catalog: Record<string, string>;\n repository?: string;\n extendsChain: string[];\n}\n\nfunction getExtendsRef(config: Record<string, unknown>): string | undefined {\n if (typeof config.extends === \"string\") {\n return config.extends;\n }\n\n if (config.extends && typeof config.extends === \"object\") {\n return resolveExtendsRef(config.extends as Record<string, string>, \"production\");\n }\n\n return undefined;\n}\n\nfunction parseBosRef(ref: string): { account: string; gateway: string } | null {\n const match = ref.match(/^bos:\\/\\/([^/]+)\\/(.+)$/);\n if (!match?.[1] || !match[2]) return null;\n return { account: match[1], gateway: match[2] };\n}\n\nfunction readWorkspaceCatalog(sourceDir: string): Record<string, string> {\n const pkgPath = join(sourceDir, \"package.json\");\n if (!existsSync(pkgPath)) {\n return {};\n }\n\n const pkg = readJsonFile<{ workspaces?: { catalog?: Record<string, string> } }>(pkgPath);\n return { ...(pkg.workspaces?.catalog ?? {}) };\n}\n\nexport async function resolveCatalogChainSource(opts: {\n extendsAccount: string;\n extendsGateway: string;\n sourceDir?: string;\n}): Promise<CatalogChainSource> {\n const catalogs: Record<string, string>[] = [];\n const cleanups: Array<() => Promise<void>> = [];\n const extendsChain: string[] = [];\n const visited = new Set<string>();\n let repository: string | undefined;\n let currentRef = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n let sourceDir = opts.sourceDir ? resolve(opts.sourceDir) : undefined;\n let configPath = sourceDir ? join(sourceDir, \"bos.config.json\") : undefined;\n\n try {\n while (true) {\n if (visited.has(currentRef)) {\n throw new Error(`Circular extends detected while resolving catalog source: ${currentRef}`);\n }\n\n visited.add(currentRef);\n extendsChain.push(currentRef);\n\n let config: Record<string, unknown>;\n let currentSourceDir = sourceDir;\n let cleanup: () => Promise<void> = async () => {};\n\n if (configPath) {\n config = readJsonFile<Record<string, unknown>>(configPath);\n currentSourceDir = dirname(configPath);\n } else {\n const parsed = parseBosRef(currentRef);\n if (!parsed) {\n break;\n }\n const sourceResult = await resolveSourceDir({\n extendsAccount: parsed.account,\n extendsGateway: parsed.gateway,\n });\n config = sourceResult.parentConfig as Record<string, unknown>;\n currentSourceDir = sourceResult.sourceDir || undefined;\n cleanup = sourceResult.cleanup;\n }\n\n cleanups.push(cleanup);\n catalogs.push(currentSourceDir ? readWorkspaceCatalog(currentSourceDir) : {});\n\n if (typeof config.repository === \"string\") {\n repository = config.repository;\n }\n\n const nextExtendsRef = getExtendsRef(config);\n if (!nextExtendsRef) {\n break;\n }\n\n if (nextExtendsRef.startsWith(\"bos://\")) {\n currentRef = nextExtendsRef;\n sourceDir = undefined;\n configPath = undefined;\n continue;\n }\n\n if (!currentSourceDir) {\n break;\n }\n\n const nextConfigPath = resolve(currentSourceDir, nextExtendsRef);\n if (!existsSync(nextConfigPath)) {\n break;\n }\n\n currentRef = nextConfigPath;\n sourceDir = dirname(nextConfigPath);\n configPath = nextConfigPath;\n }\n } finally {\n for (const cleanup of cleanups.reverse()) {\n await cleanup();\n }\n }\n\n return {\n catalog: Object.assign({}, ...catalogs.reverse()),\n repository,\n extendsChain,\n };\n}\n\nexport async function resolveSourceDir(opts: {\n extendsAccount: string;\n extendsGateway: string;\n source?: string;\n}): Promise<SourceResult> {\n if (opts.source) {\n const sourceDir = resolve(opts.source);\n if (!existsSync(join(sourceDir, \"bos.config.json\"))) {\n throw new Error(`No bos.config.json found in source directory: ${sourceDir}`);\n }\n const parentConfig = JSON.parse(\n readFileSync(join(sourceDir, \"bos.config.json\"), \"utf-8\"),\n ) as BosConfig;\n return { sourceDir, parentConfig, cleanup: async () => {} };\n }\n\n const parentConfig = await fetchParentConfig(opts.extendsAccount, opts.extendsGateway);\n\n if (parentConfig.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(parentConfig.repository);\n return { sourceDir, parentConfig, cleanup };\n }\n\n const chainResult = await resolveRepositoryViaExtendsChain(\n opts.extendsAccount,\n opts.extendsGateway,\n );\n if (chainResult?.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(chainResult.repository);\n return { sourceDir, parentConfig: chainResult.config, cleanup };\n }\n\n return {\n sourceDir: \"\",\n parentConfig,\n cleanup: async () => {},\n };\n}\n\nexport function buildInitPatterns(overrides: OverrideSection[], plugins?: string[]): string[] {\n const has = (section: OverrideSection) => overrides.includes(section);\n const patterns: string[] = [...INIT_ROOT_PATTERNS];\n\n if (has(\"ui\")) patterns.push(\"ui/**\");\n if (has(\"api\")) patterns.push(\"api/**\");\n if (has(\"host\")) patterns.push(\"host/**\");\n if (has(\"plugins\")) {\n for (const plugin of plugins ?? []) {\n patterns.push(`plugins/${plugin}/**`);\n }\n }\n\n return patterns;\n}\n\nexport function sourcePathToDestinationPath(filePath: string): string {\n return filePath.startsWith(\".github/templates/\")\n ? filePath.replace(/^\\.github\\/templates\\//, \".github/\")\n : filePath;\n}\n\nexport async function fetchParentConfig(\n extendsAccount: string,\n extendsGateway: string,\n): Promise<BosConfig> {\n const bosUrl = `bos://${extendsAccount}/${extendsGateway}`;\n return fetchBosConfigFromFastKv<BosConfig>(bosUrl);\n}\n\nexport async function resolveRepositoryViaExtendsChain(\n extendsAccount: string,\n extendsGateway: string,\n visited = new Set<string>(),\n): Promise<{ repository: string; config: BosConfig } | null> {\n const key = `bos://${extendsAccount}/${extendsGateway}`;\n if (visited.has(key)) return null;\n visited.add(key);\n\n try {\n const config = await fetchParentConfig(extendsAccount, extendsGateway);\n if (config.repository) {\n return { repository: config.repository, config };\n }\n\n const extendsRef = getExtendsRef(config as Record<string, unknown>);\n if (extendsRef) {\n const normalized = extendsRef.startsWith(\"bos://\") ? extendsRef : `bos://${extendsRef}`;\n const parsed = parseBosRef(normalized);\n if (parsed) {\n const result = await resolveRepositoryViaExtendsChain(\n parsed.account,\n parsed.gateway,\n visited,\n );\n if (result) return result;\n }\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\nexport async function detectGitRemoteUrl(directory: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd: directory,\n stdio: \"pipe\",\n });\n const url = stdout.trim();\n if (!url) return undefined;\n return normalizeGitUrl(url);\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeGitUrl(url: string): string | undefined {\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`;\n }\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`;\n }\n return url.endsWith(\".git\") ? url.slice(0, -4) : url;\n}\n\nexport async function downloadTarball(\n repoUrl: string,\n): Promise<{ dir: string; cleanup: () => Promise<void> }> {\n const parsed = parseGitHubUrl(repoUrl);\n if (!parsed) {\n throw new Error(`Cannot parse repository URL: ${repoUrl}`);\n }\n\n const { owner, repo } = parsed;\n let response: Response | null = null;\n\n for (const branch of [\"main\", \"master\"]) {\n const candidate = await fetch(\n `https://api.github.com/repos/${owner}/${repo}/tarball/${branch}`,\n {\n headers: { \"User-Agent\": \"everything-dev\" },\n redirect: \"follow\",\n },\n );\n if (candidate.ok) {\n response = candidate;\n break;\n }\n if (candidate.status !== 404) {\n throw new Error(\n `GitHub tarball download failed: ${candidate.status} ${candidate.statusText}`,\n );\n }\n }\n\n if (!response) {\n throw new Error(`GitHub tarball download failed for ${repoUrl}: tried main and master`);\n }\n\n if (!response.body) {\n throw new Error(\"GitHub tarball download returned empty body\");\n }\n\n const tmpDir = mkTmpDir(\"bos-init-tarball-\");\n const tarballPath = join(tmpDir, \"source.tar.gz\");\n\n const fileStream = createWriteStream(tarballPath);\n const reader = response.body as unknown as NodeJS.ReadableStream;\n await pipeline(reader, fileStream);\n\n const extractDir = mkTmpDir(\"bos-init-extract-\");\n try {\n const tar = require(\"tar\") as {\n extract: (opts: { cwd: string; file: string; strip: number }) => Promise<void>;\n };\n await tar.extract({ cwd: extractDir, file: tarballPath, strip: 1 });\n } catch {\n await execCommand(\"tar\", [\"-xzf\", tarballPath, \"--strip-components=1\", \"-C\", extractDir]);\n }\n\n rmSync(tmpDir, { recursive: true, force: true });\n\n return {\n dir: extractDir,\n cleanup: async () => {\n rmSync(extractDir, { recursive: true, force: true });\n },\n };\n}\n\nfunction parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return { owner: httpsMatch[1], repo: httpsMatch[2] };\n }\n\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return { owner: sshMatch[1], repo: sshMatch[2] };\n }\n\n return null;\n}\n\nexport async function copyFilteredFiles(\n sourceDir: string,\n destination: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<number> {\n if (patterns.length === 0) {\n return 0;\n }\n\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n mkdirSync(destination, { recursive: true });\n\n let count = 0;\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n\n const destPath = sourcePathToDestinationPath(filePath);\n const dest = join(destination, destPath);\n mkdirSync(dirname(dest), { recursive: true });\n const content = readFileSync(src);\n writeFileSync(dest, content);\n count++;\n }\n\n return count;\n}\n\nfunction stripProductionFields(entry: Record<string, unknown>): void {\n delete entry.production;\n delete entry.integrity;\n delete entry.ssr;\n delete entry.ssrIntegrity;\n}\n\nfunction buildRootTypecheckScript(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): string {\n const commands = [\"bun run types:gen\"];\n\n if (sections.ui) {\n commands.push(\"if [ -d ui ]; then bun run --cwd ui typecheck; fi\");\n }\n if (sections.api) {\n commands.push(\"if [ -d api ]; then bun run --cwd api typecheck; fi\");\n }\n if (sections.host) {\n commands.push(\"if [ -d host ]; then bun run --cwd host typecheck; fi\");\n }\n if (sections.plugins) {\n commands.push(\n 'if [ -d plugins ]; then for dir in plugins/*; do if [ -f \"$dir/package.json\" ]; then bun run --cwd \"$dir\" typecheck; fi; done; fi',\n );\n }\n\n return commands.join(\" && \");\n}\n\nexport function buildChildRootScripts(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): Record<string, string> {\n const scripts: Record<string, string> = {\n dev: \"node_modules/.bin/bos dev\",\n \"dev:proxy\": \"node_modules/.bin/bos dev --proxy\",\n build: \"node_modules/.bin/bos build\",\n deploy: \"node_modules/.bin/bos build --deploy\",\n publish: \"node_modules/.bin/bos publish\",\n start: \"node_modules/.bin/bos start\",\n typecheck: buildRootTypecheckScript(sections),\n lint: \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n format: \"biome format --write .\",\n \"format:check\": \"biome format .\",\n changeset: \"changeset\",\n version: \"changeset version\",\n release: \"echo 'Packages versioned - app release handled by workflow'\",\n postinstall: \"node_modules/.bin/bos types gen || true\",\n \"types:gen\": \"node_modules/.bin/bos types gen\",\n bos: \"node_modules/.bin/bos\",\n };\n\n if (sections.api) {\n scripts[\"db:push\"] = \"bun run --cwd api drizzle-kit push\";\n scripts[\"db:studio\"] = \"bun run --cwd api drizzle-kit studio\";\n scripts[\"db:generate\"] = \"bun run --cwd api drizzle-kit generate\";\n scripts[\"db:migrate\"] = \"bun run --cwd api drizzle-kit migrate\";\n scripts[\"test:api\"] = \"cd api && bun run test tests/integration/ tests/unit/\";\n scripts[\"test:integration\"] = \"cd api && bun run test tests/integration/\";\n }\n\n if (sections.host) {\n scripts[\"test:e2e\"] = \"bun run --cwd host test:e2e\";\n }\n\n if (sections.api && sections.host) {\n scripts.test = \"bun run test:api && bun run test:e2e\";\n } else if (sections.api) {\n scripts.test = \"bun run test:api\";\n } else if (sections.host) {\n scripts.test = \"bun run test:e2e\";\n }\n\n if (sections.api || sections.host) {\n scripts[\"dev:postgres\"] = \"docker compose up -d --wait && bun run dev\";\n scripts[\"dev:postgres:down\"] = \"docker compose down\";\n scripts[\"dev:postgres:reset\"] = \"docker compose down -v && docker compose up -d --wait\";\n }\n\n if (sections.ui) {\n scripts[\"dev:ui\"] = \"node_modules/.bin/bos dev --ui local --api remote\";\n }\n if (sections.api) {\n scripts[\"dev:api\"] = \"node_modules/.bin/bos dev --ui remote --api local\";\n }\n\n return scripts;\n}\n\nexport async function personalizeConfig(\n destination: string,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n pluginRoutes?: Record<string, string[]>;\n workspaceOpts?: { localOverrides?: boolean; sourceDir?: string };\n mode?: \"init\" | \"sync\";\n existingConfig?: Record<string, unknown>;\n repository?: string;\n title?: string;\n description?: string;\n testnet?: string;\n staging?: unknown;\n },\n): Promise<void> {\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n const existingApp =\n opts.mode === \"sync\" && opts.existingConfig?.app && typeof opts.existingConfig.app === \"object\"\n ? (opts.existingConfig.app as Record<string, unknown>)\n : undefined;\n const preservedAuth = existingApp?.auth;\n\n const explicitRootKeys = new Set(\n Object.entries(opts)\n .filter(\n ([key, value]) =>\n value !== undefined &&\n ![\n \"extendsAccount\",\n \"extendsGateway\",\n \"plugins\",\n \"overrides\",\n \"pluginRoutes\",\n \"workspaceOpts\",\n \"mode\",\n \"existingConfig\",\n ].includes(key),\n )\n .map(([key]) => key),\n );\n\n const configPath = join(destination, \"bos.config.json\");\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>;\n\n config.extends = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n\n if (opts.account) {\n config.account = opts.account;\n }\n if (opts.domain) {\n config.domain = opts.domain;\n }\n if (opts.repository) {\n config.repository = opts.repository;\n } else {\n delete config.repository;\n }\n\n const inheritableFields = [\"title\", \"description\", \"testnet\", \"staging\"] as const;\n for (const field of inheritableFields) {\n if (!(field in opts)) {\n delete config[field];\n }\n }\n\n if (config.app && typeof config.app === \"object\") {\n const app = config.app as Record<string, unknown>;\n\n for (const entryKey of Object.keys(app)) {\n if (\n !has(entryKey as OverrideSection) &&\n (entryKey === \"host\" || entryKey === \"ui\" || entryKey === \"api\")\n ) {\n delete app[entryKey];\n continue;\n }\n if (entryKey === \"auth\") {\n delete app[entryKey];\n continue;\n }\n const entry = app[entryKey];\n if (entry && typeof entry === \"object\") {\n stripProductionFields(entry as Record<string, unknown>);\n }\n }\n\n if (preservedAuth !== undefined) {\n app.auth = preservedAuth;\n }\n\n if (Object.keys(app).length === 0) {\n delete config.app;\n }\n }\n\n if (has(\"plugins\")) {\n if (config.plugins && typeof config.plugins === \"object\") {\n const plugins = config.plugins as Record<string, unknown>;\n\n if (opts.plugins !== undefined) {\n for (const pluginKey of Object.keys(plugins)) {\n if (!opts.plugins.includes(pluginKey)) {\n delete plugins[pluginKey];\n }\n }\n }\n\n for (const pluginKey of Object.keys(plugins)) {\n const plugin = plugins[pluginKey];\n let pluginObj: Record<string, unknown>;\n\n if (typeof plugin === \"string\") {\n pluginObj = { extends: plugin };\n plugins[pluginKey] = pluginObj;\n } else if (plugin && typeof plugin === \"object\") {\n pluginObj = { ...(plugin as Record<string, unknown>) };\n plugins[pluginKey] = pluginObj;\n } else {\n continue;\n }\n\n stripProductionFields(pluginObj);\n }\n\n if (Object.keys(plugins).length === 0) {\n config.plugins = {};\n }\n }\n } else {\n config.plugins = {};\n }\n\n if (opts.mode === \"sync\" && opts.existingConfig) {\n const managedRootKeys = new Set([\"extends\", \"account\", \"domain\", \"app\", \"plugins\"]);\n const preservedRootKeys = new Set([\n ...managedRootKeys,\n ...Object.keys(opts.existingConfig),\n ...explicitRootKeys,\n ]);\n\n for (const key of Object.keys(config)) {\n if (!preservedRootKeys.has(key)) {\n delete config[key];\n }\n }\n\n for (const [key, value] of Object.entries(opts.existingConfig)) {\n if (!(key in config) && !managedRootKeys.has(key) && !explicitRootKeys.has(key)) {\n config[key] = value;\n }\n }\n }\n\n await saveBosConfig(destination, config);\n }\n\n const pkgPath = join(destination, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const childScripts = buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n });\n\n if (typeof pkg.name !== \"string\" || pkg.name.length === 0) {\n pkg.name = \"monorepo\";\n }\n pkg.private = true;\n pkg.type = \"module\";\n delete pkg.module;\n delete pkg.peerDependencies;\n\n if (pkg.workspaces && typeof pkg.workspaces === \"object\") {\n const ws = pkg.workspaces as { packages?: string[] };\n if (Array.isArray(ws.packages)) {\n ws.packages = ws.packages.filter((p: string) => {\n if (p.startsWith(\"packages/\")) return false;\n if (p === \"ui\") return has(\"ui\");\n if (p === \"api\") return has(\"api\");\n if (p === \"host\") return has(\"host\");\n if (p.startsWith(\"plugins/\")) return false;\n return true;\n });\n\n if (has(\"plugins\")) {\n if (!ws.packages.includes(\"plugins/*\")) {\n ws.packages.push(\"plugins/*\");\n }\n }\n }\n }\n\n if (!pkg.scripts || typeof pkg.scripts !== \"object\") {\n pkg.scripts = {};\n }\n const scripts = pkg.scripts as Record<string, string>;\n for (const [key, value] of Object.entries(childScripts)) {\n scripts[key] = value;\n }\n for (const obsoleteScript of [\n \"init\",\n \"sync-catalog\",\n \"db:push\",\n \"db:studio\",\n \"db:generate\",\n \"db:migrate\",\n \"test\",\n \"test:api\",\n \"test:integration\",\n \"test:e2e\",\n \"dev:postgres\",\n \"dev:postgres:down\",\n \"dev:postgres:reset\",\n \"dev:ui\",\n \"dev:api\",\n ]) {\n if (!(obsoleteScript in childScripts)) {\n delete scripts[obsoleteScript];\n }\n }\n\n if (pkg.devDependencies && typeof pkg.devDependencies === \"object\") {\n const deps = pkg.devDependencies as Record<string, string>;\n delete deps[\"every-plugin\"];\n delete deps[\"everything-dev\"];\n }\n\n if (!pkg.workspaces || typeof pkg.workspaces !== \"object\") {\n pkg.workspaces = { packages: [], catalog: {} };\n }\n const workspaces = pkg.workspaces as { packages?: string[]; catalog?: Record<string, string> };\n if (!workspaces.catalog || typeof workspaces.catalog !== \"object\") {\n workspaces.catalog = {};\n }\n\n if (!pkg.dependencies) pkg.dependencies = {};\n const deps = pkg.dependencies as Record<string, string>;\n const spec = opts.workspaceOpts?.sourceDir\n ? loadManifestNormalizationSpec(opts.workspaceOpts.sourceDir)\n : null;\n if (spec) {\n workspaces.catalog[\"everything-dev\"] = spec.rootCatalog[\"everything-dev\"];\n workspaces.catalog[\"every-plugin\"] = spec.rootCatalog[\"every-plugin\"];\n }\n const frameworkCatalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n sourceDir: opts.workspaceOpts?.sourceDir,\n })\n ).catalog;\n for (const [name, version] of Object.entries(frameworkCatalog)) {\n workspaces.catalog[name] = version;\n }\n if (!deps[\"everything-dev\"]) deps[\"everything-dev\"] = \"catalog:\";\n if (!deps[\"every-plugin\"]) deps[\"every-plugin\"] = \"catalog:\";\n\n writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n }\n\n const apiTsConfigPath = join(destination, \"api\", \"tsconfig.json\");\n if (existsSync(apiTsConfigPath)) {\n const apiTsConfig = JSON.parse(readFileSync(apiTsConfigPath, \"utf-8\")) as {\n files?: string[];\n [key: string]: unknown;\n };\n if (apiTsConfig.files) {\n const validFiles = apiTsConfig.files.filter((f) => existsSync(join(destination, \"api\", f)));\n if (validFiles.length !== apiTsConfig.files.length) {\n if (validFiles.length === 0) {\n delete apiTsConfig.files;\n } else {\n apiTsConfig.files = validFiles;\n }\n writeFileSync(apiTsConfigPath, `${JSON.stringify(apiTsConfig, null, 2)}\\n`);\n }\n }\n }\n\n await resolveWorkspaceRefs(destination, opts.workspaceOpts);\n\n if (has(\"ui\")) {\n const genContractPath = join(destination, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n if (!existsSync(genContractPath)) {\n mkdirSync(dirname(genContractPath), { recursive: true });\n writeFileSync(genContractPath, `export type ApiContract = Record<string, never>;\\n`);\n }\n }\n\n if (has(\"api\")) {\n const pluginsClientGenPath = join(destination, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n if (!existsSync(pluginsClientGenPath)) {\n mkdirSync(dirname(pluginsClientGenPath), { recursive: true });\n writeFileSync(\n pluginsClientGenPath,\n `import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";\\ntype ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\\nexport type PluginsClient = Record<string, never>;\\n`,\n );\n }\n }\n\n const authTypesPaths: string[] = [];\n if (has(\"ui\")) {\n authTypesPaths.push(join(destination, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"api\")) {\n authTypesPaths.push(join(destination, \"api\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"host\") && existsSync(join(destination, \"host\", \"src\"))) {\n authTypesPaths.push(join(destination, \"host\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n for (const authTypesGenPath of authTypesPaths) {\n if (!existsSync(authTypesGenPath)) {\n mkdirSync(dirname(authTypesGenPath), { recursive: true });\n writeFileSync(authTypesGenPath, generateAuthTypesContent(authTypesGenPath, destination));\n }\n }\n\n if (authTypesPaths.length > 0) {\n const authDir = join(destination, \".bos\", \"generated\", \"auth\");\n if (!existsSync(authDir)) {\n mkdirSync(authDir, { recursive: true });\n }\n const authExportStubPath = join(authDir, \"auth-export.d.ts\");\n if (!existsSync(authExportStubPath)) {\n writeFileSync(\n authExportStubPath,\n `export type Auth = any;\nexport type AuthOrganizationContext = any;\nexport type AuthOrganization = any;\nexport type AuthOrganizationSummary = any;\nexport type AuthOrganizationMember = any;\nexport type AuthApiKey = any;\nexport type AuthInvitation = any;\nexport type GetActiveMemberInput = any;\nexport type GetOrganizationInput = any;\nexport type ListMembersInput = any;\nexport type ListInvitationsInput = any;\nexport type ListApiKeysInput = any;\nexport type AuthServices = any;\nexport type createAuthInstance = any;\n`,\n );\n }\n const contractStubPath = join(authDir, \"contract.d.ts\");\n if (!existsSync(contractStubPath)) {\n writeFileSync(\n contractStubPath,\n `export type ContractType = any;\nexport type InferOutput<_TRoute extends string> = any;\n`,\n );\n }\n }\n\n if (has(\"plugins\")) {\n for (const plugin of opts.plugins ?? []) {\n const pluginSrcDir = join(destination, \"plugins\", plugin, \"src\");\n const pluginIndexPath = join(pluginSrcDir, \"index.ts\");\n const pluginClientGenPath = join(pluginSrcDir, \"plugins-client.gen.ts\");\n if (!existsSync(pluginIndexPath) || existsSync(pluginClientGenPath)) {\n continue;\n }\n const pluginIndex = readFileSync(pluginIndexPath, \"utf-8\");\n if (!pluginIndex.includes(\"./plugins-client.gen\")) {\n continue;\n }\n writeFileSync(pluginClientGenPath, \"export type PluginsClient = Record<string, never>;\\n\");\n }\n }\n}\n\nfunction generateAuthTypesContent(targetPath: string, configDir: string): string {\n const authExportRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"auth-export.d.ts\"),\n targetPath,\n );\n const contractRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"contract.d.ts\"),\n targetPath,\n );\n\n return `export type {\n Auth,\n AuthOrganizationContext,\n AuthOrganization,\n AuthOrganizationSummary,\n AuthOrganizationMember,\n AuthApiKey,\n AuthInvitation,\n GetActiveMemberInput,\n GetOrganizationInput,\n ListMembersInput,\n ListInvitationsInput,\n ListApiKeysInput,\n AuthServices,\n createAuthInstance,\n} from \"${authExportRel}\";\nimport type { InferOutput, ContractType as AuthContract } from \"${contractRel}\";\nimport type { Auth as BaseAuth } from \"${authExportRel}\";\n\ntype RawAuthSession = InferOutput<\"getSession\">;\ntype RawAuthRequestContext = InferOutput<\"getContext\">;\ntype RawAuthActiveMember = InferOutput<\"getActiveMember\">;\n\nexport type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {\n role?: string | null;\n isAnonymous?: boolean | null;\n walletAddress?: string | null;\n banned?: boolean | null;\n};\nexport type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {\n activeOrganizationId?: string | null;\n};\nexport type AuthSession = {\n user: AuthSessionUser | null;\n session: AuthSessionData | null;\n};\nexport type AuthRequestContext = RawAuthRequestContext & {\n organization?: { activeOrganizationId?: string | null } | null;\n apiKey?: { id: string; permissions?: Record<string, string[]> | null } | null;\n};\nexport type AuthActiveMember = RawAuthActiveMember;\nexport type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];\nexport type AuthContractType = AuthContract;\n`;\n}\n\nfunction toRelativeImportPath(fromPath: string, toPath: string): string {\n const rel = relative(dirname(toPath), fromPath);\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nexport async function runBunInstall(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--ignore-scripts\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runBunInstallForUpgrade(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--force\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runTypesGen(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n const localBosBin = join(destination, \"node_modules\", \".bin\", \"bos\");\n if (existsSync(localBosBin)) {\n await runWithProgress(\n \"node_modules/.bin/bos\",\n [\"types\", \"gen\"],\n destination,\n spinner,\n \"Generating types\",\n );\n return;\n }\n\n throw new Error(\"Unable to locate bos CLI for types generation\");\n}\n\nexport async function runDockerComposeUp(destination: string): Promise<void> {\n await execCommand(\"docker\", [\"compose\", \"up\", \"-d\", \"--wait\"], destination, { stdio: \"inherit\" });\n}\n\nasync function runWithProgress(\n command: string,\n args: string[],\n cwd: string,\n spinner: { message: (msg: string) => void } | undefined,\n label: string,\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n const child = execa(command, args, { cwd, stdio: \"inherit\", timeout });\n\n if (spinner) {\n const start = Date.now();\n const interval = setInterval(() => {\n const elapsed = Math.round((Date.now() - start) / 1000);\n spinner.message(`${label}... (${elapsed}s)`);\n }, 2000);\n try {\n await child;\n } finally {\n clearInterval(interval);\n }\n } else {\n await child;\n }\n}\n\nexport function stripOrphanedWorkspacesFromLockfile(\n lockfilePath: string,\n allowedWorkspaces: string[],\n): void {\n if (!existsSync(lockfilePath)) return;\n\n const content = readFileSync(lockfilePath, \"utf-8\");\n let lockfile: Record<string, unknown>;\n try {\n lockfile = JSON.parse(content) as Record<string, unknown>;\n } catch {\n return;\n }\n\n const workspaces = lockfile.workspaces;\n if (!workspaces || typeof workspaces !== \"object\") return;\n\n const workspaceMap = workspaces as Record<string, unknown>;\n const allowed = new Set([\"\", ...allowedWorkspaces]);\n\n const keys = Object.keys(workspaceMap);\n let changed = false;\n for (const key of keys) {\n if (allowed.has(key)) continue;\n if (\n allowedWorkspaces.some(\n (pattern) => pattern.endsWith(\"/*\") && key.startsWith(pattern.slice(0, -1)),\n )\n )\n continue;\n delete workspaceMap[key];\n changed = true;\n }\n\n if (changed) {\n writeFileSync(lockfilePath, `${JSON.stringify(lockfile, null, 2)}\\n`);\n }\n}\n\nexport function removeInitLockfile(lockfilePath: string): void {\n if (!existsSync(lockfilePath)) return;\n rmSync(lockfilePath, { force: true });\n}\n\nfunction readJsonFile<T>(filePath: string): T {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n}\n\nexport async function scaffoldMinimalProject(\n destination: string,\n parentConfig: BosConfigInput,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n repository?: string;\n title?: string;\n description?: string;\n },\n): Promise<number> {\n mkdirSync(destination, { recursive: true });\n\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n\n const config: Record<string, unknown> = {\n extends: `bos://${opts.extendsAccount}/${opts.extendsGateway}`,\n account: opts.account || opts.extendsAccount,\n ...(opts.domain ? { domain: opts.domain } : {}),\n ...(opts.repository ? { repository: opts.repository } : {}),\n ...(opts.title ? { title: opts.title } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n };\n\n if (parentConfig.app && typeof parentConfig.app === \"object\") {\n const app: Record<string, unknown> = {};\n const parentApp = parentConfig.app as Record<string, Record<string, unknown>>;\n\n if (has(\"host\") && parentApp.host) {\n app.host = { ...parentApp.host };\n stripProductionFields(app.host as Record<string, unknown>);\n }\n\n if (has(\"ui\") && parentApp.ui) {\n app.ui = { ...parentApp.ui };\n stripProductionFields(app.ui as Record<string, unknown>);\n }\n\n if (has(\"api\") && parentApp.api) {\n app.api = { ...parentApp.api };\n stripProductionFields(app.api as Record<string, unknown>);\n }\n\n if (Object.keys(app).length > 0) {\n config.app = app;\n }\n }\n\n if (has(\"plugins\") && opts.plugins && opts.plugins.length > 0 && parentConfig.plugins) {\n const plugins: Record<string, unknown> = {};\n for (const key of opts.plugins) {\n const parentPlugin = (parentConfig.plugins as Record<string, unknown>)?.[key];\n if (parentPlugin) {\n if (typeof parentPlugin === \"string\") {\n plugins[key] = { extends: parentPlugin };\n } else {\n const pluginCopy = { ...(parentPlugin as Record<string, unknown>) };\n stripProductionFields(pluginCopy);\n plugins[key] = pluginCopy;\n }\n }\n }\n config.plugins = plugins;\n } else if (has(\"plugins\")) {\n config.plugins = {};\n }\n\n await saveBosConfig(destination, config);\n\n const workspacePackages: string[] = [];\n for (const section of opts.overrides) {\n workspacePackages.push(...OVERRIDE_WORKSPACE_MAP[section]);\n }\n if (has(\"plugins\")) {\n workspacePackages.push(\"plugins/*\");\n }\n\n const catalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n })\n ).catalog;\n\n const pkg: Record<string, unknown> = {\n name: \"monorepo\",\n private: true,\n type: \"module\",\n scripts: buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n }),\n dependencies: {\n \"everything-dev\": \"catalog:\",\n \"every-plugin\": \"catalog:\",\n },\n devDependencies: {},\n workspaces: {\n packages: workspacePackages,\n catalog,\n },\n };\n writeFileSync(join(destination, \"package.json\"), `${JSON.stringify(pkg, null, 2)}\\n`);\n\n writeFileSync(join(destination, \".gitignore\"), generateGitignore());\n\n return 4;\n}\n\nasync function resolveWorkspaceRefs(\n destination: string,\n options?: { localOverrides?: boolean; sourceDir?: string },\n): Promise<void> {\n await normalizePackageManifestsInTree({\n sourceRootDir: options?.sourceDir ?? destination,\n targetDir: destination,\n resolveCatalogRefs: false,\n preserveCatalogRefs: true,\n removeWorkspaceDeps: [\"host\"],\n });\n}\n\nexport async function writeInitSnapshot(\n destination: string,\n extendsAccount: string,\n extendsGateway: string,\n sourceDir: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<void> {\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n const fileHashes: Record<string, string> = {};\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n const content = readFileSync(src);\n const destPath = sourcePathToDestinationPath(filePath);\n fileHashes[destPath] = computeHash(content);\n }\n\n await writeSnapshot(destination, {\n parentRef: `bos://${extendsAccount}/${extendsGateway}`,\n files: fileHashes,\n });\n}\n\nfunction computeHash(data: Uint8Array): string {\n return createHash(\"sha256\").update(data).digest(\"hex\").substring(0, 16);\n}\n\nfunction mkTmpDir(prefix: string): string {\n return mkdtempSync(join(tmpdir(), `${prefix}-`));\n}\n\nexport async function generateDatabaseMigrations(destination: string): Promise<void> {\n const drizzleConfigs = await glob(\"**/drizzle.config.ts\", {\n cwd: destination,\n nodir: true,\n dot: false,\n absolute: false,\n ignore: [\"**/node_modules/**\"],\n });\n\n for (const configPath of drizzleConfigs) {\n const workspaceDir = dirname(configPath);\n const pkgPath = join(destination, workspaceDir, \"package.json\");\n if (!existsSync(pkgPath)) continue;\n\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const scripts = pkg.scripts as Record<string, string> | undefined;\n if (!scripts?.[\"db:generate\"]) continue;\n\n const cwd = join(destination, workspaceDir);\n await execCommand(\"bun\", [\"run\", \"db:generate\"], cwd);\n }\n}\n\nconst COMMAND_TIMEOUTS: Record<string, number> = {\n bun: 5 * 60_000,\n docker: 5 * 60_000,\n node_modules: 2 * 60_000,\n tar: 60_000,\n};\n\nexport async function execCommand(\n command: string,\n args: string[],\n cwd?: string,\n options?: { stdio?: \"pipe\" | \"inherit\" },\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n await execa(command, args, { cwd, stdio: options?.stdio ?? \"pipe\", timeout });\n}\n\nexport function extractSkillsBlock(content: string): string {\n const match = content.match(/<!-- intent-skills:start -->[\\s\\S]*?<!-- intent-skills:end -->/);\n return match ? match[0] : \"\";\n}\n\nfunction buildChildAgentsInstructions(opts: {\n overrides: OverrideSection[];\n plugins?: string[];\n}): string {\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n const parts: string[] = [];\n\n parts.push(`# Agent Instructions\n\nThis document provides operational guidance for AI agents working in this everything.dev project.\n\n## Quick Reference\n\n**Start Development:**\n\\`\\`\\`bash\ncp .env.example .env # First time only\nbun install\nbun run dev\n\\`\\`\\`\n\n**Check Status:**\n\\`\\`\\`bash\nbos ps # List running processes\nbos status # Project health check\nbos info # Show configuration\n\\`\\`\\``);\n\n const archLines = [\n \"This is an everything.dev child project. Depending on your overrides, it may include:\",\n ];\n if (has(\"ui\"))\n archLines.push(\"- **UI** — React 19 + TanStack Router frontend, loaded via Module Federation\");\n if (has(\"api\")) archLines.push(\"- **API** — Hono.js + oRPC backend with Effect services\");\n if (has(\"host\"))\n archLines.push(\"- **Host** — Server-side runtime with Module Federation orchestration\");\n if (has(\"plugins\"))\n archLines.push(\"- **Plugins** — Self-contained business logic modules with oRPC contracts\");\n archLines.push(\n \"\",\n \"The parent runtime provides the shared framework; your project provides custom overrides.\",\n );\n parts.push(`## Architecture\\n\\n${archLines.join(\"\\n\")}`);\n\n parts.push(`## Development Workflow\n\n### Starting Development\n1. \\`cp .env.example .env\\` (first time)\n2. \\`bun install\\`\n3. \\`bun run dev\\``);\n\n parts.push(`### Debugging Issues\n\n**API not responding:**\n- Check \\`bos ps\\` to see if the API process is running\n- Check \\`.bos/logs/api.log\\` for errors\n\n**UI not loading:**\n- Verify the dev server is running: \\`bos ps\\`\n- Check browser console for Module Federation errors\n- Clear browser cache and retry\n\n**Type errors:**\n- Run \\`bun run typecheck\\``);\n\n const changeLines: string[] = [\"### Making Changes\"];\n if (has(\"ui\"))\n changeLines.push(\"- **UI Changes**: Edit `ui/src/` files → hot reload automatically\");\n if (has(\"api\"))\n changeLines.push(\"- **API Changes**: Edit `api/src/` files → hot reload automatically\");\n if (has(\"host\"))\n changeLines.push(\n \"- **Host Changes**: Edit `host/src/` when changing runtime resolution, auth wiring, SSR, proxying, or plugin mounting\",\n );\n changeLines.push(\n \"- **New Components**: Create in `ui/src/components/ui/`, export from `ui/src/components/index.ts`\",\n );\n changeLines.push(\n \"- **New Routes**: Create file in `ui/src/routes/`, TanStack Router auto-generates tree\",\n );\n parts.push(`## Code Changes\\n\\n${changeLines.join(\"\\n\")}`);\n\n parts.push(`### Style Requirements\n- Use semantic Tailwind classes: \\`bg-background\\`, \\`text-foreground\\`, \\`text-muted-foreground\\`\n- No hardcoded colors like \\`bg-blue-600\\`\n- No code comments in implementation\n- Component file naming: lowercase kebab-case (\\`data-table.tsx\\`, \\`user-profile.tsx\\`)\n- Follow existing patterns in neighboring files`);\n\n if (has(\"api\")) {\n parts.push(`### Adding API Endpoints\n1. Define in \\`api/src/contract.ts\\` — the oRPC route definitions and Zod schemas\n2. Implement in \\`api/src/index.ts\\` — the \\`createRouter\\` function\n3. Use in UI via \\`apiClient\\` from \\`useApiClient()\\` in \\`@/app\\``);\n }\n\n if (has(\"plugins\")) {\n parts.push(`### Plugin Architecture\n\nBusiness logic is organized into independent plugins loaded via Module Federation:\n- Each plugin has its own \\`contract.ts\\` — oRPC route definitions and Zod schemas\n- Each plugin has its own \\`index.ts\\` — \\`createPlugin\\` with variables, secrets, context, router\n- Each plugin has its own rspack config for independent deployment\n\nThe UI accesses plugin routes via namespaced clients: \\`apiClient.<plugin>.<method>()\\`.\n\n### Plugin Client (pluginsClient)\n\nThe API plugin receives typed client factories for all other plugins via \\`createPlugin.withPlugins<PluginsClient>()\\`, enabling in-process composition without HTTP roundtrips.\n\n### Generated Types\n\n\\`api/src/lib/plugins-types.gen.ts\\`, \\`api/src/lib/auth-types.gen.ts\\`, \\`ui/src/lib/api-types.gen.ts\\`, and \\`ui/src/lib/auth-types.gen.ts\\` are generated by \\`bos types gen\\` from \\`bos.config.json\\`. These files are gitignored and auto-regenerated on \\`bun install\\`, \\`typecheck\\`, \\`bos dev\\`, \\`bos build\\`, and bos plugin management commands.\n\nIf you hand-edit \\`bos.config.json\\`, run \\`bos types gen\\` or restart \\`bos dev\\` to regenerate.`);\n }\n\n const testCommands: string[] = [];\n if (has(\"api\") || has(\"host\") || has(\"ui\")) {\n testCommands.push(\"bun run test # Run all tests\");\n testCommands.push(\"bun typecheck # Type check all packages\");\n testCommands.push(\"bun lint # Run linting\");\n }\n if (testCommands.length > 0) {\n parts.push(`## Testing & Quality\n\n**Before committing:**\n\\`\\`\\`bash\n${testCommands.join(\"\\n\")}\n\\`\\`\\``);\n }\n\n parts.push(`## Common Patterns\n\n### Authentication Check\n\nRoutes requiring auth use \\`_authenticated.tsx\\` layout:\n\\`\\`\\`typescript\nexport const Route = createFileRoute('/_layout/_authenticated')({\n beforeLoad: async ({ location }) => {\n const { data: session } = await authClient.getSession();\n if (!session?.user) {\n throw redirect({ to: '/login', search: { redirect: location.pathname } });\n }\n },\n});\n\\`\\`\\``);\n\n if (has(\"ui\")) {\n parts.push(`### API Client Usage\n\\`\\`\\`typescript\nimport { useApiClient } from \"@/app\";\n\nfunction MyComponent() {\n const apiClient = useApiClient();\n const { data } = await apiClient.ping();\n}\n\\`\\`\\``);\n }\n\n parts.push(`## Troubleshooting\n\n**Process won't start:**\n\\`\\`\\`bash\nbos kill # Kill all tracked processes\nbun install # Ensure dependencies\nbun run dev # Restart\n\\`\\`\\`\n\n**Module Federation errors:**\n- Check \\`bos.config.json\\` URLs are accessible\n- Verify shared dependency versions match in package.json\n- Clear browser cache\n\n**Database issues:**\n\\`\\`\\`bash\nbun run db:push # Push schema changes\nbun run db:studio # Open Drizzle Studio\n\\`\\`\\`\n\n## Environment\n\n**Required files:**\n- \\`.env\\` — Secrets (see \\`.env.example\\`)\n- \\`bos.config.json\\` — Runtime configuration (committed)`);\n\n return `${parts.join(\"\\n\\n\")}\\n`;\n}\n\nexport function buildChildAgentsMd(\n skillsBlock: string,\n opts: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): string {\n return `${skillsBlock}\\n\\n${buildChildAgentsInstructions(opts)}`;\n}\n\nexport async function personalizeAgentsMd(\n destination: string,\n opts: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<void> {\n const agentsMdPath = join(destination, \"AGENTS.md\");\n if (!existsSync(agentsMdPath)) return;\n\n const content = readFileSync(agentsMdPath, \"utf-8\");\n const skillsBlock = extractSkillsBlock(content);\n if (!skillsBlock) return;\n\n const childContent = buildChildAgentsMd(skillsBlock, opts);\n writeFileSync(agentsMdPath, childContent);\n}\n\nfunction generateGitignore(): string {\n return `node_modules/\ndist/\n.env\n.bos/\ndocker-compose.yml\n*.gen.ts\n*.gen.tsx\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAMA,yFAAwC;AAE9C,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,yBAA4D;CAChE,IAAI,CAAC,KAAK;CACV,KAAK,CAAC,MAAM;CACZ,MAAM,CAAC,OAAO;CACd,SAAS,EAAE;CACZ;AAcD,SAAS,cAAc,QAAqD;AAC1E,KAAI,OAAO,OAAO,YAAY,SAC5B,QAAO,OAAO;AAGhB,KAAI,OAAO,WAAW,OAAO,OAAO,YAAY,SAC9C,QAAOC,gCAAkB,OAAO,SAAmC,aAAa;;AAMpF,SAAS,YAAY,KAA0D;CAC7E,MAAM,QAAQ,IAAI,MAAM,0BAA0B;AAClD,KAAI,CAAC,QAAQ,MAAM,CAAC,MAAM,GAAI,QAAO;AACrC,QAAO;EAAE,SAAS,MAAM;EAAI,SAAS,MAAM;EAAI;;AAGjD,SAAS,qBAAqB,WAA2C;CACvE,MAAM,8BAAe,WAAW,eAAe;AAC/C,KAAI,yBAAY,QAAQ,CACtB,QAAO,EAAE;AAIX,QAAO,EAAE,GADG,aAAoE,QAChE,CAAC,YAAY,WAAW,EAAE,EAAG;;AAG/C,eAAsB,0BAA0B,MAIhB;CAC9B,MAAM,WAAqC,EAAE;CAC7C,MAAM,WAAuC,EAAE;CAC/C,MAAM,eAAyB,EAAE;CACjC,MAAM,0BAAU,IAAI,KAAa;CACjC,IAAI;CACJ,IAAI,aAAa,SAAS,KAAK,eAAe,GAAG,KAAK;CACtD,IAAI,YAAY,KAAK,mCAAoB,KAAK,UAAU,GAAG;CAC3D,IAAI,aAAa,gCAAiB,WAAW,kBAAkB,GAAG;