openadminjs 0.1.7 → 0.1.9
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 +114 -18
- package/dist/create-project.js +27 -4
- package/dist/create-project.test.js +57 -41
- package/dist/index.js +16 -5
- package/package.json +4 -2
- package/template/.env.example +2 -2
- package/template/README.md +24 -5
- package/template/apps/admin/app/api/auth/login/route.ts +51 -0
- package/template/apps/admin/app/api/auth/logout/route.ts +11 -0
- package/template/apps/admin/app/api/auth/refresh/route.ts +46 -0
- package/template/apps/admin/app/api-tokens/page.tsx +253 -0
- package/template/apps/admin/app/audit-logs/page.tsx +5 -0
- package/template/apps/admin/app/dashboard/page.tsx +392 -0
- package/template/apps/admin/app/files/page.tsx +5 -0
- package/template/apps/admin/app/globals.css +206 -0
- package/template/apps/admin/app/jobs/page.tsx +19 -0
- package/template/apps/admin/app/layout.tsx +57 -0
- package/template/apps/admin/app/login/page.test.tsx +18 -0
- package/template/apps/admin/app/login/page.tsx +161 -0
- package/template/apps/admin/app/login/safe-next-param.ts +4 -0
- package/template/apps/admin/app/notifications/page.tsx +146 -0
- package/template/apps/admin/app/page.tsx +5 -0
- package/template/apps/admin/app/plugins/page.tsx +407 -0
- package/template/apps/admin/app/profile/page.tsx +116 -0
- package/template/apps/admin/app/resources/[resource]/[id]/edit/page.tsx +45 -0
- package/template/apps/admin/app/resources/[resource]/[id]/page.tsx +449 -0
- package/template/apps/admin/app/resources/[resource]/create/page.tsx +34 -0
- package/template/apps/admin/app/resources/[resource]/page.tsx +100 -0
- package/template/apps/admin/app/settings/page.tsx +233 -0
- package/template/apps/admin/components/ai-assistant-widget.tsx +684 -0
- package/template/apps/admin/components/app-shell.tsx +305 -0
- package/template/apps/admin/components/auth-guard.test.tsx +55 -0
- package/template/apps/admin/components/auth-guard.tsx +39 -0
- package/template/apps/admin/components/jobs-panel.tsx +103 -0
- package/template/apps/admin/components/logo.tsx +30 -0
- package/template/apps/admin/components/resource-form.tsx +349 -0
- package/template/apps/admin/components/resource-table.tsx +277 -0
- package/template/apps/admin/lib/ai-events.ts +23 -0
- package/template/apps/admin/lib/api.test.ts +118 -0
- package/template/apps/admin/lib/api.ts +135 -0
- package/template/apps/admin/lib/auth-flow.e2e.test.ts +79 -0
- package/template/apps/admin/lib/brand.ts +14 -0
- package/template/apps/admin/lib/locale.ts +49 -0
- package/template/apps/admin/lib/tokens.ts +93 -0
- package/template/apps/admin/middleware.ts +58 -0
- package/template/apps/admin/next-env.d.ts +6 -0
- package/template/apps/admin/next.config.mjs +7 -0
- package/template/apps/admin/package.json +44 -0
- package/template/apps/admin/postcss.config.mjs +6 -0
- package/template/apps/admin/public/brand/apple-touch-icon.png +0 -0
- package/template/apps/admin/public/brand/favicon.svg +1 -0
- package/template/apps/admin/public/brand/og-image.png +0 -0
- package/template/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
- package/template/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/template/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
- package/template/apps/admin/tailwind.config.ts +37 -0
- package/template/apps/admin/tsconfig.json +23 -0
- package/template/apps/admin/vitest.config.ts +7 -0
- package/template/apps/api/package.json +56 -0
- package/template/apps/api/plugins.manifest.example.json +34 -0
- package/template/apps/api/plugins.manifest.json +4 -0
- package/template/apps/api/src/access/catalog.ts +112 -0
- package/template/apps/api/src/access/derive-permissions.test.ts +26 -0
- package/template/apps/api/src/access/derive-permissions.ts +36 -0
- package/template/apps/api/src/access/public-catalog.ts +28 -0
- package/template/apps/api/src/admin/admin-ai.controller.ts +125 -0
- package/template/apps/api/src/admin/admin-ai.events.ts +23 -0
- package/template/apps/api/src/admin/admin-ai.service.ts +1271 -0
- package/template/apps/api/src/admin/admin-analytics.service.ts +164 -0
- package/template/apps/api/src/admin/admin-plugins.controller.ts +32 -0
- package/template/apps/api/src/admin/admin-plugins.service.ts +267 -0
- package/template/apps/api/src/admin/admin-resource.service.test.ts +118 -0
- package/template/apps/api/src/admin/admin-resource.service.ts +375 -0
- package/template/apps/api/src/admin/admin.controller.ts +72 -0
- package/template/apps/api/src/admin/admin.module.ts +30 -0
- package/template/apps/api/src/admin/dto/plugins.dto.ts +55 -0
- package/template/apps/api/src/admin/validate-resource-payload.test.ts +44 -0
- package/template/apps/api/src/admin/validate-resource-payload.ts +103 -0
- package/template/apps/api/src/app.module.ts +45 -0
- package/template/apps/api/src/auth/auth.controller.ts +70 -0
- package/template/apps/api/src/auth/auth.dto.ts +49 -0
- package/template/apps/api/src/auth/auth.module.ts +30 -0
- package/template/apps/api/src/auth/auth.service.test.ts +75 -0
- package/template/apps/api/src/auth/auth.service.ts +231 -0
- package/template/apps/api/src/common/auth-realm.decorator.ts +6 -0
- package/template/apps/api/src/common/auth.guard.test.ts +61 -0
- package/template/apps/api/src/common/auth.guard.ts +78 -0
- package/template/apps/api/src/common/casl-ability.factory.test.ts +33 -0
- package/template/apps/api/src/common/casl-ability.factory.ts +41 -0
- package/template/apps/api/src/common/current-user.decorator.ts +6 -0
- package/template/apps/api/src/common/permission.decorator.ts +7 -0
- package/template/apps/api/src/common/permissions.guard.ts +31 -0
- package/template/apps/api/src/common/prisma.service.ts +13 -0
- package/template/apps/api/src/health/health.controller.ts +25 -0
- package/template/apps/api/src/mail/mail.module.ts +9 -0
- package/template/apps/api/src/mail/mail.service.ts +115 -0
- package/template/apps/api/src/main.ts +37 -0
- package/template/apps/api/src/plugins/bootstrap.ts +4 -0
- package/template/apps/api/src/plugins/bundled/admin-widget.plugin.ts +25 -0
- package/template/apps/api/src/plugins/bundled/hello.plugin.ts +19 -0
- package/template/apps/api/src/plugins/bundled/image-optimizer.plugin.ts +22 -0
- package/template/apps/api/src/plugins/bundled/registry.ts +13 -0
- package/template/apps/api/src/plugins/bundled/seo.plugin.ts +25 -0
- package/template/apps/api/src/plugins/manifest-path.ts +35 -0
- package/template/apps/api/src/plugins/manifest.schema.test.ts +36 -0
- package/template/apps/api/src/plugins/manifest.schema.ts +58 -0
- package/template/apps/api/src/plugins/plugin-api.interceptor.ts +47 -0
- package/template/apps/api/src/plugins/plugin-loader.ts +134 -0
- package/template/apps/api/src/plugins/plugin-runtime.test.ts +24 -0
- package/template/apps/api/src/plugins/plugin-runtime.ts +85 -0
- package/template/apps/api/src/queue/queue.controller.ts +28 -0
- package/template/apps/api/src/queue/queue.module.ts +23 -0
- package/template/apps/api/src/queue/queue.processor.ts +47 -0
- package/template/apps/api/src/queue/queue.service.ts +50 -0
- package/template/apps/api/src/resources/categories.resource.ts +21 -0
- package/template/apps/api/src/resources/commerce.resource.ts +157 -0
- package/template/apps/api/src/resources/operations.resource.ts +111 -0
- package/template/apps/api/src/resources/posts.resource.ts +88 -0
- package/template/apps/api/src/resources/registry.ts +27 -0
- package/template/apps/api/src/resources/resource-hooks.install.ts +18 -0
- package/template/apps/api/src/resources/resource-hooks.registry.test.ts +72 -0
- package/template/apps/api/src/resources/resource-hooks.registry.ts +66 -0
- package/template/apps/api/src/resources/resource-hooks.runner.ts +93 -0
- package/template/apps/api/src/resources/system.resource.ts +51 -0
- package/template/apps/api/src/resources/users.resource.ts +19 -0
- package/template/apps/api/src/store/payment/payment.controller.ts +98 -0
- package/template/apps/api/src/store/payment/payment.module.ts +14 -0
- package/template/apps/api/src/store/payment/payment.provider.ts +38 -0
- package/template/apps/api/src/store/payment/payment.service.ts +235 -0
- package/template/apps/api/src/store/store.controller.ts +26 -0
- package/template/apps/api/src/store/store.module.ts +12 -0
- package/template/apps/api/src/test-setup.ts +1 -0
- package/template/apps/api/tsconfig.json +11 -0
- package/template/apps/api/vitest.config.ts +21 -0
- package/template/apps/web/lib/openadmin-client.ts +11 -0
- package/template/apps/web/lib/seo.test.ts +41 -0
- package/template/apps/web/lib/seo.ts +24 -13
- package/template/apps/web/next-env.d.ts +4 -0
- package/template/apps/web/package.json +2 -1
- package/template/apps/web/test/next-stub.ts +7 -0
- package/template/apps/web/vitest.config.ts +19 -0
- package/template/package.json +18 -11
- package/template/packages/auth/package.json +17 -0
- package/template/packages/auth/src/index.test.ts +10 -0
- package/template/packages/auth/src/index.ts +17 -0
- package/template/packages/auth/tsconfig.json +8 -0
- package/template/packages/brand/apps/admin/public/brand/apple-touch-icon.png +0 -0
- package/template/packages/brand/apps/admin/public/brand/favicon.svg +1 -0
- package/template/packages/brand/apps/admin/public/brand/og-image.png +0 -0
- package/template/packages/brand/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
- package/template/packages/brand/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/template/packages/brand/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
- package/template/packages/brand/apps/web/public/brand/apple-touch-icon.png +0 -0
- package/template/packages/brand/apps/web/public/brand/favicon.svg +1 -0
- package/template/packages/brand/apps/web/public/brand/og-image.png +0 -0
- package/template/packages/brand/apps/web/public/brand/openadminjs-icon-new.png +0 -0
- package/template/packages/brand/apps/web/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/template/packages/brand/apps/web/public/brand/openadminjs-logo-new.png +0 -0
- package/template/packages/brand/package.json +19 -0
- package/template/packages/brand/site/assets/brand/favicon.svg +1 -0
- package/template/packages/brand/site/assets/brand/og-image.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-icon.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-logo-dark.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-logo-horizontal.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-logo-monochrome.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-logo.svg +1 -0
- package/template/packages/brand/src/generate-assets.mjs +182 -0
- package/template/packages/brand/src/index.test.ts +9 -0
- package/template/packages/brand/src/index.ts +7 -0
- package/template/packages/brand/tsconfig.json +7 -0
- package/template/packages/core/package.json +20 -0
- package/template/packages/core/src/index.js +1 -0
- package/template/packages/core/src/index.test.ts +27 -0
- package/template/packages/core/src/index.ts +61 -0
- package/template/packages/core/tsconfig.json +8 -0
- package/template/packages/mail/package.json +18 -0
- package/template/packages/mail/src/index.test.ts +23 -0
- package/template/packages/mail/src/index.ts +246 -0
- package/template/packages/mail/tsconfig.json +5 -0
- package/template/packages/notifications/package.json +16 -0
- package/template/packages/notifications/src/index.test.ts +9 -0
- package/template/packages/notifications/src/index.ts +5 -0
- package/template/packages/notifications/tsconfig.json +5 -0
- package/template/packages/payments/package.json +15 -0
- package/template/packages/payments/src/index.ts +256 -0
- package/template/packages/payments/tsconfig.json +9 -0
- package/template/packages/permissions/package.json +17 -0
- package/template/packages/permissions/src/blueprints.js +57 -0
- package/template/packages/permissions/src/blueprints.test.ts +62 -0
- package/template/packages/permissions/src/blueprints.ts +89 -0
- package/template/packages/permissions/src/index.js +11 -0
- package/template/packages/permissions/src/index.test.ts +34 -0
- package/template/packages/permissions/src/index.ts +22 -0
- package/template/packages/permissions/tsconfig.json +8 -0
- package/template/packages/plugin-sdk/package.json +26 -0
- package/template/packages/plugin-sdk/src/hooks.ts +135 -0
- package/template/packages/plugin-sdk/src/index.ts +42 -0
- package/template/packages/plugin-sdk/src/sdk.test.ts +13 -0
- package/template/packages/plugin-sdk/tsconfig.json +8 -0
- package/template/packages/plugin-sdk/vitest.config.ts +5 -0
- package/template/packages/queue/package.json +16 -0
- package/template/packages/queue/src/index.test.ts +12 -0
- package/template/packages/queue/src/index.ts +6 -0
- package/template/packages/queue/tsconfig.json +5 -0
- package/template/packages/resource/package.json +17 -0
- package/template/packages/resource/src/index.js +177 -0
- package/template/packages/resource/src/index.test.ts +151 -0
- package/template/packages/resource/src/index.ts +344 -0
- package/template/packages/resource/tsconfig.json +8 -0
- package/template/packages/storage/package.json +16 -0
- package/template/packages/storage/src/index.test.ts +10 -0
- package/template/packages/storage/src/index.ts +23 -0
- package/template/packages/storage/tsconfig.json +5 -0
- package/template/prisma/migrations/20260505151751_baseline_init_all_tables/migration.sql +371 -0
- package/template/prisma/migrations/migration_lock.toml +3 -0
- package/template/prisma/schema.prisma +291 -0
- package/template/prisma/seed.ts +217 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import type { OpenAdminPlugin, OpenAdminPluginModule, PluginRegistrationContext, PluginSurfaceRegistry } from "@openadminjs/plugin-sdk";
|
|
4
|
+
import { Logger } from "@nestjs/common";
|
|
5
|
+
import { registerResourceHooks, unregisterResourceHooksBySource } from "../resources/resource-hooks.registry";
|
|
6
|
+
import { bundledOpenAdminPlugins } from "./bundled/registry";
|
|
7
|
+
import { getManifestCandidateStrings, toAbsoluteManifestPath } from "./manifest-path";
|
|
8
|
+
import { pluginManifestSchema, type PluginManifestEntry } from "./manifest.schema";
|
|
9
|
+
import { pluginRuntime } from "./plugin-runtime";
|
|
10
|
+
|
|
11
|
+
const log = new Logger("OpenAdminPlugins");
|
|
12
|
+
|
|
13
|
+
const require = createRequire(import.meta.url);
|
|
14
|
+
|
|
15
|
+
function readManifest(): unknown | undefined {
|
|
16
|
+
for (const candidate of getManifestCandidateStrings()) {
|
|
17
|
+
const path = toAbsoluteManifestPath(candidate);
|
|
18
|
+
if (existsSync(path)) {
|
|
19
|
+
log.log(`Loading plugin manifest: ${path}`);
|
|
20
|
+
return JSON.parse(readFileSync(path, "utf8")) as unknown;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Clears the main module entry so the next `require` re-reads from disk (e.g. after `pnpm add`). */
|
|
27
|
+
export function invalidateNpmPluginMainModule(packageSpec: string): void {
|
|
28
|
+
try {
|
|
29
|
+
const resolved = require.resolve(packageSpec);
|
|
30
|
+
delete require.cache[resolved];
|
|
31
|
+
} catch {
|
|
32
|
+
/* not resolved yet — fine */
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function resolveNpmPlugin(entry: PluginManifestEntry): OpenAdminPlugin {
|
|
37
|
+
const spec = entry.package!;
|
|
38
|
+
if (process.env.NODE_ENV === "production" && (spec.includes("..") || spec.startsWith(".") || spec.startsWith("/"))) {
|
|
39
|
+
throw new Error(`Refusing to load plugin package path in production: ${entry.id}`);
|
|
40
|
+
}
|
|
41
|
+
const mod = require(spec) as OpenAdminPluginModule;
|
|
42
|
+
const plugin = mod.openAdminPlugin ?? mod.default;
|
|
43
|
+
if (!plugin) {
|
|
44
|
+
throw new Error(`Package "${spec}" has no openAdminPlugin or default export (${entry.id})`);
|
|
45
|
+
}
|
|
46
|
+
if (plugin.id !== entry.id) {
|
|
47
|
+
log.warn(`Plugin manifest id "${entry.id}" differs from plugin.id "${plugin.id}" — manifest id is used as source label`);
|
|
48
|
+
}
|
|
49
|
+
return plugin;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function resolveBundledPlugin(entry: PluginManifestEntry): OpenAdminPlugin {
|
|
53
|
+
const key = entry.bundled!;
|
|
54
|
+
const plugin = bundledOpenAdminPlugins[key];
|
|
55
|
+
if (!plugin) {
|
|
56
|
+
throw new Error(`Unknown bundled plugin "${key}" for ${entry.id}. Known: ${Object.keys(bundledOpenAdminPlugins).join(", ")}`);
|
|
57
|
+
}
|
|
58
|
+
return plugin;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function createContext(entry: PluginManifestEntry): PluginRegistrationContext {
|
|
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
|
+
};
|
|
85
|
+
return {
|
|
86
|
+
pluginId: entry.id,
|
|
87
|
+
config,
|
|
88
|
+
trustMode: entry.trustMode ?? "trusted",
|
|
89
|
+
capabilities: [...capabilities],
|
|
90
|
+
registerResourceHooks: (resourceName, hooks, options) =>
|
|
91
|
+
registerResourceHooks(resourceName, hooks, { ...options, source: entry.id }),
|
|
92
|
+
registerSurface
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Register hooks for one manifest entry (same as bootstrap). Throws on failure. */
|
|
97
|
+
export async function applyManifestPluginEntry(entry: PluginManifestEntry): Promise<void> {
|
|
98
|
+
if (entry.enabled === false) return;
|
|
99
|
+
const plugin: OpenAdminPlugin = entry.bundled ? resolveBundledPlugin(entry) : resolveNpmPlugin(entry);
|
|
100
|
+
const ctx = createContext(entry);
|
|
101
|
+
await plugin.register(ctx as PluginRegistrationContext);
|
|
102
|
+
if (plugin.onStart) await plugin.onStart(ctx as PluginRegistrationContext);
|
|
103
|
+
log.log(`Loaded plugin ${entry.id} (${entry.bundled ? `bundled:${entry.bundled}` : `package:${entry.package}`})`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Drop all hook registrations attributed to this plugin id (before re-apply or disable). */
|
|
107
|
+
export function removeManifestPluginHooks(pluginId: string): void {
|
|
108
|
+
unregisterResourceHooksBySource(pluginId);
|
|
109
|
+
pluginRuntime.removeBySource(pluginId);
|
|
110
|
+
log.log(`Removed runtime hooks for plugin ${pluginId}`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function loadPluginsFromManifest(): Promise<void> {
|
|
114
|
+
const raw = readManifest();
|
|
115
|
+
if (!raw) {
|
|
116
|
+
log.log("No plugins.manifest.json found — skipping plugins");
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const parsed = pluginManifestSchema.safeParse(raw);
|
|
120
|
+
if (!parsed.success) {
|
|
121
|
+
log.error(`Invalid plugins.manifest.json: ${parsed.error.message}`);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const manifest = parsed.data;
|
|
125
|
+
for (const entry of manifest.plugins) {
|
|
126
|
+
if (entry.enabled === false) continue;
|
|
127
|
+
try {
|
|
128
|
+
await applyManifestPluginEntry(entry);
|
|
129
|
+
} catch (e) {
|
|
130
|
+
log.error(`Failed to load plugin ${entry.id}: ${(e as Error).message}`);
|
|
131
|
+
if (process.env.NODE_ENV === "production") throw e;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -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();
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Controller, Get, Post, UseGuards } from "@nestjs/common";
|
|
2
|
+
import { AuthGuard } from "../common/auth.guard";
|
|
3
|
+
import { RequireAuthRealm } from "../common/auth-realm.decorator";
|
|
4
|
+
import { PermissionsGuard } from "../common/permissions.guard";
|
|
5
|
+
import { RequirePermission } from "../common/permission.decorator";
|
|
6
|
+
import { CurrentUser } from "../common/current-user.decorator";
|
|
7
|
+
import { QueueService } from "./queue.service";
|
|
8
|
+
|
|
9
|
+
type UserContext = { id: string };
|
|
10
|
+
|
|
11
|
+
@Controller("jobs")
|
|
12
|
+
@UseGuards(AuthGuard, PermissionsGuard)
|
|
13
|
+
@RequireAuthRealm("admin")
|
|
14
|
+
export class QueueController {
|
|
15
|
+
constructor(private readonly queue: QueueService) {}
|
|
16
|
+
|
|
17
|
+
@Get("stats")
|
|
18
|
+
@RequirePermission("jobs.read")
|
|
19
|
+
stats() {
|
|
20
|
+
return this.queue.getStats();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
@Post("dispatch")
|
|
24
|
+
@RequirePermission("jobs.dispatch")
|
|
25
|
+
dispatch(@CurrentUser() user: UserContext) {
|
|
26
|
+
return this.queue.dispatch(user.id);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Module } from "@nestjs/common";
|
|
2
|
+
import { JwtModule } from "@nestjs/jwt";
|
|
3
|
+
import { BullModule } from "@nestjs/bullmq";
|
|
4
|
+
import { PrismaService } from "../common/prisma.service";
|
|
5
|
+
import { AuthGuard } from "../common/auth.guard";
|
|
6
|
+
import { PermissionsGuard } from "../common/permissions.guard";
|
|
7
|
+
import { CaslAbilityFactory } from "../common/casl-ability.factory";
|
|
8
|
+
import { QueueController } from "./queue.controller";
|
|
9
|
+
import { QueueService } from "./queue.service";
|
|
10
|
+
import { QueueProcessor } from "./queue.processor";
|
|
11
|
+
|
|
12
|
+
@Module({
|
|
13
|
+
imports: [
|
|
14
|
+
JwtModule.register({}),
|
|
15
|
+
BullModule.forRoot({
|
|
16
|
+
connection: { url: process.env.REDIS_URL ?? "redis://127.0.0.1:6379" }
|
|
17
|
+
}),
|
|
18
|
+
BullModule.registerQueue({ name: "default" })
|
|
19
|
+
],
|
|
20
|
+
controllers: [QueueController],
|
|
21
|
+
providers: [QueueService, QueueProcessor, PrismaService, AuthGuard, PermissionsGuard, CaslAbilityFactory]
|
|
22
|
+
})
|
|
23
|
+
export class QueueModule {}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Processor, WorkerHost } from "@nestjs/bullmq";
|
|
2
|
+
import { Logger } from "@nestjs/common";
|
|
3
|
+
import type { Job } from "bullmq";
|
|
4
|
+
import { PrismaService } from "../common/prisma.service";
|
|
5
|
+
|
|
6
|
+
@Processor("default")
|
|
7
|
+
export class QueueProcessor extends WorkerHost {
|
|
8
|
+
private readonly logger = new Logger(QueueProcessor.name);
|
|
9
|
+
|
|
10
|
+
constructor(private readonly prisma: PrismaService) {
|
|
11
|
+
super();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async process(job: Job<{ initiatedBy?: string; at?: string }>) {
|
|
15
|
+
await this.prisma.jobLog.create({
|
|
16
|
+
data: {
|
|
17
|
+
name: job.name,
|
|
18
|
+
status: "processing",
|
|
19
|
+
payload: { queueJobId: job.id, ...job.data }
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
25
|
+
await this.prisma.jobLog.create({
|
|
26
|
+
data: {
|
|
27
|
+
name: job.name,
|
|
28
|
+
status: "completed",
|
|
29
|
+
payload: { queueJobId: job.id, ...job.data }
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
return { ok: true };
|
|
33
|
+
} catch (error) {
|
|
34
|
+
const message = error instanceof Error ? error.message : "Unknown queue error";
|
|
35
|
+
await this.prisma.jobLog.create({
|
|
36
|
+
data: {
|
|
37
|
+
name: job.name,
|
|
38
|
+
status: "failed",
|
|
39
|
+
error: message,
|
|
40
|
+
payload: { queueJobId: job.id, ...job.data }
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
this.logger.error(`Job ${job.id} failed`, error instanceof Error ? error.stack : undefined);
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Injectable, ServiceUnavailableException } from "@nestjs/common";
|
|
2
|
+
import { InjectQueue } from "@nestjs/bullmq";
|
|
3
|
+
import { Queue } from "bullmq";
|
|
4
|
+
import { PrismaService } from "../common/prisma.service";
|
|
5
|
+
|
|
6
|
+
@Injectable()
|
|
7
|
+
export class QueueService {
|
|
8
|
+
constructor(
|
|
9
|
+
@InjectQueue("default") private readonly queue: Queue,
|
|
10
|
+
private readonly prisma: PrismaService
|
|
11
|
+
) {}
|
|
12
|
+
|
|
13
|
+
async getStats() {
|
|
14
|
+
const [counts, recent] = await Promise.all([
|
|
15
|
+
this.queue.getJobCounts("active", "waiting", "completed", "failed", "delayed"),
|
|
16
|
+
this.prisma.jobLog.findMany({ orderBy: { createdAt: "desc" }, take: 10 })
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
return { counts, recent };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async dispatch(userId: string) {
|
|
23
|
+
this.ensureRedisConfigured();
|
|
24
|
+
const payload = { initiatedBy: userId, at: new Date().toISOString() };
|
|
25
|
+
const job = await this.queue.add("maintenance.sync", payload, {
|
|
26
|
+
removeOnComplete: 100,
|
|
27
|
+
attempts: 3,
|
|
28
|
+
backoff: { type: "exponential", delay: 1000 }
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
await this.prisma.jobLog.create({
|
|
32
|
+
data: {
|
|
33
|
+
name: "maintenance.sync",
|
|
34
|
+
status: "queued",
|
|
35
|
+
payload: { ...payload, queueJobId: job.id }
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
return { id: job.id, name: job.name };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private ensureRedisConfigured() {
|
|
43
|
+
if (!process.env.REDIS_URL) {
|
|
44
|
+
throw new ServiceUnavailableException({
|
|
45
|
+
message: "Redis is not configured. Set REDIS_URL to enable queues.",
|
|
46
|
+
code: "REDIS_NOT_CONFIGURED"
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { defineResource } from "@openadminjs/core";
|
|
2
|
+
|
|
3
|
+
export default defineResource({
|
|
4
|
+
name: "categories",
|
|
5
|
+
label: "Categories",
|
|
6
|
+
model: "category",
|
|
7
|
+
titleField: "name",
|
|
8
|
+
icon: "Folder",
|
|
9
|
+
permissions: {
|
|
10
|
+
read: "categories.read",
|
|
11
|
+
create: "categories.create",
|
|
12
|
+
update: "categories.update",
|
|
13
|
+
delete: "categories.delete"
|
|
14
|
+
},
|
|
15
|
+
fields: {
|
|
16
|
+
id: { type: "id", label: "ID", create: false, edit: false, list: false },
|
|
17
|
+
name: { type: "text", label: "Name", required: true, searchable: true, sortable: true },
|
|
18
|
+
slug: { type: "slug", label: "Slug", from: "name", searchable: true },
|
|
19
|
+
createdAt: { type: "datetime", label: "Created at", create: false, edit: false, sortable: true }
|
|
20
|
+
}
|
|
21
|
+
});
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import type { PrismaClient } from "@prisma/client";
|
|
2
|
+
import { defineResource } from "@openadminjs/core";
|
|
3
|
+
|
|
4
|
+
export const productsResource = defineResource({
|
|
5
|
+
name: "products",
|
|
6
|
+
label: { en: "Products", ru: "Товары" },
|
|
7
|
+
model: "product",
|
|
8
|
+
titleField: "name",
|
|
9
|
+
icon: "ShoppingBag",
|
|
10
|
+
i18n: { defaultLocale: "en", locales: ["en", "ru"] },
|
|
11
|
+
permissions: {
|
|
12
|
+
read: "products.read",
|
|
13
|
+
create: "products.create",
|
|
14
|
+
update: "products.update",
|
|
15
|
+
delete: "products.delete"
|
|
16
|
+
},
|
|
17
|
+
fields: {
|
|
18
|
+
id: { type: "id", label: "ID", create: false, edit: false, list: false },
|
|
19
|
+
name: { type: "text", label: { en: "Name", ru: "Название" }, required: true, searchable: true, maxLength: 200 },
|
|
20
|
+
slug: { type: "slug", label: "Slug", required: true, maxLength: 200 },
|
|
21
|
+
description: { type: "textarea", label: { en: "Description", ru: "Описание" }, list: false },
|
|
22
|
+
price: {
|
|
23
|
+
type: "number",
|
|
24
|
+
label: { en: "Price (cents)", ru: "Цена (копейки)" },
|
|
25
|
+
required: true,
|
|
26
|
+
min: 0,
|
|
27
|
+
filterable: true,
|
|
28
|
+
sortable: true
|
|
29
|
+
},
|
|
30
|
+
currency: {
|
|
31
|
+
type: "select",
|
|
32
|
+
label: "Currency",
|
|
33
|
+
options: ["USD", "EUR", "GBP", "RUB", "UAH"],
|
|
34
|
+
required: true
|
|
35
|
+
},
|
|
36
|
+
active: { type: "boolean", label: { en: "Active", ru: "Активен" }, filterable: true, sortable: true },
|
|
37
|
+
imageUrl: { type: "url", label: { en: "Image URL", ru: "URL изображения" }, list: false },
|
|
38
|
+
metadata: { type: "json", label: "Metadata", list: false },
|
|
39
|
+
createdAt: { type: "datetime", label: { en: "Created", ru: "Создан" }, create: false, edit: false, sortable: true }
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
export const ordersResource = defineResource({
|
|
44
|
+
name: "orders",
|
|
45
|
+
label: { en: "Orders", ru: "Заказы" },
|
|
46
|
+
model: "order",
|
|
47
|
+
titleField: "id",
|
|
48
|
+
icon: "Receipt",
|
|
49
|
+
i18n: { defaultLocale: "en", locales: ["en", "ru"] },
|
|
50
|
+
permissions: {
|
|
51
|
+
read: "orders.read",
|
|
52
|
+
update: "orders.update",
|
|
53
|
+
refund: "orders.refund"
|
|
54
|
+
},
|
|
55
|
+
fields: {
|
|
56
|
+
id: { type: "id", label: "ID", create: false, edit: false },
|
|
57
|
+
email: { type: "email", label: { en: "Email", ru: "Email" }, searchable: true, edit: false },
|
|
58
|
+
status: {
|
|
59
|
+
type: "badge",
|
|
60
|
+
label: { en: "Status", ru: "Статус" },
|
|
61
|
+
options: ["pending", "paid", "failed", "refunded", "cancelled"],
|
|
62
|
+
filterable: true,
|
|
63
|
+
sortable: true
|
|
64
|
+
},
|
|
65
|
+
total: { type: "number", label: { en: "Total (cents)", ru: "Итог (копейки)" }, edit: false, sortable: true, filterable: true },
|
|
66
|
+
currency: { type: "text", label: "Currency", edit: false },
|
|
67
|
+
notes: { type: "textarea", label: { en: "Notes", ru: "Заметки" }, list: false },
|
|
68
|
+
createdAt: { type: "datetime", label: { en: "Created", ru: "Создан" }, create: false, edit: false, sortable: true }
|
|
69
|
+
},
|
|
70
|
+
actions: {
|
|
71
|
+
refund: {
|
|
72
|
+
label: { en: "Refund", ru: "Возврат" },
|
|
73
|
+
variant: "destructive",
|
|
74
|
+
confirm: true,
|
|
75
|
+
permission: "orders.refund",
|
|
76
|
+
async handler(ctx) {
|
|
77
|
+
const db = ctx.prisma as PrismaClient;
|
|
78
|
+
const order = await db.order.findUnique({
|
|
79
|
+
where: { id: ctx.id },
|
|
80
|
+
include: { transactions: true }
|
|
81
|
+
});
|
|
82
|
+
if (!order || order.status !== "paid") {
|
|
83
|
+
throw new Error("Order is not paid or not found");
|
|
84
|
+
}
|
|
85
|
+
return db.order.update({ where: { id: ctx.id }, data: { status: "refunded" } });
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
cancel: {
|
|
89
|
+
label: { en: "Cancel", ru: "Отменить" },
|
|
90
|
+
variant: "destructive",
|
|
91
|
+
confirm: true,
|
|
92
|
+
permission: "orders.update",
|
|
93
|
+
async handler(ctx) {
|
|
94
|
+
const db = ctx.prisma as PrismaClient;
|
|
95
|
+
return db.order.update({
|
|
96
|
+
where: { id: ctx.id },
|
|
97
|
+
data: { status: "cancelled" }
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
export const transactionsResource = defineResource({
|
|
105
|
+
name: "transactions",
|
|
106
|
+
label: { en: "Transactions", ru: "Транзакции" },
|
|
107
|
+
model: "transaction",
|
|
108
|
+
titleField: "id",
|
|
109
|
+
icon: "CreditCard",
|
|
110
|
+
i18n: { defaultLocale: "en", locales: ["en", "ru"] },
|
|
111
|
+
permissions: {
|
|
112
|
+
read: "transactions.read"
|
|
113
|
+
},
|
|
114
|
+
fields: {
|
|
115
|
+
id: { type: "id", label: "ID", create: false, edit: false },
|
|
116
|
+
provider: { type: "badge", label: { en: "Provider", ru: "Провайдер" }, create: false, edit: false, filterable: true },
|
|
117
|
+
providerTxId: { type: "text", label: { en: "Provider TX ID", ru: "ID транзакции" }, create: false, edit: false },
|
|
118
|
+
status: {
|
|
119
|
+
type: "badge",
|
|
120
|
+
label: { en: "Status", ru: "Статус" },
|
|
121
|
+
options: ["pending", "succeeded", "failed", "refunded"],
|
|
122
|
+
create: false,
|
|
123
|
+
edit: false,
|
|
124
|
+
filterable: true,
|
|
125
|
+
sortable: true
|
|
126
|
+
},
|
|
127
|
+
amount: { type: "number", label: { en: "Amount (cents)", ru: "Сумма (копейки)" }, create: false, edit: false, sortable: true },
|
|
128
|
+
currency: { type: "text", label: "Currency", create: false, edit: false },
|
|
129
|
+
createdAt: { type: "datetime", label: { en: "Created", ru: "Создан" }, create: false, edit: false, sortable: true }
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
export const webhookLogsResource = defineResource({
|
|
134
|
+
name: "webhook-logs",
|
|
135
|
+
label: { en: "Webhook Logs", ru: "Вебхук Логи" },
|
|
136
|
+
model: "webhookLog",
|
|
137
|
+
titleField: "eventType",
|
|
138
|
+
icon: "Webhook",
|
|
139
|
+
permissions: {
|
|
140
|
+
read: "webhook-logs.read"
|
|
141
|
+
},
|
|
142
|
+
fields: {
|
|
143
|
+
id: { type: "id", label: "ID", create: false, edit: false, list: false },
|
|
144
|
+
provider: { type: "badge", label: "Provider", create: false, edit: false, filterable: true },
|
|
145
|
+
eventType: { type: "text", label: { en: "Event Type", ru: "Тип события" }, create: false, edit: false, searchable: true },
|
|
146
|
+
status: {
|
|
147
|
+
type: "badge",
|
|
148
|
+
label: "Status",
|
|
149
|
+
options: ["pending", "processed", "failed"],
|
|
150
|
+
create: false,
|
|
151
|
+
edit: false,
|
|
152
|
+
filterable: true
|
|
153
|
+
},
|
|
154
|
+
error: { type: "textarea", label: "Error", create: false, edit: false, list: false },
|
|
155
|
+
createdAt: { type: "datetime", label: { en: "Received", ru: "Получен" }, create: false, edit: false, sortable: true }
|
|
156
|
+
}
|
|
157
|
+
});
|