openadminjs 0.1.24 → 0.2.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 +97 -16
- package/dist/adapt-package-manager.d.ts +3 -0
- package/dist/adapt-package-manager.js +115 -0
- package/dist/adapt-package-manager.test.d.ts +1 -0
- package/dist/adapt-package-manager.test.js +76 -0
- package/dist/cli.e2e.test.d.ts +1 -0
- package/dist/cli.e2e.test.js +87 -0
- package/dist/create-project.d.ts +31 -2
- package/dist/create-project.js +296 -102
- package/dist/create-project.test.js +180 -4
- package/dist/database-providers.integration.test.d.ts +1 -0
- package/dist/database-providers.integration.test.js +64 -0
- package/dist/db-commands.d.ts +20 -0
- package/dist/db-commands.js +75 -0
- package/dist/db-commands.test.d.ts +1 -0
- package/dist/db-commands.test.js +27 -0
- package/dist/detect-package-manager.d.ts +8 -0
- package/dist/detect-package-manager.js +37 -0
- package/dist/doctor.d.ts +13 -0
- package/dist/doctor.js +203 -0
- package/dist/doctor.test.d.ts +1 -0
- package/dist/doctor.test.js +102 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +233 -141
- package/dist/index.test.js +7 -3
- package/dist/render-schema.d.ts +20 -0
- package/dist/render-schema.js +37 -0
- package/dist/render-schema.test.d.ts +1 -0
- package/dist/render-schema.test.js +57 -0
- package/dist/secrets.d.ts +24 -0
- package/dist/secrets.js +93 -0
- package/dist/secrets.test.d.ts +1 -0
- package/dist/secrets.test.js +36 -0
- package/dist/security.d.ts +13 -0
- package/dist/security.js +168 -0
- package/dist/security.test.d.ts +1 -0
- package/dist/security.test.js +54 -0
- package/dist/validate-name.d.ts +33 -0
- package/dist/validate-name.js +206 -0
- package/dist/validate-name.test.d.ts +1 -0
- package/dist/validate-name.test.js +63 -0
- package/package.json +26 -1
- package/template/README.md +22 -3
- package/template/apps/api/package.json +3 -0
- package/template/apps/api/src/common/json-field-codec.test.ts +76 -0
- package/template/apps/api/src/common/json-field-codec.ts +139 -0
- package/template/apps/api/src/common/prisma.service.test.ts +19 -0
- package/template/apps/api/src/common/prisma.service.ts +13 -0
- package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +26 -0
- package/template/apps/api/src/graphql/graphql.module.ts +13 -1
- package/template/package.json +2 -0
- package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -0
package/dist/create-project.js
CHANGED
|
@@ -1,15 +1,56 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readdirSync } from "node:fs";
|
|
1
|
+
import { accessSync, constants as fsConstants, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync } from "node:fs";
|
|
2
2
|
import net from "node:net";
|
|
3
3
|
import { dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { spawnSync } from "node:child_process";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { cancel, confirm, intro, isCancel, outro, select, text } from "@clack/prompts";
|
|
6
|
+
import { cancel, confirm, intro, isCancel, note, outro, select, text } from "@clack/prompts";
|
|
7
7
|
import fsExtra from "fs-extra";
|
|
8
8
|
import pc from "picocolors";
|
|
9
|
+
import { adaptProjectForPackageManager } from "./adapt-package-manager.js";
|
|
10
|
+
import { generateSecret } from "./secrets.js";
|
|
11
|
+
import { renderSchemaForProvider } from "./render-schema.js";
|
|
9
12
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
10
13
|
const { copySync, ensureDirSync, readFileSync, writeFileSync } = fsExtra;
|
|
11
14
|
const BINARY_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".eot"]);
|
|
15
|
+
/** Minimum supported Node.js major version (kept in sync with package.json engines). */
|
|
16
|
+
export const MIN_NODE_MAJOR = 20;
|
|
12
17
|
const placeholderPattern = /__APP_NAME__|__PACKAGE_NAME__|__DATABASE_URL__|__DATABASE_PROVIDER__|__REDIS_URL__|__JWT_SECRET__|__JWT_REFRESH_SECRET__|__ADMIN_ORIGIN__|__API_PORT__/g;
|
|
18
|
+
/**
|
|
19
|
+
* Root .gitignore written into every generated project. Written BEFORE `git init`
|
|
20
|
+
* so a subsequent `git add .` can never stage `.env` files or build output.
|
|
21
|
+
*/
|
|
22
|
+
const GITIGNORE_CONTENTS = `# dependencies
|
|
23
|
+
node_modules
|
|
24
|
+
.pnpm-store
|
|
25
|
+
|
|
26
|
+
# build output
|
|
27
|
+
.next
|
|
28
|
+
dist
|
|
29
|
+
build
|
|
30
|
+
out
|
|
31
|
+
coverage
|
|
32
|
+
*.tsbuildinfo
|
|
33
|
+
.turbo
|
|
34
|
+
|
|
35
|
+
# environment / secrets
|
|
36
|
+
.env
|
|
37
|
+
.env.*
|
|
38
|
+
!.env.example
|
|
39
|
+
|
|
40
|
+
# logs
|
|
41
|
+
*.log
|
|
42
|
+
|
|
43
|
+
# local databases
|
|
44
|
+
*.db
|
|
45
|
+
*.db-journal
|
|
46
|
+
*.sqlite
|
|
47
|
+
*.sqlite3
|
|
48
|
+
|
|
49
|
+
# OS / editor
|
|
50
|
+
.DS_Store
|
|
51
|
+
.idea
|
|
52
|
+
.vscode
|
|
53
|
+
`;
|
|
13
54
|
export function toPackageName(input) {
|
|
14
55
|
return input
|
|
15
56
|
.trim()
|
|
@@ -20,6 +61,39 @@ export function toPackageName(input) {
|
|
|
20
61
|
export function defaultTemplateDir() {
|
|
21
62
|
return resolve(__dirname, "../template");
|
|
22
63
|
}
|
|
64
|
+
/** Returns the current Node.js major version. */
|
|
65
|
+
export function currentNodeMajor() {
|
|
66
|
+
return Number(process.versions.node.split(".")[0]);
|
|
67
|
+
}
|
|
68
|
+
/** Throws if the running Node.js is older than the supported minimum. */
|
|
69
|
+
export function assertSupportedNode() {
|
|
70
|
+
const major = currentNodeMajor();
|
|
71
|
+
if (Number.isFinite(major) && major < MIN_NODE_MAJOR) {
|
|
72
|
+
throw new Error(`Node.js ${MIN_NODE_MAJOR}+ is required (found ${process.versions.node}). Please upgrade Node.js.`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Returns true when the given package manager is on PATH. */
|
|
76
|
+
export function isPackageManagerAvailable(packageManager) {
|
|
77
|
+
const result = spawnSync(packageManager, ["--version"], { stdio: "ignore" });
|
|
78
|
+
return !result.error && result.status === 0;
|
|
79
|
+
}
|
|
80
|
+
/** Throws with an actionable message when pnpm is not installed. */
|
|
81
|
+
export function assertPnpmAvailable() {
|
|
82
|
+
if (!isPackageManagerAvailable("pnpm")) {
|
|
83
|
+
throw new Error("pnpm is required but was not found on your PATH.\n" +
|
|
84
|
+
"Install it with one of:\n" +
|
|
85
|
+
" corepack enable && corepack prepare pnpm@latest --activate\n" +
|
|
86
|
+
" npm install -g pnpm");
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function assertWritableParent(cwd) {
|
|
90
|
+
try {
|
|
91
|
+
accessSync(cwd, fsConstants.W_OK);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
throw new Error(`No write permission for ${cwd}. Choose a writable directory.`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
23
97
|
function parseUrlHostPort(input) {
|
|
24
98
|
try {
|
|
25
99
|
const url = new URL(input);
|
|
@@ -35,7 +109,7 @@ function parseUrlHostPort(input) {
|
|
|
35
109
|
}
|
|
36
110
|
}
|
|
37
111
|
async function checkTcpConnection(host, port, timeoutMs = 1500) {
|
|
38
|
-
await new Promise((
|
|
112
|
+
await new Promise((resolvePromise, reject) => {
|
|
39
113
|
const socket = net.createConnection({ host, port });
|
|
40
114
|
const onError = (err) => {
|
|
41
115
|
socket.destroy();
|
|
@@ -45,7 +119,7 @@ async function checkTcpConnection(host, port, timeoutMs = 1500) {
|
|
|
45
119
|
socket.once("error", onError);
|
|
46
120
|
socket.once("connect", () => {
|
|
47
121
|
socket.end();
|
|
48
|
-
|
|
122
|
+
resolvePromise();
|
|
49
123
|
});
|
|
50
124
|
});
|
|
51
125
|
}
|
|
@@ -54,7 +128,7 @@ async function pingRedis(urlInput, timeoutMs = 1500) {
|
|
|
54
128
|
if (!parsed)
|
|
55
129
|
throw new Error("Invalid Redis URL");
|
|
56
130
|
const port = parsed.port || 6379;
|
|
57
|
-
await new Promise((
|
|
131
|
+
await new Promise((resolvePromise, reject) => {
|
|
58
132
|
const socket = net.createConnection({ host: parsed.host, port });
|
|
59
133
|
const onError = (err) => {
|
|
60
134
|
socket.destroy();
|
|
@@ -70,7 +144,7 @@ async function pingRedis(urlInput, timeoutMs = 1500) {
|
|
|
70
144
|
buffer += chunk.toString("utf8");
|
|
71
145
|
if (buffer.includes("+PONG")) {
|
|
72
146
|
socket.end();
|
|
73
|
-
|
|
147
|
+
resolvePromise();
|
|
74
148
|
}
|
|
75
149
|
if (buffer.includes("-ERR")) {
|
|
76
150
|
onError(new Error("redis error"));
|
|
@@ -79,8 +153,10 @@ async function pingRedis(urlInput, timeoutMs = 1500) {
|
|
|
79
153
|
});
|
|
80
154
|
}
|
|
81
155
|
async function validateDbConnectivity(database, databaseUrlInput) {
|
|
82
|
-
|
|
83
|
-
|
|
156
|
+
// SQLite is a local file — there is no server to reach.
|
|
157
|
+
if (database === "sqlite") {
|
|
158
|
+
return /^file:/.test(databaseUrlInput.trim()) ? undefined : 'SQLite DATABASE_URL must start with "file:".';
|
|
159
|
+
}
|
|
84
160
|
const parsed = parseUrlHostPort(databaseUrlInput);
|
|
85
161
|
if (!parsed)
|
|
86
162
|
return "Invalid database URL.";
|
|
@@ -106,14 +182,27 @@ async function validateRedisConnectivity(redisUrlInput) {
|
|
|
106
182
|
return `Cannot connect to Redis at ${parsed.host}:${port}.`;
|
|
107
183
|
}
|
|
108
184
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
185
|
+
export const DEFAULT_SUPERADMIN_EMAIL = "admin@localhost.dev";
|
|
186
|
+
/** Resolves the final email, applying the default when the user pressed Enter. */
|
|
187
|
+
export function resolveSuperadminEmail(value, fallback = DEFAULT_SUPERADMIN_EMAIL) {
|
|
188
|
+
return value.trim() || fallback;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Validates the superadmin email against the FINAL value (after default
|
|
192
|
+
* resolution), so pressing Enter to accept the default is always valid.
|
|
193
|
+
*/
|
|
194
|
+
export function validateSuperadminEmailInput(value, fallback = DEFAULT_SUPERADMIN_EMAIL) {
|
|
195
|
+
const finalValue = resolveSuperadminEmail(value, fallback);
|
|
196
|
+
return /^\S+@\S+\.\S+$/.test(finalValue) ? undefined : "Enter a valid email address.";
|
|
197
|
+
}
|
|
198
|
+
export function databaseUrl(packageName, database) {
|
|
199
|
+
if (database === "sqlite") {
|
|
200
|
+
return "file:./dev.db";
|
|
112
201
|
}
|
|
113
202
|
if (database === "mysql") {
|
|
114
203
|
return `mysql://openadminjs:openadminjs@localhost:3306/${packageName}`;
|
|
115
204
|
}
|
|
116
|
-
return
|
|
205
|
+
return `postgresql://openadminjs:openadminjs@localhost:5432/${packageName}?schema=public`;
|
|
117
206
|
}
|
|
118
207
|
function renderFile(file, replacements) {
|
|
119
208
|
if (BINARY_EXTENSIONS.has(extname(file).toLowerCase()))
|
|
@@ -139,28 +228,148 @@ function renderTemplateFiles(targetDir, replacements) {
|
|
|
139
228
|
}
|
|
140
229
|
}
|
|
141
230
|
function runPackageManagerScript(packageManager, script, cwd) {
|
|
142
|
-
const command = packageManager === "npm" ? "npm" : packageManager;
|
|
143
231
|
const args = packageManager === "npm" ? ["run", script] : [script];
|
|
144
|
-
const result = spawnSync(
|
|
232
|
+
const result = spawnSync(packageManager, args, { cwd, stdio: "inherit" });
|
|
145
233
|
if (result.status !== 0 || result.error) {
|
|
146
|
-
const
|
|
147
|
-
throw new Error(`Failed to run "${
|
|
234
|
+
const display = packageManager === "npm" ? `npm run ${script}` : `${packageManager} ${script}`;
|
|
235
|
+
throw new Error(`Failed to run "${display}" in ${cwd}.`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function runInstall(packageManager, cwd) {
|
|
239
|
+
const args = packageManager === "yarn" ? [] : ["install"];
|
|
240
|
+
const result = spawnSync(packageManager, args, { cwd, stdio: "inherit" });
|
|
241
|
+
if (result.status !== 0 || result.error) {
|
|
242
|
+
throw new Error(`Dependency installation failed. Run "${packageManager} install" inside ${cwd}.`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/** Writes the root .gitignore. Must run before `git init`. */
|
|
246
|
+
function writeGitignore(targetDir) {
|
|
247
|
+
writeFileSync(join(targetDir, ".gitignore"), GITIGNORE_CONTENTS);
|
|
248
|
+
}
|
|
249
|
+
/** Writes a root .env.example with variable names and safe placeholders only. */
|
|
250
|
+
function writeEnvExample(targetDir, database) {
|
|
251
|
+
const dbUrl = database === "sqlite"
|
|
252
|
+
? "file:./dev.db"
|
|
253
|
+
: database === "mysql"
|
|
254
|
+
? "mysql://user:password@localhost:3306/openadminjs"
|
|
255
|
+
: "postgresql://user:password@localhost:5432/openadminjs?schema=public";
|
|
256
|
+
const lines = [
|
|
257
|
+
"# Copy this file to apps/api/.env and fill in real values.",
|
|
258
|
+
"# NEVER commit the real .env — it is ignored by .gitignore.",
|
|
259
|
+
`DATABASE_URL=${dbUrl}`,
|
|
260
|
+
"REDIS_URL=redis://localhost:6379",
|
|
261
|
+
"# Generate strong secrets, e.g. `node -e \"console.log(require('crypto').randomBytes(48).toString('base64url'))\"`",
|
|
262
|
+
"JWT_SECRET=replace-with-a-long-random-secret",
|
|
263
|
+
"JWT_REFRESH_SECRET=replace-with-a-different-long-random-secret",
|
|
264
|
+
"ADMIN_ORIGIN=http://localhost:3000",
|
|
265
|
+
"API_PORT=4000",
|
|
266
|
+
"SUPERADMIN_EMAIL=admin@localhost.dev",
|
|
267
|
+
"SUPERADMIN_PASSWORD=replace-with-a-strong-password"
|
|
268
|
+
];
|
|
269
|
+
writeFileSync(join(targetDir, ".env.example"), lines.join("\n") + "\n");
|
|
270
|
+
}
|
|
271
|
+
function resolveCreateProjectOptions(options) {
|
|
272
|
+
if (options.packageManager && !["pnpm", "npm", "yarn"].includes(options.packageManager)) {
|
|
273
|
+
throw new Error('packageManager must be "pnpm", "npm", or "yarn".');
|
|
274
|
+
}
|
|
275
|
+
if (options.database && !["postgresql", "mysql", "sqlite"].includes(options.database)) {
|
|
276
|
+
throw new Error('database must be "postgresql", "mysql", or "sqlite".');
|
|
277
|
+
}
|
|
278
|
+
const missing = [];
|
|
279
|
+
if (!options.database)
|
|
280
|
+
missing.push("database");
|
|
281
|
+
if (!options.superadminEmail)
|
|
282
|
+
missing.push("superadminEmail");
|
|
283
|
+
if (!options.superadminPassword)
|
|
284
|
+
missing.push("superadminPassword");
|
|
285
|
+
if (!options.databaseUrl)
|
|
286
|
+
missing.push("databaseUrl");
|
|
287
|
+
if (!options.redisUrl)
|
|
288
|
+
missing.push("redisUrl");
|
|
289
|
+
if (!options.jwtSecret)
|
|
290
|
+
missing.push("jwtSecret");
|
|
291
|
+
if (!options.jwtRefreshSecret)
|
|
292
|
+
missing.push("jwtRefreshSecret");
|
|
293
|
+
if (!options.adminOrigin)
|
|
294
|
+
missing.push("adminOrigin");
|
|
295
|
+
if (!options.apiPort)
|
|
296
|
+
missing.push("apiPort");
|
|
297
|
+
if (missing.length) {
|
|
298
|
+
throw new Error(`createProject() missing required option(s): ${missing.join(", ")}`);
|
|
148
299
|
}
|
|
300
|
+
return {
|
|
301
|
+
projectName: options.projectName,
|
|
302
|
+
cwd: options.cwd ?? process.cwd(),
|
|
303
|
+
packageManager: options.packageManager ?? "pnpm",
|
|
304
|
+
database: options.database,
|
|
305
|
+
superadminEmail: options.superadminEmail,
|
|
306
|
+
superadminPassword: options.superadminPassword,
|
|
307
|
+
databaseUrl: options.databaseUrl,
|
|
308
|
+
redisUrl: options.redisUrl,
|
|
309
|
+
jwtSecret: options.jwtSecret,
|
|
310
|
+
jwtRefreshSecret: options.jwtRefreshSecret,
|
|
311
|
+
adminOrigin: options.adminOrigin,
|
|
312
|
+
apiPort: options.apiPort,
|
|
313
|
+
git: options.git ?? false,
|
|
314
|
+
install: options.install ?? false,
|
|
315
|
+
templateDir: options.templateDir ?? defaultTemplateDir()
|
|
316
|
+
};
|
|
149
317
|
}
|
|
318
|
+
/**
|
|
319
|
+
* Generates the scaffold into a sibling staging directory and atomically renames
|
|
320
|
+
* it into place only after generation succeeds. On failure the staging directory
|
|
321
|
+
* is removed and an existing target directory is never touched.
|
|
322
|
+
*/
|
|
150
323
|
export function createProject(options) {
|
|
151
|
-
const
|
|
324
|
+
const resolved = resolveCreateProjectOptions(options);
|
|
325
|
+
const appName = resolved.projectName;
|
|
152
326
|
const packageName = toPackageName(appName);
|
|
153
327
|
if (!packageName)
|
|
154
328
|
throw new Error("Project name must contain at least one letter or number.");
|
|
155
|
-
const targetDir = resolve(
|
|
329
|
+
const targetDir = resolve(resolved.cwd, appName);
|
|
156
330
|
if (existsSync(targetDir))
|
|
157
331
|
throw new Error(`${targetDir} already exists.`);
|
|
332
|
+
assertWritableParent(resolved.cwd);
|
|
333
|
+
const stagingDir = mkdtempSync(`${targetDir}.tmp-`);
|
|
334
|
+
try {
|
|
335
|
+
generateIntoDir(stagingDir, resolved, { appName, packageName });
|
|
336
|
+
renameSync(stagingDir, targetDir);
|
|
337
|
+
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
rmSync(stagingDir, { recursive: true, force: true });
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
// git init + install happen in the final directory (post-atomic-rename).
|
|
343
|
+
if (resolved.git) {
|
|
344
|
+
const gitResult = spawnSync("git", ["init"], { cwd: targetDir, stdio: "ignore" });
|
|
345
|
+
if (gitResult.status !== 0 || gitResult.error) {
|
|
346
|
+
throw new Error("Failed to initialize git repository.");
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (resolved.install) {
|
|
350
|
+
runInstall(resolved.packageManager, targetDir);
|
|
351
|
+
runPackageManagerScript(resolved.packageManager, "db:migrate", targetDir);
|
|
352
|
+
runPackageManagerScript(resolved.packageManager, "db:seed", targetDir);
|
|
353
|
+
}
|
|
354
|
+
return {
|
|
355
|
+
appName,
|
|
356
|
+
packageName,
|
|
357
|
+
targetDir,
|
|
358
|
+
packageManager: resolved.packageManager,
|
|
359
|
+
database: resolved.database,
|
|
360
|
+
superadminEmail: resolved.superadminEmail,
|
|
361
|
+
git: resolved.git,
|
|
362
|
+
install: resolved.install,
|
|
363
|
+
dbInitialized: resolved.install
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
function generateIntoDir(targetDir, resolved, meta) {
|
|
158
367
|
ensureDirSync(targetDir);
|
|
159
|
-
copySync(
|
|
160
|
-
overwrite:
|
|
161
|
-
errorOnExist:
|
|
368
|
+
copySync(resolved.templateDir, targetDir, {
|
|
369
|
+
overwrite: true,
|
|
370
|
+
errorOnExist: false,
|
|
162
371
|
filter: (source) => {
|
|
163
|
-
const segments = relative(
|
|
372
|
+
const segments = relative(resolved.templateDir, source).split(sep);
|
|
164
373
|
return !segments.some((segment) => segment === "node_modules" || segment === ".next" || segment === "dist" || segment === ".env.example");
|
|
165
374
|
}
|
|
166
375
|
});
|
|
@@ -168,71 +377,70 @@ export function createProject(options) {
|
|
|
168
377
|
throw new Error(`Template copy failed: package.json not found in ${targetDir}`);
|
|
169
378
|
}
|
|
170
379
|
renderTemplateFiles(targetDir, {
|
|
171
|
-
__APP_NAME__: appName,
|
|
172
|
-
__PACKAGE_NAME__: packageName,
|
|
173
|
-
__DATABASE_PROVIDER__:
|
|
174
|
-
__DATABASE_URL__:
|
|
175
|
-
__REDIS_URL__:
|
|
176
|
-
__JWT_SECRET__:
|
|
177
|
-
__JWT_REFRESH_SECRET__:
|
|
178
|
-
__ADMIN_ORIGIN__:
|
|
179
|
-
__API_PORT__:
|
|
380
|
+
__APP_NAME__: meta.appName,
|
|
381
|
+
__PACKAGE_NAME__: meta.packageName,
|
|
382
|
+
__DATABASE_PROVIDER__: resolved.database,
|
|
383
|
+
__DATABASE_URL__: resolved.databaseUrl,
|
|
384
|
+
__REDIS_URL__: resolved.redisUrl,
|
|
385
|
+
__JWT_SECRET__: resolved.jwtSecret,
|
|
386
|
+
__JWT_REFRESH_SECRET__: resolved.jwtRefreshSecret,
|
|
387
|
+
__ADMIN_ORIGIN__: resolved.adminOrigin,
|
|
388
|
+
__API_PORT__: resolved.apiPort
|
|
180
389
|
});
|
|
181
|
-
//
|
|
182
|
-
//
|
|
183
|
-
//
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
|
|
390
|
+
// The shipped baseline migration + migration_lock.toml are PostgreSQL-specific.
|
|
391
|
+
// For any other provider they would make `prisma migrate deploy` fail, so drop
|
|
392
|
+
// them and let the user create a provider-correct migration via `prisma migrate dev`.
|
|
393
|
+
// The schema itself is also transformed to remove provider-incompatible types
|
|
394
|
+
// (e.g. MySQL has no scalar lists, so `String[]` becomes a `Json` array).
|
|
395
|
+
if (resolved.database !== "postgresql") {
|
|
396
|
+
rmSync(join(targetDir, "prisma", "migrations"), { recursive: true, force: true });
|
|
397
|
+
const schemaPath = join(targetDir, "prisma", "schema.prisma");
|
|
398
|
+
if (existsSync(schemaPath)) {
|
|
399
|
+
const schema = readFileSync(schemaPath, "utf8");
|
|
400
|
+
writeFileSync(schemaPath, renderSchemaForProvider(schema, resolved.database));
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
adaptProjectForPackageManager(targetDir, resolved.packageManager);
|
|
404
|
+
// Git safety: write .gitignore + .env.example (tracked, placeholders only) as
|
|
405
|
+
// part of generation, i.e. before any `git init`.
|
|
406
|
+
writeGitignore(targetDir);
|
|
407
|
+
writeEnvExample(targetDir, resolved.database);
|
|
408
|
+
// Real secrets live only in apps/api/.env (ignored by the .gitignore above).
|
|
409
|
+
const templateApiDir = join(resolved.templateDir, "apps", "api");
|
|
187
410
|
const apiEnvDir = join(targetDir, "apps", "api");
|
|
188
411
|
if (existsSync(templateApiDir)) {
|
|
189
412
|
mkdirSync(apiEnvDir, { recursive: true });
|
|
190
413
|
writeFileSync(join(apiEnvDir, ".env"), [
|
|
191
|
-
`DATABASE_URL=${
|
|
192
|
-
`REDIS_URL=${
|
|
193
|
-
`JWT_SECRET=${
|
|
194
|
-
`JWT_REFRESH_SECRET=${
|
|
195
|
-
`ADMIN_ORIGIN=${
|
|
196
|
-
`API_PORT=${
|
|
197
|
-
`SUPERADMIN_EMAIL=${
|
|
198
|
-
`SUPERADMIN_PASSWORD=${
|
|
414
|
+
`DATABASE_URL=${resolved.databaseUrl}`,
|
|
415
|
+
`REDIS_URL=${resolved.redisUrl}`,
|
|
416
|
+
`JWT_SECRET=${resolved.jwtSecret}`,
|
|
417
|
+
`JWT_REFRESH_SECRET=${resolved.jwtRefreshSecret}`,
|
|
418
|
+
`ADMIN_ORIGIN=${resolved.adminOrigin}`,
|
|
419
|
+
`API_PORT=${resolved.apiPort}`,
|
|
420
|
+
`SUPERADMIN_EMAIL=${resolved.superadminEmail}`,
|
|
421
|
+
`SUPERADMIN_PASSWORD=${resolved.superadminPassword}`
|
|
199
422
|
].join("\n") + "\n");
|
|
200
423
|
}
|
|
201
|
-
if (options.git) {
|
|
202
|
-
const gitResult = spawnSync("git", ["init"], { cwd: targetDir, stdio: "ignore" });
|
|
203
|
-
if (gitResult.status !== 0 || gitResult.error) {
|
|
204
|
-
throw new Error("Failed to initialize git repository.");
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
if (options.install) {
|
|
208
|
-
const installArgs = options.packageManager === "yarn" ? [] : ["install"];
|
|
209
|
-
const installResult = spawnSync(options.packageManager, installArgs, { cwd: targetDir, stdio: "inherit" });
|
|
210
|
-
if (installResult.status !== 0 || installResult.error) {
|
|
211
|
-
throw new Error(`Dependency installation failed. Run "${options.packageManager} ${installArgs.join(" ")}" inside ${targetDir}.`);
|
|
212
|
-
}
|
|
213
|
-
runPackageManagerScript(options.packageManager, "db:migrate", targetDir);
|
|
214
|
-
runPackageManagerScript(options.packageManager, "db:seed", targetDir);
|
|
215
|
-
}
|
|
216
|
-
return {
|
|
217
|
-
appName,
|
|
218
|
-
packageName,
|
|
219
|
-
targetDir,
|
|
220
|
-
packageManager: options.packageManager,
|
|
221
|
-
database: options.database,
|
|
222
|
-
superadminEmail: options.superadminEmail,
|
|
223
|
-
git: options.git,
|
|
224
|
-
install: options.install,
|
|
225
|
-
dbInitialized: options.install
|
|
226
|
-
};
|
|
227
424
|
}
|
|
228
425
|
export function printNextSteps(result) {
|
|
229
426
|
const pm = result.packageManager;
|
|
230
427
|
const installStep = result.install ? "" : `\n ${pm} install\n ${pm} db:migrate\n ${pm} db:seed`;
|
|
231
428
|
const dbStepNote = result.dbInitialized ? "\nDatabase initialized: migrations + seed completed automatically." : "";
|
|
232
|
-
outro(`${pc.green("Project created.")}\n\nNext steps:\n cd ${result.appName}${installStep}\n ${pm} dev${dbStepNote}\n\nAdmin: http://localhost:3000\nAPI: http://localhost:4000\nSwagger: http://localhost:4000/api/docs\nWeb: http://localhost:3001\n\nSuperadmin: ${result.superadminEmail} / <
|
|
429
|
+
outro(`${pc.green("Project created.")}\n\nNext steps:\n cd ${result.appName}${installStep}\n ${pm} dev${dbStepNote}\n\nAdmin: http://localhost:3000\nAPI: http://localhost:4000\nSwagger: http://localhost:4000/api/docs\nWeb: http://localhost:3001\n\nSuperadmin: ${result.superadminEmail} / <the password you entered>`);
|
|
430
|
+
}
|
|
431
|
+
/** Warns where secrets live and that they must never be committed. Never prints secret values. */
|
|
432
|
+
export function printSecurityNotice(result) {
|
|
433
|
+
note([
|
|
434
|
+
`Secrets (DB URL, JWT keys, admin password) were written to ${pc.bold("apps/api/.env")}.`,
|
|
435
|
+
`A ${pc.bold(".gitignore")} was created that excludes ${pc.bold(".env")} files.`,
|
|
436
|
+
`${pc.bold(".env.example")} (placeholders only) is tracked in Git.`,
|
|
437
|
+
pc.yellow("Do NOT commit apps/api/.env or share it. Rotate secrets before production.")
|
|
438
|
+
].join("\n"), "Security");
|
|
233
439
|
}
|
|
234
440
|
export async function createProjectInteractive(options = {}) {
|
|
235
441
|
intro(pc.green("Create OpenAdminJS"));
|
|
442
|
+
// Preflight checks that don't require project files run before anything is written.
|
|
443
|
+
assertSupportedNode();
|
|
236
444
|
const projectName = options.projectName ??
|
|
237
445
|
(await text({
|
|
238
446
|
message: "Project name",
|
|
@@ -247,7 +455,7 @@ export async function createProjectInteractive(options = {}) {
|
|
|
247
455
|
(await select({
|
|
248
456
|
message: "Package manager",
|
|
249
457
|
options: [
|
|
250
|
-
{ value: "pnpm", label: "pnpm" },
|
|
458
|
+
{ value: "pnpm", label: "pnpm (recommended)" },
|
|
251
459
|
{ value: "npm", label: "npm" },
|
|
252
460
|
{ value: "yarn", label: "yarn" }
|
|
253
461
|
],
|
|
@@ -257,13 +465,16 @@ export async function createProjectInteractive(options = {}) {
|
|
|
257
465
|
cancel("Cancelled");
|
|
258
466
|
return undefined;
|
|
259
467
|
}
|
|
468
|
+
if (!isPackageManagerAvailable(packageManager)) {
|
|
469
|
+
throw new Error(`${packageManager} is required but was not found on your PATH.`);
|
|
470
|
+
}
|
|
260
471
|
const database = options.database ??
|
|
261
472
|
(await select({
|
|
262
473
|
message: "Database",
|
|
263
474
|
options: [
|
|
264
475
|
{ value: "postgresql", label: "PostgreSQL" },
|
|
265
476
|
{ value: "mysql", label: "MySQL" },
|
|
266
|
-
{ value: "sqlite", label: "SQLite" }
|
|
477
|
+
{ value: "sqlite", label: "SQLite (local file, zero-setup)" }
|
|
267
478
|
],
|
|
268
479
|
initialValue: "postgresql"
|
|
269
480
|
}));
|
|
@@ -274,16 +485,15 @@ export async function createProjectInteractive(options = {}) {
|
|
|
274
485
|
const superadminEmail = options.superadminEmail ??
|
|
275
486
|
(await text({
|
|
276
487
|
message: "Superadmin email",
|
|
277
|
-
defaultValue:
|
|
278
|
-
placeholder:
|
|
279
|
-
validate(value)
|
|
280
|
-
return /^\S+@\S+\.\S+$/.test(value) ? undefined : "Enter a valid email address.";
|
|
281
|
-
}
|
|
488
|
+
defaultValue: DEFAULT_SUPERADMIN_EMAIL,
|
|
489
|
+
placeholder: DEFAULT_SUPERADMIN_EMAIL,
|
|
490
|
+
validate: (value) => validateSuperadminEmailInput(value)
|
|
282
491
|
}));
|
|
283
492
|
if (isCancel(superadminEmail)) {
|
|
284
493
|
cancel("Cancelled");
|
|
285
494
|
return undefined;
|
|
286
495
|
}
|
|
496
|
+
const resolvedEmail = resolveSuperadminEmail(String(superadminEmail));
|
|
287
497
|
const superadminPassword = options.superadminPassword ??
|
|
288
498
|
(await text({
|
|
289
499
|
message: "Superadmin password",
|
|
@@ -305,7 +515,7 @@ export async function createProjectInteractive(options = {}) {
|
|
|
305
515
|
cancel("Cancelled");
|
|
306
516
|
return undefined;
|
|
307
517
|
}
|
|
308
|
-
let checkedDatabaseUrl = String(selectedDatabaseUrl).trim();
|
|
518
|
+
let checkedDatabaseUrl = String(selectedDatabaseUrl).trim() || databaseUrl(toPackageName(String(projectName)), database);
|
|
309
519
|
while (true) {
|
|
310
520
|
const dbError = await validateDbConnectivity(database, checkedDatabaseUrl);
|
|
311
521
|
if (!dbError)
|
|
@@ -370,26 +580,9 @@ export async function createProjectInteractive(options = {}) {
|
|
|
370
580
|
}
|
|
371
581
|
checkedRedisUrl = String(next).trim();
|
|
372
582
|
}
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
defaultValue: "change-me-to-a-long-random-secret",
|
|
377
|
-
placeholder: "at least 32 chars recommended"
|
|
378
|
-
}));
|
|
379
|
-
if (isCancel(jwtSecret)) {
|
|
380
|
-
cancel("Cancelled");
|
|
381
|
-
return undefined;
|
|
382
|
-
}
|
|
383
|
-
const jwtRefreshSecret = options.jwtRefreshSecret ??
|
|
384
|
-
(await text({
|
|
385
|
-
message: "JWT refresh secret",
|
|
386
|
-
defaultValue: "change-me-too",
|
|
387
|
-
placeholder: "at least 32 chars recommended"
|
|
388
|
-
}));
|
|
389
|
-
if (isCancel(jwtRefreshSecret)) {
|
|
390
|
-
cancel("Cancelled");
|
|
391
|
-
return undefined;
|
|
392
|
-
}
|
|
583
|
+
// JWT secrets are generated with a CSPRNG — never prompted with predictable defaults.
|
|
584
|
+
const jwtSecret = options.jwtSecret ?? generateSecret();
|
|
585
|
+
const jwtRefreshSecret = options.jwtRefreshSecret ?? generateSecret();
|
|
393
586
|
const adminOrigin = options.adminOrigin ?? "http://localhost:3000";
|
|
394
587
|
const apiPort = options.apiPort ?? "4000";
|
|
395
588
|
const git = options.git ?? (await confirm({ message: "Initialize git?", initialValue: true }));
|
|
@@ -403,7 +596,7 @@ export async function createProjectInteractive(options = {}) {
|
|
|
403
596
|
cwd: options.cwd ?? process.cwd(),
|
|
404
597
|
packageManager,
|
|
405
598
|
database,
|
|
406
|
-
superadminEmail:
|
|
599
|
+
superadminEmail: resolvedEmail,
|
|
407
600
|
superadminPassword: String(superadminPassword),
|
|
408
601
|
databaseUrl: checkedDatabaseUrl,
|
|
409
602
|
redisUrl: checkedRedisUrl,
|
|
@@ -413,8 +606,9 @@ export async function createProjectInteractive(options = {}) {
|
|
|
413
606
|
apiPort: String(apiPort),
|
|
414
607
|
git,
|
|
415
608
|
install,
|
|
416
|
-
templateDir: options.templateDir
|
|
609
|
+
templateDir: options.templateDir
|
|
417
610
|
});
|
|
611
|
+
printSecurityNotice(result);
|
|
418
612
|
printNextSteps(result);
|
|
419
613
|
return result;
|
|
420
614
|
}
|