@tschk/moonshine-cli 0.3.7 → 0.4.1
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/package.json +12 -12
- package/src/adopt/conventions.ts +39 -0
- package/src/adopt/frameworks.ts +155 -0
- package/src/adopt/gaps.ts +188 -0
- package/src/adopt/plan.ts +232 -0
- package/src/adopt/project.ts +71 -0
- package/src/adopt/report.ts +167 -0
- package/src/adopt/scan.ts +282 -0
- package/src/adopt/templates.ts +180 -0
- package/src/adopt/types.ts +66 -0
- package/src/adopt.ts +42 -1237
- package/src/compile.ts +18 -9
- package/src/config.ts +1 -1
- package/src/new.ts +112 -102
- package/src/preview.ts +18 -4
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** One scan of a project directory, composed from the pieces around it. */
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { join, relative, resolve } from "node:path";
|
|
4
|
+
import { adapterFor, templateGlobs } from "./frameworks.js";
|
|
5
|
+
import type { AdoptScan } from "./types.js";
|
|
6
|
+
import {
|
|
7
|
+
detectFramework,
|
|
8
|
+
findHostImports,
|
|
9
|
+
readJson,
|
|
10
|
+
sourceFiles,
|
|
11
|
+
toPosix,
|
|
12
|
+
type PackageJson,
|
|
13
|
+
} from "./scan.js";
|
|
14
|
+
import { compileTemplates } from "./templates.js";
|
|
15
|
+
import { findConventions } from "./conventions.js";
|
|
16
|
+
import { ALIAS_CAVEATS, findManualWork, templateManualWork } from "./gaps.js";
|
|
17
|
+
|
|
18
|
+
export async function scanProject(projectDir: string): Promise<AdoptScan> {
|
|
19
|
+
const dir = resolve(projectDir);
|
|
20
|
+
const pkg = readJson<PackageJson>(join(dir, "package.json"));
|
|
21
|
+
const files = sourceFiles(dir);
|
|
22
|
+
const detected = detectFramework(dir, pkg);
|
|
23
|
+
const imports = await findHostImports(
|
|
24
|
+
dir,
|
|
25
|
+
files,
|
|
26
|
+
adapterFor(detected.framework),
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
const globs = templateGlobs(detected.framework);
|
|
30
|
+
const templates = globs
|
|
31
|
+
? await compileTemplates(dir, detected.framework, globs)
|
|
32
|
+
: [];
|
|
33
|
+
|
|
34
|
+
const routes: { path: string; file: string }[] = [];
|
|
35
|
+
if (
|
|
36
|
+
detected.routesDir &&
|
|
37
|
+
detected.convention &&
|
|
38
|
+
existsSync(join(dir, detected.routesDir))
|
|
39
|
+
) {
|
|
40
|
+
const { discoverRoutes } = await import("@tschk/moonshine-compiler");
|
|
41
|
+
const discovered = await discoverRoutes({
|
|
42
|
+
routesDir: join(dir, detected.routesDir),
|
|
43
|
+
convention: detected.convention,
|
|
44
|
+
});
|
|
45
|
+
for (const route of discovered) {
|
|
46
|
+
routes.push({
|
|
47
|
+
path: route.path,
|
|
48
|
+
file: toPosix(relative(dir, route.file)),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
projectDir: dir,
|
|
55
|
+
framework: detected.framework,
|
|
56
|
+
...(detected.routesDir && { routesDir: detected.routesDir }),
|
|
57
|
+
...(detected.convention && { convention: detected.convention }),
|
|
58
|
+
routes,
|
|
59
|
+
templates,
|
|
60
|
+
imports,
|
|
61
|
+
conventions: findConventions(dir, files),
|
|
62
|
+
manual: [
|
|
63
|
+
...templateManualWork(detected.framework, templates),
|
|
64
|
+
...(await findManualWork(dir, files, detected)),
|
|
65
|
+
...[...new Set(imports.map((i) => i.specifier))]
|
|
66
|
+
.sort()
|
|
67
|
+
.map((s) => ALIAS_CAVEATS[s])
|
|
68
|
+
.filter((note): note is string => note !== undefined),
|
|
69
|
+
],
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/** How a plan is shown, and confirmed. */
|
|
2
|
+
import { adapterFor } from "./frameworks.js";
|
|
3
|
+
import type { AdoptPlan, NextImport } from "./types.js";
|
|
4
|
+
import { truncate, warningBar, type Tui } from "../tui.js";
|
|
5
|
+
|
|
6
|
+
function pluralize(n: number, word: string): string {
|
|
7
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function formatReport(plan: AdoptPlan, dryRun: boolean): string {
|
|
11
|
+
const { scan } = plan;
|
|
12
|
+
const lines: string[] = [];
|
|
13
|
+
const push = (text = "") => lines.push(text);
|
|
14
|
+
|
|
15
|
+
push(`moonshine adopt — ${scan.projectDir}${dryRun ? " (dry run)" : ""}`);
|
|
16
|
+
push();
|
|
17
|
+
push("SCAN");
|
|
18
|
+
push(` framework ${scan.framework}`);
|
|
19
|
+
push(` routes dir ${scan.routesDir ?? "(none found)"}`);
|
|
20
|
+
push(` routes ${scan.routes.length}`);
|
|
21
|
+
for (const route of scan.routes.slice(0, 12)) {
|
|
22
|
+
push(` ${route.path.padEnd(24)} ${route.file}`);
|
|
23
|
+
}
|
|
24
|
+
if (scan.routes.length > 12) push(` … ${scan.routes.length - 12} more`);
|
|
25
|
+
|
|
26
|
+
if (scan.templates.length) {
|
|
27
|
+
const ok = scan.templates.filter((t) => t.ok);
|
|
28
|
+
push(
|
|
29
|
+
` templates ${ok.length}/${scan.templates.length} compiled to View IR`,
|
|
30
|
+
);
|
|
31
|
+
for (const template of scan.templates) {
|
|
32
|
+
const mark = template.ok
|
|
33
|
+
? template.route
|
|
34
|
+
? "route"
|
|
35
|
+
: "no url"
|
|
36
|
+
: "FAILED";
|
|
37
|
+
push(
|
|
38
|
+
` ${template.file.padEnd(34)} ${mark.padEnd(7)} ${template.ok ? `${template.nodes} nodes${template.route ? ` → ${template.route}` : ""}` : template.error}`,
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const bySpecifier = new Map<string, NextImport[]>();
|
|
44
|
+
for (const imp of scan.imports) {
|
|
45
|
+
const list = bySpecifier.get(imp.specifier) ?? [];
|
|
46
|
+
list.push(imp);
|
|
47
|
+
bySpecifier.set(imp.specifier, list);
|
|
48
|
+
}
|
|
49
|
+
if (adapterFor(scan.framework)) {
|
|
50
|
+
push(
|
|
51
|
+
` host imports ${scan.imports.length} across ${new Set(scan.imports.map((i) => i.file)).size} files`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
for (const [specifier, list] of [...bySpecifier].sort()) {
|
|
55
|
+
const mark = list[0]!.aliasable ? "alias" : "NO IMPL";
|
|
56
|
+
push(
|
|
57
|
+
` ${specifier.padEnd(24)} ${mark.padEnd(8)} ${list.map((l) => l.file).join(", ")}`,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
if (scan.conventions.length) {
|
|
61
|
+
push(` conventions ${scan.conventions.join(", ")}`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
push();
|
|
65
|
+
push(dryRun ? "REWRITE (planned)" : "REWRITE");
|
|
66
|
+
const column = Math.max(...plan.changes.map((c) => c.file.length), 18);
|
|
67
|
+
for (const change of plan.changes) {
|
|
68
|
+
const mark = change.alreadyApplied ? "no-op" : dryRun ? "would" : "wrote";
|
|
69
|
+
push(` ${mark.padEnd(6)} ${change.file.padEnd(column)} ${change.summary}`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const aliased = scan.imports.filter((i) => i.aliasable);
|
|
73
|
+
const unaliasable = scan.imports.filter((i) => !i.aliasable);
|
|
74
|
+
|
|
75
|
+
push();
|
|
76
|
+
push("SCORECARD");
|
|
77
|
+
if (adapterFor(scan.framework)) {
|
|
78
|
+
push(
|
|
79
|
+
` aliased ${pluralize(aliased.length, "import")} across ${pluralize(new Set(aliased.map((i) => i.file)).size, "file")} — 0 source files edited`,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
if (scan.templates.length) {
|
|
83
|
+
const ok = scan.templates.filter((t) => t.ok);
|
|
84
|
+
push(
|
|
85
|
+
` compiled ${pluralize(ok.length, "template")}, ${pluralize(ok.filter((t) => t.route).length, "route")} mounted, ${scan.templates.length - ok.length} failed — 0 source files edited`,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
push(` rewritten ${pluralize(plan.rewritten.length, "source file")}`);
|
|
89
|
+
for (const file of plan.rewritten) push(` ${file}`);
|
|
90
|
+
|
|
91
|
+
const blockers = [
|
|
92
|
+
...unaliasable.map(
|
|
93
|
+
(i) =>
|
|
94
|
+
`${i.file}: imports ${i.specifier}, which @tschk/moonshine-next does not implement. This import will not resolve.`,
|
|
95
|
+
),
|
|
96
|
+
...scan.manual,
|
|
97
|
+
];
|
|
98
|
+
push(` cannot automate ${blockers.length}`);
|
|
99
|
+
for (const item of blockers) push(` - ${item}`);
|
|
100
|
+
|
|
101
|
+
push();
|
|
102
|
+
if (dryRun) {
|
|
103
|
+
push("Nothing was written. Drop --dry-run to apply.");
|
|
104
|
+
} else {
|
|
105
|
+
push("Next:");
|
|
106
|
+
push(" bun install");
|
|
107
|
+
push(" bunx moonshine build && bunx moonshine preview");
|
|
108
|
+
}
|
|
109
|
+
return lines.join("\n");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Every file the run would touch, with the exact keys and values it adds, so
|
|
114
|
+
* the answer to the prompt is informed rather than hopeful.
|
|
115
|
+
*/
|
|
116
|
+
export function formatPlan(
|
|
117
|
+
plan: AdoptPlan,
|
|
118
|
+
tui: Pick<Tui, "isTTY" | "columns">,
|
|
119
|
+
): string {
|
|
120
|
+
const width = tui.columns;
|
|
121
|
+
const lines: string[] = [];
|
|
122
|
+
lines.push(truncate("moonshine adopt will modify", width));
|
|
123
|
+
lines.push(truncate(` ${plan.scan.projectDir}`, width));
|
|
124
|
+
lines.push("");
|
|
125
|
+
for (const change of plan.changes) {
|
|
126
|
+
const verb =
|
|
127
|
+
change.action === "none"
|
|
128
|
+
? "unchanged"
|
|
129
|
+
: change.action === "create"
|
|
130
|
+
? "create"
|
|
131
|
+
: "modify";
|
|
132
|
+
lines.push(truncate(` ${verb.padEnd(9)} ${change.file}`, width));
|
|
133
|
+
for (const detail of change.details) {
|
|
134
|
+
lines.push(truncate(` + ${detail}`, width));
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
lines.push("");
|
|
138
|
+
lines.push(
|
|
139
|
+
warningBar(
|
|
140
|
+
"DESTRUCTIVE: these files are rewritten in place. Back up or commit first.",
|
|
141
|
+
tui,
|
|
142
|
+
),
|
|
143
|
+
);
|
|
144
|
+
return lines.join("\n");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Ask before writing. Without a TTY there is nobody to ask, so the run stops
|
|
149
|
+
* and points at `--yes` instead of blocking forever on a prompt.
|
|
150
|
+
*/
|
|
151
|
+
export async function confirmPlan(
|
|
152
|
+
plan: AdoptPlan,
|
|
153
|
+
tui: Tui,
|
|
154
|
+
): Promise<{ ok: boolean; message?: string }> {
|
|
155
|
+
tui.write(`${formatPlan(plan, tui)}\n`);
|
|
156
|
+
if (!tui.isTTY) {
|
|
157
|
+
return {
|
|
158
|
+
ok: false,
|
|
159
|
+
message:
|
|
160
|
+
"Not a terminal, so there is nothing to confirm with. Re-run with --yes to apply, or --dry-run to inspect.",
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
const answer = (await tui.prompt("Apply these changes? [y/N] ")).trim();
|
|
164
|
+
return /^y(es)?$/i.test(answer)
|
|
165
|
+
? { ok: true }
|
|
166
|
+
: { ok: false, message: "Aborted. Nothing was written." };
|
|
167
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/** What is on disk: source files, host imports, and which framework this is. */
|
|
2
|
+
import type { RouteConvention } from "@tschk/moonshine-compiler";
|
|
3
|
+
import { existsSync, readFileSync, promises as fsPromises } from "node:fs";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
templateGlobs,
|
|
7
|
+
type Framework,
|
|
8
|
+
type HostAdapter,
|
|
9
|
+
} from "./frameworks.js";
|
|
10
|
+
import type { NextImport } from "./types.js";
|
|
11
|
+
|
|
12
|
+
const SOURCE_GLOB = "**/*.{ts,tsx,js,jsx,mjs}";
|
|
13
|
+
const IGNORED = ["node_modules/", ".next/", ".moonshine/", "dist/", "build/"];
|
|
14
|
+
|
|
15
|
+
export const RUNTIME_DEPS = [
|
|
16
|
+
"@tschk/moonshine",
|
|
17
|
+
"@tschk/moonshine-framework",
|
|
18
|
+
"@tschk/moonshine-compiler",
|
|
19
|
+
"@tschk/moonshine-server",
|
|
20
|
+
"@tschk/moonshine-react",
|
|
21
|
+
"@tschk/moonshine-deploy-bun",
|
|
22
|
+
] as const;
|
|
23
|
+
|
|
24
|
+
export function toPosix(p: string): string {
|
|
25
|
+
return p.replaceAll("\\", "/");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function ignored(rel: string): boolean {
|
|
29
|
+
return IGNORED.some((dir) => rel === dir || rel.includes(dir));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function readJson<T>(path: string): T | undefined {
|
|
33
|
+
if (!existsSync(path)) return undefined;
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(readFileSync(path, "utf8")) as T;
|
|
36
|
+
} catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function sourceFiles(projectDir: string): string[] {
|
|
42
|
+
const found: string[] = [];
|
|
43
|
+
for (const entry of new Bun.Glob(SOURCE_GLOB).scanSync(projectDir)) {
|
|
44
|
+
const rel = toPosix(entry);
|
|
45
|
+
if (!ignored(rel)) found.push(rel);
|
|
46
|
+
}
|
|
47
|
+
return found.sort();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Every host specifier (`next/*`, `react-router`, …) a source file pulls in. */
|
|
51
|
+
export async function findHostImports(
|
|
52
|
+
projectDir: string,
|
|
53
|
+
files: string[],
|
|
54
|
+
adapter: HostAdapter | undefined,
|
|
55
|
+
): Promise<NextImport[]> {
|
|
56
|
+
if (!adapter) return [];
|
|
57
|
+
const pattern = /["']([^"']+)["']/g;
|
|
58
|
+
|
|
59
|
+
const results = await Promise.all(
|
|
60
|
+
files.map(async (file) => {
|
|
61
|
+
const source = await fsPromises.readFile(join(projectDir, file), "utf8");
|
|
62
|
+
const found: NextImport[] = [];
|
|
63
|
+
for (const match of source.matchAll(pattern)) {
|
|
64
|
+
const specifier = match[1]!;
|
|
65
|
+
if (!adapter.imports.test(specifier)) continue;
|
|
66
|
+
// A bare string is only an import when a module keyword introduces it.
|
|
67
|
+
const before = source.slice(Math.max(0, match.index - 40), match.index);
|
|
68
|
+
if (!/(?:from|import|require)\s*\(?\s*$/.test(before)) continue;
|
|
69
|
+
found.push({
|
|
70
|
+
file,
|
|
71
|
+
specifier,
|
|
72
|
+
aliasable: specifier in adapter.aliases,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return found;
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
return results.flat();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type PackageJson = {
|
|
83
|
+
name?: string;
|
|
84
|
+
workspaces?: unknown;
|
|
85
|
+
dependencies?: Record<string, string>;
|
|
86
|
+
devDependencies?: Record<string, string>;
|
|
87
|
+
scripts?: Record<string, string>;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const LOCKFILES = [
|
|
91
|
+
"bun.lock",
|
|
92
|
+
"bun.lockb",
|
|
93
|
+
"package-lock.json",
|
|
94
|
+
"pnpm-lock.yaml",
|
|
95
|
+
"yarn.lock",
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
export function hasLockfile(dir: string): boolean {
|
|
99
|
+
return LOCKFILES.some((name) => existsSync(join(dir, name)));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function allDeps(pkg: PackageJson | undefined): Record<string, string> {
|
|
103
|
+
return { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Where `moonshine adopt` writes the route modules it generates from templates. */
|
|
107
|
+
export const GENERATED_ROUTES = "moonshine/routes";
|
|
108
|
+
|
|
109
|
+
/** Where compiled-but-unrouted templates land, importable but not mounted. */
|
|
110
|
+
export const GENERATED_COMPONENTS = "moonshine/components";
|
|
111
|
+
|
|
112
|
+
export function templateFiles(
|
|
113
|
+
projectDir: string,
|
|
114
|
+
globs: readonly string[],
|
|
115
|
+
): string[] {
|
|
116
|
+
const found = new Set<string>();
|
|
117
|
+
for (const glob of globs) {
|
|
118
|
+
for (const entry of new Bun.Glob(glob).scanSync(projectDir)) {
|
|
119
|
+
const rel = toPosix(entry);
|
|
120
|
+
if (!ignored(rel)) found.add(rel);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return [...found].sort();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Projects adopted through a crepuscularity template frontend: `.svelte`,
|
|
128
|
+
* `.vue`, `.astro` and Angular component templates all compile to the same View
|
|
129
|
+
* IR as `.crepus` and JSX, which crepus-moonshine renders as React elements.
|
|
130
|
+
*/
|
|
131
|
+
export function detectTemplateFramework(
|
|
132
|
+
projectDir: string,
|
|
133
|
+
deps: Record<string, string>,
|
|
134
|
+
):
|
|
135
|
+
| { framework: Framework; routesDir: string; convention: RouteConvention }
|
|
136
|
+
| undefined {
|
|
137
|
+
const checks: {
|
|
138
|
+
framework: Framework;
|
|
139
|
+
deps: string[];
|
|
140
|
+
files: string[];
|
|
141
|
+
}[] = [
|
|
142
|
+
{
|
|
143
|
+
framework: "svelte",
|
|
144
|
+
deps: ["svelte", "@sveltejs/kit"],
|
|
145
|
+
files: ["svelte.config.js", "svelte.config.ts"],
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
framework: "vue",
|
|
149
|
+
deps: ["vue", "nuxt"],
|
|
150
|
+
files: ["vue.config.js", "nuxt.config.ts"],
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
framework: "astro",
|
|
154
|
+
deps: ["astro"],
|
|
155
|
+
files: ["astro.config.mjs", "astro.config.ts", "astro.config.js"],
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
framework: "angular",
|
|
159
|
+
deps: ["@angular/core"],
|
|
160
|
+
files: ["angular.json"],
|
|
161
|
+
},
|
|
162
|
+
];
|
|
163
|
+
|
|
164
|
+
for (const check of checks) {
|
|
165
|
+
const declared =
|
|
166
|
+
check.deps.some((dep) => deps[dep] !== undefined) ||
|
|
167
|
+
check.files.some((file) => existsSync(join(projectDir, file)));
|
|
168
|
+
const present =
|
|
169
|
+
templateFiles(projectDir, templateGlobs(check.framework)!).length > 0;
|
|
170
|
+
if (!declared && !present) continue;
|
|
171
|
+
return {
|
|
172
|
+
framework: check.framework,
|
|
173
|
+
routesDir: GENERATED_ROUTES,
|
|
174
|
+
convention: "moonshine",
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const moonshineRoutesCache = new Map<string, string | undefined>();
|
|
181
|
+
|
|
182
|
+
/** Route directory for the conventions moonshine reads directly. */
|
|
183
|
+
export function findMoonshineRoutes(projectDir: string): string | undefined {
|
|
184
|
+
if (moonshineRoutesCache.has(projectDir)) {
|
|
185
|
+
return moonshineRoutesCache.get(projectDir);
|
|
186
|
+
}
|
|
187
|
+
for (const dir of ["src/routes", "routes", "app/routes"]) {
|
|
188
|
+
if (existsSync(join(projectDir, dir))) {
|
|
189
|
+
moonshineRoutesCache.set(projectDir, dir);
|
|
190
|
+
return dir;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
moonshineRoutesCache.set(projectDir, undefined);
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function detectFramework(
|
|
198
|
+
projectDir: string,
|
|
199
|
+
pkg: PackageJson | undefined,
|
|
200
|
+
): { framework: Framework; routesDir?: string; convention?: RouteConvention } {
|
|
201
|
+
const deps = allDeps(pkg);
|
|
202
|
+
const template = detectTemplateFramework(projectDir, deps);
|
|
203
|
+
if (template) return template;
|
|
204
|
+
for (const dir of ["app", "src/app"]) {
|
|
205
|
+
if (
|
|
206
|
+
existsSync(join(projectDir, dir, "page.tsx")) ||
|
|
207
|
+
existsSync(join(projectDir, dir, "page.jsx")) ||
|
|
208
|
+
existsSync(join(projectDir, dir, "layout.tsx"))
|
|
209
|
+
) {
|
|
210
|
+
return { framework: "next-app", routesDir: dir, convention: "next-app" };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
for (const dir of ["pages", "src/pages"]) {
|
|
214
|
+
if (existsSync(join(projectDir, dir))) {
|
|
215
|
+
return {
|
|
216
|
+
framework: "next-pages",
|
|
217
|
+
routesDir: dir,
|
|
218
|
+
convention: "next-pages",
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (deps.next) return { framework: "next-app" };
|
|
223
|
+
|
|
224
|
+
const routesDir = findMoonshineRoutes(projectDir);
|
|
225
|
+
const routed = (framework: Framework) => ({
|
|
226
|
+
framework,
|
|
227
|
+
...(routesDir && { routesDir, convention: "moonshine" as RouteConvention }),
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
if (deps.waku || existsSync(join(projectDir, "waku.config.ts"))) {
|
|
231
|
+
return routed("waku");
|
|
232
|
+
}
|
|
233
|
+
if (deps["@tanstack/react-router"] || deps["@tanstack/react-start"]) {
|
|
234
|
+
return routed("tanstack");
|
|
235
|
+
}
|
|
236
|
+
if (
|
|
237
|
+
deps["react-router"] ||
|
|
238
|
+
deps["react-router-dom"] ||
|
|
239
|
+
deps["@remix-run/react"] ||
|
|
240
|
+
existsSync(join(projectDir, "react-router.config.ts")) ||
|
|
241
|
+
existsSync(join(projectDir, "remix.config.js"))
|
|
242
|
+
) {
|
|
243
|
+
return routed("react-router");
|
|
244
|
+
}
|
|
245
|
+
if (
|
|
246
|
+
existsSync(join(projectDir, "vite.config.ts")) ||
|
|
247
|
+
existsSync(join(projectDir, "vite.config.js"))
|
|
248
|
+
) {
|
|
249
|
+
return routed("vite-react");
|
|
250
|
+
}
|
|
251
|
+
if (deps.react) return routed("react");
|
|
252
|
+
return { framework: "unknown" };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Nearest ancestor of `from` that looks like the project being adopted.
|
|
257
|
+
*
|
|
258
|
+
* The nearest `package.json` wins when a framework is detectable there — that
|
|
259
|
+
* is the app the user is standing in, even inside a monorepo. Only when it says
|
|
260
|
+
* nothing does the walk continue to a workspace root (lockfile or `workspaces`).
|
|
261
|
+
*/
|
|
262
|
+
export function findProjectRoot(from: string): string | undefined {
|
|
263
|
+
let dir = resolve(from);
|
|
264
|
+
const candidates: string[] = [];
|
|
265
|
+
for (;;) {
|
|
266
|
+
if (existsSync(join(dir, "package.json"))) candidates.push(dir);
|
|
267
|
+
const parent = dirname(dir);
|
|
268
|
+
if (parent === dir) break;
|
|
269
|
+
dir = parent;
|
|
270
|
+
}
|
|
271
|
+
for (const candidate of candidates) {
|
|
272
|
+
const pkg = readJson<PackageJson>(join(candidate, "package.json"));
|
|
273
|
+
if (detectFramework(candidate, pkg).framework !== "unknown")
|
|
274
|
+
return candidate;
|
|
275
|
+
}
|
|
276
|
+
for (const candidate of candidates) {
|
|
277
|
+
const pkg = readJson<PackageJson>(join(candidate, "package.json"));
|
|
278
|
+
if (hasLockfile(candidate) || pkg?.workspaces !== undefined)
|
|
279
|
+
return candidate;
|
|
280
|
+
}
|
|
281
|
+
return candidates[0];
|
|
282
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/** Non-React templates, compiled through the parser into route modules. */
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { Framework } from "./frameworks.js";
|
|
5
|
+
import type { AdoptChange, AdoptScan, TemplateFile } from "./types.js";
|
|
6
|
+
import {
|
|
7
|
+
GENERATED_COMPONENTS,
|
|
8
|
+
GENERATED_ROUTES,
|
|
9
|
+
templateFiles,
|
|
10
|
+
} from "./scan.js";
|
|
11
|
+
|
|
12
|
+
function countNodes(nodes: readonly unknown[] = []): number {
|
|
13
|
+
let total = 0;
|
|
14
|
+
for (const node of nodes) {
|
|
15
|
+
total += 1;
|
|
16
|
+
const children = (node as { children?: unknown }).children;
|
|
17
|
+
if (Array.isArray(children)) total += countNodes(children);
|
|
18
|
+
}
|
|
19
|
+
return total;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** URL path a template file serves, or `undefined` when it is a plain component. */
|
|
23
|
+
export function templateRoute(
|
|
24
|
+
file: string,
|
|
25
|
+
framework: Framework,
|
|
26
|
+
): string | undefined {
|
|
27
|
+
// Angular has no file-based routing convention: routes live in the router
|
|
28
|
+
// module's TypeScript, which is not compiled here. Inventing a URL from a
|
|
29
|
+
// component's filename would be a guess, so its components stay unmounted.
|
|
30
|
+
if (framework === "angular") return undefined;
|
|
31
|
+
const segments = file.split("/");
|
|
32
|
+
const base = segments.pop()!;
|
|
33
|
+
const stem = base.replace(/\.(svelte|vue|astro)$/, "");
|
|
34
|
+
const rootIndex = segments.findIndex((s) => s === "routes" || s === "pages");
|
|
35
|
+
|
|
36
|
+
if (stem.startsWith("+page")) {
|
|
37
|
+
if (rootIndex === -1) return "/";
|
|
38
|
+
const rest = segments
|
|
39
|
+
.slice(rootIndex + 1)
|
|
40
|
+
.filter((s) => !s.startsWith("("));
|
|
41
|
+
return `/${rest.join("/")}`.replace(/\/$/, "") || "/";
|
|
42
|
+
}
|
|
43
|
+
if (rootIndex !== -1) {
|
|
44
|
+
const rest = [...segments.slice(rootIndex + 1), stem].filter(
|
|
45
|
+
(s) => !s.startsWith("("),
|
|
46
|
+
);
|
|
47
|
+
if (rest.at(-1) === "index") rest.pop();
|
|
48
|
+
return `/${rest.join("/")}`.replace(/\/$/, "") || "/";
|
|
49
|
+
}
|
|
50
|
+
if (/^(app|App)$/.test(stem) && segments.length <= 1) return "/";
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function generatedModule(route: string): string {
|
|
55
|
+
const rest = route.replace(/^\//, "");
|
|
56
|
+
return `${GENERATED_ROUTES}/${rest === "" ? "index" : rest}.tsx`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* A template that compiles but maps to no URL still becomes a component module,
|
|
61
|
+
* so the compiled IR is importable. Angular has no file-based routing at all, so
|
|
62
|
+
* this is the whole of its output — mounting it stays the user's decision.
|
|
63
|
+
*/
|
|
64
|
+
export function componentModule(file: string): string {
|
|
65
|
+
const slug = file
|
|
66
|
+
.replace(/\.(svelte|vue|astro|ng)$/, "")
|
|
67
|
+
.replace(/\.(component|ng)\.html$/, "")
|
|
68
|
+
.replace(/[^a-zA-Z0-9/-]/g, "-");
|
|
69
|
+
return `${GENERATED_COMPONENTS}/${slug}.tsx`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Compile every template through the crepuscularity frontend its filename
|
|
74
|
+
* selects. A template that does not compile is recorded with the parser's own
|
|
75
|
+
* message: unsupported constructs are hard errors, so nothing is silently
|
|
76
|
+
* dropped from the page.
|
|
77
|
+
*/
|
|
78
|
+
export async function compileTemplates(
|
|
79
|
+
projectDir: string,
|
|
80
|
+
framework: Framework,
|
|
81
|
+
globs: readonly string[],
|
|
82
|
+
): Promise<TemplateFile[]> {
|
|
83
|
+
const { parseTemplate } = await import("@tschk/crepuscularity-wasm");
|
|
84
|
+
const files = templateFiles(projectDir, globs);
|
|
85
|
+
|
|
86
|
+
const taken = new Set<string>();
|
|
87
|
+
|
|
88
|
+
const jobs = files.map((file) => {
|
|
89
|
+
const route = templateRoute(file, framework);
|
|
90
|
+
const entry: TemplateFile = { file, ok: false };
|
|
91
|
+
if (route !== undefined && !taken.has(route)) {
|
|
92
|
+
taken.add(route);
|
|
93
|
+
entry.route = route;
|
|
94
|
+
}
|
|
95
|
+
return { file, entry };
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const templates = await Promise.all(
|
|
99
|
+
jobs.map(async ({ file, entry }) => {
|
|
100
|
+
try {
|
|
101
|
+
const content = await readFile(join(projectDir, file), "utf8");
|
|
102
|
+
const ir = parseTemplate(content, file.split("/").pop()!);
|
|
103
|
+
entry.ok = true;
|
|
104
|
+
entry.nodes = countNodes(ir.root ?? []);
|
|
105
|
+
entry.ir = ir;
|
|
106
|
+
entry.irVersion = ir.version;
|
|
107
|
+
entry.generated =
|
|
108
|
+
entry.route !== undefined
|
|
109
|
+
? generatedModule(entry.route)
|
|
110
|
+
: componentModule(file);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
entry.error = error instanceof Error ? error.message : String(error);
|
|
113
|
+
delete entry.route;
|
|
114
|
+
}
|
|
115
|
+
return entry;
|
|
116
|
+
}),
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
return templates;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Modules generated from the templates: IR in, React elements out. */
|
|
123
|
+
export async function planTemplateRoutes(
|
|
124
|
+
scan: AdoptScan,
|
|
125
|
+
): Promise<AdoptChange[]> {
|
|
126
|
+
const changes: AdoptChange[] = [];
|
|
127
|
+
const promises = scan.templates.map(async (template) => {
|
|
128
|
+
if (!template.generated) return;
|
|
129
|
+
const path = join(scan.projectDir, template.generated);
|
|
130
|
+
const name = template.route ? "Route" : "Component";
|
|
131
|
+
const contents = `// Generated by \`moonshine adopt\` from ${template.file}: crepuscularity parsed that template into View IR v${template.irVersion}. Re-run \`moonshine adopt --force\` after editing the template.
|
|
132
|
+
import { renderCrepusIr, type CrepusIr } from "@tschk/crepus-moonshine";
|
|
133
|
+
|
|
134
|
+
const ir = ${JSON.stringify(template.ir, null, 2)} as CrepusIr;
|
|
135
|
+
|
|
136
|
+
export default function ${name}() {
|
|
137
|
+
return renderCrepusIr(ir);
|
|
138
|
+
}
|
|
139
|
+
`;
|
|
140
|
+
|
|
141
|
+
let existingContent: string | null = null;
|
|
142
|
+
let exists = false;
|
|
143
|
+
try {
|
|
144
|
+
existingContent = await readFile(path, "utf8");
|
|
145
|
+
exists = true;
|
|
146
|
+
} catch (err: any) {
|
|
147
|
+
if (err.code !== "ENOENT") {
|
|
148
|
+
throw err;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const alreadyApplied = exists && existingContent === contents;
|
|
153
|
+
const what = template.route
|
|
154
|
+
? `route ${template.route}`
|
|
155
|
+
: "unmounted component";
|
|
156
|
+
return {
|
|
157
|
+
file: template.generated,
|
|
158
|
+
action: alreadyApplied ? "none" : exists ? "modify" : "create",
|
|
159
|
+
details: alreadyApplied
|
|
160
|
+
? []
|
|
161
|
+
: [
|
|
162
|
+
`${what} renders ${template.file} (${template.nodes ?? 0} View IR nodes)`,
|
|
163
|
+
],
|
|
164
|
+
summary: alreadyApplied
|
|
165
|
+
? "already generated"
|
|
166
|
+
: `${exists ? "regenerated" : "generated"} ${what} from ${template.file}`,
|
|
167
|
+
alreadyApplied,
|
|
168
|
+
...(alreadyApplied ? {} : { contents }),
|
|
169
|
+
} as AdoptChange;
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
const results = await Promise.all(promises);
|
|
173
|
+
for (const change of results) {
|
|
174
|
+
if (change) {
|
|
175
|
+
changes.push(change);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return changes;
|
|
180
|
+
}
|