@cellajs/create-cella 0.5.1 → 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 +518 -903
- package/dist/index.js.map +1 -1
- package/package.json +20 -14
package/dist/index.js
CHANGED
|
@@ -1,979 +1,370 @@
|
|
|
1
1
|
#!/usr/bin/env tsx
|
|
2
|
-
import fs, {
|
|
3
|
-
import
|
|
4
|
-
import
|
|
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";
|
|
5
6
|
import { input, select } from "@inquirer/prompts";
|
|
6
|
-
import
|
|
7
|
+
import { styleText } from "node:util";
|
|
8
|
+
import { connect } from "node:net";
|
|
7
9
|
import git from "isomorphic-git";
|
|
8
|
-
import { Command, InvalidArgumentError } from "commander";
|
|
9
|
-
import validate from "validate-npm-package-name";
|
|
10
10
|
import http from "isomorphic-git/http/node";
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const SYNC_CONFIG = "cella/cella.config.ts";
|
|
31
|
-
/** Upstream remote of a new app: HTTPS, so reading a public template needs no SSH key. */
|
|
32
|
-
const CELLA_REMOTE_URL = TEMPLATE_GIT_URL;
|
|
33
|
-
/**
|
|
34
|
-
* Git remote name pointing at upstream cella. Matches the name the sync CLI
|
|
35
|
-
* (`pnpm cella`) expects, so scaffolds don't end up with a duplicate remote.
|
|
36
|
-
*/
|
|
37
|
-
const CELLA_REMOTE_NAME = "cella-upstream";
|
|
38
|
-
/** Export details from package.json */
|
|
39
|
-
const DESCRIPTION = description;
|
|
40
|
-
const VERSION = version;
|
|
41
|
-
const WEBSITE = homepage;
|
|
42
|
-
function getHeaderLine() {
|
|
43
|
-
const leftText = `⧈ ${NAME} · ${VERSION}`;
|
|
44
|
-
const left = `${pc.cyan(`⧈ ${NAME}`)} ${pc.dim(`· ${VERSION}`)}`;
|
|
45
|
-
const right = pc.cyan(WEBSITE);
|
|
46
|
-
const padding = Math.max(1, 60 - leftText.length - WEBSITE.length);
|
|
47
|
-
return `${left}${" ".repeat(padding)}${right}`;
|
|
48
|
-
}
|
|
49
|
-
const TO_REMOVE = ["./infra/Pulumi.production.yaml", "./infra/Pulumi.staging.yaml"];
|
|
50
|
-
const TO_CLEAN = ["./backend/drizzle"];
|
|
51
|
-
const TO_COPY = { "./frontend/.env.example": "./frontend/.env" };
|
|
52
|
-
/** The template's quickstart, which becomes the new app's README. */
|
|
53
|
-
const QUICKSTART = "./cella/QUICKSTART.md";
|
|
54
|
-
/** Entry points a coding agent reads from the repo root; the rules and skills live in the template's `cella/` folder. */
|
|
55
|
-
const AGENT_FILES = {
|
|
56
|
-
"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",
|
|
57
|
-
"CLAUDE.md": "@cella/AGENTS.md\n"
|
|
58
|
-
};
|
|
59
|
-
/** Frontend dev port of an app number. */
|
|
60
|
-
const frontendPort = (appIndex) => 3e3 + appIndex;
|
|
61
|
-
/**
|
|
62
|
-
* 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.
|
|
63
|
-
* Its links are relative to `cella/` in the template, so `./x` becomes `./cella/x` and `../x` becomes `./x`.
|
|
64
|
-
*/
|
|
65
|
-
function quickstartToReadme(source, displayName, appIndex) {
|
|
66
|
-
return source.replace(/^# .*$/m, `# ${displayName}`).replace(/^## Create\n[\s\S]*?(?=^## )/m, "").replaceAll("](./", "](./cella/").replaceAll("](../", "](./").replaceAll("http://localhost:3000", `http://localhost:${frontendPort(appIndex)}`);
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Fork config template that replaces `shared/config/config.default.ts` in new forks.
|
|
70
|
-
*/
|
|
71
|
-
const PLACEHOLDER_CONFIG = "shared/config/config.template.ts";
|
|
72
|
-
/**
|
|
73
|
-
* Starting version for a fresh fork. Resets the upstream cella version so
|
|
74
|
-
* release-please cuts the fork's first release from a clean slate.
|
|
75
|
-
*/
|
|
76
|
-
const INITIAL_VERSION = "0.0.0";
|
|
77
|
-
/**
|
|
78
|
-
* Read a `.env.example` file and apply key=value replacements.
|
|
79
|
-
* Comments and unmatched keys are preserved as-is.
|
|
80
|
-
* Returns null if the file doesn't exist (caller should generate from scratch).
|
|
81
|
-
*/
|
|
82
|
-
async function generateEnvFromExample(examplePath, replacements) {
|
|
83
|
-
const { readFile } = await import("node:fs/promises");
|
|
84
|
-
let content;
|
|
85
|
-
try {
|
|
86
|
-
content = await readFile(examplePath, "utf8");
|
|
87
|
-
} catch {
|
|
88
|
-
return null;
|
|
89
|
-
}
|
|
90
|
-
return content.replace(/^([A-Z_][A-Z0-9_]*)=(.*)$/gm, (match, key, _value) => {
|
|
91
|
-
if (key in replacements) return `${key}=${replacements[key]}`;
|
|
92
|
-
return match;
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Replacement map for the app's `.env`: the seed admin alone. The database ports and URLs follow `devAppIndex` in the
|
|
97
|
-
* shared config, and the service ports come from `services` there, so no port lives in the env file.
|
|
98
|
-
*/
|
|
99
|
-
function getBackendEnvReplacements(adminEmail) {
|
|
100
|
-
return { ADMIN_EMAIL: adminEmail };
|
|
101
|
-
}
|
|
102
|
-
/** Set the app's number in the source of `config.default.ts`; a template without the key can only give index 0. */
|
|
103
|
-
function setDevAppIndex(source, appIndex) {
|
|
104
|
-
const pattern = /^(\s*devAppIndex:\s*)\d+/m;
|
|
105
|
-
if (appIndex !== 0 && !pattern.test(source)) throw new Error("This template has no devAppIndex in its config: use app index 0, or a newer template.");
|
|
106
|
-
return source.replace(pattern, (_, head) => `${head}${appIndex}`);
|
|
107
|
-
}
|
|
108
|
-
// src/utils/git/command.ts
|
|
109
|
-
/**
|
|
110
|
-
* Git helpers backed by isomorphic-git (pure JS) instead of shelling out to the
|
|
111
|
-
* `git` binary. This keeps `create-cella` free of `child_process` (no shell access)
|
|
112
|
-
* and removes any dependency on the user's global git config — the initial commit
|
|
113
|
-
* uses an explicit author, so scaffolding never fails with "Author identity unknown".
|
|
114
|
-
*/
|
|
115
|
-
/** Author used for the scaffold's initial commit (users re-author their own commits later). */
|
|
116
|
-
const INITIAL_AUTHOR = {
|
|
117
|
-
name: "cella",
|
|
118
|
-
email: "info@cellajs.com"
|
|
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)
|
|
119
30
|
};
|
|
31
|
+
// src/dev-ports.ts
|
|
120
32
|
/**
|
|
121
|
-
*
|
|
122
|
-
|
|
123
|
-
async function gitInit(repoPath) {
|
|
124
|
-
await git.init({
|
|
125
|
-
fs,
|
|
126
|
-
dir: repoPath,
|
|
127
|
-
defaultBranch: "main"
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* Stages all files in the repository (respects `.gitignore`).
|
|
132
|
-
*/
|
|
133
|
-
async function gitAddAll(repoPath) {
|
|
134
|
-
await git.add({
|
|
135
|
-
fs,
|
|
136
|
-
dir: repoPath,
|
|
137
|
-
filepath: "."
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* Creates a commit with the specified message and returns the commit SHA.
|
|
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'.
|
|
142
35
|
*/
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
|
|
153
|
-
* `git remote get-url` failing) so callers can detect a missing remote.
|
|
154
|
-
*/
|
|
155
|
-
async function gitRemoteGetUrl(repoPath, remoteName) {
|
|
156
|
-
const match = (await git.listRemotes({
|
|
157
|
-
fs,
|
|
158
|
-
dir: repoPath
|
|
159
|
-
})).find((r) => r.remote === remoteName);
|
|
160
|
-
if (!match) throw new Error(`No such remote '${remoteName}'`);
|
|
161
|
-
return match.url;
|
|
162
|
-
}
|
|
163
|
-
/**
|
|
164
|
-
* Adds a new remote.
|
|
165
|
-
*/
|
|
166
|
-
async function gitRemoteAdd(repoPath, remoteName, remoteUrl) {
|
|
167
|
-
await git.addRemote({
|
|
168
|
-
fs,
|
|
169
|
-
dir: repoPath,
|
|
170
|
-
remote: remoteName,
|
|
171
|
-
url: remoteUrl
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Removes a remote.
|
|
176
|
-
*/
|
|
177
|
-
async function gitRemoteRemove(repoPath, remoteName) {
|
|
178
|
-
await git.deleteRemote({
|
|
179
|
-
fs,
|
|
180
|
-
dir: repoPath,
|
|
181
|
-
remote: remoteName
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
// src/add-remote.ts
|
|
185
|
-
/**
|
|
186
|
-
* Adds or updates the upstream remote for the Cella template.
|
|
187
|
-
* @param options - Configuration options
|
|
188
|
-
* @param options.silent - If true, don't throw on failure (used when called from progress tracker)
|
|
189
|
-
*/
|
|
190
|
-
async function addRemote({ targetFolder, remoteUrl = CELLA_REMOTE_URL, remoteName = CELLA_REMOTE_NAME, silent = false }) {
|
|
191
|
-
try {
|
|
192
|
-
let remote = null;
|
|
193
|
-
try {
|
|
194
|
-
remote = await gitRemoteGetUrl(targetFolder, remoteName);
|
|
195
|
-
} catch {
|
|
196
|
-
remote = null;
|
|
197
|
-
}
|
|
198
|
-
if (!remote) await gitRemoteAdd(targetFolder, remoteName, remoteUrl);
|
|
199
|
-
else if (remote !== remoteUrl) {
|
|
200
|
-
await gitRemoteRemove(targetFolder, remoteName);
|
|
201
|
-
await gitRemoteAdd(targetFolder, remoteName, remoteUrl);
|
|
202
|
-
}
|
|
203
|
-
} catch (error) {
|
|
204
|
-
if (!silent) throw error;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
// src/utils/detect-used-ports.ts
|
|
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]
|
|
41
|
+
});
|
|
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";
|
|
208
46
|
/**
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
* Handles legacy configs with backendUrl on its own port.
|
|
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.
|
|
214
51
|
*/
|
|
215
52
|
async function detectUsedPorts(targetFolder) {
|
|
216
53
|
const parentDir = dirname(targetFolder);
|
|
54
|
+
const siblings = await readdir(parentDir).catch(() => []);
|
|
217
55
|
const used = [];
|
|
218
|
-
let siblings;
|
|
219
|
-
try {
|
|
220
|
-
siblings = await readdir(parentDir);
|
|
221
|
-
} catch {
|
|
222
|
-
return used;
|
|
223
|
-
}
|
|
224
56
|
for (const name of siblings) {
|
|
225
57
|
const configDir = join(parentDir, name, "shared/config");
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
backend: backend + index * 10
|
|
242
|
-
});
|
|
243
|
-
} catch {}
|
|
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
|
+
});
|
|
244
73
|
}
|
|
245
74
|
return used;
|
|
246
75
|
}
|
|
247
|
-
/**
|
|
248
|
-
|
|
249
|
-
/** Find the first app index whose frontend port and service block no sibling uses and that `isBusy` leaves free. */
|
|
250
|
-
function findNextAppIndex(usedPorts, isBusy = () => false) {
|
|
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) {
|
|
251
78
|
for (let index = 0; index <= 9; index += 1) {
|
|
252
79
|
if (!isAppIndex(index) || isBusy(index)) continue;
|
|
253
|
-
const
|
|
254
|
-
|
|
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;
|
|
255
83
|
}
|
|
256
84
|
return 0;
|
|
257
85
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
const
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
};
|
|
269
|
-
}
|
|
270
|
-
// src/modules/cli/commands.ts
|
|
271
|
-
function parseAppIndex(value) {
|
|
272
|
-
const parsed = Number(value);
|
|
273
|
-
if (!isAppIndex(parsed)) throw new InvalidArgumentError("App index must be a whole number from 0 to 9, not 4");
|
|
274
|
-
return parsed;
|
|
275
|
-
}
|
|
276
|
-
function parseAdminEmail(value) {
|
|
277
|
-
if (!isEmail(value)) throw new InvalidArgumentError("Admin email must be an address such as admin@example.com");
|
|
278
|
-
return value;
|
|
279
|
-
}
|
|
280
|
-
let directory = null;
|
|
281
|
-
const packageManager = "pnpm";
|
|
282
|
-
/**
|
|
283
|
-
* Defines the root CLI command using Commander.
|
|
284
|
-
* This command accepts CLI options and validates user input.
|
|
285
|
-
*/
|
|
286
|
-
const 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) => {
|
|
287
|
-
const trimmedName = typeof name === "string" ? name.trim() : name;
|
|
288
|
-
if (trimmedName) {
|
|
289
|
-
const validation = validateProjectName(basename(resolve(trimmedName)));
|
|
290
|
-
if (!validation.valid) self.error(`error: invalid project name "${trimmedName}": ${validation.problems?.[0] ?? "unknown error"}. Use lowercase letters, digits and dashes, such as my-app.`);
|
|
291
|
-
directory = trimmedName;
|
|
292
|
-
}
|
|
293
|
-
}).parse();
|
|
294
|
-
const options = command.opts();
|
|
295
|
-
/**
|
|
296
|
-
* Runs the CLI and returns the parsed configuration.
|
|
297
|
-
* This function parses command line arguments and returns the CLI config.
|
|
298
|
-
*/
|
|
299
|
-
function runCli() {
|
|
300
|
-
return {
|
|
301
|
-
options,
|
|
302
|
-
args: command.args,
|
|
303
|
-
directory,
|
|
304
|
-
packageManager
|
|
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);
|
|
305
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]);
|
|
306
106
|
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
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();
|
|
311
118
|
console.info(pc.cyan(" _ _ "));
|
|
312
119
|
console.info(pc.cyan("▒▓█████▓▒ ___ ___| | | __ _ "));
|
|
313
120
|
console.info(pc.cyan("▒▓█ █▓▒ / __/ _ \\ | |/ _` | "));
|
|
314
121
|
console.info(pc.cyan("▒▓█ █▓▒ | (_| __/ | | (_| | "));
|
|
315
122
|
console.info(pc.cyan("▒▓█████▓▒ \\___\\___|_|_|\\__,_| "));
|
|
316
|
-
}
|
|
317
|
-
/**
|
|
318
|
-
* Displays the compact CLI welcome header.
|
|
319
|
-
*/
|
|
320
|
-
function showWelcome() {
|
|
321
|
-
console.info();
|
|
322
|
-
showAscii();
|
|
323
123
|
console.info();
|
|
324
|
-
console.info(pc.dim(
|
|
124
|
+
console.info(pc.dim(description));
|
|
325
125
|
console.info();
|
|
326
|
-
|
|
327
|
-
|
|
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);
|
|
328
131
|
}
|
|
329
|
-
/**
|
|
330
|
-
* Print a cleared prompt's outcome as a persistent confirmation line:
|
|
331
|
-
* `✓ <label> · <value>`, followed by a blank separator line. Used after prompts
|
|
332
|
-
* that clear themselves on done so the chosen value stays visible.
|
|
333
|
-
*/
|
|
132
|
+
/** Keep the answer of a prompt that clears itself on screen. */
|
|
334
133
|
function confirmChoice(label, value) {
|
|
335
|
-
console.info(`${
|
|
134
|
+
console.info(`${checkMark} ${label} · ${value}`);
|
|
336
135
|
console.info();
|
|
337
136
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
*/
|
|
341
|
-
function
|
|
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}`)}`);
|
|
342
182
|
console.info();
|
|
343
183
|
console.info(pc.bold("Next steps"));
|
|
344
|
-
console.info(
|
|
184
|
+
console.info(divider);
|
|
345
185
|
console.info();
|
|
346
|
-
if (
|
|
347
|
-
console.info(`${pc.dim("$")} ${pc.cyan(
|
|
348
|
-
console.info(`${pc.dim("$")} ${pc.cyan(
|
|
349
|
-
console.info(`${pc.dim("$")} ${pc.cyan(
|
|
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")}`);
|
|
350
190
|
console.info();
|
|
351
|
-
console.info(`${pc.gray("Then open")} ${pc.cyan(`http://localhost:${
|
|
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.")}`);
|
|
352
192
|
console.info();
|
|
353
|
-
|
|
354
|
-
console.info(`${pc.gray("To get started building, please read:")} ${pc.cyan(readmePath)}`);
|
|
193
|
+
console.info(`${pc.gray("To get started building, please read:")} ${pc.cyan(path ? `${path}/README.md` : "README.md")}`);
|
|
355
194
|
console.info();
|
|
356
|
-
console.info(`🥳 enjoy building ${pc.green(
|
|
195
|
+
console.info(`🥳 enjoy building ${pc.green(name)} with cella!`);
|
|
357
196
|
console.info();
|
|
358
197
|
}
|
|
359
|
-
// src/
|
|
360
|
-
const
|
|
361
|
-
/**
|
|
362
|
-
|
|
363
|
-
* @param params - Parameters containing the target folder, project name, and optional extra edits.
|
|
364
|
-
*/
|
|
365
|
-
async function cleanTemplate({ targetFolder, projectName, displayName, appIndex = 0, adminEmail = `admin@${projectName}.example.com` }) {
|
|
366
|
-
if (process.cwd() !== targetFolder) process.chdir(targetFolder);
|
|
367
|
-
return new Promise((resolve, reject) => {
|
|
368
|
-
(async () => {
|
|
369
|
-
try {
|
|
370
|
-
for (const [src, dest] of Object.entries(TO_COPY)) await copyFile(path.resolve(targetFolder, src), path.resolve(targetFolder, dest));
|
|
371
|
-
await writeReadme(targetFolder, displayName, appIndex);
|
|
372
|
-
await writeAgentEntry(targetFolder);
|
|
373
|
-
await applyPlaceholderConfig(targetFolder, projectName, displayName, appIndex);
|
|
374
|
-
await resetReleaseState(targetFolder, projectName);
|
|
375
|
-
await removeTemplateForks(targetFolder);
|
|
376
|
-
const replacements = getBackendEnvReplacements(adminEmail);
|
|
377
|
-
const rootEnv = await generateEnvFromExample(path.resolve(targetFolder, ".env.example"), replacements);
|
|
378
|
-
const appEnv = rootEnv ?? await generateEnvFromExample(path.resolve(targetFolder, "backend/.env.example"), replacements);
|
|
379
|
-
if (appEnv) await fs$1.writeFile(path.resolve(targetFolder, rootEnv ? ".env" : "backend/.env"), appEnv, "utf8");
|
|
380
|
-
await Promise.all(TO_CLEAN.map((folderPath) => {
|
|
381
|
-
return removeFolderContents(path.resolve(targetFolder, folderPath));
|
|
382
|
-
}));
|
|
383
|
-
await Promise.all(TO_REMOVE.map((filePath) => {
|
|
384
|
-
return removeFileOrFolder(path.resolve(targetFolder, filePath));
|
|
385
|
-
}));
|
|
386
|
-
resolve();
|
|
387
|
-
} catch (err) {
|
|
388
|
-
reject(`Error during the cleaning process: ${err}`);
|
|
389
|
-
}
|
|
390
|
-
})();
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
/** Write the app's README from the template's quickstart. A template without one keeps its own README. */
|
|
394
|
-
async function writeReadme(targetFolder, displayName, appIndex) {
|
|
395
|
-
try {
|
|
396
|
-
const readme = quickstartToReadme(await fs$1.readFile(path.resolve(targetFolder, QUICKSTART), "utf8"), displayName, appIndex);
|
|
397
|
-
await fs$1.writeFile(path.resolve(targetFolder, "README.md"), readme, "utf8");
|
|
398
|
-
} catch (err) {
|
|
399
|
-
if (err.code !== "ENOENT") throw err;
|
|
400
|
-
console.info(`\n${warningMark} "${QUICKSTART}" not found > Skip README`);
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
/** Point coding agents at the template's rules and skills, which sit in `cella/`, out of a root they would not search. */
|
|
404
|
-
async function writeAgentEntry(targetFolder) {
|
|
405
|
-
await Promise.all(Object.entries(AGENT_FILES).map(([file, content]) => fs$1.writeFile(path.resolve(targetFolder, file), content, "utf8")));
|
|
406
|
-
try {
|
|
407
|
-
await fs$1.mkdir(path.resolve(targetFolder, ".claude"), { recursive: true });
|
|
408
|
-
await fs$1.symlink("../cella/skills", path.resolve(targetFolder, ".claude/skills"));
|
|
409
|
-
} catch (err) {
|
|
410
|
-
console.info(`\n${warningMark} skipped .claude/skills: ${err instanceof Error ? err.message : String(err)}`);
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
/**
|
|
414
|
-
* Removes all contents within a specified folder.
|
|
415
|
-
* @param folderPath - The path of the folder to clean.
|
|
416
|
-
*/
|
|
417
|
-
async function removeFolderContents(folderPath) {
|
|
418
|
-
let files;
|
|
419
|
-
try {
|
|
420
|
-
files = await fs$1.readdir(folderPath);
|
|
421
|
-
} catch (err) {
|
|
422
|
-
if (err.code === "ENOENT") return;
|
|
423
|
-
throw err;
|
|
424
|
-
}
|
|
425
|
-
await Promise.all(files.map((file) => fs$1.rm(path.join(folderPath, file), {
|
|
426
|
-
recursive: true,
|
|
427
|
-
force: true
|
|
428
|
-
})));
|
|
429
|
-
}
|
|
430
|
-
/**
|
|
431
|
-
* Removes a specified file or folder.
|
|
432
|
-
* @param pathToRemove - The path to the file or folder to remove.
|
|
433
|
-
*/
|
|
434
|
-
async function removeFileOrFolder(pathToRemove) {
|
|
435
|
-
await fs$1.rm(pathToRemove, {
|
|
436
|
-
recursive: true,
|
|
437
|
-
force: true
|
|
438
|
-
});
|
|
439
|
-
}
|
|
440
|
-
/**
|
|
441
|
-
* Helper function to copy files if the source exists.
|
|
442
|
-
* @param src - The source file path.
|
|
443
|
-
* @param dest - The destination file path.
|
|
444
|
-
*/
|
|
445
|
-
async function copyFile(src, dest) {
|
|
446
|
-
try {
|
|
447
|
-
await fs$1.access(src);
|
|
448
|
-
await fs$1.mkdir(path.dirname(dest), { recursive: true });
|
|
449
|
-
await fs$1.copyFile(src, dest);
|
|
450
|
-
} catch (err) {
|
|
451
|
-
if (err.code === "ENOENT") console.info(`\n${warningMark} Source file "${src}" does not exist > Skip copy`);
|
|
452
|
-
else throw err;
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
/**
|
|
456
|
-
* Read the fork config template shipped inside the cloned Cella template
|
|
457
|
-
* (`shared/config/config.template.ts`), interpolate project tokens, write the
|
|
458
|
-
* result as `shared/config/config.default.ts` — replacing the original — and
|
|
459
|
-
* delete the now-consumed template from the fork.
|
|
460
|
-
*/
|
|
461
|
-
async function applyPlaceholderConfig(targetFolder, projectName, displayName, appIndex) {
|
|
462
|
-
const src = path.resolve(targetFolder, PLACEHOLDER_CONFIG);
|
|
463
|
-
const dest = path.resolve(targetFolder, "./shared/config/config.default.ts");
|
|
464
|
-
try {
|
|
465
|
-
let content = await fs$1.readFile(src, "utf8");
|
|
466
|
-
content = content.replaceAll("__project_name__", displayName);
|
|
467
|
-
content = content.replaceAll("__project_slug__", projectName);
|
|
468
|
-
content = setDevAppIndex(content, appIndex);
|
|
469
|
-
await fs$1.writeFile(dest, content, "utf8");
|
|
470
|
-
await fs$1.rm(src, { force: true });
|
|
471
|
-
} catch (err) {
|
|
472
|
-
if (err.code === "ENOENT") console.info(`\n${warningMark} Fork config template "${src}" not found > Skip`);
|
|
473
|
-
else throw err;
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* Remove the `forks` property, and a comment line directly above it, from the source of a sync
|
|
478
|
-
* config. Returns the source unchanged when it has no such property.
|
|
479
|
-
*/
|
|
480
|
-
function stripForks(source) {
|
|
481
|
-
return source.replace(/^(?:[ \t]*\/\/[^\n]*\n)?([ \t]*)forks:\s*\[(?:[^\n]*|[\s\S]*?\n\1)\],?[ \t]*\n(?:[ \t]*\n)?/m, "");
|
|
482
|
-
}
|
|
483
|
-
/**
|
|
484
|
-
* The template's sync config lists the repos the template itself syncs to. A new app has none,
|
|
485
|
-
* and the sync CLI never merges this file, so the list is removed once here.
|
|
486
|
-
*/
|
|
487
|
-
async function removeTemplateForks(targetFolder) {
|
|
488
|
-
const configPath = path.resolve(targetFolder, SYNC_CONFIG);
|
|
489
|
-
try {
|
|
490
|
-
const source = await fs$1.readFile(configPath, "utf8");
|
|
491
|
-
const stripped = stripForks(source);
|
|
492
|
-
if (stripped !== source) await fs$1.writeFile(configPath, stripped, "utf8");
|
|
493
|
-
} catch (err) {
|
|
494
|
-
if (err.code === "ENOENT") console.info(`\n${warningMark} "${SYNC_CONFIG}" not found > Skip forks removal`);
|
|
495
|
-
else throw err;
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
/**
|
|
499
|
-
* Reset the upstream cella release identity so the new fork starts clean:
|
|
500
|
-
* - root `package.json`: `name` → project slug, `version` → INITIAL_VERSION,
|
|
501
|
-
* and blank out `license`/`repository`/`description`/`keywords`/`author`/`homepage`
|
|
502
|
-
* (keys kept visible so the fork can fill in its own metadata)
|
|
503
|
-
* - `.github/release-please-manifest.json` → `{ ".": INITIAL_VERSION }`
|
|
504
|
-
* - `.github/release-please-config.json`: `changelog-path` → root `CHANGELOG.md`
|
|
505
|
-
* (cella tracks its own changelog in the template docs folder, which the fork
|
|
506
|
-
* keeps as upstream reference; the fork's own releases write to a fresh root changelog)
|
|
507
|
-
* - `CHANGELOG.md` → fresh stub
|
|
508
|
-
*/
|
|
509
|
-
async function resetReleaseState(targetFolder, projectName) {
|
|
510
|
-
const pkgPath = path.resolve(targetFolder, "package.json");
|
|
511
|
-
try {
|
|
512
|
-
let pkg = await fs$1.readFile(pkgPath, "utf8");
|
|
513
|
-
pkg = pkg.replace(/^(\s*"name":\s*)"[^"]*"/m, `$1"${projectName}"`);
|
|
514
|
-
pkg = pkg.replace(/^(\s*"version":\s*)"[^"]*"/m, `$1"${INITIAL_VERSION}"`);
|
|
515
|
-
for (const field of [
|
|
516
|
-
"license",
|
|
517
|
-
"repository",
|
|
518
|
-
"description",
|
|
519
|
-
"author",
|
|
520
|
-
"homepage"
|
|
521
|
-
]) pkg = pkg.replace(new RegExp(`^(\\s*"${field}":\\s*)"[^"]*"`, "m"), "$1\"\"");
|
|
522
|
-
pkg = pkg.replace(/^(\s*"keywords":\s*)\[[^\]]*\]/m, "$1[]");
|
|
523
|
-
await fs$1.writeFile(pkgPath, pkg, "utf8");
|
|
524
|
-
} catch (err) {
|
|
525
|
-
if (err.code === "ENOENT") console.info(`\n${warningMark} "package.json" not found > Skip version reset`);
|
|
526
|
-
else throw err;
|
|
527
|
-
}
|
|
528
|
-
const configPath = path.resolve(targetFolder, ".github/release-please-config.json");
|
|
529
|
-
try {
|
|
530
|
-
const config = JSON.parse(await fs$1.readFile(configPath, "utf8"));
|
|
531
|
-
config.packages ??= {};
|
|
532
|
-
config.packages["."] ??= {};
|
|
533
|
-
config.packages["."]["changelog-path"] = "CHANGELOG.md";
|
|
534
|
-
await fs$1.writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
535
|
-
} catch (err) {
|
|
536
|
-
if (err.code === "ENOENT") console.info(`\n${warningMark} "release-please-config.json" not found > Skip changelog path reset`);
|
|
537
|
-
else throw err;
|
|
538
|
-
}
|
|
539
|
-
await fs$1.writeFile(path.resolve(targetFolder, ".github/release-please-manifest.json"), `{\n ".": "${INITIAL_VERSION}"\n}\n`, "utf8");
|
|
540
|
-
await fs$1.writeFile(path.resolve(targetFolder, "CHANGELOG.md"), "# Changelog\n", "utf8");
|
|
541
|
-
}
|
|
542
|
-
// src/utils/download-template.ts
|
|
543
|
-
/** Parse `github:owner/repo` or `owner/repo` into its owner and repo parts. */
|
|
544
|
-
function parseGithubRepo(template) {
|
|
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) {
|
|
545
202
|
const [owner, repo] = template.replace(/^github:/, "").split("/");
|
|
546
203
|
if (!owner || !repo) throw new Error(`Invalid template '${template}'. Expected 'github:owner/repo'.`);
|
|
547
|
-
return {
|
|
548
|
-
owner,
|
|
549
|
-
repo
|
|
550
|
-
};
|
|
551
|
-
}
|
|
552
|
-
/**
|
|
553
|
-
* Clones a GitHub template into `targetFolder` using isomorphic-git (pure JS).
|
|
554
|
-
*
|
|
555
|
-
* A shallow, single-branch clone over HTTPS — no `git` binary, no `child_process`,
|
|
556
|
-
* so `create-cella` keeps a clean supply-chain profile (no shell access). Unlike a
|
|
557
|
-
* raw tarball parse, isomorphic-git reconstructs the tree itself, so file modes and
|
|
558
|
-
* long paths are always correct. The cloned `.git` history is discarded afterwards;
|
|
559
|
-
* scaffolding re-initialises the repo with a fresh initial commit.
|
|
560
|
-
*
|
|
561
|
-
* @param template - `github:owner/repo` (or `owner/repo`).
|
|
562
|
-
* @param ref - Branch or tag to check out (e.g. `main` or a release tag).
|
|
563
|
-
* @param targetFolder - Directory to clone the template into.
|
|
564
|
-
* @returns The exact upstream commit SHA the template was scaffolded from.
|
|
565
|
-
*/
|
|
566
|
-
async function downloadGithubTemplate(template, ref, targetFolder) {
|
|
567
|
-
const { owner, repo } = parseGithubRepo(template);
|
|
568
|
-
const url = `https://github.com/${owner}/${repo}.git`;
|
|
569
|
-
await git.clone({
|
|
570
|
-
fs,
|
|
571
|
-
http,
|
|
572
|
-
dir: targetFolder,
|
|
573
|
-
url,
|
|
574
|
-
ref,
|
|
575
|
-
singleBranch: true,
|
|
576
|
-
depth: 1
|
|
577
|
-
});
|
|
578
|
-
const baseSha = await git.resolveRef({
|
|
579
|
-
fs,
|
|
580
|
-
dir: targetFolder,
|
|
581
|
-
ref: "HEAD"
|
|
582
|
-
});
|
|
583
|
-
await rm(join(targetFolder, ".git"), {
|
|
584
|
-
recursive: true,
|
|
585
|
-
force: true
|
|
586
|
-
});
|
|
587
|
-
return baseSha;
|
|
588
|
-
}
|
|
589
|
-
// src/utils/list-template-files.ts
|
|
590
|
-
/**
|
|
591
|
-
* Lists the files under `root` that git would track, without shelling out to git.
|
|
592
|
-
*
|
|
593
|
-
* Honors the root `.gitignore` (via the `ignore` package) and always skips `.git`
|
|
594
|
-
* and `node_modules`. Used for the local-template dev flow (`--template ./local`)
|
|
595
|
-
* so build output and local `.env` secrets aren't copied into the new project.
|
|
596
|
-
*
|
|
597
|
-
* Paths are returned relative to `root` using POSIX separators.
|
|
598
|
-
*/
|
|
599
|
-
async function listTemplateFiles(root) {
|
|
600
|
-
const ig = ignore().add([".git", "node_modules"]);
|
|
601
|
-
try {
|
|
602
|
-
ig.add(await readFile(join(root, ".gitignore"), "utf8"));
|
|
603
|
-
} catch {}
|
|
604
|
-
const files = [];
|
|
605
|
-
async function walk(relDir) {
|
|
606
|
-
const entries = await readdir(relDir ? join(root, relDir) : root, { withFileTypes: true });
|
|
607
|
-
for (const entry of entries) {
|
|
608
|
-
const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
|
|
609
|
-
if (ig.ignores(entry.isDirectory() ? `${rel}/` : rel)) continue;
|
|
610
|
-
if (entry.isDirectory()) await walk(rel);
|
|
611
|
-
else if (entry.isFile()) files.push(rel);
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
await walk("");
|
|
615
|
-
return files;
|
|
616
|
-
}
|
|
617
|
-
// src/utils/progress.ts
|
|
618
|
-
/**
|
|
619
|
-
* Progress Tracker Utility
|
|
620
|
-
*
|
|
621
|
-
* Provides compact progress tracking for CLI operations.
|
|
622
|
-
* Uses a single spinner that updates in place.
|
|
623
|
-
*/
|
|
624
|
-
/** Global reference to the currently active spinner */
|
|
625
|
-
let activeSpinner = null;
|
|
626
|
-
/** Pause the active spinner (for interactive prompts) */
|
|
627
|
-
function pauseSpinner() {
|
|
628
|
-
if (activeSpinner) activeSpinner.stop();
|
|
629
|
-
}
|
|
630
|
-
/** Resume the active spinner after a prompt */
|
|
631
|
-
function resumeSpinner() {
|
|
632
|
-
if (activeSpinner) activeSpinner.start();
|
|
633
|
-
}
|
|
634
|
-
/**
|
|
635
|
-
* Creates a progress tracker for a multi-step operation.
|
|
636
|
-
* Shows a single spinner that updates in place.
|
|
637
|
-
*
|
|
638
|
-
* @param title - The initial title for the spinner
|
|
639
|
-
* @returns A ProgressTracker instance
|
|
640
|
-
*
|
|
641
|
-
* @example
|
|
642
|
-
* const progress = createProgress('creating project');
|
|
643
|
-
* progress.step('downloading template');
|
|
644
|
-
* progress.step('installing dependencies');
|
|
645
|
-
* progress.done('project created');
|
|
646
|
-
*/
|
|
647
|
-
function createProgress(title, silent = false) {
|
|
648
|
-
const completedSteps = [];
|
|
649
|
-
const spinner = ora({
|
|
650
|
-
text: title,
|
|
651
|
-
isSilent: silent
|
|
652
|
-
});
|
|
653
|
-
activeSpinner = spinner;
|
|
654
|
-
spinner.start();
|
|
655
|
-
const log = (msg) => {
|
|
656
|
-
if (!silent) console.info(msg);
|
|
657
|
-
};
|
|
658
|
-
return {
|
|
659
|
-
step: (message) => {
|
|
660
|
-
if (completedSteps.length > 0) {
|
|
661
|
-
spinner.stop();
|
|
662
|
-
log(`${pc.green("✓")} ${completedSteps[completedSteps.length - 1]}`);
|
|
663
|
-
}
|
|
664
|
-
completedSteps.push(message);
|
|
665
|
-
spinner.text = message;
|
|
666
|
-
spinner.start();
|
|
667
|
-
},
|
|
668
|
-
done: (message) => {
|
|
669
|
-
if (completedSteps.length > 0) {
|
|
670
|
-
spinner.stop();
|
|
671
|
-
log(`${pc.green("✓")} ${completedSteps[completedSteps.length - 1]}`);
|
|
672
|
-
} else spinner.stop();
|
|
673
|
-
activeSpinner = null;
|
|
674
|
-
if (message) {
|
|
675
|
-
log("");
|
|
676
|
-
log(`${pc.green("✓")} ${message}`);
|
|
677
|
-
}
|
|
678
|
-
},
|
|
679
|
-
fail: (message) => {
|
|
680
|
-
spinner.stop();
|
|
681
|
-
activeSpinner = null;
|
|
682
|
-
log(`${pc.red("✗")} ${pc.red(message)}`);
|
|
683
|
-
}
|
|
684
|
-
};
|
|
685
|
-
}
|
|
686
|
-
// src/create.ts
|
|
687
|
-
/** Check if a path is a local directory */
|
|
688
|
-
function isLocalPath(path) {
|
|
689
|
-
return path.startsWith("/") || path.startsWith("./") || path.startsWith("../");
|
|
690
|
-
}
|
|
691
|
-
async function create({ projectName, targetFolder, packageManager, templateUrl, templateRef, appIndex, adminEmail, silent = false }) {
|
|
692
|
-
const originalCwd = process.cwd();
|
|
693
|
-
const template = templateUrl || "github:cellajs/cella";
|
|
694
|
-
const isLocalTemplate = templateUrl && isLocalPath(templateUrl);
|
|
695
|
-
const progress = createProgress("creating project", silent);
|
|
696
|
-
try {
|
|
697
|
-
progress.step("creating project folder");
|
|
698
|
-
await mkdir(targetFolder, { recursive: true });
|
|
699
|
-
process.chdir(targetFolder);
|
|
700
|
-
let baseSha = null;
|
|
701
|
-
if (isLocalTemplate) {
|
|
702
|
-
progress.step("copying local template");
|
|
703
|
-
const sourcePath = resolve(originalCwd, templateUrl);
|
|
704
|
-
const rel = relative(sourcePath, targetFolder);
|
|
705
|
-
if (rel === "" || !rel.startsWith("..") && !isAbsolute(rel)) throw new Error(`Cannot create project inside the template directory.
|
|
706
|
-
Run from outside: cd ~ && pnpm create @cellajs/cella ${projectName} --template ${templateUrl}`);
|
|
707
|
-
const tracked = await listTemplateFiles(sourcePath);
|
|
708
|
-
for (const rel of tracked) {
|
|
709
|
-
const src = join(sourcePath, rel);
|
|
710
|
-
if (!existsSync(src)) continue;
|
|
711
|
-
const dest = join(targetFolder, rel);
|
|
712
|
-
await mkdir(dirname(dest), { recursive: true });
|
|
713
|
-
await cp(src, dest);
|
|
714
|
-
}
|
|
715
|
-
} else {
|
|
716
|
-
const ref = templateRef ?? "main";
|
|
717
|
-
progress.step(`downloading cella template${templateRef ? ` (${templateRef})` : ""}`);
|
|
718
|
-
baseSha = await downloadGithubTemplate(template, ref, targetFolder);
|
|
719
|
-
}
|
|
720
|
-
progress.step("cleaning template");
|
|
721
|
-
await cleanTemplate({
|
|
722
|
-
targetFolder,
|
|
723
|
-
projectName,
|
|
724
|
-
displayName: projectName.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
|
725
|
-
appIndex,
|
|
726
|
-
adminEmail
|
|
727
|
-
});
|
|
728
|
-
const gitFolderPath = join(targetFolder, ".git");
|
|
729
|
-
if (!existsSync(gitFolderPath)) try {
|
|
730
|
-
progress.step("initializing git");
|
|
731
|
-
await gitInit(targetFolder);
|
|
732
|
-
await gitAddAll(targetFolder);
|
|
733
|
-
await gitCommit(targetFolder, baseSha ? `Initial commit\n\nCella-Base: ${baseSha}` : "Initial commit");
|
|
734
|
-
} catch (error) {
|
|
735
|
-
if (!silent) {
|
|
736
|
-
pauseSpinner();
|
|
737
|
-
console.warn(`${pc.yellow("⚠")} skipped git init: ${error instanceof Error ? error.message : String(error)}`);
|
|
738
|
-
resumeSpinner();
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
progress.step("adding upstream remote");
|
|
742
|
-
await addRemote({
|
|
743
|
-
targetFolder,
|
|
744
|
-
silent: true
|
|
745
|
-
});
|
|
746
|
-
progress.done(pc.bold(`created ${projectName}`));
|
|
747
|
-
} catch (error) {
|
|
748
|
-
progress.fail(error instanceof Error ? error.message : String(error));
|
|
749
|
-
throw error;
|
|
750
|
-
}
|
|
751
|
-
const needsCd = originalCwd !== targetFolder;
|
|
752
|
-
showSuccess(projectName, targetFolder, relative(originalCwd, targetFolder), needsCd, packageManager, appIndex, adminEmail ?? `admin@${projectName}.example.com`);
|
|
753
|
-
}
|
|
754
|
-
// src/utils/busy-ports.ts
|
|
755
|
-
const SERVICE_PORTS = 7;
|
|
756
|
-
/** Every local port an app number takes: the frontend, its service block, and the dev and test databases. */
|
|
757
|
-
const appPorts = (appIndex) => [
|
|
758
|
-
3e3 + appIndex,
|
|
759
|
-
...Array.from({ length: SERVICE_PORTS }, (_, i) => 4e3 + appIndex * 10 + i),
|
|
760
|
-
5432 + appIndex * 10,
|
|
761
|
-
5434 + appIndex * 10
|
|
762
|
-
];
|
|
763
|
-
/** Whether something on this machine accepts a connection on the port. */
|
|
764
|
-
const isListening = (port) => new Promise((resolve) => {
|
|
765
|
-
const socket = connect({
|
|
766
|
-
port,
|
|
767
|
-
host: "127.0.0.1",
|
|
768
|
-
timeout: 300
|
|
769
|
-
});
|
|
770
|
-
const finish = (listening) => {
|
|
771
|
-
socket.destroy();
|
|
772
|
-
resolve(listening);
|
|
773
|
-
};
|
|
774
|
-
socket.once("connect", () => finish(true));
|
|
775
|
-
socket.once("timeout", () => finish(false));
|
|
776
|
-
socket.once("error", () => finish(false));
|
|
777
|
-
});
|
|
778
|
-
/** The ports of an app number that are already taken, lowest first. */
|
|
779
|
-
async function findBusyPorts(appIndex) {
|
|
780
|
-
const ports = appPorts(appIndex);
|
|
781
|
-
const listening = await Promise.all(ports.map(isListening));
|
|
782
|
-
return ports.filter((_, i) => listening[i]);
|
|
204
|
+
return `https://github.com/${owner}/${repo}.git`;
|
|
783
205
|
}
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
* The release tag is read from the template's git tags, over the transport the clone uses, so
|
|
790
|
-
* it does not depend on the GitHub API and its limit for callers without a token. Dates and the
|
|
791
|
-
* commit subject come from that API. Every helper fails soft; the caller falls back to the
|
|
792
|
-
* default branch when no release is known.
|
|
793
|
-
*/
|
|
794
|
-
const TEMPLATE_METADATA_API_BASE = `https://api.github.com/repos/${TEMPLATE_REPOSITORY}`;
|
|
795
|
-
/** Format an ISO timestamp as a locale-independent YYYY-MM-DD date. */
|
|
796
|
-
function toDate(iso) {
|
|
797
|
-
return iso ? iso.slice(0, 10) : "unknown";
|
|
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. */
|
|
209
|
+
function pickLatestReleaseTag(tags) {
|
|
210
|
+
return tags.filter((tag) => releaseTagPattern.test(tag)).sort((a, b) => a.localeCompare(b, "en", { numeric: true })).at(-1) ?? null;
|
|
798
211
|
}
|
|
799
|
-
const GITHUB_HEADERS = { Accept: "application/vnd.github+json" };
|
|
800
212
|
/**
|
|
801
|
-
*
|
|
802
|
-
*
|
|
803
|
-
* pre-releases are no template release.
|
|
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.
|
|
804
215
|
*/
|
|
805
|
-
function pickLatestReleaseTag(tags) {
|
|
806
|
-
let latest = null;
|
|
807
|
-
for (const tag of tags) {
|
|
808
|
-
const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(tag);
|
|
809
|
-
if (!match) continue;
|
|
810
|
-
const version = match.slice(1).map(Number);
|
|
811
|
-
if (!latest || isNewer(version, latest.version)) latest = {
|
|
812
|
-
tag,
|
|
813
|
-
version
|
|
814
|
-
};
|
|
815
|
-
}
|
|
816
|
-
return latest?.tag ?? null;
|
|
817
|
-
}
|
|
818
|
-
/** Whether version `a` is higher than `b`, both as [major, minor, patch]. */
|
|
819
|
-
function isNewer(a, b) {
|
|
820
|
-
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] > b[i];
|
|
821
|
-
return false;
|
|
822
|
-
}
|
|
823
|
-
/** Fetch the latest template release: its tag from the git tags, its date from the GitHub API. */
|
|
824
216
|
async function fetchLatestRelease() {
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
prefix: "refs/tags/"
|
|
831
|
-
})).map(({ ref }) => ref.slice(10)));
|
|
832
|
-
} catch {
|
|
833
|
-
return null;
|
|
834
|
-
}
|
|
217
|
+
const tag = pickLatestReleaseTag((await git.listServerRefs({
|
|
218
|
+
http,
|
|
219
|
+
url: githubGitUrl(templateRepository),
|
|
220
|
+
prefix: "refs/tags/"
|
|
221
|
+
}).catch(() => [])).map(({ ref }) => ref.slice(10)));
|
|
835
222
|
if (!tag) return null;
|
|
836
223
|
return {
|
|
837
224
|
tag,
|
|
838
|
-
date: await
|
|
225
|
+
date: (await fetchGithub(`releases/tags/${tag}`))?.published_at?.slice(0, 10)
|
|
839
226
|
};
|
|
840
227
|
}
|
|
841
|
-
/**
|
|
842
|
-
async function
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
}
|
|
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
|
+
};
|
|
851
238
|
}
|
|
852
|
-
/**
|
|
853
|
-
async function
|
|
854
|
-
const apiUrl = `${TEMPLATE_METADATA_API_BASE}/commits/${branch}`;
|
|
239
|
+
/** A GitHub API answer about the template, or null: callers without a token have a low limit. */
|
|
240
|
+
async function fetchGithub(path) {
|
|
855
241
|
try {
|
|
856
|
-
const
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
if (!data.sha) return null;
|
|
860
|
-
const message = (data.commit?.message ?? "").split("\n")[0];
|
|
861
|
-
return {
|
|
862
|
-
sha: data.sha,
|
|
863
|
-
shortSha: data.sha.slice(0, 7),
|
|
864
|
-
message,
|
|
865
|
-
date: toDate(data.commit?.author?.date)
|
|
866
|
-
};
|
|
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;
|
|
867
245
|
} catch {
|
|
868
246
|
return null;
|
|
869
247
|
}
|
|
870
248
|
}
|
|
871
|
-
|
|
249
|
+
const isLocalPath = (path) => path.startsWith("/") || path.startsWith("./") || path.startsWith("../");
|
|
872
250
|
/**
|
|
873
|
-
*
|
|
874
|
-
*
|
|
875
|
-
* @
|
|
876
|
-
*
|
|
877
|
-
* @throws Throws an error if the path is not a directory or if there's an issue reading the directory.
|
|
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.
|
|
878
255
|
*/
|
|
879
|
-
async function
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
return validation.valid ? true : `Invalid project name: ${validation.problems?.[0] ?? "unknown error"}`;
|
|
899
|
-
}
|
|
900
|
-
}, promptContext);
|
|
901
|
-
const targetFolder = resolve(cli.directory);
|
|
902
|
-
const projectName = basename(targetFolder)?.toLowerCase() || "project";
|
|
903
|
-
if (existsSync(targetFolder) && !await isEmptyDirectory(targetFolder)) {
|
|
904
|
-
const message = `${cli.directory === "." ? "Current directory" : `Target directory "${targetFolder}"`} is not empty. Please choose how you would like to proceed:`;
|
|
905
|
-
const action = await select({
|
|
906
|
-
message,
|
|
907
|
-
theme: promptTheme,
|
|
908
|
-
choices: [{
|
|
909
|
-
name: "Cancel and exit",
|
|
910
|
-
value: "cancel"
|
|
911
|
-
}, {
|
|
912
|
-
name: "Remove existing files and continue",
|
|
913
|
-
value: "remove"
|
|
914
|
-
}]
|
|
915
|
-
}, promptContext);
|
|
916
|
-
if (action === "cancel") process.exit(1);
|
|
917
|
-
if (action === "remove") await rm(targetFolder, {
|
|
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"), {
|
|
918
275
|
recursive: true,
|
|
919
276
|
force: true
|
|
920
277
|
});
|
|
278
|
+
return baseCommit;
|
|
921
279
|
}
|
|
922
|
-
|
|
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);
|
|
923
326
|
confirmChoice("App index", formatAppIndex(appIndex));
|
|
924
327
|
const busyPorts = await findBusyPorts(appIndex);
|
|
925
328
|
if (busyPorts.length > 0) {
|
|
926
|
-
|
|
329
|
+
warn(`In use on this machine: ${busyPorts.join(", ")}. Stop what holds them before pnpm docker and pnpm dev.`);
|
|
927
330
|
console.info();
|
|
928
331
|
}
|
|
929
|
-
const adminEmail =
|
|
332
|
+
const adminEmail = flags.adminEmail ?? await input({
|
|
930
333
|
message: "Admin email for initial seed user",
|
|
931
334
|
default: "admin@example.com",
|
|
932
|
-
theme
|
|
335
|
+
theme,
|
|
933
336
|
validate: (email) => isEmail(email) ? true : "Enter an address such as admin@example.com"
|
|
934
|
-
},
|
|
337
|
+
}, context);
|
|
935
338
|
confirmChoice("Admin email", adminEmail);
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
targetFolder,
|
|
939
|
-
packageManager: cli.packageManager,
|
|
940
|
-
templateUrl: cli.options.template,
|
|
339
|
+
return {
|
|
340
|
+
template,
|
|
941
341
|
templateRef,
|
|
342
|
+
targetFolder,
|
|
343
|
+
name: basename(targetFolder),
|
|
942
344
|
appIndex,
|
|
943
345
|
adminEmail
|
|
944
|
-
}
|
|
346
|
+
};
|
|
945
347
|
}
|
|
946
|
-
main().catch((error) => {
|
|
947
|
-
console.error(error);
|
|
948
|
-
process.exit(1);
|
|
949
|
-
});
|
|
950
348
|
/**
|
|
951
|
-
*
|
|
952
|
-
*
|
|
953
|
-
* scaffold from. Returns the template ref to check out (release tag or `main`), or
|
|
954
|
-
* undefined to use the default branch (when metadata is unavailable).
|
|
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).
|
|
955
351
|
*/
|
|
956
|
-
async function
|
|
352
|
+
async function askTemplateRef() {
|
|
957
353
|
const [release, commit] = await Promise.all([fetchLatestRelease(), fetchLatestCommit()]);
|
|
958
354
|
console.info(pc.dim("This create CLI allows you to get started with cella quickly."));
|
|
959
355
|
console.info();
|
|
960
356
|
if (release) console.info(` Latest release: ${release.tag}${release.date ? ` ${pc.dim(`· ${release.date}`)}` : ""}`);
|
|
961
357
|
if (commit) {
|
|
962
|
-
console.info(` Latest commit: ${commit.
|
|
963
|
-
|
|
964
|
-
console.info(` ${pc.gray(`https://github.com/${repo}/commit/${commit.sha}`)}`);
|
|
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}`)}`);
|
|
965
360
|
}
|
|
966
361
|
if (release || commit) console.info();
|
|
967
362
|
if (!release) {
|
|
968
|
-
|
|
363
|
+
warn("Latest release not found · using the latest commit on main");
|
|
969
364
|
console.info();
|
|
970
365
|
return commit ? "main" : void 0;
|
|
971
366
|
}
|
|
972
|
-
if (!commit || !process.stdin.isTTY
|
|
973
|
-
confirmChoice("Latest release", release.tag);
|
|
974
|
-
return release.tag;
|
|
975
|
-
}
|
|
976
|
-
if (await select({
|
|
367
|
+
if (!commit || !process.stdin.isTTY || await select({
|
|
977
368
|
message: "Choose which cella version to start from:",
|
|
978
369
|
theme,
|
|
979
370
|
choices: [{
|
|
@@ -987,16 +378,17 @@ async function promptTemplateRef(theme, context) {
|
|
|
987
378
|
confirmChoice("Latest release", release.tag);
|
|
988
379
|
return release.tag;
|
|
989
380
|
}
|
|
990
|
-
confirmChoice("Latest commit", commit.
|
|
381
|
+
confirmChoice("Latest commit", commit.sha.slice(0, 7));
|
|
991
382
|
return "main";
|
|
992
383
|
}
|
|
993
|
-
/**
|
|
994
|
-
function formatAppIndex(
|
|
995
|
-
|
|
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}`;
|
|
996
388
|
}
|
|
997
|
-
/**
|
|
998
|
-
async function
|
|
999
|
-
const
|
|
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);
|
|
1000
392
|
const presets = [
|
|
1001
393
|
1,
|
|
1002
394
|
2,
|
|
@@ -1004,23 +396,22 @@ async function promptAppIndex(targetFolder, theme, context) {
|
|
|
1004
396
|
];
|
|
1005
397
|
const busy = new Map(await Promise.all([0, ...presets].map(async (i) => [i, await findBusyPorts(i)])));
|
|
1006
398
|
const isBusy = (i) => (busy.get(i)?.length ?? 0) > 0;
|
|
1007
|
-
const suggested = findNextAppIndex(
|
|
399
|
+
const suggested = findNextAppIndex(siblings, isBusy);
|
|
1008
400
|
const label = (i, note = "") => formatAppIndex(i, isBusy(i) ? ` (port ${busy.get(i)?.[0]} in use)` : note);
|
|
1009
401
|
let message = `${pc.bold("App index")} ${pc.dim("· to avoid port conflicts with other apps on this machine")}`;
|
|
1010
|
-
if (
|
|
1011
|
-
const count =
|
|
402
|
+
if (siblings.length > 0) {
|
|
403
|
+
const count = siblings.length;
|
|
1012
404
|
message += pc.dim(`\nDetected ${count} sibling app${count === 1 ? "" : "s"} · suggested index ${suggested}`);
|
|
1013
405
|
}
|
|
1014
|
-
const portTheme = {
|
|
1015
|
-
...theme,
|
|
1016
|
-
style: {
|
|
1017
|
-
...theme.style ?? {},
|
|
1018
|
-
message: (text) => text
|
|
1019
|
-
}
|
|
1020
|
-
};
|
|
1021
406
|
const choice = await select({
|
|
1022
407
|
message,
|
|
1023
|
-
theme:
|
|
408
|
+
theme: {
|
|
409
|
+
...theme,
|
|
410
|
+
style: {
|
|
411
|
+
...theme.style,
|
|
412
|
+
message: (text) => text
|
|
413
|
+
}
|
|
414
|
+
},
|
|
1024
415
|
choices: [
|
|
1025
416
|
...suggested > 0 ? [{
|
|
1026
417
|
name: formatAppIndex(suggested, " (suggested)"),
|
|
@@ -1042,13 +433,237 @@ async function promptAppIndex(targetFolder, theme, context) {
|
|
|
1042
433
|
}, context);
|
|
1043
434
|
if (choice !== -1) return choice;
|
|
1044
435
|
const custom = await input({
|
|
1045
|
-
message:
|
|
436
|
+
message: `Enter custom index, ${appIndexRule}`,
|
|
1046
437
|
default: String(suggested),
|
|
1047
438
|
theme,
|
|
1048
|
-
validate: (
|
|
439
|
+
validate: (value) => isAppIndex(Number(value)) ? true : `Must be ${appIndexRule}`
|
|
1049
440
|
}, context);
|
|
1050
441
|
return Number(custom);
|
|
1051
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
|
+
}
|
|
599
|
+
}
|
|
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
|
+
}
|
|
616
|
+
async function main() {
|
|
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
|
+
})));
|
|
661
|
+
}
|
|
662
|
+
main().catch((error) => {
|
|
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);
|
|
666
|
+
});
|
|
1052
667
|
export {};
|
|
1053
668
|
|
|
1054
669
|
//# sourceMappingURL=index.js.map
|