@tschk/moonshine-cli 0.3.2 → 0.3.3

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/README.md CHANGED
@@ -11,6 +11,7 @@ bun packages/cli/bin/moonshine.ts preview
11
11
 
12
12
  Commands:
13
13
 
14
+ - `adopt [dir] [--dry-run] [--force]`
14
15
  - `new <name> [--react|--solid|--crepus] [--adapter bun|node|cloudflare|vercel] [--vite]`
15
16
  - `build [dir] [--adapter bun|node|cloudflare|vercel]`
16
17
  - `inspect [path] [--json]`
@@ -18,6 +19,25 @@ Commands:
18
19
  - `dev [dir]`
19
20
  - `compile [file]`
20
21
 
22
+ ## `adopt`
23
+
24
+ Points at an existing Next app and makes it run on moonshine without `next`
25
+ installed. It does not edit your source: every `next/*` specifier the adapter
26
+ implements is remapped through `compilerOptions.paths`, which Bun honours in
27
+ both `bun run` and `Bun.build`. `moonshine.config.ts` records the route
28
+ directory and convention so `moonshine build` reads `app/` or `pages/` in place.
29
+
30
+ ```bash
31
+ moonshine adopt --dry-run # print the plan, write nothing
32
+ moonshine adopt # apply; running twice is a no-op
33
+ bun install && moonshine build && moonshine preview
34
+ ```
35
+
36
+ The command ends with a scorecard: how many imports it aliased, how many source
37
+ files it rewrote, and a precise list of what it cannot carry over — middleware,
38
+ the metadata API, ISR, `next.config` options, server actions, async server
39
+ components, and image optimization.
40
+
21
41
  See [DESIGN.md](../../DESIGN.md), [docs/ROUTING.md](../../docs/ROUTING.md),
22
42
  [docs/DEPLOYMENT.md](../../docs/DEPLOYMENT.md), and
23
43
  [docs/MANIFEST.md](../../docs/MANIFEST.md).
package/bin/moonshine.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env bun
2
+ import { adoptCommand } from "../src/adopt";
2
3
  import { buildCommand } from "../src/build";
3
4
  import { compileCommand } from "../src/compile";
4
5
  import { devCommand } from "../src/dev";
@@ -18,6 +19,9 @@ Usage:
18
19
  --crepus add Crepus renderer
19
20
  --adapter deployment target (default: bun)
20
21
  --vite client-only Vite SPA
22
+ moonshine adopt [dir] Convert an existing Next/React app to moonshine
23
+ --dry-run print the plan, write nothing
24
+ --force rewrite an existing moonshine.config.ts
21
25
  moonshine compile [file] .crepus / View IR JSON → .tsx
22
26
  moonshine build [dir] Build project into .moonshine/manifest.json
23
27
  --adapter bun|node|cloudflare|vercel
@@ -35,6 +39,9 @@ switch (cmd) {
35
39
  case "new":
36
40
  await newCommand(args);
37
41
  break;
42
+ case "adopt":
43
+ await adoptCommand(args);
44
+ break;
38
45
  case "compile":
39
46
  await compileCommand(args);
40
47
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-cli",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "Bun CLI for moonshine — new, dev, build, preview, inspect, compile",
5
5
  "license": "ISC",
6
6
  "type": "module",
@@ -19,12 +19,13 @@
19
19
  "crepus"
20
20
  ],
21
21
  "dependencies": {
22
- "@tschk/crepus-moonshine": "^0.3.2",
23
- "@tschk/moonshine-compiler": "^0.3.2",
24
- "@tschk/moonshine-deploy-bun": "^0.3.2",
25
- "@tschk/moonshine-framework": "^0.3.2",
26
- "@tschk/moonshine-react": "^0.3.2",
27
- "@tschk/moonshine-server": "^0.3.2"
22
+ "@tschk/crepus-moonshine": "^0.3.3",
23
+ "@tschk/moonshine-compiler": "^0.3.3",
24
+ "@tschk/moonshine-deploy-bun": "^0.3.3",
25
+ "@tschk/moonshine-framework": "^0.3.3",
26
+ "@tschk/moonshine-next": "^0.3.3",
27
+ "@tschk/moonshine-react": "^0.3.3",
28
+ "@tschk/moonshine-server": "^0.3.3"
28
29
  },
29
30
  "scripts": {
30
31
  "format": "bunx prettier --check .",
@@ -33,6 +34,6 @@
33
34
  "test": "bun test"
34
35
  },
35
36
  "optionalDependencies": {
36
- "@tschk/moonshine-solid": "^0.3.2"
37
+ "@tschk/moonshine-solid": "^0.3.3"
37
38
  }
38
39
  }
package/src/adopt.ts ADDED
@@ -0,0 +1,607 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, relative, resolve } from "node:path";
3
+ import { nextAliases, resolveAlias } from "@tschk/moonshine-next/aliases";
4
+ import type { RouteConvention } from "@tschk/moonshine-compiler";
5
+ import { detectMoonshineRoot, packagePath } from "./new.js";
6
+
7
+ export type Framework = "next-app" | "next-pages" | "vite-react" | "unknown";
8
+
9
+ export type NextImport = {
10
+ /** Project-relative file holding the import. */
11
+ file: string;
12
+ specifier: string;
13
+ /** Whether `@tschk/moonshine-next` implements this specifier. */
14
+ aliasable: boolean;
15
+ };
16
+
17
+ export type AdoptScan = {
18
+ projectDir: string;
19
+ framework: Framework;
20
+ /** Project-relative route directory, when one was found. */
21
+ routesDir?: string;
22
+ convention?: RouteConvention;
23
+ routes: { path: string; file: string }[];
24
+ imports: NextImport[];
25
+ conventions: string[];
26
+ /** Blunt list of what adoption does not carry over. */
27
+ manual: string[];
28
+ };
29
+
30
+ export type AdoptChange = {
31
+ file: string;
32
+ summary: string;
33
+ /** Already true before this run; used to keep repeat runs honest. */
34
+ alreadyApplied: boolean;
35
+ contents?: string;
36
+ };
37
+
38
+ export type AdoptPlan = {
39
+ scan: AdoptScan;
40
+ changes: AdoptChange[];
41
+ /** Source files whose imports had to be edited because no alias covered them. */
42
+ rewritten: string[];
43
+ };
44
+
45
+ const SOURCE_GLOB = "**/*.{ts,tsx,js,jsx,mjs}";
46
+ const IGNORED = ["node_modules/", ".next/", ".moonshine/", "dist/", "build/"];
47
+
48
+ const RUNTIME_DEPS = [
49
+ "@tschk/moonshine",
50
+ "@tschk/moonshine-framework",
51
+ "@tschk/moonshine-compiler",
52
+ "@tschk/moonshine-server",
53
+ "@tschk/moonshine-react",
54
+ "@tschk/moonshine-next",
55
+ "@tschk/moonshine-deploy-bun",
56
+ ] as const;
57
+
58
+ function toPosix(p: string): string {
59
+ return p.replaceAll("\\", "/");
60
+ }
61
+
62
+ function ignored(rel: string): boolean {
63
+ return IGNORED.some((dir) => rel === dir || rel.includes(dir));
64
+ }
65
+
66
+ function readJson<T>(path: string): T | undefined {
67
+ if (!existsSync(path)) return undefined;
68
+ try {
69
+ return JSON.parse(readFileSync(path, "utf8")) as T;
70
+ } catch {
71
+ return undefined;
72
+ }
73
+ }
74
+
75
+ function sourceFiles(projectDir: string): string[] {
76
+ const found: string[] = [];
77
+ for (const entry of new Bun.Glob(SOURCE_GLOB).scanSync(projectDir)) {
78
+ const rel = toPosix(entry);
79
+ if (!ignored(rel)) found.push(rel);
80
+ }
81
+ return found.sort();
82
+ }
83
+
84
+ /** Every `next` / `next/*` specifier a source file pulls in. */
85
+ function findNextImports(projectDir: string, files: string[]): NextImport[] {
86
+ const pattern = /["'](next(?:\/[^"']*)?)["']/g;
87
+ const found: NextImport[] = [];
88
+ for (const file of files) {
89
+ const source = readFileSync(join(projectDir, file), "utf8");
90
+ for (const match of source.matchAll(pattern)) {
91
+ const specifier = match[1]!;
92
+ // A bare string is only an import when a module keyword introduces it.
93
+ const before = source.slice(Math.max(0, match.index - 40), match.index);
94
+ if (!/(?:from|import|require)\s*\(?\s*$/.test(before)) continue;
95
+ found.push({
96
+ file,
97
+ specifier,
98
+ aliasable: specifier in nextAliases,
99
+ });
100
+ }
101
+ }
102
+ return found;
103
+ }
104
+
105
+ function detectFramework(
106
+ projectDir: string,
107
+ pkg: { dependencies?: Record<string, string> } | undefined,
108
+ ): { framework: Framework; routesDir?: string; convention?: RouteConvention } {
109
+ for (const dir of ["app", "src/app"]) {
110
+ if (
111
+ existsSync(join(projectDir, dir, "page.tsx")) ||
112
+ existsSync(join(projectDir, dir, "page.jsx")) ||
113
+ existsSync(join(projectDir, dir, "layout.tsx"))
114
+ ) {
115
+ return { framework: "next-app", routesDir: dir, convention: "next-app" };
116
+ }
117
+ }
118
+ for (const dir of ["pages", "src/pages"]) {
119
+ if (existsSync(join(projectDir, dir))) {
120
+ return {
121
+ framework: "next-pages",
122
+ routesDir: dir,
123
+ convention: "next-pages",
124
+ };
125
+ }
126
+ }
127
+ if (
128
+ existsSync(join(projectDir, "vite.config.ts")) ||
129
+ existsSync(join(projectDir, "vite.config.js"))
130
+ ) {
131
+ return { framework: "vite-react" };
132
+ }
133
+ return { framework: pkg?.dependencies?.next ? "next-app" : "unknown" };
134
+ }
135
+
136
+ /** Next conventions present in the tree, named the way the user named them. */
137
+ function findConventions(projectDir: string, files: string[]): string[] {
138
+ const seen: string[] = [];
139
+ for (const candidate of [
140
+ "next.config.js",
141
+ "next.config.mjs",
142
+ "next.config.ts",
143
+ "middleware.ts",
144
+ "middleware.js",
145
+ "src/middleware.ts",
146
+ "instrumentation.ts",
147
+ ]) {
148
+ if (existsSync(join(projectDir, candidate))) seen.push(candidate);
149
+ }
150
+ for (const file of files) {
151
+ const base = file.split("/").pop()!;
152
+ const stem = base.replace(/\.[jt]sx?$/, "");
153
+ if (
154
+ [
155
+ "layout",
156
+ "route",
157
+ "loading",
158
+ "template",
159
+ "not-found",
160
+ "error",
161
+ "default",
162
+ ].includes(stem)
163
+ ) {
164
+ seen.push(file);
165
+ }
166
+ }
167
+ return seen;
168
+ }
169
+
170
+ /** Source-level Next features with no moonshine equivalent yet. */
171
+ function findManualWork(
172
+ projectDir: string,
173
+ files: string[],
174
+ scan: Pick<AdoptScan, "framework" | "routesDir">,
175
+ ): string[] {
176
+ const manual: string[] = [];
177
+ const note = (text: string) => {
178
+ if (!manual.includes(text)) manual.push(text);
179
+ };
180
+
181
+ for (const candidate of [
182
+ "middleware.ts",
183
+ "middleware.js",
184
+ "src/middleware.ts",
185
+ ]) {
186
+ if (existsSync(join(projectDir, candidate))) {
187
+ note(
188
+ `${candidate}: Next middleware does not run. Moonshine has no edge middleware phase — port it to a route loader or a Bun server wrapper.`,
189
+ );
190
+ }
191
+ }
192
+ for (const candidate of [
193
+ "next.config.js",
194
+ "next.config.mjs",
195
+ "next.config.ts",
196
+ ]) {
197
+ if (existsSync(join(projectDir, candidate))) {
198
+ note(
199
+ `${candidate}: not read. redirects/rewrites/headers/images/webpack options are all ignored.`,
200
+ );
201
+ }
202
+ }
203
+
204
+ for (const file of files) {
205
+ const source = readFileSync(join(projectDir, file), "utf8");
206
+ const stem = file
207
+ .split("/")
208
+ .pop()!
209
+ .replace(/\.[jt]sx?$/, "");
210
+
211
+ if (
212
+ /export\s+(?:const|async\s+function|function)\s+generateMetadata/.test(
213
+ source,
214
+ )
215
+ ) {
216
+ note(
217
+ `${file}: generateMetadata() is not called. Moonshine emits its own <head>; move tags into a layout.`,
218
+ );
219
+ } else if (/export\s+const\s+metadata\b/.test(source)) {
220
+ note(
221
+ `${file}: the metadata export is not read. Moonshine emits its own <head>; move tags into a layout.`,
222
+ );
223
+ }
224
+ if (/export\s+const\s+revalidate\b/.test(source)) {
225
+ note(`${file}: ISR (export const revalidate) is not implemented.`);
226
+ }
227
+ if (/^\s*["']use server["']/m.test(source)) {
228
+ note(`${file}: server actions ("use server") are not supported.`);
229
+ }
230
+ if (/export\s+default\s+async\s+function/.test(source) && stem === "page") {
231
+ note(
232
+ `${file}: async server component. Moonshine renders with react-dom/server, which cannot await a component — move the fetch into a loader.`,
233
+ );
234
+ }
235
+ if (stem === "layout" && /<html\b/.test(source)) {
236
+ note(
237
+ `${file}: returns <html>/<body>, but moonshine already emits the document shell. Return a fragment instead.`,
238
+ );
239
+ }
240
+ if (["loading", "template", "not-found", "default"].includes(stem)) {
241
+ note(`${file}: ${stem}.tsx has no moonshine equivalent and is ignored.`);
242
+ }
243
+ if (/getServerSideProps|getStaticProps|getStaticPaths/.test(source)) {
244
+ note(
245
+ `${file}: getServerSideProps/getStaticProps are not called. Rename to a moonshine loader.`,
246
+ );
247
+ }
248
+ }
249
+
250
+ if (scan.routesDir) {
251
+ for (const file of files) {
252
+ if (!file.startsWith(`${scan.routesDir}/`)) continue;
253
+ const segments = file.split("/");
254
+ if (segments.some((s) => s.startsWith("@"))) {
255
+ note(`${file}: parallel routes (@slot) are dropped.`);
256
+ }
257
+ if (segments.some((s) => /^\(\.+\)/.test(s))) {
258
+ note(`${file}: intercepting routes are dropped.`);
259
+ }
260
+ }
261
+ }
262
+
263
+ return manual;
264
+ }
265
+
266
+ /** Behavioural gaps in the reimplementations the app actually imports. */
267
+ const ALIAS_CAVEATS: Readonly<Record<string, string>> = {
268
+ "next/image":
269
+ "next/image renders a plain <img>: no resizing, no AVIF/WebP negotiation, no blur placeholder.",
270
+ "next/link":
271
+ "next/link navigates through the moonshine router; prefetch is a browser <link rel=prefetch> hint, not an RSC payload warm-up.",
272
+ "next/headers":
273
+ "next/headers reads the moonshine request context; cookie mutations do not propagate to the response.",
274
+ "next/font/google":
275
+ "next/font/google emits a Google Fonts <link> instead of self-hosting; call fontLinks() in your layout head or the family never loads.",
276
+ "next/dynamic":
277
+ "next/dynamic lazy-loads on the client only; `ssr: false` is the effective behaviour either way.",
278
+ };
279
+
280
+ export async function scanProject(projectDir: string): Promise<AdoptScan> {
281
+ const dir = resolve(projectDir);
282
+ const pkg = readJson<{ dependencies?: Record<string, string> }>(
283
+ join(dir, "package.json"),
284
+ );
285
+ const files = sourceFiles(dir);
286
+ const detected = detectFramework(dir, pkg);
287
+ const imports = findNextImports(dir, files);
288
+
289
+ const routes: { path: string; file: string }[] = [];
290
+ if (detected.routesDir && detected.convention) {
291
+ const { discoverRoutes } = await import("@tschk/moonshine-compiler");
292
+ const discovered = await discoverRoutes({
293
+ routesDir: join(dir, detected.routesDir),
294
+ convention: detected.convention,
295
+ });
296
+ for (const route of discovered) {
297
+ routes.push({
298
+ path: route.path,
299
+ file: toPosix(relative(dir, route.file)),
300
+ });
301
+ }
302
+ }
303
+
304
+ return {
305
+ projectDir: dir,
306
+ framework: detected.framework,
307
+ ...(detected.routesDir && { routesDir: detected.routesDir }),
308
+ ...(detected.convention && { convention: detected.convention }),
309
+ routes,
310
+ imports,
311
+ conventions: findConventions(dir, files),
312
+ manual: [
313
+ ...findManualWork(dir, files, detected),
314
+ ...[...new Set(imports.map((i) => i.specifier))]
315
+ .sort()
316
+ .map((s) => ALIAS_CAVEATS[s])
317
+ .filter((note): note is string => note !== undefined),
318
+ ],
319
+ };
320
+ }
321
+
322
+ /**
323
+ * Where the project will find `@tschk/moonshine-next` on disk. Only installed
324
+ * `node_modules` trees count: adopt normally runs before `bun install`, and
325
+ * `Bun.resolveSync` would then answer with whatever version happens to sit in
326
+ * the global module cache — a copy that can predate the adapter's current
327
+ * surface, leaving specifiers pointing at files that do not exist.
328
+ */
329
+ function adapterDir(projectDir: string): string {
330
+ let dir = projectDir;
331
+ for (;;) {
332
+ const candidate = join(dir, "node_modules", "@tschk", "moonshine-next");
333
+ if (existsSync(candidate)) return candidate;
334
+ const parent = dirname(dir);
335
+ if (parent === dir) break;
336
+ dir = parent;
337
+ }
338
+ return join(projectDir, "node_modules", "@tschk", "moonshine-next");
339
+ }
340
+
341
+ /**
342
+ * `compilerOptions.paths` entries pointing every aliasable `next/*` specifier
343
+ * at a real file. Bun applies tsconfig paths in both `bun run` and `Bun.build`,
344
+ * but only for relative targets — a bare package specifier is not remapped.
345
+ */
346
+ export function aliasPaths(projectDir: string): Record<string, string[]> {
347
+ const pkgDir = adapterDir(projectDir);
348
+ const srcDir = dirname(resolveAlias("next/link")!);
349
+ const paths: Record<string, string[]> = {};
350
+ for (const specifier of Object.keys(nextAliases)) {
351
+ const source = resolveAlias(specifier);
352
+ if (!source) continue;
353
+ const file = join(pkgDir, "src", relative(srcDir, source));
354
+ const rel = toPosix(relative(projectDir, file));
355
+ paths[specifier] = [rel.startsWith(".") ? rel : `./${rel}`];
356
+ }
357
+ return paths;
358
+ }
359
+
360
+ function planTsconfig(scan: AdoptScan): AdoptChange {
361
+ const path = join(scan.projectDir, "tsconfig.json");
362
+ const existing =
363
+ readJson<{ compilerOptions?: Record<string, unknown> }>(path) ?? {};
364
+ const compilerOptions = { ...existing.compilerOptions };
365
+ const previous = (compilerOptions.paths ?? {}) as Record<string, string[]>;
366
+ const wanted = aliasPaths(scan.projectDir);
367
+ const paths = { ...previous, ...wanted };
368
+ compilerOptions.baseUrl = compilerOptions.baseUrl ?? ".";
369
+ compilerOptions.jsx = compilerOptions.jsx ?? "react-jsx";
370
+ compilerOptions.paths = paths;
371
+
372
+ const alreadyApplied = Object.entries(wanted).every(
373
+ ([key, value]) => previous[key]?.[0] === value[0],
374
+ );
375
+
376
+ return {
377
+ file: "tsconfig.json",
378
+ summary: alreadyApplied
379
+ ? `already aliases ${Object.keys(wanted).length} next/* specifiers`
380
+ : `aliases ${Object.keys(wanted).length} next/* specifiers to @tschk/moonshine-next`,
381
+ alreadyApplied,
382
+ contents: JSON.stringify({ ...existing, compilerOptions }, null, 2) + "\n",
383
+ };
384
+ }
385
+
386
+ function planConfig(scan: AdoptScan, force: boolean): AdoptChange {
387
+ const path = join(scan.projectDir, "moonshine.config.ts");
388
+ const exists = existsSync(path);
389
+ const entries: Record<string, unknown> = {
390
+ runtime: "bun",
391
+ adapter: "bun",
392
+ renderer: "react",
393
+ ...(scan.routesDir && { routesDir: scan.routesDir }),
394
+ ...(scan.convention && { convention: scan.convention }),
395
+ };
396
+ const contents = `import { defineConfig } from "@tschk/moonshine-framework";
397
+
398
+ export default defineConfig(${JSON.stringify(entries, null, 2)});
399
+ `;
400
+ const current = exists ? readFileSync(path, "utf8") : "";
401
+ const alreadyApplied = exists && (current === contents || !force);
402
+ return {
403
+ file: "moonshine.config.ts",
404
+ summary: alreadyApplied
405
+ ? "already present, left untouched"
406
+ : `${exists ? "rewritten" : "created"} (routesDir ${scan.routesDir ?? "src/routes"}, convention ${scan.convention ?? "moonshine"})`,
407
+ alreadyApplied,
408
+ ...(alreadyApplied ? {} : { contents }),
409
+ };
410
+ }
411
+
412
+ function planPackageJson(scan: AdoptScan): AdoptChange {
413
+ const path = join(scan.projectDir, "package.json");
414
+ const pkg =
415
+ readJson<{
416
+ dependencies?: Record<string, string>;
417
+ scripts?: Record<string, string>;
418
+ }>(path) ?? {};
419
+ const root = detectMoonshineRoot();
420
+ const version = `^${cliVersion()}`;
421
+
422
+ const dependencies = { ...pkg.dependencies };
423
+ const added: string[] = [];
424
+ for (const name of RUNTIME_DEPS) {
425
+ if (dependencies[name]) continue;
426
+ const spec = packagePath(name, root, version);
427
+ if (!spec) continue;
428
+ dependencies[name] = spec;
429
+ added.push(name);
430
+ }
431
+
432
+ const scripts = { ...pkg.scripts };
433
+ const repointed: string[] = [];
434
+ const mapping: Record<string, string> = {
435
+ dev: "moonshine dev",
436
+ build: "moonshine build",
437
+ start: "moonshine preview",
438
+ };
439
+ for (const [key, value] of Object.entries(mapping)) {
440
+ const current = scripts[key];
441
+ if (current !== undefined && !/^next(\s|$)/.test(current)) continue;
442
+ if (current === value) continue;
443
+ scripts[key] = value;
444
+ repointed.push(key);
445
+ }
446
+
447
+ const alreadyApplied = added.length === 0 && repointed.length === 0;
448
+ const parts: string[] = [];
449
+ if (added.length) parts.push(`+${added.length} dependencies`);
450
+ if (repointed.length)
451
+ parts.push(`scripts ${repointed.join(", ")} → moonshine`);
452
+
453
+ return {
454
+ file: "package.json",
455
+ summary: alreadyApplied ? "already adopted" : parts.join(", "),
456
+ alreadyApplied,
457
+ contents: JSON.stringify({ ...pkg, dependencies, scripts }, null, 2) + "\n",
458
+ };
459
+ }
460
+
461
+ function cliVersion(): string {
462
+ const pkg = readJson<{ version?: string }>(
463
+ join(import.meta.dir, "..", "package.json"),
464
+ );
465
+ return pkg?.version ?? "0.3.2";
466
+ }
467
+
468
+ export async function planAdoption(
469
+ projectDir: string,
470
+ options: { force?: boolean } = {},
471
+ ): Promise<AdoptPlan> {
472
+ const scan = await scanProject(projectDir);
473
+ return {
474
+ scan,
475
+ changes: [
476
+ planTsconfig(scan),
477
+ planConfig(scan, options.force ?? false),
478
+ planPackageJson(scan),
479
+ ],
480
+ // Aliasing covers every specifier the adapter implements, so nothing in the
481
+ // user's source is edited. Unaliasable specifiers are reported, not rewritten,
482
+ // because there is no moonshine implementation to rewrite them to.
483
+ rewritten: [],
484
+ };
485
+ }
486
+
487
+ export function applyPlan(plan: AdoptPlan): void {
488
+ for (const change of plan.changes) {
489
+ if (change.contents === undefined) continue;
490
+ writeFileSync(join(plan.scan.projectDir, change.file), change.contents);
491
+ }
492
+ }
493
+
494
+ function pluralize(n: number, word: string): string {
495
+ return `${n} ${word}${n === 1 ? "" : "s"}`;
496
+ }
497
+
498
+ export function formatReport(plan: AdoptPlan, dryRun: boolean): string {
499
+ const { scan } = plan;
500
+ const lines: string[] = [];
501
+ const push = (text = "") => lines.push(text);
502
+
503
+ push(`moonshine adopt — ${scan.projectDir}${dryRun ? " (dry run)" : ""}`);
504
+ push();
505
+ push("SCAN");
506
+ push(` framework ${scan.framework}`);
507
+ push(` routes dir ${scan.routesDir ?? "(none found)"}`);
508
+ push(` routes ${scan.routes.length}`);
509
+ for (const route of scan.routes.slice(0, 12)) {
510
+ push(` ${route.path.padEnd(24)} ${route.file}`);
511
+ }
512
+ if (scan.routes.length > 12) push(` … ${scan.routes.length - 12} more`);
513
+
514
+ const bySpecifier = new Map<string, NextImport[]>();
515
+ for (const imp of scan.imports) {
516
+ const list = bySpecifier.get(imp.specifier) ?? [];
517
+ list.push(imp);
518
+ bySpecifier.set(imp.specifier, list);
519
+ }
520
+ push(
521
+ ` next/* imports ${scan.imports.length} across ${new Set(scan.imports.map((i) => i.file)).size} files`,
522
+ );
523
+ for (const [specifier, list] of [...bySpecifier].sort()) {
524
+ const mark = list[0]!.aliasable ? "alias" : "NO IMPL";
525
+ push(
526
+ ` ${specifier.padEnd(24)} ${mark.padEnd(8)} ${list.map((l) => l.file).join(", ")}`,
527
+ );
528
+ }
529
+ if (scan.conventions.length) {
530
+ push(` conventions ${scan.conventions.join(", ")}`);
531
+ }
532
+
533
+ push();
534
+ push(dryRun ? "REWRITE (planned)" : "REWRITE");
535
+ for (const change of plan.changes) {
536
+ const mark = change.alreadyApplied ? "no-op" : dryRun ? "would" : "wrote";
537
+ push(` ${mark.padEnd(6)} ${change.file.padEnd(22)} ${change.summary}`);
538
+ }
539
+
540
+ const aliased = scan.imports.filter((i) => i.aliasable);
541
+ const unaliasable = scan.imports.filter((i) => !i.aliasable);
542
+
543
+ push();
544
+ push("SCORECARD");
545
+ push(
546
+ ` aliased ${pluralize(aliased.length, "import")} across ${pluralize(new Set(aliased.map((i) => i.file)).size, "file")} — 0 source files edited`,
547
+ );
548
+ push(` rewritten ${pluralize(plan.rewritten.length, "source file")}`);
549
+ for (const file of plan.rewritten) push(` ${file}`);
550
+
551
+ const blockers = [
552
+ ...unaliasable.map(
553
+ (i) =>
554
+ `${i.file}: imports ${i.specifier}, which @tschk/moonshine-next does not implement. This import will not resolve.`,
555
+ ),
556
+ ...scan.manual,
557
+ ];
558
+ push(` cannot automate ${blockers.length}`);
559
+ for (const item of blockers) push(` - ${item}`);
560
+
561
+ push();
562
+ if (dryRun) {
563
+ push("Nothing was written. Drop --dry-run to apply.");
564
+ } else {
565
+ push("Next:");
566
+ push(" bun install");
567
+ push(" bunx moonshine build && bunx moonshine preview");
568
+ }
569
+ return lines.join("\n");
570
+ }
571
+
572
+ export async function adoptCommand(args: string[]): Promise<AdoptPlan> {
573
+ let projectDir = "";
574
+ let dryRun = false;
575
+ let force = false;
576
+ for (let i = 0; i < args.length; i++) {
577
+ const arg = args[i]!;
578
+ if (arg === "--dry-run") dryRun = true;
579
+ else if (arg === "--force") force = true;
580
+ else if (arg.startsWith("-")) {
581
+ console.error(`Unknown flag: ${arg}`);
582
+ process.exit(1);
583
+ } else if (!projectDir) {
584
+ projectDir = arg;
585
+ } else {
586
+ console.error(`Unknown flag: ${arg}`);
587
+ process.exit(1);
588
+ }
589
+ }
590
+
591
+ const dir = resolve(projectDir || process.cwd());
592
+ if (!existsSync(join(dir, "package.json"))) {
593
+ console.error(`No package.json in ${dir} — nothing to adopt.`);
594
+ process.exit(1);
595
+ }
596
+
597
+ const plan = await planAdoption(dir, { force });
598
+ if (plan.scan.framework === "unknown") {
599
+ console.error(
600
+ `Could not identify a Next or React app in ${dir}. Expected app/, pages/, or a vite config.`,
601
+ );
602
+ process.exit(1);
603
+ }
604
+ if (!dryRun) applyPlan(plan);
605
+ console.log(formatReport(plan, dryRun));
606
+ return plan;
607
+ }
package/src/build.ts CHANGED
@@ -51,6 +51,10 @@ export async function buildCommand(args: string[]): Promise<MoonshineManifest> {
51
51
  const manifest = await buildProject({
52
52
  projectDir: resolvedDir,
53
53
  runtime,
54
+ ...(config.routesDir && {
55
+ routesDir: resolve(resolvedDir, config.routesDir),
56
+ }),
57
+ ...(config.convention && { convention: config.convention }),
54
58
  });
55
59
 
56
60
  const outDir = resolve(resolvedDir, ".moonshine");
package/src/config.ts CHANGED
@@ -2,6 +2,7 @@ import { existsSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { defineConfig as baseDefineConfig } from "@tschk/moonshine-framework";
5
+ import type { RouteConvention } from "@tschk/moonshine-compiler";
5
6
  import type {
6
7
  MoonshineConfig,
7
8
  RouteDefinition,
@@ -13,6 +14,10 @@ export type MoonshineCliConfig = MoonshineConfig & {
13
14
  adapter?: "bun" | "node" | "cloudflare" | "vercel";
14
15
  renderer?: RendererName;
15
16
  routes?: RouteDefinition[];
17
+ /** Route directory, relative to the project. Defaults to `src/routes`. */
18
+ routesDir?: string;
19
+ /** File-system routing dialect; `moonshine adopt` sets the `next-*` values. */
20
+ convention?: RouteConvention;
16
21
  };
17
22
 
18
23
  export function defineConfig<T extends MoonshineCliConfig>(config: T): T {
package/src/new.ts CHANGED
@@ -4,7 +4,7 @@ import { join, resolve } from "node:path";
4
4
  type Renderer = "react" | "solid" | "crepus";
5
5
  type Adapter = "bun" | "node" | "cloudflare" | "vercel";
6
6
 
7
- function detectMoonshineRoot(): string | null {
7
+ export function detectMoonshineRoot(): string | null {
8
8
  if (process.env.MOONSHINE_PATH) return resolve(process.env.MOONSHINE_PATH);
9
9
  let dir = process.cwd();
10
10
  for (let i = 0; i < 8; i++) {
@@ -25,9 +25,14 @@ function dep(root: string | null, rel: string, version = "^0.2.0"): string {
25
25
  return root ? `file:${join(root, rel)}` : version;
26
26
  }
27
27
 
28
- function packagePath(name: string, root: string | null): string | undefined {
28
+ export function packagePath(
29
+ name: string,
30
+ root: string | null,
31
+ version = "^0.2.0",
32
+ ): string | undefined {
29
33
  const map: Record<string, string> = {
30
34
  "@tschk/moonshine": "packages/core",
35
+ "@tschk/moonshine-next": "packages/adapter-next",
31
36
  "@tschk/moonshine-framework": "packages/framework",
32
37
  "@tschk/moonshine-compiler": "packages/compiler",
33
38
  "@tschk/moonshine-server": "packages/server",
@@ -40,7 +45,7 @@ function packagePath(name: string, root: string | null): string | undefined {
40
45
  "@tschk/moonshine-deploy-vercel": "packages/deploy-vercel",
41
46
  };
42
47
  const rel = map[name];
43
- return rel ? dep(root, rel) : undefined;
48
+ return rel ? dep(root, rel, version) : undefined;
44
49
  }
45
50
 
46
51
  function runtimeForAdapter(adapter: Adapter): string {