openadminjs 0.1.2 → 0.1.4
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 +40 -88
- package/apps/admin/app/plugins/page.tsx +60 -1
- package/apps/api/plugins.manifest.example.json +12 -0
- package/apps/api/src/admin/admin-ai.service.ts +36 -3
- package/apps/api/src/admin/admin-plugins.service.ts +18 -4
- package/apps/api/src/admin/dto/plugins.dto.ts +19 -1
- package/apps/api/src/app.module.ts +9 -1
- package/apps/api/src/plugins/bootstrap.ts +2 -2
- package/apps/api/src/plugins/bundled/admin-widget.plugin.ts +25 -0
- package/apps/api/src/plugins/bundled/image-optimizer.plugin.ts +22 -0
- package/apps/api/src/plugins/bundled/registry.ts +7 -1
- package/apps/api/src/plugins/bundled/seo.plugin.ts +25 -0
- package/apps/api/src/plugins/manifest.schema.test.ts +9 -1
- package/apps/api/src/plugins/manifest.schema.ts +20 -0
- package/apps/api/src/plugins/plugin-api.interceptor.ts +47 -0
- package/apps/api/src/plugins/plugin-loader.ts +34 -9
- package/apps/api/src/plugins/plugin-runtime.test.ts +24 -0
- package/apps/api/src/plugins/plugin-runtime.ts +85 -0
- package/apps/api/src/resources/resource-hooks.runner.ts +13 -6
- package/examples/README.md +2 -2
- package/examples/basic-admin/README.md +1 -1
- package/package.json +1 -1
- package/packages/cli/package.json +1 -1
- package/packages/cli/src/create-project.ts +99 -10
- package/packages/cli/src/index.ts +64 -5
- package/packages/cli/template/.env.example +5 -3
- package/packages/create-openadminjs/package.json +1 -1
- package/packages/create-openadminjs/src/index.ts +56 -4
- package/packages/create-openadminjs/src/render-files.ts +1 -1
- package/packages/create-openadminjs/template/.env.example +5 -2
- package/packages/plugin-sdk/src/hooks.ts +91 -0
- package/packages/plugin-sdk/src/index.ts +6 -1
- package/site/docs.html +63 -56
- package/site/index.html +1 -1
|
@@ -1,9 +1,23 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
|
|
3
|
+
const capabilitySchema = z.enum([
|
|
4
|
+
"db.read",
|
|
5
|
+
"db.write",
|
|
6
|
+
"resource.hooks",
|
|
7
|
+
"api.hooks",
|
|
8
|
+
"api.routes",
|
|
9
|
+
"media.pipeline",
|
|
10
|
+
"seo.extend",
|
|
11
|
+
"jobs.run",
|
|
12
|
+
"admin.ui.extend"
|
|
13
|
+
]);
|
|
14
|
+
|
|
3
15
|
export const pluginManifestEntrySchema = z
|
|
4
16
|
.object({
|
|
5
17
|
id: z.string().min(1),
|
|
6
18
|
enabled: z.boolean().optional().default(true),
|
|
19
|
+
trustMode: z.enum(["trusted", "sandboxed"]).optional().default("trusted"),
|
|
20
|
+
capabilities: z.array(capabilitySchema).optional().default([]),
|
|
7
21
|
bundled: z
|
|
8
22
|
.string()
|
|
9
23
|
.regex(/^[a-z0-9-]+$/, "bundled id must be lowercase slug")
|
|
@@ -14,6 +28,12 @@ export const pluginManifestEntrySchema = z
|
|
|
14
28
|
.regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/i, "invalid npm package name")
|
|
15
29
|
.optional(),
|
|
16
30
|
config: z.record(z.string(), z.unknown()).optional().default({}),
|
|
31
|
+
policy: z
|
|
32
|
+
.object({
|
|
33
|
+
allowedRoutes: z.array(z.string()).optional(),
|
|
34
|
+
maxJobRuntimeMs: z.number().int().positive().optional()
|
|
35
|
+
})
|
|
36
|
+
.optional(),
|
|
17
37
|
marketplace: z
|
|
18
38
|
.object({
|
|
19
39
|
listingUrl: z.string().optional(),
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
|
2
|
+
import { Observable, tap } from "rxjs";
|
|
3
|
+
import { pluginRuntime } from "./plugin-runtime";
|
|
4
|
+
|
|
5
|
+
@Injectable()
|
|
6
|
+
export class PluginApiInterceptor implements NestInterceptor {
|
|
7
|
+
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
8
|
+
if (context.getType() !== "http") return next.handle();
|
|
9
|
+
const request = context.switchToHttp().getRequest<{
|
|
10
|
+
method?: string;
|
|
11
|
+
route?: { path?: string };
|
|
12
|
+
path?: string;
|
|
13
|
+
body?: unknown;
|
|
14
|
+
query?: Record<string, unknown>;
|
|
15
|
+
user?: { id?: string; email?: string; permissions?: string[] };
|
|
16
|
+
}>();
|
|
17
|
+
const response = context.switchToHttp().getResponse<{ statusCode?: number }>();
|
|
18
|
+
const method = request.method ?? "GET";
|
|
19
|
+
const path = request.route?.path ?? request.path ?? "/";
|
|
20
|
+
const started = Date.now();
|
|
21
|
+
for (const hook of pluginRuntime.getApiHooks()) {
|
|
22
|
+
void hook.beforeRequest?.({
|
|
23
|
+
method,
|
|
24
|
+
path,
|
|
25
|
+
body: request.body,
|
|
26
|
+
query: request.query,
|
|
27
|
+
user: request.user?.id ? { id: request.user.id, email: request.user.email ?? "", permissions: request.user.permissions ?? [] } : undefined
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
return next.handle().pipe(
|
|
31
|
+
tap({
|
|
32
|
+
next: () => {
|
|
33
|
+
const durationMs = Date.now() - started;
|
|
34
|
+
for (const hook of pluginRuntime.getApiHooks()) {
|
|
35
|
+
void hook.afterRequest?.({
|
|
36
|
+
method,
|
|
37
|
+
path,
|
|
38
|
+
statusCode: response.statusCode ?? 200,
|
|
39
|
+
durationMs,
|
|
40
|
+
user: request.user?.id ? { id: request.user.id, email: request.user.email ?? "", permissions: request.user.permissions ?? [] } : undefined
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
})
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from "node:fs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
-
import type { OpenAdminPlugin, OpenAdminPluginModule, PluginRegistrationContext } from "@openadminjs/plugin-sdk";
|
|
3
|
+
import type { OpenAdminPlugin, OpenAdminPluginModule, PluginRegistrationContext, PluginSurfaceRegistry } from "@openadminjs/plugin-sdk";
|
|
4
4
|
import { Logger } from "@nestjs/common";
|
|
5
5
|
import { registerResourceHooks, unregisterResourceHooksBySource } from "../resources/resource-hooks.registry";
|
|
6
6
|
import { bundledOpenAdminPlugins } from "./bundled/registry";
|
|
7
7
|
import { getManifestCandidateStrings, toAbsoluteManifestPath } from "./manifest-path";
|
|
8
8
|
import { pluginManifestSchema, type PluginManifestEntry } from "./manifest.schema";
|
|
9
|
+
import { pluginRuntime } from "./plugin-runtime";
|
|
9
10
|
|
|
10
11
|
const log = new Logger("OpenAdminPlugins");
|
|
11
12
|
|
|
@@ -59,33 +60,57 @@ function resolveBundledPlugin(entry: PluginManifestEntry): OpenAdminPlugin {
|
|
|
59
60
|
|
|
60
61
|
function createContext(entry: PluginManifestEntry): PluginRegistrationContext {
|
|
61
62
|
const config = (entry.config ?? {}) as Record<string, unknown>;
|
|
63
|
+
const capabilities = new Set(entry.capabilities ?? []);
|
|
64
|
+
const ensureCap = (name: string) => {
|
|
65
|
+
if ((entry.trustMode ?? "trusted") === "trusted" && capabilities.size === 0) return;
|
|
66
|
+
if (!capabilities.has(name as never)) {
|
|
67
|
+
throw new Error(`Plugin "${entry.id}" attempted to use capability "${name}" but it is not declared in manifest.`);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const registerSurface = (surface: PluginSurfaceRegistry) => {
|
|
71
|
+
if (surface.resource) {
|
|
72
|
+
ensureCap("resource.hooks");
|
|
73
|
+
throw new Error('Use registerResourceHooks(resourceName, hooks) for resource lifecycle hooks.');
|
|
74
|
+
}
|
|
75
|
+
if (surface.api) {
|
|
76
|
+
if (surface.api.routes?.length) ensureCap("api.routes");
|
|
77
|
+
else ensureCap("api.hooks");
|
|
78
|
+
}
|
|
79
|
+
if (surface.media) ensureCap("media.pipeline");
|
|
80
|
+
if (surface.seo) ensureCap("seo.extend");
|
|
81
|
+
if (surface.jobs?.length) ensureCap("jobs.run");
|
|
82
|
+
if (surface.adminUi?.length) ensureCap("admin.ui.extend");
|
|
83
|
+
pluginRuntime.register(entry.id, surface);
|
|
84
|
+
};
|
|
62
85
|
return {
|
|
63
86
|
pluginId: entry.id,
|
|
64
87
|
config,
|
|
88
|
+
trustMode: entry.trustMode ?? "trusted",
|
|
89
|
+
capabilities: [...capabilities],
|
|
65
90
|
registerResourceHooks: (resourceName, hooks, options) =>
|
|
66
|
-
registerResourceHooks(resourceName, hooks, { ...options, source: entry.id })
|
|
91
|
+
registerResourceHooks(resourceName, hooks, { ...options, source: entry.id }),
|
|
92
|
+
registerSurface
|
|
67
93
|
};
|
|
68
94
|
}
|
|
69
95
|
|
|
70
96
|
/** Register hooks for one manifest entry (same as bootstrap). Throws on failure. */
|
|
71
|
-
export function applyManifestPluginEntry(entry: PluginManifestEntry): void {
|
|
97
|
+
export async function applyManifestPluginEntry(entry: PluginManifestEntry): Promise<void> {
|
|
72
98
|
if (entry.enabled === false) return;
|
|
73
99
|
const plugin: OpenAdminPlugin = entry.bundled ? resolveBundledPlugin(entry) : resolveNpmPlugin(entry);
|
|
74
100
|
const ctx = createContext(entry);
|
|
75
|
-
|
|
76
|
-
if (
|
|
77
|
-
throw new Error(`Plugin ${entry.id} must use synchronous register() at bootstrap`);
|
|
78
|
-
}
|
|
101
|
+
await plugin.register(ctx as PluginRegistrationContext);
|
|
102
|
+
if (plugin.onStart) await plugin.onStart(ctx as PluginRegistrationContext);
|
|
79
103
|
log.log(`Loaded plugin ${entry.id} (${entry.bundled ? `bundled:${entry.bundled}` : `package:${entry.package}`})`);
|
|
80
104
|
}
|
|
81
105
|
|
|
82
106
|
/** Drop all hook registrations attributed to this plugin id (before re-apply or disable). */
|
|
83
107
|
export function removeManifestPluginHooks(pluginId: string): void {
|
|
84
108
|
unregisterResourceHooksBySource(pluginId);
|
|
109
|
+
pluginRuntime.removeBySource(pluginId);
|
|
85
110
|
log.log(`Removed runtime hooks for plugin ${pluginId}`);
|
|
86
111
|
}
|
|
87
112
|
|
|
88
|
-
export function
|
|
113
|
+
export async function loadPluginsFromManifest(): Promise<void> {
|
|
89
114
|
const raw = readManifest();
|
|
90
115
|
if (!raw) {
|
|
91
116
|
log.log("No plugins.manifest.json found — skipping plugins");
|
|
@@ -100,7 +125,7 @@ export function loadPluginsFromManifestSync(): void {
|
|
|
100
125
|
for (const entry of manifest.plugins) {
|
|
101
126
|
if (entry.enabled === false) continue;
|
|
102
127
|
try {
|
|
103
|
-
applyManifestPluginEntry(entry);
|
|
128
|
+
await applyManifestPluginEntry(entry);
|
|
104
129
|
} catch (e) {
|
|
105
130
|
log.error(`Failed to load plugin ${entry.id}: ${(e as Error).message}`);
|
|
106
131
|
if (process.env.NODE_ENV === "production") throw e;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { pluginRuntime } from "./plugin-runtime";
|
|
3
|
+
|
|
4
|
+
describe("pluginRuntime", () => {
|
|
5
|
+
it("registers and removes surfaces by source", () => {
|
|
6
|
+
pluginRuntime.register(
|
|
7
|
+
"test.plugin",
|
|
8
|
+
{
|
|
9
|
+
seo: {
|
|
10
|
+
metadata: () => ({ title: "x" })
|
|
11
|
+
},
|
|
12
|
+
jobs: [{ name: "test-job", handler: () => "ok" }]
|
|
13
|
+
},
|
|
14
|
+
"posts"
|
|
15
|
+
);
|
|
16
|
+
expect(pluginRuntime.getSeoHooks().length).toBeGreaterThan(0);
|
|
17
|
+
expect(pluginRuntime.getJobs().some((job) => job.name === "test-job")).toBe(true);
|
|
18
|
+
|
|
19
|
+
pluginRuntime.removeBySource("test.plugin");
|
|
20
|
+
|
|
21
|
+
expect(pluginRuntime.getSeoHooks().length).toBe(0);
|
|
22
|
+
expect(pluginRuntime.getJobs().some((job) => job.name === "test-job")).toBe(false);
|
|
23
|
+
});
|
|
24
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AdminUiExtension,
|
|
3
|
+
ApiHooks,
|
|
4
|
+
JobHandler,
|
|
5
|
+
MediaHooks,
|
|
6
|
+
PluginSurfaceRegistry,
|
|
7
|
+
ResourceLifecycleHooks,
|
|
8
|
+
SeoHooks
|
|
9
|
+
} from "@openadminjs/plugin-sdk";
|
|
10
|
+
|
|
11
|
+
type SurfaceEntry<T> = {
|
|
12
|
+
source: string;
|
|
13
|
+
value: T;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
class PluginRuntimeBus {
|
|
17
|
+
private readonly resourceHooks = new Map<string, SurfaceEntry<ResourceLifecycleHooks>[]>();
|
|
18
|
+
private readonly apiHooks: SurfaceEntry<ApiHooks>[] = [];
|
|
19
|
+
private readonly mediaHooks: SurfaceEntry<MediaHooks>[] = [];
|
|
20
|
+
private readonly seoHooks: SurfaceEntry<SeoHooks>[] = [];
|
|
21
|
+
private readonly jobs: SurfaceEntry<JobHandler>[] = [];
|
|
22
|
+
private readonly adminUi: SurfaceEntry<AdminUiExtension>[] = [];
|
|
23
|
+
|
|
24
|
+
register(source: string, surface: PluginSurfaceRegistry, resourceName?: string): void {
|
|
25
|
+
if (surface.resource && resourceName) {
|
|
26
|
+
const chain = this.resourceHooks.get(resourceName) ?? [];
|
|
27
|
+
chain.push({ source, value: surface.resource });
|
|
28
|
+
this.resourceHooks.set(resourceName, chain);
|
|
29
|
+
}
|
|
30
|
+
if (surface.api) this.apiHooks.push({ source, value: surface.api });
|
|
31
|
+
if (surface.media) this.mediaHooks.push({ source, value: surface.media });
|
|
32
|
+
if (surface.seo) this.seoHooks.push({ source, value: surface.seo });
|
|
33
|
+
if (surface.jobs) {
|
|
34
|
+
for (const handler of surface.jobs) this.jobs.push({ source, value: handler });
|
|
35
|
+
}
|
|
36
|
+
if (surface.adminUi) {
|
|
37
|
+
for (const extension of surface.adminUi) this.adminUi.push({ source, value: extension });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
removeBySource(source: string): void {
|
|
42
|
+
for (const [name, entries] of this.resourceHooks.entries()) {
|
|
43
|
+
const filtered = entries.filter((entry) => entry.source !== source);
|
|
44
|
+
if (filtered.length === 0) this.resourceHooks.delete(name);
|
|
45
|
+
else this.resourceHooks.set(name, filtered);
|
|
46
|
+
}
|
|
47
|
+
this.removeInPlace(this.apiHooks, source);
|
|
48
|
+
this.removeInPlace(this.mediaHooks, source);
|
|
49
|
+
this.removeInPlace(this.seoHooks, source);
|
|
50
|
+
this.removeInPlace(this.jobs, source);
|
|
51
|
+
this.removeInPlace(this.adminUi, source);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
getResourceHookChain(resourceName: string): ResourceLifecycleHooks[] {
|
|
55
|
+
return (this.resourceHooks.get(resourceName) ?? []).map((entry) => entry.value);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
getApiHooks(): ApiHooks[] {
|
|
59
|
+
return this.apiHooks.map((item) => item.value);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
getMediaHooks(): MediaHooks[] {
|
|
63
|
+
return this.mediaHooks.map((item) => item.value);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
getSeoHooks(): SeoHooks[] {
|
|
67
|
+
return this.seoHooks.map((item) => item.value);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
getJobs(): JobHandler[] {
|
|
71
|
+
return this.jobs.map((item) => item.value);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
getAdminUiExtensions(): AdminUiExtension[] {
|
|
75
|
+
return this.adminUi.map((item) => item.value);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private removeInPlace<T>(list: SurfaceEntry<T>[], source: string): void {
|
|
79
|
+
for (let i = list.length - 1; i >= 0; i -= 1) {
|
|
80
|
+
if (list[i]?.source === source) list.splice(i, 1);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export const pluginRuntime = new PluginRuntimeBus();
|
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import type { ResourceConfig } from "@openadminjs/core";
|
|
2
2
|
import type { ResourceHookUser } from "./resource-hooks.registry";
|
|
3
3
|
import { getResourceHookChain } from "./resource-hooks.registry";
|
|
4
|
+
import { pluginRuntime } from "../plugins/plugin-runtime";
|
|
5
|
+
|
|
6
|
+
function mergedHookChain(resourceName: string) {
|
|
7
|
+
const coreChain = getResourceHookChain(resourceName).map((entry) => entry.hooks);
|
|
8
|
+
const pluginChain = pluginRuntime.getResourceHookChain(resourceName);
|
|
9
|
+
return [...coreChain, ...pluginChain];
|
|
10
|
+
}
|
|
4
11
|
|
|
5
12
|
export async function runBeforeCreate(
|
|
6
13
|
resourceName: string,
|
|
@@ -10,7 +17,7 @@ export async function runBeforeCreate(
|
|
|
10
17
|
data: Record<string, unknown>
|
|
11
18
|
): Promise<void> {
|
|
12
19
|
const ctx = { resource, resourceName, user, prisma, data };
|
|
13
|
-
for (const
|
|
20
|
+
for (const hooks of mergedHookChain(resourceName)) {
|
|
14
21
|
await hooks.beforeCreate?.(ctx);
|
|
15
22
|
}
|
|
16
23
|
}
|
|
@@ -24,7 +31,7 @@ export async function runAfterCreate(
|
|
|
24
31
|
record: unknown
|
|
25
32
|
): Promise<void> {
|
|
26
33
|
const ctx = { resource, resourceName, user, prisma, data, record };
|
|
27
|
-
for (const
|
|
34
|
+
for (const hooks of mergedHookChain(resourceName)) {
|
|
28
35
|
await hooks.afterCreate?.(ctx);
|
|
29
36
|
}
|
|
30
37
|
}
|
|
@@ -38,7 +45,7 @@ export async function runBeforeUpdate(
|
|
|
38
45
|
data: Record<string, unknown>
|
|
39
46
|
): Promise<void> {
|
|
40
47
|
const ctx = { resource, resourceName, user, prisma, id, data };
|
|
41
|
-
for (const
|
|
48
|
+
for (const hooks of mergedHookChain(resourceName)) {
|
|
42
49
|
await hooks.beforeUpdate?.(ctx);
|
|
43
50
|
}
|
|
44
51
|
}
|
|
@@ -54,7 +61,7 @@ export async function runAfterUpdate(
|
|
|
54
61
|
record: unknown
|
|
55
62
|
): Promise<void> {
|
|
56
63
|
const ctx = { resource, resourceName, user, prisma, id, data, before, record };
|
|
57
|
-
for (const
|
|
64
|
+
for (const hooks of mergedHookChain(resourceName)) {
|
|
58
65
|
await hooks.afterUpdate?.(ctx);
|
|
59
66
|
}
|
|
60
67
|
}
|
|
@@ -67,7 +74,7 @@ export async function runBeforeDelete(
|
|
|
67
74
|
id: string
|
|
68
75
|
): Promise<void> {
|
|
69
76
|
const ctx = { resource, resourceName, user, prisma, id };
|
|
70
|
-
for (const
|
|
77
|
+
for (const hooks of mergedHookChain(resourceName)) {
|
|
71
78
|
await hooks.beforeDelete?.(ctx);
|
|
72
79
|
}
|
|
73
80
|
}
|
|
@@ -80,7 +87,7 @@ export async function runAfterDelete(
|
|
|
80
87
|
id: string
|
|
81
88
|
): Promise<void> {
|
|
82
89
|
const ctx = { resource, resourceName, user, prisma, id };
|
|
83
|
-
for (const
|
|
90
|
+
for (const hooks of mergedHookChain(resourceName)) {
|
|
84
91
|
await hooks.afterDelete?.(ctx);
|
|
85
92
|
}
|
|
86
93
|
}
|
package/examples/README.md
CHANGED
|
@@ -75,6 +75,6 @@ Use an automation token (`NPM_TOKEN`) in GitHub Actions with `npm publish` in a
|
|
|
75
75
|
|
|
76
76
|
---
|
|
77
77
|
|
|
78
|
-
If you only want to **
|
|
78
|
+
If you only want to **start a new project** from npm (not publish), use:
|
|
79
79
|
|
|
80
|
-
`
|
|
80
|
+
`npx openadminjs create my-app`.
|
|
@@ -14,7 +14,7 @@ Minimal generated OpenAdminJS project with users, roles, posts, files, audit log
|
|
|
14
14
|
|
|
15
15
|
### Merge into your app
|
|
16
16
|
|
|
17
|
-
1. Run `openadminjs create` (or use your existing app).
|
|
17
|
+
1. Run `npx openadminjs create my-app` (or use your existing app).
|
|
18
18
|
2. Append `prisma/models.fragment.prisma` to `prisma/schema.prisma`.
|
|
19
19
|
3. Copy `src/resources/*.ts` into `apps/api/src/resources/`.
|
|
20
20
|
4. Import resources in `registry.ts` and add them to the `resources` array (see `basicExampleResources` in `src/index.ts`).
|
package/package.json
CHANGED
|
@@ -10,7 +10,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
|
10
10
|
const { copySync, ensureDirSync, readFileSync, writeFileSync } = fsExtra;
|
|
11
11
|
|
|
12
12
|
export type PackageManager = "pnpm" | "npm" | "yarn";
|
|
13
|
-
export type DatabaseDriver = "postgresql";
|
|
13
|
+
export type DatabaseDriver = "postgresql" | "mysql" | "sqlite";
|
|
14
14
|
|
|
15
15
|
export type CreateProjectOptions = {
|
|
16
16
|
projectName?: string;
|
|
@@ -19,6 +19,12 @@ export type CreateProjectOptions = {
|
|
|
19
19
|
database?: DatabaseDriver;
|
|
20
20
|
superadminEmail?: string;
|
|
21
21
|
superadminPassword?: string;
|
|
22
|
+
databaseUrl?: string;
|
|
23
|
+
redisUrl?: string;
|
|
24
|
+
jwtSecret?: string;
|
|
25
|
+
jwtRefreshSecret?: string;
|
|
26
|
+
adminOrigin?: string;
|
|
27
|
+
apiPort?: string;
|
|
22
28
|
git?: boolean;
|
|
23
29
|
install?: boolean;
|
|
24
30
|
templateDir?: string;
|
|
@@ -36,7 +42,7 @@ export type CreateProjectResult = {
|
|
|
36
42
|
};
|
|
37
43
|
|
|
38
44
|
const placeholderPattern =
|
|
39
|
-
/__APP_NAME__|__PACKAGE_NAME__|__DATABASE_URL__|__DATABASE_PROVIDER__/g;
|
|
45
|
+
/__APP_NAME__|__PACKAGE_NAME__|__DATABASE_URL__|__DATABASE_PROVIDER__|__REDIS_URL__|__JWT_SECRET__|__JWT_REFRESH_SECRET__|__ADMIN_ORIGIN__|__API_PORT__/g;
|
|
40
46
|
|
|
41
47
|
export function toPackageName(input: string): string {
|
|
42
48
|
return input
|
|
@@ -54,7 +60,10 @@ function databaseUrl(packageName: string, database: DatabaseDriver): string {
|
|
|
54
60
|
if (database === "postgresql") {
|
|
55
61
|
return `postgresql://openadminjs:openadminjs@localhost:5432/${packageName}?schema=public`;
|
|
56
62
|
}
|
|
57
|
-
|
|
63
|
+
if (database === "mysql") {
|
|
64
|
+
return `mysql://openadminjs:openadminjs@localhost:3306/${packageName}`;
|
|
65
|
+
}
|
|
66
|
+
return "file:./prisma/dev.db";
|
|
58
67
|
}
|
|
59
68
|
|
|
60
69
|
function renderFile(file: string, replacements: Record<string, string>): void {
|
|
@@ -96,7 +105,12 @@ export function createProject(options: Required<CreateProjectOptions>): CreatePr
|
|
|
96
105
|
__APP_NAME__: appName,
|
|
97
106
|
__PACKAGE_NAME__: packageName,
|
|
98
107
|
__DATABASE_PROVIDER__: options.database,
|
|
99
|
-
__DATABASE_URL__: databaseUrl
|
|
108
|
+
__DATABASE_URL__: options.databaseUrl,
|
|
109
|
+
__REDIS_URL__: options.redisUrl,
|
|
110
|
+
__JWT_SECRET__: options.jwtSecret,
|
|
111
|
+
__JWT_REFRESH_SECRET__: options.jwtRefreshSecret,
|
|
112
|
+
__ADMIN_ORIGIN__: options.adminOrigin,
|
|
113
|
+
__API_PORT__: options.apiPort
|
|
100
114
|
});
|
|
101
115
|
|
|
102
116
|
if (options.git) {
|
|
@@ -122,8 +136,9 @@ export function createProject(options: Required<CreateProjectOptions>): CreatePr
|
|
|
122
136
|
|
|
123
137
|
export function printNextSteps(result: CreateProjectResult): void {
|
|
124
138
|
const pm = result.packageManager;
|
|
139
|
+
const installStep = result.install ? "" : `\n ${pm} install`;
|
|
125
140
|
outro(
|
|
126
|
-
`${pc.green("Project created.")}\n\nNext steps:\n cd ${result.appName}
|
|
141
|
+
`${pc.green("Project created.")}\n\nNext steps:\n cd ${result.appName}${installStep}\n docker compose up -d\n ${pm} db:migrate\n ${pm} db:seed\n ${pm} dev\n\nAdmin: http://localhost:3000\nAPI: http://localhost:4000\nDocs: http://localhost:4000/api/docs\n\nSuperadmin: ${result.superadminEmail} / <your password>`
|
|
127
142
|
);
|
|
128
143
|
}
|
|
129
144
|
|
|
@@ -162,7 +177,11 @@ export async function createProjectInteractive(options: CreateProjectOptions = {
|
|
|
162
177
|
options.database ??
|
|
163
178
|
(await select<DatabaseDriver>({
|
|
164
179
|
message: "Database",
|
|
165
|
-
options: [
|
|
180
|
+
options: [
|
|
181
|
+
{ value: "postgresql", label: "PostgreSQL" },
|
|
182
|
+
{ value: "mysql", label: "MySQL" },
|
|
183
|
+
{ value: "sqlite", label: "SQLite" }
|
|
184
|
+
],
|
|
166
185
|
initialValue: "postgresql"
|
|
167
186
|
}));
|
|
168
187
|
if (isCancel(database)) {
|
|
@@ -199,18 +218,82 @@ export async function createProjectInteractive(options: CreateProjectOptions = {
|
|
|
199
218
|
return undefined;
|
|
200
219
|
}
|
|
201
220
|
|
|
202
|
-
const
|
|
203
|
-
|
|
221
|
+
const selectedDatabaseUrl =
|
|
222
|
+
options.databaseUrl ??
|
|
223
|
+
(await text({
|
|
224
|
+
message: "Database URL",
|
|
225
|
+
defaultValue: databaseUrl(toPackageName(String(projectName)), database)
|
|
226
|
+
}));
|
|
227
|
+
if (isCancel(selectedDatabaseUrl)) {
|
|
228
|
+
cancel("Cancelled");
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const redisUrl =
|
|
233
|
+
options.redisUrl ??
|
|
234
|
+
(await text({
|
|
235
|
+
message: "Redis URL (optional for queues)",
|
|
236
|
+
defaultValue: "redis://localhost:6379"
|
|
237
|
+
}));
|
|
238
|
+
if (isCancel(redisUrl)) {
|
|
239
|
+
cancel("Cancelled");
|
|
240
|
+
return undefined;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const jwtSecret =
|
|
244
|
+
options.jwtSecret ??
|
|
245
|
+
(await text({
|
|
246
|
+
message: "JWT secret",
|
|
247
|
+
defaultValue: "change-me-to-a-long-random-secret",
|
|
248
|
+
placeholder: "at least 32 chars recommended"
|
|
249
|
+
}));
|
|
250
|
+
if (isCancel(jwtSecret)) {
|
|
251
|
+
cancel("Cancelled");
|
|
252
|
+
return undefined;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const jwtRefreshSecret =
|
|
256
|
+
options.jwtRefreshSecret ??
|
|
257
|
+
(await text({
|
|
258
|
+
message: "JWT refresh secret",
|
|
259
|
+
defaultValue: "change-me-too",
|
|
260
|
+
placeholder: "at least 32 chars recommended"
|
|
261
|
+
}));
|
|
262
|
+
if (isCancel(jwtRefreshSecret)) {
|
|
263
|
+
cancel("Cancelled");
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const adminOrigin =
|
|
268
|
+
options.adminOrigin ??
|
|
269
|
+
(await text({
|
|
270
|
+
message: "Admin origin",
|
|
271
|
+
defaultValue: "http://localhost:3000"
|
|
272
|
+
}));
|
|
273
|
+
if (isCancel(adminOrigin)) {
|
|
274
|
+
cancel("Cancelled");
|
|
275
|
+
return undefined;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const apiPort =
|
|
279
|
+
options.apiPort ??
|
|
280
|
+
(await text({
|
|
281
|
+
message: "API port",
|
|
282
|
+
defaultValue: "4000"
|
|
283
|
+
}));
|
|
284
|
+
if (isCancel(apiPort)) {
|
|
204
285
|
cancel("Cancelled");
|
|
205
286
|
return undefined;
|
|
206
287
|
}
|
|
207
288
|
|
|
208
|
-
const
|
|
209
|
-
if (isCancel(
|
|
289
|
+
const git = options.git ?? (await confirm({ message: "Initialize git?", initialValue: true }));
|
|
290
|
+
if (isCancel(git)) {
|
|
210
291
|
cancel("Cancelled");
|
|
211
292
|
return undefined;
|
|
212
293
|
}
|
|
213
294
|
|
|
295
|
+
const install = options.install ?? true;
|
|
296
|
+
|
|
214
297
|
const result = createProject({
|
|
215
298
|
projectName: String(projectName),
|
|
216
299
|
cwd: options.cwd ?? process.cwd(),
|
|
@@ -218,6 +301,12 @@ export async function createProjectInteractive(options: CreateProjectOptions = {
|
|
|
218
301
|
database,
|
|
219
302
|
superadminEmail: String(superadminEmail),
|
|
220
303
|
superadminPassword: String(superadminPassword),
|
|
304
|
+
databaseUrl: String(selectedDatabaseUrl),
|
|
305
|
+
redisUrl: String(redisUrl),
|
|
306
|
+
jwtSecret: String(jwtSecret),
|
|
307
|
+
jwtRefreshSecret: String(jwtRefreshSecret),
|
|
308
|
+
adminOrigin: String(adminOrigin),
|
|
309
|
+
apiPort: String(apiPort),
|
|
221
310
|
git,
|
|
222
311
|
install,
|
|
223
312
|
templateDir: options.templateDir ?? defaultTemplateDir()
|
|
@@ -67,6 +67,24 @@ function generateResource(modelName: string, options: { force?: boolean }): void
|
|
|
67
67
|
console.log(pc.green(`Created ${target}`));
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
function generatePlugin(pluginId: string, options: { force?: boolean }): void {
|
|
71
|
+
const safeId = pluginId.trim().toLowerCase().replace(/[^a-z0-9.-]+/g, "-");
|
|
72
|
+
const slug = safeId.replace(/\./g, "-");
|
|
73
|
+
const targetDir = join(process.cwd(), "apps/api/src/plugins/custom");
|
|
74
|
+
const target = join(targetDir, `${slug}.plugin.ts`);
|
|
75
|
+
if (existsSync(target) && !options.force) {
|
|
76
|
+
console.error(pc.red(`${target} already exists. Use --force to overwrite.`));
|
|
77
|
+
process.exitCode = 1;
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
mkdirSync(targetDir, { recursive: true });
|
|
81
|
+
writeFileSync(
|
|
82
|
+
target,
|
|
83
|
+
`import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";\n\nexport const ${slug.replace(/-([a-z])/g, (_, c) => c.toUpperCase())}Plugin: OpenAdminPlugin = {\n id: "${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`
|
|
84
|
+
);
|
|
85
|
+
console.log(pc.green(`Created ${target}`));
|
|
86
|
+
}
|
|
87
|
+
|
|
70
88
|
cli.command("dev", "Start API and admin apps").action(() => runScript("dev"));
|
|
71
89
|
cli.command("create [projectName]", "Create a new OpenAdminJS project").action(async (projectName?: string) => {
|
|
72
90
|
try {
|
|
@@ -78,11 +96,52 @@ cli.command("create [projectName]", "Create a new OpenAdminJS project").action(a
|
|
|
78
96
|
});
|
|
79
97
|
cli.command("build", "Build all workspaces").action(() => runScript("build"));
|
|
80
98
|
cli.command("start", "Start production apps").action(() => runScript("start"));
|
|
81
|
-
cli
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
99
|
+
cli
|
|
100
|
+
.command("db <action>", "Run database helper commands")
|
|
101
|
+
.action((action?: string) => {
|
|
102
|
+
switch (action) {
|
|
103
|
+
case "migrate":
|
|
104
|
+
console.log("Run: pnpm --filter @openadminjs/api prisma migrate dev");
|
|
105
|
+
return;
|
|
106
|
+
case "seed":
|
|
107
|
+
console.log("Run: pnpm --filter @openadminjs/api prisma db seed");
|
|
108
|
+
return;
|
|
109
|
+
case "studio":
|
|
110
|
+
console.log("Run: pnpm --filter @openadminjs/api prisma studio");
|
|
111
|
+
return;
|
|
112
|
+
default:
|
|
113
|
+
console.error(pc.red("Unknown db action. Use: migrate, seed, studio."));
|
|
114
|
+
process.exitCode = 1;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
function runGenerateCommand(kind: string | undefined, name: string | undefined, options: { force?: boolean }): void {
|
|
119
|
+
if (!kind || !name) {
|
|
120
|
+
console.error(pc.red("Usage: openadminjs generate <resource|plugin> <name> [--force]"));
|
|
121
|
+
process.exitCode = 1;
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (kind === "resource") {
|
|
125
|
+
generateResource(name, options);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (kind === "plugin") {
|
|
129
|
+
generatePlugin(name, options);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
console.error(pc.red(`Unknown generate kind: ${kind}. Use resource or plugin.`));
|
|
133
|
+
process.exitCode = 1;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
cli
|
|
137
|
+
.command("generate <kind> <name>", "Generate resource or plugin starter")
|
|
138
|
+
.option("--force", "Overwrite existing file")
|
|
139
|
+
.action(runGenerateCommand);
|
|
140
|
+
|
|
141
|
+
cli
|
|
142
|
+
.command("make <kind> <name>", "Alias for generate")
|
|
143
|
+
.option("--force", "Overwrite existing file")
|
|
144
|
+
.action(runGenerateCommand);
|
|
86
145
|
cli.command("doctor", "Check generated project health").action(doctor);
|
|
87
146
|
cli.command("security", "Run security checklist").action(securityCheck);
|
|
88
147
|
cli.command("security check", "Run security checklist").action(securityCheck);
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
DATABASE_URL=__DATABASE_URL__
|
|
2
|
-
REDIS_URL=
|
|
3
|
-
JWT_SECRET=
|
|
4
|
-
JWT_REFRESH_SECRET=
|
|
2
|
+
REDIS_URL=__REDIS_URL__
|
|
3
|
+
JWT_SECRET=__JWT_SECRET__
|
|
4
|
+
JWT_REFRESH_SECRET=__JWT_REFRESH_SECRET__
|
|
5
|
+
ADMIN_ORIGIN=__ADMIN_ORIGIN__
|
|
6
|
+
API_PORT=__API_PORT__
|