openadminjs 0.1.24 → 0.3.0-rc.1
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 +117 -81
- package/dist/adapt-package-manager.d.ts +3 -0
- package/dist/adapt-package-manager.js +118 -0
- package/dist/create-project.d.ts +77 -2
- package/dist/create-project.js +685 -224
- package/dist/db-commands.d.ts +20 -0
- package/dist/db-commands.js +75 -0
- package/dist/detect-package-manager.d.ts +8 -0
- package/dist/detect-package-manager.js +37 -0
- package/dist/doctor.d.ts +26 -0
- package/dist/doctor.js +232 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +476 -166
- package/dist/render-schema.d.ts +3 -0
- package/dist/render-schema.js +33 -0
- package/dist/resource-slug.d.ts +1 -0
- package/dist/resource-slug.js +7 -0
- package/dist/runtime-mode.d.ts +16 -0
- package/dist/runtime-mode.js +138 -0
- package/dist/secrets.d.ts +24 -0
- package/dist/secrets.js +93 -0
- package/dist/security.d.ts +13 -0
- package/dist/security.js +168 -0
- package/dist/upgrade.d.ts +10 -0
- package/dist/upgrade.js +133 -0
- package/dist/validate-name.d.ts +33 -0
- package/dist/validate-name.js +206 -0
- package/package.json +39 -11
- package/template/.dockerignore +15 -0
- package/template/.env.production.example +5 -0
- package/template/Dockerfile +12 -0
- package/template/README.md +23 -3
- package/template/apps/admin/app/api/auth/login/route.ts +9 -9
- package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
- package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
- package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
- package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
- package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
- package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
- package/template/apps/admin/app/api-tokens/page.tsx +39 -39
- package/template/apps/admin/app/assistant/page.tsx +11 -0
- package/template/apps/admin/app/dashboard/page.tsx +45 -462
- package/template/apps/admin/app/globals.css +52 -16
- package/template/apps/admin/app/layout.tsx +1 -1
- package/template/apps/admin/app/login/page.tsx +13 -145
- package/template/apps/admin/app/plugins/page.tsx +16 -402
- package/template/apps/admin/app/profile/page.tsx +5 -2
- package/template/apps/admin/app/settings/page.tsx +14 -265
- package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
- package/template/apps/admin/components/app-shell.tsx +25 -373
- package/template/apps/admin/components/auth-guard.tsx +8 -28
- package/template/apps/admin/components/logo.tsx +1 -30
- package/template/apps/admin/components/resource-form.tsx +3 -3
- package/template/apps/admin/components/resource-table.tsx +12 -8
- package/template/apps/admin/lib/api.ts +45 -107
- package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
- package/template/apps/admin/lib/server-api.ts +7 -0
- package/template/apps/admin/lib/tokens.ts +9 -81
- package/template/apps/admin/middleware.ts +9 -50
- package/template/apps/admin/next.config.mjs +4 -0
- package/template/apps/admin/package.json +2 -1
- package/template/apps/admin/public/brand/favicon.svg +4 -1
- package/template/apps/admin/tailwind.config.ts +9 -8
- package/template/apps/api/package.json +13 -6
- package/template/apps/api/src/access/catalog.ts +4 -0
- package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
- package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
- package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
- package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
- package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
- package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
- package/template/apps/api/src/admin/admin.controller.ts +17 -4
- package/template/apps/api/src/admin/admin.module.ts +2 -2
- package/template/apps/api/src/admin/resource-policy.ts +1 -0
- package/template/apps/api/src/admin/resource-query.ts +1 -0
- package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
- package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
- package/template/apps/api/src/auth/auth.controller.ts +4 -2
- package/template/apps/api/src/auth/auth.service.ts +68 -83
- package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
- package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
- package/template/apps/api/src/common/api-exception.filter.ts +1 -0
- package/template/apps/api/src/common/auth.guard.ts +66 -39
- package/template/apps/api/src/common/json-field-codec.ts +138 -0
- package/template/apps/api/src/common/prisma.service.ts +12 -7
- package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
- package/template/apps/api/src/graphql/graphql.module.ts +14 -1
- package/template/apps/api/src/health/health.controller.ts +6 -0
- package/template/apps/api/src/main.ts +11 -2
- package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
- package/template/apps/api/src/resources/commerce.resource.ts +3 -34
- package/template/apps/api/src/resources/operations.resource.ts +1 -0
- package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
- package/template/apps/api/src/store/payment/payment.module.ts +2 -3
- package/template/apps/api/src/store/payment/payment.service.ts +121 -227
- package/template/apps/api/webpack.config.cjs +2 -1
- package/template/apps/web/next.config.mjs +4 -0
- package/template/apps/web/public/brand/favicon.svg +4 -1
- package/template/compose.yaml +56 -0
- package/template/examples/crm-admin/README.md +31 -0
- package/template/examples/crm-admin/package.json +17 -0
- package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
- package/template/examples/crm-admin/src/index.ts +7 -0
- package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
- package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
- package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
- package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
- package/template/examples/crm-admin/tsconfig.json +7 -0
- package/template/package.json +8 -1
- package/template/packages/admin-client/package.json +18 -0
- package/template/packages/admin-client/src/contracts.ts +29 -0
- package/template/packages/admin-client/src/index.ts +2 -0
- package/template/packages/admin-client/src/preferences.ts +57 -0
- package/template/packages/admin-client/tsconfig.json +12 -0
- package/template/packages/auth/package.json +1 -1
- package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
- package/template/packages/brand/src/generate-assets.mjs +17 -186
- package/template/packages/core/package.json +1 -1
- package/template/packages/mail/package.json +1 -1
- package/template/packages/nest/package.json +22 -0
- package/template/packages/nest/src/api-exception.filter.ts +23 -0
- package/template/packages/nest/src/index.ts +3 -0
- package/template/packages/nest/src/resource-policy.ts +64 -0
- package/template/packages/nest/src/resource-query.ts +103 -0
- package/template/packages/nest/tsconfig.json +12 -0
- package/template/packages/notifications/package.json +1 -1
- package/template/packages/payments/package.json +1 -1
- package/template/packages/permissions/package.json +1 -1
- package/template/packages/permissions/src/index.ts +2 -2
- package/template/packages/plugin-sdk/package.json +1 -1
- package/template/packages/plugin-sdk/src/index.ts +2 -2
- package/template/packages/prisma/package.json +21 -0
- package/template/packages/prisma/schema/ai.prisma +36 -0
- package/template/packages/prisma/schema/audit.prisma +13 -0
- package/template/packages/prisma/schema/commerce.prisma +79 -0
- package/template/packages/prisma/schema/content.prisma +27 -0
- package/template/packages/prisma/schema/core.prisma +106 -0
- package/template/packages/prisma/schema/header.prisma +8 -0
- package/template/packages/prisma/schema/jobs.prisma +9 -0
- package/template/packages/prisma/schema/media.prisma +9 -0
- package/template/packages/prisma/schema/modules.json +47 -0
- package/template/packages/prisma/schema/notifications.prisma +9 -0
- package/template/packages/prisma/schema/settings.prisma +8 -0
- package/template/packages/prisma/schema/tokens.prisma +10 -0
- package/template/packages/prisma/src/index.d.ts +12 -0
- package/template/packages/prisma/src/index.mjs +138 -0
- package/template/packages/queue/package.json +1 -1
- package/template/packages/resource/package.json +1 -1
- package/template/packages/resource/src/index.ts +1 -0
- package/template/packages/storage/package.json +1 -1
- package/template/packages/storage/src/index.ts +37 -0
- package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -0
- package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
- package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
- package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
- package/template/prisma/schema.prisma +82 -54
- package/template/prisma/seed.ts +14 -38
- package/template/runtime-versions.json +15 -0
- package/template/scripts/db-init.mjs +33 -0
- package/template/scripts/install-crm.mjs +50 -0
- package/template/scripts/migrate-existing.mjs +65 -0
- package/template/scripts/schema.mjs +48 -0
- package/template/tsconfig.base.json +23 -5
- package/LICENSE +0 -21
- package/dist/create-project.test.d.ts +0 -1
- package/dist/create-project.test.js +0 -99
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -7
- package/dist/resource-slug.test.d.ts +0 -1
- package/dist/resource-slug.test.js +0 -9
- package/template/apps/admin/.storybook/main.ts +0 -12
- package/template/apps/admin/.storybook/preview.ts +0 -10
- package/template/apps/admin/app/login/page.test.tsx +0 -18
- package/template/apps/admin/components/auth-guard.test.tsx +0 -55
- package/template/apps/admin/components/logo.stories.tsx +0 -24
- package/template/apps/admin/lib/api.test.ts +0 -118
- package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
- package/template/apps/admin/vitest.config.ts +0 -7
- package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
- package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
- package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
- package/template/apps/api/src/app.module.test.ts +0 -12
- package/template/apps/api/src/auth/auth.service.test.ts +0 -78
- package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
- package/template/apps/api/src/common/auth.guard.test.ts +0 -62
- package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
- package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
- package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
- package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
- package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
- package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
- package/template/apps/api/src/queue/queue.service.test.ts +0 -33
- package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
- package/template/apps/api/vitest.config.ts +0 -21
- package/template/apps/web/lib/seo.test.ts +0 -41
- package/template/apps/web/vitest.config.ts +0 -19
- package/template/packages/auth/src/index.test.ts +0 -10
- package/template/packages/brand/src/index.test.ts +0 -9
- package/template/packages/core/src/index.test.ts +0 -27
- package/template/packages/core/vitest.config.ts +0 -9
- package/template/packages/mail/src/index.test.ts +0 -23
- package/template/packages/notifications/src/index.test.ts +0 -9
- package/template/packages/permissions/src/blueprints.test.ts +0 -62
- package/template/packages/permissions/src/index.test.ts +0 -34
- package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
- package/template/packages/plugin-sdk/vitest.config.ts +0 -5
- package/template/packages/queue/src/index.test.ts +0 -12
- package/template/packages/resource/src/index.test.ts +0 -196
- package/template/packages/storage/src/index.test.ts +0 -10
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { defineResource } from "@openadminjs/core";
|
|
2
|
+
|
|
3
|
+
export default defineResource({
|
|
4
|
+
name: "deals",
|
|
5
|
+
label: "Deals",
|
|
6
|
+
model: "deal",
|
|
7
|
+
titleField: "title",
|
|
8
|
+
icon: "Handshake",
|
|
9
|
+
permissions: {
|
|
10
|
+
read: "deals.read",
|
|
11
|
+
create: "deals.create",
|
|
12
|
+
update: "deals.update",
|
|
13
|
+
delete: "deals.delete"
|
|
14
|
+
},
|
|
15
|
+
fields: {
|
|
16
|
+
id: { type: "id", label: "ID", create: false, edit: false, list: false },
|
|
17
|
+
title: { type: "text", label: "Title", required: true, searchable: true, sortable: true },
|
|
18
|
+
stage: {
|
|
19
|
+
type: "select",
|
|
20
|
+
label: "Stage",
|
|
21
|
+
options: ["lead", "qualified", "proposal", "won", "lost"],
|
|
22
|
+
filterable: true,
|
|
23
|
+
sortable: true
|
|
24
|
+
},
|
|
25
|
+
amount: { type: "money", label: "Amount", sortable: true },
|
|
26
|
+
companyId: { type: "relation", label: "Company", resource: "companies", displayField: "name", filterable: true },
|
|
27
|
+
contactId: { type: "relation", label: "Contact", resource: "contacts", displayField: "email", filterable: true },
|
|
28
|
+
createdAt: { type: "datetime", label: "Created", create: false, edit: false, sortable: true }
|
|
29
|
+
}
|
|
30
|
+
});
|
package/template/package.json
CHANGED
|
@@ -11,9 +11,16 @@
|
|
|
11
11
|
"typecheck": "pnpm -r typecheck",
|
|
12
12
|
"test": "pnpm -r test",
|
|
13
13
|
"db:migrate": "pnpm --filter @openadminjs/api db:migrate",
|
|
14
|
+
"db:migrate:deploy": "pnpm --filter @openadminjs/api db:migrate:deploy",
|
|
14
15
|
"db:seed": "pnpm --filter @openadminjs/api db:seed",
|
|
15
16
|
"db:studio": "pnpm --filter @openadminjs/api db:studio",
|
|
16
|
-
"
|
|
17
|
+
"db:reset": "pnpm --filter @openadminjs/api db:reset",
|
|
18
|
+
"generate": "pnpm --filter @openadminjs/api generate",
|
|
19
|
+
"schema:check": "node scripts/schema.mjs check",
|
|
20
|
+
"schema:compose": "node scripts/schema.mjs compose",
|
|
21
|
+
"schema:adopt": "node scripts/schema.mjs adopt",
|
|
22
|
+
"schema:upgrade-plan": "node scripts/migrate-existing.mjs",
|
|
23
|
+
"db:init": "node scripts/db-init.mjs"
|
|
17
24
|
},
|
|
18
25
|
"devDependencies": {
|
|
19
26
|
"@prisma/client": "^6.1.0",
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@openadminjs/admin-client",
|
|
3
|
+
"version": "0.2.0-rc.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"types": "src/index.ts",
|
|
8
|
+
"dependencies": {},
|
|
9
|
+
"peerDependencies": {},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsc -p tsconfig.json",
|
|
12
|
+
"lint": "tsc -p tsconfig.json --noEmit",
|
|
13
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
14
|
+
},
|
|
15
|
+
"devDependencies": {
|
|
16
|
+
"typescript": "^5.7.2"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type ResourceMeta = {
|
|
2
|
+
name: string;
|
|
3
|
+
label: string;
|
|
4
|
+
icon?: string;
|
|
5
|
+
titleField?: string;
|
|
6
|
+
permissions: Record<string, string>;
|
|
7
|
+
fields: Record<
|
|
8
|
+
string,
|
|
9
|
+
{
|
|
10
|
+
type: string;
|
|
11
|
+
label?: string;
|
|
12
|
+
list?: boolean;
|
|
13
|
+
create?: boolean;
|
|
14
|
+
edit?: boolean;
|
|
15
|
+
required?: boolean;
|
|
16
|
+
sortable?: boolean;
|
|
17
|
+
searchable?: boolean;
|
|
18
|
+
filterable?: boolean;
|
|
19
|
+
sensitive?: boolean;
|
|
20
|
+
resource?: string;
|
|
21
|
+
displayField?: string;
|
|
22
|
+
options?: string[];
|
|
23
|
+
}
|
|
24
|
+
>;
|
|
25
|
+
actions?: Record<string, { label: string; variant?: string; confirm?: boolean; permission: string }>;
|
|
26
|
+
i18n?: { defaultLocale?: string; locales?: readonly string[] };
|
|
27
|
+
seo?: { public?: boolean; slugField?: string; pathPattern?: string; titleField?: string; descriptionField?: string };
|
|
28
|
+
};
|
|
29
|
+
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
const PREFIX = "openadminjs.resourceTable.";
|
|
2
|
+
|
|
3
|
+
function keyColumnOrder(resourceName: string): string {
|
|
4
|
+
return `${PREFIX}${resourceName}.columnOrder`;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function keyDensity(resourceName: string): string {
|
|
8
|
+
return `${PREFIX}${resourceName}.density`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type TableDensity = "comfortable" | "compact";
|
|
12
|
+
|
|
13
|
+
export function loadColumnOrder(resourceName: string, allowed: string[]): string[] {
|
|
14
|
+
if (typeof window === "undefined") return allowed;
|
|
15
|
+
try {
|
|
16
|
+
const raw = window.localStorage.getItem(keyColumnOrder(resourceName));
|
|
17
|
+
if (!raw) return allowed;
|
|
18
|
+
const parsed = JSON.parse(raw) as unknown;
|
|
19
|
+
if (!Array.isArray(parsed)) return allowed;
|
|
20
|
+
const set = new Set(allowed);
|
|
21
|
+
const ordered = [...new Set(parsed.map(String).filter((n) => set.has(n)))];
|
|
22
|
+
for (const n of allowed) {
|
|
23
|
+
if (!ordered.includes(n)) ordered.push(n);
|
|
24
|
+
}
|
|
25
|
+
return ordered;
|
|
26
|
+
} catch {
|
|
27
|
+
return allowed;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function saveColumnOrder(resourceName: string, order: string[]): void {
|
|
32
|
+
if (typeof window === "undefined") return;
|
|
33
|
+
try {
|
|
34
|
+
window.localStorage.setItem(keyColumnOrder(resourceName), JSON.stringify(order));
|
|
35
|
+
} catch {
|
|
36
|
+
/* ignore */
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function loadDensity(resourceName: string): TableDensity {
|
|
41
|
+
if (typeof window === "undefined") return "comfortable";
|
|
42
|
+
try {
|
|
43
|
+
const v = window.localStorage.getItem(keyDensity(resourceName));
|
|
44
|
+
return v === "compact" ? "compact" : "comfortable";
|
|
45
|
+
} catch {
|
|
46
|
+
return "comfortable";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function saveDensity(resourceName: string, density: TableDensity): void {
|
|
51
|
+
if (typeof window === "undefined") return;
|
|
52
|
+
try {
|
|
53
|
+
window.localStorage.setItem(keyDensity(resourceName), density);
|
|
54
|
+
} catch {
|
|
55
|
+
/* ignore */
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="OpenAdminJS
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="OpenAdminJS">
|
|
2
|
+
<rect width="64" height="64" rx="13" fill="#101820"/>
|
|
3
|
+
<path fill="#B9F56D" d="M29 13a19 19 0 1 0 0 38h9l11-23 7 15H45l-4 8h18L42 13h-8L21 42a11 11 0 1 1 8-21l3-7z"/>
|
|
4
|
+
</svg>
|
|
@@ -1,189 +1,20 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* - openadminjs-icon-new.png (optional) — square mark for favicon / app icon; falls back to logo if missing
|
|
5
|
-
*
|
|
6
|
-
* Outputs PNG + thin SVG wrappers (`<image href="…"/>`) for each target directory.
|
|
7
|
-
*/
|
|
8
|
-
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
1
|
+
/** Reproducible Open Core vector masters; no dependency on an external PNG. */
|
|
2
|
+
import sharp from "sharp";
|
|
3
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
9
4
|
import { join, dirname } from "node:path";
|
|
10
5
|
import { fileURLToPath } from "node:url";
|
|
11
|
-
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
"apps/admin/public/brand",
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
"
|
|
25
|
-
];
|
|
26
|
-
|
|
27
|
-
const UNUSED_BRAND_FILES = [
|
|
28
|
-
"openadminjs-logo-horizontal.svg",
|
|
29
|
-
"openadminjs-logo.svg",
|
|
30
|
-
"openadminjs-logo-dark.svg",
|
|
31
|
-
"openadminjs-logo-monochrome.svg",
|
|
32
|
-
"openadminjs-icon.png",
|
|
33
|
-
"openadminjs-icon.svg",
|
|
34
|
-
"og-image.svg",
|
|
35
|
-
"favicon.png"
|
|
36
|
-
];
|
|
37
|
-
|
|
38
|
-
/** SVG shell so browsers can scale; raster lives alongside as `href`. */
|
|
39
|
-
function svgRasterImage(href, w, h, label) {
|
|
40
|
-
const safe = String(label).replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
41
|
-
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 ${w} ${h}" role="img" aria-label="${safe}"><image xlink:href="${href}" href="${href}" width="${w}" height="${h}" preserveAspectRatio="xMidYMid meet"/></svg>`;
|
|
6
|
+
const root=join(dirname(fileURLToPath(import.meta.url)),"../../..");
|
|
7
|
+
const mark="M29 13a19 19 0 1 0 0 38h9l11-23 7 15H45l-4 8h18L42 13h-8L21 42a11 11 0 1 1 8-21l3-7z";
|
|
8
|
+
const svg=(w,h,content)=>`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" role="img" aria-label="OpenAdminJS">${content}</svg>`;
|
|
9
|
+
const icon=svg(64,64,`<rect width="64" height="64" rx="13" fill="#101820"/><path fill="#B9F56D" d="${mark}"/>`);
|
|
10
|
+
const word=(ink,accent)=>svg(480,96,`<g transform="translate(4 16)"><path fill="${accent}" d="${mark}"/></g><text x="78" y="64" font-family="Arial, sans-serif" font-weight="700" font-size="49" letter-spacing="-2" fill="${ink}">OpenAdmin<tspan fill="${accent}">JS</tspan></text>`);
|
|
11
|
+
const og=svg(1200,630,`<rect width="1200" height="630" fill="#101820"/><path d="M1200 110V630H630Z" fill="#B9F56D"/><g transform="translate(72 60) scale(1.3)"><path fill="#B9F56D" d="${mark}"/></g><text x="170" y="119" font-family="Arial,sans-serif" font-size="43" font-weight="700" fill="#F5F7F2">OpenAdminJS</text><text x="78" y="292" font-family="Arial,sans-serif" font-size="86" font-weight="700" letter-spacing="-4" fill="#F5F7F2">Define once.</text><text x="78" y="385" font-family="Arial,sans-serif" font-size="86" font-weight="700" letter-spacing="-4" fill="#B9F56D">Build your admin.</text><text x="80" y="500" font-family="Arial,sans-serif" font-size="25" fill="#d2dbd7">NestJS / Prisma / Next.js</text>`);
|
|
12
|
+
if(!process.argv.includes("--check")){
|
|
13
|
+
const targets=["apps/admin/public/brand","apps/web/public/brand","site/assets/brand"].filter(path=>!path.startsWith("site/")||existsSync(join(root,"site")));
|
|
14
|
+
for(const rel of targets){
|
|
15
|
+
const dir=join(root,rel);mkdirSync(dir,{recursive:true});
|
|
16
|
+
for(const [name,value] of Object.entries({"favicon.svg":icon,"openadminjs-icon.svg":icon,"openadminjs-logo.svg":word("#101820","#426b1d"),"openadminjs-logo-dark.svg":word("#F5F7F2","#B9F56D"),"openadminjs-logo-monochrome.svg":word("#ffffff","#ffffff"),"og-image.svg":og}))writeFileSync(join(dir,name),value);
|
|
17
|
+
for(const [name,value,size] of [["openadminjs-logo-new.png",word("#101820","#426b1d"),960],["openadminjs-logo-monochrome.png",word("#ffffff","#ffffff"),960],["openadminjs-icon-new.png",icon,512],["favicon-16.png",icon,16],["favicon-32.png",icon,32],["favicon-48.png",icon,48],["apple-touch-icon.png",icon,180],["og-image.png",og,1200]])await sharp(Buffer.from(value)).resize(size).png().toFile(join(dir,name));
|
|
18
|
+
}
|
|
19
|
+
console.log("Open Core vector and raster assets generated");
|
|
42
20
|
}
|
|
43
|
-
|
|
44
|
-
async function extractLogoMark(sharp, logoBuf) {
|
|
45
|
-
const { data, info } = await sharp(logoBuf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
46
|
-
const { width, height, channels } = info;
|
|
47
|
-
const alphaIndex = channels - 1;
|
|
48
|
-
|
|
49
|
-
const activeCols = new Array(width).fill(false);
|
|
50
|
-
for (let x = 0; x < width; x += 1) {
|
|
51
|
-
for (let y = 0; y < height; y += 1) {
|
|
52
|
-
const idx = (y * width + x) * channels + alphaIndex;
|
|
53
|
-
if (data[idx] > 18) {
|
|
54
|
-
activeCols[x] = true;
|
|
55
|
-
break;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
let symbolStart = activeCols.findIndex(Boolean);
|
|
61
|
-
if (symbolStart < 0) symbolStart = 0;
|
|
62
|
-
|
|
63
|
-
let symbolEnd = width - 1;
|
|
64
|
-
let gap = 0;
|
|
65
|
-
for (let x = symbolStart; x < width; x += 1) {
|
|
66
|
-
if (activeCols[x]) {
|
|
67
|
-
gap = 0;
|
|
68
|
-
symbolEnd = x;
|
|
69
|
-
continue;
|
|
70
|
-
}
|
|
71
|
-
gap += 1;
|
|
72
|
-
if (gap >= 10) break;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const activeRows = new Array(height).fill(false);
|
|
76
|
-
for (let y = 0; y < height; y += 1) {
|
|
77
|
-
for (let x = symbolStart; x <= symbolEnd; x += 1) {
|
|
78
|
-
const idx = (y * width + x) * channels + alphaIndex;
|
|
79
|
-
if (data[idx] > 18) {
|
|
80
|
-
activeRows[y] = true;
|
|
81
|
-
break;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
let top = activeRows.findIndex(Boolean);
|
|
87
|
-
if (top < 0) top = 0;
|
|
88
|
-
let bottom = height - 1;
|
|
89
|
-
for (let y = height - 1; y >= 0; y -= 1) {
|
|
90
|
-
if (activeRows[y]) {
|
|
91
|
-
bottom = y;
|
|
92
|
-
break;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
const markW = Math.max(1, symbolEnd - symbolStart + 1);
|
|
97
|
-
const markH = Math.max(1, bottom - top + 1);
|
|
98
|
-
const side = Math.max(markW, markH);
|
|
99
|
-
const cx = symbolStart + markW / 2;
|
|
100
|
-
const cy = top + markH / 2;
|
|
101
|
-
|
|
102
|
-
let left = Math.floor(cx - side / 2);
|
|
103
|
-
let cropTop = Math.floor(cy - side / 2);
|
|
104
|
-
if (left < 0) left = 0;
|
|
105
|
-
if (cropTop < 0) cropTop = 0;
|
|
106
|
-
if (left + side > width) left = width - side;
|
|
107
|
-
if (cropTop + side > height) cropTop = height - side;
|
|
108
|
-
|
|
109
|
-
return sharp(logoBuf)
|
|
110
|
-
.extract({ left: Math.max(0, left), top: Math.max(0, cropTop), width: Math.min(side, width), height: Math.min(side, height) })
|
|
111
|
-
.resize(512, 512, { fit: "cover" })
|
|
112
|
-
.png()
|
|
113
|
-
.toBuffer();
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async function writeBrandToDir(sharp, targetDir) {
|
|
117
|
-
mkdirSync(targetDir, { recursive: true });
|
|
118
|
-
|
|
119
|
-
const logoBuf = readFileSync(LOGO_SRC);
|
|
120
|
-
const logoMeta = await sharp(logoBuf).metadata();
|
|
121
|
-
const lw = logoMeta.width ?? 800;
|
|
122
|
-
const lh = logoMeta.height ?? 200;
|
|
123
|
-
|
|
124
|
-
writeFileSync(join(targetDir, "openadminjs-logo-new.png"), logoBuf);
|
|
125
|
-
|
|
126
|
-
const monoPng = await sharp(logoBuf).grayscale().png().toBuffer();
|
|
127
|
-
writeFileSync(join(targetDir, "openadminjs-logo-monochrome.png"), monoPng);
|
|
128
|
-
|
|
129
|
-
const iconBuf = await extractLogoMark(sharp, logoBuf);
|
|
130
|
-
writeFileSync(join(targetDir, "openadminjs-icon-new.png"), iconBuf);
|
|
131
|
-
|
|
132
|
-
writeFileSync(join(targetDir, "favicon.svg"), svgRasterImage("openadminjs-icon-new.png", 512, 512, "OpenAdminJS"));
|
|
133
|
-
|
|
134
|
-
const apple = await sharp(iconBuf).resize(180, 180, { fit: "cover" }).png().toBuffer();
|
|
135
|
-
writeFileSync(join(targetDir, "apple-touch-icon.png"), apple);
|
|
136
|
-
|
|
137
|
-
const ogW = 1200;
|
|
138
|
-
const ogH = 630;
|
|
139
|
-
const logoForOg = await sharp(logoBuf).resize(560, null, { fit: "inside" }).png().toBuffer();
|
|
140
|
-
const ogLm = await sharp(logoForOg).metadata();
|
|
141
|
-
const logoH = ogLm.height ?? 0;
|
|
142
|
-
const top = Math.max(0, Math.round((ogH - logoH) / 2));
|
|
143
|
-
const ogPng = await sharp({
|
|
144
|
-
create: { width: ogW, height: ogH, channels: 4, background: { r: 248, g: 251, b: 255, alpha: 1 } }
|
|
145
|
-
})
|
|
146
|
-
.composite([{ input: logoForOg, left: 72, top }])
|
|
147
|
-
.png()
|
|
148
|
-
.toBuffer();
|
|
149
|
-
writeFileSync(join(targetDir, "og-image.png"), ogPng);
|
|
150
|
-
|
|
151
|
-
for (const filename of UNUSED_BRAND_FILES) {
|
|
152
|
-
const full = join(targetDir, filename);
|
|
153
|
-
if (existsSync(full)) unlinkSync(full);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
async function main() {
|
|
158
|
-
if (process.argv.includes("--check")) {
|
|
159
|
-
if (!existsSync(LOGO_SRC)) {
|
|
160
|
-
console.error(`Missing required source: ${LOGO_SRC}`);
|
|
161
|
-
process.exit(1);
|
|
162
|
-
}
|
|
163
|
-
process.exit(0);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
if (!existsSync(LOGO_SRC)) {
|
|
167
|
-
throw new Error(`Missing required source logo: ${LOGO_SRC}`);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
let sharp;
|
|
171
|
-
try {
|
|
172
|
-
const sharpModule = await import("sharp");
|
|
173
|
-
sharp = sharpModule.default;
|
|
174
|
-
} catch {
|
|
175
|
-
throw new Error("Missing optional dependency 'sharp'. Install dependencies before generating brand assets.");
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
for (const rel of targets) {
|
|
179
|
-
const dir = join(repoRoot, rel);
|
|
180
|
-
await writeBrandToDir(sharp, dir);
|
|
181
|
-
console.log("Wrote", rel);
|
|
182
|
-
}
|
|
183
|
-
console.log("Brand assets generated from openadminjs-logo-new.png");
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
main().catch((e) => {
|
|
187
|
-
console.error(e);
|
|
188
|
-
process.exit(1);
|
|
189
|
-
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@openadminjs/nest",
|
|
3
|
+
"version": "0.2.0-rc.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"types": "src/index.ts",
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"@openadminjs/core": "workspace:*"
|
|
10
|
+
},
|
|
11
|
+
"peerDependencies": {
|
|
12
|
+
"@nestjs/common": "11.1.21"
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "tsc -p tsconfig.json",
|
|
16
|
+
"lint": "tsc -p tsconfig.json --noEmit",
|
|
17
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"typescript": "^5.7.2"
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ArgumentsHost,Catch,ExceptionFilter,HttpException } from "@nestjs/common";
|
|
2
|
+
type Response = { headersSent:boolean; status(code:number):Response; json(body:unknown):void; getHeader(name:string):unknown };
|
|
3
|
+
@Catch()
|
|
4
|
+
export class ApiExceptionFilter implements ExceptionFilter {
|
|
5
|
+
catch(exception:unknown,host:ArgumentsHost) {
|
|
6
|
+
if(host.getType()!=="http") throw exception;
|
|
7
|
+
const res=host.switchToHttp().getResponse<Response>();
|
|
8
|
+
if(res.headersSent) return;
|
|
9
|
+
let status=500,code="INTERNAL_ERROR",message:unknown="Internal request failure";
|
|
10
|
+
let details:unknown;
|
|
11
|
+
if(exception instanceof HttpException){
|
|
12
|
+
status=exception.getStatus();
|
|
13
|
+
const body=exception.getResponse();
|
|
14
|
+
const obj=typeof body==="object"&&body!==null?body as Record<string,unknown>:null;
|
|
15
|
+
if(status<500){code=typeof obj?.code==="string"?obj.code:"HTTP_"+status;message=obj?.message??body;details=obj?.details;}
|
|
16
|
+
}else if(exception&&typeof exception==="object"&&"code" in exception){
|
|
17
|
+
const p=(exception as {code:unknown}).code;
|
|
18
|
+
if(p==="P2002"||p==="P2003"){status=409;code="CONFLICT";message="Record conflicts with existing data";}
|
|
19
|
+
if(p==="P2025"){status=404;code="NOT_FOUND";message="Record not found";}
|
|
20
|
+
}
|
|
21
|
+
res.status(status).json({statusCode:status,code,message,requestId:res.getHeader("x-request-id"),...(details===undefined?{}:{details})});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { BadRequestException, ForbiddenException } from "@nestjs/common";
|
|
2
|
+
import { isSensitiveField, shouldApplyListScope, listScopeWhereClause } from "@openadminjs/core";
|
|
3
|
+
import type { ResourceConfig } from "@openadminjs/core";
|
|
4
|
+
export type UserContext = { id: string; email?: string; permissions: string[] };
|
|
5
|
+
export function isOutOfListScope(resource: ResourceConfig, user: UserContext, record: unknown): boolean {
|
|
6
|
+
if (resource.name === "settings" && String((record as Record<string, unknown>).key ?? "").toLowerCase().startsWith("ai.")) return true;
|
|
7
|
+
if (!shouldApplyListScope(resource, user.permissions)) return false;
|
|
8
|
+
const clause = listScopeWhereClause(resource, user.id);
|
|
9
|
+
if (!clause) return false;
|
|
10
|
+
const row = record as Record<string, unknown>;
|
|
11
|
+
for (const [key, expected] of Object.entries(clause)) {
|
|
12
|
+
if (row[key] !== expected) return true;
|
|
13
|
+
}
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function has(user: UserContext, permission?: string) {
|
|
18
|
+
return Boolean(permission && (user.permissions.includes(permission) || user.permissions.includes("*")));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function systemScope(resource: ResourceConfig) {
|
|
22
|
+
return resource.name === "settings" ? { NOT: { key: { startsWith: "ai." } } } : undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function canReadField(resource: ResourceConfig, name: string, user: UserContext) {
|
|
26
|
+
const field = Object.hasOwn(resource.fields, name) ? resource.fields[name] : undefined;
|
|
27
|
+
return Boolean(field && !isSensitiveField(name, field) && (!field.permissions?.read || has(user, field.permissions.read)));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function safeData(resource: ResourceConfig, data: Record<string, unknown>, mode: "create" | "edit", user: UserContext) {
|
|
31
|
+
for (const name of Object.keys(data)) {
|
|
32
|
+
const field = Object.hasOwn(resource.fields, name) ? resource.fields[name] : undefined;
|
|
33
|
+
if (!field) throw new BadRequestException({ message: "Unknown field", code: "FIELD_UNKNOWN" });
|
|
34
|
+
const permission = field.permissions?.[mode === "create" ? "create" : "update"];
|
|
35
|
+
if (permission && !has(user, permission)) throw new ForbiddenException({ message: "Missing field permission", code: "FIELD_PERMISSION_DENIED" });
|
|
36
|
+
if (field[mode] === false || isSensitiveField(name, field) || field.type === "id" || field.type === "computed") throw new ForbiddenException("Field is not writable");
|
|
37
|
+
}
|
|
38
|
+
if (resource.name === "settings" && "key" in data && String(data.key).toLowerCase().startsWith("ai.")) throw new ForbiddenException("Reserved setting");
|
|
39
|
+
return { ...data };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function redact(value: unknown): unknown {
|
|
43
|
+
if (Array.isArray(value)) return value.map(item => redact(item));
|
|
44
|
+
if (!value || typeof value !== "object" || value instanceof Date) return value;
|
|
45
|
+
return Object.fromEntries(Object.entries(value).filter(([name]) => !isSensitiveField(name)).map(([name, item]) => [name, redact(item)]));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function auditSnapshot(resource: ResourceConfig, record: unknown) {
|
|
49
|
+
if (!record || typeof record !== "object") return {};
|
|
50
|
+
return redact(Object.fromEntries(Object.entries(record).filter(([name]) => {
|
|
51
|
+
const field = resource.fields[name];
|
|
52
|
+
return Object.hasOwn(resource.fields, name) && field && !isSensitiveField(name, field) && field.type !== "json";
|
|
53
|
+
})));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function sanitizeRecord(resource: ResourceConfig, record: unknown, user: UserContext) {
|
|
57
|
+
if (!record || typeof record !== "object") return record;
|
|
58
|
+
const entries = Object.entries(record).filter(([name]) => canReadField(resource, name, user));
|
|
59
|
+
// Historical snapshots may contain secrets and cannot reliably be sanitized retroactively.
|
|
60
|
+
if (resource.name === "audit-logs") return Object.fromEntries(entries.filter(([name]) => name !== "before" && name !== "after"));
|
|
61
|
+
if (resource.name === "settings" && String((record as Record<string, unknown>).key ?? "").toLowerCase().startsWith("ai.")) return {};
|
|
62
|
+
return Object.fromEntries(entries);
|
|
63
|
+
}
|
|
64
|
+
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { BadRequestException } from "@nestjs/common";
|
|
2
|
+
import type { ResourceConfig, ResourceField } from "@openadminjs/core";
|
|
3
|
+
import { canReadField, type UserContext } from "./resource-policy.js";
|
|
4
|
+
export function buildWhere(resource: ResourceConfig, query: Record<string, unknown>, user: UserContext) {
|
|
5
|
+
const clauses: Record<string, unknown>[] = [];
|
|
6
|
+
if (query.search) {
|
|
7
|
+
const searchable = Object.entries(resource.fields).filter(([name, field]) => field.searchable && canReadField(resource, name, user));
|
|
8
|
+
clauses.push({ OR: searchable.map(([field]) => ({ [field]: { contains: String(query.search), ...(/^(postgres|postgresql):/.test(process.env.DATABASE_URL ?? "postgresql:") ? { mode: "insensitive" } : {}) } })) });
|
|
9
|
+
}
|
|
10
|
+
for (const [key, value] of Object.entries(query)) {
|
|
11
|
+
const opMatch = key.match(/^filter\[([^\]]+)]\[(\w+)]$/);
|
|
12
|
+
if (opMatch?.[1] && opMatch[2]) {
|
|
13
|
+
const clause = buildOperatorClause(resource, opMatch[1], opMatch[2], value, user);
|
|
14
|
+
if (clause) clauses.push(clause);
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
const legacy = key.match(/^filter\[([^\]]+)]$/);
|
|
18
|
+
if (legacy?.[1]) {
|
|
19
|
+
const clause = buildOperatorClause(resource, legacy[1], "eq", value, user);
|
|
20
|
+
if (clause) clauses.push(clause);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return clauses.length ? { AND: clauses } : undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function buildOperatorClause(resource: ResourceConfig, fieldName: string, op: string, raw: unknown, user: UserContext): Record<string, unknown> | null {
|
|
27
|
+
const field = resource.fields[fieldName];
|
|
28
|
+
if (!field?.filterable || !canReadField(resource, fieldName, user)) {
|
|
29
|
+
throw new BadRequestException({ message: `Field "${fieldName}" is not filterable`, code: "FILTER_NOT_ALLOWED" });
|
|
30
|
+
}
|
|
31
|
+
const str = raw == null ? "" : String(raw);
|
|
32
|
+
switch (op) {
|
|
33
|
+
case "eq":
|
|
34
|
+
return { [fieldName]: coerceFilterScalar(field, str) };
|
|
35
|
+
case "ne":
|
|
36
|
+
return { [fieldName]: { not: coerceFilterScalar(field, str) } };
|
|
37
|
+
case "in": {
|
|
38
|
+
const parts = str
|
|
39
|
+
.split(",")
|
|
40
|
+
.map((s) => s.trim())
|
|
41
|
+
.filter(Boolean)
|
|
42
|
+
.map((p) => coerceFilterScalar(field, p));
|
|
43
|
+
return { [fieldName]: { in: parts } };
|
|
44
|
+
}
|
|
45
|
+
case "gt":
|
|
46
|
+
return { [fieldName]: { gt: coerceFilterComparable(field, str) } };
|
|
47
|
+
case "gte":
|
|
48
|
+
return { [fieldName]: { gte: coerceFilterComparable(field, str) } };
|
|
49
|
+
case "lt":
|
|
50
|
+
return { [fieldName]: { lt: coerceFilterComparable(field, str) } };
|
|
51
|
+
case "lte":
|
|
52
|
+
return { [fieldName]: { lte: coerceFilterComparable(field, str) } };
|
|
53
|
+
case "contains": {
|
|
54
|
+
if (!isStringFilterField(field)) {
|
|
55
|
+
throw new BadRequestException({ message: `Operator "contains" is only for string-like fields`, code: "FILTER_OP_INVALID" });
|
|
56
|
+
}
|
|
57
|
+
return { [fieldName]: { contains: str, ...(/^(postgres|postgresql):/.test(process.env.DATABASE_URL ?? "postgresql:") ? { mode: "insensitive" } : {}) } };
|
|
58
|
+
}
|
|
59
|
+
default:
|
|
60
|
+
throw new BadRequestException({ message: `Unknown filter operator "${op}"`, code: "FILTER_OP_UNKNOWN" });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function isStringFilterField(field: ResourceField): boolean {
|
|
65
|
+
return ["text", "textarea", "email", "url", "slug", "markdown", "code", "richtext", "badge", "select"].includes(field.type);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function coerceFilterScalar(field: ResourceField, value: string): string | number | boolean {
|
|
69
|
+
if (field.type === "number" || field.type === "money") {
|
|
70
|
+
const n = Number(value);
|
|
71
|
+
if (!Number.isFinite(n) || !value.trim()) {
|
|
72
|
+
throw new BadRequestException({ message: `Invalid number for filter`, code: "FILTER_VALUE_INVALID" });
|
|
73
|
+
}
|
|
74
|
+
return n;
|
|
75
|
+
}
|
|
76
|
+
if (field.type === "boolean") { if (!["true","false","1","0"].includes(value)) throw new BadRequestException("Invalid boolean"); return value === "true" || value === "1"; }
|
|
77
|
+
return value;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function coerceFilterComparable(field: ResourceField, value: string): Date | number | string | boolean {
|
|
81
|
+
if (field.type === "datetime" || field.type === "date") {
|
|
82
|
+
const d = new Date(value);
|
|
83
|
+
if (Number.isNaN(d.getTime())) {
|
|
84
|
+
throw new BadRequestException({ message: `Invalid date for filter`, code: "FILTER_VALUE_INVALID" });
|
|
85
|
+
}
|
|
86
|
+
return d;
|
|
87
|
+
}
|
|
88
|
+
return coerceFilterScalar(field, value);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function buildOrderBy(resource: ResourceConfig, sort: string, user: UserContext) {
|
|
92
|
+
const [field, dirRaw] = sort.split(":");
|
|
93
|
+
const direction = dirRaw === "asc" ? "asc" : "desc";
|
|
94
|
+
const candidate = field ? resource.fields[field] : undefined;
|
|
95
|
+
if (field && candidate?.sortable && canReadField(resource, field, user)) {
|
|
96
|
+
return { [field]: direction };
|
|
97
|
+
}
|
|
98
|
+
if (resource.fields.createdAt?.sortable && canReadField(resource, "createdAt", user)) {
|
|
99
|
+
return { createdAt: direction };
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
|