openadminjs 0.1.24 → 0.3.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -81
- package/dist/adapt-package-manager.d.ts +3 -0
- package/dist/adapt-package-manager.js +118 -0
- package/dist/create-project.d.ts +77 -2
- package/dist/create-project.js +685 -224
- package/dist/db-commands.d.ts +20 -0
- package/dist/db-commands.js +75 -0
- package/dist/detect-package-manager.d.ts +8 -0
- package/dist/detect-package-manager.js +37 -0
- package/dist/doctor.d.ts +26 -0
- package/dist/doctor.js +232 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +476 -166
- package/dist/render-schema.d.ts +3 -0
- package/dist/render-schema.js +33 -0
- package/dist/resource-slug.d.ts +1 -0
- package/dist/resource-slug.js +7 -0
- package/dist/runtime-mode.d.ts +16 -0
- package/dist/runtime-mode.js +138 -0
- package/dist/secrets.d.ts +24 -0
- package/dist/secrets.js +93 -0
- package/dist/security.d.ts +13 -0
- package/dist/security.js +168 -0
- package/dist/upgrade.d.ts +10 -0
- package/dist/upgrade.js +133 -0
- package/dist/validate-name.d.ts +33 -0
- package/dist/validate-name.js +206 -0
- package/package.json +39 -11
- package/template/.dockerignore +15 -0
- package/template/.env.production.example +5 -0
- package/template/Dockerfile +12 -0
- package/template/README.md +23 -3
- package/template/apps/admin/app/api/auth/login/route.ts +9 -9
- package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
- package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
- package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
- package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
- package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
- package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
- package/template/apps/admin/app/api-tokens/page.tsx +39 -39
- package/template/apps/admin/app/assistant/page.tsx +11 -0
- package/template/apps/admin/app/dashboard/page.tsx +45 -462
- package/template/apps/admin/app/globals.css +52 -16
- package/template/apps/admin/app/layout.tsx +1 -1
- package/template/apps/admin/app/login/page.tsx +13 -145
- package/template/apps/admin/app/plugins/page.tsx +16 -402
- package/template/apps/admin/app/profile/page.tsx +5 -2
- package/template/apps/admin/app/settings/page.tsx +14 -265
- package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
- package/template/apps/admin/components/app-shell.tsx +25 -373
- package/template/apps/admin/components/auth-guard.tsx +8 -28
- package/template/apps/admin/components/logo.tsx +1 -30
- package/template/apps/admin/components/resource-form.tsx +3 -3
- package/template/apps/admin/components/resource-table.tsx +12 -8
- package/template/apps/admin/lib/api.ts +45 -107
- package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
- package/template/apps/admin/lib/server-api.ts +7 -0
- package/template/apps/admin/lib/tokens.ts +9 -81
- package/template/apps/admin/middleware.ts +9 -50
- package/template/apps/admin/next.config.mjs +4 -0
- package/template/apps/admin/package.json +2 -1
- package/template/apps/admin/public/brand/favicon.svg +4 -1
- package/template/apps/admin/tailwind.config.ts +9 -8
- package/template/apps/api/package.json +13 -6
- package/template/apps/api/src/access/catalog.ts +4 -0
- package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
- package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
- package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
- package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
- package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
- package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
- package/template/apps/api/src/admin/admin.controller.ts +17 -4
- package/template/apps/api/src/admin/admin.module.ts +2 -2
- package/template/apps/api/src/admin/resource-policy.ts +1 -0
- package/template/apps/api/src/admin/resource-query.ts +1 -0
- package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
- package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
- package/template/apps/api/src/auth/auth.controller.ts +4 -2
- package/template/apps/api/src/auth/auth.service.ts +68 -83
- package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
- package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
- package/template/apps/api/src/common/api-exception.filter.ts +1 -0
- package/template/apps/api/src/common/auth.guard.ts +66 -39
- package/template/apps/api/src/common/json-field-codec.ts +138 -0
- package/template/apps/api/src/common/prisma.service.ts +12 -7
- package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
- package/template/apps/api/src/graphql/graphql.module.ts +14 -1
- package/template/apps/api/src/health/health.controller.ts +6 -0
- package/template/apps/api/src/main.ts +11 -2
- package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
- package/template/apps/api/src/resources/commerce.resource.ts +3 -34
- package/template/apps/api/src/resources/operations.resource.ts +1 -0
- package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
- package/template/apps/api/src/store/payment/payment.module.ts +2 -3
- package/template/apps/api/src/store/payment/payment.service.ts +121 -227
- package/template/apps/api/webpack.config.cjs +2 -1
- package/template/apps/web/next.config.mjs +4 -0
- package/template/apps/web/public/brand/favicon.svg +4 -1
- package/template/compose.yaml +56 -0
- package/template/examples/crm-admin/README.md +31 -0
- package/template/examples/crm-admin/package.json +17 -0
- package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
- package/template/examples/crm-admin/src/index.ts +7 -0
- package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
- package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
- package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
- package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
- package/template/examples/crm-admin/tsconfig.json +7 -0
- package/template/package.json +8 -1
- package/template/packages/admin-client/package.json +18 -0
- package/template/packages/admin-client/src/contracts.ts +29 -0
- package/template/packages/admin-client/src/index.ts +2 -0
- package/template/packages/admin-client/src/preferences.ts +57 -0
- package/template/packages/admin-client/tsconfig.json +12 -0
- package/template/packages/auth/package.json +1 -1
- package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
- package/template/packages/brand/src/generate-assets.mjs +17 -186
- package/template/packages/core/package.json +1 -1
- package/template/packages/mail/package.json +1 -1
- package/template/packages/nest/package.json +22 -0
- package/template/packages/nest/src/api-exception.filter.ts +23 -0
- package/template/packages/nest/src/index.ts +3 -0
- package/template/packages/nest/src/resource-policy.ts +64 -0
- package/template/packages/nest/src/resource-query.ts +103 -0
- package/template/packages/nest/tsconfig.json +12 -0
- package/template/packages/notifications/package.json +1 -1
- package/template/packages/payments/package.json +1 -1
- package/template/packages/permissions/package.json +1 -1
- package/template/packages/permissions/src/index.ts +2 -2
- package/template/packages/plugin-sdk/package.json +1 -1
- package/template/packages/plugin-sdk/src/index.ts +2 -2
- package/template/packages/prisma/package.json +21 -0
- package/template/packages/prisma/schema/ai.prisma +36 -0
- package/template/packages/prisma/schema/audit.prisma +13 -0
- package/template/packages/prisma/schema/commerce.prisma +79 -0
- package/template/packages/prisma/schema/content.prisma +27 -0
- package/template/packages/prisma/schema/core.prisma +106 -0
- package/template/packages/prisma/schema/header.prisma +8 -0
- package/template/packages/prisma/schema/jobs.prisma +9 -0
- package/template/packages/prisma/schema/media.prisma +9 -0
- package/template/packages/prisma/schema/modules.json +47 -0
- package/template/packages/prisma/schema/notifications.prisma +9 -0
- package/template/packages/prisma/schema/settings.prisma +8 -0
- package/template/packages/prisma/schema/tokens.prisma +10 -0
- package/template/packages/prisma/src/index.d.ts +12 -0
- package/template/packages/prisma/src/index.mjs +138 -0
- package/template/packages/queue/package.json +1 -1
- package/template/packages/resource/package.json +1 -1
- package/template/packages/resource/src/index.ts +1 -0
- package/template/packages/storage/package.json +1 -1
- package/template/packages/storage/src/index.ts +37 -0
- package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -0
- package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
- package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
- package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
- package/template/prisma/schema.prisma +82 -54
- package/template/prisma/seed.ts +14 -38
- package/template/runtime-versions.json +15 -0
- package/template/scripts/db-init.mjs +33 -0
- package/template/scripts/install-crm.mjs +50 -0
- package/template/scripts/migrate-existing.mjs +65 -0
- package/template/scripts/schema.mjs +48 -0
- package/template/tsconfig.base.json +23 -5
- package/LICENSE +0 -21
- package/dist/create-project.test.d.ts +0 -1
- package/dist/create-project.test.js +0 -99
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -7
- package/dist/resource-slug.test.d.ts +0 -1
- package/dist/resource-slug.test.js +0 -9
- package/template/apps/admin/.storybook/main.ts +0 -12
- package/template/apps/admin/.storybook/preview.ts +0 -10
- package/template/apps/admin/app/login/page.test.tsx +0 -18
- package/template/apps/admin/components/auth-guard.test.tsx +0 -55
- package/template/apps/admin/components/logo.stories.tsx +0 -24
- package/template/apps/admin/lib/api.test.ts +0 -118
- package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
- package/template/apps/admin/vitest.config.ts +0 -7
- package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
- package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
- package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
- package/template/apps/api/src/app.module.test.ts +0 -12
- package/template/apps/api/src/auth/auth.service.test.ts +0 -78
- package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
- package/template/apps/api/src/common/auth.guard.test.ts +0 -62
- package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
- package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
- package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
- package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
- package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
- package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
- package/template/apps/api/src/queue/queue.service.test.ts +0 -33
- package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
- package/template/apps/api/vitest.config.ts +0 -21
- package/template/apps/web/lib/seo.test.ts +0 -41
- package/template/apps/web/vitest.config.ts +0 -19
- package/template/packages/auth/src/index.test.ts +0 -10
- package/template/packages/brand/src/index.test.ts +0 -9
- package/template/packages/core/src/index.test.ts +0 -27
- package/template/packages/core/vitest.config.ts +0 -9
- package/template/packages/mail/src/index.test.ts +0 -23
- package/template/packages/notifications/src/index.test.ts +0 -9
- package/template/packages/permissions/src/blueprints.test.ts +0 -62
- package/template/packages/permissions/src/index.test.ts +0 -34
- package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
- package/template/packages/plugin-sdk/vitest.config.ts +0 -5
- package/template/packages/queue/src/index.test.ts +0 -12
- package/template/packages/resource/src/index.test.ts +0 -196
- package/template/packages/storage/src/index.test.ts +0 -10
package/dist/create-project.js
CHANGED
|
@@ -1,15 +1,60 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { migrateRuntime } from "./runtime-mode.js";
|
|
2
|
+
import { writeManagedBaseline } from "./upgrade.js";
|
|
3
|
+
import { accessSync, constants as fsConstants, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync } from "node:fs";
|
|
2
4
|
import net from "node:net";
|
|
3
5
|
import { dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
4
6
|
import { spawnSync } from "node:child_process";
|
|
5
7
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { cancel, confirm, intro, isCancel, outro, select, text } from "@clack/prompts";
|
|
8
|
+
import { cancel, confirm, intro, isCancel, note, outro, password, select, text } from "@clack/prompts";
|
|
7
9
|
import fsExtra from "fs-extra";
|
|
8
10
|
import pc from "picocolors";
|
|
11
|
+
import { adaptProjectForPackageManager } from "./adapt-package-manager.js";
|
|
12
|
+
import { generateSecret, inspectPassword } from "./secrets.js";
|
|
13
|
+
import { renderSchemaForProvider } from "./render-schema.js";
|
|
9
14
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
10
15
|
const { copySync, ensureDirSync, readFileSync, writeFileSync } = fsExtra;
|
|
11
16
|
const BINARY_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".eot"]);
|
|
17
|
+
/** Minimum supported Node.js major version (kept in sync with package.json engines). */
|
|
18
|
+
export const MIN_NODE_MAJOR = 20;
|
|
12
19
|
const placeholderPattern = /__APP_NAME__|__PACKAGE_NAME__|__DATABASE_URL__|__DATABASE_PROVIDER__|__REDIS_URL__|__JWT_SECRET__|__JWT_REFRESH_SECRET__|__ADMIN_ORIGIN__|__API_PORT__/g;
|
|
20
|
+
/**
|
|
21
|
+
* Root .gitignore written into every generated project. Written BEFORE `git init`
|
|
22
|
+
* so a subsequent `git add .` can never stage `.env` files or build output.
|
|
23
|
+
*/
|
|
24
|
+
const GITIGNORE_CONTENTS = `# dependencies
|
|
25
|
+
node_modules
|
|
26
|
+
.pnpm-store
|
|
27
|
+
|
|
28
|
+
# build output
|
|
29
|
+
.next
|
|
30
|
+
dist
|
|
31
|
+
build
|
|
32
|
+
out
|
|
33
|
+
coverage
|
|
34
|
+
*.tsbuildinfo
|
|
35
|
+
.turbo
|
|
36
|
+
|
|
37
|
+
# environment / secrets
|
|
38
|
+
.env
|
|
39
|
+
.env.*
|
|
40
|
+
!.env.example
|
|
41
|
+
.openadminjs-runtime-backup/
|
|
42
|
+
prisma/schema.prisma.before-compose
|
|
43
|
+
|
|
44
|
+
# logs
|
|
45
|
+
*.log
|
|
46
|
+
|
|
47
|
+
# local databases
|
|
48
|
+
*.db
|
|
49
|
+
*.db-journal
|
|
50
|
+
*.sqlite
|
|
51
|
+
*.sqlite3
|
|
52
|
+
|
|
53
|
+
# OS / editor
|
|
54
|
+
.DS_Store
|
|
55
|
+
.idea
|
|
56
|
+
.vscode
|
|
57
|
+
`;
|
|
13
58
|
export function toPackageName(input) {
|
|
14
59
|
return input
|
|
15
60
|
.trim()
|
|
@@ -20,6 +65,39 @@ export function toPackageName(input) {
|
|
|
20
65
|
export function defaultTemplateDir() {
|
|
21
66
|
return resolve(__dirname, "../template");
|
|
22
67
|
}
|
|
68
|
+
/** Returns the current Node.js major version. */
|
|
69
|
+
export function currentNodeMajor() {
|
|
70
|
+
return Number(process.versions.node.split(".")[0]);
|
|
71
|
+
}
|
|
72
|
+
/** Throws if the running Node.js is older than the supported minimum. */
|
|
73
|
+
export function assertSupportedNode() {
|
|
74
|
+
const major = currentNodeMajor();
|
|
75
|
+
if (Number.isFinite(major) && major < MIN_NODE_MAJOR) {
|
|
76
|
+
throw new Error(`Node.js ${MIN_NODE_MAJOR}+ is required (found ${process.versions.node}). Please upgrade Node.js.`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Returns true when the given package manager is on PATH. */
|
|
80
|
+
export function isPackageManagerAvailable(packageManager) {
|
|
81
|
+
const result = spawnSync(packageManager, ["--version"], { stdio: "ignore" });
|
|
82
|
+
return !result.error && result.status === 0;
|
|
83
|
+
}
|
|
84
|
+
/** Throws with an actionable message when pnpm is not installed. */
|
|
85
|
+
export function assertPnpmAvailable() {
|
|
86
|
+
if (!isPackageManagerAvailable("pnpm")) {
|
|
87
|
+
throw new Error("pnpm is required but was not found on your PATH.\n" +
|
|
88
|
+
"Install it with one of:\n" +
|
|
89
|
+
" corepack enable && corepack prepare pnpm@latest --activate\n" +
|
|
90
|
+
" npm install -g pnpm");
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function assertWritableParent(cwd) {
|
|
94
|
+
try {
|
|
95
|
+
accessSync(cwd, fsConstants.W_OK);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new Error(`No write permission for ${cwd}. Choose a writable directory.`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
23
101
|
function parseUrlHostPort(input) {
|
|
24
102
|
try {
|
|
25
103
|
const url = new URL(input);
|
|
@@ -35,7 +113,7 @@ function parseUrlHostPort(input) {
|
|
|
35
113
|
}
|
|
36
114
|
}
|
|
37
115
|
async function checkTcpConnection(host, port, timeoutMs = 1500) {
|
|
38
|
-
await new Promise((
|
|
116
|
+
await new Promise((resolvePromise, reject) => {
|
|
39
117
|
const socket = net.createConnection({ host, port });
|
|
40
118
|
const onError = (err) => {
|
|
41
119
|
socket.destroy();
|
|
@@ -45,7 +123,7 @@ async function checkTcpConnection(host, port, timeoutMs = 1500) {
|
|
|
45
123
|
socket.once("error", onError);
|
|
46
124
|
socket.once("connect", () => {
|
|
47
125
|
socket.end();
|
|
48
|
-
|
|
126
|
+
resolvePromise();
|
|
49
127
|
});
|
|
50
128
|
});
|
|
51
129
|
}
|
|
@@ -54,7 +132,7 @@ async function pingRedis(urlInput, timeoutMs = 1500) {
|
|
|
54
132
|
if (!parsed)
|
|
55
133
|
throw new Error("Invalid Redis URL");
|
|
56
134
|
const port = parsed.port || 6379;
|
|
57
|
-
await new Promise((
|
|
135
|
+
await new Promise((resolvePromise, reject) => {
|
|
58
136
|
const socket = net.createConnection({ host: parsed.host, port });
|
|
59
137
|
const onError = (err) => {
|
|
60
138
|
socket.destroy();
|
|
@@ -70,7 +148,7 @@ async function pingRedis(urlInput, timeoutMs = 1500) {
|
|
|
70
148
|
buffer += chunk.toString("utf8");
|
|
71
149
|
if (buffer.includes("+PONG")) {
|
|
72
150
|
socket.end();
|
|
73
|
-
|
|
151
|
+
resolvePromise();
|
|
74
152
|
}
|
|
75
153
|
if (buffer.includes("-ERR")) {
|
|
76
154
|
onError(new Error("redis error"));
|
|
@@ -79,8 +157,10 @@ async function pingRedis(urlInput, timeoutMs = 1500) {
|
|
|
79
157
|
});
|
|
80
158
|
}
|
|
81
159
|
async function validateDbConnectivity(database, databaseUrlInput) {
|
|
82
|
-
|
|
83
|
-
|
|
160
|
+
// SQLite is a local file — there is no server to reach.
|
|
161
|
+
if (database === "sqlite") {
|
|
162
|
+
return /^file:/.test(databaseUrlInput.trim()) ? undefined : 'SQLite DATABASE_URL must start with "file:".';
|
|
163
|
+
}
|
|
84
164
|
const parsed = parseUrlHostPort(databaseUrlInput);
|
|
85
165
|
if (!parsed)
|
|
86
166
|
return "Invalid database URL.";
|
|
@@ -106,14 +186,53 @@ async function validateRedisConnectivity(redisUrlInput) {
|
|
|
106
186
|
return `Cannot connect to Redis at ${parsed.host}:${port}.`;
|
|
107
187
|
}
|
|
108
188
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
189
|
+
export const DEFAULT_SUPERADMIN_EMAIL = "admin@localhost.dev";
|
|
190
|
+
/** Resolves the final email, applying the default when the user pressed Enter. */
|
|
191
|
+
export function resolveSuperadminEmail(value, fallback = DEFAULT_SUPERADMIN_EMAIL) {
|
|
192
|
+
return value.trim() || fallback;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Validates the superadmin email against the FINAL value (after default
|
|
196
|
+
* resolution), so pressing Enter to accept the default is always valid.
|
|
197
|
+
*/
|
|
198
|
+
export function validateSuperadminEmailInput(value, fallback = DEFAULT_SUPERADMIN_EMAIL) {
|
|
199
|
+
const finalValue = resolveSuperadminEmail(value, fallback);
|
|
200
|
+
return /^\S+@\S+\.\S+$/.test(finalValue) ? undefined : "Enter a valid email address.";
|
|
201
|
+
}
|
|
202
|
+
export const DEFAULT_REDIS_URL = "redis://localhost:6379";
|
|
203
|
+
export const PACKAGE_MANAGERS = ["pnpm", "npm", "yarn"];
|
|
204
|
+
/** Returns the first package manager that is installed on PATH, or undefined. */
|
|
205
|
+
export function firstAvailablePackageManager(preference = PACKAGE_MANAGERS) {
|
|
206
|
+
return preference.find((pm) => isPackageManagerAvailable(pm));
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Validates a Redis URL. An empty value is VALID — it disables background job
|
|
210
|
+
* queues. A non-empty value must be a parseable redis:// (or rediss://) URL so
|
|
211
|
+
* pressing Enter on the shown default is always accepted.
|
|
212
|
+
*/
|
|
213
|
+
export function validateRedisUrlInput(value) {
|
|
214
|
+
const v = value.trim();
|
|
215
|
+
if (v === "")
|
|
216
|
+
return undefined;
|
|
217
|
+
try {
|
|
218
|
+
const url = new URL(v);
|
|
219
|
+
if (url.protocol !== "redis:" && url.protocol !== "rediss:") {
|
|
220
|
+
return "Redis URL must start with redis:// or rediss:// (or be blank to disable queues).";
|
|
221
|
+
}
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return "Enter a valid Redis URL (or leave blank to disable queues).";
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
export function databaseUrl(packageName, database) {
|
|
229
|
+
if (database === "sqlite") {
|
|
230
|
+
return "file:./dev.db";
|
|
112
231
|
}
|
|
113
232
|
if (database === "mysql") {
|
|
114
233
|
return `mysql://openadminjs:openadminjs@localhost:3306/${packageName}`;
|
|
115
234
|
}
|
|
116
|
-
return
|
|
235
|
+
return `postgresql://openadminjs:openadminjs@localhost:5432/${packageName}?schema=public`;
|
|
117
236
|
}
|
|
118
237
|
function renderFile(file, replacements) {
|
|
119
238
|
if (BINARY_EXTENSIONS.has(extname(file).toLowerCase()))
|
|
@@ -139,28 +258,209 @@ function renderTemplateFiles(targetDir, replacements) {
|
|
|
139
258
|
}
|
|
140
259
|
}
|
|
141
260
|
function runPackageManagerScript(packageManager, script, cwd) {
|
|
142
|
-
const command = packageManager === "npm" ? "npm" : packageManager;
|
|
143
261
|
const args = packageManager === "npm" ? ["run", script] : [script];
|
|
144
|
-
const result = spawnSync(
|
|
262
|
+
const result = spawnSync(packageManager, args, { cwd, stdio: "inherit" });
|
|
263
|
+
if (result.status !== 0 || result.error) {
|
|
264
|
+
const display = packageManager === "npm" ? `npm run ${script}` : `${packageManager} ${script}`;
|
|
265
|
+
throw new Error(`Failed to run "${display}" in ${cwd}.`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/** Applies schema to the database after install — non-interactive and provider-aware. */
|
|
269
|
+
function runDatabaseSetup(packageManager, database, cwd) {
|
|
270
|
+
const schemaFlag = ["--schema", "../../prisma/schema.prisma"];
|
|
271
|
+
const prismaArgs = database === "postgresql"
|
|
272
|
+
? ["migrate", "deploy", ...schemaFlag]
|
|
273
|
+
: ["db", "push", ...schemaFlag];
|
|
274
|
+
const label = database === "postgresql" ? "prisma migrate deploy" : "prisma db push";
|
|
275
|
+
if (packageManager === "npm") {
|
|
276
|
+
const result = spawnSync("npm", ["exec", "prisma", ...prismaArgs], { cwd: join(cwd, "apps", "api"), stdio: "inherit" });
|
|
277
|
+
if (result.status !== 0 || result.error) {
|
|
278
|
+
throw new Error(`Failed to run "${label}" in ${cwd}/apps/api.\n` +
|
|
279
|
+
"If Prisma engine binaries could not download, check your network/proxy and retry.\n" +
|
|
280
|
+
`Resume with: cd <project> && npm exec prisma ${prismaArgs.join(" ")} (from apps/api).`);
|
|
281
|
+
}
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
const filterArgs = packageManager === "pnpm"
|
|
285
|
+
? ["--filter", "@openadminjs/api", "exec", "prisma", ...prismaArgs]
|
|
286
|
+
: ["workspace", "@openadminjs/api", "exec", "prisma", ...prismaArgs];
|
|
287
|
+
const result = spawnSync(packageManager, filterArgs, { cwd, stdio: "inherit" });
|
|
145
288
|
if (result.status !== 0 || result.error) {
|
|
146
|
-
|
|
147
|
-
|
|
289
|
+
throw new Error(`Failed to run "${label}" via ${packageManager}.\n` +
|
|
290
|
+
"If Prisma engine binaries could not download, check your network/proxy and retry.");
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
function runInstall(packageManager, cwd) {
|
|
294
|
+
const args = packageManager === "yarn" ? [] : ["install"];
|
|
295
|
+
const result = spawnSync(packageManager, args, { cwd, stdio: "inherit" });
|
|
296
|
+
if (result.status !== 0 || result.error) {
|
|
297
|
+
throw new Error(`Dependency installation failed. Run "${packageManager} install" inside ${cwd}.`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** Writes the root .gitignore. Must run before `git init`. */
|
|
301
|
+
function writeGitignore(targetDir) {
|
|
302
|
+
writeFileSync(join(targetDir, ".gitignore"), GITIGNORE_CONTENTS);
|
|
303
|
+
}
|
|
304
|
+
/** Writes a root .env.example with variable names and safe placeholders only. */
|
|
305
|
+
function writeEnvExample(targetDir, database) {
|
|
306
|
+
const dbUrl = database === "sqlite"
|
|
307
|
+
? "file:./dev.db"
|
|
308
|
+
: database === "mysql"
|
|
309
|
+
? "mysql://user:password@localhost:3306/openadminjs"
|
|
310
|
+
: "postgresql://user:password@localhost:5432/openadminjs?schema=public";
|
|
311
|
+
const lines = [
|
|
312
|
+
"# Copy this file to apps/api/.env and fill in real values.",
|
|
313
|
+
"# NEVER commit the real .env — it is ignored by .gitignore.",
|
|
314
|
+
`DATABASE_URL=${dbUrl}`,
|
|
315
|
+
"# REDIS_URL is optional. Leave it blank to disable background job queues.",
|
|
316
|
+
"REDIS_URL=redis://localhost:6379",
|
|
317
|
+
"# Generate strong secrets, e.g. `node -e \"console.log(require('crypto').randomBytes(48).toString('base64url'))\"`",
|
|
318
|
+
"JWT_SECRET=replace-with-a-long-random-secret",
|
|
319
|
+
"JWT_REFRESH_SECRET=replace-with-a-different-long-random-secret",
|
|
320
|
+
"ADMIN_ORIGIN=http://localhost:3000",
|
|
321
|
+
"API_PORT=4000",
|
|
322
|
+
"SUPERADMIN_EMAIL=admin@localhost.dev",
|
|
323
|
+
"SUPERADMIN_PASSWORD=replace-with-a-strong-password"
|
|
324
|
+
];
|
|
325
|
+
writeFileSync(join(targetDir, ".env.example"), lines.join("\n") + "\n");
|
|
326
|
+
}
|
|
327
|
+
function resolveCreateProjectOptions(options) {
|
|
328
|
+
if (options.packageManager && !["pnpm", "npm", "yarn"].includes(options.packageManager)) {
|
|
329
|
+
throw new Error('packageManager must be "pnpm", "npm", or "yarn".');
|
|
330
|
+
}
|
|
331
|
+
if (options.database && !["postgresql", "mysql", "sqlite"].includes(options.database)) {
|
|
332
|
+
throw new Error('database must be "postgresql", "mysql", or "sqlite".');
|
|
333
|
+
}
|
|
334
|
+
// Redis is optional: an empty REDIS_URL disables background job queues, which
|
|
335
|
+
// the generated API handles gracefully at runtime.
|
|
336
|
+
const redisUrl = options.skipRedis ? "" : (options.redisUrl ?? "");
|
|
337
|
+
const missing = [];
|
|
338
|
+
if (!options.database)
|
|
339
|
+
missing.push("database");
|
|
340
|
+
if (!options.superadminEmail)
|
|
341
|
+
missing.push("superadminEmail");
|
|
342
|
+
if (!options.superadminPassword)
|
|
343
|
+
missing.push("superadminPassword");
|
|
344
|
+
if (!options.databaseUrl)
|
|
345
|
+
missing.push("databaseUrl");
|
|
346
|
+
if (!options.jwtSecret)
|
|
347
|
+
missing.push("jwtSecret");
|
|
348
|
+
if (!options.jwtRefreshSecret)
|
|
349
|
+
missing.push("jwtRefreshSecret");
|
|
350
|
+
if (!options.adminOrigin)
|
|
351
|
+
missing.push("adminOrigin");
|
|
352
|
+
if (!options.apiPort)
|
|
353
|
+
missing.push("apiPort");
|
|
354
|
+
if (missing.length) {
|
|
355
|
+
throw new Error(`createProject() missing required option(s): ${missing.join(", ")}`);
|
|
148
356
|
}
|
|
357
|
+
return {
|
|
358
|
+
projectName: options.projectName,
|
|
359
|
+
cwd: options.cwd ?? process.cwd(),
|
|
360
|
+
packageManager: options.packageManager ?? "pnpm",
|
|
361
|
+
database: options.database,
|
|
362
|
+
superadminEmail: options.superadminEmail,
|
|
363
|
+
superadminPassword: options.superadminPassword,
|
|
364
|
+
databaseUrl: options.databaseUrl,
|
|
365
|
+
redisUrl,
|
|
366
|
+
skipRedis: options.skipRedis ?? redisUrl.trim() === "",
|
|
367
|
+
jwtSecret: options.jwtSecret,
|
|
368
|
+
jwtRefreshSecret: options.jwtRefreshSecret,
|
|
369
|
+
adminOrigin: options.adminOrigin,
|
|
370
|
+
apiPort: options.apiPort,
|
|
371
|
+
git: options.git ?? false,
|
|
372
|
+
install: options.install ?? false,
|
|
373
|
+
nonInteractive: options.nonInteractive ?? false,
|
|
374
|
+
runtimeMode: options.runtimeMode ?? "source",
|
|
375
|
+
templateDir: options.templateDir ?? defaultTemplateDir()
|
|
376
|
+
};
|
|
149
377
|
}
|
|
378
|
+
/**
|
|
379
|
+
* Generates the scaffold into a sibling staging directory and atomically renames
|
|
380
|
+
* it into place only after generation succeeds. On failure the staging directory
|
|
381
|
+
* is removed and an existing target directory is never touched.
|
|
382
|
+
*/
|
|
150
383
|
export function createProject(options) {
|
|
151
|
-
const
|
|
384
|
+
const resolved = resolveCreateProjectOptions(options);
|
|
385
|
+
const appName = resolved.projectName;
|
|
152
386
|
const packageName = toPackageName(appName);
|
|
153
387
|
if (!packageName)
|
|
154
388
|
throw new Error("Project name must contain at least one letter or number.");
|
|
155
|
-
const targetDir = resolve(
|
|
389
|
+
const targetDir = resolve(resolved.cwd, appName);
|
|
156
390
|
if (existsSync(targetDir))
|
|
157
391
|
throw new Error(`${targetDir} already exists.`);
|
|
392
|
+
assertWritableParent(resolved.cwd);
|
|
393
|
+
const stagingDir = mkdtempSync(`${targetDir}.tmp-`);
|
|
394
|
+
try {
|
|
395
|
+
generateIntoDir(stagingDir, resolved, { appName, packageName });
|
|
396
|
+
renameSync(stagingDir, targetDir);
|
|
397
|
+
}
|
|
398
|
+
catch (error) {
|
|
399
|
+
rmSync(stagingDir, { recursive: true, force: true });
|
|
400
|
+
throw error;
|
|
401
|
+
}
|
|
402
|
+
// git init + install happen in the final directory (post-atomic-rename).
|
|
403
|
+
if (resolved.git) {
|
|
404
|
+
const gitResult = spawnSync("git", ["init"], { cwd: targetDir, stdio: "ignore" });
|
|
405
|
+
if (gitResult.status !== 0 || gitResult.error) {
|
|
406
|
+
throw new Error("Failed to initialize git repository.");
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
let dbInitialized = false;
|
|
410
|
+
if (resolved.install) {
|
|
411
|
+
// The scaffold is fully written at this point. If install / db setup fails
|
|
412
|
+
// we keep the project directory and surface an exact resume command rather
|
|
413
|
+
// than deleting the user's freshly generated files.
|
|
414
|
+
try {
|
|
415
|
+
runInstall(resolved.packageManager, targetDir);
|
|
416
|
+
runDatabaseSetup(resolved.packageManager, resolved.database, targetDir);
|
|
417
|
+
runPackageManagerScript(resolved.packageManager, "db:seed", targetDir);
|
|
418
|
+
dbInitialized = true;
|
|
419
|
+
}
|
|
420
|
+
catch (error) {
|
|
421
|
+
throw new SetupIncompleteError(error instanceof Error ? error.message : "Setup failed after the project was created.", { targetDir, appName, packageManager: resolved.packageManager });
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return {
|
|
425
|
+
appName,
|
|
426
|
+
packageName,
|
|
427
|
+
targetDir,
|
|
428
|
+
packageManager: resolved.packageManager,
|
|
429
|
+
database: resolved.database,
|
|
430
|
+
superadminEmail: resolved.superadminEmail,
|
|
431
|
+
git: resolved.git,
|
|
432
|
+
install: resolved.install,
|
|
433
|
+
dbInitialized,
|
|
434
|
+
redisEnabled: resolved.redisUrl.trim() !== "",
|
|
435
|
+
passwordGenerated: false
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Thrown when the scaffold was generated successfully but a later step
|
|
440
|
+
* (install, migrate, seed) failed. Carries the exact command to resume so the
|
|
441
|
+
* user never has to guess, and signals that the directory was intentionally
|
|
442
|
+
* preserved (never auto-deleted).
|
|
443
|
+
*/
|
|
444
|
+
export class SetupIncompleteError extends Error {
|
|
445
|
+
targetDir;
|
|
446
|
+
resumeCommand;
|
|
447
|
+
constructor(message, meta) {
|
|
448
|
+
const pm = meta.packageManager;
|
|
449
|
+
const install = pm === "yarn" ? "yarn" : `${pm} install`;
|
|
450
|
+
const resume = `cd ${meta.appName} && ${install} && ${pm} run db:migrate && ${pm} run db:seed`;
|
|
451
|
+
super(`${message}\n\nThe project was created at ${meta.targetDir} and left in place.\nResume setup with:\n ${resume}`);
|
|
452
|
+
this.name = "SetupIncompleteError";
|
|
453
|
+
this.targetDir = meta.targetDir;
|
|
454
|
+
this.resumeCommand = resume;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
function generateIntoDir(targetDir, resolved, meta) {
|
|
158
458
|
ensureDirSync(targetDir);
|
|
159
|
-
copySync(
|
|
160
|
-
overwrite:
|
|
161
|
-
errorOnExist:
|
|
459
|
+
copySync(resolved.templateDir, targetDir, {
|
|
460
|
+
overwrite: true,
|
|
461
|
+
errorOnExist: false,
|
|
162
462
|
filter: (source) => {
|
|
163
|
-
const segments = relative(
|
|
463
|
+
const segments = relative(resolved.templateDir, source).split(sep);
|
|
164
464
|
return !segments.some((segment) => segment === "node_modules" || segment === ".next" || segment === "dist" || segment === ".env.example");
|
|
165
465
|
}
|
|
166
466
|
});
|
|
@@ -168,234 +468,340 @@ export function createProject(options) {
|
|
|
168
468
|
throw new Error(`Template copy failed: package.json not found in ${targetDir}`);
|
|
169
469
|
}
|
|
170
470
|
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__:
|
|
471
|
+
__APP_NAME__: meta.appName,
|
|
472
|
+
__PACKAGE_NAME__: meta.packageName,
|
|
473
|
+
__DATABASE_PROVIDER__: resolved.database,
|
|
474
|
+
__DATABASE_URL__: resolved.databaseUrl,
|
|
475
|
+
__REDIS_URL__: resolved.redisUrl,
|
|
476
|
+
__JWT_SECRET__: resolved.jwtSecret,
|
|
477
|
+
__JWT_REFRESH_SECRET__: resolved.jwtRefreshSecret,
|
|
478
|
+
__ADMIN_ORIGIN__: resolved.adminOrigin,
|
|
479
|
+
__API_PORT__: resolved.apiPort
|
|
180
480
|
});
|
|
181
|
-
//
|
|
182
|
-
//
|
|
183
|
-
//
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
|
|
481
|
+
// The shipped baseline migration + migration_lock.toml are PostgreSQL-specific.
|
|
482
|
+
// For any other provider they would make `prisma migrate deploy` fail, so drop
|
|
483
|
+
// them and let the user create a provider-correct migration via `prisma migrate dev`.
|
|
484
|
+
// The schema itself is also transformed to remove provider-incompatible types
|
|
485
|
+
// (e.g. MySQL has no scalar lists, so `String[]` becomes a `Json` array).
|
|
486
|
+
if (resolved.database !== "postgresql") {
|
|
487
|
+
rmSync(join(targetDir, "prisma", "migrations"), { recursive: true, force: true });
|
|
488
|
+
const schemaPath = join(targetDir, "prisma", "schema.prisma");
|
|
489
|
+
if (existsSync(schemaPath)) {
|
|
490
|
+
const schema = readFileSync(schemaPath, "utf8");
|
|
491
|
+
writeFileSync(schemaPath, renderSchemaForProvider(schema, resolved.database));
|
|
492
|
+
}
|
|
493
|
+
// Non-PostgreSQL development profiles do not ship provider-specific migration history.
|
|
494
|
+
// Bootstrap is non-interactive and must never accept data loss automatically.
|
|
495
|
+
const apiPackagePath = join(targetDir, "apps", "api", "package.json");
|
|
496
|
+
if (existsSync(apiPackagePath)) {
|
|
497
|
+
const apiPackage = JSON.parse(readFileSync(apiPackagePath, "utf8"));
|
|
498
|
+
apiPackage.scripts["db:migrate"] = "prisma db push --schema ../../prisma/schema.prisma";
|
|
499
|
+
// Production deploy requires the operator to supply provider-correct reviewed migrations.
|
|
500
|
+
writeFileSync(apiPackagePath, JSON.stringify(apiPackage, null, 2) + "\n");
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
adaptProjectForPackageManager(targetDir, resolved.packageManager);
|
|
504
|
+
writeManagedBaseline(targetDir);
|
|
505
|
+
if (resolved.runtimeMode === "registry")
|
|
506
|
+
migrateRuntime(targetDir, resolved.templateDir, { apply: true, initial: true });
|
|
507
|
+
// Git safety: write .gitignore + .env.example (tracked, placeholders only) as
|
|
508
|
+
// part of generation, i.e. before any `git init`.
|
|
509
|
+
writeGitignore(targetDir);
|
|
510
|
+
writeEnvExample(targetDir, resolved.database);
|
|
511
|
+
// Real secrets live only in apps/api/.env (ignored by the .gitignore above).
|
|
512
|
+
const templateApiDir = join(resolved.templateDir, "apps", "api");
|
|
187
513
|
const apiEnvDir = join(targetDir, "apps", "api");
|
|
188
514
|
if (existsSync(templateApiDir)) {
|
|
189
515
|
mkdirSync(apiEnvDir, { recursive: true });
|
|
516
|
+
const redisLine = resolved.redisUrl.trim() === ""
|
|
517
|
+
? "# REDIS_URL is unset — background job queues are disabled.\n# Set it (e.g. redis://localhost:6379) to enable BullMQ queues.\nREDIS_URL="
|
|
518
|
+
: `REDIS_URL=${resolved.redisUrl}`;
|
|
190
519
|
writeFileSync(join(apiEnvDir, ".env"), [
|
|
191
|
-
`DATABASE_URL=${
|
|
192
|
-
|
|
193
|
-
`JWT_SECRET=${
|
|
194
|
-
`JWT_REFRESH_SECRET=${
|
|
195
|
-
`ADMIN_ORIGIN=${
|
|
196
|
-
`API_PORT=${
|
|
197
|
-
`SUPERADMIN_EMAIL=${
|
|
198
|
-
`SUPERADMIN_PASSWORD=${
|
|
520
|
+
`DATABASE_URL=${resolved.databaseUrl}`,
|
|
521
|
+
redisLine,
|
|
522
|
+
`JWT_SECRET=${resolved.jwtSecret}`,
|
|
523
|
+
`JWT_REFRESH_SECRET=${resolved.jwtRefreshSecret}`,
|
|
524
|
+
`ADMIN_ORIGIN=${resolved.adminOrigin}`,
|
|
525
|
+
`API_PORT=${resolved.apiPort}`,
|
|
526
|
+
`SUPERADMIN_EMAIL=${resolved.superadminEmail}`,
|
|
527
|
+
`SUPERADMIN_PASSWORD=${resolved.superadminPassword}`
|
|
199
528
|
].join("\n") + "\n");
|
|
200
529
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
530
|
+
}
|
|
531
|
+
/** Returns the shell form to run a root script with the given package manager. */
|
|
532
|
+
function pmRun(pm, script) {
|
|
533
|
+
if (pm === "yarn")
|
|
534
|
+
return `yarn ${script}`;
|
|
535
|
+
if (pm === "npm")
|
|
536
|
+
return `npm run ${script}`;
|
|
537
|
+
return `pnpm ${script}`;
|
|
538
|
+
}
|
|
539
|
+
export function printNextSteps(result) {
|
|
540
|
+
const pm = result.packageManager;
|
|
541
|
+
const install = pm === "yarn" ? "yarn" : `${pm} install`;
|
|
542
|
+
const installStep = result.install
|
|
543
|
+
? ""
|
|
544
|
+
: `\n ${install}\n ${pmRun(pm, "db:migrate")}\n ${pmRun(pm, "db:seed")}`;
|
|
545
|
+
const dbStepNote = result.dbInitialized
|
|
546
|
+
? "\nDatabase initialized: migrations + seed completed automatically."
|
|
547
|
+
: "";
|
|
548
|
+
// `dev` starts ONLY the admin UI and the API (see root "dev" script). The
|
|
549
|
+
// public web app is optional and started separately, so we do not advertise
|
|
550
|
+
// a URL the default command never serves.
|
|
551
|
+
const password = result.passwordGenerated
|
|
552
|
+
? "a generated password (see apps/api/.env)"
|
|
553
|
+
: "<the password you entered>";
|
|
554
|
+
const webNote = `\n\nOptional public web app (not started by "${pmRun(pm, "dev")}"):\n ${pm === "yarn" ? "yarn workspace @openadminjs/web dev" : pm === "npm" ? "npm run dev --workspace=@openadminjs/web" : "pnpm --filter @openadminjs/web dev"} → http://localhost:3001`;
|
|
555
|
+
const redisNote = result.redisEnabled
|
|
556
|
+
? ""
|
|
557
|
+
: "\n\nBackground job queues are disabled (no REDIS_URL). Set REDIS_URL in apps/api/.env to enable them.";
|
|
558
|
+
outro(`${pc.green("Project created.")}\n\nNext steps:\n cd ${result.appName}${installStep}\n ${pmRun(pm, "dev")}${dbStepNote}\n\nAdmin: http://localhost:3000\nAPI: http://localhost:4000\nSwagger: http://localhost:4000/api/docs${webNote}${redisNote}\n\nSuperadmin: ${result.superadminEmail} / ${password}`);
|
|
559
|
+
}
|
|
560
|
+
/** Warns where secrets live and that they must never be committed. Never prints secret values. */
|
|
561
|
+
export function printSecurityNotice(result) {
|
|
562
|
+
note([
|
|
563
|
+
`Secrets (DB URL, JWT keys, admin password) were written to ${pc.bold("apps/api/.env")}.`,
|
|
564
|
+
`A ${pc.bold(".gitignore")} was created that excludes ${pc.bold(".env")} files.`,
|
|
565
|
+
`${pc.bold(".env.example")} (placeholders only) is tracked in Git.`,
|
|
566
|
+
pc.yellow("Do NOT commit apps/api/.env or share it. Rotate secrets before production.")
|
|
567
|
+
].join("\n"), "Security");
|
|
568
|
+
}
|
|
569
|
+
/** Cancellation sentinel used to unwind prompts without throwing. */
|
|
570
|
+
const CANCELLED = Symbol("cancelled");
|
|
571
|
+
/** Generates a strong, human-usable password (used in non-interactive mode). */
|
|
572
|
+
export function generatePassword() {
|
|
573
|
+
return generateSecret(18);
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Resolves the package manager, honoring an explicit choice, detecting what is
|
|
577
|
+
* actually installed, and offering a recovery path when the desired manager is
|
|
578
|
+
* missing (issue: pnpm-unavailable should not hard-exit).
|
|
579
|
+
*/
|
|
580
|
+
async function resolvePackageManager(options, interactive) {
|
|
581
|
+
const available = PACKAGE_MANAGERS.filter(isPackageManagerAvailable);
|
|
582
|
+
let desired = options.packageManager;
|
|
583
|
+
if (!desired) {
|
|
584
|
+
if (interactive) {
|
|
585
|
+
const pool = available.length ? available : PACKAGE_MANAGERS;
|
|
586
|
+
const answer = await select({
|
|
587
|
+
message: "Package manager",
|
|
588
|
+
options: pool.map((pm) => ({
|
|
589
|
+
value: pm,
|
|
590
|
+
label: pm === "pnpm" ? "pnpm (recommended)" : pm
|
|
591
|
+
})),
|
|
592
|
+
initialValue: pool.includes("pnpm") ? "pnpm" : pool[0]
|
|
593
|
+
});
|
|
594
|
+
if (isCancel(answer))
|
|
595
|
+
return CANCELLED;
|
|
596
|
+
desired = answer;
|
|
597
|
+
}
|
|
598
|
+
else {
|
|
599
|
+
desired = firstAvailablePackageManager() ?? "npm";
|
|
205
600
|
}
|
|
206
601
|
}
|
|
207
|
-
if (
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
602
|
+
if (isPackageManagerAvailable(desired))
|
|
603
|
+
return desired;
|
|
604
|
+
const fallback = firstAvailablePackageManager();
|
|
605
|
+
const corepackHint = desired === "pnpm" ? " Enable it with `corepack enable && corepack prepare pnpm@latest --activate`." : "";
|
|
606
|
+
if (!interactive) {
|
|
607
|
+
if (options.packageManager) {
|
|
608
|
+
throw new Error(`${desired} was requested but is not installed.${corepackHint}` +
|
|
609
|
+
(fallback ? ` Or re-run with --package-manager ${fallback}.` : ""));
|
|
610
|
+
}
|
|
611
|
+
if (!fallback) {
|
|
612
|
+
throw new Error("No supported package manager (pnpm, npm, or yarn) was found on PATH.");
|
|
212
613
|
}
|
|
213
|
-
|
|
214
|
-
runPackageManagerScript(options.packageManager, "db:seed", targetDir);
|
|
614
|
+
return fallback;
|
|
215
615
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
};
|
|
616
|
+
if (available.length) {
|
|
617
|
+
const answer = await select({
|
|
618
|
+
message: `${desired} is not installed. Choose an available package manager`,
|
|
619
|
+
options: available.map((pm) => ({ value: pm, label: pm })),
|
|
620
|
+
initialValue: available[0]
|
|
621
|
+
});
|
|
622
|
+
if (isCancel(answer))
|
|
623
|
+
return CANCELLED;
|
|
624
|
+
return answer;
|
|
625
|
+
}
|
|
626
|
+
throw new Error(`${desired} is not installed and no supported package manager was found on PATH.${corepackHint}`);
|
|
227
627
|
}
|
|
228
|
-
|
|
628
|
+
/** Prints a plain (non-clack) summary suitable for non-interactive / CI output. */
|
|
629
|
+
function printSummaryPlain(result) {
|
|
229
630
|
const pm = result.packageManager;
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
631
|
+
const lines = [
|
|
632
|
+
"",
|
|
633
|
+
`Project created at ${result.targetDir}`,
|
|
634
|
+
`Package manager: ${pm} Database: ${result.database}`,
|
|
635
|
+
result.dbInitialized ? "Database initialized (migrate + seed)." : "Run migrate + seed before starting.",
|
|
636
|
+
result.redisEnabled ? "Redis queues: enabled." : "Redis queues: disabled (no REDIS_URL).",
|
|
637
|
+
"Secrets written to apps/api/.env (git-ignored). Never commit it.",
|
|
638
|
+
result.passwordGenerated
|
|
639
|
+
? "Superadmin password was generated — read it from apps/api/.env (SUPERADMIN_PASSWORD)."
|
|
640
|
+
: `Superadmin: ${result.superadminEmail}`,
|
|
641
|
+
""
|
|
642
|
+
];
|
|
643
|
+
console.log(lines.join("\n"));
|
|
233
644
|
}
|
|
234
645
|
export async function createProjectInteractive(options = {}) {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
return undefined;
|
|
646
|
+
// Preflight checks that don't require project files run before anything is written.
|
|
647
|
+
assertSupportedNode();
|
|
648
|
+
// Interactive only when stdin is a TTY and the caller did not opt out. This
|
|
649
|
+
// avoids `uv_tty_init EINVAL` crashes in CI / piped environments.
|
|
650
|
+
const interactive = !options.nonInteractive && Boolean(process.stdin.isTTY);
|
|
651
|
+
if (!interactive && !options.projectName) {
|
|
652
|
+
throw new Error("A project name is required in non-interactive mode.\n" +
|
|
653
|
+
" Example: openadminjs create my-app --yes --database sqlite\n" +
|
|
654
|
+
"(stdin is not a TTY, or --yes / --non-interactive was passed.)");
|
|
245
655
|
}
|
|
246
|
-
|
|
247
|
-
(
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
}));
|
|
256
|
-
if (isCancel(packageManager)) {
|
|
257
|
-
cancel("Cancelled");
|
|
258
|
-
return undefined;
|
|
259
|
-
}
|
|
260
|
-
const database = options.database ??
|
|
261
|
-
(await select({
|
|
262
|
-
message: "Database",
|
|
263
|
-
options: [
|
|
264
|
-
{ value: "postgresql", label: "PostgreSQL" },
|
|
265
|
-
{ value: "mysql", label: "MySQL" },
|
|
266
|
-
{ value: "sqlite", label: "SQLite" }
|
|
267
|
-
],
|
|
268
|
-
initialValue: "postgresql"
|
|
269
|
-
}));
|
|
270
|
-
if (isCancel(database)) {
|
|
271
|
-
cancel("Cancelled");
|
|
272
|
-
return undefined;
|
|
273
|
-
}
|
|
274
|
-
const superadminEmail = options.superadminEmail ??
|
|
275
|
-
(await text({
|
|
276
|
-
message: "Superadmin email",
|
|
277
|
-
defaultValue: "admin@localhost.dev",
|
|
278
|
-
placeholder: "admin@localhost.dev",
|
|
279
|
-
validate(value) {
|
|
280
|
-
return /^\S+@\S+\.\S+$/.test(value) ? undefined : "Enter a valid email address.";
|
|
281
|
-
}
|
|
282
|
-
}));
|
|
283
|
-
if (isCancel(superadminEmail)) {
|
|
284
|
-
cancel("Cancelled");
|
|
285
|
-
return undefined;
|
|
286
|
-
}
|
|
287
|
-
const superadminPassword = options.superadminPassword ??
|
|
288
|
-
(await text({
|
|
289
|
-
message: "Superadmin password",
|
|
290
|
-
placeholder: "At least 8 characters",
|
|
291
|
-
validate(value) {
|
|
292
|
-
return value.length >= 8 ? undefined : "Password must be at least 8 characters.";
|
|
293
|
-
}
|
|
294
|
-
}));
|
|
295
|
-
if (isCancel(superadminPassword)) {
|
|
296
|
-
cancel("Cancelled");
|
|
297
|
-
return undefined;
|
|
656
|
+
if (interactive)
|
|
657
|
+
intro(pc.green("Create OpenAdminJS"));
|
|
658
|
+
// ── project name ──
|
|
659
|
+
let projectName = options.projectName;
|
|
660
|
+
if (!projectName) {
|
|
661
|
+
const answer = await text({ message: "Project name", defaultValue: "my-app", placeholder: "my-app" });
|
|
662
|
+
if (isCancel(answer))
|
|
663
|
+
return cancelledUndefined();
|
|
664
|
+
projectName = String(answer);
|
|
298
665
|
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
666
|
+
// ── package manager (with availability fallback) ──
|
|
667
|
+
const packageManager = await resolvePackageManager(options, interactive);
|
|
668
|
+
if (packageManager === CANCELLED)
|
|
669
|
+
return cancelledUndefined();
|
|
670
|
+
// ── database ──
|
|
671
|
+
let database = options.database;
|
|
672
|
+
if (!database) {
|
|
673
|
+
if (interactive) {
|
|
674
|
+
const answer = await select({
|
|
675
|
+
message: "Database",
|
|
676
|
+
options: [
|
|
677
|
+
{ value: "postgresql", label: "PostgreSQL" },
|
|
678
|
+
{ value: "mysql", label: "MySQL" },
|
|
679
|
+
{ value: "sqlite", label: "SQLite (local file, zero-setup)" }
|
|
680
|
+
],
|
|
681
|
+
initialValue: "postgresql"
|
|
682
|
+
});
|
|
683
|
+
if (isCancel(answer))
|
|
684
|
+
return cancelledUndefined();
|
|
685
|
+
database = answer;
|
|
686
|
+
}
|
|
687
|
+
else {
|
|
688
|
+
database = "sqlite";
|
|
689
|
+
}
|
|
307
690
|
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
if (
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
691
|
+
// ── superadmin email ──
|
|
692
|
+
let email = options.superadminEmail;
|
|
693
|
+
if (!email) {
|
|
694
|
+
if (interactive) {
|
|
695
|
+
const answer = await text({
|
|
696
|
+
message: "Superadmin email",
|
|
697
|
+
defaultValue: DEFAULT_SUPERADMIN_EMAIL,
|
|
698
|
+
placeholder: DEFAULT_SUPERADMIN_EMAIL,
|
|
699
|
+
validate: (value) => validateSuperadminEmailInput(value)
|
|
700
|
+
});
|
|
701
|
+
if (isCancel(answer))
|
|
702
|
+
return cancelledUndefined();
|
|
703
|
+
email = String(answer);
|
|
320
704
|
}
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
const next = await text({
|
|
324
|
-
message: "Database URL",
|
|
325
|
-
defaultValue: checkedDatabaseUrl
|
|
326
|
-
});
|
|
327
|
-
if (isCancel(next)) {
|
|
328
|
-
cancel("Cancelled");
|
|
329
|
-
return undefined;
|
|
705
|
+
else {
|
|
706
|
+
email = DEFAULT_SUPERADMIN_EMAIL;
|
|
330
707
|
}
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
708
|
+
}
|
|
709
|
+
const resolvedEmail = resolveSuperadminEmail(String(email));
|
|
710
|
+
// ── superadmin password (masked in interactive mode; generated otherwise) ──
|
|
711
|
+
let passwordGenerated = false;
|
|
712
|
+
let superadminPassword = options.superadminPassword;
|
|
713
|
+
if (!superadminPassword) {
|
|
714
|
+
if (interactive) {
|
|
715
|
+
const answer = await password({
|
|
716
|
+
message: "Superadmin password (input hidden, min 8 chars)",
|
|
339
717
|
validate(value) {
|
|
340
|
-
|
|
718
|
+
const { weak, reason } = inspectPassword(value);
|
|
719
|
+
return weak ? capitalize(reason ?? "Password is too weak.") : undefined;
|
|
341
720
|
}
|
|
342
|
-
})
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
721
|
+
});
|
|
722
|
+
if (isCancel(answer))
|
|
723
|
+
return cancelledUndefined();
|
|
724
|
+
superadminPassword = String(answer);
|
|
346
725
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
const redisError = await validateRedisConnectivity(checkedRedisUrl);
|
|
351
|
-
if (!redisError)
|
|
352
|
-
break;
|
|
353
|
-
const retry = await confirm({
|
|
354
|
-
message: `${redisError} Retry entering REDIS_URL?`,
|
|
355
|
-
initialValue: true
|
|
356
|
-
});
|
|
357
|
-
if (isCancel(retry)) {
|
|
358
|
-
cancel("Cancelled");
|
|
359
|
-
return undefined;
|
|
726
|
+
else {
|
|
727
|
+
superadminPassword = generatePassword();
|
|
728
|
+
passwordGenerated = true;
|
|
360
729
|
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
730
|
+
}
|
|
731
|
+
// ── database URL (Enter accepts the shown default) ──
|
|
732
|
+
const defaultDbUrl = databaseUrl(toPackageName(String(projectName)), database);
|
|
733
|
+
let checkedDatabaseUrl = (options.databaseUrl ?? "").trim();
|
|
734
|
+
if (!checkedDatabaseUrl) {
|
|
735
|
+
if (interactive) {
|
|
736
|
+
const answer = await text({
|
|
737
|
+
message: "Database URL",
|
|
738
|
+
defaultValue: defaultDbUrl,
|
|
739
|
+
placeholder: defaultDbUrl,
|
|
740
|
+
validate: (value) => validateDatabaseUrlInput(database, value, defaultDbUrl)
|
|
741
|
+
});
|
|
742
|
+
if (isCancel(answer))
|
|
743
|
+
return cancelledUndefined();
|
|
744
|
+
checkedDatabaseUrl = String(answer).trim() || defaultDbUrl;
|
|
745
|
+
}
|
|
746
|
+
else {
|
|
747
|
+
checkedDatabaseUrl = defaultDbUrl;
|
|
370
748
|
}
|
|
371
|
-
checkedRedisUrl = String(next).trim();
|
|
372
|
-
}
|
|
373
|
-
const jwtSecret = options.jwtSecret ??
|
|
374
|
-
(await text({
|
|
375
|
-
message: "JWT secret",
|
|
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
749
|
}
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
})
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
750
|
+
// Connectivity is checked only interactively and never blocks: the user can
|
|
751
|
+
// decline to retry and continue (e.g. DB not started yet).
|
|
752
|
+
if (interactive) {
|
|
753
|
+
const outcome = await confirmConnectivityLoop(() => validateDbConnectivity(database, checkedDatabaseUrl), "DATABASE_URL", () => text({ message: "Database URL", defaultValue: checkedDatabaseUrl, placeholder: checkedDatabaseUrl }), (next) => {
|
|
754
|
+
checkedDatabaseUrl = next.trim() || checkedDatabaseUrl;
|
|
755
|
+
});
|
|
756
|
+
if (outcome === CANCELLED)
|
|
757
|
+
return cancelledUndefined();
|
|
758
|
+
}
|
|
759
|
+
// ── Redis (optional; blank disables background job queues) ──
|
|
760
|
+
let checkedRedisUrl;
|
|
761
|
+
if (options.skipRedis) {
|
|
762
|
+
checkedRedisUrl = "";
|
|
763
|
+
}
|
|
764
|
+
else if (options.redisUrl !== undefined) {
|
|
765
|
+
checkedRedisUrl = options.redisUrl.trim();
|
|
766
|
+
}
|
|
767
|
+
else if (interactive) {
|
|
768
|
+
const def = database === "sqlite" ? "" : DEFAULT_REDIS_URL;
|
|
769
|
+
const answer = await text({
|
|
770
|
+
message: "Redis URL (blank to disable background job queues)",
|
|
771
|
+
defaultValue: def,
|
|
772
|
+
placeholder: def || "blank = queues disabled",
|
|
773
|
+
validate: (value) => validateRedisUrlInput(value)
|
|
774
|
+
});
|
|
775
|
+
if (isCancel(answer))
|
|
776
|
+
return cancelledUndefined();
|
|
777
|
+
checkedRedisUrl = String(answer).trim();
|
|
778
|
+
}
|
|
779
|
+
else {
|
|
780
|
+
checkedRedisUrl = "";
|
|
781
|
+
}
|
|
782
|
+
if (interactive && checkedRedisUrl) {
|
|
783
|
+
const outcome = await confirmConnectivityLoop(() => validateRedisConnectivity(checkedRedisUrl), "REDIS_URL", () => text({ message: "Redis URL (blank to disable)", defaultValue: checkedRedisUrl }), (next) => {
|
|
784
|
+
checkedRedisUrl = next.trim();
|
|
785
|
+
});
|
|
786
|
+
if (outcome === CANCELLED)
|
|
787
|
+
return cancelledUndefined();
|
|
392
788
|
}
|
|
789
|
+
// JWT secrets are generated with a CSPRNG — never prompted with predictable defaults.
|
|
790
|
+
const jwtSecret = options.jwtSecret ?? generateSecret();
|
|
791
|
+
const jwtRefreshSecret = options.jwtRefreshSecret ?? generateSecret();
|
|
393
792
|
const adminOrigin = options.adminOrigin ?? "http://localhost:3000";
|
|
394
793
|
const apiPort = options.apiPort ?? "4000";
|
|
395
|
-
|
|
396
|
-
if (
|
|
397
|
-
|
|
398
|
-
|
|
794
|
+
let git = options.git;
|
|
795
|
+
if (git === undefined) {
|
|
796
|
+
if (interactive) {
|
|
797
|
+
const answer = await confirm({ message: "Initialize git?", initialValue: true });
|
|
798
|
+
if (isCancel(answer))
|
|
799
|
+
return cancelledUndefined();
|
|
800
|
+
git = answer;
|
|
801
|
+
}
|
|
802
|
+
else {
|
|
803
|
+
git = true;
|
|
804
|
+
}
|
|
399
805
|
}
|
|
400
806
|
const install = options.install ?? true;
|
|
401
807
|
const result = createProject({
|
|
@@ -403,7 +809,7 @@ export async function createProjectInteractive(options = {}) {
|
|
|
403
809
|
cwd: options.cwd ?? process.cwd(),
|
|
404
810
|
packageManager,
|
|
405
811
|
database,
|
|
406
|
-
superadminEmail:
|
|
812
|
+
superadminEmail: resolvedEmail,
|
|
407
813
|
superadminPassword: String(superadminPassword),
|
|
408
814
|
databaseUrl: checkedDatabaseUrl,
|
|
409
815
|
redisUrl: checkedRedisUrl,
|
|
@@ -413,8 +819,63 @@ export async function createProjectInteractive(options = {}) {
|
|
|
413
819
|
apiPort: String(apiPort),
|
|
414
820
|
git,
|
|
415
821
|
install,
|
|
416
|
-
|
|
822
|
+
nonInteractive: !interactive,
|
|
823
|
+
runtimeMode: options.runtimeMode,
|
|
824
|
+
templateDir: options.templateDir
|
|
417
825
|
});
|
|
418
|
-
|
|
826
|
+
result.passwordGenerated = passwordGenerated;
|
|
827
|
+
if (interactive) {
|
|
828
|
+
printSecurityNotice(result);
|
|
829
|
+
printNextSteps(result);
|
|
830
|
+
}
|
|
831
|
+
else {
|
|
832
|
+
printSummaryPlain(result);
|
|
833
|
+
}
|
|
419
834
|
return result;
|
|
420
835
|
}
|
|
836
|
+
function cancelledUndefined() {
|
|
837
|
+
cancel("Cancelled");
|
|
838
|
+
return undefined;
|
|
839
|
+
}
|
|
840
|
+
function capitalize(s) {
|
|
841
|
+
return s ? s[0].toUpperCase() + s.slice(1) : s;
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Validates a DATABASE_URL against the FINAL resolved value so pressing Enter to
|
|
845
|
+
* accept the shown default is always valid.
|
|
846
|
+
*/
|
|
847
|
+
export function validateDatabaseUrlInput(database, value, fallback) {
|
|
848
|
+
const v = value.trim() || fallback;
|
|
849
|
+
if (database === "sqlite") {
|
|
850
|
+
return /^file:/.test(v) ? undefined : 'SQLite DATABASE_URL must start with "file:".';
|
|
851
|
+
}
|
|
852
|
+
try {
|
|
853
|
+
// eslint-disable-next-line no-new
|
|
854
|
+
new URL(v);
|
|
855
|
+
return undefined;
|
|
856
|
+
}
|
|
857
|
+
catch {
|
|
858
|
+
return "Enter a valid database URL.";
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Runs a non-blocking connectivity check with an interactive retry loop. Returns
|
|
863
|
+
* CANCELLED if the user cancels; otherwise resolves once the check passes or the
|
|
864
|
+
* user declines to retry.
|
|
865
|
+
*/
|
|
866
|
+
async function confirmConnectivityLoop(check, label, reprompt, apply) {
|
|
867
|
+
for (;;) {
|
|
868
|
+
const error = await check();
|
|
869
|
+
if (!error)
|
|
870
|
+
return;
|
|
871
|
+
const retry = await confirm({ message: `${error} Retry entering ${label}?`, initialValue: true });
|
|
872
|
+
if (isCancel(retry))
|
|
873
|
+
return CANCELLED;
|
|
874
|
+
if (!retry)
|
|
875
|
+
return;
|
|
876
|
+
const next = await reprompt();
|
|
877
|
+
if (isCancel(next))
|
|
878
|
+
return CANCELLED;
|
|
879
|
+
apply(String(next));
|
|
880
|
+
}
|
|
881
|
+
}
|