@cellajs/create-cella 0.5.0 → 0.6.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/README.md +12 -9
- package/dist/index.js +653 -993
- package/dist/index.js.map +1 -1
- package/package.json +31 -25
package/dist/index.js
CHANGED
|
@@ -1,1009 +1,669 @@
|
|
|
1
1
|
#!/usr/bin/env tsx
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { basename as basename2, resolve as resolve3 } from "path";
|
|
2
|
+
import fs, { cp, mkdir, readFile, readdir, rm } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
4
|
+
import { Command, InvalidArgumentError } from "commander";
|
|
5
|
+
import fs$1, { existsSync } from "node:fs";
|
|
7
6
|
import { input, select } from "@inquirer/prompts";
|
|
8
|
-
import
|
|
9
|
-
|
|
10
|
-
// src/constants.ts
|
|
11
|
-
import pc from "picocolors";
|
|
12
|
-
|
|
13
|
-
// package.json
|
|
14
|
-
var package_default = {
|
|
15
|
-
name: "@cellajs/create-cella",
|
|
16
|
-
version: "0.5.0",
|
|
17
|
-
private: false,
|
|
18
|
-
license: "MIT",
|
|
19
|
-
description: "Cella is a TypeScript template to create web apps with sync and offline capabilities.",
|
|
20
|
-
publishConfig: {
|
|
21
|
-
access: "public"
|
|
22
|
-
},
|
|
23
|
-
repository: {
|
|
24
|
-
type: "git",
|
|
25
|
-
url: "https://github.com/cellajs/create-cella"
|
|
26
|
-
},
|
|
27
|
-
homepage: "https://cellajs.com",
|
|
28
|
-
author: "CellaJS <info@cellajs.com>",
|
|
29
|
-
engines: {
|
|
30
|
-
node: "26.x"
|
|
31
|
-
},
|
|
32
|
-
type: "module",
|
|
33
|
-
main: "./dist/index.js",
|
|
34
|
-
files: [
|
|
35
|
-
"dist",
|
|
36
|
-
"index.js",
|
|
37
|
-
"README.md"
|
|
38
|
-
],
|
|
39
|
-
imports: {
|
|
40
|
-
"#/*": "./src/*"
|
|
41
|
-
},
|
|
42
|
-
bin: {
|
|
43
|
-
"create-cella": "index.js"
|
|
44
|
-
},
|
|
45
|
-
scripts: {
|
|
46
|
-
start: "tsx ./src/create-cella-cli.ts",
|
|
47
|
-
try: "tsx ./src/create-cella-cli.ts ../cella-try-app",
|
|
48
|
-
clean: "rimraf ./dist",
|
|
49
|
-
build: "tsup",
|
|
50
|
-
"test-build": "pnpm run build && node index.js",
|
|
51
|
-
prepublishOnly: "pnpm run test:release",
|
|
52
|
-
check: "pnpm ts && pnpm biome check --write .",
|
|
53
|
-
ts: "tsgo --pretty",
|
|
54
|
-
lint: "biome check .",
|
|
55
|
-
"lint:fix": "biome check --write .",
|
|
56
|
-
test: "vitest run",
|
|
57
|
-
"test:release": "pnpm run build && vitest run --config vitest.release.config.ts",
|
|
58
|
-
"test:watch": "vitest",
|
|
59
|
-
prepare: "lefthook install"
|
|
60
|
-
},
|
|
61
|
-
dependencies: {
|
|
62
|
-
"@inquirer/prompts": "^8.7.2",
|
|
63
|
-
commander: "^15.0.0",
|
|
64
|
-
ignore: "^7.0.11",
|
|
65
|
-
"isomorphic-git": "^1.42.5",
|
|
66
|
-
ora: "^9.4.1",
|
|
67
|
-
picocolors: "^1.1.1",
|
|
68
|
-
"validate-npm-package-name": "^8.0.0"
|
|
69
|
-
},
|
|
70
|
-
devDependencies: {
|
|
71
|
-
"@biomejs/biome": "^2.5.15",
|
|
72
|
-
"@commitlint/cli": "^21.2.3",
|
|
73
|
-
"@commitlint/config-conventional": "^21.2.3",
|
|
74
|
-
"@evilmartians/lefthook": "^2.1.15",
|
|
75
|
-
"@types/node": "26.6.3",
|
|
76
|
-
"@types/validate-npm-package-name": "^4.0.2",
|
|
77
|
-
"@typescript/native-preview": "7.0.0-dev.20260707.2",
|
|
78
|
-
rimraf: "^6.1.3",
|
|
79
|
-
tsup: "^8.5.1",
|
|
80
|
-
tsx: "^4.23.15",
|
|
81
|
-
typescript: "6.0.3",
|
|
82
|
-
vitest: "^5.0.3"
|
|
83
|
-
},
|
|
84
|
-
packageManager: "pnpm@11.28.7",
|
|
85
|
-
commitlint: {
|
|
86
|
-
extends: [
|
|
87
|
-
"@commitlint/config-conventional"
|
|
88
|
-
],
|
|
89
|
-
rules: {
|
|
90
|
-
"type-enum": [
|
|
91
|
-
2,
|
|
92
|
-
"always",
|
|
93
|
-
[
|
|
94
|
-
"feat",
|
|
95
|
-
"fix",
|
|
96
|
-
"perf",
|
|
97
|
-
"refactor",
|
|
98
|
-
"revert",
|
|
99
|
-
"docs",
|
|
100
|
-
"chore",
|
|
101
|
-
"build",
|
|
102
|
-
"ci",
|
|
103
|
-
"style",
|
|
104
|
-
"test"
|
|
105
|
-
]
|
|
106
|
-
]
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
// src/constants.ts
|
|
112
|
-
var NAME = "create cella";
|
|
113
|
-
var DIVIDER = "\u2500".repeat(60);
|
|
114
|
-
var TEMPLATE_URL = "github:cellajs/cella";
|
|
115
|
-
var TEMPLATE_REPOSITORY = "cellajs/cella";
|
|
116
|
-
var TEMPLATE_GIT_URL = `https://github.com/${TEMPLATE_REPOSITORY}.git`;
|
|
117
|
-
var SYNC_CONFIG = "cella/cella.config.ts";
|
|
118
|
-
var CELLA_REMOTE_URL = TEMPLATE_GIT_URL;
|
|
119
|
-
var CELLA_REMOTE_NAME = "cella-upstream";
|
|
120
|
-
var DESCRIPTION = package_default.description;
|
|
121
|
-
var VERSION = package_default.version;
|
|
122
|
-
var WEBSITE = package_default.homepage;
|
|
123
|
-
function getHeaderLine() {
|
|
124
|
-
const leftText = `\u29C8 ${NAME} \xB7 ${VERSION}`;
|
|
125
|
-
const left = `${pc.cyan(`\u29C8 ${NAME}`)} ${pc.dim(`\xB7 ${VERSION}`)}`;
|
|
126
|
-
const right = pc.cyan(WEBSITE);
|
|
127
|
-
const padding = Math.max(1, 60 - leftText.length - WEBSITE.length);
|
|
128
|
-
return `${left}${" ".repeat(padding)}${right}`;
|
|
129
|
-
}
|
|
130
|
-
var TO_REMOVE = ["./infra/Pulumi.production.yaml", "./infra/Pulumi.staging.yaml"];
|
|
131
|
-
var TO_CLEAN = ["./backend/drizzle"];
|
|
132
|
-
var TO_COPY = {
|
|
133
|
-
"./frontend/.env.example": "./frontend/.env"
|
|
134
|
-
};
|
|
135
|
-
var QUICKSTART = "./cella/QUICKSTART.md";
|
|
136
|
-
var AGENT_FILES = {
|
|
137
|
-
"AGENTS.md": "# Agent guidelines\n\nThis app is built from the cella template. Read [cella/AGENTS.md](./cella/AGENTS.md) before changing code: it holds the project rules. Skills, such as `add-entity`, live in [cella/skills](./cella/skills).\n",
|
|
138
|
-
"CLAUDE.md": "@cella/AGENTS.md\n"
|
|
139
|
-
};
|
|
140
|
-
var frontendPort = (appIndex) => 3e3 + appIndex;
|
|
141
|
-
function quickstartToReadme(source, displayName, appIndex) {
|
|
142
|
-
return source.replace(/^# .*$/m, `# ${displayName}`).replace(/^## Create\n[\s\S]*?(?=^## )/m, "").replaceAll("](./", "](./cella/").replaceAll("](../", "](./").replaceAll("http://localhost:3000", `http://localhost:${frontendPort(appIndex)}`);
|
|
143
|
-
}
|
|
144
|
-
var PLACEHOLDER_CONFIG = "shared/config/config.template.ts";
|
|
145
|
-
var INITIAL_VERSION = "0.0.0";
|
|
146
|
-
async function generateEnvFromExample(examplePath, replacements) {
|
|
147
|
-
const { readFile: readFile3 } = await import("fs/promises");
|
|
148
|
-
let content;
|
|
149
|
-
try {
|
|
150
|
-
content = await readFile3(examplePath, "utf8");
|
|
151
|
-
} catch {
|
|
152
|
-
return null;
|
|
153
|
-
}
|
|
154
|
-
return content.replace(/^([A-Z_][A-Z0-9_]*)=(.*)$/gm, (match, key, _value) => {
|
|
155
|
-
if (key in replacements) return `${key}=${replacements[key]}`;
|
|
156
|
-
return match;
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
function getBackendEnvReplacements(adminEmail) {
|
|
160
|
-
return { ADMIN_EMAIL: adminEmail };
|
|
161
|
-
}
|
|
162
|
-
function setDevAppIndex(source, appIndex) {
|
|
163
|
-
const pattern = /^(\s*devAppIndex:\s*)\d+/m;
|
|
164
|
-
if (appIndex !== 0 && !pattern.test(source)) {
|
|
165
|
-
throw new Error("This template has no devAppIndex in its config: use app index 0, or a newer template.");
|
|
166
|
-
}
|
|
167
|
-
return source.replace(pattern, (_, head) => `${head}${appIndex}`);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// src/create.ts
|
|
171
|
-
import { existsSync } from "fs";
|
|
172
|
-
import { cp, mkdir } from "fs/promises";
|
|
173
|
-
import { dirname as dirname2, isAbsolute, join as join4, relative, resolve as resolve2 } from "path";
|
|
174
|
-
import pc5 from "picocolors";
|
|
175
|
-
|
|
176
|
-
// src/utils/git/command.ts
|
|
177
|
-
import fs from "fs";
|
|
7
|
+
import { styleText } from "node:util";
|
|
8
|
+
import { connect } from "node:net";
|
|
178
9
|
import git from "isomorphic-git";
|
|
179
|
-
var INITIAL_AUTHOR = { name: "cella", email: "info@cellajs.com" };
|
|
180
|
-
async function gitInit(repoPath) {
|
|
181
|
-
await git.init({ fs, dir: repoPath, defaultBranch: "main" });
|
|
182
|
-
}
|
|
183
|
-
async function gitAddAll(repoPath) {
|
|
184
|
-
await git.add({ fs, dir: repoPath, filepath: "." });
|
|
185
|
-
}
|
|
186
|
-
async function gitCommit(repoPath, message) {
|
|
187
|
-
return git.commit({ fs, dir: repoPath, message, author: INITIAL_AUTHOR });
|
|
188
|
-
}
|
|
189
|
-
async function gitRemoteGetUrl(repoPath, remoteName) {
|
|
190
|
-
const remotes = await git.listRemotes({ fs, dir: repoPath });
|
|
191
|
-
const match = remotes.find((r) => r.remote === remoteName);
|
|
192
|
-
if (!match) throw new Error(`No such remote '${remoteName}'`);
|
|
193
|
-
return match.url;
|
|
194
|
-
}
|
|
195
|
-
async function gitRemoteAdd(repoPath, remoteName, remoteUrl) {
|
|
196
|
-
await git.addRemote({ fs, dir: repoPath, remote: remoteName, url: remoteUrl });
|
|
197
|
-
}
|
|
198
|
-
async function gitRemoteRemove(repoPath, remoteName) {
|
|
199
|
-
await git.deleteRemote({ fs, dir: repoPath, remote: remoteName });
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// src/add-remote.ts
|
|
203
|
-
async function addRemote({
|
|
204
|
-
targetFolder,
|
|
205
|
-
remoteUrl = CELLA_REMOTE_URL,
|
|
206
|
-
remoteName = CELLA_REMOTE_NAME,
|
|
207
|
-
silent = false
|
|
208
|
-
}) {
|
|
209
|
-
try {
|
|
210
|
-
let remote = null;
|
|
211
|
-
try {
|
|
212
|
-
remote = await gitRemoteGetUrl(targetFolder, remoteName);
|
|
213
|
-
} catch {
|
|
214
|
-
remote = null;
|
|
215
|
-
}
|
|
216
|
-
if (!remote) {
|
|
217
|
-
await gitRemoteAdd(targetFolder, remoteName, remoteUrl);
|
|
218
|
-
} else if (remote !== remoteUrl) {
|
|
219
|
-
await gitRemoteRemove(targetFolder, remoteName);
|
|
220
|
-
await gitRemoteAdd(targetFolder, remoteName, remoteUrl);
|
|
221
|
-
}
|
|
222
|
-
} catch (error) {
|
|
223
|
-
if (!silent) {
|
|
224
|
-
throw error;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
// src/modules/cli/commands.ts
|
|
230
|
-
import { basename, resolve } from "path";
|
|
231
|
-
import { Command, InvalidArgumentError } from "commander";
|
|
232
|
-
|
|
233
|
-
// src/utils/detect-used-ports.ts
|
|
234
|
-
import { readdir, readFile } from "fs/promises";
|
|
235
|
-
import { dirname, join } from "path";
|
|
236
|
-
async function detectUsedPorts(targetFolder) {
|
|
237
|
-
const parentDir = dirname(targetFolder);
|
|
238
|
-
const used = [];
|
|
239
|
-
let siblings;
|
|
240
|
-
try {
|
|
241
|
-
siblings = await readdir(parentDir);
|
|
242
|
-
} catch {
|
|
243
|
-
return used;
|
|
244
|
-
}
|
|
245
|
-
for (const name of siblings) {
|
|
246
|
-
const configDir = join(parentDir, name, "shared/config");
|
|
247
|
-
try {
|
|
248
|
-
const development = await readFile(join(configDir, "config.development.ts"), "utf8");
|
|
249
|
-
const defaults = await readFile(join(configDir, "config.default.ts"), "utf8").catch(() => "");
|
|
250
|
-
const feMatch = development.match(/(?:origin|frontendUrl):\s*'http:\/\/localhost:(\d+)/);
|
|
251
|
-
if (!feMatch) continue;
|
|
252
|
-
const frontend = Number(feMatch[1]);
|
|
253
|
-
const index = Number(defaults.match(/devAppIndex:\s*(\d+)/)?.[1] ?? 0);
|
|
254
|
-
const servicePattern = /backend:\s*\{[^}]*?\bport:\s*(\d+)/;
|
|
255
|
-
const apiPattern = /devPorts:\s*\{[^}]*?\bapi:\s*(\d+)/;
|
|
256
|
-
const portMatch = defaults.match(servicePattern) ?? development.match(apiPattern) ?? defaults.match(apiPattern);
|
|
257
|
-
const legacyBeMatch = development.match(/backendUrl:\s*'http:\/\/localhost:(\d+)'/);
|
|
258
|
-
const backend = portMatch ? Number(portMatch[1]) : legacyBeMatch ? Number(legacyBeMatch[1]) : frontend + 1e3;
|
|
259
|
-
used.push({ project: name, frontend: frontend + index, backend: backend + index * 10 });
|
|
260
|
-
} catch {
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
return used;
|
|
264
|
-
}
|
|
265
|
-
var isAppIndex = (index) => Number.isInteger(index) && index >= 0 && index <= 9 && index !== 4;
|
|
266
|
-
function findNextAppIndex(usedPorts, isBusy = () => false) {
|
|
267
|
-
for (let index = 0; index <= 9; index += 1) {
|
|
268
|
-
if (!isAppIndex(index) || isBusy(index)) continue;
|
|
269
|
-
const api = 4e3 + index * 10;
|
|
270
|
-
const taken = usedPorts.some((p) => p.frontend === 3e3 + index || p.backend >= api && p.backend < api + 10);
|
|
271
|
-
if (!taken) return index;
|
|
272
|
-
}
|
|
273
|
-
return 0;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// src/utils/is-email.ts
|
|
277
|
-
var isEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
|
278
|
-
|
|
279
|
-
// src/utils/validate-project-name.ts
|
|
280
|
-
import validate from "validate-npm-package-name";
|
|
281
|
-
function validateProjectName(name) {
|
|
282
|
-
const nameValidation = validate(name);
|
|
283
|
-
if (nameValidation.validForNewPackages) {
|
|
284
|
-
return { valid: true };
|
|
285
|
-
}
|
|
286
|
-
return {
|
|
287
|
-
valid: false,
|
|
288
|
-
problems: [...nameValidation.errors || [], ...nameValidation.warnings || []]
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
// src/modules/cli/commands.ts
|
|
293
|
-
function parseAppIndex(value) {
|
|
294
|
-
const parsed = Number(value);
|
|
295
|
-
if (!isAppIndex(parsed)) {
|
|
296
|
-
throw new InvalidArgumentError("App index must be a whole number from 0 to 9, not 4");
|
|
297
|
-
}
|
|
298
|
-
return parsed;
|
|
299
|
-
}
|
|
300
|
-
function parseAdminEmail(value) {
|
|
301
|
-
if (!isEmail(value)) throw new InvalidArgumentError("Admin email must be an address such as admin@example.com");
|
|
302
|
-
return value;
|
|
303
|
-
}
|
|
304
|
-
var directory = null;
|
|
305
|
-
var packageManager = "pnpm";
|
|
306
|
-
var command = new Command(NAME).version(VERSION, "-v, --version", `output the current version of ${NAME}`).argument("[directory]", "the directory name for the new project").usage("[directory] [options]").helpOption("-h, --help", "display this help message").option("--template <path>", "use a custom template (local path or github:user/repo)").option("--app-index <number>", "set this app's number for its dev ports (0-9, not 4)", parseAppIndex).option("--admin-email <email>", "set the admin email for the initial seed user", parseAdminEmail).action((name, _options, self) => {
|
|
307
|
-
const trimmedName = typeof name === "string" ? name.trim() : name;
|
|
308
|
-
if (trimmedName) {
|
|
309
|
-
const validation = validateProjectName(basename(resolve(trimmedName)));
|
|
310
|
-
if (!validation.valid) {
|
|
311
|
-
self.error(
|
|
312
|
-
`error: invalid project name "${trimmedName}": ${validation.problems?.[0] ?? "unknown error"}. Use lowercase letters, digits and dashes, such as my-app.`
|
|
313
|
-
);
|
|
314
|
-
}
|
|
315
|
-
directory = trimmedName;
|
|
316
|
-
}
|
|
317
|
-
}).parse();
|
|
318
|
-
var options = command.opts();
|
|
319
|
-
function runCli() {
|
|
320
|
-
return {
|
|
321
|
-
options,
|
|
322
|
-
args: command.args,
|
|
323
|
-
directory,
|
|
324
|
-
packageManager
|
|
325
|
-
};
|
|
326
|
-
}
|
|
327
|
-
var cli = runCli();
|
|
328
|
-
|
|
329
|
-
// src/modules/cli/display.ts
|
|
330
|
-
import pc2 from "picocolors";
|
|
331
|
-
function showAscii() {
|
|
332
|
-
console.info(pc2.cyan(" _ _ "));
|
|
333
|
-
console.info(pc2.cyan("\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2593\u2592 ___ ___| | | __ _ "));
|
|
334
|
-
console.info(pc2.cyan("\u2592\u2593\u2588 \u2588\u2593\u2592 / __/ _ \\ | |/ _` | "));
|
|
335
|
-
console.info(pc2.cyan("\u2592\u2593\u2588 \u2588\u2593\u2592 | (_| __/ | | (_| | "));
|
|
336
|
-
console.info(pc2.cyan("\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2593\u2592 \\___\\___|_|_|\\__,_| "));
|
|
337
|
-
}
|
|
338
|
-
function showWelcome() {
|
|
339
|
-
console.info();
|
|
340
|
-
showAscii();
|
|
341
|
-
console.info();
|
|
342
|
-
console.info(pc2.dim(DESCRIPTION));
|
|
343
|
-
console.info();
|
|
344
|
-
console.info(getHeaderLine());
|
|
345
|
-
console.info(DIVIDER);
|
|
346
|
-
}
|
|
347
|
-
function confirmChoice(label, value) {
|
|
348
|
-
console.info(`${pc2.green("\u2713")} ${label} \xB7 ${value}`);
|
|
349
|
-
console.info();
|
|
350
|
-
}
|
|
351
|
-
function showSuccess(projectName, _targetFolder, relativePath, needsCd, packageManager2, appIndex, adminEmail) {
|
|
352
|
-
console.info();
|
|
353
|
-
console.info(pc2.bold("Next steps"));
|
|
354
|
-
console.info(DIVIDER);
|
|
355
|
-
console.info();
|
|
356
|
-
if (needsCd) {
|
|
357
|
-
console.info(`${pc2.dim("$")} cd ${pc2.cyan(relativePath)}`);
|
|
358
|
-
}
|
|
359
|
-
console.info(`${pc2.dim("$")} ${pc2.cyan(`${packageManager2} install`)}`);
|
|
360
|
-
console.info(`${pc2.dim("$")} ${pc2.cyan(`${packageManager2} generate`)}`);
|
|
361
|
-
console.info(
|
|
362
|
-
`${pc2.dim("$")} ${pc2.cyan(`${packageManager2} docker`)} ${pc2.dim("&&")} ${pc2.cyan(`${packageManager2} seed`)} ${pc2.dim("&&")} ${pc2.cyan(`${packageManager2} dev`)}`
|
|
363
|
-
);
|
|
364
|
-
console.info();
|
|
365
|
-
console.info(
|
|
366
|
-
`${pc2.gray("Then open")} ${pc2.cyan(`http://localhost:${frontendPort(appIndex)}`)} ${pc2.gray("and sign in as")} ${pc2.cyan(adminEmail)}${pc2.gray(`: the magic link is printed in the ${packageManager2} dev output.`)}`
|
|
367
|
-
);
|
|
368
|
-
console.info();
|
|
369
|
-
const readmePath = relativePath ? `${relativePath}/README.md` : "README.md";
|
|
370
|
-
console.info(`${pc2.gray("To get started building, please read:")} ${pc2.cyan(readmePath)}`);
|
|
371
|
-
console.info();
|
|
372
|
-
console.info(`\u{1F973} enjoy building ${pc2.green(projectName)} with cella!`);
|
|
373
|
-
console.info();
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
// src/utils/clean-template.ts
|
|
377
|
-
import fs2 from "fs/promises";
|
|
378
|
-
import path from "path";
|
|
379
|
-
import pc3 from "picocolors";
|
|
380
|
-
var warningMark = pc3.yellow("\u26A0");
|
|
381
|
-
async function cleanTemplate({
|
|
382
|
-
targetFolder,
|
|
383
|
-
projectName,
|
|
384
|
-
displayName,
|
|
385
|
-
appIndex = 0,
|
|
386
|
-
adminEmail = `admin@${projectName}.example.com`
|
|
387
|
-
}) {
|
|
388
|
-
if (process.cwd() !== targetFolder) {
|
|
389
|
-
process.chdir(targetFolder);
|
|
390
|
-
}
|
|
391
|
-
return new Promise((resolve4, reject) => {
|
|
392
|
-
(async () => {
|
|
393
|
-
try {
|
|
394
|
-
for (const [src, dest] of Object.entries(TO_COPY)) {
|
|
395
|
-
const srcAbsolutePath = path.resolve(targetFolder, src);
|
|
396
|
-
const destAbsolutePath = path.resolve(targetFolder, dest);
|
|
397
|
-
await copyFile(srcAbsolutePath, destAbsolutePath);
|
|
398
|
-
}
|
|
399
|
-
await writeReadme(targetFolder, displayName, appIndex);
|
|
400
|
-
await writeAgentEntry(targetFolder);
|
|
401
|
-
await applyPlaceholderConfig(targetFolder, projectName, displayName, appIndex);
|
|
402
|
-
await resetReleaseState(targetFolder, projectName);
|
|
403
|
-
await removeTemplateForks(targetFolder);
|
|
404
|
-
const replacements = getBackendEnvReplacements(adminEmail);
|
|
405
|
-
const rootEnv = await generateEnvFromExample(path.resolve(targetFolder, ".env.example"), replacements);
|
|
406
|
-
const appEnv = rootEnv ?? await generateEnvFromExample(path.resolve(targetFolder, "backend/.env.example"), replacements);
|
|
407
|
-
if (appEnv) {
|
|
408
|
-
await fs2.writeFile(path.resolve(targetFolder, rootEnv ? ".env" : "backend/.env"), appEnv, "utf8");
|
|
409
|
-
}
|
|
410
|
-
await Promise.all(
|
|
411
|
-
TO_CLEAN.map((folderPath) => {
|
|
412
|
-
const absolutePath = path.resolve(targetFolder, folderPath);
|
|
413
|
-
return removeFolderContents(absolutePath);
|
|
414
|
-
})
|
|
415
|
-
);
|
|
416
|
-
await Promise.all(
|
|
417
|
-
TO_REMOVE.map((filePath) => {
|
|
418
|
-
const absolutePath = path.resolve(targetFolder, filePath);
|
|
419
|
-
return removeFileOrFolder(absolutePath);
|
|
420
|
-
})
|
|
421
|
-
);
|
|
422
|
-
resolve4();
|
|
423
|
-
} catch (err) {
|
|
424
|
-
reject(`Error during the cleaning process: ${err}`);
|
|
425
|
-
}
|
|
426
|
-
})();
|
|
427
|
-
});
|
|
428
|
-
}
|
|
429
|
-
async function writeReadme(targetFolder, displayName, appIndex) {
|
|
430
|
-
try {
|
|
431
|
-
const quickstart = await fs2.readFile(path.resolve(targetFolder, QUICKSTART), "utf8");
|
|
432
|
-
const readme = quickstartToReadme(quickstart, displayName, appIndex);
|
|
433
|
-
await fs2.writeFile(path.resolve(targetFolder, "README.md"), readme, "utf8");
|
|
434
|
-
} catch (err) {
|
|
435
|
-
if (err.code !== "ENOENT") throw err;
|
|
436
|
-
console.info(`
|
|
437
|
-
${warningMark} "${QUICKSTART}" not found > Skip README`);
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
async function writeAgentEntry(targetFolder) {
|
|
441
|
-
await Promise.all(
|
|
442
|
-
Object.entries(AGENT_FILES).map(
|
|
443
|
-
([file, content]) => fs2.writeFile(path.resolve(targetFolder, file), content, "utf8")
|
|
444
|
-
)
|
|
445
|
-
);
|
|
446
|
-
try {
|
|
447
|
-
await fs2.mkdir(path.resolve(targetFolder, ".claude"), { recursive: true });
|
|
448
|
-
await fs2.symlink("../cella/skills", path.resolve(targetFolder, ".claude/skills"));
|
|
449
|
-
} catch (err) {
|
|
450
|
-
console.info(`
|
|
451
|
-
${warningMark} skipped .claude/skills: ${err instanceof Error ? err.message : String(err)}`);
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
async function removeFolderContents(folderPath) {
|
|
455
|
-
let files;
|
|
456
|
-
try {
|
|
457
|
-
files = await fs2.readdir(folderPath);
|
|
458
|
-
} catch (err) {
|
|
459
|
-
if (err.code === "ENOENT") return;
|
|
460
|
-
throw err;
|
|
461
|
-
}
|
|
462
|
-
await Promise.all(files.map((file) => fs2.rm(path.join(folderPath, file), { recursive: true, force: true })));
|
|
463
|
-
}
|
|
464
|
-
async function removeFileOrFolder(pathToRemove) {
|
|
465
|
-
await fs2.rm(pathToRemove, { recursive: true, force: true });
|
|
466
|
-
}
|
|
467
|
-
async function copyFile(src, dest) {
|
|
468
|
-
try {
|
|
469
|
-
await fs2.access(src);
|
|
470
|
-
await fs2.mkdir(path.dirname(dest), { recursive: true });
|
|
471
|
-
await fs2.copyFile(src, dest);
|
|
472
|
-
} catch (err) {
|
|
473
|
-
if (err.code === "ENOENT") {
|
|
474
|
-
console.info(`
|
|
475
|
-
${warningMark} Source file "${src}" does not exist > Skip copy`);
|
|
476
|
-
} else {
|
|
477
|
-
throw err;
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
async function applyPlaceholderConfig(targetFolder, projectName, displayName, appIndex) {
|
|
482
|
-
const src = path.resolve(targetFolder, PLACEHOLDER_CONFIG);
|
|
483
|
-
const dest = path.resolve(targetFolder, "./shared/config/config.default.ts");
|
|
484
|
-
try {
|
|
485
|
-
let content = await fs2.readFile(src, "utf8");
|
|
486
|
-
content = content.replaceAll("__project_name__", displayName);
|
|
487
|
-
content = content.replaceAll("__project_slug__", projectName);
|
|
488
|
-
content = setDevAppIndex(content, appIndex);
|
|
489
|
-
await fs2.writeFile(dest, content, "utf8");
|
|
490
|
-
await fs2.rm(src, { force: true });
|
|
491
|
-
} catch (err) {
|
|
492
|
-
if (err.code === "ENOENT") {
|
|
493
|
-
console.info(`
|
|
494
|
-
${warningMark} Fork config template "${src}" not found > Skip`);
|
|
495
|
-
} else {
|
|
496
|
-
throw err;
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
function stripForks(source) {
|
|
501
|
-
return source.replace(
|
|
502
|
-
/^(?:[ \t]*\/\/[^\n]*\n)?([ \t]*)forks:\s*\[(?:[^\n]*|[\s\S]*?\n\1)\],?[ \t]*\n(?:[ \t]*\n)?/m,
|
|
503
|
-
""
|
|
504
|
-
);
|
|
505
|
-
}
|
|
506
|
-
async function removeTemplateForks(targetFolder) {
|
|
507
|
-
const configPath = path.resolve(targetFolder, SYNC_CONFIG);
|
|
508
|
-
try {
|
|
509
|
-
const source = await fs2.readFile(configPath, "utf8");
|
|
510
|
-
const stripped = stripForks(source);
|
|
511
|
-
if (stripped !== source) await fs2.writeFile(configPath, stripped, "utf8");
|
|
512
|
-
} catch (err) {
|
|
513
|
-
if (err.code === "ENOENT") {
|
|
514
|
-
console.info(`
|
|
515
|
-
${warningMark} "${SYNC_CONFIG}" not found > Skip forks removal`);
|
|
516
|
-
} else {
|
|
517
|
-
throw err;
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
async function resetReleaseState(targetFolder, projectName) {
|
|
522
|
-
const pkgPath = path.resolve(targetFolder, "package.json");
|
|
523
|
-
try {
|
|
524
|
-
let pkg = await fs2.readFile(pkgPath, "utf8");
|
|
525
|
-
pkg = pkg.replace(/^(\s*"name":\s*)"[^"]*"/m, `$1"${projectName}"`);
|
|
526
|
-
pkg = pkg.replace(/^(\s*"version":\s*)"[^"]*"/m, `$1"${INITIAL_VERSION}"`);
|
|
527
|
-
for (const field of ["license", "repository", "description", "author", "homepage"]) {
|
|
528
|
-
pkg = pkg.replace(new RegExp(`^(\\s*"${field}":\\s*)"[^"]*"`, "m"), '$1""');
|
|
529
|
-
}
|
|
530
|
-
pkg = pkg.replace(/^(\s*"keywords":\s*)\[[^\]]*\]/m, "$1[]");
|
|
531
|
-
await fs2.writeFile(pkgPath, pkg, "utf8");
|
|
532
|
-
} catch (err) {
|
|
533
|
-
if (err.code === "ENOENT") {
|
|
534
|
-
console.info(`
|
|
535
|
-
${warningMark} "package.json" not found > Skip version reset`);
|
|
536
|
-
} else {
|
|
537
|
-
throw err;
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
const configPath = path.resolve(targetFolder, ".github/release-please-config.json");
|
|
541
|
-
try {
|
|
542
|
-
const config = JSON.parse(await fs2.readFile(configPath, "utf8"));
|
|
543
|
-
config.packages ??= {};
|
|
544
|
-
config.packages["."] ??= {};
|
|
545
|
-
config.packages["."]["changelog-path"] = "CHANGELOG.md";
|
|
546
|
-
await fs2.writeFile(configPath, `${JSON.stringify(config, null, 2)}
|
|
547
|
-
`, "utf8");
|
|
548
|
-
} catch (err) {
|
|
549
|
-
if (err.code === "ENOENT") {
|
|
550
|
-
console.info(`
|
|
551
|
-
${warningMark} "release-please-config.json" not found > Skip changelog path reset`);
|
|
552
|
-
} else {
|
|
553
|
-
throw err;
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
await fs2.writeFile(
|
|
557
|
-
path.resolve(targetFolder, ".github/release-please-manifest.json"),
|
|
558
|
-
`{
|
|
559
|
-
".": "${INITIAL_VERSION}"
|
|
560
|
-
}
|
|
561
|
-
`,
|
|
562
|
-
"utf8"
|
|
563
|
-
);
|
|
564
|
-
await fs2.writeFile(path.resolve(targetFolder, "CHANGELOG.md"), "# Changelog\n", "utf8");
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
// src/utils/download-template.ts
|
|
568
|
-
import fs3 from "fs";
|
|
569
|
-
import { rm } from "fs/promises";
|
|
570
|
-
import { join as join2 } from "path";
|
|
571
|
-
import git2 from "isomorphic-git";
|
|
572
10
|
import http from "isomorphic-git/http/node";
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
|
|
604
|
-
if (ig.ignores(entry.isDirectory() ? `${rel}/` : rel)) continue;
|
|
605
|
-
if (entry.isDirectory()) await walk(rel);
|
|
606
|
-
else if (entry.isFile()) files.push(rel);
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
await walk("");
|
|
610
|
-
return files;
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
// src/utils/progress.ts
|
|
614
|
-
import ora from "ora";
|
|
615
|
-
import pc4 from "picocolors";
|
|
616
|
-
var activeSpinner = null;
|
|
617
|
-
function pauseSpinner() {
|
|
618
|
-
if (activeSpinner) {
|
|
619
|
-
activeSpinner.stop();
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
function resumeSpinner() {
|
|
623
|
-
if (activeSpinner) {
|
|
624
|
-
activeSpinner.start();
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
function createProgress(title, silent = false) {
|
|
628
|
-
const completedSteps = [];
|
|
629
|
-
const spinner = ora({
|
|
630
|
-
text: title,
|
|
631
|
-
isSilent: silent
|
|
632
|
-
});
|
|
633
|
-
activeSpinner = spinner;
|
|
634
|
-
spinner.start();
|
|
635
|
-
const log = (msg) => {
|
|
636
|
-
if (!silent) console.info(msg);
|
|
637
|
-
};
|
|
638
|
-
return {
|
|
639
|
-
step: (message) => {
|
|
640
|
-
if (completedSteps.length > 0) {
|
|
641
|
-
spinner.stop();
|
|
642
|
-
log(`${pc4.green("\u2713")} ${completedSteps[completedSteps.length - 1]}`);
|
|
643
|
-
}
|
|
644
|
-
completedSteps.push(message);
|
|
645
|
-
spinner.text = message;
|
|
646
|
-
spinner.start();
|
|
647
|
-
},
|
|
648
|
-
done: (message) => {
|
|
649
|
-
if (completedSteps.length > 0) {
|
|
650
|
-
spinner.stop();
|
|
651
|
-
log(`${pc4.green("\u2713")} ${completedSteps[completedSteps.length - 1]}`);
|
|
652
|
-
} else {
|
|
653
|
-
spinner.stop();
|
|
654
|
-
}
|
|
655
|
-
activeSpinner = null;
|
|
656
|
-
if (message) {
|
|
657
|
-
log("");
|
|
658
|
-
log(`${pc4.green("\u2713")} ${message}`);
|
|
659
|
-
}
|
|
660
|
-
},
|
|
661
|
-
fail: (message) => {
|
|
662
|
-
spinner.stop();
|
|
663
|
-
activeSpinner = null;
|
|
664
|
-
log(`${pc4.red("\u2717")} ${pc4.red(message)}`);
|
|
665
|
-
}
|
|
666
|
-
};
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
// src/create.ts
|
|
670
|
-
function isLocalPath(path2) {
|
|
671
|
-
return path2.startsWith("/") || path2.startsWith("./") || path2.startsWith("../");
|
|
672
|
-
}
|
|
673
|
-
async function create({
|
|
674
|
-
projectName,
|
|
675
|
-
targetFolder,
|
|
676
|
-
packageManager: packageManager2,
|
|
677
|
-
templateUrl,
|
|
678
|
-
templateRef,
|
|
679
|
-
appIndex,
|
|
680
|
-
adminEmail,
|
|
681
|
-
silent = false
|
|
682
|
-
}) {
|
|
683
|
-
const originalCwd = process.cwd();
|
|
684
|
-
const template = templateUrl || TEMPLATE_URL;
|
|
685
|
-
const isLocalTemplate = templateUrl && isLocalPath(templateUrl);
|
|
686
|
-
const progress = createProgress("creating project", silent);
|
|
687
|
-
try {
|
|
688
|
-
progress.step("creating project folder");
|
|
689
|
-
await mkdir(targetFolder, { recursive: true });
|
|
690
|
-
process.chdir(targetFolder);
|
|
691
|
-
let baseSha = null;
|
|
692
|
-
if (isLocalTemplate) {
|
|
693
|
-
progress.step("copying local template");
|
|
694
|
-
const sourcePath = resolve2(originalCwd, templateUrl);
|
|
695
|
-
const rel = relative(sourcePath, targetFolder);
|
|
696
|
-
const targetInsideTemplate = rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
697
|
-
if (targetInsideTemplate) {
|
|
698
|
-
throw new Error(
|
|
699
|
-
`Cannot create project inside the template directory.
|
|
700
|
-
Run from outside: cd ~ && pnpm create @cellajs/cella ${projectName} --template ${templateUrl}`
|
|
701
|
-
);
|
|
702
|
-
}
|
|
703
|
-
const tracked = await listTemplateFiles(sourcePath);
|
|
704
|
-
for (const rel2 of tracked) {
|
|
705
|
-
const src = join4(sourcePath, rel2);
|
|
706
|
-
if (!existsSync(src)) continue;
|
|
707
|
-
const dest = join4(targetFolder, rel2);
|
|
708
|
-
await mkdir(dirname2(dest), { recursive: true });
|
|
709
|
-
await cp(src, dest);
|
|
710
|
-
}
|
|
711
|
-
} else {
|
|
712
|
-
const ref = templateRef ?? "main";
|
|
713
|
-
progress.step(`downloading cella template${templateRef ? ` (${templateRef})` : ""}`);
|
|
714
|
-
baseSha = await downloadGithubTemplate(template, ref, targetFolder);
|
|
715
|
-
}
|
|
716
|
-
progress.step("cleaning template");
|
|
717
|
-
const displayName = projectName.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
718
|
-
await cleanTemplate({ targetFolder, projectName, displayName, appIndex, adminEmail });
|
|
719
|
-
const gitFolderPath = join4(targetFolder, ".git");
|
|
720
|
-
if (!existsSync(gitFolderPath)) {
|
|
721
|
-
try {
|
|
722
|
-
progress.step("initializing git");
|
|
723
|
-
await gitInit(targetFolder);
|
|
724
|
-
await gitAddAll(targetFolder);
|
|
725
|
-
const message = baseSha ? `Initial commit
|
|
726
|
-
|
|
727
|
-
Cella-Base: ${baseSha}` : "Initial commit";
|
|
728
|
-
await gitCommit(targetFolder, message);
|
|
729
|
-
} catch (error) {
|
|
730
|
-
if (!silent) {
|
|
731
|
-
pauseSpinner();
|
|
732
|
-
console.warn(`${pc5.yellow("\u26A0")} skipped git init: ${error instanceof Error ? error.message : String(error)}`);
|
|
733
|
-
resumeSpinner();
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
progress.step("adding upstream remote");
|
|
738
|
-
await addRemote({ targetFolder, silent: true });
|
|
739
|
-
progress.done(pc5.bold(`created ${projectName}`));
|
|
740
|
-
} catch (error) {
|
|
741
|
-
progress.fail(error instanceof Error ? error.message : String(error));
|
|
742
|
-
throw error;
|
|
743
|
-
}
|
|
744
|
-
const needsCd = originalCwd !== targetFolder;
|
|
745
|
-
const relativePath = relative(originalCwd, targetFolder);
|
|
746
|
-
showSuccess(
|
|
747
|
-
projectName,
|
|
748
|
-
targetFolder,
|
|
749
|
-
relativePath,
|
|
750
|
-
needsCd,
|
|
751
|
-
packageManager2,
|
|
752
|
-
appIndex,
|
|
753
|
-
adminEmail ?? `admin@${projectName}.example.com`
|
|
754
|
-
);
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
// src/utils/busy-ports.ts
|
|
758
|
-
import { connect } from "net";
|
|
759
|
-
var SERVICE_PORTS = 7;
|
|
760
|
-
var appPorts = (appIndex) => [
|
|
761
|
-
3e3 + appIndex,
|
|
762
|
-
...Array.from({ length: SERVICE_PORTS }, (_, i) => 4e3 + appIndex * 10 + i),
|
|
763
|
-
5432 + appIndex * 10,
|
|
764
|
-
5434 + appIndex * 10
|
|
765
|
-
];
|
|
766
|
-
var isListening = (port) => new Promise((resolve4) => {
|
|
767
|
-
const socket = connect({ port, host: "127.0.0.1", timeout: 300 });
|
|
768
|
-
const finish = (listening) => {
|
|
769
|
-
socket.destroy();
|
|
770
|
-
resolve4(listening);
|
|
771
|
-
};
|
|
772
|
-
socket.once("connect", () => finish(true));
|
|
773
|
-
socket.once("timeout", () => finish(false));
|
|
774
|
-
socket.once("error", () => finish(false));
|
|
11
|
+
// src/colors.ts
|
|
12
|
+
function colorsEnabled() {
|
|
13
|
+
const { NO_COLOR, FORCE_COLOR } = process.env;
|
|
14
|
+
if (NO_COLOR !== void 0) return false;
|
|
15
|
+
if (FORCE_COLOR !== void 0) return FORCE_COLOR !== "0" && FORCE_COLOR !== "false";
|
|
16
|
+
return !!process.stdout.isTTY;
|
|
17
|
+
}
|
|
18
|
+
function applyStyle(style, text) {
|
|
19
|
+
if (!colorsEnabled()) return text;
|
|
20
|
+
return styleText(style, text, { validateStream: false });
|
|
21
|
+
}
|
|
22
|
+
const pc = {
|
|
23
|
+
bold: (text) => applyStyle("bold", text),
|
|
24
|
+
cyan: (text) => applyStyle("cyan", text),
|
|
25
|
+
dim: (text) => applyStyle("dim", text),
|
|
26
|
+
gray: (text) => applyStyle("gray", text),
|
|
27
|
+
green: (text) => applyStyle("green", text),
|
|
28
|
+
red: (text) => applyStyle("red", text),
|
|
29
|
+
yellow: (text) => applyStyle("yellow", text)
|
|
30
|
+
};
|
|
31
|
+
// src/dev-ports.ts
|
|
32
|
+
/**
|
|
33
|
+
* The local ports the template's dev stack takes for an app index, as its config shifts them: the index is added to
|
|
34
|
+
* the frontend's and Drizzle Studio's, ten times the index to the seven services' and the dev and test databases'.
|
|
35
|
+
*/
|
|
36
|
+
const appPorts = (index) => ({
|
|
37
|
+
frontend: 3e3 + index,
|
|
38
|
+
drizzleStudio: 3983 + index,
|
|
39
|
+
services: Array.from({ length: 7 }, (_, i) => 4e3 + index * 10 + i),
|
|
40
|
+
databases: [5432 + index * 10, 5434 + index * 10]
|
|
775
41
|
});
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
42
|
+
/** Index 4 is never offered: its internal listener would sit on 4045, which fetch refuses. */
|
|
43
|
+
const isAppIndex = (index) => Number.isInteger(index) && index >= 0 && index <= 9 && index !== 4;
|
|
44
|
+
/** The rule `isAppIndex` checks, worded for a refusal. */
|
|
45
|
+
const appIndexRule = "a whole number from 0 to 9, not 4";
|
|
46
|
+
/**
|
|
47
|
+
* The dev ports of the cella apps beside `targetFolder`, found by their `shared/config/config.development.ts`. The
|
|
48
|
+
* frontend port sits in that file's `origin`, or `frontendUrl` in older apps; the backend port in
|
|
49
|
+
* `services.backend.port` of `config.default.ts`, or `devPorts` in either file before that, or `backendUrl` on a port
|
|
50
|
+
* of its own before that; `devAppIndex` in the default config moves whatever ports the files carry.
|
|
51
|
+
*/
|
|
52
|
+
async function detectUsedPorts(targetFolder) {
|
|
53
|
+
const parentDir = dirname(targetFolder);
|
|
54
|
+
const siblings = await readdir(parentDir).catch(() => []);
|
|
55
|
+
const used = [];
|
|
56
|
+
for (const name of siblings) {
|
|
57
|
+
const configDir = join(parentDir, name, "shared/config");
|
|
58
|
+
const development = await readFile(join(configDir, "config.development.ts"), "utf8").catch(() => null);
|
|
59
|
+
const frontendMatch = development?.match(/(?:origin|frontendUrl):\s*'http:\/\/localhost:(\d+)/);
|
|
60
|
+
if (!development || !frontendMatch) continue;
|
|
61
|
+
const defaults = await readFile(join(configDir, "config.default.ts"), "utf8").catch(() => "");
|
|
62
|
+
const frontend = Number(frontendMatch[1]);
|
|
63
|
+
const index = Number(defaults.match(/devAppIndex:\s*(\d+)/)?.[1] ?? 0);
|
|
64
|
+
const servicePattern = /backend:\s*\{[^}]*?\bport:\s*(\d+)/;
|
|
65
|
+
const apiPattern = /devPorts:\s*\{[^}]*?\bapi:\s*(\d+)/;
|
|
66
|
+
const portMatch = defaults.match(servicePattern) ?? development.match(apiPattern) ?? defaults.match(apiPattern) ?? development.match(/backendUrl:\s*'http:\/\/localhost:(\d+)'/);
|
|
67
|
+
const backend = portMatch ? Number(portMatch[1]) : frontend + 1e3;
|
|
68
|
+
used.push({
|
|
69
|
+
project: name,
|
|
70
|
+
frontend: frontend + index,
|
|
71
|
+
backend: backend + index * 10
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return used;
|
|
75
|
+
}
|
|
76
|
+
/** The first app index whose frontend port and service block no sibling uses and that `isBusy` leaves free, else 0. */
|
|
77
|
+
function findNextAppIndex(siblings, isBusy = () => false) {
|
|
78
|
+
for (let index = 0; index <= 9; index += 1) {
|
|
79
|
+
if (!isAppIndex(index) || isBusy(index)) continue;
|
|
80
|
+
const { frontend, services } = appPorts(index);
|
|
81
|
+
const api = services[0];
|
|
82
|
+
if (!siblings.some((p) => p.frontend === frontend || p.backend >= api && p.backend < api + 10)) return index;
|
|
83
|
+
}
|
|
84
|
+
return 0;
|
|
85
|
+
}
|
|
86
|
+
/** Whether something on this machine accepts a connection on the port. */
|
|
87
|
+
const isListening = (port) => new Promise((resolve) => {
|
|
88
|
+
const socket = connect({
|
|
89
|
+
port,
|
|
90
|
+
host: "127.0.0.1",
|
|
91
|
+
timeout: 300
|
|
92
|
+
});
|
|
93
|
+
const finish = (listening) => {
|
|
94
|
+
socket.destroy();
|
|
95
|
+
resolve(listening);
|
|
96
|
+
};
|
|
97
|
+
socket.once("connect", () => finish(true));
|
|
98
|
+
socket.once("timeout", () => finish(false));
|
|
99
|
+
socket.once("error", () => finish(false));
|
|
100
|
+
});
|
|
101
|
+
/** The ports of an app index that are already taken, lowest first. */
|
|
102
|
+
async function findBusyPorts(index) {
|
|
103
|
+
const ports = Object.values(appPorts(index)).flat();
|
|
104
|
+
const listening = await Promise.all(ports.map(isListening));
|
|
105
|
+
return ports.filter((_, i) => listening[i]);
|
|
780
106
|
}
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
107
|
+
// package.json
|
|
108
|
+
var version = "0.6.0";
|
|
109
|
+
var description = "Cella is a TypeScript template to create web apps with sync and offline capabilities.";
|
|
110
|
+
var homepage = "https://cellajs.com";
|
|
111
|
+
// src/display.ts
|
|
112
|
+
const cliName = "create cella";
|
|
113
|
+
const cliVersion = version;
|
|
114
|
+
const divider = "─".repeat(60);
|
|
115
|
+
const checkMark = pc.green("✓");
|
|
116
|
+
function showBanner() {
|
|
117
|
+
console.info();
|
|
118
|
+
console.info(pc.cyan(" _ _ "));
|
|
119
|
+
console.info(pc.cyan("▒▓█████▓▒ ___ ___| | | __ _ "));
|
|
120
|
+
console.info(pc.cyan("▒▓█ █▓▒ / __/ _ \\ | |/ _` | "));
|
|
121
|
+
console.info(pc.cyan("▒▓█ █▓▒ | (_| __/ | | (_| | "));
|
|
122
|
+
console.info(pc.cyan("▒▓█████▓▒ \\___\\___|_|_|\\__,_| "));
|
|
123
|
+
console.info();
|
|
124
|
+
console.info(pc.dim(description));
|
|
125
|
+
console.info();
|
|
126
|
+
const left = `⧈ ${cliName}`;
|
|
127
|
+
const right = homepage;
|
|
128
|
+
const padding = Math.max(1, divider.length - `${left} · ${cliVersion}${right}`.length);
|
|
129
|
+
console.info(`${pc.cyan(left)} ${pc.dim(`· ${cliVersion}`)}${" ".repeat(padding)}${pc.cyan(right)}`);
|
|
130
|
+
console.info(divider);
|
|
131
|
+
}
|
|
132
|
+
/** Keep the answer of a prompt that clears itself on screen. */
|
|
133
|
+
function confirmChoice(label, value) {
|
|
134
|
+
console.info(`${checkMark} ${label} · ${value}`);
|
|
135
|
+
console.info();
|
|
136
|
+
}
|
|
137
|
+
let stepText;
|
|
138
|
+
let timer;
|
|
139
|
+
/** Animate the running step on a terminal only: a log gets the finished steps. Stdin stays untouched, so ctrl-c reaches the run. */
|
|
140
|
+
function spin() {
|
|
141
|
+
if (!stepText || !process.stdout.isTTY) return;
|
|
142
|
+
const frames = [
|
|
143
|
+
"-",
|
|
144
|
+
"\\",
|
|
145
|
+
"|",
|
|
146
|
+
"/"
|
|
147
|
+
];
|
|
148
|
+
let frame = 0;
|
|
149
|
+
const render = () => process.stdout.write(`\r${pc.cyan(frames[frame++ % frames.length])} ${stepText}`);
|
|
150
|
+
render();
|
|
151
|
+
timer = setInterval(render, 80);
|
|
152
|
+
}
|
|
153
|
+
function clearSpinner() {
|
|
154
|
+
if (!timer) return;
|
|
155
|
+
clearInterval(timer);
|
|
156
|
+
timer = void 0;
|
|
157
|
+
process.stdout.write("\r\x1B[2K");
|
|
158
|
+
}
|
|
159
|
+
/** Mark the running step done and start `text`; without text the steps end. */
|
|
160
|
+
function step(text) {
|
|
161
|
+
clearSpinner();
|
|
162
|
+
if (stepText) console.info(`${checkMark} ${stepText}`);
|
|
163
|
+
stepText = text;
|
|
164
|
+
spin();
|
|
165
|
+
}
|
|
166
|
+
/** End the steps without marking the running one done. */
|
|
167
|
+
function stopSpinner() {
|
|
168
|
+
clearSpinner();
|
|
169
|
+
stepText = void 0;
|
|
170
|
+
}
|
|
171
|
+
/** Print a warning above the running step. */
|
|
172
|
+
function warn(message) {
|
|
173
|
+
clearSpinner();
|
|
174
|
+
console.warn(`${pc.yellow("⚠")} ${message}`);
|
|
175
|
+
spin();
|
|
176
|
+
}
|
|
177
|
+
function showNextSteps({ name, targetFolder, appIndex, adminEmail }) {
|
|
178
|
+
const path = relative(process.cwd(), targetFolder);
|
|
179
|
+
const and = pc.dim("&&");
|
|
180
|
+
console.info();
|
|
181
|
+
console.info(`${checkMark} ${pc.bold(`created ${name}`)}`);
|
|
182
|
+
console.info();
|
|
183
|
+
console.info(pc.bold("Next steps"));
|
|
184
|
+
console.info(divider);
|
|
185
|
+
console.info();
|
|
186
|
+
if (path) console.info(`${pc.dim("$")} cd ${pc.cyan(path)}`);
|
|
187
|
+
console.info(`${pc.dim("$")} ${pc.cyan("pnpm install")}`);
|
|
188
|
+
console.info(`${pc.dim("$")} ${pc.cyan("pnpm generate")}`);
|
|
189
|
+
console.info(`${pc.dim("$")} ${pc.cyan("pnpm docker")} ${and} ${pc.cyan("pnpm seed")} ${and} ${pc.cyan("pnpm dev")}`);
|
|
190
|
+
console.info();
|
|
191
|
+
console.info(`${pc.gray("Then open")} ${pc.cyan(`http://localhost:${appPorts(appIndex).frontend}`)} ${pc.gray("and sign in as")} ${pc.cyan(adminEmail)}${pc.gray(": the magic link is printed in the pnpm dev output.")}`);
|
|
192
|
+
console.info();
|
|
193
|
+
console.info(`${pc.gray("To get started building, please read:")} ${pc.cyan(path ? `${path}/README.md` : "README.md")}`);
|
|
194
|
+
console.info();
|
|
195
|
+
console.info(`🥳 enjoy building ${pc.green(name)} with cella!`);
|
|
196
|
+
console.info();
|
|
197
|
+
}
|
|
198
|
+
// src/template.ts
|
|
199
|
+
const templateRepository = "cellajs/cella";
|
|
200
|
+
/** The HTTPS git URL of `github:owner/repo` or `owner/repo`: reading a public repository needs no SSH key. */
|
|
201
|
+
function githubGitUrl(template) {
|
|
202
|
+
const [owner, repo] = template.replace(/^github:/, "").split("/");
|
|
203
|
+
if (!owner || !repo) throw new Error(`Invalid template '${template}'. Expected 'github:owner/repo'.`);
|
|
204
|
+
return `https://github.com/${owner}/${repo}.git`;
|
|
205
|
+
}
|
|
206
|
+
/** A version, with or without the `v` prefix; `create-cella-0.2.3` and `archive/pre-release` start with a name. */
|
|
207
|
+
const releaseTagPattern = /^v?\d[\w.+-]*$/;
|
|
208
|
+
/** The highest release tag, in git's `version:refname` order as `pnpm cella upgrade` sorts them, or null. */
|
|
790
209
|
function pickLatestReleaseTag(tags) {
|
|
791
|
-
|
|
792
|
-
for (const tag of tags) {
|
|
793
|
-
const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(tag);
|
|
794
|
-
if (!match) continue;
|
|
795
|
-
const version = match.slice(1).map(Number);
|
|
796
|
-
if (!latest || isNewer(version, latest.version)) latest = { tag, version };
|
|
797
|
-
}
|
|
798
|
-
return latest?.tag ?? null;
|
|
799
|
-
}
|
|
800
|
-
function isNewer(a, b) {
|
|
801
|
-
for (let i = 0; i < a.length; i++) {
|
|
802
|
-
if (a[i] !== b[i]) return a[i] > b[i];
|
|
803
|
-
}
|
|
804
|
-
return false;
|
|
210
|
+
return tags.filter((tag) => releaseTagPattern.test(tag)).sort((a, b) => a.localeCompare(b, "en", { numeric: true })).at(-1) ?? null;
|
|
805
211
|
}
|
|
212
|
+
/**
|
|
213
|
+
* The latest template release: its tag from the git tags, over the transport the clone uses, so the GitHub API limit
|
|
214
|
+
* for callers without a token cannot hide it; its date (YYYY-MM-DD) from that API when it answers. Null offline.
|
|
215
|
+
*/
|
|
806
216
|
async function fetchLatestRelease() {
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
217
|
+
const tag = pickLatestReleaseTag((await git.listServerRefs({
|
|
218
|
+
http,
|
|
219
|
+
url: githubGitUrl(templateRepository),
|
|
220
|
+
prefix: "refs/tags/"
|
|
221
|
+
}).catch(() => [])).map(({ ref }) => ref.slice(10)));
|
|
222
|
+
if (!tag) return null;
|
|
223
|
+
return {
|
|
224
|
+
tag,
|
|
225
|
+
date: (await fetchGithub(`releases/tags/${tag}`))?.published_at?.slice(0, 10)
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
/** The latest commit on the template's main branch, with its subject and date (YYYY-MM-DD), or null. */
|
|
229
|
+
async function fetchLatestCommit() {
|
|
230
|
+
const data = await fetchGithub("commits/main");
|
|
231
|
+
if (!data?.sha) return null;
|
|
232
|
+
const message = (data.commit?.message ?? "").split("\n")[0];
|
|
233
|
+
return {
|
|
234
|
+
sha: data.sha,
|
|
235
|
+
message,
|
|
236
|
+
date: data.commit?.author?.date?.slice(0, 10) ?? "unknown"
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/** A GitHub API answer about the template, or null: callers without a token have a low limit. */
|
|
240
|
+
async function fetchGithub(path) {
|
|
241
|
+
try {
|
|
242
|
+
const url = `https://api.github.com/repos/${templateRepository}/${path}`;
|
|
243
|
+
const response = await fetch(url, { headers: { Accept: "application/vnd.github+json" } });
|
|
244
|
+
return response.ok ? await response.json() : null;
|
|
245
|
+
} catch {
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const isLocalPath = (path) => path.startsWith("/") || path.startsWith("./") || path.startsWith("../");
|
|
250
|
+
/**
|
|
251
|
+
* Put the template's files in `targetFolder`: a shallow clone of a GitHub template, or the tracked files of a local
|
|
252
|
+
* checkout from its working tree, so build output and local `.env` secrets stay behind.
|
|
253
|
+
* @returns The template commit the files come from; null when isomorphic-git cannot resolve a local checkout's `HEAD`,
|
|
254
|
+
* as in a linked worktree.
|
|
255
|
+
*/
|
|
256
|
+
async function getTemplate({ template, templateRef, targetFolder, name }) {
|
|
257
|
+
if (!template || !isLocalPath(template)) {
|
|
258
|
+
step(`downloading cella template${templateRef ? ` (${templateRef})` : ""}`);
|
|
259
|
+
const url = githubGitUrl(template ?? "cellajs/cella");
|
|
260
|
+
await git.clone({
|
|
261
|
+
fs: fs$1,
|
|
262
|
+
http,
|
|
263
|
+
dir: targetFolder,
|
|
264
|
+
url,
|
|
265
|
+
ref: templateRef ?? "main",
|
|
266
|
+
singleBranch: true,
|
|
267
|
+
depth: 1
|
|
268
|
+
});
|
|
269
|
+
const baseCommit = await git.resolveRef({
|
|
270
|
+
fs: fs$1,
|
|
271
|
+
dir: targetFolder,
|
|
272
|
+
ref: "HEAD"
|
|
273
|
+
});
|
|
274
|
+
await rm(join(targetFolder, ".git"), {
|
|
275
|
+
recursive: true,
|
|
276
|
+
force: true
|
|
277
|
+
});
|
|
278
|
+
return baseCommit;
|
|
279
|
+
}
|
|
280
|
+
step("copying local template");
|
|
281
|
+
const source = resolve(template);
|
|
282
|
+
const rel = relative(source, targetFolder);
|
|
283
|
+
if (rel === "" || !rel.startsWith("..") && !isAbsolute(rel)) throw new Error(`Cannot create the app inside the template directory.
|
|
284
|
+
Run from outside: cd ~ && pnpm create @cellajs/cella ${name} --template ${template}`);
|
|
285
|
+
const files = await git.listFiles({
|
|
286
|
+
fs: fs$1,
|
|
287
|
+
dir: source
|
|
288
|
+
});
|
|
289
|
+
if (files.length === 0) throw new Error(`${source} is no git checkout: a local template must be one.`);
|
|
290
|
+
for (const file of files) {
|
|
291
|
+
const from = join(source, file);
|
|
292
|
+
if (!existsSync(from)) continue;
|
|
293
|
+
const to = join(targetFolder, file);
|
|
294
|
+
await mkdir(dirname(to), { recursive: true });
|
|
295
|
+
await cp(from, to);
|
|
296
|
+
}
|
|
297
|
+
return git.resolveRef({
|
|
298
|
+
fs: fs$1,
|
|
299
|
+
dir: source,
|
|
300
|
+
ref: "HEAD"
|
|
301
|
+
}).catch(() => null);
|
|
302
|
+
}
|
|
303
|
+
// src/answers.ts
|
|
304
|
+
/** The template's config refuses any other `slug` at its first load (cella `shared/src/config-builder/app-config.ts`). */
|
|
305
|
+
const isAppSlug = (name) => /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name) && name.replaceAll("-", "").length >= 4;
|
|
306
|
+
/** The rule `isAppSlug` checks, worded for a refusal. */
|
|
307
|
+
const appSlugRule = "the name becomes the app slug: lowercase letters and digits, starting with a letter, single hyphens between parts and at least 4 characters besides hyphens, such as my-app";
|
|
308
|
+
/** A plain shape check: the value lands on one line of the app's `.env` and is the seed user's sign-in address. */
|
|
309
|
+
const isEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
|
310
|
+
const theme = {
|
|
311
|
+
prefix: "",
|
|
312
|
+
style: { answer: (text) => text }
|
|
313
|
+
};
|
|
314
|
+
const context = { clearPromptOnDone: true };
|
|
315
|
+
/** Ask what the flags leave open, and refuse a folder that is not empty. */
|
|
316
|
+
async function askAnswers({ directory, template, ...flags }) {
|
|
317
|
+
const templateRef = template ? void 0 : await askTemplateRef();
|
|
318
|
+
const targetFolder = resolve(directory ?? await input({
|
|
319
|
+
message: "Enter your app name",
|
|
320
|
+
default: "my-cella-app",
|
|
321
|
+
theme,
|
|
322
|
+
validate: (name) => isAppSlug(basename(resolve(name))) ? true : `Invalid app name: the name becomes the app slug: lowercase letters and digits, starting with a letter, single hyphens between parts and at least 4 characters besides hyphens, such as my-app`
|
|
323
|
+
}, context));
|
|
324
|
+
if (existsSync(targetFolder) && (await readdir(targetFolder)).length > 0) throw new Error(`${targetFolder} is not empty: choose a new folder, or empty this one first.`);
|
|
325
|
+
const appIndex = flags.appIndex ?? await askAppIndex(targetFolder);
|
|
326
|
+
confirmChoice("App index", formatAppIndex(appIndex));
|
|
327
|
+
const busyPorts = await findBusyPorts(appIndex);
|
|
328
|
+
if (busyPorts.length > 0) {
|
|
329
|
+
warn(`In use on this machine: ${busyPorts.join(", ")}. Stop what holds them before pnpm docker and pnpm dev.`);
|
|
330
|
+
console.info();
|
|
331
|
+
}
|
|
332
|
+
const adminEmail = flags.adminEmail ?? await input({
|
|
333
|
+
message: "Admin email for initial seed user",
|
|
334
|
+
default: "admin@example.com",
|
|
335
|
+
theme,
|
|
336
|
+
validate: (email) => isEmail(email) ? true : "Enter an address such as admin@example.com"
|
|
337
|
+
}, context);
|
|
338
|
+
confirmChoice("Admin email", adminEmail);
|
|
339
|
+
return {
|
|
340
|
+
template,
|
|
341
|
+
templateRef,
|
|
342
|
+
targetFolder,
|
|
343
|
+
name: basename(targetFolder),
|
|
344
|
+
appIndex,
|
|
345
|
+
adminEmail
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Offer the latest release and the latest commit, each with its date, as the template to start from.
|
|
350
|
+
* @returns The release tag, or `main` for the latest commit; undefined when neither is known (offline).
|
|
351
|
+
*/
|
|
352
|
+
async function askTemplateRef() {
|
|
353
|
+
const [release, commit] = await Promise.all([fetchLatestRelease(), fetchLatestCommit()]);
|
|
354
|
+
console.info(pc.dim("This create CLI allows you to get started with cella quickly."));
|
|
355
|
+
console.info();
|
|
356
|
+
if (release) console.info(` Latest release: ${release.tag}${release.date ? ` ${pc.dim(`· ${release.date}`)}` : ""}`);
|
|
357
|
+
if (commit) {
|
|
358
|
+
console.info(` Latest commit: ${commit.sha.slice(0, 7)} ${pc.dim(`· ${commit.message} · ${commit.date}`)}`);
|
|
359
|
+
console.info(` ${pc.gray(`https://github.com/${templateRepository}/commit/${commit.sha}`)}`);
|
|
360
|
+
}
|
|
361
|
+
if (release || commit) console.info();
|
|
362
|
+
if (!release) {
|
|
363
|
+
warn("Latest release not found · using the latest commit on main");
|
|
364
|
+
console.info();
|
|
365
|
+
return commit ? "main" : void 0;
|
|
366
|
+
}
|
|
367
|
+
if (!commit || !process.stdin.isTTY || await select({
|
|
368
|
+
message: "Choose which cella version to start from:",
|
|
369
|
+
theme,
|
|
370
|
+
choices: [{
|
|
371
|
+
name: "Latest release",
|
|
372
|
+
value: "release"
|
|
373
|
+
}, {
|
|
374
|
+
name: "Latest commit",
|
|
375
|
+
value: "commit"
|
|
376
|
+
}]
|
|
377
|
+
}, context) === "release") {
|
|
378
|
+
confirmChoice("Latest release", release.tag);
|
|
379
|
+
return release.tag;
|
|
380
|
+
}
|
|
381
|
+
confirmChoice("Latest commit", commit.sha.slice(0, 7));
|
|
382
|
+
return "main";
|
|
383
|
+
}
|
|
384
|
+
/** An app index with its frontend, backend and database ports, such as "1 → :3001 / :4010 / :5442". */
|
|
385
|
+
function formatAppIndex(index, note = "") {
|
|
386
|
+
const { frontend, services, databases } = appPorts(index);
|
|
387
|
+
return `${index} → :${frontend} / :${services[0]} / :${databases[0]}${note}`;
|
|
388
|
+
}
|
|
389
|
+
/** Suggest an app index no sibling app and no listener on this machine takes, and ask for one. */
|
|
390
|
+
async function askAppIndex(targetFolder) {
|
|
391
|
+
const siblings = await detectUsedPorts(targetFolder);
|
|
392
|
+
const presets = [
|
|
393
|
+
1,
|
|
394
|
+
2,
|
|
395
|
+
3
|
|
396
|
+
];
|
|
397
|
+
const busy = new Map(await Promise.all([0, ...presets].map(async (i) => [i, await findBusyPorts(i)])));
|
|
398
|
+
const isBusy = (i) => (busy.get(i)?.length ?? 0) > 0;
|
|
399
|
+
const suggested = findNextAppIndex(siblings, isBusy);
|
|
400
|
+
const label = (i, note = "") => formatAppIndex(i, isBusy(i) ? ` (port ${busy.get(i)?.[0]} in use)` : note);
|
|
401
|
+
let message = `${pc.bold("App index")} ${pc.dim("· to avoid port conflicts with other apps on this machine")}`;
|
|
402
|
+
if (siblings.length > 0) {
|
|
403
|
+
const count = siblings.length;
|
|
404
|
+
message += pc.dim(`\nDetected ${count} sibling app${count === 1 ? "" : "s"} · suggested index ${suggested}`);
|
|
405
|
+
}
|
|
406
|
+
const choice = await select({
|
|
407
|
+
message,
|
|
408
|
+
theme: {
|
|
409
|
+
...theme,
|
|
410
|
+
style: {
|
|
411
|
+
...theme.style,
|
|
412
|
+
message: (text) => text
|
|
413
|
+
}
|
|
414
|
+
},
|
|
415
|
+
choices: [
|
|
416
|
+
...suggested > 0 ? [{
|
|
417
|
+
name: formatAppIndex(suggested, " (suggested)"),
|
|
418
|
+
value: suggested
|
|
419
|
+
}] : [],
|
|
420
|
+
{
|
|
421
|
+
name: label(0, " (default)"),
|
|
422
|
+
value: 0
|
|
423
|
+
},
|
|
424
|
+
...presets.filter((i) => i !== suggested).map((i) => ({
|
|
425
|
+
name: label(i),
|
|
426
|
+
value: i
|
|
427
|
+
})),
|
|
428
|
+
{
|
|
429
|
+
name: "Custom index",
|
|
430
|
+
value: -1
|
|
431
|
+
}
|
|
432
|
+
]
|
|
433
|
+
}, context);
|
|
434
|
+
if (choice !== -1) return choice;
|
|
435
|
+
const custom = await input({
|
|
436
|
+
message: `Enter custom index, ${appIndexRule}`,
|
|
437
|
+
default: String(suggested),
|
|
438
|
+
theme,
|
|
439
|
+
validate: (value) => isAppIndex(Number(value)) ? true : `Must be ${appIndexRule}`
|
|
440
|
+
}, context);
|
|
441
|
+
return Number(custom);
|
|
442
|
+
}
|
|
443
|
+
// src/app-files.ts
|
|
444
|
+
/** The version an app starts from, so release-please cuts its first release from a clean slate. */
|
|
445
|
+
const initialVersion = "0.0.0";
|
|
446
|
+
/** Entry points a coding agent reads from the repo root; the rules and skills live in the template's `cella/` folder. */
|
|
447
|
+
const agentFiles = {
|
|
448
|
+
"AGENTS.md": "# Agent guidelines\n\nThis app is built from the cella template. Read [cella/AGENTS.md](./cella/AGENTS.md) before changing code: it holds the project rules. Skills, such as `add-entity`, live in [cella/skills](./cella/skills).\n",
|
|
449
|
+
"CLAUDE.md": "@cella/AGENTS.md\n"
|
|
450
|
+
};
|
|
451
|
+
const manifestPath = "cella/create-cella.json";
|
|
452
|
+
const editNames = [
|
|
453
|
+
"quickstart",
|
|
454
|
+
"configTemplate",
|
|
455
|
+
"config",
|
|
456
|
+
"cliConfig",
|
|
457
|
+
"envExample",
|
|
458
|
+
"releaseConfig",
|
|
459
|
+
"releaseManifest"
|
|
460
|
+
];
|
|
461
|
+
/** @throws When the template has no manifest, or its manifest names no path for an edit this version makes. */
|
|
462
|
+
async function readManifest(targetFolder) {
|
|
463
|
+
const source = await fs.readFile(join(targetFolder, manifestPath), "utf8").catch(() => null);
|
|
464
|
+
if (source === null) throw new Error(`This template has no ${manifestPath}: use a newer template.`);
|
|
465
|
+
const manifest = JSON.parse(source);
|
|
466
|
+
const unnamed = editNames.filter((name) => typeof manifest.edit?.[name] !== "string");
|
|
467
|
+
if (unnamed.length > 0) throw new Error(`${manifestPath} names no path for ${unnamed.join(", ")}: use a newer template.`);
|
|
468
|
+
return manifest;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Turn the template's files in `targetFolder` into the app's: its name, index and admin email in the config and the
|
|
472
|
+
* `.env`, its own release state, the quickstart as README, and none of the template's own repos, migrations or stack.
|
|
473
|
+
* @returns The template paths it expected and did not find; a template without one skips that edit.
|
|
474
|
+
*/
|
|
475
|
+
async function writeAppFiles({ targetFolder, name, appIndex, adminEmail }) {
|
|
476
|
+
const missing = [];
|
|
477
|
+
const at = (path) => join(targetFolder, path);
|
|
478
|
+
const edit = async (path, change) => {
|
|
479
|
+
try {
|
|
480
|
+
await change(at(path));
|
|
481
|
+
} catch (error) {
|
|
482
|
+
if (error.code !== "ENOENT") throw error;
|
|
483
|
+
missing.push(path);
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
const rewrite = (path, change) => edit(path, async (file) => fs.writeFile(file, change(await fs.readFile(file, "utf8")), "utf8"));
|
|
487
|
+
const displayName = name.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
488
|
+
const { remove, empty, copy, link, edit: paths } = await readManifest(targetFolder);
|
|
489
|
+
try {
|
|
490
|
+
for (const [from, to] of Object.entries(copy)) await edit(from, (file) => fs.copyFile(file, at(to)));
|
|
491
|
+
await edit(paths.quickstart, async (file) => fs.writeFile(at("README.md"), quickstartToReadme(await fs.readFile(file, "utf8"), displayName, appIndex), "utf8"));
|
|
492
|
+
await writeAgentEntry(targetFolder, link);
|
|
493
|
+
await edit(paths.configTemplate, async (file) => {
|
|
494
|
+
const config = (await fs.readFile(file, "utf8")).replaceAll("__project_name__", displayName).replaceAll("__project_slug__", name).replace(/^(\s*devAppIndex:\s*)\d+/m, (_, head) => `${head}${appIndex}`);
|
|
495
|
+
await fs.writeFile(at(paths.config), config, "utf8");
|
|
496
|
+
await fs.rm(file);
|
|
497
|
+
});
|
|
498
|
+
await rewrite("package.json", (source) => {
|
|
499
|
+
let pkg = source.replace(/^(\s*"name":\s*)"[^"]*"/m, `$1"${name}"`).replace(/^(\s*"version":\s*)"[^"]*"/m, `$1"${initialVersion}"`).replace(/^(\s*"keywords":\s*)\[[^\]]*\]/m, "$1[]");
|
|
500
|
+
for (const field of [
|
|
501
|
+
"license",
|
|
502
|
+
"repository",
|
|
503
|
+
"description",
|
|
504
|
+
"author",
|
|
505
|
+
"homepage"
|
|
506
|
+
]) pkg = pkg.replace(new RegExp(`^(\\s*"${field}":\\s*)"[^"]*"`, "m"), "$1\"\"");
|
|
507
|
+
return pkg;
|
|
508
|
+
});
|
|
509
|
+
await rewrite(paths.releaseConfig, (source) => {
|
|
510
|
+
const config = JSON.parse(source);
|
|
511
|
+
config.packages ??= {};
|
|
512
|
+
config.packages["."] ??= {};
|
|
513
|
+
config.packages["."]["changelog-path"] = "CHANGELOG.md";
|
|
514
|
+
return `${JSON.stringify(config, null, 2)}\n`;
|
|
515
|
+
});
|
|
516
|
+
await edit(paths.releaseManifest, (file) => fs.writeFile(file, `{\n ".": "${initialVersion}"\n}\n`, "utf8"));
|
|
517
|
+
await fs.writeFile(at("CHANGELOG.md"), "# Changelog\n", "utf8");
|
|
518
|
+
await rewrite(paths.cliConfig, stripForks);
|
|
519
|
+
await edit(paths.envExample, async (file) => {
|
|
520
|
+
const env = (await fs.readFile(file, "utf8")).replace(/^ADMIN_EMAIL=.*$/gm, () => `ADMIN_EMAIL=${adminEmail}`);
|
|
521
|
+
await fs.writeFile(file.replace(/\.example$/, ""), env, "utf8");
|
|
522
|
+
});
|
|
523
|
+
for (const folder of empty) await edit(folder, async (dir) => {
|
|
524
|
+
const entries = await fs.readdir(dir);
|
|
525
|
+
await Promise.all(entries.map((entry) => fs.rm(join(dir, entry), {
|
|
526
|
+
recursive: true,
|
|
527
|
+
force: true
|
|
528
|
+
})));
|
|
529
|
+
});
|
|
530
|
+
for (const path of remove) await edit(path, (file) => fs.rm(file, { recursive: true }));
|
|
531
|
+
} catch (error) {
|
|
532
|
+
throw new Error(`Error during the cleaning process: ${error instanceof Error ? error.message : error}`);
|
|
533
|
+
}
|
|
534
|
+
return missing;
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* The quickstart as the README of a new app: at the repo root, with this app's port and without the step that just ran.
|
|
538
|
+
* Its links are relative to `cella/` in the template, so `./x` becomes `./cella/x` and `../x` becomes `./x`.
|
|
539
|
+
*/
|
|
540
|
+
function quickstartToReadme(source, displayName, appIndex) {
|
|
541
|
+
return source.replace(/^# .*$/m, `# ${displayName}`).replace(/^## Create\n[\s\S]*?(?=^## )/m, "").replaceAll("](./", "](./cella/").replaceAll("](../", "](./").replaceAll("http://localhost:3000", `http://localhost:${appPorts(appIndex).frontend}`);
|
|
542
|
+
}
|
|
543
|
+
/** Point coding agents at the template's rules and skills, which sit in `cella/`, out of a root they would not search. */
|
|
544
|
+
async function writeAgentEntry(targetFolder, link) {
|
|
545
|
+
await Promise.all(Object.entries(agentFiles).map(([file, content]) => fs.writeFile(join(targetFolder, file), content, "utf8")));
|
|
546
|
+
for (const [target, path] of Object.entries(link)) {
|
|
547
|
+
const file = join(targetFolder, path);
|
|
548
|
+
try {
|
|
549
|
+
await fs.mkdir(dirname(file), { recursive: true });
|
|
550
|
+
await fs.symlink(relative(dirname(file), join(targetFolder, target)), file);
|
|
551
|
+
} catch (error) {
|
|
552
|
+
warn(`skipped ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
/** The source of an upgrade config (`cella/cella.config.ts`) without its `forks` property and a comment line directly above it. */
|
|
557
|
+
function stripForks(source) {
|
|
558
|
+
return source.replace(/^(?:[ \t]*\/\/[^\n]*\n)?([ \t]*)forks:\s*\[(?:[^\n]*|[\s\S]*?\n\1)\],?[ \t]*\n(?:[ \t]*\n)?/m, "");
|
|
559
|
+
}
|
|
560
|
+
// src/app-repo.ts
|
|
561
|
+
/**
|
|
562
|
+
* Make the app's repository: one commit of its files, and the template as remote `cella-upstream`, the name
|
|
563
|
+
* `pnpm cella upgrade` looks for. The commit's `Cella-Base:` trailer names the template commit the files come from,
|
|
564
|
+
* which the upgrade reads from the root commit to find its first merge base: the app shares no history with the template.
|
|
565
|
+
* A failure only warns: the app's files stay usable without git.
|
|
566
|
+
*/
|
|
567
|
+
async function makeRepository(dir, baseCommit) {
|
|
568
|
+
try {
|
|
569
|
+
await git.init({
|
|
570
|
+
fs: fs$1,
|
|
571
|
+
dir,
|
|
572
|
+
defaultBranch: "main"
|
|
573
|
+
});
|
|
574
|
+
await git.add({
|
|
575
|
+
fs: fs$1,
|
|
576
|
+
dir,
|
|
577
|
+
filepath: "."
|
|
578
|
+
});
|
|
579
|
+
const message = baseCommit ? `Initial commit\n\nCella-Base: ${baseCommit}` : "Initial commit";
|
|
580
|
+
await git.commit({
|
|
581
|
+
fs: fs$1,
|
|
582
|
+
dir,
|
|
583
|
+
message,
|
|
584
|
+
author: {
|
|
585
|
+
name: "cella",
|
|
586
|
+
email: "info@cellajs.com"
|
|
587
|
+
}
|
|
588
|
+
});
|
|
589
|
+
await git.addRemote({
|
|
590
|
+
fs: fs$1,
|
|
591
|
+
dir,
|
|
592
|
+
remote: "cella-upstream",
|
|
593
|
+
url: githubGitUrl(templateRepository),
|
|
594
|
+
force: true
|
|
595
|
+
});
|
|
596
|
+
} catch (error) {
|
|
597
|
+
warn(`skipped git init: ${error instanceof Error ? error.message : String(error)}`);
|
|
598
|
+
}
|
|
846
599
|
}
|
|
847
|
-
|
|
848
600
|
// src/create-cella-cli.ts
|
|
601
|
+
function parseFlags() {
|
|
602
|
+
const program = new Command(cliName).version(cliVersion, "-v, --version", `output the current version of ${cliName}`).argument("[directory]", "the directory name for the new app").usage("[directory] [options]").helpOption("-h, --help", "display this help message").option("--template <path>", "use a custom template (local git checkout or github:user/repo)").option("--app-index <number>", `set this app's number for its dev ports, ${appIndexRule}`, (value) => {
|
|
603
|
+
if (!isAppIndex(Number(value))) throw new InvalidArgumentError(`App index must be ${appIndexRule}`);
|
|
604
|
+
return Number(value);
|
|
605
|
+
}).option("--admin-email <email>", "set the admin email for the initial seed user", (value) => {
|
|
606
|
+
if (!isEmail(value)) throw new InvalidArgumentError("Admin email must be an address such as admin@example.com");
|
|
607
|
+
return value;
|
|
608
|
+
}).parse();
|
|
609
|
+
const directory = program.args[0]?.trim() || void 0;
|
|
610
|
+
if (directory && !isAppSlug(basename(resolve(directory)))) program.error(`error: invalid app name "${directory}": ${appSlugRule}.`);
|
|
611
|
+
return {
|
|
612
|
+
directory,
|
|
613
|
+
...program.opts()
|
|
614
|
+
};
|
|
615
|
+
}
|
|
849
616
|
async function main() {
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
if (busyPorts.length > 0) {
|
|
895
|
-
console.info(
|
|
896
|
-
`${pc6.yellow("\u26A0")} In use on this machine: ${busyPorts.join(", ")}. Stop what holds them before pnpm docker and pnpm dev.`
|
|
897
|
-
);
|
|
898
|
-
console.info();
|
|
899
|
-
}
|
|
900
|
-
const adminEmail = cli.options.adminEmail ?? await input(
|
|
901
|
-
{
|
|
902
|
-
message: "Admin email for initial seed user",
|
|
903
|
-
default: "admin@example.com",
|
|
904
|
-
theme: promptTheme,
|
|
905
|
-
validate: (email) => isEmail(email) ? true : "Enter an address such as admin@example.com"
|
|
906
|
-
},
|
|
907
|
-
promptContext
|
|
908
|
-
);
|
|
909
|
-
confirmChoice("Admin email", adminEmail);
|
|
910
|
-
const createOptions = {
|
|
911
|
-
projectName,
|
|
912
|
-
targetFolder,
|
|
913
|
-
packageManager: cli.packageManager,
|
|
914
|
-
templateUrl: cli.options.template,
|
|
915
|
-
templateRef,
|
|
916
|
-
appIndex,
|
|
917
|
-
adminEmail
|
|
918
|
-
};
|
|
919
|
-
await create(createOptions);
|
|
617
|
+
const flags = parseFlags();
|
|
618
|
+
showBanner();
|
|
619
|
+
const answers = await askAnswers(flags);
|
|
620
|
+
const { targetFolder } = answers;
|
|
621
|
+
let undo = async () => {};
|
|
622
|
+
const onSignal = (code) => () => {
|
|
623
|
+
stopSpinner();
|
|
624
|
+
undo().finally(() => process.exit(code));
|
|
625
|
+
};
|
|
626
|
+
const onSigint = onSignal(130);
|
|
627
|
+
const onSigterm = onSignal(143);
|
|
628
|
+
process.once("SIGINT", onSigint).once("SIGTERM", onSigterm);
|
|
629
|
+
let missing;
|
|
630
|
+
try {
|
|
631
|
+
step("creating app folder");
|
|
632
|
+
const createdFolder = await mkdir(targetFolder, { recursive: true });
|
|
633
|
+
undo = () => removeOutput(targetFolder, createdFolder);
|
|
634
|
+
const baseCommit = await getTemplate(answers);
|
|
635
|
+
step("cleaning template");
|
|
636
|
+
missing = await writeAppFiles(answers);
|
|
637
|
+
step("initializing git");
|
|
638
|
+
await makeRepository(targetFolder, baseCommit);
|
|
639
|
+
step();
|
|
640
|
+
} catch (error) {
|
|
641
|
+
stopSpinner();
|
|
642
|
+
await undo();
|
|
643
|
+
throw error;
|
|
644
|
+
} finally {
|
|
645
|
+
process.off("SIGINT", onSigint).off("SIGTERM", onSigterm);
|
|
646
|
+
}
|
|
647
|
+
if (missing.length > 0) warn(`Not in the template, skipped: ${missing.join(", ")}`);
|
|
648
|
+
showNextSteps(answers);
|
|
649
|
+
}
|
|
650
|
+
/** Remove what a run wrote: the folders `mkdir` made, else everything in the target, which the run only accepts empty. */
|
|
651
|
+
async function removeOutput(targetFolder, createdFolder) {
|
|
652
|
+
if (createdFolder) return rm(createdFolder, {
|
|
653
|
+
recursive: true,
|
|
654
|
+
force: true
|
|
655
|
+
});
|
|
656
|
+
const entries = await readdir(targetFolder);
|
|
657
|
+
await Promise.all(entries.map((entry) => rm(join(targetFolder, entry), {
|
|
658
|
+
recursive: true,
|
|
659
|
+
force: true
|
|
660
|
+
})));
|
|
920
661
|
}
|
|
921
662
|
main().catch((error) => {
|
|
922
|
-
|
|
923
|
-
|
|
663
|
+
if (error instanceof Error && error.name === "ExitPromptError") process.exit(130);
|
|
664
|
+
console.error(`${pc.red("✗")} ${pc.red(error instanceof Error ? error.message : String(error))}`);
|
|
665
|
+
process.exit(1);
|
|
924
666
|
});
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
console.info(pc6.dim("This create CLI allows you to get started with cella quickly."));
|
|
928
|
-
console.info();
|
|
929
|
-
if (release)
|
|
930
|
-
console.info(` Latest release: ${release.tag}${release.date ? ` ${pc6.dim(`\xB7 ${release.date}`)}` : ""}`);
|
|
931
|
-
if (commit) {
|
|
932
|
-
console.info(` Latest commit: ${commit.shortSha} ${pc6.dim(`\xB7 ${commit.message} \xB7 ${commit.date}`)}`);
|
|
933
|
-
const repo = TEMPLATE_URL.replace("github:", "");
|
|
934
|
-
console.info(` ${pc6.gray(`https://github.com/${repo}/commit/${commit.sha}`)}`);
|
|
935
|
-
}
|
|
936
|
-
if (release || commit) console.info();
|
|
937
|
-
if (!release) {
|
|
938
|
-
console.info(`${pc6.yellow("\u26A0")} Latest release not found \xB7 using the latest commit on main`);
|
|
939
|
-
console.info();
|
|
940
|
-
return commit ? "main" : void 0;
|
|
941
|
-
}
|
|
942
|
-
if (!commit || !process.stdin.isTTY) {
|
|
943
|
-
confirmChoice("Latest release", release.tag);
|
|
944
|
-
return release.tag;
|
|
945
|
-
}
|
|
946
|
-
const choice = await select(
|
|
947
|
-
{
|
|
948
|
-
message: "Choose which cella version to start from:",
|
|
949
|
-
theme,
|
|
950
|
-
choices: [
|
|
951
|
-
{ name: "Latest release", value: "release" },
|
|
952
|
-
{ name: "Latest commit", value: "commit" }
|
|
953
|
-
]
|
|
954
|
-
},
|
|
955
|
-
context
|
|
956
|
-
);
|
|
957
|
-
if (choice === "release") {
|
|
958
|
-
confirmChoice("Latest release", release.tag);
|
|
959
|
-
return release.tag;
|
|
960
|
-
}
|
|
961
|
-
confirmChoice("Latest commit", commit.shortSha);
|
|
962
|
-
return "main";
|
|
963
|
-
}
|
|
964
|
-
function formatAppIndex(i, suffix = "") {
|
|
965
|
-
return `${i} \u2192 :${3e3 + i} / :${4e3 + i * 10} / :${5432 + i * 10}${suffix}`;
|
|
966
|
-
}
|
|
967
|
-
async function promptAppIndex(targetFolder, theme, context) {
|
|
968
|
-
const usedPorts = await detectUsedPorts(targetFolder);
|
|
969
|
-
const presets = [1, 2, 3];
|
|
970
|
-
const busy = new Map(await Promise.all([0, ...presets].map(async (i) => [i, await findBusyPorts(i)])));
|
|
971
|
-
const isBusy = (i) => (busy.get(i)?.length ?? 0) > 0;
|
|
972
|
-
const suggested = findNextAppIndex(usedPorts, isBusy);
|
|
973
|
-
const label = (i, note = "") => formatAppIndex(i, isBusy(i) ? ` (port ${busy.get(i)?.[0]} in use)` : note);
|
|
974
|
-
let message = `${pc6.bold("App index")} ${pc6.dim("\xB7 to avoid port conflicts with other apps on this machine")}`;
|
|
975
|
-
if (usedPorts.length > 0) {
|
|
976
|
-
const count = usedPorts.length;
|
|
977
|
-
message += pc6.dim(`
|
|
978
|
-
Detected ${count} sibling app${count === 1 ? "" : "s"} \xB7 suggested index ${suggested}`);
|
|
979
|
-
}
|
|
980
|
-
const portTheme = {
|
|
981
|
-
...theme,
|
|
982
|
-
style: { ...theme.style ?? {}, message: (text) => text }
|
|
983
|
-
};
|
|
984
|
-
const choice = await select(
|
|
985
|
-
{
|
|
986
|
-
message,
|
|
987
|
-
theme: portTheme,
|
|
988
|
-
choices: [
|
|
989
|
-
...suggested > 0 ? [{ name: formatAppIndex(suggested, " (suggested)"), value: suggested }] : [],
|
|
990
|
-
{ name: label(0, " (default)"), value: 0 },
|
|
991
|
-
...presets.filter((i) => i !== suggested).map((i) => ({ name: label(i), value: i })),
|
|
992
|
-
{ name: "Custom index", value: -1 }
|
|
993
|
-
]
|
|
994
|
-
},
|
|
995
|
-
context
|
|
996
|
-
);
|
|
997
|
-
if (choice !== -1) return choice;
|
|
998
|
-
const custom = await input(
|
|
999
|
-
{
|
|
1000
|
-
message: "Enter custom index (0-9, not 4)",
|
|
1001
|
-
default: String(suggested),
|
|
1002
|
-
theme,
|
|
1003
|
-
validate: (val) => isAppIndex(Number(val)) ? true : "Must be a whole number from 0 to 9, not 4"
|
|
1004
|
-
},
|
|
1005
|
-
context
|
|
1006
|
-
);
|
|
1007
|
-
return Number(custom);
|
|
1008
|
-
}
|
|
667
|
+
export {};
|
|
668
|
+
|
|
1009
669
|
//# sourceMappingURL=index.js.map
|