openadminjs 0.1.15 → 0.1.17
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/dist/create-project.js +4 -1
- package/dist/index.js +127 -0
- package/package.json +2 -2
- package/template/apps/admin/.storybook/main.ts +12 -0
- package/template/apps/admin/.storybook/preview.ts +10 -0
- package/template/apps/admin/app/dashboard/page.tsx +357 -277
- package/template/apps/admin/app/layout.tsx +5 -1
- package/template/apps/admin/app/login/page.tsx +38 -0
- package/template/apps/admin/app/resources/[resource]/page.tsx +15 -1
- package/template/apps/admin/app/settings/page.tsx +40 -2
- package/template/apps/admin/app/system-logs/page.tsx +212 -0
- package/template/apps/admin/components/api-error-banner.tsx +26 -0
- package/template/apps/admin/components/app-shell.tsx +92 -18
- package/template/apps/admin/components/logo.stories.tsx +24 -0
- package/template/apps/admin/components/resource-form.tsx +47 -0
- package/template/apps/admin/components/resource-table.tsx +417 -44
- package/template/apps/admin/lib/api.ts +44 -1
- package/template/apps/admin/lib/resource-table-prefs.ts +57 -0
- package/template/apps/admin/package.json +6 -0
- package/template/apps/admin/storybook-static/370.e922f076.iframe.bundle.js +9 -0
- package/template/apps/admin/storybook-static/389.c0dd6bde.iframe.bundle.js +818 -0
- package/template/apps/admin/storybook-static/990.36428b6c.iframe.bundle.js +25 -0
- package/template/apps/admin/storybook-static/favicon-wrapper.svg +46 -0
- package/template/apps/admin/storybook-static/favicon.svg +1 -0
- package/template/apps/admin/storybook-static/iframe.html +560 -0
- package/template/apps/admin/storybook-static/index.html +139 -0
- package/template/apps/admin/storybook-static/index.json +1 -0
- package/template/apps/admin/storybook-static/logo-stories.c470fc8c.iframe.bundle.js +1 -0
- package/template/apps/admin/storybook-static/main.743ea6f2.iframe.bundle.js +2550 -0
- package/template/apps/admin/storybook-static/mocker-runtime-injected.js +2 -0
- package/template/apps/admin/storybook-static/nunito-sans-bold-italic.woff2 +0 -0
- package/template/apps/admin/storybook-static/nunito-sans-bold.woff2 +0 -0
- package/template/apps/admin/storybook-static/nunito-sans-italic.woff2 +0 -0
- package/template/apps/admin/storybook-static/nunito-sans-regular.woff2 +0 -0
- package/template/apps/admin/storybook-static/project.json +1 -0
- package/template/apps/admin/storybook-static/runtime~main.6f822e3b.iframe.bundle.js +2 -0
- package/template/apps/admin/storybook-static/sb-addons/onboarding-1/manager-bundle.js +97 -0
- package/template/apps/admin/storybook-static/sb-addons/storybook-core-server-presets-0/common-manager-bundle.js +630 -0
- package/template/apps/admin/storybook-static/sb-common-assets/favicon-wrapper.svg +46 -0
- package/template/apps/admin/storybook-static/sb-common-assets/favicon.svg +1 -0
- package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-bold-italic.woff2 +0 -0
- package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-bold.woff2 +0 -0
- package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-italic.woff2 +0 -0
- package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-regular.woff2 +0 -0
- package/template/apps/admin/storybook-static/sb-manager/globals-runtime.js +76309 -0
- package/template/apps/admin/storybook-static/sb-manager/globals.js +24 -0
- package/template/apps/admin/storybook-static/sb-manager/manager-stores.js +23 -0
- package/template/apps/admin/storybook-static/sb-manager/runtime.js +26078 -0
- package/template/apps/admin/storybook-static/sb-preview/globals.js +20 -0
- package/template/apps/admin/storybook-static/sb-preview/runtime.js +35472 -0
- package/template/apps/api/package.json +13 -2
- package/template/apps/api/plugins.manifest.example.json +12 -0
- package/template/apps/api/src/admin/admin-logs.controller.ts +31 -0
- package/template/apps/api/src/admin/admin-plugins.controller.ts +5 -0
- package/template/apps/api/src/admin/admin-plugins.service.ts +11 -0
- package/template/apps/api/src/admin/admin-resource.service.ts +235 -1
- package/template/apps/api/src/admin/admin.controller.ts +35 -0
- package/template/apps/api/src/admin/admin.module.ts +6 -3
- package/template/apps/api/src/admin/dto/resource-bulk.dto.ts +17 -0
- package/template/apps/api/src/admin/dto/resource-reorder.dto.ts +17 -0
- package/template/apps/api/src/admin/dto/resource-upload.dto.ts +20 -0
- package/template/apps/api/src/app.module.ts +45 -5
- package/template/apps/api/src/auth/auth.module.ts +5 -3
- package/template/apps/api/src/auth/auth.service.test.ts +6 -3
- package/template/apps/api/src/auth/auth.service.ts +84 -0
- package/template/apps/api/src/auth/sso-oidc.controller.ts +78 -0
- package/template/apps/api/src/auth/sso-oidc.service.test.ts +84 -0
- package/template/apps/api/src/auth/sso-oidc.service.ts +281 -0
- package/template/apps/api/src/common/app-logger.service.ts +138 -0
- package/template/apps/api/src/common/auth.guard.test.ts +1 -0
- package/template/apps/api/src/common/auth.guard.ts +15 -1
- package/template/apps/api/src/common/current-user.decorator.ts +6 -2
- package/template/apps/api/src/common/logging.module.ts +10 -0
- package/template/apps/api/src/common/request-logging.interceptor.ts +70 -0
- package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +44 -0
- package/template/apps/api/src/graphql/admin-resources.resolver.ts +65 -0
- package/template/apps/api/src/graphql/graphql.module.ts +26 -0
- package/template/apps/api/src/main.ts +2 -0
- package/template/apps/api/src/plugins/bundled/registry.ts +3 -1
- package/template/apps/api/src/plugins/bundled/webhook.plugin.ts +64 -0
- package/template/apps/api/src/resources/categories.resource.ts +1 -0
- package/template/apps/api/src/resources/system.resource.ts +1 -0
- package/template/packages/core/src/index.ts +5 -0
- package/template/packages/core/vitest.config.ts +9 -0
- package/template/packages/resource/package.json +11 -0
- package/template/packages/resource/src/index.test.ts +45 -0
- package/template/packages/resource/src/index.ts +63 -0
- package/template/prisma/schema.prisma +5 -0
- package/template/packages/core/src/index.js +0 -1
- package/template/packages/permissions/src/blueprints.js +0 -57
- package/template/packages/permissions/src/index.js +0 -11
- package/template/packages/resource/src/index.js +0 -177
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
} from "@nestjs/common";
|
|
9
9
|
import { ConfigService } from "@nestjs/config";
|
|
10
10
|
import { Reflector } from "@nestjs/core";
|
|
11
|
+
import { GqlExecutionContext } from "@nestjs/graphql";
|
|
11
12
|
import { JwtService } from "@nestjs/jwt";
|
|
12
13
|
import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
|
|
13
14
|
import { PrismaService } from "./prisma.service";
|
|
@@ -32,7 +33,7 @@ export class AuthGuard implements CanActivate {
|
|
|
32
33
|
) {}
|
|
33
34
|
|
|
34
35
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
35
|
-
const request =
|
|
36
|
+
const request = this.getRequest(context);
|
|
36
37
|
const header = request.headers.authorization;
|
|
37
38
|
const token = header?.startsWith("Bearer ") ? header.slice(7) : undefined;
|
|
38
39
|
if (!token) throw new UnauthorizedException({ message: "Missing access token", code: "AUTH_REQUIRED" });
|
|
@@ -82,4 +83,17 @@ export class AuthGuard implements CanActivate {
|
|
|
82
83
|
throw new UnauthorizedException({ message: "Invalid access token", code: "AUTH_INVALID" });
|
|
83
84
|
}
|
|
84
85
|
}
|
|
86
|
+
|
|
87
|
+
private getRequest(context: ExecutionContext): {
|
|
88
|
+
headers: { authorization?: string };
|
|
89
|
+
user?: RequestUser;
|
|
90
|
+
ip?: string;
|
|
91
|
+
} {
|
|
92
|
+
const type = context.getType<string>();
|
|
93
|
+
if (type === "graphql") {
|
|
94
|
+
const gql = GqlExecutionContext.create(context);
|
|
95
|
+
return gql.getContext<{ req: { headers: { authorization?: string }; user?: RequestUser; ip?: string } }>().req;
|
|
96
|
+
}
|
|
97
|
+
return context.switchToHttp().getRequest();
|
|
98
|
+
}
|
|
85
99
|
}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
|
|
2
|
+
import { GqlExecutionContext } from "@nestjs/graphql";
|
|
2
3
|
|
|
3
4
|
export const CurrentUser = createParamDecorator((_data: unknown, context: ExecutionContext) => {
|
|
4
|
-
const
|
|
5
|
-
|
|
5
|
+
const type = context.getType<string>();
|
|
6
|
+
if (type === "graphql") {
|
|
7
|
+
return GqlExecutionContext.create(context).getContext<{ req: { user?: unknown } }>().req.user;
|
|
8
|
+
}
|
|
9
|
+
return context.switchToHttp().getRequest().user;
|
|
6
10
|
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CallHandler,
|
|
3
|
+
ExecutionContext,
|
|
4
|
+
Injectable,
|
|
5
|
+
NestInterceptor
|
|
6
|
+
} from "@nestjs/common";
|
|
7
|
+
import { Observable, catchError, tap, throwError } from "rxjs";
|
|
8
|
+
import { AppLoggerService } from "./app-logger.service";
|
|
9
|
+
|
|
10
|
+
@Injectable()
|
|
11
|
+
export class RequestLoggingInterceptor implements NestInterceptor {
|
|
12
|
+
constructor(private readonly logger: AppLoggerService) {}
|
|
13
|
+
|
|
14
|
+
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
15
|
+
if (context.getType() !== "http") return next.handle();
|
|
16
|
+
const req = context.switchToHttp().getRequest<{
|
|
17
|
+
method?: string;
|
|
18
|
+
url?: string;
|
|
19
|
+
ip?: string;
|
|
20
|
+
user?: { id?: string };
|
|
21
|
+
}>();
|
|
22
|
+
const res = context.switchToHttp().getResponse<{ statusCode?: number }>();
|
|
23
|
+
const started = Date.now();
|
|
24
|
+
const method = req.method ?? "UNKNOWN";
|
|
25
|
+
const path = req.url ?? "/";
|
|
26
|
+
const ip = req.ip ?? "";
|
|
27
|
+
const userId = req.user?.id;
|
|
28
|
+
|
|
29
|
+
return next.handle().pipe(
|
|
30
|
+
tap(() => {
|
|
31
|
+
const durationMs = Date.now() - started;
|
|
32
|
+
this.logger.info("request.completed", {
|
|
33
|
+
context: "http",
|
|
34
|
+
method,
|
|
35
|
+
path,
|
|
36
|
+
statusCode: res.statusCode ?? 200,
|
|
37
|
+
durationMs,
|
|
38
|
+
ip,
|
|
39
|
+
userId
|
|
40
|
+
});
|
|
41
|
+
}),
|
|
42
|
+
catchError((err: unknown) => {
|
|
43
|
+
const durationMs = Date.now() - started;
|
|
44
|
+
const statusCode =
|
|
45
|
+
typeof err === "object" && err !== null && "status" in err && typeof (err as { status?: number }).status === "number"
|
|
46
|
+
? (err as { status: number }).status
|
|
47
|
+
: 500;
|
|
48
|
+
const message =
|
|
49
|
+
err instanceof Error
|
|
50
|
+
? err.message
|
|
51
|
+
: typeof err === "object" && err !== null && "message" in err
|
|
52
|
+
? String((err as { message?: unknown }).message ?? "unknown error")
|
|
53
|
+
: "unknown error";
|
|
54
|
+
|
|
55
|
+
this.logger.error("request.failed", {
|
|
56
|
+
context: "http",
|
|
57
|
+
method,
|
|
58
|
+
path,
|
|
59
|
+
statusCode,
|
|
60
|
+
durationMs,
|
|
61
|
+
ip,
|
|
62
|
+
userId,
|
|
63
|
+
errorMessage: message
|
|
64
|
+
});
|
|
65
|
+
return throwError(() => err);
|
|
66
|
+
})
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { AdminResourcesResolver } from "./admin-resources.resolver";
|
|
3
|
+
|
|
4
|
+
describe("AdminResourcesResolver", () => {
|
|
5
|
+
it("maps GraphQL filter input to REST-style filter query keys", async () => {
|
|
6
|
+
const adminResources = {
|
|
7
|
+
list: vi.fn().mockResolvedValue({ data: [], meta: { page: 1, limit: 20, total: 0, pages: 1 } })
|
|
8
|
+
};
|
|
9
|
+
const resolver = new AdminResourcesResolver(adminResources as never);
|
|
10
|
+
const user = { id: "u1", permissions: ["*"] };
|
|
11
|
+
|
|
12
|
+
await resolver.adminResourceList(
|
|
13
|
+
"posts",
|
|
14
|
+
user as never,
|
|
15
|
+
2,
|
|
16
|
+
15,
|
|
17
|
+
"hello",
|
|
18
|
+
"createdAt:desc",
|
|
19
|
+
"en",
|
|
20
|
+
{
|
|
21
|
+
status: { eq: "published" },
|
|
22
|
+
views: { gte: 10, lte: 100 },
|
|
23
|
+
authorId: "u1"
|
|
24
|
+
}
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
expect(adminResources.list).toHaveBeenCalledWith(
|
|
28
|
+
"posts",
|
|
29
|
+
{
|
|
30
|
+
page: 2,
|
|
31
|
+
limit: 15,
|
|
32
|
+
search: "hello",
|
|
33
|
+
sort: "createdAt:desc",
|
|
34
|
+
locale: "en",
|
|
35
|
+
"filter[status][eq]": "published",
|
|
36
|
+
"filter[views][gte]": 10,
|
|
37
|
+
"filter[views][lte]": 100,
|
|
38
|
+
"filter[authorId]": "u1"
|
|
39
|
+
},
|
|
40
|
+
user
|
|
41
|
+
);
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { UseGuards } from "@nestjs/common";
|
|
2
|
+
import { Args, Int, Query, Resolver } from "@nestjs/graphql";
|
|
3
|
+
import { GraphQLJSON } from "graphql-scalars";
|
|
4
|
+
import { AdminResourceService } from "../admin/admin-resource.service";
|
|
5
|
+
import { AuthGuard } from "../common/auth.guard";
|
|
6
|
+
import type { RequestUser } from "../common/auth.guard";
|
|
7
|
+
import { RequireAuthRealm } from "../common/auth-realm.decorator";
|
|
8
|
+
import { CurrentUser } from "../common/current-user.decorator";
|
|
9
|
+
import { resources } from "../resources/registry";
|
|
10
|
+
|
|
11
|
+
@Resolver()
|
|
12
|
+
@UseGuards(AuthGuard)
|
|
13
|
+
@RequireAuthRealm("admin")
|
|
14
|
+
export class AdminResourcesResolver {
|
|
15
|
+
constructor(private readonly adminResources: AdminResourceService) {}
|
|
16
|
+
|
|
17
|
+
private flattenFilters(input: unknown): Record<string, unknown> {
|
|
18
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return {};
|
|
19
|
+
const out: Record<string, unknown> = {};
|
|
20
|
+
for (const [field, raw] of Object.entries(input as Record<string, unknown>)) {
|
|
21
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
22
|
+
out[`filter[${field}]`] = raw;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
for (const [op, val] of Object.entries(raw as Record<string, unknown>)) {
|
|
26
|
+
out[`filter[${field}][${op}]`] = val;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
@Query(() => [String], { name: "adminRegisteredResourceNames" })
|
|
33
|
+
adminRegisteredResourceNames(@CurrentUser() user: RequestUser): string[] {
|
|
34
|
+
return resources
|
|
35
|
+
.filter(
|
|
36
|
+
(r) =>
|
|
37
|
+
Boolean(r.permissions.read) &&
|
|
38
|
+
(user.permissions.includes("*") || user.permissions.includes(r.permissions.read!))
|
|
39
|
+
)
|
|
40
|
+
.map((r) => r.name);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
@Query(() => GraphQLJSON, { name: "adminResourceList", description: "Paginated list (same rules as REST /admin/resources/:name)" })
|
|
44
|
+
adminResourceList(
|
|
45
|
+
@Args("name") name: string,
|
|
46
|
+
@CurrentUser() user: RequestUser,
|
|
47
|
+
@Args("page", { type: () => Int, nullable: true, defaultValue: 1 }) page: number,
|
|
48
|
+
@Args("limit", { type: () => Int, nullable: true, defaultValue: 20 }) limit: number,
|
|
49
|
+
@Args("search", { nullable: true }) search?: string,
|
|
50
|
+
@Args("sort", { nullable: true }) sort?: string,
|
|
51
|
+
@Args("locale", { nullable: true }) locale?: string,
|
|
52
|
+
@Args("filter", { type: () => GraphQLJSON, nullable: true }) filter?: Record<string, unknown>
|
|
53
|
+
) {
|
|
54
|
+
const query: Record<string, unknown> = { page, limit, ...this.flattenFilters(filter) };
|
|
55
|
+
if (search) query.search = search;
|
|
56
|
+
if (sort) query.sort = sort;
|
|
57
|
+
if (locale) query.locale = locale;
|
|
58
|
+
return this.adminResources.list(name, query, user);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
@Query(() => GraphQLJSON, { name: "adminResourceRecord" })
|
|
62
|
+
adminResourceRecord(@Args("name") name: string, @Args("id") id: string, @CurrentUser() user: RequestUser) {
|
|
63
|
+
return this.adminResources.get(name, id, user);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Module } from "@nestjs/common";
|
|
2
|
+
import { GraphQLModule } from "@nestjs/graphql";
|
|
3
|
+
import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo";
|
|
4
|
+
import { GraphQLJSON } from "graphql-scalars";
|
|
5
|
+
import { AdminModule } from "../admin/admin.module";
|
|
6
|
+
import { AuthModule } from "../auth/auth.module";
|
|
7
|
+
import { AuthGuard } from "../common/auth.guard";
|
|
8
|
+
import { AdminResourcesResolver } from "./admin-resources.resolver";
|
|
9
|
+
|
|
10
|
+
@Module({
|
|
11
|
+
imports: [
|
|
12
|
+
GraphQLModule.forRoot<ApolloDriverConfig>({
|
|
13
|
+
driver: ApolloDriver,
|
|
14
|
+
autoSchemaFile: true,
|
|
15
|
+
sortSchema: true,
|
|
16
|
+
path: "/graphql",
|
|
17
|
+
context: ({ req, res }: { req: unknown; res: unknown }) => ({ req, res }),
|
|
18
|
+
resolvers: { JSON: GraphQLJSON },
|
|
19
|
+
playground: process.env.NODE_ENV !== "production"
|
|
20
|
+
}),
|
|
21
|
+
AdminModule,
|
|
22
|
+
AuthModule
|
|
23
|
+
],
|
|
24
|
+
providers: [AdminResourcesResolver, AuthGuard]
|
|
25
|
+
})
|
|
26
|
+
export class GraphqlApiModule {}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
|
+
import cookieParser from "cookie-parser";
|
|
2
3
|
import helmet from "helmet";
|
|
3
4
|
import { NestFactory } from "@nestjs/core";
|
|
4
5
|
import { ValidationPipe } from "@nestjs/common";
|
|
@@ -7,6 +8,7 @@ import { AppModule } from "./app.module";
|
|
|
7
8
|
|
|
8
9
|
async function bootstrap() {
|
|
9
10
|
const app = await NestFactory.create(AppModule);
|
|
11
|
+
app.use(cookieParser());
|
|
10
12
|
app.use(helmet());
|
|
11
13
|
const prodOrigins = (process.env.ADMIN_ORIGIN ?? "")
|
|
12
14
|
.split(",")
|
|
@@ -3,11 +3,13 @@ import { adminWidgetBundledPlugin } from "./admin-widget.plugin";
|
|
|
3
3
|
import { helloBundledPlugin } from "./hello.plugin";
|
|
4
4
|
import { imageOptimizerBundledPlugin } from "./image-optimizer.plugin";
|
|
5
5
|
import { seoBundledPlugin } from "./seo.plugin";
|
|
6
|
+
import { webhookBundledPlugin } from "./webhook.plugin";
|
|
6
7
|
|
|
7
8
|
/** First-party plugins shipped inside the API package (no separate npm install). */
|
|
8
9
|
export const bundledOpenAdminPlugins: Record<string, OpenAdminPlugin> = {
|
|
9
10
|
hello: helloBundledPlugin,
|
|
10
11
|
seo: seoBundledPlugin,
|
|
11
12
|
"image-optimizer": imageOptimizerBundledPlugin,
|
|
12
|
-
"admin-widget": adminWidgetBundledPlugin
|
|
13
|
+
"admin-widget": adminWidgetBundledPlugin,
|
|
14
|
+
webhook: webhookBundledPlugin
|
|
13
15
|
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
|
|
2
|
+
import { resources } from "../../resources/registry";
|
|
3
|
+
|
|
4
|
+
type WebhookConfig = {
|
|
5
|
+
url?: string;
|
|
6
|
+
secret?: string;
|
|
7
|
+
resources?: string[];
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export const webhookBundledPlugin: OpenAdminPlugin<WebhookConfig> = {
|
|
12
|
+
id: "io.openadminjs.webhook",
|
|
13
|
+
version: "0.1.0",
|
|
14
|
+
displayName: "Webhook bridge",
|
|
15
|
+
register({ config, registerResourceHooks }) {
|
|
16
|
+
const url = typeof config.url === "string" ? config.url.trim() : "";
|
|
17
|
+
if (!url) return;
|
|
18
|
+
const secret = typeof config.secret === "string" ? config.secret : "";
|
|
19
|
+
const timeoutMs = typeof config.timeoutMs === "number" ? Math.max(500, config.timeoutMs) : 8_000;
|
|
20
|
+
const allow = Array.isArray(config.resources) ? new Set(config.resources.map((r) => String(r))) : null;
|
|
21
|
+
|
|
22
|
+
const emit = async (payload: Record<string, unknown>) => {
|
|
23
|
+
const controller = new AbortController();
|
|
24
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
25
|
+
try {
|
|
26
|
+
await fetch(url, {
|
|
27
|
+
method: "POST",
|
|
28
|
+
signal: controller.signal,
|
|
29
|
+
headers: {
|
|
30
|
+
"content-type": "application/json",
|
|
31
|
+
...(secret ? { "x-openadminjs-signature": secret } : {})
|
|
32
|
+
},
|
|
33
|
+
body: JSON.stringify(payload)
|
|
34
|
+
});
|
|
35
|
+
} catch {
|
|
36
|
+
/* fire-and-forget */
|
|
37
|
+
} finally {
|
|
38
|
+
clearTimeout(timeout);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
for (const resource of resources) {
|
|
43
|
+
if (allow && !allow.has(resource.name)) continue;
|
|
44
|
+
registerResourceHooks(resource.name, {
|
|
45
|
+
afterCreate: async (ctx) => {
|
|
46
|
+
await emit({ event: "resource.created", resource: ctx.resourceName, record: ctx.record, actor: ctx.user });
|
|
47
|
+
},
|
|
48
|
+
afterUpdate: async (ctx) => {
|
|
49
|
+
await emit({
|
|
50
|
+
event: "resource.updated",
|
|
51
|
+
resource: ctx.resourceName,
|
|
52
|
+
id: ctx.id,
|
|
53
|
+
before: ctx.before,
|
|
54
|
+
after: ctx.record,
|
|
55
|
+
actor: ctx.user
|
|
56
|
+
});
|
|
57
|
+
},
|
|
58
|
+
afterDelete: async (ctx) => {
|
|
59
|
+
await emit({ event: "resource.deleted", resource: ctx.resourceName, id: ctx.id, actor: ctx.user });
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
};
|
|
@@ -16,6 +16,7 @@ export default defineResource({
|
|
|
16
16
|
id: { type: "id", label: "ID", create: false, edit: false, list: false },
|
|
17
17
|
name: { type: "text", label: "Name", required: true, searchable: true, sortable: true },
|
|
18
18
|
slug: { type: "slug", label: "Slug", from: "name", searchable: true },
|
|
19
|
+
order: { type: "number", label: "Order", list: true, sortable: true, min: 0 },
|
|
19
20
|
createdAt: { type: "datetime", label: "Created at", create: false, edit: false, sortable: true }
|
|
20
21
|
}
|
|
21
22
|
});
|
|
@@ -10,6 +10,7 @@ export const filesResource = defineResource({
|
|
|
10
10
|
fields: {
|
|
11
11
|
id: { type: "id", create: false, edit: false, list: false },
|
|
12
12
|
filename: { type: "text", label: "Filename", searchable: true },
|
|
13
|
+
path: { type: "text", label: "Path", list: false },
|
|
13
14
|
mimeType: { type: "text", label: "MIME", filterable: true },
|
|
14
15
|
size: { type: "number", label: "Size" },
|
|
15
16
|
createdAt: { type: "datetime", label: "Created", create: false, edit: false }
|
|
@@ -2,6 +2,9 @@ export {
|
|
|
2
2
|
buildSeoPagePayload,
|
|
3
3
|
defineResource,
|
|
4
4
|
effectiveLocale,
|
|
5
|
+
formatIcuMessage,
|
|
6
|
+
formatLocalizedIcuMessage,
|
|
7
|
+
formatPlural,
|
|
5
8
|
isSensitiveField,
|
|
6
9
|
listScopeWhereClause,
|
|
7
10
|
mergeWhereClauses,
|
|
@@ -17,7 +20,9 @@ export type {
|
|
|
17
20
|
FieldPermission,
|
|
18
21
|
FieldType,
|
|
19
22
|
ListScopeConfig,
|
|
23
|
+
IcuMessageValues,
|
|
20
24
|
LocalizedLabel,
|
|
25
|
+
PluralFormBundle,
|
|
21
26
|
PermissionMap,
|
|
22
27
|
ResourceAction,
|
|
23
28
|
ResourceActionContext,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { defineConfig } from "vitest/config";
|
|
2
|
+
|
|
3
|
+
/** Prefer workspace package `development` export (TS sources) when `dist/` is not built yet (CI). */
|
|
4
|
+
export default defineConfig({
|
|
5
|
+
resolve: {
|
|
6
|
+
conditions: ["development", "node", "import", "module", "browser", "default"]
|
|
7
|
+
},
|
|
8
|
+
test: { environment: "node" }
|
|
9
|
+
});
|
|
@@ -4,6 +4,14 @@
|
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"development": "./src/index.ts",
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
7
15
|
"scripts": {
|
|
8
16
|
"build": "tsc -p tsconfig.json",
|
|
9
17
|
"lint": "tsc -p tsconfig.json --noEmit",
|
|
@@ -13,5 +21,8 @@
|
|
|
13
21
|
"devDependencies": {
|
|
14
22
|
"typescript": "^5.7.2",
|
|
15
23
|
"vitest": "^2.1.8"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"intl-messageformat": "^11.2.4"
|
|
16
27
|
}
|
|
17
28
|
}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
2
|
import {
|
|
3
3
|
defineResource,
|
|
4
|
+
formatIcuMessage,
|
|
5
|
+
formatLocalizedIcuMessage,
|
|
6
|
+
formatPlural,
|
|
4
7
|
isSensitiveField,
|
|
5
8
|
resolveResourceForLocale,
|
|
6
9
|
validateResource,
|
|
@@ -8,6 +11,48 @@ import {
|
|
|
8
11
|
withSafeFields
|
|
9
12
|
} from "./index";
|
|
10
13
|
|
|
14
|
+
describe("formatPlural", () => {
|
|
15
|
+
it("replaces {count} using English plural rules", () => {
|
|
16
|
+
expect(
|
|
17
|
+
formatPlural("en", 1, { one: "{count} item", other: "{count} items" })
|
|
18
|
+
).toBe("1 item");
|
|
19
|
+
expect(
|
|
20
|
+
formatPlural("en", 42, { one: "{count} item", other: "{count} items" })
|
|
21
|
+
).toBe("42 items");
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
describe("formatIcuMessage", () => {
|
|
26
|
+
it("formats ICU plural rules", () => {
|
|
27
|
+
expect(
|
|
28
|
+
formatIcuMessage("en", "{count, plural, one {# file} other {# files}}", { count: 1 })
|
|
29
|
+
).toBe("1 file");
|
|
30
|
+
expect(
|
|
31
|
+
formatIcuMessage("en", "{count, plural, one {# file} other {# files}}", { count: 5 })
|
|
32
|
+
).toBe("5 files");
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("formats select/plural complex ICU patterns", () => {
|
|
36
|
+
const output = formatIcuMessage(
|
|
37
|
+
"en",
|
|
38
|
+
"{gender, select, male {{count, plural, one {He has # alert} other {He has # alerts}}} female {{count, plural, one {She has # alert} other {She has # alerts}}} other {{count, plural, one {They have # alert} other {They have # alerts}}}}",
|
|
39
|
+
{ gender: "female", count: 3 }
|
|
40
|
+
);
|
|
41
|
+
expect(output).toBe("She has 3 alerts");
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
describe("formatLocalizedIcuMessage", () => {
|
|
46
|
+
it("resolves locale map and renders ICU", () => {
|
|
47
|
+
const label = {
|
|
48
|
+
en: "{count, plural, one {# draft} other {# drafts}}",
|
|
49
|
+
ru: "{count, plural, one {# черновик} few {# черновика} many {# черновиков} other {# черновика}}"
|
|
50
|
+
};
|
|
51
|
+
expect(formatLocalizedIcuMessage(label, "en", { count: 2 })).toBe("2 drafts");
|
|
52
|
+
expect(formatLocalizedIcuMessage(label, "ru", { count: 5 })).toContain("5 ");
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
11
56
|
describe("defineResource", () => {
|
|
12
57
|
it("hides sensitive fields by default", () => {
|
|
13
58
|
const resource = defineResource({
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import IntlMessageFormat from "intl-messageformat";
|
|
2
|
+
|
|
1
3
|
export type FieldType =
|
|
2
4
|
| "id"
|
|
3
5
|
| "text"
|
|
@@ -218,6 +220,67 @@ export function pickLocalizedLabel(label: LocalizedLabel | undefined, locale: st
|
|
|
218
220
|
return label[locale] ?? label[fallbackLocale] ?? Object.values(label)[0] ?? "";
|
|
219
221
|
}
|
|
220
222
|
|
|
223
|
+
/** ICU-style plural categories for `Intl.PluralRules` (locales like `en`, `ru`). */
|
|
224
|
+
export type PluralFormBundle = {
|
|
225
|
+
zero?: string;
|
|
226
|
+
one: string;
|
|
227
|
+
two?: string;
|
|
228
|
+
few?: string;
|
|
229
|
+
many?: string;
|
|
230
|
+
other: string;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Picks the correct plural template for `count` in `locale`, then replaces `{count}`.
|
|
235
|
+
* Use in resource `i18n.translations` blocks for list summaries, pagination, etc.
|
|
236
|
+
*/
|
|
237
|
+
export function formatPlural(locale: string, count: number, forms: PluralFormBundle): string {
|
|
238
|
+
const pr = new Intl.PluralRules(locale);
|
|
239
|
+
const cat = pr.select(count);
|
|
240
|
+
const raw =
|
|
241
|
+
(cat === "zero" && forms.zero) ||
|
|
242
|
+
(cat === "one" && forms.one) ||
|
|
243
|
+
(cat === "two" && forms.two) ||
|
|
244
|
+
(cat === "few" && forms.few) ||
|
|
245
|
+
(cat === "many" && forms.many) ||
|
|
246
|
+
forms.other ||
|
|
247
|
+
forms.one;
|
|
248
|
+
return raw.replace(/\{count\}/g, String(count));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Full ICU MessageFormat strings (plural/select/rich text per Unicode TR35).
|
|
253
|
+
* Example: `"{n, plural, one {# item} other {# items}}"`.
|
|
254
|
+
*/
|
|
255
|
+
export function formatIcuMessage(
|
|
256
|
+
locale: string,
|
|
257
|
+
pattern: string,
|
|
258
|
+
values?: Record<string, string | number | boolean | Date | null | undefined>
|
|
259
|
+
): string {
|
|
260
|
+
try {
|
|
261
|
+
return new IntlMessageFormat(pattern, locale).format(values ?? {}) as string;
|
|
262
|
+
} catch {
|
|
263
|
+
return pattern;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export type IcuMessageValues = Record<string, string | number | boolean | Date | null | undefined>;
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Resolve localized ICU template then render it with `intl-messageformat`.
|
|
271
|
+
* Useful for translation blocks where each locale has its own ICU string.
|
|
272
|
+
*/
|
|
273
|
+
export function formatLocalizedIcuMessage(
|
|
274
|
+
label: LocalizedLabel | undefined,
|
|
275
|
+
locale: string,
|
|
276
|
+
values?: IcuMessageValues,
|
|
277
|
+
fallbackLocale = "en"
|
|
278
|
+
): string {
|
|
279
|
+
const pattern = pickLocalizedLabel(label, locale, fallbackLocale);
|
|
280
|
+
if (!pattern) return "";
|
|
281
|
+
return formatIcuMessage(locale, pattern, values);
|
|
282
|
+
}
|
|
283
|
+
|
|
221
284
|
export function effectiveLocale(resource: ResourceConfig, requested: string | undefined): string {
|
|
222
285
|
const fb = resource.i18n?.defaultLocale ?? "en";
|
|
223
286
|
const locales = resource.i18n?.locales;
|
|
@@ -11,6 +11,8 @@ model User {
|
|
|
11
11
|
id String @id @default(cuid())
|
|
12
12
|
email String @unique
|
|
13
13
|
passwordHash String
|
|
14
|
+
/** Stable IdP subject, format `issuerNormalized::sub` — set when user signs in via OIDC. */
|
|
15
|
+
oidcKey String? @unique
|
|
14
16
|
refreshTokenHash String?
|
|
15
17
|
name String?
|
|
16
18
|
avatarUrl String?
|
|
@@ -70,9 +72,12 @@ model Category {
|
|
|
70
72
|
id String @id @default(cuid())
|
|
71
73
|
name String
|
|
72
74
|
slug String @unique
|
|
75
|
+
order Int @default(0)
|
|
73
76
|
createdAt DateTime @default(now())
|
|
74
77
|
updatedAt DateTime @updatedAt
|
|
75
78
|
posts Post[]
|
|
79
|
+
|
|
80
|
+
@@index([order])
|
|
76
81
|
}
|
|
77
82
|
|
|
78
83
|
model Post {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { buildSeoPagePayload, defineResource, effectiveLocale, isSensitiveField, listScopeWhereClause, mergeWhereClauses, pickLocalizedLabel, resolveResourceForLocale, sensitiveFieldPatterns, shouldApplyListScope, validateResource, visibleFields, withSafeFields } from "@openadminjs/resource";
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
export const DEFAULT_AUTH_REALM = "admin";
|
|
2
|
-
export function realmOf(blueprint) {
|
|
3
|
-
return blueprint.realm ?? DEFAULT_AUTH_REALM;
|
|
4
|
-
}
|
|
5
|
-
export function roleMatrixKey(realm, roleName) {
|
|
6
|
-
return `${realm}:${roleName}`;
|
|
7
|
-
}
|
|
8
|
-
function collectRolePermissions(blueprints, realm, roleName, wildcardSlugs, stack, memo) {
|
|
9
|
-
const memoKey = roleMatrixKey(realm, roleName);
|
|
10
|
-
if (memo.has(memoKey))
|
|
11
|
-
return new Set(memo.get(memoKey));
|
|
12
|
-
if (stack.has(memoKey)) {
|
|
13
|
-
throw new Error(`Circular role inheritance involving "${realm}:${roleName}"`);
|
|
14
|
-
}
|
|
15
|
-
const bp = blueprints.find((b) => b.name === roleName && realmOf(b) === realm);
|
|
16
|
-
if (!bp) {
|
|
17
|
-
throw new Error(`Unknown role blueprint: "${roleName}" in realm "${realm}"`);
|
|
18
|
-
}
|
|
19
|
-
stack.add(memoKey);
|
|
20
|
-
const out = new Set();
|
|
21
|
-
for (const parent of bp.inherits ?? []) {
|
|
22
|
-
for (const p of collectRolePermissions(blueprints, realm, parent, wildcardSlugs, stack, memo)) {
|
|
23
|
-
out.add(p);
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
for (const p of bp.permissions ?? []) {
|
|
27
|
-
if (p === "*") {
|
|
28
|
-
out.add("*");
|
|
29
|
-
for (const s of wildcardSlugs)
|
|
30
|
-
out.add(s);
|
|
31
|
-
}
|
|
32
|
-
else {
|
|
33
|
-
out.add(p);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
stack.delete(memoKey);
|
|
37
|
-
memo.set(memoKey, out);
|
|
38
|
-
return out;
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Resolves inherits + wildcard expansion within one realm.
|
|
42
|
-
* When `slugsByRealm` is set, `"*"` expands only that realm's slug list (so admin superusers do not silently gain storefront-only slugs unless you assign them).
|
|
43
|
-
*/
|
|
44
|
-
export function expandRolePermissions(blueprints, realm, roleName, allPermissionSlugs, slugsByRealm) {
|
|
45
|
-
const wildcardSlugs = slugsByRealm?.[realm] ?? allPermissionSlugs;
|
|
46
|
-
return collectRolePermissions(blueprints, realm, roleName, wildcardSlugs, new Set(), new Map());
|
|
47
|
-
}
|
|
48
|
-
/** Every blueprint gets a frozen permission array keyed as `realm:roleName`. */
|
|
49
|
-
export function materializeAllRoles(blueprints, allPermissionSlugs, slugsByRealm) {
|
|
50
|
-
const map = new Map();
|
|
51
|
-
for (const bp of blueprints) {
|
|
52
|
-
const r = realmOf(bp);
|
|
53
|
-
const set = expandRolePermissions(blueprints, r, bp.name, allPermissionSlugs, slugsByRealm);
|
|
54
|
-
map.set(roleMatrixKey(r, bp.name), [...set].sort());
|
|
55
|
-
}
|
|
56
|
-
return map;
|
|
57
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
export { DEFAULT_AUTH_REALM, expandRolePermissions, materializeAllRoles, realmOf, roleMatrixKey } from "./blueprints";
|
|
2
|
-
export function can(permissions, permission) {
|
|
3
|
-
return permissions.includes(permission) || permissions.includes("*");
|
|
4
|
-
}
|
|
5
|
-
export function requirePermission(permissions, permission) {
|
|
6
|
-
if (!can(permissions, permission)) {
|
|
7
|
-
const error = new Error(`Missing permission: ${permission}`);
|
|
8
|
-
error.name = "ForbiddenError";
|
|
9
|
-
throw error;
|
|
10
|
-
}
|
|
11
|
-
}
|