@incremental/turbopack 0.0.0-stage → 0.1.0

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/src/run.ts ADDED
@@ -0,0 +1,457 @@
1
+ #!/usr/bin/env node
2
+ // `incremental-turbopack run`: the Turbopack adapter loop (PLAN 10.4).
3
+ //
4
+ // B = store baseline
5
+ // ch = ChangeSet from B to the worktree (incremental-git)
6
+ // plan = affected(ch, context, declared apps)
7
+ // forget the apps whose package.json was deleted
8
+ // build each selected app with `next build --turbopack` and observe it
9
+ // advance to HEAD only if every selected app ran, the worktree is clean
10
+ // and HEAD did not move; otherwise exit 7 (ran, not advanced).
11
+ //
12
+ // Every observation is dirty: no module graph is recorded, so no run is
13
+ // complete (spec/adapters/turbopack.md, PLAN 11.1 rule 4). The engine
14
+ // therefore re-runs every app on each query until the graph capability exists.
15
+ //
16
+ // Exit codes: 0 ok and advanced; 1 a build failed (advanced when allowed);
17
+ // 2 usage error; 4 engine or setup error; 7 ran but not advanced.
18
+ import { spawnSync } from "node:child_process";
19
+ import { existsSync, readFileSync } from "node:fs";
20
+ import path from "node:path";
21
+ import { pathToFileURL } from "node:url";
22
+ import {
23
+ connect,
24
+ defaultEngine,
25
+ isIncrementalError,
26
+ repoRoot,
27
+ type Change,
28
+ type Context,
29
+ type Fallback,
30
+ type Input,
31
+ type Observation,
32
+ type Outcome,
33
+ type Plan,
34
+ } from "@incremental/client";
35
+ import {
36
+ allPackageJsons,
37
+ buildApp,
38
+ envHashes,
39
+ repoInputs,
40
+ discoverApps,
41
+ LOCKFILES,
42
+ nextPackage,
43
+ sha256,
44
+ type DeclaredInput,
45
+ } from "./project.js";
46
+
47
+ export interface RunOptions {
48
+ root: string;
49
+ store: string;
50
+ base?: string;
51
+ all: boolean;
52
+ // Timeout for one `next build`, in milliseconds.
53
+ timeoutMs: number;
54
+ }
55
+
56
+ export interface AppRun {
57
+ task: string;
58
+ outcome: Outcome;
59
+ durationMs: number;
60
+ problem: string | null;
61
+ }
62
+
63
+ export interface RunReport {
64
+ mode: "run" | "all";
65
+ root: string;
66
+ stored: string | null;
67
+ base: string | null;
68
+ head: string;
69
+ headEnd: string;
70
+ dirty: boolean;
71
+ changes: Change[];
72
+ plan: Plan | null;
73
+ fallback: Fallback | null;
74
+ selected: string[];
75
+ discovered: string[];
76
+ results: AppRun[];
77
+ observed: number;
78
+ advanced: boolean;
79
+ notAdvanced: string[];
80
+ exit: number;
81
+ }
82
+
83
+ export class UsageError extends Error {
84
+ constructor(message: string) {
85
+ super(message);
86
+ this.name = "UsageError";
87
+ }
88
+ }
89
+
90
+ interface GitChangeSet {
91
+ baseline: string;
92
+ head: string;
93
+ dirty: boolean;
94
+ changes: Change[];
95
+ }
96
+
97
+ // The git change source (PLAN 11.7). Throws on failure.
98
+ function gitSourcePath(): string {
99
+ return (
100
+ process.env.INCREMENTAL_GIT ||
101
+ path.join(repoRoot(), "adapters", "git", "dist", "incremental-git")
102
+ );
103
+ }
104
+
105
+ function gitChangeSet(root: string, ref: string): GitChangeSet {
106
+ const r = spawnSync(gitSourcePath(), ["changes", "--base", ref, "--root", root], {
107
+ encoding: "utf8",
108
+ });
109
+ if (r.error !== undefined)
110
+ throw new Error(`cannot run the git change source: ${r.error.message}`);
111
+ if (r.status !== 0)
112
+ throw new Error(
113
+ `git change source failed (exit ${r.status}): ${(r.stdout || r.stderr || "").trim()}`,
114
+ );
115
+ return JSON.parse(r.stdout) as GitChangeSet;
116
+ }
117
+
118
+ function hashOrAbsent(file: string): string {
119
+ return existsSync(file) ? sha256(readFileSync(file)) : "absent";
120
+ }
121
+
122
+ // The context (PLAN 8.4). `runner` names the next version the apps build with.
123
+ // Probes, directory listings and environment reads are not observed, and the
124
+ // module graph is not recorded (`graph: false`).
125
+ // Hashes of the tracked environment, as observation inputs (kind env), so a change
126
+ // to a tracked variable invalidates the apps that recorded it.
127
+ function envInputs(): Input[] {
128
+ return Object.entries(envHashes(process.env)).map(([name, value_hash]) => ({
129
+ kind: "env" as const,
130
+ name,
131
+ value_hash,
132
+ }));
133
+ }
134
+
135
+ // The directories of the other apps, for the app `task`. An app that contains
136
+ // `task` (the root app contains every app) is not excluded.
137
+ export function excludedFor(task: string, apps: readonly string[]): Set<string> {
138
+ const out = new Set<string>();
139
+ for (const other of apps) {
140
+ if (other !== task) {
141
+ const containsTask = other === "." || task.startsWith(`${other}/`);
142
+ if (!containsTask) out.add(other);
143
+ }
144
+ }
145
+ return out;
146
+ }
147
+
148
+ function sameInputs(a: readonly DeclaredInput[], b: readonly DeclaredInput[]): boolean {
149
+ return a.length === b.length && a.every((x, i) => x.path === b[i]?.path && x.hash === b[i]?.hash);
150
+ }
151
+
152
+ export function contextFor(root: string, runner: string): Context {
153
+ const lock = LOCKFILES.find((f) => existsSync(path.join(root, f)));
154
+ const pkgs = allPackageJsons(root);
155
+ const pkgjson =
156
+ pkgs.length === 0
157
+ ? "absent"
158
+ : sha256(pkgs.map((rel) => `${rel}\0${hashOrAbsent(path.join(root, rel))}`).join("\n"));
159
+ return {
160
+ lockfile: lock === undefined ? "absent" : hashOrAbsent(path.join(root, lock)),
161
+ tsconfig: hashOrAbsent(path.join(root, "tsconfig.json")),
162
+ pkgjson,
163
+ runner,
164
+ node: process.version,
165
+ fmt: 1,
166
+ caps: { probes: false, dirs: false, env: false },
167
+ graph: false,
168
+ };
169
+ }
170
+
171
+ // The next version of each discovered app that resolves it. Apps that do not
172
+ // resolve next are reported as errors when they run. All resolved versions
173
+ // must agree, because the context names one runner.
174
+ function runnerFor(root: string, apps: string[]): string {
175
+ const versions = new Set<string>();
176
+ for (const task of apps) {
177
+ try {
178
+ versions.add(nextPackage(path.join(root, task)).version);
179
+ } catch {
180
+ // reported per app when it runs
181
+ }
182
+ }
183
+ if (versions.size === 0) return "next@none";
184
+ if (versions.size > 1)
185
+ throw new Error(`apps resolve different next versions: ${[...versions].sort().join(", ")}`);
186
+ return `next@${[...versions][0]}`;
187
+ }
188
+
189
+ function ensureStore(store: string): void {
190
+ if (existsSync(store)) return;
191
+ const r = spawnSync(defaultEngine(), ["init", "--store", store], { encoding: "utf8" });
192
+ if (r.status !== 0)
193
+ throw new UsageError(`cannot create the store at ${store}: ${(r.stderr || "").trim()}`);
194
+ }
195
+
196
+ // The task of a deleted package.json, if it was an app directory.
197
+ function deletedApp(c: Change): string | null {
198
+ if (c.status !== "deleted" || !c.path.endsWith("package.json")) return null;
199
+ return path.posix.dirname(c.path) === "." ? "." : path.posix.dirname(c.path);
200
+ }
201
+
202
+ export async function runAdapter(opts: RunOptions): Promise<RunReport> {
203
+ const root = path.resolve(opts.root);
204
+ const store = path.resolve(opts.store);
205
+ ensureStore(store);
206
+
207
+ const discovered = discoverApps(root);
208
+ const context = contextFor(root, runnerFor(root, discovered));
209
+
210
+ let head0: GitChangeSet;
211
+ try {
212
+ head0 = gitChangeSet(root, "HEAD");
213
+ } catch (e) {
214
+ throw new UsageError(e instanceof Error ? e.message : String(e));
215
+ }
216
+
217
+ const client = await connect({
218
+ store,
219
+ root,
220
+ command: [defaultEngine(), "serve"],
221
+ timeoutMs: 60_000,
222
+ });
223
+ try {
224
+ const stored = (await client.baseline()).baseline;
225
+
226
+ let cs: GitChangeSet | null = null;
227
+ let gitError: string | null = null;
228
+ try {
229
+ cs = gitChangeSet(root, opts.base ?? stored ?? "HEAD");
230
+ } catch (e) {
231
+ gitError = e instanceof Error ? e.message : String(e);
232
+ }
233
+ if (cs === null && (opts.base !== undefined || stored === null)) {
234
+ throw new UsageError(gitError ?? "the git change source failed");
235
+ }
236
+ if (cs !== null && opts.base !== undefined && stored !== null && cs.baseline !== stored) {
237
+ throw new UsageError(
238
+ `--base resolves to ${cs.baseline}, but the store baseline is ${stored}`,
239
+ );
240
+ }
241
+
242
+ let plan: Plan | null = null;
243
+ if (cs !== null) {
244
+ plan = await client.affected(
245
+ { baseline: cs.baseline, head: cs.head, changes: cs.changes },
246
+ {
247
+ baseline: cs.baseline,
248
+ context,
249
+ env: envHashes(process.env),
250
+ declared_tasks: discovered,
251
+ verify: false,
252
+ policy: "balanced",
253
+ },
254
+ );
255
+ }
256
+
257
+ const deleted = new Set<string>(plan?.deleted_tasks ?? []);
258
+ for (const c of cs?.changes ?? []) {
259
+ const app = deletedApp(c);
260
+ if (app !== null && !discovered.includes(app)) deleted.add(app);
261
+ }
262
+ for (const t of [...deleted].sort()) await client.forget(t);
263
+
264
+ const runAll = opts.all || plan === null || plan.fallback !== null;
265
+ const planned = new Set((plan?.tasks ?? []).map((t) => t.id));
266
+ const selected = runAll ? discovered : discovered.filter((t) => planned.has(t));
267
+
268
+ const results: AppRun[] = [];
269
+ const observations: Observation[] = [];
270
+ const obsBaseline = stored ?? head0.head;
271
+ for (const task of selected) {
272
+ const appAbs = path.join(root, task);
273
+ let nextDir: string;
274
+ let before: DeclaredInput[];
275
+ try {
276
+ nextDir = nextPackage(appAbs).dir;
277
+ before = repoInputs(root, excludedFor(task, discovered));
278
+ const build = buildApp(appAbs, nextDir, opts.timeoutMs);
279
+ results.push({
280
+ task,
281
+ outcome: build.outcome,
282
+ durationMs: build.durationMs,
283
+ problem: build.problem,
284
+ });
285
+ // The inputs are read after the build, because the build may write some of
286
+ // them (next-env.d.ts, a rewritten tsconfig.json). If it changed any file,
287
+ // this build did not read the state it records, so the observation is dirty.
288
+ const after = repoInputs(root, excludedFor(task, discovered));
289
+ const rewritten = !sameInputs(before, after);
290
+ const inputs = [...after, ...envInputs()];
291
+ observations.push({
292
+ task,
293
+ baseline: obsBaseline,
294
+ dirty: rewritten,
295
+ context,
296
+ inputs,
297
+ outputs: [],
298
+ outcome: build.outcome,
299
+ duration_ms: build.durationMs,
300
+ });
301
+ } catch (e) {
302
+ const problem = e instanceof Error ? e.message : String(e);
303
+ results.push({ task, outcome: "error", durationMs: 0, problem });
304
+ }
305
+ }
306
+
307
+ const end = gitChangeSet(root, "HEAD");
308
+ const dirty = end.dirty;
309
+ const headEnd = end.head;
310
+ if (dirty) for (const o of observations) o.dirty = true;
311
+
312
+ const allRan = results.every((r) => r.outcome !== "error");
313
+ const canAdvance = allRan && !dirty && headEnd === head0.head;
314
+ if (observations.length > 0) await client.observeMany(observations);
315
+ let advanced = false;
316
+ if (canAdvance) {
317
+ if (headEnd !== stored) await client.advance(headEnd, stored);
318
+ advanced = true;
319
+ }
320
+
321
+ const notAdvanced: string[] = [];
322
+ if (!canAdvance) {
323
+ for (const r of results)
324
+ if (r.outcome === "error")
325
+ notAdvanced.push(`error: ${r.task}${r.problem ? ` (${r.problem})` : ""}`);
326
+ if (dirty)
327
+ notAdvanced.push(
328
+ "the worktree is dirty at the end of the run (next build writes .next and may rewrite tsconfig.json)",
329
+ );
330
+ if (headEnd !== head0.head) notAdvanced.push("HEAD moved during the run");
331
+ }
332
+ const failed = results.some((r) => r.outcome === "fail");
333
+ const exit = !advanced ? 7 : failed ? 1 : 0;
334
+
335
+ return {
336
+ mode: opts.all ? "all" : "run",
337
+ root,
338
+ stored,
339
+ base: cs?.baseline ?? null,
340
+ head: head0.head,
341
+ headEnd,
342
+ dirty,
343
+ changes: cs?.changes ?? [],
344
+ plan,
345
+ fallback:
346
+ plan?.fallback ??
347
+ (runAll && plan === null ? { action: "run_all", reason: "git_source" } : null),
348
+ selected,
349
+ discovered,
350
+ results,
351
+ observed: observations.length,
352
+ advanced,
353
+ notAdvanced,
354
+ exit,
355
+ };
356
+ } finally {
357
+ await client.close();
358
+ }
359
+ }
360
+
361
+ interface ParsedArgs {
362
+ opts: RunOptions;
363
+ json: boolean;
364
+ }
365
+
366
+ export function parseArgs(argv: string[]): ParsedArgs {
367
+ const [cmd, ...rest] = argv;
368
+ if (cmd !== "run")
369
+ throw new UsageError(
370
+ "usage: incremental-turbopack run [--base REF] [--json] [--all] [--store DIR] [--root DIR] [--timeout MS]",
371
+ );
372
+ const opts: RunOptions = { root: process.cwd(), store: "", all: false, timeoutMs: 1_200_000 };
373
+ let json = false;
374
+ let storeGiven = false;
375
+ for (let i = 0; i < rest.length; i++) {
376
+ const a = rest[i] as string;
377
+ const value = (): string => {
378
+ const v = rest[++i];
379
+ if (v === undefined) throw new UsageError(`${a} needs a value`);
380
+ return v;
381
+ };
382
+ if (a === "--base") {
383
+ opts.base = value();
384
+ } else if (a === "--json") {
385
+ json = true;
386
+ } else if (a === "--all") {
387
+ opts.all = true;
388
+ } else if (a === "--store") {
389
+ opts.store = value();
390
+ storeGiven = true;
391
+ } else if (a === "--root") {
392
+ opts.root = value();
393
+ } else if (a === "--timeout") {
394
+ const n = Number(value());
395
+ if (!Number.isInteger(n) || n < 1) throw new UsageError("--timeout needs a positive integer");
396
+ opts.timeoutMs = n;
397
+ } else {
398
+ throw new UsageError(`unknown option ${a}`);
399
+ }
400
+ }
401
+ opts.root = path.resolve(opts.root);
402
+ if (!storeGiven)
403
+ opts.store = process.env.INCREMENTAL_STORE || path.join(opts.root, ".incremental");
404
+ return { opts, json };
405
+ }
406
+
407
+ function printText(r: RunReport): void {
408
+ const counts: Record<Outcome, number> = { pass: 0, fail: 0, error: 0, none: 0 };
409
+ for (const t of r.results) counts[t.outcome]++;
410
+ const lines = [
411
+ `incremental turbopack ${r.mode}: stored ${r.stored ?? "none"}, query ${r.base ?? "none"}, head ${r.headEnd}${r.dirty ? " (dirty)" : ""}`,
412
+ ];
413
+ if (r.fallback !== null) lines.push(`fallback: ${r.fallback.reason}`);
414
+ else if (r.plan !== null)
415
+ lines.push(
416
+ `plan: ${r.plan.tasks.length} invalid of ${r.plan.total_tasks}, confidence ${r.plan.confidence}`,
417
+ );
418
+ lines.push(
419
+ `built ${r.results.length}: pass ${counts.pass}, fail ${counts.fail}, error ${counts.error}`,
420
+ );
421
+ for (const t of r.results)
422
+ if (t.outcome !== "pass")
423
+ lines.push(` ${t.outcome} ${t.task}${t.problem ? ` (${t.problem})` : ""}`);
424
+ lines.push(r.advanced ? `advanced to ${r.headEnd}` : `not advanced: ${r.notAdvanced.join("; ")}`);
425
+ lines.push(`exit ${r.exit}`);
426
+ process.stdout.write(`${lines.join("\n")}\n`);
427
+ }
428
+
429
+ export async function main(argv: string[]): Promise<number> {
430
+ let parsed: ParsedArgs;
431
+ try {
432
+ parsed = parseArgs(argv);
433
+ } catch (e) {
434
+ process.stderr.write(`${e instanceof Error ? e.message : String(e)}\n`);
435
+ return 2;
436
+ }
437
+ try {
438
+ const report = await runAdapter(parsed.opts);
439
+ if (parsed.json) process.stdout.write(`${JSON.stringify(report)}\n`);
440
+ else printText(report);
441
+ return report.exit;
442
+ } catch (e) {
443
+ const code =
444
+ e instanceof UsageError ? "invalid_params" : isIncrementalError(e) ? e.code : "internal";
445
+ const message = e instanceof Error ? e.message : String(e);
446
+ if (parsed.json)
447
+ process.stdout.write(`${JSON.stringify({ ok: false, error: { code, message } })}\n`);
448
+ process.stderr.write(`incremental turbopack: ${message}\n`);
449
+ return e instanceof UsageError ? 2 : 4;
450
+ }
451
+ }
452
+
453
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
454
+ main(process.argv.slice(2)).then((code) => {
455
+ process.exitCode = code;
456
+ });
457
+ }
@@ -0,0 +1,228 @@
1
+ // Integration tests: a scratch git repository with one Next.js app, built by the
2
+ // real `next build --turbopack` and run through the real engine and incremental-git
3
+ // (spec/adapters/turbopack.md). The fixture's node_modules is a copy of this
4
+ // package's pinned next, react and typescript, so it builds offline.
5
+ import assert from "node:assert/strict";
6
+ import { spawnSync } from "node:child_process";
7
+ import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { after, before, test } from "node:test";
12
+ import { discoverApps, runAdapter, type RunReport } from "../src/index.js";
13
+
14
+ const here = path.dirname(fileURLToPath(import.meta.url));
15
+ const PACKAGE_DIR = path.resolve(here, "../..");
16
+ const APP = "apps/web";
17
+
18
+ const GIT_ENV = {
19
+ ...process.env,
20
+ GIT_AUTHOR_NAME: "t",
21
+ GIT_AUTHOR_EMAIL: "t@example.com",
22
+ GIT_COMMITTER_NAME: "t",
23
+ GIT_COMMITTER_EMAIL: "t@example.com",
24
+ };
25
+
26
+ function git(cwd: string, ...args: string[]): string {
27
+ const r = spawnSync("git", args, { cwd, encoding: "utf8", env: GIT_ENV });
28
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${r.stderr}`);
29
+ return r.stdout.trim();
30
+ }
31
+
32
+ function write(root: string, rel: string, content: string): void {
33
+ const abs = path.join(root, rel);
34
+ mkdirSync(path.dirname(abs), { recursive: true });
35
+ writeFileSync(abs, content);
36
+ }
37
+
38
+ function commit(root: string, message: string): void {
39
+ git(root, "add", "-A");
40
+ git(root, "commit", "-q", "-m", message);
41
+ }
42
+
43
+ // tsconfig.json as `next build` leaves it, so the build does not rewrite it.
44
+ const TSCONFIG = JSON.stringify({
45
+ compilerOptions: {
46
+ target: "ES2022",
47
+ lib: ["dom", "es2022"],
48
+ jsx: "react-jsx",
49
+ strict: true,
50
+ module: "esnext",
51
+ moduleResolution: "bundler",
52
+ noEmit: true,
53
+ isolatedModules: true,
54
+ skipLibCheck: true,
55
+ allowJs: true,
56
+ incremental: true,
57
+ esModuleInterop: true,
58
+ resolveJsonModule: true,
59
+ plugins: [{ name: "next" }],
60
+ },
61
+ include: [
62
+ "next-env.d.ts",
63
+ "**/*.ts",
64
+ "**/*.tsx",
65
+ ".next/types/**/*.ts",
66
+ ".next/dev/types/**/*.ts",
67
+ ],
68
+ exclude: ["node_modules"],
69
+ });
70
+
71
+ const PAGE_OK = "export default function Page() {\n return <main>hi</main>;\n}\n";
72
+
73
+ interface Fixture {
74
+ root: string;
75
+ base: string;
76
+ // The initial commit. Each test returns the worktree to it.
77
+ initial: string;
78
+ stores: number;
79
+ }
80
+
81
+ function makeFixture(): Fixture {
82
+ const base = mkdtempSync(path.join(os.tmpdir(), "incremental-tp-"));
83
+ const root = path.join(base, "repo");
84
+ mkdirSync(root);
85
+ git(root, "init", "-q", "-b", "main");
86
+ write(root, ".gitignore", "node_modules/\n.next/\nnext-env.d.ts\n.incremental/\n");
87
+ write(root, "package.json", JSON.stringify({ name: "fixture", private: true }));
88
+ write(
89
+ root,
90
+ "package-lock.json",
91
+ readFileSync(path.join(PACKAGE_DIR, "package-lock.json"), "utf8"),
92
+ );
93
+ write(root, "libs/util/package.json", JSON.stringify({ name: "util", private: true }));
94
+ write(root, "libs/util/index.ts", "export const u = 1;\n");
95
+ write(
96
+ root,
97
+ `${APP}/package.json`,
98
+ JSON.stringify({
99
+ name: "web",
100
+ private: true,
101
+ dependencies: { next: "16.4.2", react: "19.2.8", "react-dom": "19.2.8" },
102
+ devDependencies: {
103
+ typescript: "5.9.3",
104
+ "@types/node": "22.20.5",
105
+ "@types/react": "19.2.8",
106
+ "@types/react-dom": "19.2.3",
107
+ },
108
+ }),
109
+ );
110
+ write(root, `${APP}/next.config.mjs`, "export default {};\n");
111
+ write(root, `${APP}/tsconfig.json`, TSCONFIG);
112
+ write(
113
+ root,
114
+ `${APP}/app/layout.tsx`,
115
+ 'export default function RootLayout({ children }: { children: React.ReactNode }) {\n return <html lang="en"><body>{children}</body></html>;\n}\n',
116
+ );
117
+ write(root, `${APP}/app/page.tsx`, PAGE_OK);
118
+ // A symbolic link would not do: Turbopack does not compile files outside the
119
+ // workspace root, so the dependencies are copied, once for the whole file.
120
+ cpSync(path.join(PACKAGE_DIR, "node_modules"), path.join(root, "node_modules"), {
121
+ recursive: true,
122
+ verbatimSymlinks: true,
123
+ });
124
+ commit(root, "init");
125
+ return { root, base, initial: git(root, "rev-parse", "HEAD"), stores: 0 };
126
+ }
127
+
128
+ // Copying node_modules and building the app are slow, so the fixture is shared by
129
+ // the whole file. `fresh` returns the worktree to the initial commit, removes the
130
+ // previous build output, and gives the test a store of its own.
131
+ let fx: Fixture;
132
+ before(() => {
133
+ fx = makeFixture();
134
+ });
135
+
136
+ after(() => {
137
+ rmSync(fx.base, { recursive: true, force: true });
138
+ });
139
+
140
+ function fresh(): { root: string; store: string } {
141
+ git(fx.root, "reset", "-q", "--hard", fx.initial);
142
+ git(fx.root, "clean", "-q", "-fd");
143
+ rmSync(path.join(fx.root, APP, ".next"), { recursive: true, force: true });
144
+ fx.stores += 1;
145
+ return { root: fx.root, store: path.join(fx.base, `store-${fx.stores}`) };
146
+ }
147
+
148
+ async function run(root: string, store: string): Promise<RunReport> {
149
+ return runAdapter({ root, store, all: false, timeoutMs: 600_000 });
150
+ }
151
+
152
+ test("discovers each package.json that depends on next", () => {
153
+ assert.deepEqual(discoverApps(fresh().root), [APP]);
154
+ });
155
+
156
+ test("first run builds every app and advances the baseline", async () => {
157
+ const { root, store } = fresh();
158
+ const r = await run(root, store);
159
+ assert.deepEqual(r.selected, [APP]);
160
+ assert.deepEqual(
161
+ r.results.map((x) => x.outcome),
162
+ ["pass"],
163
+ JSON.stringify(r.results),
164
+ );
165
+ assert.equal(r.advanced, true, r.notAdvanced.join("; "));
166
+ assert.equal(r.exit, 0);
167
+ });
168
+
169
+ test("an edit to a declared input invalidates the app", async () => {
170
+ const { root, store } = fresh();
171
+ await run(root, store);
172
+ write(root, `${APP}/next.config.mjs`, "export default { poweredByHeader: false };\n");
173
+ commit(root, "edit next config");
174
+ const r = await run(root, store);
175
+ assert.deepEqual(r.selected, [APP]);
176
+ assert.deepEqual(
177
+ r.results.map((x) => x.outcome),
178
+ ["pass"],
179
+ );
180
+ assert.equal(r.advanced, true, r.notAdvanced.join("; "));
181
+ });
182
+
183
+ test("a failed build is reported as fail and exits 1", async () => {
184
+ const { root, store } = fresh();
185
+ await run(root, store);
186
+ write(
187
+ root,
188
+ `${APP}/app/page.tsx`,
189
+ 'export default function Page() {\n const x: number = "not a number";\n return <main>{x}</main>;\n}\n',
190
+ );
191
+ commit(root, "break the page");
192
+ const r = await run(root, store);
193
+ assert.deepEqual(
194
+ r.results.map((x) => x.outcome),
195
+ ["fail"],
196
+ JSON.stringify(r.results),
197
+ );
198
+ assert.equal(r.advanced, true, "a failed build is a complete run, so the baseline advances");
199
+ assert.equal(r.exit, 1);
200
+ });
201
+
202
+ test("an uncommitted change leaves the baseline in place and exits 7", async () => {
203
+ const { root, store } = fresh();
204
+ await run(root, store);
205
+ write(
206
+ root,
207
+ `${APP}/app/page.tsx`,
208
+ "export default function Page() {\n return <main>changed</main>;\n}\n",
209
+ );
210
+ const r = await run(root, store);
211
+ assert.equal(r.advanced, false);
212
+ assert.equal(r.exit, 7);
213
+ assert.ok(
214
+ r.notAdvanced.some((m) => m.includes("dirty")),
215
+ r.notAdvanced.join("; "),
216
+ );
217
+ });
218
+
219
+ // Skipping: the observation is clean (no rewrite by the build, every read input
220
+ // hashed), so an unchanged app is not built again.
221
+ test("an unchanged app is skipped on the next run, without a second build", async () => {
222
+ const { root, store } = fresh();
223
+ await run(root, store);
224
+ const r = await run(root, store);
225
+ assert.deepEqual(r.selected, [], "no app is selected, so none is built");
226
+ assert.equal(r.advanced, true);
227
+ assert.equal(r.exit, 0);
228
+ });