openadminjs 0.1.23 → 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/admin/app/layout.tsx +2 -9
- package/template/apps/api/package.json +22 -20
- package/template/apps/api/src/app.module.test.ts +12 -0
- package/template/apps/api/src/app.module.ts +17 -11
- 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/openadmin-throttler.guard.ts +39 -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/common/request-logging.interceptor.test.ts +39 -0
- package/template/apps/api/src/common/request-logging.interceptor.ts +5 -3
- package/template/apps/api/src/graphql/admin-resources.args.ts +15 -0
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +20 -1
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.ts +15 -0
- package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +26 -0
- package/template/apps/api/src/graphql/graphql-schema.test.ts +8 -0
- package/template/apps/api/src/graphql/graphql.module.ts +13 -1
- package/template/apps/api/src/queue/queue.module.ts +1 -8
- package/template/apps/api/src/queue/queue.processor.ts +26 -6
- package/template/apps/api/src/queue/queue.service.test.ts +33 -0
- package/template/apps/api/src/queue/queue.service.ts +30 -12
- package/template/package.json +19 -0
- package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -0
- package/template/prisma/seed.ts +30 -1
package/dist/index.js
CHANGED
|
@@ -1,104 +1,61 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import {
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { cac } from "cac";
|
|
6
6
|
import pc from "picocolors";
|
|
7
7
|
import { createProjectInteractive } from "./create-project.js";
|
|
8
8
|
import { modelNameToResourceSlug } from "./resource-slug.js";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
return;
|
|
21
|
-
}
|
|
22
|
-
const [cmd, args] = entry;
|
|
23
|
-
const result = spawnSync(cmd, args, { stdio: "inherit", cwd: process.cwd() });
|
|
24
|
-
if (result.status !== 0 || result.error) {
|
|
25
|
-
process.exitCode = result.status ?? 1;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
function doctor() {
|
|
29
|
-
const cwd = process.cwd();
|
|
30
|
-
const required = ["package.json", "pnpm-workspace.yaml", "prisma/schema.prisma"];
|
|
31
|
-
const missing = required.filter((file) => !existsSync(join(cwd, file)));
|
|
32
|
-
const hasEnvSample = existsSync(join(cwd, ".env.example")) || existsSync(join(cwd, "apps", "api", ".env"));
|
|
33
|
-
if (!hasEnvSample) {
|
|
34
|
-
missing.push("apps/api/.env (or .env.example at repo root)");
|
|
35
|
-
}
|
|
36
|
-
if (missing.length) {
|
|
37
|
-
console.error(pc.red("OpenAdminJS doctor found missing files:"));
|
|
38
|
-
for (const file of missing)
|
|
39
|
-
console.error(` - ${file}`);
|
|
40
|
-
process.exitCode = 1;
|
|
41
|
-
return;
|
|
9
|
+
import { assertInsideDir, toKebabCase, toPascalCase, validateName, validatePluginId } from "./validate-name.js";
|
|
10
|
+
import { buildDbCommand, runInherit } from "./db-commands.js";
|
|
11
|
+
import { detectPackageManager } from "./detect-package-manager.js";
|
|
12
|
+
import { runDoctorChecks } from "./doctor.js";
|
|
13
|
+
import { runSecurityChecks } from "./security.js";
|
|
14
|
+
export { createProject, createProjectInteractive, databaseUrl, defaultTemplateDir, printNextSteps, printSecurityNotice, toPackageName } from "./create-project.js";
|
|
15
|
+
export { modelNameToResourceSlug } from "./resource-slug.js";
|
|
16
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
17
|
+
function readPackageVersion() {
|
|
18
|
+
try {
|
|
19
|
+
const pkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf8"));
|
|
20
|
+
return pkg.version ?? "0.0.0";
|
|
42
21
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
function securityCheck() {
|
|
46
|
-
const cwd = process.cwd();
|
|
47
|
-
const envSample = existsSync(join(cwd, ".env.example"))
|
|
48
|
-
? readFileSync(join(cwd, ".env.example"), "utf8")
|
|
49
|
-
: existsSync(join(cwd, "apps", "api", ".env"))
|
|
50
|
-
? readFileSync(join(cwd, "apps", "api", ".env"), "utf8")
|
|
51
|
-
: "";
|
|
52
|
-
const findings = [];
|
|
53
|
-
if (!envSample) {
|
|
54
|
-
findings.push("No .env.example or apps/api/.env found for security checklist");
|
|
55
|
-
}
|
|
56
|
-
else if (!envSample.includes("JWT_SECRET")) {
|
|
57
|
-
findings.push("JWT_SECRET is missing from env sample (.env.example or apps/api/.env)");
|
|
58
|
-
}
|
|
59
|
-
if (envSample.includes("DATABASE_URL=postgresql://") && !envSample.includes("localhost")) {
|
|
60
|
-
findings.push("DATABASE_URL example should not point to production");
|
|
61
|
-
}
|
|
62
|
-
if (existsSync("apps/admin/app")) {
|
|
63
|
-
const login = existsSync("apps/admin/app/login/page.tsx");
|
|
64
|
-
if (!login)
|
|
65
|
-
findings.push("Admin login route is missing");
|
|
66
|
-
}
|
|
67
|
-
if (findings.length) {
|
|
68
|
-
console.error(pc.red("Security check failed:"));
|
|
69
|
-
for (const finding of findings)
|
|
70
|
-
console.error(` - ${finding}`);
|
|
71
|
-
process.exitCode = 1;
|
|
72
|
-
return;
|
|
22
|
+
catch {
|
|
23
|
+
return "0.0.0";
|
|
73
24
|
}
|
|
74
|
-
console.log(pc.green("Security check passed."));
|
|
75
25
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const
|
|
26
|
+
const cli = cac("openadminjs");
|
|
27
|
+
// ── generators ──────────────────────────────────────────────────────────────
|
|
28
|
+
function generateResource(rawName, options) {
|
|
29
|
+
const validated = validateName(rawName, "resource name");
|
|
30
|
+
const model = toPascalCase(validated);
|
|
31
|
+
const slug = toKebabCase(validated);
|
|
32
|
+
const plural = `${slug}s`;
|
|
33
|
+
const projectRoot = process.cwd();
|
|
34
|
+
const targetDir = join(projectRoot, "apps/api/src/resources");
|
|
35
|
+
const target = assertInsideDir(targetDir, `${slug}.resource.ts`);
|
|
80
36
|
if (existsSync(target) && !options.force) {
|
|
81
37
|
console.error(pc.red(`${target} already exists. Use --force to overwrite.`));
|
|
82
38
|
process.exitCode = 1;
|
|
83
39
|
return;
|
|
84
40
|
}
|
|
85
41
|
mkdirSync(targetDir, { recursive: true });
|
|
86
|
-
|
|
87
|
-
writeFileSync(target, `import { defineResource } from '@openadminjs/core';\n\nexport default defineResource({\n name: '${plural}',\n label: '${modelName}s',\n model: '${modelName}',\n titleField: 'id',\n icon: 'Database',\n permissions: {\n read: '${plural}.read',\n create: '${plural}.create',\n update: '${plural}.update',\n delete: '${plural}.delete',\n },\n fields: {\n id: { type: 'id', label: 'ID', create: false, edit: false },\n },\n});\n`);
|
|
42
|
+
writeFileSync(target, `import { defineResource } from '@openadminjs/core';\n\nexport default defineResource({\n name: '${plural}',\n label: '${model}s',\n model: '${model}',\n titleField: 'id',\n icon: 'Database',\n permissions: {\n read: '${plural}.read',\n create: '${plural}.create',\n update: '${plural}.update',\n delete: '${plural}.delete',\n },\n fields: {\n id: { type: 'id', label: 'ID', create: false, edit: false },\n },\n});\n`);
|
|
88
43
|
console.log(pc.green(`Created ${target}`));
|
|
89
44
|
}
|
|
90
|
-
function generatePlugin(
|
|
91
|
-
const safeId =
|
|
92
|
-
const slug = safeId.replace(/\./g, "-");
|
|
93
|
-
const
|
|
94
|
-
const
|
|
45
|
+
function generatePlugin(rawId, options) {
|
|
46
|
+
const safeId = validatePluginId(rawId);
|
|
47
|
+
const slug = safeId.replace(/\./g, "-").toLowerCase();
|
|
48
|
+
const varName = slug.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
49
|
+
const projectRoot = process.cwd();
|
|
50
|
+
const targetDir = join(projectRoot, "apps/api/src/plugins/custom");
|
|
51
|
+
const target = assertInsideDir(targetDir, `${slug}.plugin.ts`);
|
|
95
52
|
if (existsSync(target) && !options.force) {
|
|
96
53
|
console.error(pc.red(`${target} already exists. Use --force to overwrite.`));
|
|
97
54
|
process.exitCode = 1;
|
|
98
55
|
return;
|
|
99
56
|
}
|
|
100
57
|
mkdirSync(targetDir, { recursive: true });
|
|
101
|
-
writeFileSync(target, `import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";\n\nexport const ${
|
|
58
|
+
writeFileSync(target, `import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";\n\nexport const ${varName}Plugin: OpenAdminPlugin = {\n id: ${JSON.stringify(safeId)},\n version: "0.1.0",\n register({ registerSurface }) {\n registerSurface({\n seo: {\n metadata({ resourceName, record }) {\n if (resourceName !== "posts") return {};\n return { title: record.title ?? "Untitled" };\n }\n }\n });\n }\n};\n`);
|
|
102
59
|
console.log(pc.green(`Created ${target}`));
|
|
103
60
|
}
|
|
104
61
|
function normalizeFieldType(raw) {
|
|
@@ -157,6 +114,8 @@ function startCase(input) {
|
|
|
157
114
|
return withSpaces ? withSpaces[0].toUpperCase() + withSpaces.slice(1) : input;
|
|
158
115
|
}
|
|
159
116
|
function generateResourceField(resourceArg, fieldName, fieldTypeRaw, options) {
|
|
117
|
+
// resourceArg is only used to resolve an existing file; validate to block traversal.
|
|
118
|
+
validateName(resourceArg.replace(/\.resource\.ts$/i, ""), "resource");
|
|
160
119
|
const target = resolveResourceFile(resourceArg);
|
|
161
120
|
if (!target) {
|
|
162
121
|
console.error(pc.red(`Could not find *.resource.ts for "${resourceArg}" under apps/api/src/resources`));
|
|
@@ -164,7 +123,7 @@ function generateResourceField(resourceArg, fieldName, fieldTypeRaw, options) {
|
|
|
164
123
|
return;
|
|
165
124
|
}
|
|
166
125
|
if (!/^[a-z][a-zA-Z0-9]*$/.test(fieldName)) {
|
|
167
|
-
console.error(pc.red("fieldName must be camelCase"));
|
|
126
|
+
console.error(pc.red("fieldName must be camelCase (e.g. publishedAt)."));
|
|
168
127
|
process.exitCode = 1;
|
|
169
128
|
return;
|
|
170
129
|
}
|
|
@@ -177,7 +136,7 @@ function generateResourceField(resourceArg, fieldName, fieldTypeRaw, options) {
|
|
|
177
136
|
}
|
|
178
137
|
const fieldsBlock = content.match(/fields:\s*\{[\s\S]*?\n\s*\},\n\s*(permissions|actions|i18n|seo|listScope|hooks|})/m);
|
|
179
138
|
if (fieldsBlock?.index == null) {
|
|
180
|
-
console.error(pc.red(
|
|
139
|
+
console.error(pc.red("Could not locate fields block (`fields: { ... }`)."));
|
|
181
140
|
process.exitCode = 1;
|
|
182
141
|
return;
|
|
183
142
|
}
|
|
@@ -204,87 +163,220 @@ function generateResourceField(resourceArg, fieldName, fieldTypeRaw, options) {
|
|
|
204
163
|
const snippet = `\n ${fieldName}: { ${attributes.join(", ")} },`;
|
|
205
164
|
writeFileSync(target, `${head.slice(0, lb + 2)}${snippet}${tail}`);
|
|
206
165
|
console.log(pc.green(`Updated ${target}`));
|
|
207
|
-
console.log(pc.dim("// Prisma model fragment — merge into schema.prisma, then
|
|
166
|
+
console.log(pc.dim("// Prisma model fragment — merge into schema.prisma, then run: openadminjs db migrate dev"));
|
|
208
167
|
console.log(pc.dim(`// ${prismaFieldFragment(fieldName, fieldType, Boolean(options.required))}`));
|
|
209
168
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
169
|
+
// ── doctor / security ─────────────────────────────────────────────────────────
|
|
170
|
+
async function doctor(options) {
|
|
171
|
+
const report = await runDoctorChecks(process.cwd(), { skipNetwork: options.skipNetwork });
|
|
172
|
+
if (options.json) {
|
|
173
|
+
console.log(JSON.stringify(report, null, 2));
|
|
214
174
|
}
|
|
215
|
-
|
|
216
|
-
console.
|
|
175
|
+
else {
|
|
176
|
+
console.log(pc.bold("OpenAdminJS doctor"));
|
|
177
|
+
for (const r of report.results)
|
|
178
|
+
printCheck(r);
|
|
179
|
+
console.log(report.ok ? pc.green("\nDoctor: no blocking issues.") : pc.red("\nDoctor: failed checks found."));
|
|
180
|
+
}
|
|
181
|
+
if (!report.ok)
|
|
217
182
|
process.exitCode = 1;
|
|
183
|
+
}
|
|
184
|
+
function printCheck(r) {
|
|
185
|
+
const icon = r.status === "pass" ? pc.green("PASS") : r.status === "warn" ? pc.yellow("WARN") : pc.red("FAIL");
|
|
186
|
+
console.log(` [${icon}] ${r.name}: ${r.message}`);
|
|
187
|
+
}
|
|
188
|
+
function securityCheck(options) {
|
|
189
|
+
const report = runSecurityChecks(process.cwd(), { skipNetwork: options.skipNetwork });
|
|
190
|
+
if (options.json) {
|
|
191
|
+
console.log(JSON.stringify(report, null, 2));
|
|
218
192
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
.action((action) => {
|
|
225
|
-
switch (action) {
|
|
226
|
-
case "migrate":
|
|
227
|
-
console.log("Run: pnpm --filter @openadminjs/api prisma migrate dev");
|
|
228
|
-
return;
|
|
229
|
-
case "seed":
|
|
230
|
-
console.log("Run: pnpm --filter @openadminjs/api prisma db seed");
|
|
231
|
-
return;
|
|
232
|
-
case "studio":
|
|
233
|
-
console.log("Run: pnpm --filter @openadminjs/api prisma studio");
|
|
234
|
-
return;
|
|
235
|
-
default:
|
|
236
|
-
console.error(pc.red("Unknown db action. Use: migrate, seed, studio."));
|
|
237
|
-
process.exitCode = 1;
|
|
193
|
+
else {
|
|
194
|
+
console.log(pc.bold("OpenAdminJS security check"));
|
|
195
|
+
for (const f of report.findings)
|
|
196
|
+
printFinding(f);
|
|
197
|
+
console.log(report.ok ? pc.green("\nSecurity: no critical issues.") : pc.red("\nSecurity: critical issues found."));
|
|
238
198
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
199
|
+
if (!report.ok)
|
|
200
|
+
process.exitCode = 1;
|
|
201
|
+
}
|
|
202
|
+
function printFinding(f) {
|
|
203
|
+
const sev = f.severity === "critical" ? pc.red("CRIT") : f.severity === "warning" ? pc.yellow("WARN") : pc.cyan("INFO");
|
|
204
|
+
console.log(` [${sev}] ${f.id}: ${f.message}`);
|
|
205
|
+
}
|
|
206
|
+
// ── db commands ────────────────────────────────────────────────────────────
|
|
207
|
+
async function dbCommand(action, mode, options) {
|
|
208
|
+
if (!action) {
|
|
209
|
+
console.error(pc.red("Usage: openadminjs db <migrate [dev|deploy]|seed|studio|reset> [--dry-run]"));
|
|
210
|
+
process.exitCode = 1;
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const cwd = process.cwd();
|
|
214
|
+
const pm = detectPackageManager(cwd);
|
|
215
|
+
let command;
|
|
216
|
+
try {
|
|
217
|
+
command = buildDbCommand(action, mode, pm);
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
console.error(pc.red(error instanceof Error ? error.message : "Invalid db command."));
|
|
243
221
|
process.exitCode = 1;
|
|
244
222
|
return;
|
|
245
223
|
}
|
|
246
|
-
if (
|
|
247
|
-
|
|
224
|
+
if (options.dryRun) {
|
|
225
|
+
console.log(command.label);
|
|
248
226
|
return;
|
|
249
227
|
}
|
|
250
|
-
if (
|
|
251
|
-
|
|
228
|
+
if (command.destructive && !options.yes) {
|
|
229
|
+
console.error(pc.red(`"${command.label}" is destructive and will drop data. Re-run with --yes to confirm.`));
|
|
230
|
+
process.exitCode = 1;
|
|
252
231
|
return;
|
|
253
232
|
}
|
|
254
|
-
|
|
255
|
-
|
|
233
|
+
const code = await runInherit(command.cmd, command.args, cwd);
|
|
234
|
+
if (code !== 0)
|
|
235
|
+
process.exitCode = code;
|
|
256
236
|
}
|
|
237
|
+
// ── command registrations ─────────────────────────────────────────────────────
|
|
238
|
+
cli.command("create [projectName]", "Create a new OpenAdminJS project").action(async (projectName) => {
|
|
239
|
+
try {
|
|
240
|
+
await createProjectInteractive({ projectName });
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
console.error(pc.red(error instanceof Error ? error.message : "Failed to create project."));
|
|
244
|
+
process.exitCode = 1;
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
cli
|
|
248
|
+
.command("db <action> [mode]", "Database commands: migrate [dev|deploy], seed, studio, reset")
|
|
249
|
+
.option("--dry-run", "Print the command without executing it")
|
|
250
|
+
.option("--yes", "Confirm destructive commands (e.g. reset)")
|
|
251
|
+
.action((action, mode, options) => dbCommand(action, mode, options));
|
|
257
252
|
cli
|
|
258
|
-
.command("generate
|
|
259
|
-
.option("--type <type>", "Field type (text, number, boolean, date, json)", { default: "text" })
|
|
253
|
+
.command("generate <kind> [name] [fieldName]", "Generate a resource, plugin, or field")
|
|
254
|
+
.option("--type <type>", "Field type for `generate field` (text, number, boolean, date, json)", { default: "text" })
|
|
255
|
+
.option("--label <label>", "Field label override (generate field)")
|
|
256
|
+
.option("--required", "Mark field as required (generate field)")
|
|
257
|
+
.option("--list", "Show field in list views (generate field)")
|
|
258
|
+
.option("--sortable", "Mark field as sortable (generate field)")
|
|
259
|
+
.option("--filterable", "Mark field as filterable (generate field)")
|
|
260
|
+
.option("--searchable", "Mark field as searchable (generate field)")
|
|
261
|
+
.option("--force", "Overwrite / append even when the target already exists")
|
|
262
|
+
.action(runGenerate);
|
|
263
|
+
cli
|
|
264
|
+
.command("make <kind> [name] [fieldName]", "Alias for generate")
|
|
265
|
+
.option("--type <type>", "Field type for `make field`", { default: "text" })
|
|
260
266
|
.option("--label <label>", "Field label override")
|
|
261
267
|
.option("--required", "Mark field as required")
|
|
262
268
|
.option("--list", "Show field in list views")
|
|
263
269
|
.option("--sortable", "Mark field as sortable")
|
|
264
270
|
.option("--filterable", "Mark field as filterable")
|
|
265
271
|
.option("--searchable", "Mark field as searchable")
|
|
266
|
-
.option("--force", "Write even when the field key already exists")
|
|
267
|
-
.action((resource, fieldName, options) => {
|
|
268
|
-
generateResourceField(resource, fieldName, options.type ?? "text", {
|
|
269
|
-
force: options.force,
|
|
270
|
-
required: options.required,
|
|
271
|
-
list: options.list,
|
|
272
|
-
sortable: options.sortable,
|
|
273
|
-
filterable: options.filterable,
|
|
274
|
-
searchable: options.searchable,
|
|
275
|
-
label: options.label
|
|
276
|
-
});
|
|
277
|
-
});
|
|
278
|
-
cli
|
|
279
|
-
.command("generate <kind> <name>", "Generate resource or plugin starter")
|
|
280
272
|
.option("--force", "Overwrite existing file")
|
|
281
|
-
.action(
|
|
273
|
+
.action(runGenerate);
|
|
274
|
+
function runGenerate(kind, name, fieldName, options) {
|
|
275
|
+
try {
|
|
276
|
+
switch (kind) {
|
|
277
|
+
case "resource":
|
|
278
|
+
if (!name)
|
|
279
|
+
return usageError("openadminjs generate resource <Model> [--force]");
|
|
280
|
+
generateResource(name, { force: options.force });
|
|
281
|
+
return;
|
|
282
|
+
case "plugin":
|
|
283
|
+
if (!name)
|
|
284
|
+
return usageError("openadminjs generate plugin <plugin.id> [--force]");
|
|
285
|
+
generatePlugin(name, { force: options.force });
|
|
286
|
+
return;
|
|
287
|
+
case "field":
|
|
288
|
+
if (!name || !fieldName) {
|
|
289
|
+
return usageError("openadminjs generate field <resource> <fieldName> [--type <type>] [--required] ...");
|
|
290
|
+
}
|
|
291
|
+
generateResourceField(name, fieldName, options.type ?? "text", {
|
|
292
|
+
force: options.force,
|
|
293
|
+
required: options.required,
|
|
294
|
+
list: options.list,
|
|
295
|
+
sortable: options.sortable,
|
|
296
|
+
filterable: options.filterable,
|
|
297
|
+
searchable: options.searchable,
|
|
298
|
+
label: options.label
|
|
299
|
+
});
|
|
300
|
+
return;
|
|
301
|
+
default:
|
|
302
|
+
console.error(pc.red(`Unknown generate kind "${kind ?? ""}". Use: resource, plugin, or field.`));
|
|
303
|
+
process.exitCode = 1;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
console.error(pc.red(error instanceof Error ? error.message : "Generation failed."));
|
|
308
|
+
process.exitCode = 1;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
function usageError(usage) {
|
|
312
|
+
console.error(pc.red(`Usage: ${usage}`));
|
|
313
|
+
process.exitCode = 1;
|
|
314
|
+
}
|
|
282
315
|
cli
|
|
283
|
-
.command("
|
|
284
|
-
.option("--
|
|
285
|
-
.
|
|
286
|
-
|
|
287
|
-
cli
|
|
288
|
-
|
|
316
|
+
.command("doctor", "Check generated project health")
|
|
317
|
+
.option("--json", "Output machine-readable JSON")
|
|
318
|
+
.option("--skip-network", "Skip network-dependent checks (db/redis/pm)")
|
|
319
|
+
.action((options) => doctor(options));
|
|
320
|
+
cli
|
|
321
|
+
.command("security [check]", "Run the security checklist")
|
|
322
|
+
.option("--json", "Output machine-readable JSON")
|
|
323
|
+
.option("--skip-network", "Skip network-dependent checks (npm audit)")
|
|
324
|
+
.action((_sub, options) => securityCheck(options));
|
|
325
|
+
// NOTE: we intentionally do NOT call cli.version() — cac's built-in prints a
|
|
326
|
+
// "name/version platform node" line. We handle --version/-v manually below to
|
|
327
|
+
// output the exact "openadminjs <version>" format.
|
|
289
328
|
cli.help();
|
|
290
|
-
|
|
329
|
+
async function main() {
|
|
330
|
+
const argv = process.argv;
|
|
331
|
+
let parsed;
|
|
332
|
+
try {
|
|
333
|
+
parsed = cli.parse(argv, { run: false });
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
console.error(pc.red(error instanceof Error ? error.message : String(error)));
|
|
337
|
+
console.error(pc.dim("Run `openadminjs --help` for usage."));
|
|
338
|
+
process.exit(1);
|
|
339
|
+
}
|
|
340
|
+
if (parsed.options.version || parsed.options.v) {
|
|
341
|
+
console.log(`openadminjs ${readPackageVersion()}`);
|
|
342
|
+
process.exit(0);
|
|
343
|
+
}
|
|
344
|
+
if (parsed.options.help || parsed.options.h) {
|
|
345
|
+
cli.outputHelp();
|
|
346
|
+
process.exit(0);
|
|
347
|
+
}
|
|
348
|
+
if (!cli.matchedCommand) {
|
|
349
|
+
const requested = parsed.args[0];
|
|
350
|
+
if (requested) {
|
|
351
|
+
console.error(pc.red(`Unknown command: ${requested}`));
|
|
352
|
+
console.error(pc.dim("Run `openadminjs --help` to see available commands."));
|
|
353
|
+
process.exit(1);
|
|
354
|
+
}
|
|
355
|
+
cli.outputHelp();
|
|
356
|
+
process.exit(0);
|
|
357
|
+
}
|
|
358
|
+
try {
|
|
359
|
+
await cli.runMatchedCommand();
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
console.error(pc.red(error instanceof Error ? error.message : String(error)));
|
|
363
|
+
process.exit(1);
|
|
364
|
+
}
|
|
365
|
+
if (process.exitCode && process.exitCode !== 0)
|
|
366
|
+
process.exit(process.exitCode);
|
|
367
|
+
}
|
|
368
|
+
function isCliEntry() {
|
|
369
|
+
const entry = process.argv[1];
|
|
370
|
+
if (!entry)
|
|
371
|
+
return false;
|
|
372
|
+
const modulePath = fileURLToPath(import.meta.url);
|
|
373
|
+
try {
|
|
374
|
+
return realpathSync(resolve(entry)) === realpathSync(modulePath);
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
return resolve(entry) === modulePath;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (isCliEntry()) {
|
|
381
|
+
void main();
|
|
382
|
+
}
|
package/dist/index.test.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { modelNameToResourceSlug } from "./
|
|
3
|
-
describe("openadminjs
|
|
4
|
-
it("exposes
|
|
2
|
+
import { createProject, databaseUrl, defaultTemplateDir, modelNameToResourceSlug } from "./index.js";
|
|
3
|
+
describe("openadminjs package exports", () => {
|
|
4
|
+
it("exposes createProject and helpers from the main entry", () => {
|
|
5
|
+
expect(typeof createProject).toBe("function");
|
|
6
|
+
expect(typeof databaseUrl).toBe("function");
|
|
7
|
+
expect(typeof defaultTemplateDir).toBe("function");
|
|
5
8
|
expect(modelNameToResourceSlug("OrderItem")).toBe("order-item");
|
|
9
|
+
expect(databaseUrl("shop", "sqlite")).toBe("file:./dev.db");
|
|
6
10
|
});
|
|
7
11
|
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { DatabaseDriver } from "./create-project.js";
|
|
2
|
+
/**
|
|
3
|
+
* Transforms the (PostgreSQL-authored) Prisma schema so it is valid for the
|
|
4
|
+
* selected database provider.
|
|
5
|
+
*
|
|
6
|
+
* PostgreSQL: returned unchanged.
|
|
7
|
+
* MySQL: scalar lists (e.g. `String[]`) are unsupported, so they are stored as
|
|
8
|
+
* `Json` arrays instead. Relation lists (e.g. `Post[]`) are left intact
|
|
9
|
+
* because those reference models, not scalars.
|
|
10
|
+
* SQLite: has neither scalar lists NOR a `Json` type. Both scalar lists and
|
|
11
|
+
* `Json`/`Json?` columns become `String`/`String?`; the API's PrismaService
|
|
12
|
+
* transparently JSON-encodes/decodes those columns at runtime for SQLite
|
|
13
|
+
* (see apps/api/src/common/json-field-codec.ts).
|
|
14
|
+
*/
|
|
15
|
+
export declare function renderSchemaForProvider(schema: string, provider: DatabaseDriver): string;
|
|
16
|
+
/**
|
|
17
|
+
* Returns the datasource provider currently declared in a Prisma schema string,
|
|
18
|
+
* or undefined when it cannot be determined.
|
|
19
|
+
*/
|
|
20
|
+
export declare function schemaDatasourceProvider(schema: string): string | undefined;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** Prisma scalar types that can appear as a scalar list (`Type[]`). */
|
|
2
|
+
const SCALAR_TYPES = ["String", "Boolean", "Int", "BigInt", "Float", "Decimal", "DateTime", "Bytes", "Json"];
|
|
3
|
+
const SCALAR_LIST_RE = new RegExp(`\\b(${SCALAR_TYPES.join("|")})\\[\\]`, "g");
|
|
4
|
+
/**
|
|
5
|
+
* Transforms the (PostgreSQL-authored) Prisma schema so it is valid for the
|
|
6
|
+
* selected database provider.
|
|
7
|
+
*
|
|
8
|
+
* PostgreSQL: returned unchanged.
|
|
9
|
+
* MySQL: scalar lists (e.g. `String[]`) are unsupported, so they are stored as
|
|
10
|
+
* `Json` arrays instead. Relation lists (e.g. `Post[]`) are left intact
|
|
11
|
+
* because those reference models, not scalars.
|
|
12
|
+
* SQLite: has neither scalar lists NOR a `Json` type. Both scalar lists and
|
|
13
|
+
* `Json`/`Json?` columns become `String`/`String?`; the API's PrismaService
|
|
14
|
+
* transparently JSON-encodes/decodes those columns at runtime for SQLite
|
|
15
|
+
* (see apps/api/src/common/json-field-codec.ts).
|
|
16
|
+
*/
|
|
17
|
+
export function renderSchemaForProvider(schema, provider) {
|
|
18
|
+
if (provider === "postgresql")
|
|
19
|
+
return schema;
|
|
20
|
+
if (provider === "mysql") {
|
|
21
|
+
// Only rewrite scalar lists; relation lists use capitalized model names that
|
|
22
|
+
// are not in SCALAR_TYPES, so they never match.
|
|
23
|
+
return schema.replace(SCALAR_LIST_RE, "Json");
|
|
24
|
+
}
|
|
25
|
+
if (provider === "sqlite") {
|
|
26
|
+
// Scalar lists → String, then Json/Json? → String/String?.
|
|
27
|
+
return schema.replace(SCALAR_LIST_RE, "String").replace(/\bJson\b/g, "String");
|
|
28
|
+
}
|
|
29
|
+
return schema;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Returns the datasource provider currently declared in a Prisma schema string,
|
|
33
|
+
* or undefined when it cannot be determined.
|
|
34
|
+
*/
|
|
35
|
+
export function schemaDatasourceProvider(schema) {
|
|
36
|
+
return schema.match(/datasource\s+\w+\s*\{[^}]*?provider\s*=\s*"([^"]+)"/m)?.[1];
|
|
37
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { renderSchemaForProvider, schemaDatasourceProvider } from "./render-schema.js";
|
|
3
|
+
const SAMPLE = `datasource db {
|
|
4
|
+
provider = "postgresql"
|
|
5
|
+
url = env("DATABASE_URL")
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
model User {
|
|
9
|
+
id String @id @default(cuid())
|
|
10
|
+
posts Post[]
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
model ApiToken {
|
|
14
|
+
id String @id @default(cuid())
|
|
15
|
+
scopes String[]
|
|
16
|
+
tags String[]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
model AuditLog {
|
|
20
|
+
id String @id @default(cuid())
|
|
21
|
+
before Json?
|
|
22
|
+
after Json?
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
model Post {
|
|
26
|
+
id String @id @default(cuid())
|
|
27
|
+
}
|
|
28
|
+
`;
|
|
29
|
+
describe("renderSchemaForProvider", () => {
|
|
30
|
+
it("returns the schema unchanged for postgresql", () => {
|
|
31
|
+
expect(renderSchemaForProvider(SAMPLE, "postgresql")).toBe(SAMPLE);
|
|
32
|
+
});
|
|
33
|
+
it("converts scalar lists to Json for mysql but keeps relation lists", () => {
|
|
34
|
+
const out = renderSchemaForProvider(SAMPLE, "mysql");
|
|
35
|
+
expect(out).not.toContain("String[]");
|
|
36
|
+
expect(out).toMatch(/scopes\s+Json/);
|
|
37
|
+
expect(out).toMatch(/tags\s+Json/);
|
|
38
|
+
// relation lists reference models, not scalars — must be preserved
|
|
39
|
+
expect(out).toContain("posts Post[]");
|
|
40
|
+
});
|
|
41
|
+
it("converts scalar lists and Json to String for sqlite", () => {
|
|
42
|
+
const out = renderSchemaForProvider(SAMPLE, "sqlite");
|
|
43
|
+
expect(out).not.toContain("String[]");
|
|
44
|
+
expect(out).not.toMatch(/\bJson\b/);
|
|
45
|
+
expect(out).toMatch(/scopes\s+String/);
|
|
46
|
+
expect(out).toMatch(/tags\s+String/);
|
|
47
|
+
expect(out).toMatch(/before\s+String\?/);
|
|
48
|
+
expect(out).toMatch(/after\s+String\?/);
|
|
49
|
+
expect(out).toContain("posts Post[]");
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
describe("schemaDatasourceProvider", () => {
|
|
53
|
+
it("reads the datasource provider, not the generator provider", () => {
|
|
54
|
+
const withGenerator = `generator client {\n provider = "prisma-client-js"\n}\n\n${SAMPLE}`;
|
|
55
|
+
expect(schemaDatasourceProvider(withGenerator)).toBe("postgresql");
|
|
56
|
+
});
|
|
57
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generates a cryptographically secure secret suitable for JWT signing keys.
|
|
3
|
+
* Returns a URL-safe base64 string. 48 bytes → 64 base64url chars (~384 bits).
|
|
4
|
+
*/
|
|
5
|
+
export declare function generateSecret(bytes?: number): string;
|
|
6
|
+
/** Minimum acceptable secret length (characters). */
|
|
7
|
+
export declare const MIN_SECRET_LENGTH = 32;
|
|
8
|
+
/**
|
|
9
|
+
* Estimates Shannon entropy (bits) of a string. Used to flag low-entropy
|
|
10
|
+
* secrets such as `aaaaaaaa...` that pass a naive length check.
|
|
11
|
+
*/
|
|
12
|
+
export declare function shannonEntropyBits(value: string): number;
|
|
13
|
+
export type SecretWeakness = {
|
|
14
|
+
weak: boolean;
|
|
15
|
+
reason?: string;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Returns whether a secret is weak/predictable and why. A secret is weak when
|
|
19
|
+
* it is empty, a known placeholder, too short, or has insufficient entropy.
|
|
20
|
+
*/
|
|
21
|
+
export declare function inspectSecret(value: string | undefined, label?: string): SecretWeakness;
|
|
22
|
+
export declare function isWeakSecret(value: string | undefined): boolean;
|
|
23
|
+
export declare const MIN_PASSWORD_LENGTH = 8;
|
|
24
|
+
export declare function inspectPassword(value: string | undefined): SecretWeakness;
|