@sukujs/cli 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +49 -2
- package/dist/bin.d.mts +1 -0
- package/dist/bin.mjs +9 -0
- package/dist/bin.mjs.map +1 -0
- package/dist/index.d.mts +173 -0
- package/dist/index.mjs +3 -0
- package/dist/src-DP9MVAe3.mjs +1387 -0
- package/dist/src-DP9MVAe3.mjs.map +1 -0
- package/package.json +52 -4
|
@@ -0,0 +1,1387 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
4
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
5
|
+
import { emitKeypressEvents } from "node:readline";
|
|
6
|
+
|
|
7
|
+
// src/errors.ts
|
|
8
|
+
/** A mistake in how the CLI was used. Printed without a stack trace, exit code 1. */
|
|
9
|
+
var CliError = class extends Error {
|
|
10
|
+
constructor(..._args) {
|
|
11
|
+
super(..._args);
|
|
12
|
+
this.name = "CliError";
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// src/deploy.ts
|
|
17
|
+
const DEPLOY_TARGETS = {
|
|
18
|
+
docker: {
|
|
19
|
+
label: "Docker",
|
|
20
|
+
hint: "Dockerfile and docker-compose.yml"
|
|
21
|
+
},
|
|
22
|
+
pm2: {
|
|
23
|
+
label: "VPS with PM2",
|
|
24
|
+
hint: "ecosystem.config.cjs"
|
|
25
|
+
},
|
|
26
|
+
systemd: {
|
|
27
|
+
label: "VPS with systemd",
|
|
28
|
+
hint: "a unit file"
|
|
29
|
+
},
|
|
30
|
+
cloudflare: {
|
|
31
|
+
label: "Cloudflare Workers",
|
|
32
|
+
hint: "src/worker.ts and wrangler.jsonc"
|
|
33
|
+
},
|
|
34
|
+
vercel: {
|
|
35
|
+
label: "Vercel",
|
|
36
|
+
hint: "api/index.ts and vercel.json"
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
/** Parses `docker,pm2` or repeated flags into known targets. `none` means an empty list. */
|
|
40
|
+
function parseDeployTargets(input) {
|
|
41
|
+
const out = /* @__PURE__ */ new Set();
|
|
42
|
+
for (const name of input.flatMap((value) => value.split(",")).map((value) => value.trim())) {
|
|
43
|
+
if (name === "" || name === "none") continue;
|
|
44
|
+
if (!(name in DEPLOY_TARGETS)) throw new CliError(`Unknown deployment target "${name}". Use any of: ${Object.keys(DEPLOY_TARGETS).join(", ")}, or none.`);
|
|
45
|
+
out.add(name);
|
|
46
|
+
}
|
|
47
|
+
return [...out];
|
|
48
|
+
}
|
|
49
|
+
/** The files, scripts and README notes each chosen deployment target adds to a new project. */
|
|
50
|
+
function deployFiles(name, runtime, targets) {
|
|
51
|
+
const out = {
|
|
52
|
+
files: {},
|
|
53
|
+
scripts: {},
|
|
54
|
+
devDependencies: {},
|
|
55
|
+
readme: []
|
|
56
|
+
};
|
|
57
|
+
const bun = runtime === "bun";
|
|
58
|
+
const startCommand = bun ? "bun dist/main.js" : "node dist/main.js";
|
|
59
|
+
if (targets.includes("docker")) {
|
|
60
|
+
out.files.Dockerfile = `# syntax=docker/dockerfile:1
|
|
61
|
+
FROM oven/bun:1 AS build
|
|
62
|
+
WORKDIR /app
|
|
63
|
+
COPY package.json bun.lock* ./
|
|
64
|
+
# With a lockfile the image gets exactly the versions you tested; without one, a fresh install.
|
|
65
|
+
RUN if [ -f bun.lock ]; then bun install --frozen-lockfile; else bun install; fi
|
|
66
|
+
COPY . .
|
|
67
|
+
RUN bun run build
|
|
68
|
+
|
|
69
|
+
FROM ${bun ? "oven/bun:1-alpine" : "node:22-alpine"} AS runner
|
|
70
|
+
WORKDIR /app
|
|
71
|
+
ENV NODE_ENV=production
|
|
72
|
+
ENV PORT=3000
|
|
73
|
+
# The bundle carries its dependencies, so the image needs only this.
|
|
74
|
+
COPY --from=build /app/package.json ./
|
|
75
|
+
COPY --from=build /app/dist ./dist
|
|
76
|
+
USER ${bun ? "bun" : "node"}
|
|
77
|
+
EXPOSE 3000
|
|
78
|
+
CMD [${startCommand.split(" ").map((part) => `"${part}"`).join(", ")}]
|
|
79
|
+
`;
|
|
80
|
+
out.files[".dockerignore"] = "node_modules\ndist\n.git\n.env\n";
|
|
81
|
+
out.files["docker-compose.yml"] = `services:
|
|
82
|
+
api:
|
|
83
|
+
build: .
|
|
84
|
+
ports:
|
|
85
|
+
- '3000:3000'
|
|
86
|
+
environment:
|
|
87
|
+
PORT: 3000
|
|
88
|
+
restart: unless-stopped
|
|
89
|
+
stop_grace_period: 15s
|
|
90
|
+
healthcheck:
|
|
91
|
+
test: ['CMD', 'wget', '-qO-', 'http://127.0.0.1:3000/health']
|
|
92
|
+
interval: 30s
|
|
93
|
+
timeout: 3s
|
|
94
|
+
retries: 3
|
|
95
|
+
`;
|
|
96
|
+
out.readme.push(`### Docker
|
|
97
|
+
|
|
98
|
+
\`\`\`bash
|
|
99
|
+
docker compose up -d --build
|
|
100
|
+
curl http://localhost:3000/health
|
|
101
|
+
\`\`\``);
|
|
102
|
+
}
|
|
103
|
+
if (targets.includes("pm2")) {
|
|
104
|
+
out.files["ecosystem.config.cjs"] = `module.exports = {
|
|
105
|
+
apps: [
|
|
106
|
+
{
|
|
107
|
+
name: '${name}',
|
|
108
|
+
script: 'dist/main.js',
|
|
109
|
+
${bun ? ` interpreter: 'bun',
|
|
110
|
+
instances: 1,
|
|
111
|
+
exec_mode: 'fork',` : ` instances: 'max', // one worker per CPU core
|
|
112
|
+
exec_mode: 'cluster',`}
|
|
113
|
+
kill_timeout: 15000, // longer than the shutdown deadline in src/main.ts
|
|
114
|
+
max_memory_restart: '512M',
|
|
115
|
+
env: {
|
|
116
|
+
NODE_ENV: 'production',
|
|
117
|
+
PORT: 3000,
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
],
|
|
121
|
+
};
|
|
122
|
+
`;
|
|
123
|
+
out.readme.push(`### VPS with PM2
|
|
124
|
+
|
|
125
|
+
\`\`\`bash
|
|
126
|
+
bun install && bun run build
|
|
127
|
+
pm2 startOrReload ecosystem.config.cjs
|
|
128
|
+
pm2 save
|
|
129
|
+
\`\`\``);
|
|
130
|
+
}
|
|
131
|
+
if (targets.includes("systemd")) {
|
|
132
|
+
out.files[`deploy/${name}.service`] = `[Unit]
|
|
133
|
+
Description=${name}
|
|
134
|
+
After=network-online.target
|
|
135
|
+
Wants=network-online.target
|
|
136
|
+
|
|
137
|
+
[Service]
|
|
138
|
+
Type=simple
|
|
139
|
+
User=www-data
|
|
140
|
+
WorkingDirectory=/var/www/${name}
|
|
141
|
+
Environment=NODE_ENV=production
|
|
142
|
+
EnvironmentFile=/var/www/${name}/.env
|
|
143
|
+
ExecStart=${bun ? "/usr/local/bin/bun" : "/usr/bin/node"} dist/main.js
|
|
144
|
+
Restart=on-failure
|
|
145
|
+
RestartSec=5
|
|
146
|
+
KillSignal=SIGTERM
|
|
147
|
+
TimeoutStopSec=30
|
|
148
|
+
NoNewPrivileges=true
|
|
149
|
+
PrivateTmp=true
|
|
150
|
+
|
|
151
|
+
[Install]
|
|
152
|
+
WantedBy=multi-user.target
|
|
153
|
+
`;
|
|
154
|
+
out.readme.push(`### VPS with systemd
|
|
155
|
+
|
|
156
|
+
Copy the project to \`/var/www/${name}\`, build it, then install the unit:
|
|
157
|
+
|
|
158
|
+
\`\`\`bash
|
|
159
|
+
sudo cp deploy/${name}.service /etc/systemd/system/
|
|
160
|
+
sudo systemctl daemon-reload
|
|
161
|
+
sudo systemctl enable --now ${name}
|
|
162
|
+
\`\`\``);
|
|
163
|
+
}
|
|
164
|
+
if (targets.includes("cloudflare")) {
|
|
165
|
+
out.files["src/worker.ts"] = `import { Suku, type SukuApplication } from '@sukujs/core';
|
|
166
|
+
import { securityHeaders } from '@sukujs/security';
|
|
167
|
+
import { AppFeature } from './app.feature';
|
|
168
|
+
import { Env } from './config';
|
|
169
|
+
|
|
170
|
+
// Bindings arrive with the first request, so the app is created then and kept.
|
|
171
|
+
let app: Promise<SukuApplication> | undefined;
|
|
172
|
+
|
|
173
|
+
const createApp = async (env: Record<string, unknown>) =>
|
|
174
|
+
Suku.create({
|
|
175
|
+
features: [await Env.load({ ...env }), AppFeature],
|
|
176
|
+
middlewares: [securityHeaders()],
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
export default {
|
|
180
|
+
async fetch(request: Request, env: Record<string, unknown>): Promise<Response> {
|
|
181
|
+
app ??= createApp(env);
|
|
182
|
+
const { handle } = await app;
|
|
183
|
+
const remoteAddress = request.headers.get('cf-connecting-ip') ?? undefined;
|
|
184
|
+
return handle(request, remoteAddress ? { remoteAddress } : undefined);
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
`;
|
|
188
|
+
out.files["wrangler.jsonc"] = `{
|
|
189
|
+
"$schema": "node_modules/wrangler/config-schema.json",
|
|
190
|
+
"name": "${name}",
|
|
191
|
+
// Bun bundles the Worker first, because it keeps the decorator metadata that
|
|
192
|
+
// constructor injection needs.
|
|
193
|
+
"main": "dist/worker.js",
|
|
194
|
+
"compatibility_date": "${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}",
|
|
195
|
+
"build": {
|
|
196
|
+
"command": "bun run build:worker"
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
`;
|
|
200
|
+
out.scripts["build:worker"] = "bun build src/worker.ts --target browser --format esm --outfile dist/worker.js";
|
|
201
|
+
out.scripts["dev:worker"] = "wrangler dev";
|
|
202
|
+
out.scripts["deploy:cloudflare"] = "wrangler deploy";
|
|
203
|
+
out.devDependencies.wrangler = "^4.0.0";
|
|
204
|
+
out.readme.push(`### Cloudflare Workers
|
|
205
|
+
|
|
206
|
+
\`\`\`bash
|
|
207
|
+
bun run dev:worker # run locally in the Workers runtime
|
|
208
|
+
bun run deploy:cloudflare
|
|
209
|
+
\`\`\``);
|
|
210
|
+
}
|
|
211
|
+
if (targets.includes("vercel")) {
|
|
212
|
+
out.files["api/index.ts"] = `import { Suku } from '@sukujs/core';
|
|
213
|
+
import { securityHeaders } from '@sukujs/security';
|
|
214
|
+
import { AppFeature } from '../src/app.feature';
|
|
215
|
+
import { Env } from '../src/config';
|
|
216
|
+
|
|
217
|
+
const app = await Suku.create({
|
|
218
|
+
features: [Env.load(), AppFeature],
|
|
219
|
+
middlewares: [securityHeaders()],
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
// One function for the whole API. vercel.json sends every path here.
|
|
223
|
+
export default {
|
|
224
|
+
fetch: (request: Request) => app.handle(request),
|
|
225
|
+
};
|
|
226
|
+
`;
|
|
227
|
+
out.files["vercel.json"] = `${JSON.stringify({ rewrites: [{
|
|
228
|
+
source: "/(.*)",
|
|
229
|
+
destination: "/api"
|
|
230
|
+
}] }, null, 2)}\n`;
|
|
231
|
+
out.scripts["dev:vercel"] = "vercel dev";
|
|
232
|
+
out.scripts["deploy:vercel"] = "vercel deploy";
|
|
233
|
+
out.devDependencies.vercel = "latest";
|
|
234
|
+
out.readme.push(`### Vercel
|
|
235
|
+
|
|
236
|
+
\`\`\`bash
|
|
237
|
+
bun run dev:vercel
|
|
238
|
+
bun run deploy:vercel
|
|
239
|
+
\`\`\``);
|
|
240
|
+
}
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// src/names.ts
|
|
245
|
+
const cap = (word) => word.charAt(0).toUpperCase() + word.slice(1);
|
|
246
|
+
/** Turns any spelling (`userProfiles`, `user_profiles`, `User Profiles`) into every casing. */
|
|
247
|
+
function names(input) {
|
|
248
|
+
const words = input.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map((word) => word.toLowerCase());
|
|
249
|
+
if (words.length === 0) throw new CliError(`"${input}" is not a usable name.`);
|
|
250
|
+
if (/^[0-9]/.test(words[0])) throw new CliError(`"${input}" starts with a digit, which is not a valid identifier.`);
|
|
251
|
+
const pascal = words.map(cap).join("");
|
|
252
|
+
return {
|
|
253
|
+
kebab: words.join("-"),
|
|
254
|
+
pascal,
|
|
255
|
+
camel: pascal.charAt(0).toLowerCase() + pascal.slice(1)
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
/** `users` -> `user`, `categories` -> `category`, `addresses` -> `address`. Good enough for a type name. */
|
|
259
|
+
function singular(word) {
|
|
260
|
+
if (/ies$/i.test(word)) return word.replace(/ies$/i, "y");
|
|
261
|
+
if (/(ss|x|ch|sh)es$/i.test(word)) return word.replace(/es$/i, "");
|
|
262
|
+
if (/s$/i.test(word) && !/ss$/i.test(word)) return word.slice(0, -1);
|
|
263
|
+
return word;
|
|
264
|
+
}
|
|
265
|
+
/** Splits `admin/users` into the folder `admin` and the name `users`. */
|
|
266
|
+
function splitPath(input) {
|
|
267
|
+
const parts = input.split(/[\\/]+/).filter(Boolean);
|
|
268
|
+
const name = parts.pop();
|
|
269
|
+
if (!name) throw new CliError("A name is required.");
|
|
270
|
+
if (parts.some((part) => part === "..")) throw new CliError("The name cannot contain \"..\".");
|
|
271
|
+
return {
|
|
272
|
+
dir: parts.join("/"),
|
|
273
|
+
name
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// src/plan.ts
|
|
278
|
+
/**
|
|
279
|
+
* Collects every file a command wants to write, then writes them together. Nothing touches
|
|
280
|
+
* the disk until `commit`, so a command either does all of its work or none of it.
|
|
281
|
+
*/
|
|
282
|
+
var Plan = class {
|
|
283
|
+
constructor(root) {
|
|
284
|
+
this.root = root;
|
|
285
|
+
this.changes = [];
|
|
286
|
+
this.notes = [];
|
|
287
|
+
}
|
|
288
|
+
key(path) {
|
|
289
|
+
return relative(this.root, join(this.root, path)).split("\\").join("/");
|
|
290
|
+
}
|
|
291
|
+
exists(path) {
|
|
292
|
+
return this.read(path) !== void 0;
|
|
293
|
+
}
|
|
294
|
+
/** The planned content of a file if this plan changes it, otherwise what is on disk. */
|
|
295
|
+
read(path) {
|
|
296
|
+
const key = this.key(path);
|
|
297
|
+
const planned = this.changes.find((change) => change.path === key);
|
|
298
|
+
if (planned) return planned.content;
|
|
299
|
+
const absolute = join(this.root, key);
|
|
300
|
+
return existsSync(absolute) ? readFileSync(absolute, "utf8") : void 0;
|
|
301
|
+
}
|
|
302
|
+
create(path, content) {
|
|
303
|
+
this.changes.push({
|
|
304
|
+
action: "CREATE",
|
|
305
|
+
path: this.key(path),
|
|
306
|
+
content
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
update(path, content) {
|
|
310
|
+
const key = this.key(path);
|
|
311
|
+
const planned = this.changes.find((change) => change.path === key);
|
|
312
|
+
if (planned) planned.content = content;
|
|
313
|
+
else this.changes.push({
|
|
314
|
+
action: "UPDATE",
|
|
315
|
+
path: key,
|
|
316
|
+
content
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
note(message) {
|
|
320
|
+
this.notes.push(message);
|
|
321
|
+
}
|
|
322
|
+
commit(options = {}) {
|
|
323
|
+
const log = options.log ?? console.log;
|
|
324
|
+
if (!options.force) {
|
|
325
|
+
const taken = this.changes.filter((change) => change.action === "CREATE" && existsSync(join(this.root, change.path)));
|
|
326
|
+
if (taken.length > 0) throw new CliError(`Refusing to overwrite ${taken.map((change) => change.path).join(", ")}. Pass --force to replace.`);
|
|
327
|
+
}
|
|
328
|
+
for (const change of this.changes) {
|
|
329
|
+
if (!options.dryRun) {
|
|
330
|
+
const absolute = join(this.root, change.path);
|
|
331
|
+
mkdirSync(dirname(absolute), { recursive: true });
|
|
332
|
+
writeFileSync(absolute, change.content);
|
|
333
|
+
}
|
|
334
|
+
log(`${change.action} ${change.path} (${Buffer.byteLength(change.content)} bytes)`);
|
|
335
|
+
}
|
|
336
|
+
for (const note of this.notes) log(`NOTE ${note}`);
|
|
337
|
+
if (options.dryRun) log("Dry run: nothing was written.");
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
// src/project.ts
|
|
342
|
+
/** Reads the project in `cwd`. Settings come from the `suku` field of its `package.json`. */
|
|
343
|
+
function loadProject(cwd) {
|
|
344
|
+
const file = join(cwd, "package.json");
|
|
345
|
+
if (!existsSync(file)) throw new CliError("No package.json here. Run this from the root of a Suku project, or create one with `suku new <name>`.");
|
|
346
|
+
let pkg;
|
|
347
|
+
try {
|
|
348
|
+
pkg = JSON.parse(readFileSync(file, "utf8"));
|
|
349
|
+
} catch {
|
|
350
|
+
throw new CliError("package.json is not valid JSON.");
|
|
351
|
+
}
|
|
352
|
+
const settings = pkg.suku ?? {};
|
|
353
|
+
const sourceRoot = settings.sourceRoot ?? "src";
|
|
354
|
+
const entry = settings.entry ?? `${sourceRoot}/main.ts`;
|
|
355
|
+
const runtime = settings.runtime ?? "node";
|
|
356
|
+
if (runtime !== "node" && runtime !== "bun") throw new CliError(`"suku.runtime" in package.json must be "node" or "bun", not "${runtime}".`);
|
|
357
|
+
return {
|
|
358
|
+
root: cwd,
|
|
359
|
+
sourceRoot,
|
|
360
|
+
entry,
|
|
361
|
+
runtime,
|
|
362
|
+
importExtension: detectExtension(join(cwd, entry)),
|
|
363
|
+
dependencies: {
|
|
364
|
+
...pkg.dependencies,
|
|
365
|
+
...pkg.devDependencies
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
function detectExtension(entryFile) {
|
|
370
|
+
if (!existsSync(entryFile)) return "";
|
|
371
|
+
return /from\s+['"]\.{1,2}\/[^'"]+\.js['"]/.test(readFileSync(entryFile, "utf8")) ? ".js" : "";
|
|
372
|
+
}
|
|
373
|
+
/** The specifier to import `to` from `from`, both relative to the project root, without `.ts`. */
|
|
374
|
+
function importPath(from, to, extension) {
|
|
375
|
+
const path = relative(dirname(from), to).split("\\").join("/").replace(/\.ts$/, "");
|
|
376
|
+
return `${path.startsWith(".") ? path : `./${path}`}${extension}`;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// src/run.ts
|
|
380
|
+
/** Runs a command with the terminal attached and resolves with its exit code. */
|
|
381
|
+
function exec(command, args, options = {}) {
|
|
382
|
+
return new Promise((resolve, reject) => {
|
|
383
|
+
const child = spawn(command, args, {
|
|
384
|
+
cwd: options.cwd,
|
|
385
|
+
env: {
|
|
386
|
+
...process.env,
|
|
387
|
+
...options.env
|
|
388
|
+
},
|
|
389
|
+
stdio: "inherit"
|
|
390
|
+
});
|
|
391
|
+
const ignore = () => {};
|
|
392
|
+
process.on("SIGINT", ignore);
|
|
393
|
+
process.on("SIGTERM", () => child.kill("SIGTERM"));
|
|
394
|
+
child.on("error", (error) => {
|
|
395
|
+
process.off("SIGINT", ignore);
|
|
396
|
+
reject(error.code === "ENOENT" ? new CliError(command === "bun" ? "Bun is required for this command and was not found. Install it from https://bun.sh." : `Could not find \`${command}\` on your PATH.`) : error);
|
|
397
|
+
});
|
|
398
|
+
child.on("exit", (code, signal) => {
|
|
399
|
+
process.off("SIGINT", ignore);
|
|
400
|
+
resolve(code ?? (signal ? 1 : 0));
|
|
401
|
+
});
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
/** The version a tool reports, or `undefined` when it is not installed. */
|
|
405
|
+
function versionOf(command) {
|
|
406
|
+
const result = spawnSync(command, ["--version"], { encoding: "utf8" });
|
|
407
|
+
if (result.error || result.status !== 0) return void 0;
|
|
408
|
+
return result.stdout.trim().split("\n")[0];
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// src/register.ts
|
|
412
|
+
/** Small, text-based edits that wire a generated file into an existing one. */
|
|
413
|
+
/** Adds `import { name } from 'from';` after the last import, unless it is already imported. */
|
|
414
|
+
function addImport(source, name, from) {
|
|
415
|
+
if (new RegExp(`import\\s*\\{[^}]*\\b${name}\\b[^}]*\\}\\s*from`).test(source)) return source;
|
|
416
|
+
const line = `import { ${name} } from '${from}';`;
|
|
417
|
+
const last = [...source.matchAll(/^import[\s\S]*?from\s*['"][^'"]+['"];?[ \t]*$/gm)].at(-1);
|
|
418
|
+
if (!last || last.index === void 0) return `${line}\n\n${source}`;
|
|
419
|
+
const end = last.index + last[0].length;
|
|
420
|
+
return `${source.slice(0, end)}\n${line}${source.slice(end)}`;
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Appends `item` to the first `key: [...]` array in `source`. Returns `undefined` when there
|
|
424
|
+
* is no such array, so the caller can tell the user to register by hand.
|
|
425
|
+
*/
|
|
426
|
+
function addToArray(source, key, item) {
|
|
427
|
+
const match = new RegExp(`(\\b${key}\\s*:\\s*\\[)([^\\]]*)(\\])`).exec(source);
|
|
428
|
+
if (!match) return void 0;
|
|
429
|
+
const [whole, open = "", body = "", close = ""] = match;
|
|
430
|
+
if (new RegExp(`\\b${item}\\b`).test(body)) return source;
|
|
431
|
+
let next;
|
|
432
|
+
if (body.trim() === "") next = `${open}${item}${close}`;
|
|
433
|
+
else if (body.includes("\n")) {
|
|
434
|
+
const indent = /\n([ \t]*)\S/.exec(body)?.[1] ?? " ";
|
|
435
|
+
const closing = /\n([ \t]*)$/.exec(body)?.[1] ?? "";
|
|
436
|
+
next = `${open}${body.trimEnd().replace(/,$/, "")},\n${indent}${item},\n${closing}${close}`;
|
|
437
|
+
} else next = `${open}${body.trim().replace(/,$/, "")}, ${item}${close}`;
|
|
438
|
+
return source.slice(0, match.index) + next + source.slice(match.index + whole.length);
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Adds `key: [item]` as the first property of the options object passed to `feature(...)`,
|
|
442
|
+
* for a feature that does not have that array yet.
|
|
443
|
+
*/
|
|
444
|
+
function addArrayToFeature(source, key, item) {
|
|
445
|
+
const match = /feature\(\s*['"][^'"]*['"]\s*,\s*\{/.exec(source);
|
|
446
|
+
if (!match) return void 0;
|
|
447
|
+
const at = match.index + match[0].length;
|
|
448
|
+
const rest = source.slice(at);
|
|
449
|
+
if (/^\s*\}/.test(rest)) return `${source.slice(0, at)} ${key}: [${item}] ${rest.trimStart()}`;
|
|
450
|
+
const indent = /^\n([ \t]*)/.exec(rest)?.[1];
|
|
451
|
+
return indent === void 0 ? `${source.slice(0, at)} ${key}: [${item}],${rest}` : `${source.slice(0, at)}\n${indent}${key}: [${item}],${rest}`;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// src/schematics.ts
|
|
455
|
+
const SCHEMATICS = {
|
|
456
|
+
feature: {
|
|
457
|
+
alias: "f",
|
|
458
|
+
description: "A feature: a named group of routes and services"
|
|
459
|
+
},
|
|
460
|
+
routes: {
|
|
461
|
+
alias: "r",
|
|
462
|
+
description: "A routes class (or a route group with --classless)"
|
|
463
|
+
},
|
|
464
|
+
service: {
|
|
465
|
+
alias: "s",
|
|
466
|
+
description: "A service class (or service() with --classless)"
|
|
467
|
+
},
|
|
468
|
+
middleware: {
|
|
469
|
+
alias: "mw",
|
|
470
|
+
description: "A middleware"
|
|
471
|
+
},
|
|
472
|
+
resource: {
|
|
473
|
+
alias: "res",
|
|
474
|
+
description: "A CRUD feature: routes, service, schemas and a test"
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
function resolveSchematic(input) {
|
|
478
|
+
for (const [name, { alias }] of Object.entries(SCHEMATICS)) if (input === name || input === alias) return name;
|
|
479
|
+
throw new CliError(`Unknown schematic "${input}". Available: ${Object.entries(SCHEMATICS).map(([name, { alias }]) => `${name} (${alias})`).join(", ")}.`);
|
|
480
|
+
}
|
|
481
|
+
function target(project, input, options, ownFolder = true) {
|
|
482
|
+
const { dir, name } = splitPath(input);
|
|
483
|
+
const n = names(name);
|
|
484
|
+
const folder = [
|
|
485
|
+
project.sourceRoot,
|
|
486
|
+
dir,
|
|
487
|
+
ownFolder && !options.flat ? n.kebab : ""
|
|
488
|
+
].filter(Boolean).join("/");
|
|
489
|
+
return {
|
|
490
|
+
n,
|
|
491
|
+
dir: folder,
|
|
492
|
+
file: (suffix) => `${folder}/${n.kebab}.${suffix}.ts`
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
/** Edits `file` so it imports `symbol` and lists it under `key`. Leaves a note when it cannot. */
|
|
496
|
+
function register(plan, project, options, file, key, symbol, from) {
|
|
497
|
+
if (options.skipImport) return;
|
|
498
|
+
const source = plan.read(file);
|
|
499
|
+
if (source === void 0) return;
|
|
500
|
+
const listed = addToArray(source, key, symbol) ?? addArrayToFeature(source, key, symbol);
|
|
501
|
+
if (listed === void 0) {
|
|
502
|
+
plan.note(`Could not find where to add ${symbol} in ${file}. Add it to \`${key}\` by hand.`);
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
plan.update(file, addImport(listed, symbol, importPath(file, from, project.importExtension)));
|
|
506
|
+
}
|
|
507
|
+
/** Registers a feature with the app: in `app.feature.ts` if there is one, else in the entry file. */
|
|
508
|
+
function registerFeature(plan, project, options, symbol, from) {
|
|
509
|
+
if (options.skipImport) return;
|
|
510
|
+
const appFeature = `${project.sourceRoot}/app.feature.ts`;
|
|
511
|
+
if (plan.exists(appFeature)) register(plan, project, options, appFeature, "imports", symbol, from);
|
|
512
|
+
else if (plan.exists(project.entry)) register(plan, project, options, project.entry, "features", symbol, from);
|
|
513
|
+
else plan.note(`Add ${symbol} to your app's features.`);
|
|
514
|
+
}
|
|
515
|
+
function featureFile(t) {
|
|
516
|
+
return `import { feature } from '@sukujs/core';
|
|
517
|
+
|
|
518
|
+
export const ${t.n.pascal}Feature = feature('${t.n.kebab}', {
|
|
519
|
+
routes: [],
|
|
520
|
+
services: [],
|
|
521
|
+
});
|
|
522
|
+
`;
|
|
523
|
+
}
|
|
524
|
+
function routesFile(t, options) {
|
|
525
|
+
if (options.classless) return {
|
|
526
|
+
symbol: `${t.n.camel}Routes`,
|
|
527
|
+
content: `import { route } from '@sukujs/core';
|
|
528
|
+
|
|
529
|
+
export const ${t.n.camel}Routes = route.group('/${t.n.kebab}', {
|
|
530
|
+
list: route.get('/', {
|
|
531
|
+
handle: () => [],
|
|
532
|
+
}),
|
|
533
|
+
});
|
|
534
|
+
`
|
|
535
|
+
};
|
|
536
|
+
return {
|
|
537
|
+
symbol: `${t.n.pascal}Routes`,
|
|
538
|
+
content: `import { Routes, route } from '@sukujs/core';
|
|
539
|
+
|
|
540
|
+
@Routes('/${t.n.kebab}')
|
|
541
|
+
export class ${t.n.pascal}Routes {
|
|
542
|
+
list = route.get('/', {
|
|
543
|
+
handle: () => [],
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
`
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
function serviceFile(t, options) {
|
|
550
|
+
if (options.classless) return {
|
|
551
|
+
symbol: `${t.n.pascal}Service`,
|
|
552
|
+
content: `import { service } from '@sukujs/core';
|
|
553
|
+
|
|
554
|
+
export const ${t.n.pascal}Service = service('${t.n.kebab}', () => ({
|
|
555
|
+
// methods go here
|
|
556
|
+
}));
|
|
557
|
+
`
|
|
558
|
+
};
|
|
559
|
+
return {
|
|
560
|
+
symbol: `${t.n.pascal}Service`,
|
|
561
|
+
content: `import { Service } from '@sukujs/core';
|
|
562
|
+
|
|
563
|
+
@Service()
|
|
564
|
+
export class ${t.n.pascal}Service {}
|
|
565
|
+
`
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
function middlewareFile(t) {
|
|
569
|
+
return `import { middleware } from '@sukujs/core';
|
|
570
|
+
|
|
571
|
+
export const ${t.n.camel} = middleware(async (ctx, next) => {
|
|
572
|
+
// before the handler
|
|
573
|
+
const response = await next();
|
|
574
|
+
// after the handler
|
|
575
|
+
return response;
|
|
576
|
+
});
|
|
577
|
+
`;
|
|
578
|
+
}
|
|
579
|
+
function resourceFiles(t, project) {
|
|
580
|
+
const ext = project.importExtension;
|
|
581
|
+
const one = names(singular(t.n.kebab));
|
|
582
|
+
const { kebab, pascal } = t.n;
|
|
583
|
+
return {
|
|
584
|
+
schemas: `import { z } from 'zod';
|
|
585
|
+
|
|
586
|
+
export const Create${one.pascal} = z.object({
|
|
587
|
+
name: z.string().min(1),
|
|
588
|
+
});
|
|
589
|
+
export type Create${one.pascal} = z.infer<typeof Create${one.pascal}>;
|
|
590
|
+
|
|
591
|
+
export const Update${one.pascal} = Create${one.pascal}.partial();
|
|
592
|
+
export type Update${one.pascal} = z.infer<typeof Update${one.pascal}>;
|
|
593
|
+
|
|
594
|
+
export const ${one.pascal}Id = z.object({ id: z.coerce.number().int().positive() });
|
|
595
|
+
|
|
596
|
+
export interface ${one.pascal} extends Create${one.pascal} {
|
|
597
|
+
id: number;
|
|
598
|
+
}
|
|
599
|
+
`,
|
|
600
|
+
service: `import { NotFoundException, Service } from '@sukujs/core';
|
|
601
|
+
import type { Create${one.pascal}, ${one.pascal}, Update${one.pascal} } from './${kebab}.schemas${ext}';
|
|
602
|
+
|
|
603
|
+
/** Keeps ${kebab} in memory. Replace the map with a repository when you add a database. */
|
|
604
|
+
@Service()
|
|
605
|
+
export class ${pascal}Service {
|
|
606
|
+
private readonly items = new Map<number, ${one.pascal}>();
|
|
607
|
+
private nextId = 1;
|
|
608
|
+
|
|
609
|
+
findAll(): ${one.pascal}[] {
|
|
610
|
+
return [...this.items.values()];
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
findOne(id: number): ${one.pascal} {
|
|
614
|
+
const item = this.items.get(id);
|
|
615
|
+
if (!item) throw new NotFoundException(\`${one.pascal} \${id} not found\`);
|
|
616
|
+
return item;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
create(input: Create${one.pascal}): ${one.pascal} {
|
|
620
|
+
const item = { id: this.nextId++, ...input };
|
|
621
|
+
this.items.set(item.id, item);
|
|
622
|
+
return item;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
update(id: number, input: Update${one.pascal}): ${one.pascal} {
|
|
626
|
+
const item = { ...this.findOne(id), ...input } as ${one.pascal};
|
|
627
|
+
this.items.set(id, item);
|
|
628
|
+
return item;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
remove(id: number): void {
|
|
632
|
+
this.findOne(id);
|
|
633
|
+
this.items.delete(id);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
`,
|
|
637
|
+
routes: `import { Routes, route } from '@sukujs/core';
|
|
638
|
+
import { Create${one.pascal}, ${one.pascal}Id, Update${one.pascal} } from './${kebab}.schemas${ext}';
|
|
639
|
+
import { ${pascal}Service } from './${kebab}.service${ext}';
|
|
640
|
+
|
|
641
|
+
@Routes('/${kebab}')
|
|
642
|
+
export class ${pascal}Routes {
|
|
643
|
+
constructor(private readonly ${t.n.camel}: ${pascal}Service) {}
|
|
644
|
+
|
|
645
|
+
list = route.get('/', {
|
|
646
|
+
handle: () => this.${t.n.camel}.findAll(),
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
findOne = route.get('/:id', {
|
|
650
|
+
params: ${one.pascal}Id,
|
|
651
|
+
handle: ({ params }) => this.${t.n.camel}.findOne(params.id),
|
|
652
|
+
});
|
|
653
|
+
|
|
654
|
+
create = route.post('/', {
|
|
655
|
+
body: Create${one.pascal},
|
|
656
|
+
handle: ({ body }) => this.${t.n.camel}.create(body),
|
|
657
|
+
});
|
|
658
|
+
|
|
659
|
+
update = route.patch('/:id', {
|
|
660
|
+
params: ${one.pascal}Id,
|
|
661
|
+
body: Update${one.pascal},
|
|
662
|
+
handle: ({ params, body }) => this.${t.n.camel}.update(params.id, body),
|
|
663
|
+
});
|
|
664
|
+
|
|
665
|
+
remove = route.delete('/:id', {
|
|
666
|
+
params: ${one.pascal}Id,
|
|
667
|
+
handle: ({ params }) => this.${t.n.camel}.remove(params.id),
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
`,
|
|
671
|
+
feature: `import { feature } from '@sukujs/core';
|
|
672
|
+
import { ${pascal}Routes } from './${kebab}.routes${ext}';
|
|
673
|
+
import { ${pascal}Service } from './${kebab}.service${ext}';
|
|
674
|
+
|
|
675
|
+
export const ${pascal}Feature = feature('${kebab}', {
|
|
676
|
+
routes: [${pascal}Routes],
|
|
677
|
+
services: [${pascal}Service],
|
|
678
|
+
});
|
|
679
|
+
`,
|
|
680
|
+
test: `import { expect, test } from 'bun:test';
|
|
681
|
+
import { Suku } from '@sukujs/core';
|
|
682
|
+
import { ${pascal}Feature } from './${kebab}.feature${ext}';
|
|
683
|
+
|
|
684
|
+
const json = (method: string, path: string, body?: unknown) =>
|
|
685
|
+
new Request(\`http://test\${path}\`, {
|
|
686
|
+
method,
|
|
687
|
+
headers: { 'content-type': 'application/json' },
|
|
688
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
689
|
+
});
|
|
690
|
+
|
|
691
|
+
test('${kebab}: create, read, update and delete', async () => {
|
|
692
|
+
const app = await Suku.create({ features: [${pascal}Feature] });
|
|
693
|
+
|
|
694
|
+
const created = await app.handle(json('POST', '/${kebab}', { name: 'First' }));
|
|
695
|
+
expect(created.status).toBe(201);
|
|
696
|
+
expect(await created.json()).toEqual({ id: 1, name: 'First' });
|
|
697
|
+
|
|
698
|
+
const updated = await app.handle(json('PATCH', '/${kebab}/1', { name: 'Renamed' }));
|
|
699
|
+
expect(await updated.json()).toEqual({ id: 1, name: 'Renamed' });
|
|
700
|
+
|
|
701
|
+
expect(await (await app.handle(json('GET', '/${kebab}'))).json()).toHaveLength(1);
|
|
702
|
+
expect((await app.handle(json('POST', '/${kebab}', {}))).status).toBe(400);
|
|
703
|
+
|
|
704
|
+
expect((await app.handle(json('DELETE', '/${kebab}/1'))).status).toBe(204);
|
|
705
|
+
expect((await app.handle(json('GET', '/${kebab}/1'))).status).toBe(404);
|
|
706
|
+
});
|
|
707
|
+
`
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
/** Adds the files for one schematic to `plan`, and the edits that register them. */
|
|
711
|
+
function generate(plan, project, schematic, input, options = {}) {
|
|
712
|
+
switch (schematic) {
|
|
713
|
+
case "feature": {
|
|
714
|
+
const t = target(project, input, options);
|
|
715
|
+
plan.create(t.file("feature"), featureFile(t));
|
|
716
|
+
registerFeature(plan, project, options, `${t.n.pascal}Feature`, t.file("feature"));
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
case "routes": {
|
|
720
|
+
const t = target(project, input, options);
|
|
721
|
+
const { symbol, content } = routesFile(t, options);
|
|
722
|
+
plan.create(t.file("routes"), content);
|
|
723
|
+
register(plan, project, options, t.file("feature"), "routes", symbol, t.file("routes"));
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
case "service": {
|
|
727
|
+
const t = target(project, input, options);
|
|
728
|
+
const { symbol, content } = serviceFile(t, options);
|
|
729
|
+
plan.create(t.file("service"), content);
|
|
730
|
+
register(plan, project, options, t.file("feature"), "services", symbol, t.file("service"));
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
case "middleware": {
|
|
734
|
+
const t = target(project, !/[\\/]/.test(input) ? `middlewares/${input}` : input, options, false);
|
|
735
|
+
plan.create(t.file("middleware"), middlewareFile(t));
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
case "resource": {
|
|
739
|
+
const t = target(project, input, options);
|
|
740
|
+
const files = resourceFiles(t, project);
|
|
741
|
+
for (const [suffix, content] of Object.entries(files)) {
|
|
742
|
+
if (suffix === "test" && options.skipTests) continue;
|
|
743
|
+
plan.create(t.file(suffix), content);
|
|
744
|
+
}
|
|
745
|
+
registerFeature(plan, project, options, `${t.n.pascal}Feature`, t.file("feature"));
|
|
746
|
+
if (!project.dependencies.zod) plan.note("The schemas use zod, which is not in package.json. Install it: bun add zod");
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// src/starter.ts
|
|
753
|
+
/** The files of a new project, keyed by path. */
|
|
754
|
+
function starter(options) {
|
|
755
|
+
const { name, runtime, version, packageManager = "bun", deploy = [] } = options;
|
|
756
|
+
const extra = deployFiles(name, runtime, deploy);
|
|
757
|
+
const pm = packageManager;
|
|
758
|
+
const pmx = pm === "bun" ? "bunx" : pm === "pnpm" ? "pnpm exec" : pm === "yarn" ? "yarn" : "npx";
|
|
759
|
+
const explicitInject = deploy.includes("vercel");
|
|
760
|
+
const platform = runtime === "bun" ? "platform-bun" : "platform-node";
|
|
761
|
+
const adapter = runtime === "bun" ? "bunAdapter" : "nodeAdapter";
|
|
762
|
+
const range = `^${version}`;
|
|
763
|
+
const pkg = {
|
|
764
|
+
name,
|
|
765
|
+
version: "0.0.1",
|
|
766
|
+
private: true,
|
|
767
|
+
type: "module",
|
|
768
|
+
scripts: {
|
|
769
|
+
dev: "suku dev",
|
|
770
|
+
build: "suku build",
|
|
771
|
+
start: "suku start",
|
|
772
|
+
test: "bun test",
|
|
773
|
+
typecheck: "tsc --noEmit",
|
|
774
|
+
...extra.scripts
|
|
775
|
+
},
|
|
776
|
+
suku: { runtime },
|
|
777
|
+
dependencies: {
|
|
778
|
+
"@sukujs/core": range,
|
|
779
|
+
[`@sukujs/${platform}`]: range,
|
|
780
|
+
"@sukujs/security": range,
|
|
781
|
+
zod: "^4.0.0"
|
|
782
|
+
},
|
|
783
|
+
devDependencies: {
|
|
784
|
+
"@sukujs/cli": range,
|
|
785
|
+
"@types/bun": "latest",
|
|
786
|
+
"@types/node": "^22.0.0",
|
|
787
|
+
typescript: "^5.9.0",
|
|
788
|
+
...extra.devDependencies
|
|
789
|
+
}
|
|
790
|
+
};
|
|
791
|
+
const tsconfig = {
|
|
792
|
+
compilerOptions: {
|
|
793
|
+
target: "ES2022",
|
|
794
|
+
module: "ESNext",
|
|
795
|
+
moduleResolution: "Bundler",
|
|
796
|
+
lib: ["ES2023"],
|
|
797
|
+
types: ["node", "bun"],
|
|
798
|
+
strict: true,
|
|
799
|
+
experimentalDecorators: true,
|
|
800
|
+
emitDecoratorMetadata: true,
|
|
801
|
+
useDefineForClassFields: false,
|
|
802
|
+
skipLibCheck: true,
|
|
803
|
+
noEmit: true
|
|
804
|
+
},
|
|
805
|
+
include: deploy.includes("vercel") ? ["src", "api"] : ["src"]
|
|
806
|
+
};
|
|
807
|
+
return {
|
|
808
|
+
"package.json": `${JSON.stringify(pkg, null, 2)}\n`,
|
|
809
|
+
"tsconfig.json": `${JSON.stringify(tsconfig, null, 2)}\n`,
|
|
810
|
+
".gitignore": "node_modules/\ndist/\n.env\n.DS_Store\n",
|
|
811
|
+
".env.example": "PORT=3000\n",
|
|
812
|
+
"README.md": `# ${name}
|
|
813
|
+
|
|
814
|
+
A [Suku](https://github.com/sukujs/sukujs) API.
|
|
815
|
+
|
|
816
|
+
\`\`\`bash
|
|
817
|
+
${pm} run dev # start with reload on change
|
|
818
|
+
${pm} run test # run the tests
|
|
819
|
+
${pm} run build # bundle to dist/
|
|
820
|
+
${pm} run start # run the bundle with ${runtime === "bun" ? "Bun" : "Node"}
|
|
821
|
+
\`\`\`
|
|
822
|
+
|
|
823
|
+
The \`dev\`, \`build\` and \`test\` commands use [Bun](https://bun.sh).
|
|
824
|
+
|
|
825
|
+
## Generate code
|
|
826
|
+
|
|
827
|
+
\`\`\`bash
|
|
828
|
+
${pmx} suku generate resource products # a CRUD feature with a test
|
|
829
|
+
${pmx} suku generate feature billing
|
|
830
|
+
${pmx} suku generate routes billing
|
|
831
|
+
${pmx} suku generate service billing
|
|
832
|
+
${pmx} suku generate middleware audit
|
|
833
|
+
\`\`\`
|
|
834
|
+
${extra.readme.length > 0 ? `\n## Deploy\n\n${extra.readme.join("\n\n")}\n` : ""}`,
|
|
835
|
+
"src/main.ts": `import { Suku } from '@sukujs/core';
|
|
836
|
+
import { ${adapter} } from '@sukujs/${platform}';
|
|
837
|
+
import { securityHeaders } from '@sukujs/security';
|
|
838
|
+
import { AppFeature } from './app.feature';
|
|
839
|
+
import { Env } from './config';
|
|
840
|
+
|
|
841
|
+
const app = await Suku.create({
|
|
842
|
+
features: [Env.load(), AppFeature],
|
|
843
|
+
// Defensive headers on every response, including 404s and errors.
|
|
844
|
+
middlewares: [securityHeaders()],
|
|
845
|
+
adapter: ${adapter}(),
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
const server = await app.listen(app.get(Env).PORT);
|
|
849
|
+
console.log(\`listening on \${server.url}\`);
|
|
850
|
+
|
|
851
|
+
// Finish requests in flight, then close. Give up after ten seconds.
|
|
852
|
+
let closing = false;
|
|
853
|
+
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
|
854
|
+
process.on(signal, () => {
|
|
855
|
+
if (closing) return;
|
|
856
|
+
closing = true;
|
|
857
|
+
const deadline = setTimeout(() => void app.close({ force: true }), 10_000);
|
|
858
|
+
void app.close().finally(() => {
|
|
859
|
+
clearTimeout(deadline);
|
|
860
|
+
process.exit(0);
|
|
861
|
+
});
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
`,
|
|
865
|
+
"src/config.ts": `import { defineConfig } from '@sukujs/core';
|
|
866
|
+
import { z } from 'zod';
|
|
867
|
+
|
|
868
|
+
/** Validated when the app starts. A missing or malformed variable stops it before it listens. */
|
|
869
|
+
export const Env = defineConfig(
|
|
870
|
+
'env',
|
|
871
|
+
z.object({
|
|
872
|
+
PORT: z.coerce.number().int().min(0).default(3000),
|
|
873
|
+
}),
|
|
874
|
+
);
|
|
875
|
+
`,
|
|
876
|
+
"src/app.feature.ts": `import { feature, route } from '@sukujs/core';
|
|
877
|
+
import { HelloFeature } from './hello/hello.feature';
|
|
878
|
+
|
|
879
|
+
export const health = route.get('/health', {
|
|
880
|
+
handle: () => ({ status: 'ok' }),
|
|
881
|
+
});
|
|
882
|
+
|
|
883
|
+
/** The root feature. \`suku generate feature\` and \`resource\` add theirs to \`imports\`. */
|
|
884
|
+
export const AppFeature = feature('app', {
|
|
885
|
+
imports: [HelloFeature],
|
|
886
|
+
routes: [health],
|
|
887
|
+
});
|
|
888
|
+
`,
|
|
889
|
+
"src/hello/hello.feature.ts": `import { feature } from '@sukujs/core';
|
|
890
|
+
import { HelloRoutes } from './hello.routes';
|
|
891
|
+
import { HelloService } from './hello.service';
|
|
892
|
+
|
|
893
|
+
export const HelloFeature = feature('hello', {
|
|
894
|
+
routes: [HelloRoutes],
|
|
895
|
+
services: [HelloService],
|
|
896
|
+
});
|
|
897
|
+
`,
|
|
898
|
+
"src/hello/hello.service.ts": `import { Service } from '@sukujs/core';
|
|
899
|
+
|
|
900
|
+
@Service()
|
|
901
|
+
export class HelloService {
|
|
902
|
+
greet(name: string): string {
|
|
903
|
+
return \`Hello, \${name}!\`;
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
`,
|
|
907
|
+
"src/hello/hello.routes.ts": `import { Routes, route } from '@sukujs/core';
|
|
908
|
+
import { z } from 'zod';
|
|
909
|
+
import { HelloService } from './hello.service';
|
|
910
|
+
|
|
911
|
+
@Routes('/hello')
|
|
912
|
+
export class HelloRoutes {${explicitInject ? "\n static inject = [HelloService];\n" : ""}
|
|
913
|
+
constructor(private readonly hello: HelloService) {}
|
|
914
|
+
|
|
915
|
+
greet = route.get('/:name', {
|
|
916
|
+
params: z.object({ name: z.string().min(1).max(50) }),
|
|
917
|
+
handle: ({ params }) => ({ message: this.hello.greet(params.name) }),
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
`,
|
|
921
|
+
"src/app.test.ts": `import { expect, test } from 'bun:test';
|
|
922
|
+
import { Suku } from '@sukujs/core';
|
|
923
|
+
import { AppFeature } from './app.feature';
|
|
924
|
+
|
|
925
|
+
// No adapter and no port: app.handle runs a request through the whole app in process.
|
|
926
|
+
const app = await Suku.create({ features: [AppFeature] });
|
|
927
|
+
const get = (path: string) => app.handle(new Request(\`http://test\${path}\`));
|
|
928
|
+
|
|
929
|
+
test('GET /health', async () => {
|
|
930
|
+
const response = await get('/health');
|
|
931
|
+
expect(response.status).toBe(200);
|
|
932
|
+
expect(await response.json()).toEqual({ status: 'ok' });
|
|
933
|
+
});
|
|
934
|
+
|
|
935
|
+
test('GET /hello/:name', async () => {
|
|
936
|
+
expect(await (await get('/hello/Ada')).json()).toEqual({ message: 'Hello, Ada!' });
|
|
937
|
+
});
|
|
938
|
+
`,
|
|
939
|
+
...extra.files
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// src/commands.ts
|
|
944
|
+
/** The version of this CLI, which is the version of every `@sukujs/*` package. */
|
|
945
|
+
function cliVersion() {
|
|
946
|
+
const file = new URL("../package.json", import.meta.url);
|
|
947
|
+
return JSON.parse(readFileSync(file, "utf8")).version;
|
|
948
|
+
}
|
|
949
|
+
function asRuntime(value, fallback) {
|
|
950
|
+
if (value === void 0) return fallback;
|
|
951
|
+
if (value !== "node" && value !== "bun") throw new CliError(`The runtime must be "node" or "bun", not "${value}".`);
|
|
952
|
+
return value;
|
|
953
|
+
}
|
|
954
|
+
const MANAGERS = [
|
|
955
|
+
"bun",
|
|
956
|
+
"npm",
|
|
957
|
+
"pnpm",
|
|
958
|
+
"yarn"
|
|
959
|
+
];
|
|
960
|
+
/**
|
|
961
|
+
* Creates a project. In a terminal it asks for whatever the flags left open; with `--yes`,
|
|
962
|
+
* or when there is no terminal, it uses the defaults: Node, Bun as the package manager, no
|
|
963
|
+
* deployment files, a git repository and an install.
|
|
964
|
+
*/
|
|
965
|
+
async function newProject(io, input, options) {
|
|
966
|
+
const ask = options.yes ? void 0 : io.prompter;
|
|
967
|
+
const target = input ?? (ask ? await ask.text("Project name", "my-api") : void 0);
|
|
968
|
+
if (!target) throw new CliError("Usage: suku new <name>");
|
|
969
|
+
const root = resolve(io.cwd, target);
|
|
970
|
+
const name = names(basename(root)).kebab;
|
|
971
|
+
if (existsSync(root) && readdirSync(root).length > 0 && !options.force) throw new CliError(`${target} already exists and is not empty. Pass --force to write into it.`);
|
|
972
|
+
const runtime = asRuntime(options.runtime ?? (ask ? await ask.select("Production runtime", [{
|
|
973
|
+
value: "node",
|
|
974
|
+
label: "Node.js",
|
|
975
|
+
hint: "bundled with Bun, run with Node"
|
|
976
|
+
}, {
|
|
977
|
+
value: "bun",
|
|
978
|
+
label: "Bun"
|
|
979
|
+
}]) : void 0), "node");
|
|
980
|
+
const manager = options.packageManager ?? (ask ? await ask.select("Package manager", MANAGERS.map((value) => ({
|
|
981
|
+
value,
|
|
982
|
+
label: value,
|
|
983
|
+
...value === "bun" ? { hint: "default" } : {}
|
|
984
|
+
}))) : "bun");
|
|
985
|
+
if (!MANAGERS.includes(manager)) throw new CliError(`Unknown package manager "${manager}". Use one of: ${MANAGERS.join(", ")}.`);
|
|
986
|
+
const deploy = options.deploy ? parseDeployTargets(options.deploy) : ask ? await ask.multiselect("Deployment targets", Object.entries(DEPLOY_TARGETS).map(([value, { label, hint }]) => ({
|
|
987
|
+
value,
|
|
988
|
+
label,
|
|
989
|
+
hint
|
|
990
|
+
}))) : [];
|
|
991
|
+
const git = options.skipGit === void 0 && ask ? await ask.confirm("Initialise a git repository?") : !options.skipGit;
|
|
992
|
+
const install = options.skipInstall === void 0 && ask ? await ask.confirm(`Install dependencies with ${manager}?`) : !options.skipInstall;
|
|
993
|
+
const plan = new Plan(root);
|
|
994
|
+
const files = starter({
|
|
995
|
+
name,
|
|
996
|
+
runtime,
|
|
997
|
+
version: cliVersion(),
|
|
998
|
+
packageManager: manager,
|
|
999
|
+
deploy
|
|
1000
|
+
});
|
|
1001
|
+
for (const [path, content] of Object.entries(files)) plan.create(path, content);
|
|
1002
|
+
if (ask) io.log("");
|
|
1003
|
+
plan.commit({
|
|
1004
|
+
log: io.log,
|
|
1005
|
+
...options.dryRun ? { dryRun: true } : {},
|
|
1006
|
+
force: options.force === true
|
|
1007
|
+
});
|
|
1008
|
+
if (options.dryRun) return 0;
|
|
1009
|
+
if (git && versionOf("git")) await exec("git", ["init", "--quiet"], { cwd: root }).catch(() => 1);
|
|
1010
|
+
if (install) {
|
|
1011
|
+
io.log(`\nInstalling dependencies with ${manager}...`);
|
|
1012
|
+
const code = await exec(manager, ["install"], { cwd: root });
|
|
1013
|
+
if (code !== 0) {
|
|
1014
|
+
io.log(`\nThe install failed. Run \`${manager} install\` in ${target} once it is fixed.`);
|
|
1015
|
+
return code;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
io.log(`\nCreated ${name}. Next:\n\n cd ${target}`);
|
|
1019
|
+
if (!install) io.log(` ${manager} install`);
|
|
1020
|
+
io.log(` ${manager} run dev\n`);
|
|
1021
|
+
return 0;
|
|
1022
|
+
}
|
|
1023
|
+
function generateCommand(io, schematic, name, options) {
|
|
1024
|
+
const project = loadProject(io.cwd);
|
|
1025
|
+
const plan = new Plan(project.root);
|
|
1026
|
+
generate(plan, project, resolveSchematic(schematic), name, options);
|
|
1027
|
+
plan.commit({
|
|
1028
|
+
log: io.log,
|
|
1029
|
+
...options.dryRun ? { dryRun: true } : {},
|
|
1030
|
+
force: options.force === true
|
|
1031
|
+
});
|
|
1032
|
+
return 0;
|
|
1033
|
+
}
|
|
1034
|
+
function entryOf(io, override) {
|
|
1035
|
+
const entry = override ?? loadProject(io.cwd).entry;
|
|
1036
|
+
if (!existsSync(join(io.cwd, entry))) throw new CliError(`Entry file ${entry} does not exist.`);
|
|
1037
|
+
return entry;
|
|
1038
|
+
}
|
|
1039
|
+
/** Runs the app with Bun and restarts it when a source file changes. */
|
|
1040
|
+
function dev(io, options, passthrough) {
|
|
1041
|
+
const entry = entryOf(io, options.entry);
|
|
1042
|
+
return exec("bun", [
|
|
1043
|
+
"--watch",
|
|
1044
|
+
entry,
|
|
1045
|
+
...passthrough
|
|
1046
|
+
], {
|
|
1047
|
+
cwd: io.cwd,
|
|
1048
|
+
env: { NODE_ENV: process.env.NODE_ENV ?? "development" }
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
/** Bundles the app, with its dependencies, into one file that the runtime can start. */
|
|
1052
|
+
async function build(io, options) {
|
|
1053
|
+
const project = loadProject(io.cwd);
|
|
1054
|
+
const entry = entryOf(io, options.entry);
|
|
1055
|
+
const target = asRuntime(options.target, project.runtime);
|
|
1056
|
+
const args = [
|
|
1057
|
+
"build",
|
|
1058
|
+
entry,
|
|
1059
|
+
"--target",
|
|
1060
|
+
target,
|
|
1061
|
+
"--outdir",
|
|
1062
|
+
options.outdir ?? "dist"
|
|
1063
|
+
];
|
|
1064
|
+
if (options.minify) args.push("--minify");
|
|
1065
|
+
if (options.sourcemap) args.push("--sourcemap=linked");
|
|
1066
|
+
for (const name of options.external ?? []) args.push("--external", name);
|
|
1067
|
+
const code = await exec("bun", args, { cwd: io.cwd });
|
|
1068
|
+
if (code === 0) io.log(`\nBuilt for ${target}. Start it with: suku start`);
|
|
1069
|
+
return code;
|
|
1070
|
+
}
|
|
1071
|
+
/** Runs the built app with the project's production runtime. */
|
|
1072
|
+
function start(io, options, passthrough) {
|
|
1073
|
+
const project = loadProject(io.cwd);
|
|
1074
|
+
const runtime = asRuntime(options.runtime, project.runtime);
|
|
1075
|
+
const source = options.entry ?? project.entry;
|
|
1076
|
+
const file = join(options.outdir ?? "dist", basename(source).replace(/\.[cm]?tsx?$/, ".js"));
|
|
1077
|
+
if (!existsSync(join(io.cwd, file))) throw new CliError(`${file} does not exist. Run \`suku build\` first.`);
|
|
1078
|
+
return exec(runtime, [file, ...passthrough], {
|
|
1079
|
+
cwd: io.cwd,
|
|
1080
|
+
env: { NODE_ENV: process.env.NODE_ENV ?? "production" }
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
/** Prints the versions that matter when reporting a problem. */
|
|
1084
|
+
function info(io) {
|
|
1085
|
+
io.log(`Suku CLI ${cliVersion()}`);
|
|
1086
|
+
io.log(`Node ${process.version.replace(/^v/, "")}`);
|
|
1087
|
+
io.log(`Bun ${versionOf("bun") ?? "not installed"}`);
|
|
1088
|
+
io.log(`Platform ${process.platform} ${process.arch}`);
|
|
1089
|
+
if (!existsSync(join(io.cwd, "package.json"))) return 0;
|
|
1090
|
+
const project = loadProject(io.cwd);
|
|
1091
|
+
const packages = Object.entries(project.dependencies).filter(([name]) => name.startsWith("@sukujs/"));
|
|
1092
|
+
io.log(`Runtime ${project.runtime}`);
|
|
1093
|
+
io.log(`Entry ${project.entry}`);
|
|
1094
|
+
for (const [name, range] of packages.sort()) {
|
|
1095
|
+
const installed = join(io.cwd, "node_modules", name, "package.json");
|
|
1096
|
+
const version = existsSync(installed) ? JSON.parse(readFileSync(installed, "utf8")).version : "not installed";
|
|
1097
|
+
io.log(`${name.padEnd(24)} ${version} (wanted ${range})`);
|
|
1098
|
+
}
|
|
1099
|
+
return 0;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
// src/prompts.ts
|
|
1103
|
+
const dim = (text) => `\x1b[2m${text}\x1b[22m`;
|
|
1104
|
+
const cyan = (text) => `\x1b[36m${text}\x1b[39m`;
|
|
1105
|
+
const bold = (text) => `\x1b[1m${text}\x1b[22m`;
|
|
1106
|
+
/**
|
|
1107
|
+
* Questions for the terminal: arrow keys to move, space to toggle, enter to confirm. It has
|
|
1108
|
+
* no dependencies and reads keys from any stream, which is how the tests drive it.
|
|
1109
|
+
*/
|
|
1110
|
+
var Prompter = class {
|
|
1111
|
+
constructor(input = process.stdin, output = process.stdout) {
|
|
1112
|
+
this.input = input;
|
|
1113
|
+
this.output = output;
|
|
1114
|
+
}
|
|
1115
|
+
/** Runs one question: draws it, feeds it keys until it returns a value, then tidies up. */
|
|
1116
|
+
ask(render, onKey, summary) {
|
|
1117
|
+
return new Promise((resolve, reject) => {
|
|
1118
|
+
const { input, output } = this;
|
|
1119
|
+
let lines = 0;
|
|
1120
|
+
const draw = (content) => {
|
|
1121
|
+
if (lines > 0) output.write(`\x1b[${lines}A\x1b[0J`);
|
|
1122
|
+
output.write(`${content.join("\n")}\n`);
|
|
1123
|
+
lines = content.length;
|
|
1124
|
+
};
|
|
1125
|
+
const finish = () => {
|
|
1126
|
+
input.off("keypress", listener);
|
|
1127
|
+
input.setRawMode?.(false);
|
|
1128
|
+
input.pause();
|
|
1129
|
+
};
|
|
1130
|
+
const listener = (text, key = {}) => {
|
|
1131
|
+
if (key.ctrl && key.name === "c") {
|
|
1132
|
+
finish();
|
|
1133
|
+
output.write("\n");
|
|
1134
|
+
reject(new CliError("Cancelled."));
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
const result = onKey(key, text ?? "");
|
|
1138
|
+
if (result) {
|
|
1139
|
+
finish();
|
|
1140
|
+
draw([summary(result.done)]);
|
|
1141
|
+
resolve(result.done);
|
|
1142
|
+
} else draw(render());
|
|
1143
|
+
};
|
|
1144
|
+
emitKeypressEvents(input);
|
|
1145
|
+
input.setRawMode?.(true);
|
|
1146
|
+
input.resume();
|
|
1147
|
+
input.on("keypress", listener);
|
|
1148
|
+
draw(render());
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
/** Free text. Enter with nothing typed accepts the default. */
|
|
1152
|
+
text(question, fallback = "") {
|
|
1153
|
+
let value = "";
|
|
1154
|
+
return this.ask(() => [`${bold(question)} ${value || dim(fallback)}`], (key, text) => {
|
|
1155
|
+
if (key.name === "return" || key.name === "enter") return { done: value.trim() || fallback };
|
|
1156
|
+
if (key.name === "backspace") value = value.slice(0, -1);
|
|
1157
|
+
else if (text.length === 1 && text >= " ") value += text;
|
|
1158
|
+
}, (answer) => `${bold(question)} ${cyan(answer)}`);
|
|
1159
|
+
}
|
|
1160
|
+
/** Yes or no. */
|
|
1161
|
+
confirm(question, fallback = true) {
|
|
1162
|
+
return this.ask(() => [`${bold(question)} ${dim(fallback ? "(Y/n)" : "(y/N)")}`], (key) => {
|
|
1163
|
+
if (key.name === "return" || key.name === "enter") return { done: fallback };
|
|
1164
|
+
if (key.name === "y") return { done: true };
|
|
1165
|
+
if (key.name === "n") return { done: false };
|
|
1166
|
+
}, (answer) => `${bold(question)} ${cyan(answer ? "Yes" : "No")}`);
|
|
1167
|
+
}
|
|
1168
|
+
/** Pick one. The first choice is the default. */
|
|
1169
|
+
select(question, choices) {
|
|
1170
|
+
let at = 0;
|
|
1171
|
+
const move = (by) => {
|
|
1172
|
+
at = (at + by + choices.length) % choices.length;
|
|
1173
|
+
};
|
|
1174
|
+
return this.ask(() => [`${bold(question)} ${dim("(arrows to move, enter to choose)")}`, ...choices.map((choice, index) => {
|
|
1175
|
+
const hint = choice.hint ? ` ${dim(choice.hint)}` : "";
|
|
1176
|
+
return index === at ? `${cyan(`> ${choice.label}`)}${hint}` : ` ${choice.label}${hint}`;
|
|
1177
|
+
})], (key) => {
|
|
1178
|
+
if (key.name === "up" || key.name === "k") move(-1);
|
|
1179
|
+
else if (key.name === "down" || key.name === "j") move(1);
|
|
1180
|
+
else if (key.name === "return" || key.name === "enter") return { done: choices[at].value };
|
|
1181
|
+
}, (answer) => `${bold(question)} ${cyan(choices.find((choice) => choice.value === answer)?.label ?? "")}`);
|
|
1182
|
+
}
|
|
1183
|
+
/** Pick any number, including none. */
|
|
1184
|
+
multiselect(question, choices) {
|
|
1185
|
+
let at = 0;
|
|
1186
|
+
const picked = /* @__PURE__ */ new Set();
|
|
1187
|
+
return this.ask(() => [`${bold(question)} ${dim("(space to toggle, enter to confirm)")}`, ...choices.map((choice, index) => {
|
|
1188
|
+
const box = picked.has(index) ? "[x]" : "[ ]";
|
|
1189
|
+
const hint = choice.hint ? ` ${dim(choice.hint)}` : "";
|
|
1190
|
+
const line = `${box} ${choice.label}`;
|
|
1191
|
+
return index === at ? `${cyan(`> ${line}`)}${hint}` : ` ${line}${hint}`;
|
|
1192
|
+
})], (key) => {
|
|
1193
|
+
if (key.name === "up" || key.name === "k") at = (at - 1 + choices.length) % choices.length;
|
|
1194
|
+
else if (key.name === "down" || key.name === "j") at = (at + 1) % choices.length;
|
|
1195
|
+
else if (key.name === "space") {
|
|
1196
|
+
if (picked.has(at)) picked.delete(at);
|
|
1197
|
+
else picked.add(at);
|
|
1198
|
+
} else if (key.name === "return" || key.name === "enter") return { done: [...picked].sort((a, b) => a - b).map((index) => choices[index].value) };
|
|
1199
|
+
}, (answer) => {
|
|
1200
|
+
const labels = choices.filter((choice) => answer.includes(choice.value)).map((c) => c.label);
|
|
1201
|
+
return `${bold(question)} ${cyan(labels.length > 0 ? labels.join(", ") : "None")}`;
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
|
|
1206
|
+
// src/index.ts
|
|
1207
|
+
const HELP = `Suku CLI
|
|
1208
|
+
|
|
1209
|
+
Usage: suku <command> [options]
|
|
1210
|
+
|
|
1211
|
+
Commands:
|
|
1212
|
+
new [name] Create a project, asking for the options
|
|
1213
|
+
generate <schematic> <name> Generate code (alias: g)
|
|
1214
|
+
dev Run the app and restart on change
|
|
1215
|
+
build Bundle the app into dist/
|
|
1216
|
+
start Run the built app
|
|
1217
|
+
info Print versions, for bug reports
|
|
1218
|
+
|
|
1219
|
+
Schematics:
|
|
1220
|
+
${Object.entries(SCHEMATICS).map(([name, { alias, description }]) => ` ${`${name} (${alias})`.padEnd(18)} ${description}`).join("\n")}
|
|
1221
|
+
|
|
1222
|
+
Options for new (in a terminal, anything you leave out is asked):
|
|
1223
|
+
--runtime <node|bun> Production runtime (default: node)
|
|
1224
|
+
--package-manager <name> bun, npm, pnpm or yarn (default: bun)
|
|
1225
|
+
--deploy <targets> docker, pm2, systemd, cloudflare, vercel or none
|
|
1226
|
+
(comma-separated or repeated)
|
|
1227
|
+
--skip-install Do not install dependencies
|
|
1228
|
+
--skip-git Do not run git init
|
|
1229
|
+
-y, --yes Ask nothing, use the defaults
|
|
1230
|
+
|
|
1231
|
+
Options for generate:
|
|
1232
|
+
--classless Functions instead of classes
|
|
1233
|
+
--flat Do not create a folder for it
|
|
1234
|
+
--skip-import Do not register it in other files
|
|
1235
|
+
--skip-tests resource: do not generate a test
|
|
1236
|
+
|
|
1237
|
+
Options for dev, build and start:
|
|
1238
|
+
--entry <file> Entry file (default: src/main.ts)
|
|
1239
|
+
--target <node|bun> build: what the bundle runs on
|
|
1240
|
+
--outdir <dir> build, start: output folder (default: dist)
|
|
1241
|
+
--minify, --sourcemap build
|
|
1242
|
+
--external <package> build: leave a package out of the bundle (repeatable)
|
|
1243
|
+
|
|
1244
|
+
Everywhere:
|
|
1245
|
+
-d, --dry-run Show what would be written, write nothing
|
|
1246
|
+
--force Overwrite existing files
|
|
1247
|
+
-h, --help, -v, --version
|
|
1248
|
+
|
|
1249
|
+
Arguments after -- are passed to your app: suku dev -- --port 4000
|
|
1250
|
+
`;
|
|
1251
|
+
const OPTIONS = {
|
|
1252
|
+
runtime: { type: "string" },
|
|
1253
|
+
"package-manager": { type: "string" },
|
|
1254
|
+
"skip-install": { type: "boolean" },
|
|
1255
|
+
"skip-git": { type: "boolean" },
|
|
1256
|
+
deploy: {
|
|
1257
|
+
type: "string",
|
|
1258
|
+
multiple: true
|
|
1259
|
+
},
|
|
1260
|
+
yes: {
|
|
1261
|
+
type: "boolean",
|
|
1262
|
+
short: "y"
|
|
1263
|
+
},
|
|
1264
|
+
classless: { type: "boolean" },
|
|
1265
|
+
flat: { type: "boolean" },
|
|
1266
|
+
"skip-import": { type: "boolean" },
|
|
1267
|
+
"skip-tests": { type: "boolean" },
|
|
1268
|
+
entry: { type: "string" },
|
|
1269
|
+
target: { type: "string" },
|
|
1270
|
+
outdir: { type: "string" },
|
|
1271
|
+
minify: { type: "boolean" },
|
|
1272
|
+
sourcemap: { type: "boolean" },
|
|
1273
|
+
external: {
|
|
1274
|
+
type: "string",
|
|
1275
|
+
multiple: true
|
|
1276
|
+
},
|
|
1277
|
+
"dry-run": {
|
|
1278
|
+
type: "boolean",
|
|
1279
|
+
short: "d"
|
|
1280
|
+
},
|
|
1281
|
+
force: { type: "boolean" },
|
|
1282
|
+
help: {
|
|
1283
|
+
type: "boolean",
|
|
1284
|
+
short: "h"
|
|
1285
|
+
},
|
|
1286
|
+
version: {
|
|
1287
|
+
type: "boolean",
|
|
1288
|
+
short: "v"
|
|
1289
|
+
}
|
|
1290
|
+
};
|
|
1291
|
+
/** Drops keys whose value is `undefined`, so optional properties stay absent. */
|
|
1292
|
+
function defined(object) {
|
|
1293
|
+
return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== void 0));
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* Runs the CLI with `argv` (without `node` and the script path) and resolves with the exit
|
|
1297
|
+
* code. Usage mistakes are printed and return `1`; they do not throw. Questions are asked
|
|
1298
|
+
* only when `io.prompter` is given.
|
|
1299
|
+
*/
|
|
1300
|
+
async function run(argv, io = {}) {
|
|
1301
|
+
const out = {
|
|
1302
|
+
cwd: io.cwd ?? process.cwd(),
|
|
1303
|
+
log: io.log ?? console.log,
|
|
1304
|
+
...io.prompter ? { prompter: io.prompter } : {}
|
|
1305
|
+
};
|
|
1306
|
+
const split = argv.indexOf("--");
|
|
1307
|
+
const own = split === -1 ? argv : argv.slice(0, split);
|
|
1308
|
+
const passthrough = split === -1 ? [] : argv.slice(split + 1);
|
|
1309
|
+
try {
|
|
1310
|
+
let parsed;
|
|
1311
|
+
try {
|
|
1312
|
+
parsed = parseArgs({
|
|
1313
|
+
args: own,
|
|
1314
|
+
options: OPTIONS,
|
|
1315
|
+
allowPositionals: true
|
|
1316
|
+
});
|
|
1317
|
+
} catch (error) {
|
|
1318
|
+
throw new CliError(`${error.message.split(". ")[0]}. Run \`suku --help\`.`);
|
|
1319
|
+
}
|
|
1320
|
+
const { values, positionals } = parsed;
|
|
1321
|
+
const [command, first, second] = positionals;
|
|
1322
|
+
if (values.version) {
|
|
1323
|
+
out.log(cliVersion());
|
|
1324
|
+
return 0;
|
|
1325
|
+
}
|
|
1326
|
+
if (values.help || command === void 0 || command === "help") {
|
|
1327
|
+
out.log(HELP);
|
|
1328
|
+
return 0;
|
|
1329
|
+
}
|
|
1330
|
+
const write = defined({
|
|
1331
|
+
dryRun: values["dry-run"],
|
|
1332
|
+
force: values.force
|
|
1333
|
+
});
|
|
1334
|
+
switch (command) {
|
|
1335
|
+
case "new":
|
|
1336
|
+
case "n": return await newProject(out, first, {
|
|
1337
|
+
...write,
|
|
1338
|
+
...defined({
|
|
1339
|
+
runtime: values.runtime,
|
|
1340
|
+
packageManager: values["package-manager"],
|
|
1341
|
+
deploy: values.deploy,
|
|
1342
|
+
yes: values.yes,
|
|
1343
|
+
skipInstall: values["skip-install"],
|
|
1344
|
+
skipGit: values["skip-git"]
|
|
1345
|
+
})
|
|
1346
|
+
});
|
|
1347
|
+
case "generate":
|
|
1348
|
+
case "g":
|
|
1349
|
+
if (!first || !second) throw new CliError("Usage: suku generate <schematic> <name>");
|
|
1350
|
+
return generateCommand(out, first, second, {
|
|
1351
|
+
...write,
|
|
1352
|
+
...defined({
|
|
1353
|
+
classless: values.classless,
|
|
1354
|
+
flat: values.flat,
|
|
1355
|
+
skipImport: values["skip-import"],
|
|
1356
|
+
skipTests: values["skip-tests"]
|
|
1357
|
+
})
|
|
1358
|
+
});
|
|
1359
|
+
case "dev": return await dev(out, defined({ entry: values.entry }), passthrough);
|
|
1360
|
+
case "build": return await build(out, defined({
|
|
1361
|
+
entry: values.entry,
|
|
1362
|
+
target: values.target,
|
|
1363
|
+
outdir: values.outdir,
|
|
1364
|
+
minify: values.minify,
|
|
1365
|
+
sourcemap: values.sourcemap,
|
|
1366
|
+
external: values.external
|
|
1367
|
+
}));
|
|
1368
|
+
case "start": return await start(out, defined({
|
|
1369
|
+
entry: values.entry,
|
|
1370
|
+
outdir: values.outdir,
|
|
1371
|
+
runtime: values.runtime
|
|
1372
|
+
}), passthrough);
|
|
1373
|
+
case "info":
|
|
1374
|
+
case "i": return info(out);
|
|
1375
|
+
default: throw new CliError(`Unknown command "${command}". Run \`suku --help\`.`);
|
|
1376
|
+
}
|
|
1377
|
+
} catch (error) {
|
|
1378
|
+
if (error instanceof CliError) {
|
|
1379
|
+
out.log(`Error: ${error.message}`);
|
|
1380
|
+
return 1;
|
|
1381
|
+
}
|
|
1382
|
+
throw error;
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
export { generate as a, names as c, SCHEMATICS as i, DEPLOY_TARGETS as l, Prompter as n, loadProject as o, starter as r, Plan as s, run as t, CliError as u };
|
|
1387
|
+
//# sourceMappingURL=src-DP9MVAe3.mjs.map
|