import fs from "fs"; import os from "os"; import path from "path"; import zlib from "zlib"; import type { BuildTarget, PublishArtifact } from "@valbuild/tanstack-build"; import type { VendorLayer } from "@valbuild/tanstack-build/node"; import { typecheckInstalled, type InstalledTypecheck, } from "@valbuild/shared/typecheck/node"; /** * `val publish`'s build: the site, built from the checkout, as the artifacts * the publish API takes (valbuild/home, docs/app-mode.md, "Briefing: * val-publish" and "Flow B"). * * The same builder the Studio runs in a tab -- `@valbuild/tanstack-build` -- * plus the half a tab cannot run: the project's dependency layer, built from * its own `node_modules` (`@valbuild/tanstack-build/node`). So a CI checkout * and a Studio build of the same content produce the same site, and the layer * is the one thing only this side can make. * * Against content's build target, never the loader's: content is the only * address a publisher has, and it answers what the platform expects. * * Written to a directory, and then published by the upload path `val publish * --artifacts` has always had: one path for bytes to leave by, whoever built * them. */ /** What `val publish` hands on to the upload. */ export type BuiltArtifacts = | { status: "built"; /** A directory of artifacts, laid out as `--artifacts` reads them. */ dir: string; buildHash: string; linksOwnCss: boolean; /** * The layer by name, when content already holds it and it was not * written; `null` when the project declares nothing beyond the base set. * `undefined` when the layer artifact is in `dir`, which names it. */ layerRev?: string | null; /** The base layer this was built against: the build target's `base.rev`. */ baseRev: string; warnings: string[]; /** The project's typecheck, made on the install the layer was built from. */ typecheck: BuildTypecheck; } | { status: "error"; message: string }; /** `off` when the build was asked not to typecheck (`--no-typecheck`). */ export type BuildTypecheck = InstalledTypecheck | { status: "off" }; type TanstackBuild = typeof import("@valbuild/tanstack-build"); type TanstackBuildNode = typeof import("@valbuild/tanstack-build/node"); /** * The builder, loaded only when a build is asked for: it brings rolldown's * native binary with it, and `val validate` has no use for one. */ async function loadBuilder(): Promise< | { status: "ok"; build: TanstackBuild; node: TanstackBuildNode } | { status: "error"; message: string } > { try { const [build, node] = await Promise.all([ import("@valbuild/tanstack-build"), import("@valbuild/tanstack-build/node"), ]); /* * Native rolldown rather than its WebAssembly build, whose glue the site's * lockfile picks and can break (`rolldown.ts` in tanstack-build). Asked * for, because the project's own tanstack-build may predate the choice. */ if ("useRolldown" in build && "nativeRolldown" in node) { build.useRolldown(node.nativeRolldown); } return { status: "ok", build, node }; } catch (e) { return { status: "error", message: "`val publish` builds the site with @valbuild/tanstack-build and rolldown, and " + `they could not be loaded: ${e instanceof Error ? e.message : String(e)}\n\n` + "Install them in the project:\n\n" + " npm install --save-dev @valbuild/tanstack-build rolldown @tanstack/router-generator @tanstack/router-plugin\n\n" + "or publish a build made elsewhere with --artifacts .", }; } } /** * Whether `val publish` could build here: the builder loaded as a publish * loads it, and its bundler made to parse and bundle a module. Nothing is * read from the project and nothing is asked of content. * * What Val Build runs on an upgrade's install before a connected project * may publish it, since the project's CI is what builds a connected publish: * an upgrade that resolved a bundler which cannot load would otherwise land * on the branch and fail every build after it (architecture/quirks.md, * 2026-10-26). */ export async function checkBuildTools(): Promise< { status: "ok" } | { status: "error"; message: string } > { const loaded = await loadBuilder(); if (loaded.status === "error") return loaded; try { // A builder older than `loadRolldown` loaded its bundler on import. if (!("loadRolldown" in loaded.build)) return { status: "ok" }; const { build, parseAstAsync } = await loaded.build.loadRolldown(); await parseAstAsync("export const checked = true;"); const ENTRY = "\0val-check-build-tools"; await build({ input: ENTRY, cwd: "/", write: false, plugins: [ { name: "val-check-build-tools", resolveId: (id) => (id === ENTRY ? id : null), load: (id) => (id === ENTRY ? "export default 1;" : null), }, ], }); return { status: "ok" }; } catch (e) { return { status: "error", message: `rolldown loaded, and could not build: ${e instanceof Error ? e.message : String(e)}`, }; } } /** * The `@valbuild/ui` this checkout runs: the one its `@valbuild/tanstack` * resolves, which is a transitive dependency pnpm does not hoist -- so it is * looked for FROM that package, and only then from the project itself. `null` * when neither has one installed. * * Handed to `wireUp`, which declares `@valbuild/ui` for a project that does * not and can only see source files. */ export function installedStudioVersion(root: string): string | null { const tanstack = installedPackageDir(root, "@valbuild/tanstack"); const ui = (tanstack ? installedPackageDir(tanstack, "@valbuild/ui") : null) ?? installedPackageDir(root, "@valbuild/ui"); if (ui === null) return null; try { const manifest: unknown = JSON.parse( fs.readFileSync(path.join(ui, "package.json"), "utf8"), ); return typeof manifest === "object" && manifest !== null && "version" in manifest && typeof manifest.version === "string" ? manifest.version : null; } catch { return null; } } /** * Where `name` is installed as Node would find it from `from`: in the nearest * `node_modules` upward, through pnpm's symlinks. Walked by hand rather than * with `require.resolve`, which a test runner replaces with its own resolver. */ function installedPackageDir(from: string, name: string): string | null { let dir = path.resolve(from); for (;;) { const candidate = path.join(dir, "node_modules", name); if (fs.existsSync(path.join(candidate, "package.json"))) { return fs.realpathSync(candidate); } const parent = path.dirname(dir); if (parent === dir) return null; dir = parent; } } /** * Never the project's own files, at any depth: installed packages. Dot * directories (`.git`, `.tanstack`, `.val`, `.output`) are tooling too. */ const IGNORED_DIRS = new Set(["node_modules"]); /** * Build output, at the project's root only: `src/routes/build/` is a route * called "build", not a previous build. */ const ROOT_OUTPUT_DIRS = new Set(["dist", "build"]); /** Lockfiles are JSON, and nothing imports them. */ const ROOT_LOCKFILES = new Set(["package-lock.json"]); const CODE_FILE = /\.(tsx?|jsx?|mjs|cjs|css)$/; /** * JSON is the project's too: `tsconfig.json` and `tsr.config.json` are read * by the build, a `.val.json` holds a `.jsonValues()` entry no import points * at, and a module may import one -- the starter's `val.server.ts` imports * `.prettierrc.json`, which is also why a dot FILE is read. */ const JSON_FILE = /\.json$/; /** * The project's source as it is STORED, which is what the Studio builds from: * every file this build read, less the stylesheets. * * This build compiles them, because it can run what a stylesheet asks for -- a * Tailwind `@plugin` is a module resolved and executed from `node_modules`. A * build in the browser cannot, and refuses the stylesheet rather than ship a * page that is quietly unstyled; the starter's `src/styles.css` has * `@plugin "@tailwindcss/typography"`. So a stored stylesheet made every * Studio publish after the first one fail. Without it, the Studio's build has * no CSS of its own and ships the live site's (`liveStylesheet` in the * Studio), which is right: a Studio save changes content and uploaded files, * never a stylesheet. It is also what the platform's own publish has always * stored. */ export function withoutStylesheets( sources: Record, ): Record { return Object.fromEntries( Object.entries(sources).filter(([key]) => !key.endsWith(".css")), ); } /** * The project's own files: its source as text, and the binaries it imports * (an image, a font) base64, as `BuildInput.assets` takes them. `public/` is * neither: it is served as is, and read by `readPublicFiles`. */ export function readProjectFiles( root: string, isAsset: (path: string) => boolean, ): { sources: Record; assets: Record } { const sources: Record = {}; const assets: Record = {}; const walk = (dir: string) => { let entries: fs.Dirent[]; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } for (const entry of entries) { const full = path.join(dir, entry.name); if (entry.isDirectory()) { if (entry.name.startsWith(".") || IGNORED_DIRS.has(entry.name)) continue; if (dir === root && ROOT_OUTPUT_DIRS.has(entry.name)) continue; if (dir === root && entry.name === "public") continue; walk(full); continue; } const key = path.relative(root, full).split(path.sep).join("/"); if (CODE_FILE.test(entry.name)) { sources[key] = fs.readFileSync(full, "utf8"); } else if (JSON_FILE.test(entry.name)) { if (!ROOT_LOCKFILES.has(key)) { sources[key] = fs.readFileSync(full, "utf8"); } } else if (isAsset(key)) { assets[key] = fs.readFileSync(full).toString("base64"); } } }; walk(root); return { sources, assets }; } /** Files under `public/`, base64, keyed `public/` as the build takes them. */ export function readPublicFiles(root: string): Record { const out: Record = {}; const base = path.join(root, "public"); const walk = (dir: string) => { let entries: fs.Dirent[]; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } for (const entry of entries) { const full = path.join(dir, entry.name); if (entry.isDirectory()) walk(full); else { const key = path.relative(root, full).split(path.sep).join("/"); out[key] = fs.readFileSync(full).toString("base64"); } } }; walk(base); return out; } /** The project's build-time variables: `PUBLIC_*` reach the browser, by the builder's rule. */ function publicEnv(env: NodeJS.ProcessEnv): Record { const out: Record = {}; for (const [key, value] of Object.entries(env)) { if (key.startsWith("PUBLIC_") && value !== undefined) out[key] = value; } return out; } /** * The target, with this project's layer as built here rather than as content * last stored it: a build has to link against the layer it ships with. */ export function targetWithLayer( target: BuildTarget, layer: VendorLayer | null, ): BuildTarget { return { ...target, project: { ...target.project, rev: layer?.rev ?? null, modules: layer?.modules ?? {}, css: layer?.css ?? {}, workerOnly: layer?.workerOnly ?? [], }, }; } function writeArtifact(dir: string, key: string, body: string | Buffer) { const file = path.join(dir, ...key.split("/")); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, body); } export async function buildArtifacts(options: { root: string; target: BuildTarget; /** The project, as the platform names it; only for the wiring's record. */ project: string; /** Content, which is the platform as far as this publisher knows. */ contentHost: string; /** The commit this checkout is at, and the branch it publishes. */ git: { commit: string; branch: string } | null; env?: NodeJS.ProcessEnv; log?: (line: string) => void; /** Where to write; a fresh temporary directory by default. */ outDir?: string; /** * Typecheck the project too, on the install the layer is built from, so * the declarations are read from disk rather than fetched again. Reported, * never refused on. On by default. */ typecheck?: boolean; }): Promise { const log = options.log ?? (() => {}); const loaded = await loadBuilder(); if (loaded.status === "error") return loaded; const { build: builder, node } = loaded; const { root, target } = options; const warnings: string[] = []; try { /* * Wired for the platform at publish time, as the Studio's builds are: the * wired `val.server.ts` reads its files from a module the BUILD emits, so * no checkout can carry it. `rebakeGit` would be the tab's spelling of the * same thing for a record that is already wired. */ const { sources: onDisk, assets } = readProjectFiles(root, builder.isAsset); const studioVersion = installedStudioVersion(root); const wiring = builder.isValProject(onDisk) && !builder.isWired(onDisk) ? builder.wireUp(onDisk, { project: options.project, loader: options.contentHost, ...(options.git ? { git: options.git } : {}), ...(studioVersion ? { studioVersion } : {}), }) : null; // Less the one about the layer, which is the thing this goes on to build. warnings.push( ...(wiring?.warnings ?? []).filter( (warning) => !warning.includes("dependency layer built for it"), ), ); const sources = wiring?.files ?? onDisk; const projectSource = withoutStylesheets(sources); // The dependency layer: from what the project imports, of what it declares. log("Building the dependency layer"); const manifest: { dependencies?: Record } = (() => { try { return JSON.parse(sources["package.json"] ?? "{}"); } catch { return {}; } })(); const deps = node.layerDepsOf(manifest, sources); // The files those stylesheets point at -- a font package's `.woff2`s -- // published with the site under the names their `url()`s now use. const dependencyAssets: Record = {}; const css = await node.collectDependencyCss( root, node.cssSpecifiersOf(sources), dependencyAssets, ); /* * There is no platform checkout here, so nothing can be PINNED to the * platform's copies and no built base layer can be read. What stands in * for both is what the platform says about its base set -- `base.pins`, * which refuses a layer carrying a pinned package at another version, and * `base.exports`, which the export audit reads. A platform that predates * them sends neither, and the layer builds unchecked, as it always did * here; that is worth a line in the log rather than silence. */ if (deps.length > 0 && !target.base.pins) { warnings.push( "The platform did not say which versions its base layer carries, so " + "this build could not check that the project's TanStack and React " + "agree with them.", ); } if (deps.length > 0 && !target.base.exports) { warnings.push( "The platform did not say what its base layer exports, so this build " + "could not check that the project's dependencies import only what it has.", ); } const layer = await node.buildVendorLayer(root, deps, css, { base: target.base, resolvePlatformModule: () => null, baseLayerDir: null, }); /* * What the layer left out, and why. A dependency the layer could not build * is dropped rather than fatal -- a Vite plugin nobody imports, say -- and * one the app DOES import then fails the site build naming only the * specifier. The reason is what says whether to fix the import or the * package: an export the base layer does not have, most of all, which is a * version disagreement with the platform rather than a missing package. */ for (const { specifier, reason } of layer?.skipped ?? []) { warnings.push(`${specifier} is not in the dependency layer: ${reason}`); } const fileBased = await node.isFileBased(root); const files = fileBased ? await node.generateRouteTree(root, sources) : sources; /* * The typecheck, while the install is here: the one `typecheckProject` the * Studio and the upgrade page run, reading the declarations this layer * was just built from instead of fetching them. Of the files this build * builds -- wired, and with the generated route tree a checkout may not * have -- since there is no site to compare with here, and an import of a * file only the build makes is not an error in the project. */ let typecheck: BuildTypecheck = { status: "off" }; if (options.typecheck !== false) { log("Typechecking"); typecheck = await typecheckInstalled({ root, files }); } log("Building the site"); /* * The project's copy of the splitter first, then the one beside this CLI * -- where a package manager puts an optional peer the project installed * but did not hoist. Neither is a build that does not split, which costs * size and not behaviour. */ const splitter = (await node.routeSplitter(root)) ?? (typeof __dirname === "string" ? await node.routeSplitter(__dirname) : null); if (splitter === null) { warnings.push( "Routes are not code-split: @tanstack/router-plugin is not installed.", ); } const built = await builder.buildUserApp({ files, target: targetWithLayer(target, layer), env: publicEnv(options.env ?? process.env), publicFiles: readPublicFiles(root), assets, dependencyAssets, // The project's own files, without the generated tree or the // stylesheets: what the next publish -- the Studio's included -- starts // from. See `withoutStylesheets`. projectSource, loadCssModule: node.cssModuleLoader(root), ...(splitter ? { routeSplitter: splitter } : {}), rsc: target.project.rsc, }); const artifacts: PublishArtifact[] = await builder.publishArtifacts(built, { projectSource, }); const dir = options.outDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "val-publish-")); for (const artifact of artifacts) { writeArtifact(dir, artifact.key, artifact.body); } /* * The layer: sent when content does not hold this one, named when it * does. The rev is a digest of the built chunks, so "content has this" is * a fact rather than a hope. */ let layerRev: string | null | undefined; if (layer === null) layerRev = null; else if (layer.rev === target.project.rev) layerRev = layer.rev; else writeArtifact(dir, "layer", zlib.gzipSync(JSON.stringify(layer))); return { status: "built", dir, buildHash: built.hash, linksOwnCss: built.linksOwnCss, ...(layerRev !== undefined ? { layerRev } : {}), baseRev: target.base.rev, warnings, typecheck, }; } catch (e) { return { status: "error", message: `The site could not be built: ${ e instanceof Error ? e.message.split("\n")[0] : String(e) }`, }; } } /** At most this many type errors are printed; the count says how many there were. */ const SHOWN_TYPE_ERRORS = 20; /** * What `val publish` prints of the typecheck. Type errors are warnings: a * project's own CI decides whether they stop it, and a publish that has run * this long is not the place to find out the build is blocked. */ export function typecheckReport(typecheck: BuildTypecheck): string[] { switch (typecheck.status) { case "off": return []; case "skipped": return [`Not typechecked: ${typecheck.reason}.`]; case "failed": return [ `warn: the project could not be typechecked: ${typecheck.message}`, ]; case "checked": { const { errors, missing } = typecheck.result; const lines: string[] = []; if (errors.length === 0) { lines.push("Typechecked: no type errors."); } else { lines.push( `warn: ${errors.length} type error${errors.length === 1 ? "" : "s"} (published anyway; --no-typecheck skips the check):`, ); for (const error of errors.slice(0, SHOWN_TYPE_ERRORS)) { const at = error.file === null ? error.tsconfig : `${error.file}${error.line !== null ? `:${error.line}:${error.column ?? 1}` : ""}`; lines.push( `warn: ${at} TS${error.code} ${error.message.split("\n")[0]}`, ); } if (errors.length > SHOWN_TYPE_ERRORS) { lines.push(`warn: and ${errors.length - SHOWN_TYPE_ERRORS} more`); } } if (missing.length > 0) { lines.push( `warn: the types of ${missing.length} package${missing.length === 1 ? " were" : "s were"} not installed, ` + `so errors about ${missing.length === 1 ? "it" : "them"} may be missing or wrong: ` + missing.map((pkg) => `${pkg.name}@${pkg.version}`).join(", "), ); } return lines; } } }