/** * Stitch stage (docs/architecture.md#4-stitch): the deterministic patch set that * turns N independent scaffolds into one coherent bun workspace. Every operation * is idempotent — re-running a stitch over its own output is safe. * * Failures throw EXIT.STITCH and leave the tree in place for inspection. */ import { existsSync } from "node:fs"; import { appendFile, readFile, rm, writeFile } from "node:fs/promises"; import { basename, join } from "node:path"; import { apiPortSource } from "../adapters/elysia.ts"; import { ADAPTERS } from "../adapters/index.ts"; import { writeFileAtomic } from "../core/fs/atomic.ts"; import { resolveInProject } from "../core/fs/paths.ts"; import { backendEnvLines } from "./env-names.ts"; import { EXIT, GrootError } from "./errors.ts"; import { stitchLock } from "./locks.ts"; import { findChoice } from "./matrix.ts"; import { planToManifest } from "./plan.ts"; import type { FrameworkId, Plan } from "./types.ts"; /** Lockfiles a generator may have left inside its scaffold directory. */ const NESTED_LOCKFILES = [ "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", ]; async function readJson(path: string): Promise> { try { return JSON.parse(await readFile(path, "utf8")) as Record; } catch (error) { throw new GrootError( `Stitch failed: could not parse ${path} (${error instanceof Error ? error.message : String(error)})`, EXIT.STITCH, ); } } async function writeJson(path: string, value: Record): Promise { await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, "utf8"); } /** Root package.json: workspace name, private, workspace globs. */ export async function stitchRootIdentity(plan: Plan): Promise { const path = join(plan.targetDir, "package.json"); const pkg = await readJson(path); pkg.name = plan.name; pkg.private = true; const workspaces = Array.isArray(pkg.workspaces) ? (pkg.workspaces as string[]) : []; for (const glob of ["apps/*", "packages/*"]) { if (!workspaces.includes(glob)) workspaces.push(glob); } pkg.workspaces = workspaces; await writeJson(path, pkg); return `root package.json → name "${plan.name}", workspaces [${workspaces.join(", ")}]`; } /** * Apps get bare names from their directory basename ("web", "mobile", "api") — * generators disagree wildly (sv uses the full path argument, which isn't even a * valid package name). The backend keeps its @repo/* name from its adapter. */ export async function stitchAppNames(plan: Plan): Promise { const notes: string[] = []; for (const scaffold of plan.scaffolds) { if (!scaffold.path.startsWith("apps/")) continue; const path = join(plan.targetDir, scaffold.path, "package.json"); if (!existsSync(path)) continue; const pkg = await readJson(path); const name = basename(scaffold.path); if (pkg.name !== name) { pkg.name = name; pkg.private = true; await writeJson(path, pkg); notes.push(`${scaffold.path}/package.json → name "${name}"`); } } return notes; } /** Exactly one lockfile per workspace: the root one (written by verify's install). */ export async function stitchLockfileHygiene(plan: Plan): Promise { const notes: string[] = []; for (const scaffold of plan.scaffolds) { for (const lockfile of NESTED_LOCKFILES) { const path = join(plan.targetDir, scaffold.path, lockfile); if (existsSync(path)) { await rm(path, { force: true }); notes.push(`removed nested ${scaffold.path}/${lockfile}`); } } } return notes; } /** * Hono's bun template exports the app directly, which Bun serves on port 3000 — * colliding with Next.js. Rewrite each hono scaffold to read PORT (how verify * runs it on an ephemeral port), defaulting to its assigned port — * `groot add --path` can grow a second one. (Elysia's port is written correctly * at generation time; Next/Vite/Metro keep their defaults.) */ export async function stitchHonoPort(plan: Plan): Promise { const notes: string[] = []; for (const hono of plan.scaffolds) { if (hono.framework !== "hono" || hono.port === null) continue; const path = join(plan.targetDir, hono.path, "src/index.ts"); if (!existsSync(path)) continue; const source = await readFile(path, "utf8"); const marker = "export default app"; if (!source.includes(marker)) { // Upstream template changed shape — or a previous stitch already rewrote // this file. Leave it alone rather than corrupting it. notes.push( `${hono.path}/src/index.ts: default-export marker not found; port rewrite skipped`, ); continue; } const rewritten = source.replace( marker, `export default {\n port: ${apiPortSource(hono.port)},\n fetch: app.fetch,\n}`, ); await writeFile(path, rewritten, "utf8"); notes.push(`${hono.path}/src/index.ts → dev port ${hono.port}`); } return notes; } /** Dev CLIs whose `-p` short flag is also the port flag (docs/scaffold-flows.md#dev-port-flags). */ const SHORT_PORT_FLAG: ReadonlySet = new Set(["next", "nuxt"]); /** The port flag in a dev script (`--port ` / `--port=`, and `-p` where documented); group 1 is the port. */ function devPortFlag(framework: FrameworkId): RegExp { const short = SHORT_PORT_FLAG.has(framework) ? String.raw`|(?<=^|\s)-p` : ""; return new RegExp(String.raw`(?:--port${short})(?:=|\s+)(\d+)(?!\d)`); } /** A stitch write target inside the workspace — a path or link leading out of it is a stitch failure. */ function stitchTarget(plan: Plan, relPath: string): string { try { return resolveInProject(plan.targetDir, relPath); } catch (error) { throw new GrootError( `Stitch failed: ${error instanceof Error ? error.message : String(error)}`, EXIT.STITCH, error instanceof GrootError ? error.hint : undefined, ); } } /** * Apply allocated dev ports (docs/architecture.md#port-allocation): in a v2 * workspace, a web scaffold whose port differs from its framework's default — * `groot add` moved it off a claimed port — gets `--port ` in its `dev` * script, replacing the script's own port flag unless that already names the * port. Scaffolds on their default port are left byte-identical, so init * output is unchanged; v1 workspaces keep the v1 rule (warn, never rewrite). * Source-assigned ports (Elysia/Hono/Fastify) are written by their own steps. * A scaffold path or link leading out of the workspace is never written through. */ export async function stitchDevPorts(plan: Plan): Promise { if ((plan.manifestVersion ?? 2) !== 2) return []; const notes: string[] = []; for (const scaffold of plan.scaffolds) { if (scaffold.port === null) continue; if (ADAPTERS[scaffold.framework].portAssignment !== "dev-script") continue; if (scaffold.port === findChoice(scaffold.slot, scaffold.framework)?.port) continue; const path = stitchTarget(plan, `${scaffold.path}/package.json`); if (!existsSync(path)) continue; const pkg = await readJson(path); const scripts = (pkg.scripts ?? {}) as Record; const dev = scripts.dev; if (dev === undefined) { notes.push( `${scaffold.path}/package.json: no dev script — dev port ${scaffold.port} not applied`, ); continue; } const flag = devPortFlag(scaffold.framework); const current = flag.exec(dev); if (current !== null && Number(current[1]) === scaffold.port) continue; // already applied const desired = current === null ? `${dev} --port ${scaffold.port}` : dev.replace(flag, `--port ${scaffold.port}`); const next = { ...pkg, scripts: { ...scripts, dev: desired } }; writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\n`); notes.push(`${scaffold.path}/package.json → dev script serves on :${scaffold.port}`); } return notes; } /** * fastify-cli's TypeScript template drives everything through its Node-centric * `fastify start` wrapper and package-manager-invoking script chains * (`npm run build:ts && …` — upstream's wording, not groot's) — neither belongs * in a bun-first workspace. Rewrite each fastify scaffold's scripts wholesale * to run groot's src/server.ts overlay under bun (dev/start), build with tsc * (the template tsconfig already emits dist/, which turbo caches), typecheck, * and test with bun's runner (its node:test shim runs the template's suite — * verified on bun 1.3.14). The rewrite is marker-gated on the template's own * dev script: an already-stitched scaffold is a silent no-op (re-stitches via * `groot add` stay idempotent), and a hand-rolled script set is never * clobbered — it gets a note instead, like the hono port rewrite. * devDependencies are left untouched: ts-node/c8/concurrently go unused under * bun, but removing them would couple groot to the template's internals. */ export async function stitchFastifyScripts(plan: Plan): Promise { const notes: string[] = []; for (const fastify of plan.scaffolds) { if (fastify.framework !== "fastify") continue; const path = join(plan.targetDir, fastify.path, "package.json"); if (!existsSync(path)) continue; const pkg = await readJson(path); const scripts = (pkg.scripts ?? {}) as Record; const desired: Record = { dev: "bun --watch src/server.ts", start: "NODE_ENV=production bun src/server.ts", build: "tsc", test: "bun test", typecheck: "tsc --noEmit", }; if (scripts.dev === desired.dev) continue; // already stitched if (!(scripts.dev ?? "").includes("fastify start")) { // Upstream template changed shape — or the user replaced the scripts. // Leave them alone rather than clobbering intent. notes.push( `${fastify.path}/package.json: template dev script not found; bun rewrite skipped`, ); continue; } pkg.scripts = desired; await writeJson(path, pkg); notes.push(`${fastify.path}/package.json → bun-native scripts (dev: ${desired.dev})`); } return notes; } /** * Bare React Native's metro only watches and resolves inside the app * directory — in a bun workspace that breaks at runtime ("Unable to resolve * module …") because dependencies hoist to the root node_modules and shared * packages live outside the app. Rewrite the template's empty config object * (`const config = {};` — verified in @react-native-community/template * 0.86.0) into the standard monorepo wiring: watch the workspace root, * resolve from both the app's and the root's node_modules. Expo needs none * of this (auto-configured since SDK 52 — see adapters/expo.ts). * * Same triple-state contract as the other template patches: already-stitched * scaffolds are silent no-ops, an unrecognized shape gets a note instead of a * clobber. */ export async function stitchMetroMonorepo(plan: Plan): Promise { const notes: string[] = []; for (const scaffold of plan.scaffolds) { if (scaffold.framework !== "react-native") continue; const path = join(plan.targetDir, scaffold.path, "metro.config.js"); if (!existsSync(path)) continue; const source = await readFile(path, "utf8"); if (source.includes("groot: monorepo wiring")) continue; // already stitched const marker = "const config = {};"; if (!source.includes(marker)) { // Upstream template changed shape — or the user replaced the config. notes.push( `${scaffold.path}/metro.config.js: template marker not found; monorepo wiring skipped`, ); continue; } // apps/mobile → "../.." — climb the scaffold path back to the workspace root. const toRoot = scaffold.path .split("/") .map(() => "..") .join("/"); const wiring = `const path = require('path'); // groot: monorepo wiring — metro must watch the workspace root and resolve // modules from both the app's and the workspace's node_modules (bun hoists). const workspaceRoot = path.resolve(__dirname, '${toRoot}'); const config = { watchFolders: [workspaceRoot], resolver: { nodeModulesPaths: [ path.resolve(__dirname, 'node_modules'), path.resolve(workspaceRoot, 'node_modules'), ], }, };`; await writeFile(path, source.replace(marker, wiring), "utf8"); notes.push(`${scaffold.path}/metro.config.js → workspace watchFolders + module resolution`); } return notes; } /** * `supabase init` derives config.toml's project_id from its cwd's basename — * "backend" for every groot workspace, but the field exists to "distinguish * different Supabase projects on the same host" (their words: Docker * containers are named after it), so two groot workspaces would collide. * Rewrite it to the workspace name. Triple-state like the other template * patches: already-stitched → silent, unexpected shape → note, never a * clobber. Anchored on the exact default line — the substring rule. */ export async function stitchSupabaseProjectId(plan: Plan): Promise { const notes: string[] = []; for (const scaffold of plan.scaffolds) { if (scaffold.framework !== "supabase") continue; const path = join(plan.targetDir, scaffold.path, "supabase/config.toml"); if (!existsSync(path)) continue; // Docker-safe subset of the workspace name (project_id names containers). const projectId = plan.name.replace(/[^A-Za-z0-9_-]/g, "-"); const source = await readFile(path, "utf8"); const stitched = new RegExp(`^project_id = "${projectId}"$`, "m"); if (stitched.test(source)) continue; // already stitched const defaultLine = new RegExp(`^project_id = "${basename(scaffold.path)}"$`, "m"); if (!defaultLine.test(source)) { // Upstream default changed shape — or the user renamed it. Leave it. notes.push( `${scaffold.path}/supabase/config.toml: default project_id not found; rename skipped`, ); continue; } await writeFile(path, source.replace(defaultLine, `project_id = "${projectId}"`), "utf8"); notes.push(`${scaffold.path}/supabase/config.toml → project_id "${projectId}"`); } return notes; } /** The one-line provenance header written when `.env.example` is first created. */ const ENV_EXAMPLE_HEADER_BY_BACKEND: Partial> = { convex: "# Convex deployment URL — written to packages/backend/.env.local by `bun run setup`.\n", supabase: "# Supabase API URL + anon key — `bun run dev` in the backend package (supabase start) prints the local values.\n", }; /** * Wire frontends to the workspace backend: workspace dependency + env * placeholders named for what each backend's clients read (docs/architecture.md * — Convex is consumed via deep imports of convex/_generated, Supabase via the * generated Database types). */ export async function stitchBackendLinks(plan: Plan): Promise { const backend = plan.scaffolds.find((s) => s.slot === "backend"); if (backend === undefined) return []; const backendName = `${plan.conventions.packagesNamespace}/backend`; const notes: string[] = []; const envLines: string[] = []; for (const scaffold of plan.scaffolds) { if (scaffold.slot !== "web" && scaffold.slot !== "mobile") continue; const path = join(plan.targetDir, scaffold.path, "package.json"); if (!existsSync(path)) continue; const pkg = await readJson(path); const deps = (pkg.dependencies ?? {}) as Record; if (deps[backendName] !== "workspace:*") { deps[backendName] = "workspace:*"; pkg.dependencies = deps; await writeJson(path, pkg); notes.push(`${scaffold.path} → depends on ${backendName} (workspace:*)`); } envLines.push(...backendEnvLines(backend.framework, scaffold)); } if (envLines.length > 0) { const envPath = join(plan.targetDir, ".env.example"); const header = ENV_EXAMPLE_HEADER_BY_BACKEND[backend.framework] ?? "# Backend connection placeholders written by groot.\n"; const existing = existsSync(envPath) ? await readFile(envPath, "utf8") : ""; // Exact-line membership: a substring test would let NEXT_PUBLIC_CONVEX_URL= // swallow SvelteKit's PUBLIC_CONVEX_URL= in mixed-web workspaces. The Set // over envLines also collapses duplicates when two scaffolds of the same // framework coexist (add --path). const existingLines = new Set(existing.split("\n").map((line) => line.trim())); const missing = [...new Set(envLines)].filter((line) => !existingLines.has(line)); if (missing.length > 0) { await appendFile(envPath, `${existing.length > 0 ? "\n" : header}${missing.join("\n")}\n`); notes.push(`.env.example → ${missing.join(", ")}`); } } return notes; } /** Build outputs per selected framework so turbo caching works out of the box. */ export async function stitchTurboOutputs(plan: Plan): Promise { const path = join(plan.targetDir, "turbo.json"); if (!existsSync(path)) return null; const turbo = await readJson(path); const tasks = (turbo.tasks ?? {}) as Record>; const build = tasks.build ?? { dependsOn: ["^build"] }; const outputs = new Set(Array.isArray(build.outputs) ? (build.outputs as string[]) : []); const frameworks = new Set(plan.scaffolds.map((s) => s.framework)); if (frameworks.has("next")) { outputs.add(".next/**"); outputs.add("!.next/cache/**"); } if (frameworks.has("sveltekit")) outputs.add(".svelte-kit/**"); // Tauri's `build` is the Vite frontend build (dist/); the Rust build lives in // src-tauri/target (cargo-managed, never a turbo output). TanStack Start's // 1.x template is plain `vite build` → dist/ (no Nitro .output). Fastify's // stitched `build: tsc` emits dist/ per the template tsconfig's outDir. if ( frameworks.has("elysia") || frameworks.has("hono") || frameworks.has("fastify") || frameworks.has("tauri") || frameworks.has("tanstack-start") || frameworks.has("astro") || frameworks.has("vite") ) { outputs.add("dist/**"); } // nuxt build → .output/ (Nitro). if (frameworks.has("nuxt")) outputs.add(".output/**"); // electron-vite builds main/preload/renderer into out/. if (frameworks.has("electron")) outputs.add("out/**"); // react-router build → build/ (client + server). if (frameworks.has("react-router")) outputs.add("build/**"); build.outputs = [...outputs]; tasks.build = build; turbo.tasks = tasks; await writeJson(path, turbo); return `turbo.json → build.outputs [${[...outputs].join(", ")}]`; } /** * Bun runs dependency lifecycle scripts only for trusted packages, and * electron's runtime download is a postinstall script that is NOT on bun's * default-trusted list (verified empirically: the flagship E2E's real * `bun install` left node_modules/electron/dist missing until this landed). * Workspaces with an electron scaffold get it added to the root * trustedDependencies so the verify-stage install produces a runnable app. * * Note: bun treats an explicit trustedDependencies as replacing its default * allowlist — a deliberate tradeoff here. Packages a user later adds that need * their own postinstalls belong in this same array; doctor's electron-binary * check points at `bun pm trust` for exactly that discovery flow. */ export async function stitchTrustedDependencies(plan: Plan): Promise { if (!plan.scaffolds.some((scaffold) => scaffold.framework === "electron")) return null; const path = join(plan.targetDir, "package.json"); const pkg = await readJson(path); const trusted = new Set( Array.isArray(pkg.trustedDependencies) ? (pkg.trustedDependencies as string[]) : [], ); if (trusted.has("electron")) return null; trusted.add("electron"); pkg.trustedDependencies = [...trusted]; await writeJson(path, pkg); return "root package.json → trustedDependencies [electron] (bun runs its postinstall)"; } /** Root .gitignore must cover the workspace basics regardless of what the trunk shipped. */ export async function stitchRootGitignore(plan: Plan): Promise { const path = join(plan.targetDir, ".gitignore"); const required = ["node_modules", ".turbo", ".env", ".env.*", "!.env.example"]; const existing = existsSync(path) ? await readFile(path, "utf8") : ""; const lines = new Set(existing.split("\n").map((line) => line.trim())); const missing = required.filter((entry) => !lines.has(entry) && !lines.has(`${entry}/`)); if (missing.length === 0) return null; await appendFile( path, `${existing.endsWith("\n") || existing === "" ? "" : "\n"}\n# groot\n${missing.join("\n")}\n`, ); return `.gitignore → added ${missing.join(", ")}`; } /** groot.json — the manifest add/doctor consume (docs/cli-spec.md#grootjson-manifest). */ export async function stitchManifest(plan: Plan): Promise { const path = join(plan.targetDir, "groot.json"); await writeFile(path, `${JSON.stringify(planToManifest(plan), null, 2)}\n`, "utf8"); return "groot.json written"; } export interface StitchOptions { /** Progress callback — receives a human label as each operation lands. */ readonly onStep?: (label: string) => void; } /** Run every stitch operation in order. Returns the applied-operation notes. */ export async function stitch(plan: Plan, options: StitchOptions = {}): Promise { const report = options.onStep ?? (() => {}); report("Stitching workspace"); const notes: string[] = []; const push = (note: string | string[] | null): void => { if (note === null) return; if (Array.isArray(note)) notes.push(...note); else notes.push(note); }; push(await stitchAppNames(plan)); push(await stitchLockfileHygiene(plan)); push(await stitchHonoPort(plan)); push(await stitchDevPorts(plan)); push(await stitchFastifyScripts(plan)); push(await stitchMetroMonorepo(plan)); push(await stitchSupabaseProjectId(plan)); push(await stitchBackendLinks(plan)); push(await stitchTurboOutputs(plan)); push(await stitchRootIdentity(plan)); push(await stitchTrustedDependencies(plan)); push(await stitchRootGitignore(plan)); push(await stitchManifest(plan)); push(stitchLock(plan)); return notes; } export { backendEnvLines } from "./env-names.ts";