๐Ÿ“ฆ cloudflare / vinext

๐Ÿ“„ init.test.ts ยท 651 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import {
  init,
  generateViteConfig,
  addScripts,
  getInitDeps,
  isDepInstalled,
  getReactUpgradeDeps,
  type InitOptions,
} from "../packages/vinext/src/init.js";

// โ”€โ”€โ”€ Test Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

let tmpDir: string;

function createTmpDir(): string {
  return fs.mkdtempSync(path.join(os.tmpdir(), "vinext-init-test-"));
}

function writeFile(dir: string, relativePath: string, content: string): void {
  const fullPath = path.join(dir, relativePath);
  fs.mkdirSync(path.dirname(fullPath), { recursive: true });
  fs.writeFileSync(fullPath, content, "utf-8");
}

function mkdir(dir: string, relativePath: string): void {
  fs.mkdirSync(path.join(dir, relativePath), { recursive: true });
}

function readPkg(dir: string): Record<string, unknown> {
  return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf-8"));
}

function readFile(dir: string, relativePath: string): string {
  return fs.readFileSync(path.join(dir, relativePath), "utf-8");
}

/**
 * Create a minimal Next.js-like project structure in a temp directory.
 */
function setupProject(
  dir: string,
  opts: {
    router?: "app" | "pages";
    typeModule?: boolean;
    extraPkg?: Record<string, unknown>;
  } = {},
): void {
  const router = opts.router ?? "app";
  const pkg: Record<string, unknown> = {
    name: "test-project",
    version: "1.0.0",
    dependencies: { react: "^19.0.0", "react-dom": "^19.0.0", next: "^15.0.0" },
    ...opts.extraPkg,
  };
  if (opts.typeModule) {
    pkg.type = "module";
  }

  writeFile(dir, "package.json", JSON.stringify(pkg, null, 2));

  if (router === "app") {
    mkdir(dir, "app");
    writeFile(dir, "app/page.tsx", 'export default function Home() { return <div>hi</div> }');
    writeFile(
      dir,
      "app/layout.tsx",
      "export default function Layout({ children }) { return <html><body>{children}</body></html> }",
    );
  } else {
    mkdir(dir, "pages");
    writeFile(dir, "pages/index.tsx", 'export default function Home() { return <div>hi</div> }');
  }
}

/** No-op exec for tests โ€” records calls for assertions */
function noopExec(): {
  exec: (cmd: string, opts: { cwd: string; stdio: string }) => void;
  calls: Array<{ cmd: string; opts: { cwd: string; stdio: string } }>;
} {
  const calls: Array<{ cmd: string; opts: { cwd: string; stdio: string } }> = [];
  return {
    exec: (cmd: string, opts: { cwd: string; stdio: string }) => {
      calls.push({ cmd, opts });
    },
    calls,
  };
}

/**
 * Run init with a no-op exec and suppressed console output.
 */
async function runInit(
  dir: string,
  opts: Partial<InitOptions> = {},
): Promise<{ result: Awaited<ReturnType<typeof init>>; execCalls: Array<{ cmd: string }> }> {
  const { exec, calls } = noopExec();

  // Suppress console output during tests
  const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  const consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});

  // Mock process.exit to prevent test from exiting
  const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: string | number | null) => {
    throw new Error(`process.exit(${code})`);
  }) as never);

  try {
    const result = await init({
      root: dir,
      skipCheck: true,
      _exec: exec,
      ...opts,
    });
    return { result, execCalls: calls };
  } finally {
    consoleSpy.mockRestore();
    consoleErrSpy.mockRestore();
    exitSpy.mockRestore();
  }
}

/**
 * Run init expecting it to fail (process.exit).
 */
async function runInitExpectExit(
  dir: string,
  opts: Partial<InitOptions> = {},
): Promise<string> {
  const { exec } = noopExec();

  const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  const consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: string | number | null) => {
    throw new Error(`process.exit(${code})`);
  }) as never);

  try {
    await init({
      root: dir,
      skipCheck: true,
      _exec: exec,
      ...opts,
    });
    throw new Error("Expected process.exit to be called");
  } catch (e) {
    return (e as Error).message;
  } finally {
    consoleSpy.mockRestore();
    consoleErrSpy.mockRestore();
    exitSpy.mockRestore();
  }
}

beforeEach(() => {
  tmpDir = createTmpDir();
});

afterEach(() => {
  fs.rmSync(tmpDir, { recursive: true, force: true });
});

// โ”€โ”€โ”€ Unit Tests: generateViteConfig โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe("generateViteConfig", () => {
  it("generates App Router config with RSC plugin", () => {
    const config = generateViteConfig(true);
    expect(config).toContain('import vinext from "vinext"');
    expect(config).toContain("vinext()");
  });

  it("generates Pages Router config without RSC", () => {
    const config = generateViteConfig(false);
    expect(config).toContain('import vinext from "vinext"');
    expect(config).toContain("vinext()");
    expect(config).not.toContain("plugin-rsc");
    expect(config).not.toContain("rsc(");
  });

  it("does not include cloudflare plugin", () => {
    expect(generateViteConfig(true)).not.toContain("cloudflare");
    expect(generateViteConfig(false)).not.toContain("cloudflare");
  });

  it("includes defineConfig import", () => {
    expect(generateViteConfig(true)).toContain("defineConfig");
    expect(generateViteConfig(false)).toContain("defineConfig");
  });
});

// โ”€โ”€โ”€ Unit Tests: addScripts โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe("addScripts", () => {
  it("adds dev:vinext and build:vinext scripts", () => {
    setupProject(tmpDir, { router: "app" });

    const added = addScripts(tmpDir, 3001);

    expect(added).toContain("dev:vinext");
    expect(added).toContain("build:vinext");

    const pkg = readPkg(tmpDir) as { scripts: Record<string, string> };
    expect(pkg.scripts["dev:vinext"]).toBe("vite dev --port 3001");
    expect(pkg.scripts["build:vinext"]).toBe("vite build");
  });

  it("uses custom port", () => {
    setupProject(tmpDir, { router: "app" });

    addScripts(tmpDir, 4000);

    const pkg = readPkg(tmpDir) as { scripts: Record<string, string> };
    expect(pkg.scripts["dev:vinext"]).toBe("vite dev --port 4000");
  });

  it("does not overwrite existing scripts", () => {
    setupProject(tmpDir, {
      router: "app",
      extraPkg: { scripts: { "dev:vinext": "custom-command" } },
    });

    const added = addScripts(tmpDir, 3001);

    expect(added).not.toContain("dev:vinext");
    expect(added).toContain("build:vinext");

    const pkg = readPkg(tmpDir) as { scripts: Record<string, string> };
    expect(pkg.scripts["dev:vinext"]).toBe("custom-command");
  });

  it("creates scripts object if missing", () => {
    writeFile(tmpDir, "package.json", JSON.stringify({ name: "test" }));

    const added = addScripts(tmpDir, 3001);

    expect(added).toContain("dev:vinext");
    const pkg = readPkg(tmpDir) as { scripts: Record<string, string> };
    expect(pkg.scripts["dev:vinext"]).toBeDefined();
  });

  it("returns empty array when no package.json", () => {
    const added = addScripts(tmpDir, 3001);
    expect(added).toEqual([]);
  });
});

// โ”€โ”€โ”€ Unit Tests: getInitDeps / isDepInstalled โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe("getInitDeps", () => {
  it("returns vinext + vite + @vitejs/plugin-rsc + react-server-dom-webpack for App Router", () => {
    const deps = getInitDeps(true);
    expect(deps).toContain("vinext");
    expect(deps).toContain("vite");
    expect(deps).toContain("@vitejs/plugin-rsc");
    expect(deps).toContain("react-server-dom-webpack");
  });

  it("returns vinext + vite for Pages Router", () => {
    const deps = getInitDeps(false);
    expect(deps).toContain("vinext");
    expect(deps).toContain("vite");
    expect(deps).not.toContain("@vitejs/plugin-rsc");
    expect(deps).not.toContain("react-server-dom-webpack");
  });
});

/** Helper: create a fake resolvable react package in node_modules */
function setupFakeReact(dir: string, version: string): void {
  const reactDir = path.join(dir, "node_modules", "react");
  fs.mkdirSync(reactDir, { recursive: true });
  fs.writeFileSync(
    path.join(reactDir, "package.json"),
    JSON.stringify({ name: "react", version, main: "index.js" }),
  );
  fs.writeFileSync(path.join(reactDir, "index.js"), "");
}

describe("getReactUpgradeDeps", () => {
  it("returns react@latest + react-dom@latest when React is too old", () => {
    setupProject(tmpDir, { router: "app" });
    setupFakeReact(tmpDir, "19.2.3");

    const deps = getReactUpgradeDeps(tmpDir);
    expect(deps).toEqual(["react@latest", "react-dom@latest"]);
  });

  it("returns empty array when React is new enough", () => {
    setupProject(tmpDir, { router: "app" });
    setupFakeReact(tmpDir, "19.2.4");

    const deps = getReactUpgradeDeps(tmpDir);
    expect(deps).toEqual([]);
  });

  it("returns empty array when React is a newer minor version", () => {
    setupProject(tmpDir, { router: "app" });
    setupFakeReact(tmpDir, "19.3.0");

    const deps = getReactUpgradeDeps(tmpDir);
    expect(deps).toEqual([]);
  });

  it("returns upgrade deps when React major is below 19", () => {
    setupProject(tmpDir, { router: "app" });
    setupFakeReact(tmpDir, "18.3.1");

    const deps = getReactUpgradeDeps(tmpDir);
    expect(deps).toEqual(["react@latest", "react-dom@latest"]);
  });

  it("returns empty array when node_modules/react does not exist", () => {
    setupProject(tmpDir, { router: "app" });
    const deps = getReactUpgradeDeps(tmpDir);
    expect(deps).toEqual([]);
  });
});

describe("isDepInstalled", () => {
  it("returns true when dep is in dependencies", () => {
    setupProject(tmpDir, { router: "app" });
    expect(isDepInstalled(tmpDir, "react")).toBe(true);
  });

  it("returns true when dep is in devDependencies", () => {
    setupProject(tmpDir, {
      router: "app",
      extraPkg: { devDependencies: { vite: "^7.0.0" } },
    });
    expect(isDepInstalled(tmpDir, "vite")).toBe(true);
  });

  it("returns false when dep is not installed", () => {
    setupProject(tmpDir, { router: "app" });
    expect(isDepInstalled(tmpDir, "vite")).toBe(false);
  });

  it("returns false when no package.json", () => {
    expect(isDepInstalled(tmpDir, "vite")).toBe(false);
  });
});

// โ”€โ”€โ”€ Integration: init() โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe("init โ€” basic functionality", () => {
  it("generates vite.config.ts for App Router project", async () => {
    setupProject(tmpDir, { router: "app" });

    const { result } = await runInit(tmpDir);

    expect(result.generatedViteConfig).toBe(true);
    expect(fs.existsSync(path.join(tmpDir, "vite.config.ts"))).toBe(true);

    const config = readFile(tmpDir, "vite.config.ts");
    expect(config).toContain('import vinext from "vinext"');
  });

  it("generates vite.config.ts for Pages Router project", async () => {
    setupProject(tmpDir, { router: "pages" });

    const { result } = await runInit(tmpDir);

    expect(result.generatedViteConfig).toBe(true);
    const config = readFile(tmpDir, "vite.config.ts");
    expect(config).toContain("vinext()");
    expect(config).not.toContain("plugin-rsc");
  });

  it("adds 'type': 'module' to package.json", async () => {
    setupProject(tmpDir, { router: "app" });

    const { result } = await runInit(tmpDir);

    expect(result.addedTypeModule).toBe(true);
    const pkg = readPkg(tmpDir);
    expect(pkg.type).toBe("module");
  });

  it("skips adding 'type': 'module' when already present", async () => {
    setupProject(tmpDir, { router: "app", typeModule: true });

    const { result } = await runInit(tmpDir);

    expect(result.addedTypeModule).toBe(false);
  });

  it("adds dev:vinext and build:vinext scripts", async () => {
    setupProject(tmpDir, { router: "app" });

    const { result } = await runInit(tmpDir);

    expect(result.addedScripts).toContain("dev:vinext");
    expect(result.addedScripts).toContain("build:vinext");

    const pkg = readPkg(tmpDir) as { scripts: Record<string, string> };
    expect(pkg.scripts["dev:vinext"]).toBe("vite dev --port 3001");
    expect(pkg.scripts["build:vinext"]).toBe("vite build");
  });

  it("uses custom port in dev:vinext script", async () => {
    setupProject(tmpDir, { router: "app" });

    await runInit(tmpDir, { port: 4000 });

    const pkg = readPkg(tmpDir) as { scripts: Record<string, string> };
    expect(pkg.scripts["dev:vinext"]).toBe("vite dev --port 4000");
  });

  it("does not overwrite existing scripts", async () => {
    setupProject(tmpDir, {
      router: "app",
      extraPkg: { scripts: { "dev:vinext": "custom-command" } },
    });

    const { result } = await runInit(tmpDir);

    expect(result.addedScripts).not.toContain("dev:vinext");
    expect(result.addedScripts).toContain("build:vinext");

    const pkg = readPkg(tmpDir) as { scripts: Record<string, string> };
    expect(pkg.scripts["dev:vinext"]).toBe("custom-command");
  });
});

// โ”€โ”€โ”€ CJS Config Renaming โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe("init โ€” CJS config renaming", () => {
  it("renames CJS postcss.config.js to .cjs", async () => {
    setupProject(tmpDir, { router: "app" });
    writeFile(tmpDir, "postcss.config.js", "module.exports = { plugins: {} };");

    const { result } = await runInit(tmpDir);

    expect(result.renamedConfigs).toContainEqual(["postcss.config.js", "postcss.config.cjs"]);
    expect(fs.existsSync(path.join(tmpDir, "postcss.config.cjs"))).toBe(true);
    expect(fs.existsSync(path.join(tmpDir, "postcss.config.js"))).toBe(false);
  });

  it("does not rename ESM config files", async () => {
    setupProject(tmpDir, { router: "app" });
    writeFile(tmpDir, "postcss.config.js", "export default { plugins: {} };");

    const { result } = await runInit(tmpDir);

    expect(result.renamedConfigs).toEqual([]);
    expect(fs.existsSync(path.join(tmpDir, "postcss.config.js"))).toBe(true);
  });
});

// โ”€โ”€โ”€ Dependency Installation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe("init โ€” dependency installation", () => {
  it("detects missing vinext and vite dependencies and installs them", async () => {
    setupProject(tmpDir, { router: "app" });

    const { result } = await runInit(tmpDir);

    expect(result.installedDeps).toContain("vinext");
    expect(result.installedDeps).toContain("vite");
  });

  it("detects missing @vitejs/plugin-rsc for App Router", async () => {
    setupProject(tmpDir, { router: "app" });

    const { result } = await runInit(tmpDir);

    expect(result.installedDeps).toContain("@vitejs/plugin-rsc");
  });

  it("detects missing react-server-dom-webpack for App Router", async () => {
    setupProject(tmpDir, { router: "app" });

    const { result } = await runInit(tmpDir);

    expect(result.installedDeps).toContain("react-server-dom-webpack");
  });

  it("does not require @vitejs/plugin-rsc for Pages Router", async () => {
    setupProject(tmpDir, { router: "pages" });

    const { result } = await runInit(tmpDir);

    expect(result.installedDeps).not.toContain("@vitejs/plugin-rsc");
  });

  it("does not require react-server-dom-webpack for Pages Router", async () => {
    setupProject(tmpDir, { router: "pages" });

    const { result } = await runInit(tmpDir);

    expect(result.installedDeps).not.toContain("react-server-dom-webpack");
  });

  it("upgrades React before installing dev deps when React is too old (App Router)", async () => {
    setupProject(tmpDir, { router: "app" });
    setupFakeReact(tmpDir, "19.2.3");

    const { execCalls } = await runInit(tmpDir);

    // The first exec call should be the React upgrade (without -D)
    const reactUpgradeCall = execCalls.find(
      (c) => c.cmd.includes("react@latest") && c.cmd.includes("react-dom@latest"),
    );
    expect(reactUpgradeCall).toBeDefined();
    // The React upgrade should NOT use -D flag (keeps them in dependencies)
    expect(reactUpgradeCall!.cmd).not.toContain("-D");

    // The second exec call should be the dev deps install (with -D)
    const devDepsCall = execCalls.find(
      (c) => c.cmd.includes("react-server-dom-webpack") && c.cmd.includes("-D"),
    );
    expect(devDepsCall).toBeDefined();

    // React upgrade should come before dev deps install
    const upgradeIdx = execCalls.indexOf(reactUpgradeCall!);
    const devDepsIdx = execCalls.indexOf(devDepsCall!);
    expect(upgradeIdx).toBeLessThan(devDepsIdx);
  });

  it("does not upgrade React when version is already compatible", async () => {
    setupProject(tmpDir, { router: "app" });
    setupFakeReact(tmpDir, "19.2.4");

    const { execCalls } = await runInit(tmpDir);

    // No React upgrade call
    const reactUpgradeCall = execCalls.find(
      (c) => c.cmd.includes("react@latest"),
    );
    expect(reactUpgradeCall).toBeUndefined();
  });

  it("calls exec with correct package manager for pnpm", async () => {
    setupProject(tmpDir, { router: "pages" });
    writeFile(tmpDir, "pnpm-lock.yaml", "lockfileVersion: 5");

    const { execCalls } = await runInit(tmpDir);

    const installCall = execCalls.find((c) => c.cmd.includes("add -D") || c.cmd.includes("install -D"));
    expect(installCall).toBeDefined();
    expect(installCall!.cmd).toMatch(/^pnpm add -D/);
  });

  it("calls exec with npm when no lock file exists", async () => {
    setupProject(tmpDir, { router: "pages" });

    const { execCalls } = await runInit(tmpDir);

    const installCall = execCalls.find((c) => c.cmd.includes("install -D") || c.cmd.includes("add -D"));
    expect(installCall).toBeDefined();
    expect(installCall!.cmd).toMatch(/^npm install -D/);
  });
});

// โ”€โ”€โ”€ Guard Rails โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe("init โ€” guard rails", () => {
  it("skips vite.config.ts when it already exists (without --force)", async () => {
    setupProject(tmpDir, { router: "app" });
    writeFile(tmpDir, "vite.config.ts", "export default {}");

    const { result } = await runInit(tmpDir);

    expect(result.generatedViteConfig).toBe(false);
    expect(result.skippedViteConfig).toBe(true);
    // Original config should be preserved
    const config = readFile(tmpDir, "vite.config.ts");
    expect(config).toBe("export default {}");
  });

  it("still runs all other steps when vite.config.ts exists", async () => {
    setupProject(tmpDir, { router: "app" });
    writeFile(tmpDir, "vite.config.ts", "export default {}");

    const { result } = await runInit(tmpDir);

    // Dependencies should still be installed
    expect(result.installedDeps).toContain("vite");
    // ESM migration should still happen
    expect(result.addedTypeModule).toBe(true);
    // Scripts should still be added
    expect(result.addedScripts).toContain("dev:vinext");
    expect(result.addedScripts).toContain("build:vinext");
    // But vite config should be skipped
    expect(result.generatedViteConfig).toBe(false);
    expect(result.skippedViteConfig).toBe(true);
  });

  it("overwrites vite.config.ts with --force", async () => {
    setupProject(tmpDir, { router: "app" });
    writeFile(tmpDir, "vite.config.ts", "export default {}");

    const { result } = await runInit(tmpDir, { force: true });

    expect(result.generatedViteConfig).toBe(true);
    expect(result.skippedViteConfig).toBe(false);
    const config = readFile(tmpDir, "vite.config.ts");
    expect(config).toContain("vinext()");
  });

  it("exits when no package.json exists", async () => {
    mkdir(tmpDir, "app");

    const msg = await runInitExpectExit(tmpDir);
    expect(msg).toContain("process.exit(1)");
  });
});

// โ”€โ”€โ”€ Preserves Existing Project โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€๏ฟฝ๏ฟฝโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe("init โ€” non-destructive", () => {
  it("preserves existing package.json fields", async () => {
    setupProject(tmpDir, {
      router: "app",
      extraPkg: {
        scripts: { dev: "next dev", build: "next build" },
        dependencies: { react: "^19.0.0", next: "^15.0.0" },
      },
    });

    await runInit(tmpDir);

    const pkg = readPkg(tmpDir) as Record<string, Record<string, string>>;
    expect(pkg.scripts.dev).toBe("next dev");
    expect(pkg.scripts.build).toBe("next build");
    expect(pkg.dependencies.react).toBe("^19.0.0");
    expect(pkg.dependencies.next).toBe("^15.0.0");
  });

  it("does not modify source files", async () => {
    setupProject(tmpDir, { router: "app" });
    const originalPage = readFile(tmpDir, "app/page.tsx");

    await runInit(tmpDir);

    expect(readFile(tmpDir, "app/page.tsx")).toBe(originalPage);
  });

  it("does not modify next.config", async () => {
    setupProject(tmpDir, { router: "app" });
    writeFile(tmpDir, "next.config.mjs", "export default {};");
    const originalConfig = readFile(tmpDir, "next.config.mjs");

    await runInit(tmpDir);

    expect(readFile(tmpDir, "next.config.mjs")).toBe(originalConfig);
  });
});