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.
Files changed (34) hide show
  1. package/README.md +40 -88
  2. package/apps/admin/app/plugins/page.tsx +60 -1
  3. package/apps/api/plugins.manifest.example.json +12 -0
  4. package/apps/api/src/admin/admin-ai.service.ts +36 -3
  5. package/apps/api/src/admin/admin-plugins.service.ts +18 -4
  6. package/apps/api/src/admin/dto/plugins.dto.ts +19 -1
  7. package/apps/api/src/app.module.ts +9 -1
  8. package/apps/api/src/plugins/bootstrap.ts +2 -2
  9. package/apps/api/src/plugins/bundled/admin-widget.plugin.ts +25 -0
  10. package/apps/api/src/plugins/bundled/image-optimizer.plugin.ts +22 -0
  11. package/apps/api/src/plugins/bundled/registry.ts +7 -1
  12. package/apps/api/src/plugins/bundled/seo.plugin.ts +25 -0
  13. package/apps/api/src/plugins/manifest.schema.test.ts +9 -1
  14. package/apps/api/src/plugins/manifest.schema.ts +20 -0
  15. package/apps/api/src/plugins/plugin-api.interceptor.ts +47 -0
  16. package/apps/api/src/plugins/plugin-loader.ts +34 -9
  17. package/apps/api/src/plugins/plugin-runtime.test.ts +24 -0
  18. package/apps/api/src/plugins/plugin-runtime.ts +85 -0
  19. package/apps/api/src/resources/resource-hooks.runner.ts +13 -6
  20. package/examples/README.md +2 -2
  21. package/examples/basic-admin/README.md +1 -1
  22. package/package.json +1 -1
  23. package/packages/cli/package.json +1 -1
  24. package/packages/cli/src/create-project.ts +99 -10
  25. package/packages/cli/src/index.ts +64 -5
  26. package/packages/cli/template/.env.example +5 -3
  27. package/packages/create-openadminjs/package.json +1 -1
  28. package/packages/create-openadminjs/src/index.ts +56 -4
  29. package/packages/create-openadminjs/src/render-files.ts +1 -1
  30. package/packages/create-openadminjs/template/.env.example +5 -2
  31. package/packages/plugin-sdk/src/hooks.ts +91 -0
  32. package/packages/plugin-sdk/src/index.ts +6 -1
  33. package/site/docs.html +63 -56
  34. package/site/index.html +1 -1
package/README.md CHANGED
@@ -2,30 +2,28 @@
2
2
 
3
3
  OpenAdminJS is an open-source, resource-driven admin platform for the Node.js ecosystem, built with Nest.js, Prisma, PostgreSQL, Next.js, TailwindCSS and shadcn/ui.
4
4
 
5
- ![OpenAdminJS logo](./site/assets/brand/openadminjs-logo-new.png)
5
+ ![OpenAdminJS logo](https://js-senpai.github.io/open-admin-js/assets/brand/openadminjs-logo-new.png)
6
6
 
7
- ## Quick start (this repository)
7
+ ## Quick start (for package users)
8
8
 
9
- Follow these steps in order the first time you clone the repo.
9
+ Full documentation: [https://js-senpai.github.io/open-admin-js/docs.html](https://js-senpai.github.io/open-admin-js/docs.html)
10
10
 
11
- ### 1. Prerequisites
12
-
13
- - **Node.js** 22+ (CI uses 22; newer LTS usually works).
14
- - **pnpm** 9 (`packageManager` in root `package.json`).
15
- - **PostgreSQL** reachable from your machine (local or Docker).
16
- - **Redis** (optional): queues and some health checks use `REDIS_URL`; the API can start without it for basic admin usage.
17
-
18
- ### 2. Install dependencies
11
+ ### 1. Create a new project
19
12
 
20
13
  ```bash
21
- pnpm install
14
+ npx openadminjs create my-app
15
+ cd my-app
22
16
  ```
23
17
 
24
- ### 3. Configure the API environment
18
+ `npx` runs the single `openadminjs` package and scaffolds the project with dependencies installed automatically.
19
+ During scaffolding, you can choose the database driver from a list (PostgreSQL, MySQL, or SQLite), and the CLI fills `DATABASE_URL` for you.
25
20
 
26
- Create **`apps/api/.env`** (this file is gitignored). The API loads, in order, **`<repo>/.env`** and **`apps/api/.env`** so you can keep secrets next to the API or at the repo root.
21
+ ### 2. Configure environment
27
22
 
28
- Minimal example:
23
+ The scaffold wizard asks for database access and key env values (`DATABASE_URL`, `REDIS_URL`, JWT secrets, `ADMIN_ORIGIN`, `API_PORT`) and writes them into `.env.example`.
24
+ Copy it to `.env` in the generated project, then adjust as needed.
25
+
26
+ Minimal `.env` example:
29
27
 
30
28
  ```env
31
29
  NODE_ENV=development
@@ -36,9 +34,6 @@ JWT_REFRESH_SECRET=another-long-random-string
36
34
  ADMIN_ORIGIN=http://localhost:3000
37
35
  ```
38
36
 
39
- - **`JWT_SECRET`** is required for login. If it is missing, sign-in fails (previously surfaced as a generic “Internal server error”).
40
- - **`DATABASE_URL`** must point at an existing database the user can create schemas in.
41
-
42
37
  Optional:
43
38
 
44
39
  ```env
@@ -46,34 +41,14 @@ REDIS_URL=redis://localhost:6379
46
41
  OPENADMIN_PLUGIN_PNPM_INSTALL=0
47
42
  ```
48
43
 
49
- ### 4. Apply database schema and seed demo data
50
-
51
- From the repository root:
44
+ ### 3. Prepare database and run
52
45
 
53
46
  ```bash
54
47
  pnpm db:migrate
55
48
  pnpm db:seed
56
- ```
57
-
58
- `db:migrate` runs Prisma migrations against `DATABASE_URL`.
59
- `db:seed` creates permissions, roles, and demo users (including the admin below).
60
-
61
- ### 5. Configure the admin UI (optional)
62
-
63
- The admin defaults to **`http://localhost:4000`** for the API. If your API runs elsewhere, create **`apps/admin/.env.local`**:
64
-
65
- ```env
66
- NEXT_PUBLIC_API_URL=http://localhost:4000
67
- ```
68
-
69
- ### 6. Run everything in development
70
-
71
- ```bash
72
49
  pnpm dev
73
50
  ```
74
51
 
75
- This starts the API and the admin app in parallel (see root `package.json` `dev` script). To run the public `apps/web` app as well, use `pnpm --filter @openadminjs/web dev` in another terminal.
76
-
77
52
  Typical URLs:
78
53
 
79
54
  | App | URL |
@@ -83,67 +58,51 @@ Typical URLs:
83
58
  | API Swagger | http://localhost:4000/api/docs |
84
59
  | Web (demo) | http://localhost:3001 |
85
60
 
86
- ### 7. Sign in
61
+ ### 4. Sign in
87
62
 
88
63
  After a successful seed:
89
64
 
90
65
  - **Email:** `openadminjs@proton.me`
91
66
  - **Password:** `password`
92
67
 
93
- ### 8. Resources and data
94
-
95
- - **Built-in resources** live as Nest modules under `apps/api/src/resources` (e.g. `*.resource.ts`). They define list/create/edit metadata and permissions for Prisma models.
96
- - **Add a resource for a Prisma model** from the repo root (requires the CLI package in the workspace):
97
-
98
- ```bash
99
- pnpm exec openadminjs generate resource YourModelName
100
- ```
68
+ ## MVP scope
101
69
 
102
- This writes a starter file under `apps/api/src/resources`. Adjust fields, labels, and permissions, then restart or rely on hot reload depending on your setup.
70
+ - Resource-driven admin metadata with safe defaults.
71
+ - Auth, RBAC contracts, generic CRUD API, audit log and file/settings modules.
72
+ - Next.js admin shell with login, dashboard, resource screens and operational pages.
73
+ - Generated app `apps/web` for public frontend pages and SEO.
74
+ - CLI: `dev`, `build`, `db migrate`, `db seed`, `generate resource`, `doctor`, `security check`.
103
75
 
104
- - **Fill tables with data** either through the admin UI (Resources menu) or with Prisma scripts, SQL, or your own seed files.
76
+ ## Plugin Platform
105
77
 
106
- ### 9. Static marketing site
78
+ OpenAdminJS now uses a broad extension model (no legacy compatibility layer). Plugins can register multiple surfaces through `@openadminjs/plugin-sdk`:
107
79
 
108
- The hand-written site lives under **`site/`**. Sanity check:
80
+ - `resource` hooks (CRUD lifecycle)
81
+ - `api` hooks/routes
82
+ - `media` pipeline (upload transforms)
83
+ - `seo` metadata/sitemap contributors
84
+ - `jobs` handlers
85
+ - `adminUi` extensions (menus/pages/widgets/actions)
109
86
 
110
- ```bash
111
- pnpm site:check
112
- ```
87
+ Plugins are controlled by manifest capabilities and trust mode (`trusted` / `sandboxed`) in `apps/api/plugins.manifest.json`.
113
88
 
114
- ### 10. Quality commands
89
+ ### Capability matrix
115
90
 
116
- ```bash
117
- pnpm lint
118
- pnpm typecheck
119
- pnpm test
120
- pnpm build
121
- pnpm security:check
122
- pnpm e2e
123
- ```
91
+ - `resource.hooks` — CRUD lifecycle hooks per resource.
92
+ - `api.hooks` / `api.routes` — request lifecycle hooks and custom API endpoints.
93
+ - `media.pipeline` — file/image transform pipeline.
94
+ - `seo.extend` — metadata + sitemap contributors.
95
+ - `jobs.run` — background job handlers.
96
+ - `admin.ui.extend` — admin menu/page/widget/action extensions.
124
97
 
125
- `pnpm e2e` runs an auth regression scenario for admin session handling (invalid token + refresh fallback) and then the repository smoke checks.
98
+ `trusted` mode may run with broad access; `sandboxed` mode should explicitly declare only required capabilities.
126
99
 
127
- ## Scaffold a new project from npm
100
+ Generate a starter plugin:
128
101
 
129
102
  ```bash
130
- npm create openadminjs@latest my-app
131
- cd my-app
132
- pnpm db:migrate
133
- pnpm db:seed
134
- pnpm dev
103
+ pnpm exec openadminjs generate plugin com.example.my-plugin
135
104
  ```
136
105
 
137
- Use the same demo credentials unless you change the seed.
138
-
139
- ## MVP scope
140
-
141
- - Resource-driven admin metadata with safe defaults.
142
- - Auth, RBAC contracts, generic CRUD API, audit log and file/settings modules.
143
- - Next.js admin shell with login, dashboard, resource screens and operational pages.
144
- - Generated app `apps/web` for public frontend pages and SEO.
145
- - CLI: `dev`, `build`, `db migrate`, `db seed`, `generate resource`, `doctor`, `security check`.
146
-
147
106
  ### Optional queue setup
148
107
 
149
108
  Set `REDIS_URL` in your environment to enable queue processing (example: `redis://localhost:6379`).
@@ -152,13 +111,6 @@ Set `REDIS_URL` in your environment to enable queue processing (example: `redis:
152
111
 
153
112
  OpenAdminJS is community-powered and stays free thanks to partner support.
154
113
 
155
- <!-- - Nebula Systems (example)
156
- - Arcbyte (example)
157
- - Vertex Labs (example)
158
- - Gridstack (example)
159
- - Orbitlab (example)
160
- - Pulseforge (example) -->
161
-
162
114
  Want to become a partner and place your logo in the project materials?
163
115
  Email us at `openadminjs@proton.me`.
164
116
 
@@ -19,12 +19,21 @@ type PluginRow = {
19
19
  bundled?: string;
20
20
  package?: string;
21
21
  config?: Record<string, unknown>;
22
+ trustMode?: "trusted" | "sandboxed";
23
+ capabilities?: string[];
22
24
  };
23
25
 
24
26
  type PluginsState = {
25
27
  manifestPath: string;
26
28
  bundledAvailable: string[];
27
29
  plugins: PluginRow[];
30
+ runtime?: {
31
+ adminUiExtensions: number;
32
+ jobs: number;
33
+ apiHooks: number;
34
+ mediaHooks: number;
35
+ seoHooks: number;
36
+ };
28
37
  };
29
38
 
30
39
  export default function PluginsPage() {
@@ -38,6 +47,8 @@ export default function PluginsPage() {
38
47
  const [bundledKey, setBundledKey] = useState("hello");
39
48
  const [packageName, setPackageName] = useState("");
40
49
  const [runPnpm, setRunPnpm] = useState(false);
50
+ const [trustMode, setTrustMode] = useState<"trusted" | "sandboxed">("trusted");
51
+ const [capsText, setCapsText] = useState("");
41
52
  const [adding, setAdding] = useState(false);
42
53
 
43
54
  const load = useCallback(async () => {
@@ -76,18 +87,34 @@ export default function PluginsPage() {
76
87
  method: "POST",
77
88
  body: JSON.stringify(
78
89
  addMode === "bundled"
79
- ? { id: newId.trim(), bundled: bundledKey, enabled: true, config: {} }
90
+ ? {
91
+ id: newId.trim(),
92
+ bundled: bundledKey,
93
+ enabled: true,
94
+ config: {},
95
+ trustMode,
96
+ capabilities: capsText
97
+ .split(",")
98
+ .map((item) => item.trim())
99
+ .filter(Boolean)
100
+ }
80
101
  : {
81
102
  id: newId.trim(),
82
103
  package: packageName.trim(),
83
104
  enabled: true,
84
105
  config: {},
106
+ trustMode,
107
+ capabilities: capsText
108
+ .split(",")
109
+ .map((item) => item.trim())
110
+ .filter(Boolean),
85
111
  runPnpmInstall: runPnpm
86
112
  }
87
113
  )
88
114
  });
89
115
  setNewId("");
90
116
  setPackageName("");
117
+ setCapsText("");
91
118
  await load();
92
119
  } catch (e) {
93
120
  setError(e instanceof Error ? e.message : "Failed to add plugin");
@@ -178,6 +205,12 @@ export default function PluginsPage() {
178
205
  <span className="break-all font-mono text-slate-700">{state.manifestPath}</span>
179
206
  </p>
180
207
  )}
208
+ {state?.runtime && (
209
+ <p className="mt-2 text-xs text-slate-500">
210
+ Runtime surfaces: ui {state.runtime.adminUiExtensions}, jobs {state.runtime.jobs}, api {state.runtime.apiHooks}, media{" "}
211
+ {state.runtime.mediaHooks}, seo {state.runtime.seoHooks}
212
+ </p>
213
+ )}
181
214
  </div>
182
215
  </div>
183
216
  </div>
@@ -250,6 +283,24 @@ export default function PluginsPage() {
250
283
  </label>
251
284
  )}
252
285
  </div>
286
+ <div className="mt-3 grid gap-3 sm:grid-cols-2">
287
+ <label className="block space-y-1.5">
288
+ <span className="text-xs font-semibold uppercase tracking-wide text-slate-500">Trust mode</span>
289
+ <select className="input-base" value={trustMode} onChange={(e) => setTrustMode(e.target.value as "trusted" | "sandboxed")}>
290
+ <option value="trusted">trusted</option>
291
+ <option value="sandboxed">sandboxed</option>
292
+ </select>
293
+ </label>
294
+ <label className="block space-y-1.5">
295
+ <span className="text-xs font-semibold uppercase tracking-wide text-slate-500">Capabilities (comma separated)</span>
296
+ <input
297
+ className="input-base font-mono text-xs"
298
+ value={capsText}
299
+ onChange={(e) => setCapsText(e.target.value)}
300
+ placeholder="resource.hooks,seo.extend,media.pipeline"
301
+ />
302
+ </label>
303
+ </div>
253
304
 
254
305
  {addMode === "package" && (
255
306
  <label className="mt-3 flex cursor-pointer items-center gap-2 text-sm text-slate-600">
@@ -311,6 +362,14 @@ export default function PluginsPage() {
311
362
  >
312
363
  {row.enabled === false ? "Disabled" : "Enabled"}
313
364
  </span>
365
+ <p className="mt-1 text-xs text-slate-500">
366
+ trust: <span className="font-mono text-slate-700">{row.trustMode ?? "trusted"}</span>
367
+ </p>
368
+ {row.capabilities && row.capabilities.length > 0 && (
369
+ <p className="mt-1 text-xs text-slate-500">
370
+ caps: <span className="font-mono text-slate-700">{row.capabilities.join(", ")}</span>
371
+ </p>
372
+ )}
314
373
  </div>
315
374
  <div className="flex shrink-0 items-center gap-2">
316
375
  <button
@@ -4,12 +4,24 @@
4
4
  {
5
5
  "id": "io.openadminjs.hello",
6
6
  "enabled": true,
7
+ "trustMode": "trusted",
8
+ "capabilities": ["resource.hooks"],
7
9
  "bundled": "hello",
8
10
  "config": { "tag": "optional-config-passed-to-plugin" }
9
11
  },
12
+ {
13
+ "id": "io.openadminjs.seo",
14
+ "enabled": false,
15
+ "trustMode": "sandboxed",
16
+ "capabilities": ["seo.extend"],
17
+ "bundled": "seo",
18
+ "config": {}
19
+ },
10
20
  {
11
21
  "id": "com.vendor.billing",
12
22
  "enabled": false,
23
+ "trustMode": "sandboxed",
24
+ "capabilities": ["resource.hooks", "api.routes", "jobs.run", "admin.ui.extend"],
13
25
  "package": "@vendor/openadmin-billing",
14
26
  "marketplace": {
15
27
  "listingUrl": "https://example.com/plugins/billing",
@@ -1,6 +1,7 @@
1
1
  import { BadRequestException, ForbiddenException, Injectable } from "@nestjs/common";
2
2
  import type { Prisma } from "@prisma/client";
3
3
  import { PrismaService } from "../common/prisma.service";
4
+ import { pluginRuntime } from "../plugins/plugin-runtime";
4
5
  import { resources } from "../resources/registry";
5
6
  import { AdminResourceService } from "./admin-resource.service";
6
7
 
@@ -1071,20 +1072,52 @@ export class AdminAiService {
1071
1072
  meta?: Record<string, unknown>;
1072
1073
  }
1073
1074
  ) {
1074
- const contentBase64 =
1075
+ const initialContentBase64 =
1075
1076
  input.encoding === "base64" ? content : Buffer.from(content, "utf8").toString("base64");
1077
+ let filename = input.filename.slice(0, 180);
1078
+ let mimeType = input.mimeType.slice(0, 120);
1079
+ let contentBase64 = initialContentBase64;
1080
+ for (const hooks of pluginRuntime.getMediaHooks()) {
1081
+ await hooks.beforeStore?.({
1082
+ filename,
1083
+ mimeType,
1084
+ size: Buffer.from(contentBase64, "base64").byteLength,
1085
+ contentBase64,
1086
+ user: { id: userId, email: "", permissions: [] }
1087
+ });
1088
+ if (hooks.transform) {
1089
+ const transformed = await hooks.transform({
1090
+ filename,
1091
+ mimeType,
1092
+ contentBase64,
1093
+ user: { id: userId, email: "", permissions: [] }
1094
+ });
1095
+ filename = (transformed.filename ?? filename).slice(0, 180);
1096
+ mimeType = (transformed.mimeType ?? mimeType).slice(0, 120);
1097
+ contentBase64 = transformed.contentBase64;
1098
+ }
1099
+ }
1076
1100
  const size = Buffer.from(contentBase64, "base64").byteLength;
1077
1101
  const artifact = await this.prisma.aiArtifact.create({
1078
1102
  data: {
1079
1103
  userId,
1080
1104
  conversationId: input.conversationId ?? null,
1081
- filename: input.filename.slice(0, 180),
1082
- mimeType: input.mimeType.slice(0, 120),
1105
+ filename,
1106
+ mimeType,
1083
1107
  size,
1084
1108
  contentBase64,
1085
1109
  meta: (input.meta ?? null) as Prisma.InputJsonValue | Prisma.NullableJsonNullValueInput
1086
1110
  }
1087
1111
  });
1112
+ for (const hooks of pluginRuntime.getMediaHooks()) {
1113
+ await hooks.afterStore?.({
1114
+ fileId: artifact.id,
1115
+ filename: artifact.filename,
1116
+ mimeType: artifact.mimeType,
1117
+ size: artifact.size,
1118
+ user: { id: userId, email: "", permissions: [] }
1119
+ });
1120
+ }
1088
1121
  return {
1089
1122
  id: artifact.id,
1090
1123
  artifactId: artifact.id,
@@ -17,6 +17,7 @@ import {
17
17
  type PluginManifest,
18
18
  type PluginManifestEntry
19
19
  } from "../plugins/manifest.schema";
20
+ import { pluginRuntime } from "../plugins/plugin-runtime";
20
21
 
21
22
  const execFileAsync = promisify(execFile);
22
23
 
@@ -62,7 +63,14 @@ export class AdminPluginsService {
62
63
  return {
63
64
  manifestPath: path,
64
65
  bundledAvailable: Object.keys(bundledOpenAdminPlugins),
65
- plugins: manifest.plugins
66
+ plugins: manifest.plugins,
67
+ runtime: {
68
+ adminUiExtensions: pluginRuntime.getAdminUiExtensions().length,
69
+ jobs: pluginRuntime.getJobs().length,
70
+ apiHooks: pluginRuntime.getApiHooks().length,
71
+ mediaHooks: pluginRuntime.getMediaHooks().length,
72
+ seoHooks: pluginRuntime.getSeoHooks().length
73
+ }
66
74
  };
67
75
  }
68
76
 
@@ -81,6 +89,8 @@ export class AdminPluginsService {
81
89
  package?: string;
82
90
  enabled?: boolean;
83
91
  config?: Record<string, unknown>;
92
+ trustMode?: "trusted" | "sandboxed";
93
+ capabilities?: string[];
84
94
  runPnpmInstall?: boolean;
85
95
  }) {
86
96
  const hasBundled = Boolean(dto.bundled);
@@ -103,7 +113,9 @@ export class AdminPluginsService {
103
113
  id: dto.id,
104
114
  enabled: dto.enabled ?? true,
105
115
  ...(dto.bundled ? { bundled: dto.bundled } : { package: dto.package! }),
106
- config: dto.config ?? {}
116
+ config: dto.config ?? {},
117
+ trustMode: dto.trustMode ?? "trusted",
118
+ capabilities: dto.capabilities ?? []
107
119
  };
108
120
 
109
121
  const entryParsed = pluginManifestEntrySchema.safeParse(entry);
@@ -144,7 +156,7 @@ export class AdminPluginsService {
144
156
  };
145
157
  }
146
158
 
147
- async patch(id: string, dto: { enabled?: boolean; config?: Record<string, unknown> }) {
159
+ async patch(id: string, dto: { enabled?: boolean; config?: Record<string, unknown>; trustMode?: "trusted" | "sandboxed"; capabilities?: string[] }) {
148
160
  const manifest = this.readManifestOrEmpty();
149
161
  const idx = manifest.plugins.findIndex((p) => p.id === id);
150
162
  if (idx === -1) {
@@ -153,6 +165,8 @@ export class AdminPluginsService {
153
165
  const cur = { ...manifest.plugins[idx]! };
154
166
  if (dto.enabled !== undefined) cur.enabled = dto.enabled;
155
167
  if (dto.config !== undefined) cur.config = dto.config;
168
+ if (dto.trustMode !== undefined) cur.trustMode = dto.trustMode;
169
+ if (dto.capabilities !== undefined) cur.capabilities = dto.capabilities;
156
170
 
157
171
  const entryParsed = pluginManifestEntrySchema.safeParse(cur);
158
172
  if (!entryParsed.success) {
@@ -224,7 +238,7 @@ export class AdminPluginsService {
224
238
  invalidateNpmPluginMainModule(entry.package);
225
239
  }
226
240
  try {
227
- applyManifestPluginEntry(entry);
241
+ await applyManifestPluginEntry(entry);
228
242
  return;
229
243
  } catch (e) {
230
244
  last = e instanceof Error ? e : new Error(String(e));
@@ -1,4 +1,4 @@
1
- import { IsBoolean, IsObject, IsOptional, IsString } from "class-validator";
1
+ import { IsArray, IsBoolean, IsIn, IsObject, IsOptional, IsString } from "class-validator";
2
2
 
3
3
  export class AddPluginDto {
4
4
  @IsString()
@@ -20,6 +20,15 @@ export class AddPluginDto {
20
20
  @IsObject()
21
21
  config?: Record<string, unknown>;
22
22
 
23
+ @IsOptional()
24
+ @IsIn(["trusted", "sandboxed"])
25
+ trustMode?: "trusted" | "sandboxed";
26
+
27
+ @IsOptional()
28
+ @IsArray()
29
+ @IsString({ each: true })
30
+ capabilities?: string[];
31
+
23
32
  /** When true and `package` is set, runs `pnpm add <package> --filter @openadminjs/api` (dev / non-production only). */
24
33
  @IsOptional()
25
34
  @IsBoolean()
@@ -34,4 +43,13 @@ export class PatchPluginDto {
34
43
  @IsOptional()
35
44
  @IsObject()
36
45
  config?: Record<string, unknown>;
46
+
47
+ @IsOptional()
48
+ @IsIn(["trusted", "sandboxed"])
49
+ trustMode?: "trusted" | "sandboxed";
50
+
51
+ @IsOptional()
52
+ @IsArray()
53
+ @IsString({ each: true })
54
+ capabilities?: string[];
37
55
  }
@@ -3,6 +3,7 @@ import "./plugins/bootstrap";
3
3
  import { existsSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { Module } from "@nestjs/common";
6
+ import { APP_INTERCEPTOR } from "@nestjs/core";
6
7
  import { ConfigModule } from "@nestjs/config";
7
8
  import { ThrottlerModule } from "@nestjs/throttler";
8
9
  import { PrismaService } from "./common/prisma.service";
@@ -12,6 +13,7 @@ import { HealthController } from "./health/health.controller";
12
13
  import { QueueModule } from "./queue/queue.module";
13
14
  import { StoreModule } from "./store/store.module";
14
15
  import { MailModule } from "./mail/mail.module";
16
+ import { PluginApiInterceptor } from "./plugins/plugin-api.interceptor";
15
17
 
16
18
  const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "api", ".env")].filter((p) =>
17
19
  existsSync(p)
@@ -31,7 +33,13 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
31
33
  StoreModule
32
34
  ],
33
35
  controllers: [HealthController],
34
- providers: [PrismaService],
36
+ providers: [
37
+ PrismaService,
38
+ {
39
+ provide: APP_INTERCEPTOR,
40
+ useClass: PluginApiInterceptor
41
+ }
42
+ ],
35
43
  exports: [PrismaService]
36
44
  })
37
45
  export class AppModule {}
@@ -1,4 +1,4 @@
1
- import { loadPluginsFromManifestSync } from "./plugin-loader";
1
+ import { loadPluginsFromManifest } from "./plugin-loader";
2
2
 
3
3
  /** Runs after core `resource-hooks.install` so plugin hooks stack after built-ins. */
4
- loadPluginsFromManifestSync();
4
+ void loadPluginsFromManifest();
@@ -0,0 +1,25 @@
1
+ import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+
3
+ export const adminWidgetBundledPlugin: OpenAdminPlugin = {
4
+ id: "io.openadminjs.admin-widget",
5
+ version: "0.1.0",
6
+ displayName: "Admin widget demo",
7
+ register({ registerSurface }) {
8
+ registerSurface({
9
+ adminUi: [
10
+ {
11
+ kind: "widget",
12
+ id: "ops-health",
13
+ title: "Ops Health",
14
+ config: { metric: "queueLag", severity: "info" }
15
+ },
16
+ {
17
+ kind: "menu",
18
+ id: "plugin-insights",
19
+ title: "Plugin Insights",
20
+ route: "/plugins/insights"
21
+ }
22
+ ]
23
+ });
24
+ }
25
+ };
@@ -0,0 +1,22 @@
1
+ import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+
3
+ export const imageOptimizerBundledPlugin: OpenAdminPlugin = {
4
+ id: "io.openadminjs.image-optimizer",
5
+ version: "0.1.0",
6
+ displayName: "Image optimizer demo",
7
+ register({ registerSurface }) {
8
+ registerSurface({
9
+ media: {
10
+ transform(ctx) {
11
+ if (!ctx.mimeType.startsWith("image/")) return ctx;
12
+ const filename = ctx.filename.replace(/\.(png|jpe?g|webp)$/i, "") + ".webp";
13
+ return {
14
+ ...ctx,
15
+ filename,
16
+ mimeType: "image/webp"
17
+ };
18
+ }
19
+ }
20
+ });
21
+ }
22
+ };
@@ -1,7 +1,13 @@
1
1
  import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+ import { adminWidgetBundledPlugin } from "./admin-widget.plugin";
2
3
  import { helloBundledPlugin } from "./hello.plugin";
4
+ import { imageOptimizerBundledPlugin } from "./image-optimizer.plugin";
5
+ import { seoBundledPlugin } from "./seo.plugin";
3
6
 
4
7
  /** First-party plugins shipped inside the API package (no separate npm install). */
5
8
  export const bundledOpenAdminPlugins: Record<string, OpenAdminPlugin> = {
6
- hello: helloBundledPlugin
9
+ hello: helloBundledPlugin,
10
+ seo: seoBundledPlugin,
11
+ "image-optimizer": imageOptimizerBundledPlugin,
12
+ "admin-widget": adminWidgetBundledPlugin
7
13
  };
@@ -0,0 +1,25 @@
1
+ import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+
3
+ export const seoBundledPlugin: OpenAdminPlugin = {
4
+ id: "io.openadminjs.seo",
5
+ version: "0.1.0",
6
+ displayName: "SEO metadata + sitemap demo",
7
+ register({ registerSurface }) {
8
+ registerSurface({
9
+ seo: {
10
+ metadata({ resourceName, record }) {
11
+ if (resourceName !== "posts") return {};
12
+ return {
13
+ title: record.title ?? "Untitled",
14
+ description: record.excerpt ?? "",
15
+ canonical: record.slug ? `/posts/${record.slug}` : undefined
16
+ };
17
+ },
18
+ sitemapEntry({ resourceName, record }) {
19
+ if (resourceName !== "posts" || !record.slug) return null;
20
+ return { url: `/posts/${record.slug}`, lastModified: typeof record.updatedAt === "string" ? record.updatedAt : undefined };
21
+ }
22
+ }
23
+ });
24
+ }
25
+ };
@@ -5,11 +5,19 @@ describe("pluginManifestSchema", () => {
5
5
  it("accepts bundled-only entry", () => {
6
6
  const r = pluginManifestSchema.safeParse({
7
7
  version: 1,
8
- plugins: [{ id: "a.b", bundled: "hello", enabled: true, config: { x: 1 } }]
8
+ plugins: [{ id: "a.b", bundled: "hello", enabled: true, config: { x: 1 }, capabilities: ["resource.hooks"], trustMode: "sandboxed" }]
9
9
  });
10
10
  expect(r.success).toBe(true);
11
11
  });
12
12
 
13
+ it("rejects unknown capability", () => {
14
+ const r = pluginManifestSchema.safeParse({
15
+ version: 1,
16
+ plugins: [{ id: "a.b", bundled: "hello", capabilities: ["unknown.cap"] }]
17
+ });
18
+ expect(r.success).toBe(false);
19
+ });
20
+
13
21
  it("rejects both bundled and package", () => {
14
22
  const r = pluginManifestSchema.safeParse({
15
23
  version: 1,