@tschk/moonshine-cli 0.3.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/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # `@tschk/moonshine-cli`
2
+
3
+ Bun CLI for scaffolding, building, and inspecting Moonshine projects.
4
+
5
+ ```bash
6
+ bun packages/cli/bin/moonshine.ts new my-app
7
+ bun packages/cli/bin/moonshine.ts build
8
+ bun packages/cli/bin/moonshine.ts inspect
9
+ bun packages/cli/bin/moonshine.ts preview
10
+ ```
11
+
12
+ Commands:
13
+
14
+ - `new <name> [--react|--solid|--crepus] [--adapter bun|node|cloudflare|vercel] [--vite]`
15
+ - `build [dir] [--adapter bun|node|cloudflare|vercel]`
16
+ - `inspect [path] [--json]`
17
+ - `preview [dir] [--port <n>]`
18
+ - `dev [dir]`
19
+ - `compile [file]`
20
+
21
+ See [DESIGN.md](../../DESIGN.md), [docs/ROUTING.md](../../docs/ROUTING.md),
22
+ [docs/DEPLOYMENT.md](../../docs/DEPLOYMENT.md), and
23
+ [docs/MANIFEST.md](../../docs/MANIFEST.md).
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env bun
2
+ import { buildCommand } from "../src/build";
3
+ import { compileCommand } from "../src/compile";
4
+ import { devCommand } from "../src/dev";
5
+ import { inspectCommand } from "../src/inspect";
6
+ import { newCommand } from "../src/new";
7
+ import { previewCommand } from "../src/preview";
8
+
9
+ const [cmd, ...args] = Bun.argv.slice(2);
10
+
11
+ function usage(code = 0): never {
12
+ console.error(`moonshine — Bun-first hyperminimal UI runtime
13
+
14
+ Usage:
15
+ moonshine new <name> [--react|--solid|--crepus] [--adapter bun|node|cloudflare|vercel] [--vite]
16
+ --react add React renderer
17
+ --solid add Solid renderer
18
+ --crepus add Crepus renderer
19
+ --adapter deployment target (default: bun)
20
+ --vite client-only Vite SPA
21
+ moonshine compile [file] .crepus / View IR JSON → .tsx
22
+ moonshine build [dir] Build project into .moonshine/manifest.json
23
+ --adapter bun|node|cloudflare|vercel
24
+ moonshine inspect [path] Inspect build manifest
25
+ --json print manifest JSON unchanged
26
+ moonshine preview [dir] Run built manifest on port 0
27
+ --port <n>
28
+ moonshine dev [dir] Build and preview with watch
29
+ --vite run vite (bunx) instead
30
+ `);
31
+ process.exit(code);
32
+ }
33
+
34
+ switch (cmd) {
35
+ case "new":
36
+ await newCommand(args);
37
+ break;
38
+ case "compile":
39
+ await compileCommand(args);
40
+ break;
41
+ case "build":
42
+ await buildCommand(args);
43
+ break;
44
+ case "inspect":
45
+ await inspectCommand(args);
46
+ break;
47
+ case "preview":
48
+ await previewCommand(args);
49
+ break;
50
+ case "dev":
51
+ await devCommand(args);
52
+ break;
53
+ case "-h":
54
+ case "--help":
55
+ case "help":
56
+ usage(0);
57
+ break;
58
+ case undefined:
59
+ usage(1);
60
+ break;
61
+ default:
62
+ console.error(`Unknown command: ${cmd}\n`);
63
+ usage(1);
64
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@tschk/moonshine-cli",
3
+ "version": "0.3.1",
4
+ "description": "Bun CLI for moonshine — new, dev, build, preview, inspect, compile",
5
+ "license": "ISC",
6
+ "type": "module",
7
+ "bin": {
8
+ "moonshine": "./bin/moonshine.ts"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "README.md"
14
+ ],
15
+ "keywords": [
16
+ "moonshine",
17
+ "bun",
18
+ "cli",
19
+ "crepus"
20
+ ],
21
+ "dependencies": {
22
+ "@tschk/moonshine-compiler": "^0.3.1",
23
+ "@tschk/moonshine-framework": "^0.3.1",
24
+ "@tschk/moonshine-server": "^0.3.1",
25
+ "@tschk/moonshine-deploy-bun": "^0.3.1",
26
+ "@tschk/moonshine-react": "^0.3.1"
27
+ },
28
+ "scripts": {
29
+ "format": "bunx prettier --check .",
30
+ "lint": "bunx oxlint .",
31
+ "typecheck": "exit 0",
32
+ "test": "bun test"
33
+ }
34
+ }
package/src/build.ts ADDED
@@ -0,0 +1,68 @@
1
+ import { resolve } from "node:path";
2
+ import { buildProject } from "@tschk/moonshine-compiler";
3
+ import type { MoonshineManifest } from "@tschk/moonshine-framework";
4
+ import { findConfig, loadConfig } from "./config.js";
5
+
6
+ type AdapterName = "bun" | "node" | "cloudflare" | "vercel";
7
+
8
+ function defaultRuntime(adapter: AdapterName): string {
9
+ switch (adapter) {
10
+ case "node":
11
+ return "node";
12
+ case "cloudflare":
13
+ return "cloudflare";
14
+ case "vercel":
15
+ return "vercel-edge";
16
+ case "bun":
17
+ default:
18
+ return "bun";
19
+ }
20
+ }
21
+
22
+ export async function buildCommand(args: string[]): Promise<MoonshineManifest> {
23
+ let projectDir = "";
24
+ let adapter: AdapterName = "bun";
25
+ for (let i = 0; i < args.length; i++) {
26
+ const arg = args[i]!;
27
+ if (arg === "--adapter") {
28
+ const next = args[++i];
29
+ if (!next || !["bun", "node", "cloudflare", "vercel"].includes(next)) {
30
+ console.error(`Invalid --adapter: ${next}`);
31
+ process.exit(1);
32
+ }
33
+ adapter = next as AdapterName;
34
+ } else if (arg.startsWith("-")) {
35
+ console.error(`Unknown flag: ${arg}`);
36
+ process.exit(1);
37
+ } else if (!projectDir) {
38
+ projectDir = arg;
39
+ } else {
40
+ console.error(`Unknown flag: ${arg}`);
41
+ process.exit(1);
42
+ }
43
+ }
44
+
45
+ const resolvedDir = resolve(projectDir || process.cwd());
46
+ const configPath = findConfig(resolvedDir);
47
+ const config = configPath ? await loadConfig(configPath) : {};
48
+ const runtime = (config.runtime ?? defaultRuntime(adapter)) as
49
+ "bun" | "node" | "cloudflare" | "vercel-edge";
50
+
51
+ const manifest = await buildProject({
52
+ projectDir: resolvedDir,
53
+ runtime,
54
+ });
55
+
56
+ const outDir = resolve(resolvedDir, ".moonshine");
57
+ const adapterModule = await import(`@tschk/moonshine-deploy-${adapter}`);
58
+ const adapterFn = adapterModule[`${adapter}Adapter`];
59
+ if (typeof adapterFn?.build !== "function") {
60
+ throw new Error(`Adapter "${adapter}" does not export a build function`);
61
+ }
62
+ await adapterFn.build(manifest, outDir);
63
+
64
+ console.log(
65
+ `Built ${manifest.routes.length} routes into .moonshine/manifest.json (${adapter})`,
66
+ );
67
+ return manifest;
68
+ }
package/src/compile.ts ADDED
@@ -0,0 +1,83 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, extname, join, resolve } from "node:path";
3
+
4
+ function which(bin: string): string | null {
5
+ const path = process.env.PATH ?? "";
6
+ for (const dir of path.split(":")) {
7
+ const candidate = join(dir, bin);
8
+ if (existsSync(candidate)) return candidate;
9
+ }
10
+ return null;
11
+ }
12
+
13
+ function emitTsxFromIr(ir: unknown, outPath: string): void {
14
+ const json = JSON.stringify(ir, null, 2);
15
+ const src = `import { createApp } from "@tschk/moonshine/react";
16
+ import { renderCrepusIr, type ViewIr } from "@tschk/crepus-moonshine";
17
+
18
+ const ir = ${json} as ViewIr;
19
+
20
+ function App() {
21
+ return renderCrepusIr(ir);
22
+ }
23
+
24
+ createApp({ root: App }).mount("#app");
25
+ `;
26
+ writeFileSync(outPath, src);
27
+ console.log(`Wrote ${outPath}`);
28
+ }
29
+
30
+ export async function compileCommand(args: string[]): Promise<void> {
31
+ const input = args[0];
32
+ if (!input) {
33
+ console.error("Usage: moonshine compile <file.crepus|file.json>");
34
+ process.exit(1);
35
+ }
36
+
37
+ const abs = resolve(process.cwd(), input);
38
+ if (!existsSync(abs)) {
39
+ console.error(`File not found: ${abs}`);
40
+ process.exit(1);
41
+ }
42
+
43
+ const ext = extname(abs).toLowerCase();
44
+ const outPath = join(dirname(abs), `${basename(abs, ext)}.tsx`);
45
+
46
+ if (ext === ".json") {
47
+ const ir = JSON.parse(readFileSync(abs, "utf8"));
48
+ emitTsxFromIr(ir, outPath);
49
+ return;
50
+ }
51
+
52
+ if (ext === ".crepus") {
53
+ const crepus = which("crepus");
54
+ if (crepus) {
55
+ const proc = Bun.spawn(
56
+ [crepus, "web", "build", "--emit", "moonshine", abs],
57
+ {
58
+ cwd: dirname(abs),
59
+ stdout: "inherit",
60
+ stderr: "inherit",
61
+ },
62
+ );
63
+ const code = await proc.exited;
64
+ if (code !== 0) process.exit(code);
65
+ console.log(`crepus emit finished for ${abs}`);
66
+ return;
67
+ }
68
+
69
+ console.error(
70
+ `No \`crepus\` on PATH and input is .crepus (not JSON IR).
71
+
72
+ Install crepus (≥ 0.11) and retry, or pass View IR JSON:
73
+
74
+ moonshine compile view.json
75
+
76
+ Hint: crepus web build --emit moonshine ${input}`,
77
+ );
78
+ process.exit(1);
79
+ }
80
+
81
+ console.error(`Unsupported extension: ${ext} (expected .crepus or .json)`);
82
+ process.exit(1);
83
+ }
package/src/config.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { defineConfig as baseDefineConfig } from "@tschk/moonshine-framework";
5
+ import type {
6
+ MoonshineConfig,
7
+ RouteDefinition,
8
+ } from "@tschk/moonshine-framework";
9
+
10
+ export type RendererName = "react" | "solid" | "crepus";
11
+
12
+ export type MoonshineCliConfig = MoonshineConfig & {
13
+ adapter?: "bun" | "node" | "cloudflare" | "vercel";
14
+ renderer?: RendererName;
15
+ routes?: RouteDefinition[];
16
+ };
17
+
18
+ export function defineConfig<T extends MoonshineCliConfig>(config: T): T {
19
+ return baseDefineConfig(config);
20
+ }
21
+
22
+ export function findConfig(projectDir: string): string | undefined {
23
+ const candidates = ["moonshine.config.ts", "moonshine.config.js"];
24
+ for (const name of candidates) {
25
+ const path = resolve(projectDir, name);
26
+ if (existsSync(path)) return path;
27
+ }
28
+ return undefined;
29
+ }
30
+
31
+ export async function loadConfig(path: string): Promise<MoonshineCliConfig> {
32
+ const mod = await import(pathToFileURL(path).href);
33
+ const config = mod.default ?? mod;
34
+ if (typeof config !== "object" || config === null) {
35
+ throw new Error(`Invalid moonshine config: ${path}`);
36
+ }
37
+ return config as MoonshineCliConfig;
38
+ }
package/src/dev.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { watch } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { buildCommand } from "./build.js";
4
+ import { startPreview, type PreviewHandle } from "./preview.js";
5
+
6
+ export async function devCommand(args: string[]): Promise<void> {
7
+ const vite = args.includes("--vite");
8
+ if (vite) {
9
+ const proc = Bun.spawn(
10
+ ["bunx", "vite", ...args.filter((a) => a !== "--vite")],
11
+ {
12
+ cwd: process.cwd(),
13
+ stdin: "inherit",
14
+ stdout: "inherit",
15
+ stderr: "inherit",
16
+ },
17
+ );
18
+ process.exit(await proc.exited);
19
+ }
20
+
21
+ let projectDir = "";
22
+ for (const arg of args) {
23
+ if (arg.startsWith("-")) {
24
+ console.error(`Unknown flag: ${arg}`);
25
+ process.exit(1);
26
+ } else if (!projectDir) {
27
+ projectDir = arg;
28
+ } else {
29
+ console.error(`Unknown flag: ${arg}`);
30
+ process.exit(1);
31
+ }
32
+ }
33
+
34
+ const root = resolve(projectDir || process.cwd());
35
+ const srcDir = resolve(root, "src");
36
+ let preview: PreviewHandle | undefined;
37
+ let watcher: ReturnType<typeof watch> | undefined;
38
+ let rebuildTimer: ReturnType<typeof setTimeout> | undefined;
39
+
40
+ async function runBuildAndPreview(): Promise<void> {
41
+ if (preview) {
42
+ await preview.stop();
43
+ preview = undefined;
44
+ }
45
+ try {
46
+ await buildCommand([root]);
47
+ preview = await startPreview({ projectDir: root, port: 0 });
48
+ console.log(`Dev server on http://localhost:${preview.port}/`);
49
+ } catch (error) {
50
+ console.error(error);
51
+ }
52
+ }
53
+
54
+ await runBuildAndPreview();
55
+
56
+ if (watcher) {
57
+ watcher.close();
58
+ }
59
+
60
+ watcher = watch(srcDir, { recursive: true }, () => {
61
+ if (rebuildTimer) clearTimeout(rebuildTimer);
62
+ rebuildTimer = setTimeout(() => {
63
+ void runBuildAndPreview();
64
+ }, 100);
65
+ });
66
+
67
+ const stop = async () => {
68
+ if (rebuildTimer) clearTimeout(rebuildTimer);
69
+ if (watcher) {
70
+ watcher.close();
71
+ watcher = undefined;
72
+ }
73
+ if (preview) {
74
+ await preview.stop();
75
+ preview = undefined;
76
+ }
77
+ process.exit(0);
78
+ };
79
+
80
+ process.on("SIGINT", () => void stop());
81
+ process.on("SIGTERM", () => void stop());
82
+
83
+ await new Promise(() => {});
84
+ }
package/src/inspect.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { readManifest } from "@tschk/moonshine-compiler";
4
+ import type { MoonshineManifest } from "@tschk/moonshine-framework";
5
+
6
+ export function formatInspection(manifest: MoonshineManifest): string {
7
+ const maxPath = Math.max(
8
+ ...manifest.routes.map((route) => route.path.length),
9
+ );
10
+ const lines = manifest.routes.map(
11
+ (route) =>
12
+ `${route.mode.padEnd(8)}${route.path.padEnd(maxPath + 2)}${route.decision}`,
13
+ );
14
+ return `${lines.join("\n")}\n`;
15
+ }
16
+
17
+ export async function inspectCommand(args: string[]): Promise<void> {
18
+ const json = args.includes("--json");
19
+ const positional = args.filter((a) => a !== "--json");
20
+ const manifestPath = positional[0]
21
+ ? resolve(positional[0]!)
22
+ : resolve(process.cwd(), ".moonshine", "manifest.json");
23
+
24
+ if (!existsSync(manifestPath)) {
25
+ console.error(`Manifest not found: ${manifestPath}`);
26
+ process.exit(1);
27
+ }
28
+
29
+ if (json) {
30
+ const file = Bun.file(manifestPath);
31
+ process.stdout.write(await file.text());
32
+ return;
33
+ }
34
+
35
+ const manifest = await readManifest(manifestPath);
36
+ process.stdout.write(formatInspection(manifest));
37
+ }
package/src/new.ts ADDED
@@ -0,0 +1,433 @@
1
+ import { mkdirSync, writeFileSync, existsSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+
4
+ type Renderer = "react" | "solid" | "crepus";
5
+ type Adapter = "bun" | "node" | "cloudflare" | "vercel";
6
+
7
+ function detectMoonshineRoot(): string | null {
8
+ if (process.env.MOONSHINE_PATH) return resolve(process.env.MOONSHINE_PATH);
9
+ let dir = process.cwd();
10
+ for (let i = 0; i < 8; i++) {
11
+ if (
12
+ existsSync(join(dir, "packages/core/package.json")) &&
13
+ existsSync(join(dir, "packages/cli/package.json"))
14
+ ) {
15
+ return dir;
16
+ }
17
+ const parent = resolve(dir, "..");
18
+ if (parent === dir) break;
19
+ dir = parent;
20
+ }
21
+ return null;
22
+ }
23
+
24
+ function dep(root: string | null, rel: string, version = "^0.2.0"): string {
25
+ return root ? `file:${join(root, rel)}` : version;
26
+ }
27
+
28
+ function packagePath(name: string, root: string | null): string | undefined {
29
+ const map: Record<string, string> = {
30
+ "@tschk/moonshine": "packages/core",
31
+ "@tschk/moonshine-framework": "packages/framework",
32
+ "@tschk/moonshine-compiler": "packages/compiler",
33
+ "@tschk/moonshine-server": "packages/server",
34
+ "@tschk/moonshine-react": "packages/react",
35
+ "@tschk/moonshine-solid": "packages/adapter-solid",
36
+ "@tschk/crepus-moonshine": "packages/crepus-moonshine",
37
+ "@tschk/moonshine-deploy-bun": "packages/deploy-bun",
38
+ "@tschk/moonshine-deploy-node": "packages/deploy-node",
39
+ "@tschk/moonshine-deploy-cloudflare": "packages/deploy-cloudflare",
40
+ "@tschk/moonshine-deploy-vercel": "packages/deploy-vercel",
41
+ };
42
+ const rel = map[name];
43
+ return rel ? dep(root, rel) : undefined;
44
+ }
45
+
46
+ function runtimeForAdapter(adapter: Adapter): string {
47
+ switch (adapter) {
48
+ case "node":
49
+ return "node";
50
+ case "cloudflare":
51
+ return "cloudflare";
52
+ case "vercel":
53
+ return "vercel-edge";
54
+ case "bun":
55
+ default:
56
+ return "bun";
57
+ }
58
+ }
59
+
60
+ function parseArgs(args: string[]): {
61
+ name: string;
62
+ renderer?: Renderer;
63
+ adapter: Adapter;
64
+ vite: boolean;
65
+ } {
66
+ let name = "";
67
+ let renderer: Renderer | undefined;
68
+ let adapter: Adapter = "bun";
69
+ let vite = false;
70
+ for (let i = 0; i < args.length; i++) {
71
+ const a = args[i]!;
72
+ if (a === "--react") renderer = "react";
73
+ else if (a === "--solid") renderer = "solid";
74
+ else if (a === "--crepus") renderer = "crepus";
75
+ else if (a === "--adapter") {
76
+ const next = args[++i];
77
+ if (next && ["bun", "node", "cloudflare", "vercel"].includes(next)) {
78
+ adapter = next as Adapter;
79
+ } else {
80
+ console.error(`Invalid --adapter: ${next}`);
81
+ process.exit(1);
82
+ }
83
+ } else if (a === "--vite") vite = true;
84
+ else if (a.startsWith("-")) {
85
+ console.error(`Unknown flag: ${a}`);
86
+ process.exit(1);
87
+ } else if (!name) {
88
+ name = a;
89
+ } else {
90
+ console.error(`Unknown flag: ${a}`);
91
+ process.exit(1);
92
+ }
93
+ }
94
+ if (!name) {
95
+ console.error(
96
+ "Usage: moonshine new <name> [--react|--solid|--crepus] [--adapter bun|node|cloudflare|vercel] [--vite]",
97
+ );
98
+ process.exit(1);
99
+ }
100
+ return { name, renderer, adapter, vite };
101
+ }
102
+
103
+ function writePackageJson(
104
+ dir: string,
105
+ name: string,
106
+ root: string | null,
107
+ renderer: Renderer | undefined,
108
+ adapter: Adapter,
109
+ ): void {
110
+ const dependencies: Record<string, string> = {
111
+ "@tschk/moonshine": packagePath("@tschk/moonshine", root)!,
112
+ "@tschk/moonshine-framework": packagePath(
113
+ "@tschk/moonshine-framework",
114
+ root,
115
+ )!,
116
+ "@tschk/moonshine-compiler": packagePath(
117
+ "@tschk/moonshine-compiler",
118
+ root,
119
+ )!,
120
+ "@tschk/moonshine-server": packagePath("@tschk/moonshine-server", root)!,
121
+ };
122
+ dependencies[`@tschk/moonshine-deploy-${adapter}`] = packagePath(
123
+ `@tschk/moonshine-deploy-${adapter}`,
124
+ root,
125
+ )!;
126
+
127
+ const devDependencies: Record<string, string> = {
128
+ "@types/bun": "^1.3.14",
129
+ typescript: "~7.0.0",
130
+ };
131
+
132
+ if (renderer === "react") {
133
+ dependencies["@tschk/moonshine-react"] = packagePath(
134
+ "@tschk/moonshine-react",
135
+ root,
136
+ )!;
137
+ dependencies.react = "^19.1.0";
138
+ dependencies["react-dom"] = "^19.1.0";
139
+ devDependencies["@types/react"] = "^19.1.0";
140
+ devDependencies["@types/react-dom"] = "^19.1.0";
141
+ } else if (renderer === "solid") {
142
+ dependencies["@tschk/moonshine-solid"] = packagePath(
143
+ "@tschk/moonshine-solid",
144
+ root,
145
+ )!;
146
+ dependencies["solid-js"] = "^1.9.14";
147
+ } else if (renderer === "crepus") {
148
+ dependencies["@tschk/crepus-moonshine"] = packagePath(
149
+ "@tschk/crepus-moonshine",
150
+ root,
151
+ )!;
152
+ dependencies["@tschk/moonshine-react"] = packagePath(
153
+ "@tschk/moonshine-react",
154
+ root,
155
+ )!;
156
+ dependencies.react = "^19.1.0";
157
+ dependencies["react-dom"] = "^19.1.0";
158
+ devDependencies["@types/react"] = "^19.1.0";
159
+ devDependencies["@types/react-dom"] = "^19.1.0";
160
+ }
161
+
162
+ writeFileSync(
163
+ join(dir, "package.json"),
164
+ JSON.stringify(
165
+ {
166
+ name,
167
+ private: true,
168
+ version: "0.0.0",
169
+ type: "module",
170
+ scripts: {
171
+ build: "moonshine build",
172
+ dev: "moonshine dev",
173
+ preview: "moonshine preview",
174
+ },
175
+ dependencies,
176
+ devDependencies,
177
+ },
178
+ null,
179
+ 2,
180
+ ) + "\n",
181
+ );
182
+ }
183
+
184
+ function writeTsconfig(dir: string, renderer: Renderer | undefined): void {
185
+ const compilerOptions: Record<string, unknown> = {
186
+ target: "ES2024",
187
+ module: "ESNext",
188
+ moduleResolution: "Bundler",
189
+ jsx: renderer === "solid" ? "preserve" : "react-jsx",
190
+ strict: true,
191
+ skipLibCheck: true,
192
+ noEmit: true,
193
+ types: ["bun"],
194
+ lib: ["ES2024", "DOM"],
195
+ };
196
+ if (renderer === "solid") {
197
+ compilerOptions.jsxImportSource = "solid-js";
198
+ }
199
+ writeFileSync(
200
+ join(dir, "tsconfig.json"),
201
+ JSON.stringify(
202
+ {
203
+ compilerOptions,
204
+ include: ["src"],
205
+ },
206
+ null,
207
+ 2,
208
+ ) + "\n",
209
+ );
210
+ }
211
+
212
+ function writeConfig(
213
+ dir: string,
214
+ renderer: Renderer | undefined,
215
+ adapter: Adapter,
216
+ ): void {
217
+ const runtime = runtimeForAdapter(adapter);
218
+ const entries: Record<string, unknown> = { runtime, adapter };
219
+ if (renderer) entries.renderer = renderer;
220
+ writeFileSync(
221
+ join(dir, "moonshine.config.ts"),
222
+ `import { defineConfig } from "@tschk/moonshine-framework";
223
+
224
+ export default defineConfig(${JSON.stringify(entries)});
225
+ `,
226
+ );
227
+ }
228
+
229
+ function writeRoute(dir: string, renderer: Renderer | undefined): void {
230
+ mkdirSync(join(dir, "src", "routes"), { recursive: true });
231
+ if (renderer === "react") {
232
+ writeFileSync(
233
+ join(dir, "src", "routes", "index.tsx"),
234
+ `export default function Home({ data }: { data?: unknown }) {
235
+ const d = (data ?? {}) as Record<string, string>;
236
+ return (
237
+ <main data-moonshine-mode={d.mode ?? "default"}>
238
+ <h1>Moonshine</h1>
239
+ </main>
240
+ );
241
+ }
242
+ `,
243
+ );
244
+ } else if (renderer === "solid") {
245
+ writeFileSync(
246
+ join(dir, "src", "routes", "index.ts"),
247
+ `import h from "@tschk/moonshine-solid/h";
248
+
249
+ export default function Home({ data }: { data?: unknown }) {
250
+ const d = (data ?? {}) as Record<string, string>;
251
+ return h(
252
+ "main",
253
+ { "data-moonshine-mode": d.mode ?? "default" },
254
+ h("h1", null, "Moonshine"),
255
+ );
256
+ }
257
+ `,
258
+ );
259
+ } else if (renderer === "crepus") {
260
+ writeFileSync(join(dir, "src", "routes", "index.ts"), "\n");
261
+ } else {
262
+ writeFileSync(
263
+ join(dir, "src", "routes", "index.server.ts"),
264
+ `export function loader() {
265
+ return { ok: true };
266
+ }
267
+ `,
268
+ );
269
+ }
270
+ }
271
+
272
+ function writeReadme(
273
+ dir: string,
274
+ name: string,
275
+ renderer: Renderer | undefined,
276
+ adapter: Adapter,
277
+ ): void {
278
+ const runtime = runtimeForAdapter(adapter);
279
+ let body = `# ${name}\n\nMoonshine on **${adapter}** (${runtime}).\n\n\`\`\`bash\nbun install\nbun run dev\n\`\`\`\n`;
280
+ if (!renderer)
281
+ body += `\nAdd \`--react\`, \`--solid\`, or \`--crepus\` for a UI renderer.\n`;
282
+ writeFileSync(join(dir, "README.md"), body);
283
+ }
284
+
285
+ function writeViteApp(dir: string, name: string, root: string | null): void {
286
+ mkdirSync(join(dir, "src"), { recursive: true });
287
+
288
+ writeFileSync(
289
+ join(dir, "package.json"),
290
+ JSON.stringify(
291
+ {
292
+ name,
293
+ private: true,
294
+ version: "0.0.0",
295
+ type: "module",
296
+ scripts: {
297
+ dev: "vite",
298
+ build: "vite build",
299
+ preview: "vite preview",
300
+ },
301
+ dependencies: {
302
+ "@tschk/moonshine": dep(root, "packages/core"),
303
+ react: "^19.1.0",
304
+ "react-dom": "^19.1.0",
305
+ },
306
+ devDependencies: {
307
+ "@types/react": "^19.1.0",
308
+ "@types/react-dom": "^19.1.0",
309
+ "@vitejs/plugin-react": "^4.5.0",
310
+ typescript: "~7.0.0",
311
+ vite: "^6.3.5",
312
+ },
313
+ },
314
+ null,
315
+ 2,
316
+ ) + "\n",
317
+ );
318
+
319
+ writeFileSync(
320
+ join(dir, "tsconfig.json"),
321
+ JSON.stringify(
322
+ {
323
+ compilerOptions: {
324
+ target: "ES2024",
325
+ module: "ESNext",
326
+ moduleResolution: "Bundler",
327
+ jsx: "react-jsx",
328
+ strict: true,
329
+ skipLibCheck: true,
330
+ noEmit: true,
331
+ types: ["vite/client"],
332
+ },
333
+ include: ["src"],
334
+ },
335
+ null,
336
+ 2,
337
+ ) + "\n",
338
+ );
339
+
340
+ writeFileSync(
341
+ join(dir, "vite.config.ts"),
342
+ `import { defineConfig } from "vite";
343
+ import react from "@vitejs/plugin-react";
344
+
345
+ export default defineConfig({
346
+ plugins: [react()],
347
+ });
348
+ `,
349
+ );
350
+
351
+ writeFileSync(
352
+ join(dir, "index.html"),
353
+ `<!doctype html>
354
+ <html lang="en">
355
+ <head>
356
+ <meta charset="UTF-8" />
357
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
358
+ <title>${name}</title>
359
+ </head>
360
+ <body>
361
+ <div id="app"></div>
362
+ <script type="module" src="/src/main.tsx"></script>
363
+ </body>
364
+ </html>
365
+ `,
366
+ );
367
+
368
+ writeFileSync(
369
+ join(dir, "src/main.tsx"),
370
+ `import { createSignal, useSignal, createApp } from "@tschk/moonshine/react";
371
+
372
+ const count = createSignal(0);
373
+
374
+ function App() {
375
+ const n = useSignal(count);
376
+ return (
377
+ <main style={{ fontFamily: "system-ui", padding: 32 }}>
378
+ <h1>${name}</h1>
379
+ <p>count: {n}</p>
380
+ <button type="button" onClick={() => count.set((c) => c + 1)}>
381
+ +1
382
+ </button>
383
+ </main>
384
+ );
385
+ }
386
+
387
+ createApp({ root: App }).mount("#app");
388
+ `,
389
+ );
390
+
391
+ writeFileSync(
392
+ join(dir, "README.md"),
393
+ `# ${name}\n\nVite + moonshine signals (client SPA).\n\n\`\`\`bash\nbun install\nbun run dev\n\`\`\`\n\nFull-stack Bun (server + static + hydrate): \`moonshine new app --bun\`.\n`,
394
+ );
395
+ }
396
+
397
+ function writeBunApp(
398
+ dir: string,
399
+ name: string,
400
+ root: string | null,
401
+ renderer: Renderer | undefined,
402
+ adapter: Adapter,
403
+ ): void {
404
+ mkdirSync(join(dir, "src", "routes"), { recursive: true });
405
+
406
+ writePackageJson(dir, name, root, renderer, adapter);
407
+ writeTsconfig(dir, renderer);
408
+ writeConfig(dir, renderer, adapter);
409
+ writeRoute(dir, renderer);
410
+ writeReadme(dir, name, renderer, adapter);
411
+ }
412
+
413
+ export async function newCommand(args: string[]): Promise<void> {
414
+ const { name, renderer, adapter, vite } = parseArgs(args);
415
+ if (vite && (renderer === "solid" || renderer === "crepus")) {
416
+ console.error("--vite only supports React scaffolds");
417
+ process.exit(1);
418
+ }
419
+ const root = detectMoonshineRoot();
420
+ const dir = resolve(process.cwd(), name);
421
+ if (existsSync(dir)) {
422
+ console.error(`Refusing to overwrite existing directory: ${dir}`);
423
+ process.exit(1);
424
+ }
425
+
426
+ mkdirSync(dir, { recursive: true });
427
+ if (vite) writeViteApp(dir, name, root);
428
+ else writeBunApp(dir, name, root, renderer, adapter);
429
+
430
+ console.log(`Created ${name}/ (${vite ? "vite" : adapter})`);
431
+ if (root) console.log(`Linked moonshine from ${root}`);
432
+ console.log(`\n cd ${name} && bun install && bun run dev\n`);
433
+ }
package/src/preview.ts ADDED
@@ -0,0 +1,144 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { createBunServer } from "@tschk/moonshine-deploy-bun";
4
+ import { readManifest } from "@tschk/moonshine-compiler";
5
+ import { createRequestHandler } from "@tschk/moonshine-server";
6
+ import type {
7
+ MoonshineManifest,
8
+ Renderer,
9
+ RouteArtifact,
10
+ } from "@tschk/moonshine-framework";
11
+ import { findConfig, loadConfig, type MoonshineCliConfig } from "./config.js";
12
+
13
+ export type PreviewHandle = {
14
+ url: URL;
15
+ port: number;
16
+ stop: () => Promise<void>;
17
+ };
18
+
19
+ function resolveManifest(
20
+ projectDir: string,
21
+ manifest: MoonshineManifest,
22
+ ): MoonshineManifest {
23
+ function abs(p: string | undefined): string | undefined {
24
+ return p ? resolve(projectDir, p) : undefined;
25
+ }
26
+ return {
27
+ ...manifest,
28
+ routes: manifest.routes.map((route: RouteArtifact) => ({
29
+ ...route,
30
+ file: abs(route.file)!,
31
+ dataFile: abs(route.dataFile),
32
+ layouts: route.layouts?.map(abs).filter(Boolean) as string[] | undefined,
33
+ middleware: route.middleware?.map(abs).filter(Boolean) as
34
+ string[] | undefined,
35
+ errorBoundary: abs(route.errorBoundary),
36
+ })),
37
+ };
38
+ }
39
+
40
+ async function loadConfigMaybe(
41
+ projectDir: string,
42
+ ): Promise<MoonshineCliConfig> {
43
+ const path = findConfig(projectDir);
44
+ return path ? await loadConfig(path) : {};
45
+ }
46
+
47
+ async function resolveRenderer(
48
+ name: string | undefined,
49
+ ): Promise<Renderer | undefined> {
50
+ switch (name) {
51
+ case "solid":
52
+ return (await import("@tschk/moonshine-solid")).solidRenderer;
53
+ case "crepus":
54
+ return (await import("@tschk/crepus-moonshine")).crepusRenderer;
55
+ case "react":
56
+ default:
57
+ return (await import("@tschk/moonshine-react")).reactRenderer;
58
+ }
59
+ }
60
+
61
+ export async function startPreview(options: {
62
+ projectDir: string;
63
+ port?: number;
64
+ manifestPath?: string;
65
+ }): Promise<PreviewHandle> {
66
+ const projectDir = resolve(options.projectDir);
67
+ const manifestPath = options.manifestPath
68
+ ? resolve(options.manifestPath)
69
+ : resolve(projectDir, ".moonshine", "manifest.json");
70
+ if (!existsSync(manifestPath)) {
71
+ throw new Error(`Manifest not found: ${manifestPath}`);
72
+ }
73
+
74
+ const raw = await readManifest(manifestPath);
75
+ const manifest = resolveManifest(projectDir, raw);
76
+ const config = await loadConfigMaybe(projectDir);
77
+ const renderer = await resolveRenderer(config.renderer);
78
+ const staticDir = resolve(projectDir, ".moonshine");
79
+ const serverBundlePath = resolve(
80
+ projectDir,
81
+ ".moonshine",
82
+ raw.entries.server ?? "dist/server.js",
83
+ );
84
+ let modules: Record<string, unknown> = {};
85
+ try {
86
+ const bundle = (await import(serverBundlePath)) as {
87
+ modules?: Record<string, unknown>;
88
+ };
89
+ modules = bundle.modules ?? {};
90
+ } catch {}
91
+ const fetch = createRequestHandler({
92
+ manifest,
93
+ modules,
94
+ renderer,
95
+ staticDir,
96
+ });
97
+ const server = createBunServer({
98
+ fetch,
99
+ port: options.port ?? 0,
100
+ staticDir,
101
+ });
102
+
103
+ return {
104
+ url: server.url,
105
+ port: server.port,
106
+ stop: async () => {
107
+ await server.stop(true);
108
+ },
109
+ };
110
+ }
111
+
112
+ export async function previewCommand(args: string[]): Promise<void> {
113
+ let projectDir = "";
114
+ let port = 0;
115
+ for (let i = 0; i < args.length; i++) {
116
+ const arg = args[i]!;
117
+ if (arg === "--port") {
118
+ port = Number(args[++i]) || 0;
119
+ } else if (arg.startsWith("-")) {
120
+ console.error(`Unknown flag: ${arg}`);
121
+ process.exit(1);
122
+ } else if (!projectDir) {
123
+ projectDir = arg;
124
+ } else {
125
+ console.error(`Unknown flag: ${arg}`);
126
+ process.exit(1);
127
+ }
128
+ }
129
+
130
+ const preview = await startPreview({
131
+ projectDir: projectDir || process.cwd(),
132
+ port,
133
+ });
134
+ console.log(`Preview on http://localhost:${preview.port}/`);
135
+
136
+ const stopAndExit = async () => {
137
+ await preview.stop();
138
+ process.exit(0);
139
+ };
140
+ process.on("SIGINT", stopAndExit);
141
+ process.on("SIGTERM", stopAndExit);
142
+
143
+ await new Promise(() => {});
144
+ }