@nest-my-admin/core 0.7.4 → 0.8.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 +41 -0
- package/dist/api/admin-api.service.js +11 -6
- package/dist/api/write-runner.d.ts +1 -1
- package/dist/api/write-runner.js +13 -0
- package/dist/appearance/appearance.service.d.ts +28 -0
- package/dist/appearance/appearance.service.js +63 -0
- package/dist/audit/audit-participant.js +1 -0
- package/dist/audit/audit-reader.js +1 -1
- package/dist/contract.d.ts +12 -1
- package/dist/decorators/admin-resource.d.ts +14 -0
- package/dist/decorators/admin-resource.js +14 -0
- package/dist/files/file-owner.js +1 -0
- package/dist/http/admin-http.server.js +34 -5
- package/dist/http/http-io.d.ts +2 -0
- package/dist/http/http-io.js +19 -1
- package/dist/http/ui-assets.d.ts +15 -2
- package/dist/http/ui-assets.js +29 -3
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/inlines/inline-reader.js +1 -1
- package/dist/inlines/inline-writer.js +1 -1
- package/dist/policy/admin-policy.service.js +12 -5
- package/dist/policy/explain.js +2 -1
- package/dist/registry/resource-registry.d.ts +7 -3
- package/dist/registry/resource-registry.js +77 -14
- package/dist/resource/admin-source-base.d.ts +35 -0
- package/dist/resource/admin-source-base.js +115 -0
- package/dist/schema/source-metadata.d.ts +15 -0
- package/dist/schema/source-metadata.js +76 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -615,6 +615,39 @@ export class ShopSettingsPage implements AdminSettingsSource<ShopSettingsDto> {
|
|
|
615
615
|
- **Names.** Letters, digits, `-` and `_`; not the name of a resource, an operation (`view`, `update`, …) or a resource's custom permission. Because page codes start with `page.`, **a resource cannot be named `page` in an admin with settings pages**: boot fails and suggests `@AdminResource(Page, { name: 'content-page' })`.
|
|
616
616
|
- **API.** `GET /api/pages/:name` answers `{ schema, values, secrets, files }`, and `PATCH /api/pages/:name` takes the changed keys and answers the same.
|
|
617
617
|
|
|
618
|
+
### Source resources
|
|
619
|
+
|
|
620
|
+
Rows that are not database rows (DNS records behind an HTTP API, files on disk, live container status) get the same list, record page, forms and actions as a table: `@AdminSource(RowClass, options)` on a class that extends `AdminSourceBase`. The demo's couriers (`examples/demo-api/src/sales/courier.source.ts`) are one.
|
|
621
|
+
|
|
622
|
+
```ts
|
|
623
|
+
export class DnsRow {
|
|
624
|
+
@IsString() id: string;
|
|
625
|
+
@IsString() name: string;
|
|
626
|
+
@IsIn(['a', 'cname', 'txt']) type: string;
|
|
627
|
+
@IsString() value: string;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
@AdminSource(DnsRow, { name: 'dns', label: 'DNS records', title: 'name' }) // primaryKey: 'id' by default
|
|
631
|
+
export class DnsAdmin extends AdminSourceBase<DnsRow, string> {
|
|
632
|
+
list: ListConfig<DnsRow> = { columns: ['name', 'type', 'value'], search: ['name', 'value'], filters: ['type'], sort: 'name' };
|
|
633
|
+
form = { create: CreateDnsDto, update: UpdateDnsDto };
|
|
634
|
+
|
|
635
|
+
constructor(private readonly dns: DnsClient) { super(); }
|
|
636
|
+
|
|
637
|
+
async findMany(params: ListParams) { return inMemoryList(await this.dns.all(), params); }
|
|
638
|
+
async findOne(id: string) { return (await this.dns.all()).find((row) => row.id === id) ?? null; }
|
|
639
|
+
override async create(dto: object) { return this.dns.create(dto as CreateDnsDto); }
|
|
640
|
+
override async update(id: string, dto: object) { return this.dns.update(id, dto as UpdateDnsDto); }
|
|
641
|
+
override async delete(id: string) { await this.dns.delete(id); }
|
|
642
|
+
}
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
- **The row class** is the schema: one field per property with a class-validator decorator, typed like a DTO's (`@IsIn` is an enum, `@IsInt` an integer, `@IsDate` a date). `@AdminField` and `fields` set labels, help and widgets. `primaryKey` names the id property (or several); it defaults to `id`.
|
|
646
|
+
- **`findMany(params, ctx)`** answers a page: `{ items, total }`. `params` carries the search (`term` and the `list.search` fields), the filters, the sort and the page. `inMemoryList(rows, params)` does all of it for rows fetched whole; an API that searches and pages itself can be asked directly. **`findOne(id, ctx)`** answers one row, or `null` (a 404).
|
|
647
|
+
- **Writes are opt-in.** Override `create`, `update` and `delete` to allow them. A source that does not is offered no New, Save or Delete, and the API refuses them with 403 whatever the roles say. Throw `AdminFieldError` to refuse a value (422 on the field), as anywhere.
|
|
648
|
+
- **No DataSource.** `ctx.manager` is never set and writes run without a transaction: a source writes to its own system, which the admin cannot roll back. Actions (record, bulk and resource actions), permissions, global search and the command palette work as on a table. Row scopes do not apply, and writes to a source are not in the audit log. `@BeforeSave`, `@AfterSave` and `@BeforeDelete` run only if your `create`, `update` and `delete` call `this.runHooks(...)`, as for any override.
|
|
649
|
+
- **Refused at boot**, with a sentence: list tabs, computed columns, keyset paging, a `count` other than exact, export, inlines, relation cards, form history, file/image/rich-text widgets and atomic actions. They need a database.
|
|
650
|
+
|
|
618
651
|
### Inlines
|
|
619
652
|
|
|
620
653
|
A parent's form can edit its child records (a product's variants, specifications and pictures; an order's lines), and one Save writes the parent and every change to its children in **one transaction**. The child is an ordinary resource, with its own permissions, scopes, fields, DTOs, hooks and service overrides; the parent's layout places it:
|
|
@@ -936,6 +969,14 @@ Things hosts tend to write by hand that the admin already does:
|
|
|
936
969
|
- **Inline children stay out of the sidebar** by default (`nav: false` unless they set `nav`): no extra group to hide them in.
|
|
937
970
|
- **Labels in one language** are plain strings; other languages can come from `translate` (see Languages, theme and branding).
|
|
938
971
|
|
|
972
|
+
## Upgrading to 0.8.1
|
|
973
|
+
|
|
974
|
+
Nothing to change. New: with `appearance` on, whoever holds `appearance.manage` uploads the **logo** (sidebar and sign-in page) and the **tab icon** (favicon) from the account menu, for everyone (PNG, JPEG, GIF, WebP, ICO or SVG, up to 512 KB; stored in `nma_setting`, served at `<path>/appearance/logo` and `/appearance/favicon`). An uploaded logo wins over `branding.logo`. Without a logo the sidebar shows the admin's own mark instead of the first letter of the title, and it is the default tab icon.
|
|
975
|
+
|
|
976
|
+
## Upgrading to 0.8.0
|
|
977
|
+
|
|
978
|
+
Nothing to change. New: [source resources](#source-resources): `@AdminSource(RowClass, …)` and `AdminSourceBase` give rows that are not database rows (an HTTP API, files, live state) the list, record page, forms and actions of a table; `inMemoryList` searches, filters, sorts and pages rows fetched whole.
|
|
979
|
+
|
|
939
980
|
## Upgrading to 0.7.4
|
|
940
981
|
|
|
941
982
|
Nothing to change. New: `@AdminField({ default })` starts action input forms and create forms at a value (checked at boot to fit the field), and `@AdminField({ fillFrom: '{crm}.example.com' })` fills a text field from other fields of the same form until someone types in it, in action dialogs too (see Field config).
|
|
@@ -461,8 +461,9 @@ let AdminApiService = class AdminApiService {
|
|
|
461
461
|
fields = fields.filter((field) => visible.has(field.name));
|
|
462
462
|
const perms = await this.policy.recordPermissions(entry, entities, ctx);
|
|
463
463
|
const titled = this.policy.titleVisible(entry, ctx);
|
|
464
|
-
|
|
465
|
-
const
|
|
464
|
+
// A source has no relations or paths to load, and no DataSource to load them with.
|
|
465
|
+
const manager = ctx.manager ?? entry.dataSource?.manager;
|
|
466
|
+
const loaded = fields.length > 0 && manager ? await loadReferences(entry, entities, fields, { registry: this.registry, manager }) : undefined;
|
|
466
467
|
const discriminator = entry.metadata.discriminatorColumn?.propertyName;
|
|
467
468
|
const kindOf = (entity) => entry.metadata.childEntityMetadatas.find((child) => child.target === entity.constructor)?.discriminatorValue ?? entry.metadata.discriminatorValue;
|
|
468
469
|
const locale = ctx.locale ?? this.options.locale;
|
|
@@ -511,7 +512,8 @@ let AdminApiService = class AdminApiService {
|
|
|
511
512
|
const entry = this.registry.get(name);
|
|
512
513
|
const { resource } = entry;
|
|
513
514
|
// A read-only resource answers 403 (it refuses writes), not the 400 of a resource that cannot be created.
|
|
514
|
-
|
|
515
|
+
// A source that does not create says so (403) too.
|
|
516
|
+
if (entry.schema.creatable || entry.schema.readonly || entry.source)
|
|
515
517
|
this.policy.require(entry, 'create', ctx);
|
|
516
518
|
else
|
|
517
519
|
this.policy.requireReach(entry, ctx);
|
|
@@ -681,10 +683,11 @@ let AdminApiService = class AdminApiService {
|
|
|
681
683
|
*/
|
|
682
684
|
async checkVersion(entry, id, expected, ctx, withDeleted = false) {
|
|
683
685
|
const version = entry.schema.version;
|
|
684
|
-
|
|
686
|
+
const { dataSource } = entry;
|
|
687
|
+
if (expected === undefined || !version || !dataSource)
|
|
685
688
|
return;
|
|
686
|
-
const manager = ctx.manager ??
|
|
687
|
-
const lock = inAdminTransaction(ctx) && !SINGLE_CONNECTION_DRIVERS.has(
|
|
689
|
+
const manager = ctx.manager ?? dataSource.manager;
|
|
690
|
+
const lock = inAdminTransaction(ctx) && !SINGLE_CONNECTION_DRIVERS.has(dataSource.options.type) ? { mode: 'pessimistic_write' } : undefined;
|
|
688
691
|
const where = typeof id === 'object' ? id : { [entry.schema.primaryKeys[0]]: id };
|
|
689
692
|
const current = await manager.getRepository(entry.metadata.target).findOne({ where, withDeleted, ...(lock ? { lock } : {}) });
|
|
690
693
|
if (!current)
|
|
@@ -699,6 +702,8 @@ let AdminApiService = class AdminApiService {
|
|
|
699
702
|
*/
|
|
700
703
|
async optionsQuery(entry, field, ctx, values) {
|
|
701
704
|
const target = entry.relations.get(field).inverseEntityMetadata;
|
|
705
|
+
if (!entry.dataSource)
|
|
706
|
+
throw new AdminNotFoundError(`${entry.schema.label} has no relation fields`);
|
|
702
707
|
const manager = ctx.manager ?? entry.dataSource.manager;
|
|
703
708
|
const qb = manager.getRepository(target.target).createQueryBuilder('option');
|
|
704
709
|
// The target resource's query() restricts what may be picked, before this field's relationOptions().
|
|
@@ -20,7 +20,7 @@ export declare class WriteRunner {
|
|
|
20
20
|
* `onRollback` runs only when it fails. A failing one is logged, never thrown.
|
|
21
21
|
*/
|
|
22
22
|
run<T>(target: {
|
|
23
|
-
dataSource
|
|
23
|
+
dataSource?: DataSource;
|
|
24
24
|
}, ctx: AdminContext, work: (ctx: AdminWriteContext) => Promise<T>): Promise<T>;
|
|
25
25
|
/**
|
|
26
26
|
* One change inside the write `tx`: every participant's `before`, then the host `method`, then every `after` with
|
package/dist/api/write-runner.js
CHANGED
|
@@ -41,6 +41,13 @@ export class WriteRunner {
|
|
|
41
41
|
await this.settle(steps.filter((step) => step.done), 'onCommit', tx);
|
|
42
42
|
return result;
|
|
43
43
|
};
|
|
44
|
+
if (!target.dataSource) {
|
|
45
|
+
// An @AdminSource: no DataSource, so no transaction and no manager (`ctx.manager` stays unset in its methods).
|
|
46
|
+
if (this.open.has(ctx))
|
|
47
|
+
return work(ctx);
|
|
48
|
+
const plain = { ...ctx };
|
|
49
|
+
return committed(plain, () => runInAdminContext(plain, () => work(plain)));
|
|
50
|
+
}
|
|
44
51
|
if (!this.options.transactions) {
|
|
45
52
|
// Nothing to commit: the participants settle when the outermost write on this context is done.
|
|
46
53
|
// The write still gets a manager, the DataSource's own; it is not a transaction (`inAdminTransaction` says no).
|
|
@@ -78,6 +85,10 @@ export class WriteRunner {
|
|
|
78
85
|
const steps = this.open.get(tx);
|
|
79
86
|
if (!steps)
|
|
80
87
|
throw new Error('nest-my-admin: a change was made outside a write');
|
|
88
|
+
// A source's rows are not in a table: no file is attached to them and the audit log does not record them.
|
|
89
|
+
// (A settings page has a `source` too: its load/save provider. Only a resource's `source: true` marks an @AdminSource.)
|
|
90
|
+
if ('schema' in change.target && change.target.source === true)
|
|
91
|
+
return method();
|
|
81
92
|
const mine = [];
|
|
82
93
|
for (const participant of this.participants) {
|
|
83
94
|
const state = await participant.before(change, tx);
|
|
@@ -122,6 +133,8 @@ async function storedRow(change, saved, tx) {
|
|
|
122
133
|
const key = change.id ?? (change.existing ? keyOf(target, change.existing) : saved ? keyOf(target, saved) : undefined);
|
|
123
134
|
if (key === undefined)
|
|
124
135
|
return { gone: false };
|
|
136
|
+
if (!target.dataSource)
|
|
137
|
+
return { gone: false };
|
|
125
138
|
const stored = await loadStored(target, key, tx.manager ?? target.dataSource.manager);
|
|
126
139
|
return { key, ...(stored ? { stored } : {}), gone: !stored };
|
|
127
140
|
}
|
|
@@ -5,6 +5,19 @@ import { AdminPolicy } from '../policy/admin-policy.service.js';
|
|
|
5
5
|
import type { AdminContext } from '../resource/admin-context.js';
|
|
6
6
|
/** Changing the admin-wide look. A code only while `appearance` is on. */
|
|
7
7
|
export declare const APPEARANCE_CODES: string[];
|
|
8
|
+
/** The pictures the admin's look has: the logo (sidebar and sign-in page) and the browser tab's icon. */
|
|
9
|
+
export declare const APPEARANCE_IMAGES: readonly ['logo', 'favicon'];
|
|
10
|
+
export type AppearanceImageKind = (typeof APPEARANCE_IMAGES)[number];
|
|
11
|
+
/** The most an uploaded logo or favicon may weigh. */
|
|
12
|
+
export declare const MAX_APPEARANCE_IMAGE_BYTES: number;
|
|
13
|
+
/** The media type of an upload (`image/png; charset=…` → `image/png`), or undefined when it is not an accepted image. */
|
|
14
|
+
export declare function appearanceImageType(contentType: string | undefined): string | undefined;
|
|
15
|
+
interface StoredImage {
|
|
16
|
+
type: string;
|
|
17
|
+
data: Buffer;
|
|
18
|
+
/** The first 12 hex digits of its SHA-256: the `?v=` of its URL, so a new picture is never served from a cache. */
|
|
19
|
+
version: string;
|
|
20
|
+
}
|
|
8
21
|
/**
|
|
9
22
|
* The admin-wide accent colour (`forRoot({ appearance })`): set in the admin by whoever holds `appearance.manage`, seen
|
|
10
23
|
* by everyone (it wins over `branding.primaryColor`; each person may still pick their own in their browser).
|
|
@@ -16,9 +29,23 @@ export declare class AdminAppearance implements OnApplicationBootstrap {
|
|
|
16
29
|
private dataSource?;
|
|
17
30
|
/** The stored accent, read once at boot and kept current by `setAccent`. */
|
|
18
31
|
private accent;
|
|
32
|
+
/** The uploaded pictures, read once at boot and kept current by `setImage`. */
|
|
33
|
+
private readonly images;
|
|
19
34
|
constructor(options: ResolvedAdminOptions, moduleRef: ModuleRef, policy: AdminPolicy);
|
|
20
35
|
get enabled(): boolean;
|
|
21
36
|
onApplicationBootstrap(): Promise<void>;
|
|
37
|
+
/** An uploaded picture (served at `<path>/appearance/<kind>`), or undefined. */
|
|
38
|
+
image(kind: string): StoredImage | undefined;
|
|
39
|
+
/** Where the page finds each uploaded picture, relative to the admin's `<base href>`; null when there is none. */
|
|
40
|
+
imageUrls(): {
|
|
41
|
+
logo: string | null;
|
|
42
|
+
favicon: string | null;
|
|
43
|
+
};
|
|
44
|
+
/** `PUT /api/appearance/:kind` (a picture) and `DELETE` (`null`: none again, so `branding.logo` is back). */
|
|
45
|
+
setImage(kind: string, type: string | undefined, data: Buffer | null, ctx: AdminContext): Promise<{
|
|
46
|
+
logo: string | null;
|
|
47
|
+
favicon: string | null;
|
|
48
|
+
}>;
|
|
22
49
|
/** The admin-wide accent (`SessionResponse.appearance.accent`). */
|
|
23
50
|
current(): string | null;
|
|
24
51
|
/** `PUT /api/appearance`: a CSS colour, or `null` for the host's branding again. */
|
|
@@ -26,3 +53,4 @@ export declare class AdminAppearance implements OnApplicationBootstrap {
|
|
|
26
53
|
accent: string | null;
|
|
27
54
|
}>;
|
|
28
55
|
}
|
|
56
|
+
export {};
|
|
@@ -10,6 +10,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
|
|
10
10
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
13
14
|
import { Inject, Injectable } from '@nestjs/common';
|
|
14
15
|
import { ModuleRef } from '@nestjs/core';
|
|
15
16
|
import { getDataSourceToken } from '@nestjs/typeorm';
|
|
@@ -21,6 +22,25 @@ import { ADMIN_SETTING_ENTITIES, NmaSetting } from './entities.js';
|
|
|
21
22
|
/** Changing the admin-wide look. A code only while `appearance` is on. */
|
|
22
23
|
export const APPEARANCE_CODES = ['appearance.manage'];
|
|
23
24
|
const ACCENT = 'appearance.accent';
|
|
25
|
+
/** The pictures the admin's look has: the logo (sidebar and sign-in page) and the browser tab's icon. */
|
|
26
|
+
export const APPEARANCE_IMAGES = ['logo', 'favicon'];
|
|
27
|
+
/** The most an uploaded logo or favicon may weigh. */
|
|
28
|
+
export const MAX_APPEARANCE_IMAGE_BYTES = 512 * 1024;
|
|
29
|
+
/** The image types accepted, each with a check of the bytes (so a file is what its type says). */
|
|
30
|
+
const IMAGE_TYPES = {
|
|
31
|
+
'image/png': (d) => d.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
|
|
32
|
+
'image/jpeg': (d) => d[0] === 0xff && d[1] === 0xd8 && d[2] === 0xff,
|
|
33
|
+
'image/gif': (d) => d.subarray(0, 4).toString('latin1') === 'GIF8',
|
|
34
|
+
'image/webp': (d) => d.subarray(0, 4).toString('latin1') === 'RIFF' && d.subarray(8, 12).toString('latin1') === 'WEBP',
|
|
35
|
+
'image/x-icon': (d) => d.readUInt32BE(0) === 0x00000100,
|
|
36
|
+
'image/vnd.microsoft.icon': (d) => d.readUInt32BE(0) === 0x00000100,
|
|
37
|
+
'image/svg+xml': (d) => /<svg[\s>]/i.test(d.subarray(0, 4096).toString('utf8')),
|
|
38
|
+
};
|
|
39
|
+
/** The media type of an upload (`image/png; charset=…` → `image/png`), or undefined when it is not an accepted image. */
|
|
40
|
+
export function appearanceImageType(contentType) {
|
|
41
|
+
const type = (contentType ?? '').split(';')[0].trim().toLowerCase();
|
|
42
|
+
return type in IMAGE_TYPES ? type : undefined;
|
|
43
|
+
}
|
|
24
44
|
/**
|
|
25
45
|
* The admin-wide accent colour (`forRoot({ appearance })`): set in the admin by whoever holds `appearance.manage`, seen
|
|
26
46
|
* by everyone (it wins over `branding.primaryColor`; each person may still pick their own in their browser).
|
|
@@ -32,6 +52,8 @@ let AdminAppearance = class AdminAppearance {
|
|
|
32
52
|
dataSource;
|
|
33
53
|
/** The stored accent, read once at boot and kept current by `setAccent`. */
|
|
34
54
|
accent = null;
|
|
55
|
+
/** The uploaded pictures, read once at boot and kept current by `setImage`. */
|
|
56
|
+
images = new Map();
|
|
35
57
|
constructor(options, moduleRef, policy) {
|
|
36
58
|
this.options = options;
|
|
37
59
|
this.moduleRef = moduleRef;
|
|
@@ -56,6 +78,46 @@ let AdminAppearance = class AdminAppearance {
|
|
|
56
78
|
}
|
|
57
79
|
const stored = await this.dataSource.getRepository(NmaSetting).findOneBy({ key: ACCENT });
|
|
58
80
|
this.accent = typeof stored?.value === 'string' && isCssColor(stored.value) ? stored.value : null;
|
|
81
|
+
for (const kind of APPEARANCE_IMAGES) {
|
|
82
|
+
const row = await this.dataSource.getRepository(NmaSetting).findOneBy({ key: `appearance.${kind}` });
|
|
83
|
+
const value = row?.value;
|
|
84
|
+
if (typeof value?.type !== 'string' || typeof value.data !== 'string' || !(value.type in IMAGE_TYPES))
|
|
85
|
+
continue;
|
|
86
|
+
const data = Buffer.from(value.data, 'base64');
|
|
87
|
+
this.images.set(kind, { type: value.type, data, version: versionOf(data) });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** An uploaded picture (served at `<path>/appearance/<kind>`), or undefined. */
|
|
91
|
+
image(kind) {
|
|
92
|
+
return APPEARANCE_IMAGES.includes(kind) ? this.images.get(kind) : undefined;
|
|
93
|
+
}
|
|
94
|
+
/** Where the page finds each uploaded picture, relative to the admin's `<base href>`; null when there is none. */
|
|
95
|
+
imageUrls() {
|
|
96
|
+
const url = (kind) => {
|
|
97
|
+
const image = this.images.get(kind);
|
|
98
|
+
return image ? `appearance/${kind}?v=${image.version}` : null;
|
|
99
|
+
};
|
|
100
|
+
return { logo: url('logo'), favicon: url('favicon') };
|
|
101
|
+
}
|
|
102
|
+
/** `PUT /api/appearance/:kind` (a picture) and `DELETE` (`null`: none again, so `branding.logo` is back). */
|
|
103
|
+
async setImage(kind, type, data, ctx) {
|
|
104
|
+
if (!this.dataSource)
|
|
105
|
+
throw new AdminNotFoundError('The look is not set in this admin (no `appearance` option)');
|
|
106
|
+
if (!APPEARANCE_IMAGES.includes(kind))
|
|
107
|
+
throw new AdminNotFoundError(`No admin picture "${kind}" (logo or favicon)`);
|
|
108
|
+
if (ctx.viewAs || !this.policy.permissionsOf(ctx).can('appearance.manage'))
|
|
109
|
+
throw new AdminForbiddenError('You may not change the admin’s look');
|
|
110
|
+
const repo = this.dataSource.getRepository(NmaSetting);
|
|
111
|
+
if (data === null) {
|
|
112
|
+
await repo.delete({ key: `appearance.${kind}` });
|
|
113
|
+
this.images.delete(kind);
|
|
114
|
+
return this.imageUrls();
|
|
115
|
+
}
|
|
116
|
+
if (!type || !IMAGE_TYPES[type](data))
|
|
117
|
+
throw new AdminValidationError({ [kind]: [`the file is not a ${type ?? 'picture'}`] });
|
|
118
|
+
await repo.save({ key: `appearance.${kind}`, value: { type, data: data.toString('base64') } });
|
|
119
|
+
this.images.set(kind, { type, data, version: versionOf(data) });
|
|
120
|
+
return this.imageUrls();
|
|
59
121
|
}
|
|
60
122
|
/** The admin-wide accent (`SessionResponse.appearance.accent`). */
|
|
61
123
|
current() {
|
|
@@ -85,4 +147,5 @@ AdminAppearance = __decorate([
|
|
|
85
147
|
AdminPolicy])
|
|
86
148
|
], AdminAppearance);
|
|
87
149
|
export { AdminAppearance };
|
|
150
|
+
const versionOf = (data) => createHash('sha256').update(data).digest('hex').slice(0, 12);
|
|
88
151
|
//# sourceMappingURL=appearance.service.js.map
|
|
@@ -40,6 +40,7 @@ export function auditParticipant(audit) {
|
|
|
40
40
|
const { target } = change;
|
|
41
41
|
if (!('schema' in target))
|
|
42
42
|
return { before: pageValues(target, change.existing) };
|
|
43
|
+
// Sources never get here (WriteRunner.change skips the participants for them): a resource has its DataSource.
|
|
43
44
|
const manager = tx.manager ?? target.dataSource.manager;
|
|
44
45
|
// The stored row, read here: like "after", so the two compare column for column whatever the resource's
|
|
45
46
|
// `findOne` selected, and the entity the host method is handed (and may change) is never the one serialized.
|
|
@@ -329,7 +329,7 @@ let AuditReader = class AuditReader {
|
|
|
329
329
|
if (ids.size === 0)
|
|
330
330
|
return new Set();
|
|
331
331
|
let seen = new Set(ids.keys());
|
|
332
|
-
if (narrowed) {
|
|
332
|
+
if (narrowed && entry.dataSource) {
|
|
333
333
|
const qb = entry.dataSource.getRepository(entry.metadata.target).createQueryBuilder('entity').withDeleted();
|
|
334
334
|
// The ids go on last: a `query()` that starts its own `where()` must not leave the select unbounded.
|
|
335
335
|
const restricted = this.policy.applyScopes(entry.resource.query(qb, ctx), entry, 'view', ctx).andWhereInIds([...ids.values()]);
|
package/dist/contract.d.ts
CHANGED
|
@@ -504,6 +504,12 @@ export interface ResourceSchema {
|
|
|
504
504
|
* `POST …/:id/restore` brings one back and `DELETE …/:id?purge=true` removes it for good.
|
|
505
505
|
*/
|
|
506
506
|
softDelete: boolean;
|
|
507
|
+
/** Set for an `@AdminSource` (rows that are not database rows): which writes its class implements. */
|
|
508
|
+
source?: {
|
|
509
|
+
create: boolean;
|
|
510
|
+
update: boolean;
|
|
511
|
+
delete: boolean;
|
|
512
|
+
};
|
|
507
513
|
form: {
|
|
508
514
|
create: string[];
|
|
509
515
|
update: string[];
|
|
@@ -648,10 +654,15 @@ export interface SessionResponse {
|
|
|
648
654
|
enabled: boolean;
|
|
649
655
|
view: boolean;
|
|
650
656
|
};
|
|
651
|
-
/**
|
|
657
|
+
/**
|
|
658
|
+
* With `appearance`: the admin-wide accent colour (null: the host's branding), whether this user may change it, and
|
|
659
|
+
* the uploaded logo and favicon (URLs relative to the admin; null: none, so `branding.logo` and the build's icon).
|
|
660
|
+
*/
|
|
652
661
|
appearance?: {
|
|
653
662
|
accent: string | null;
|
|
654
663
|
manage: boolean;
|
|
664
|
+
logo: string | null;
|
|
665
|
+
favicon: string | null;
|
|
655
666
|
};
|
|
656
667
|
/** Changes when roles or memberships change: refetch meta and schemas. */
|
|
657
668
|
permissionsVersion: number;
|
|
@@ -41,7 +41,21 @@ export interface AdminResourceOptions {
|
|
|
41
41
|
}
|
|
42
42
|
export interface AdminResourceDefinition extends AdminResourceOptions {
|
|
43
43
|
entity: Function;
|
|
44
|
+
/** Set by `@AdminSource`: the rows come from the class's own `findMany`/`findOne`, not from a table. */
|
|
45
|
+
source?: {
|
|
46
|
+
primaryKeys: string[];
|
|
47
|
+
};
|
|
44
48
|
}
|
|
49
|
+
export interface AdminSourceOptions extends Omit<AdminResourceOptions, 'dataSource'> {
|
|
50
|
+
/** The row property (or properties) that identify a row. Default `id`. */
|
|
51
|
+
primaryKey?: string | string[];
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Marks a provider as an admin resource whose rows are not database rows (an HTTP API, files, live state): the class
|
|
55
|
+
* extends AdminSourceBase and answers `findMany`/`findOne` (and `create`/`update`/`delete` when it allows them).
|
|
56
|
+
* `row` is a class whose class-validator decorators describe a row's fields, like an action's input DTO.
|
|
57
|
+
*/
|
|
58
|
+
export declare function AdminSource(row: Function, options?: AdminSourceOptions): ClassDecorator;
|
|
45
59
|
/** Marks a provider as an admin resource for `entity`. The class must extend AdminResourceBase. */
|
|
46
60
|
export declare function AdminResource(entity: Function, options?: AdminResourceOptions): ClassDecorator;
|
|
47
61
|
export declare function getAdminResourceDefinition(target: Function): AdminResourceDefinition | undefined;
|
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
import { Injectable } from '@nestjs/common';
|
|
3
3
|
import { ADMIN_RESOURCE_METADATA } from '../constants.js';
|
|
4
|
+
/**
|
|
5
|
+
* Marks a provider as an admin resource whose rows are not database rows (an HTTP API, files, live state): the class
|
|
6
|
+
* extends AdminSourceBase and answers `findMany`/`findOne` (and `create`/`update`/`delete` when it allows them).
|
|
7
|
+
* `row` is a class whose class-validator decorators describe a row's fields, like an action's input DTO.
|
|
8
|
+
*/
|
|
9
|
+
export function AdminSource(row, options = {}) {
|
|
10
|
+
return (target) => {
|
|
11
|
+
const { primaryKey, ...rest } = options;
|
|
12
|
+
const primaryKeys = primaryKey === undefined ? ['id'] : Array.isArray(primaryKey) ? [...primaryKey] : [primaryKey];
|
|
13
|
+
const definition = { ...rest, entity: row, source: { primaryKeys } };
|
|
14
|
+
Reflect.defineMetadata(ADMIN_RESOURCE_METADATA, definition, target);
|
|
15
|
+
Injectable()(target);
|
|
16
|
+
};
|
|
17
|
+
}
|
|
4
18
|
/** Marks a provider as an admin resource for `entity`. The class must extend AdminResourceBase. */
|
|
5
19
|
export function AdminResource(entity, options = {}) {
|
|
6
20
|
return (target) => {
|
package/dist/files/file-owner.js
CHANGED
|
@@ -10,6 +10,7 @@ export function resourceFileOwner(entry, policy) {
|
|
|
10
10
|
return {
|
|
11
11
|
name,
|
|
12
12
|
keyPrefix: name,
|
|
13
|
+
// File fields are refused on sources at boot: an owner of files always has a DataSource.
|
|
13
14
|
dataSource: entry.dataSource,
|
|
14
15
|
fieldConfig: entry.fieldConfig,
|
|
15
16
|
hasField: (field) => !field.includes('.') && entry.schema.fields.some((candidate) => candidate.name === field),
|
|
@@ -20,7 +20,7 @@ import { AuditReader } from '../audit/audit-reader.js';
|
|
|
20
20
|
import { addAuditRoutes } from '../audit/audit-routes.js';
|
|
21
21
|
import { addMenuRoutes } from '../api/menu-routes.js';
|
|
22
22
|
import { addDashboardRoutes } from '../dashboard/dashboard-routes.js';
|
|
23
|
-
import { AdminAppearance } from '../appearance/appearance.service.js';
|
|
23
|
+
import { AdminAppearance, appearanceImageType, MAX_APPEARANCE_IMAGE_BYTES } from '../appearance/appearance.service.js';
|
|
24
24
|
import { DashboardService } from '../dashboard/dashboard.service.js';
|
|
25
25
|
import { AdminAudit, clientOf } from '../audit/audit.service.js';
|
|
26
26
|
import { AdminAuthService } from '../auth/auth.service.js';
|
|
@@ -33,7 +33,7 @@ import { AdminRbac } from '../rbac/rbac.service.js';
|
|
|
33
33
|
import { ResourceRegistry } from '../registry/resource-registry.js';
|
|
34
34
|
import { createAdminContext, runInAdminContext } from '../resource/admin-context.js';
|
|
35
35
|
import { codeForStatus, toErrorResponse } from './error-response.js';
|
|
36
|
-
import { readJsonBody, sendJson } from './http-io.js';
|
|
36
|
+
import { readJsonBody, readRawBody, sendJson } from './http-io.js';
|
|
37
37
|
import { Router } from './router.js';
|
|
38
38
|
import { UiAssets, resolveUiDist } from './ui-assets.js';
|
|
39
39
|
import { AdminApiService } from '../api/admin-api.service.js';
|
|
@@ -41,6 +41,10 @@ import { ADMIN_OPTIONS } from '../constants.js';
|
|
|
41
41
|
import { readUiMessages, uiOverrides } from './ui-messages.js';
|
|
42
42
|
/** The only API routes that answer without a session: reading it (to learn you are signed out) and logging in. */
|
|
43
43
|
const PUBLIC_ROUTES = new Set(['GET /api/session', 'POST /api/session']);
|
|
44
|
+
/** The logo/favicon uploads: their body is the picture, and the route checks it is an image type. */
|
|
45
|
+
const IMAGE_ROUTE = /^PUT \/api\/appearance\/[^/]+$/;
|
|
46
|
+
/** An uploaded logo or favicon, served to anyone (the sign-in page and the browser tab need it). */
|
|
47
|
+
const IMAGE_PATH = /^\/appearance\/([^/]+)$/;
|
|
44
48
|
// Methods that carry a JSON body. DELETE is never a CORS "simple" request, so a foreign page cannot send one without a preflight.
|
|
45
49
|
const BODY_METHODS = new Set(['POST', 'PATCH', 'PUT']);
|
|
46
50
|
function isJsonContentType(header) {
|
|
@@ -276,6 +280,15 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
276
280
|
addAuditRoutes(this.router, { reader: auditReader });
|
|
277
281
|
addMenuRoutes(this.router, { api: this.api });
|
|
278
282
|
addDashboardRoutes(this.router, { dashboard: this.dashboard });
|
|
283
|
+
// The logo and favicon: the picture itself is the body (an image type: never a CORS "simple" request).
|
|
284
|
+
this.router.add('PUT', '/api/appearance/:kind', async ({ req, res, ctx }, p) => {
|
|
285
|
+
const type = appearanceImageType(req.headers['content-type']);
|
|
286
|
+
if (!type)
|
|
287
|
+
throw new AdminUnsupportedMediaTypeError('Upload a PNG, JPEG, GIF, WebP, ICO or SVG picture');
|
|
288
|
+
const data = await readRawBody(req, MAX_APPEARANCE_IMAGE_BYTES);
|
|
289
|
+
sendJson(res, 200, await this.appearance.setImage(p.kind, type, data, ctx));
|
|
290
|
+
});
|
|
291
|
+
this.router.add('DELETE', '/api/appearance/:kind', async ({ res, ctx }, p) => sendJson(res, 200, await this.appearance.setImage(p.kind, undefined, null, ctx)));
|
|
279
292
|
this.router.add('PUT', '/api/appearance', async ({ req, res, ctx }) => sendJson(res, 200, await this.appearance.setAccent(((await readJsonBody(req)) ?? {}).accent ?? null, ctx)));
|
|
280
293
|
addRbacRoutes(this.router, { rbac: this.rbac, auth: this.auth, api: this.api, policy: this.policy, registry: this.registry, audit: this.audit });
|
|
281
294
|
}
|
|
@@ -339,7 +352,7 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
339
352
|
auth: this.auth.capabilities,
|
|
340
353
|
rbac: { enabled, view: enabled && (permissions.can('rbac.view') || permissions.can('rbac.manage')), manage: enabled && permissions.can('rbac.manage') },
|
|
341
354
|
audit: { enabled: this.audit.enabled, view: this.audit.enabled && permissions.can('audit.view') },
|
|
342
|
-
...(this.appearance.enabled ? { appearance: { accent: this.appearance.current(), manage: !viewAs && permissions.can('appearance.manage') } } : {}),
|
|
355
|
+
...(this.appearance.enabled ? { appearance: { accent: this.appearance.current(), manage: !viewAs && permissions.can('appearance.manage'), ...this.appearance.imageUrls() } } : {}),
|
|
343
356
|
permissionsVersion: this.rbac.permissionsVersion,
|
|
344
357
|
...(viewAs ? { viewAs: { by: toSessionUser(viewAs.by) } } : {}),
|
|
345
358
|
};
|
|
@@ -366,7 +379,7 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
366
379
|
branding: this.options.branding,
|
|
367
380
|
...(this.options.currency ? { currency: this.options.currency } : {}),
|
|
368
381
|
...(Object.keys(messages).length > 0 ? { messages } : {}),
|
|
369
|
-
}, { title: this.options.title });
|
|
382
|
+
}, { title: this.options.title }, this.appearance.enabled ? () => this.appearance.imageUrls() : undefined);
|
|
370
383
|
adapter.use(this.options.path, (req, res, next) => {
|
|
371
384
|
this.handle(req, res, next).catch((error) => {
|
|
372
385
|
const correlationId = randomUUID();
|
|
@@ -414,7 +427,7 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
414
427
|
// Only JSON can be sent by a script; forms and text/plain are CORS "simple" requests a foreign page could forge.
|
|
415
428
|
// Uploads carry the raw file instead; FilesService.upload refuses the simple types itself.
|
|
416
429
|
const route = `${req.method} ${pathname.replace(/\/+$/, '')}`;
|
|
417
|
-
if (BODY_METHODS.has(req.method ?? '') && route !== UPLOAD_ROUTE && !isJsonContentType(req.headers['content-type'])) {
|
|
430
|
+
if (BODY_METHODS.has(req.method ?? '') && route !== UPLOAD_ROUTE && !IMAGE_ROUTE.test(route) && !isJsonContentType(req.headers['content-type'])) {
|
|
418
431
|
throw new AdminUnsupportedMediaTypeError('Content-Type must be application/json');
|
|
419
432
|
}
|
|
420
433
|
resourceName = match.params.resource;
|
|
@@ -441,6 +454,22 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
441
454
|
next();
|
|
442
455
|
return;
|
|
443
456
|
}
|
|
457
|
+
const picture = IMAGE_PATH.exec(pathname);
|
|
458
|
+
if (picture && this.appearance.enabled) {
|
|
459
|
+
const image = this.appearance.image(picture[1]);
|
|
460
|
+
if (!image)
|
|
461
|
+
throw new AdminNotFoundError('No such picture');
|
|
462
|
+
res.statusCode = 200;
|
|
463
|
+
res.setHeader('Content-Type', image.type);
|
|
464
|
+
res.setHeader('Content-Length', image.data.length);
|
|
465
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
466
|
+
// Opened on its own (an SVG is a document), nothing in it may run or load.
|
|
467
|
+
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
|
468
|
+
// The URL carries ?v=<hash>: a new picture has a new URL, so this one may be cached for good.
|
|
469
|
+
res.setHeader('Cache-Control', url.searchParams.has('v') ? 'public, max-age=31536000, immutable' : 'no-cache');
|
|
470
|
+
res.end(req.method === 'HEAD' ? undefined : image.data);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
444
473
|
this.ui.serve(pathname, req, res);
|
|
445
474
|
}
|
|
446
475
|
catch (error) {
|
package/dist/http/http-io.d.ts
CHANGED
|
@@ -6,3 +6,5 @@ export type AdminRequest = IncomingMessage & {
|
|
|
6
6
|
export declare function sendJson(res: ServerResponse, status: number, body: unknown): void;
|
|
7
7
|
/** Uses the host-parsed body when present (Nest registers express.json()); otherwise reads the stream. */
|
|
8
8
|
export declare function readJsonBody(req: AdminRequest): Promise<unknown>;
|
|
9
|
+
/** The raw body of an upload, refused (413) past `limit` bytes. A body the host already read as a Buffer is used as is. */
|
|
10
|
+
export declare function readRawBody(req: AdminRequest, limit: number): Promise<Buffer>;
|
package/dist/http/http-io.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AdminBadRequestError } from '../errors.js';
|
|
1
|
+
import { AdminBadRequestError, AdminPayloadTooLargeError } from '../errors.js';
|
|
2
2
|
const MAX_BODY_BYTES = 1_048_576;
|
|
3
3
|
export function sendJson(res, status, body) {
|
|
4
4
|
const payload = JSON.stringify(body);
|
|
@@ -37,4 +37,22 @@ function parseJson(text) {
|
|
|
37
37
|
throw new AdminBadRequestError('Request body is not valid JSON');
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
|
+
/** The raw body of an upload, refused (413) past `limit` bytes. A body the host already read as a Buffer is used as is. */
|
|
41
|
+
export async function readRawBody(req, limit) {
|
|
42
|
+
if (Buffer.isBuffer(req.body)) {
|
|
43
|
+
if (req.body.length > limit)
|
|
44
|
+
throw new AdminPayloadTooLargeError(`The file is larger than ${limit} bytes`);
|
|
45
|
+
return req.body;
|
|
46
|
+
}
|
|
47
|
+
const chunks = [];
|
|
48
|
+
let size = 0;
|
|
49
|
+
for await (const chunk of req) {
|
|
50
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
51
|
+
size += buffer.length;
|
|
52
|
+
if (size > limit)
|
|
53
|
+
throw new AdminPayloadTooLargeError(`The file is larger than ${limit} bytes`);
|
|
54
|
+
chunks.push(buffer);
|
|
55
|
+
}
|
|
56
|
+
return Buffer.concat(chunks);
|
|
57
|
+
}
|
|
40
58
|
//# sourceMappingURL=http-io.js.map
|
package/dist/http/ui-assets.d.ts
CHANGED
|
@@ -22,12 +22,25 @@ export interface UiPageOptions {
|
|
|
22
22
|
/** The admin's `title`, in every language given. Defaults to the runtime config's title. */
|
|
23
23
|
title?: LocalizedText;
|
|
24
24
|
}
|
|
25
|
+
/** Pictures uploaded in the admin (`appearance`), read on every page load: they win over `branding.logo`. */
|
|
26
|
+
export type UiPictures = () => {
|
|
27
|
+
logo: string | null;
|
|
28
|
+
favicon: string | null;
|
|
29
|
+
};
|
|
30
|
+
/** A `<link rel="icon">` in `<head>` (replacing the build's own, if any). */
|
|
31
|
+
export declare function withFavicon(html: string, href: string): string;
|
|
25
32
|
export declare class UiAssets {
|
|
26
33
|
private readonly runtime;
|
|
34
|
+
private readonly pictures?;
|
|
27
35
|
private readonly root;
|
|
28
36
|
/** index.html as served: in the admin's default locale, with `<base href>` and the runtime config. */
|
|
29
|
-
private
|
|
30
|
-
|
|
37
|
+
private indexHtml;
|
|
38
|
+
/** The page before the runtime config, and the pictures the cached `indexHtml` was made with. */
|
|
39
|
+
private readonly localized;
|
|
40
|
+
private madeFor;
|
|
41
|
+
constructor(distDir: string, runtime: AdminRuntimeConfig, page?: UiPageOptions, pictures?: UiPictures | undefined);
|
|
42
|
+
/** The page with the pictures uploaded now (made again only when they change). */
|
|
43
|
+
private page;
|
|
31
44
|
/** Serves a file, 404s a missing /assets/* file, and falls back to index.html for client-side routes. */
|
|
32
45
|
serve(pathname: string, req: AdminRequest, res: ServerResponse): void;
|
|
33
46
|
private sendFile;
|
package/dist/http/ui-assets.js
CHANGED
|
@@ -92,13 +92,24 @@ export function resolveStaticFile(root, pathname) {
|
|
|
92
92
|
return undefined;
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
|
+
/** A `<link rel="icon">` in `<head>` (replacing the build's own, if any). */
|
|
96
|
+
export function withFavicon(html, href) {
|
|
97
|
+
const link = `<link rel="icon" href="${escapeAttribute(href)}">`;
|
|
98
|
+
const withoutOwn = html.replace(/<link\b[^>]*\brel\s*=\s*["']?(?:shortcut )?icon["']?[^>]*>/gi, '');
|
|
99
|
+
return withoutOwn.replace(/<\/head\s*>/i, (close) => link + close);
|
|
100
|
+
}
|
|
95
101
|
export class UiAssets {
|
|
96
102
|
runtime;
|
|
103
|
+
pictures;
|
|
97
104
|
root;
|
|
98
105
|
/** index.html as served: in the admin's default locale, with `<base href>` and the runtime config. */
|
|
99
106
|
indexHtml;
|
|
100
|
-
|
|
107
|
+
/** The page before the runtime config, and the pictures the cached `indexHtml` was made with. */
|
|
108
|
+
localized;
|
|
109
|
+
madeFor = '';
|
|
110
|
+
constructor(distDir, runtime, page = {}, pictures) {
|
|
101
111
|
this.runtime = runtime;
|
|
112
|
+
this.pictures = pictures;
|
|
102
113
|
this.root = resolve(distDir);
|
|
103
114
|
const indexPath = join(this.root, 'index.html');
|
|
104
115
|
// index.html as built, or the "missing build" page.
|
|
@@ -107,7 +118,22 @@ export class UiAssets {
|
|
|
107
118
|
// saved another choice, which lives in their browser where the server cannot see it), so `lang`, `dir` and the
|
|
108
119
|
// title are right from the first byte for everyone who has not switched. `Accept-Language` is not consulted.
|
|
109
120
|
const title = resolveText(page.title ?? runtime.title, runtime.locale, runtime.locale);
|
|
110
|
-
this.
|
|
121
|
+
this.localized = localizeDocument(template, { locale: runtime.locale, title });
|
|
122
|
+
this.indexHtml = injectRuntime(this.localized, runtime);
|
|
123
|
+
}
|
|
124
|
+
/** The page with the pictures uploaded now (made again only when they change). */
|
|
125
|
+
page() {
|
|
126
|
+
if (!this.pictures)
|
|
127
|
+
return this.indexHtml;
|
|
128
|
+
const now = this.pictures();
|
|
129
|
+
const key = `${now.logo ?? ''}|${now.favicon ?? ''}`;
|
|
130
|
+
if (key !== this.madeFor) {
|
|
131
|
+
const runtime = now.logo ? { ...this.runtime, branding: { ...this.runtime.branding, logo: now.logo } } : this.runtime;
|
|
132
|
+
const html = injectRuntime(this.localized, runtime);
|
|
133
|
+
this.indexHtml = now.favicon ? withFavicon(html, now.favicon) : html;
|
|
134
|
+
this.madeFor = key;
|
|
135
|
+
}
|
|
136
|
+
return this.indexHtml;
|
|
111
137
|
}
|
|
112
138
|
/** Serves a file, 404s a missing /assets/* file, and falls back to index.html for client-side routes. */
|
|
113
139
|
serve(pathname, req, res) {
|
|
@@ -122,7 +148,7 @@ export class UiAssets {
|
|
|
122
148
|
}
|
|
123
149
|
// One page for every request: no `Vary` (a host's own `Vary` header is left as it is).
|
|
124
150
|
res.setHeader('Content-Language', this.runtime.locale);
|
|
125
|
-
this.send(req, res, 200, 'text/html; charset=utf-8', this.
|
|
151
|
+
this.send(req, res, 200, 'text/html; charset=utf-8', this.page(), 'no-cache');
|
|
126
152
|
}
|
|
127
153
|
sendFile(file, pathname, req, res) {
|
|
128
154
|
let size;
|
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,8 @@ export type { AdminTranslate } from './i18n/texts.js';
|
|
|
5
5
|
export { ResourceRegistry, type RegisteredGroup, type RegisteredResource } from './registry/resource-registry.js';
|
|
6
6
|
export type { DbNames } from './registry/db-names.js';
|
|
7
7
|
export { AdminGroup, type AdminGroupOptions } from './decorators/admin-group.js';
|
|
8
|
-
export { AdminResource, type AdminResourceOptions } from './decorators/admin-resource.js';
|
|
8
|
+
export { AdminResource, AdminSource, type AdminResourceOptions, type AdminSourceOptions } from './decorators/admin-resource.js';
|
|
9
|
+
export { AdminSourceBase, inMemoryList } from './resource/admin-source-base.js';
|
|
9
10
|
export { AdminResourceBase, type FilterCondition, type FilterValue, type FindManyResult, type CountMode, type FormConfig, type ComputedColumn, type ComputedSource, type ListConfig, type ListTab, type ListParams, type RecordId, type RecordLinkConfig, } from './resource/admin-resource-base.js';
|
|
10
11
|
export { AdminField, BADGE_COLORS, WIDGETS, type AdminFieldOptions, type FileFieldOptions, type BadgeColor, type WidgetName } from './decorators/admin-field.js';
|
|
11
12
|
export type { FieldConfig, FieldsConfig, LayoutConfig, LayoutInlineConfig, LayoutSectionConfig, LayoutTabConfig } from './schema/field-config.js';
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export { AdminModule } from './admin.module.js';
|
|
2
2
|
export { ResourceRegistry } from './registry/resource-registry.js';
|
|
3
3
|
export { AdminGroup } from './decorators/admin-group.js';
|
|
4
|
-
export { AdminResource } from './decorators/admin-resource.js';
|
|
4
|
+
export { AdminResource, AdminSource } from './decorators/admin-resource.js';
|
|
5
|
+
export { AdminSourceBase, inMemoryList } from './resource/admin-source-base.js';
|
|
5
6
|
export { AdminResourceBase, } from './resource/admin-resource-base.js';
|
|
6
7
|
export { AdminField, BADGE_COLORS, WIDGETS } from './decorators/admin-field.js';
|
|
7
8
|
export { AdminContext } from './resource/admin-context.js';
|
|
@@ -83,7 +83,7 @@ export class InlineReader {
|
|
|
83
83
|
/** This parent's children as the user may view them: the child's `query()`, the user's view scopes, the link. */
|
|
84
84
|
children(inline, value, ctx) {
|
|
85
85
|
const { child } = inline;
|
|
86
|
-
const manager = ctx.manager ?? child.dataSource.manager;
|
|
86
|
+
const manager = ctx.manager ?? child.dataSource.manager; // a source has no relation, so it is never an inline child
|
|
87
87
|
const qb = manager.getRepository(child.metadata.target).createQueryBuilder('nma_inline');
|
|
88
88
|
return this.deps.policy.applyScopes(child.resource.query(qb, ctx), child, 'view', ctx).andWhere(`nma_inline.${inline.link} = :nmaInlineParent`, { nmaInlineParent: value });
|
|
89
89
|
}
|
|
@@ -152,7 +152,7 @@ export class InlineWriter {
|
|
|
152
152
|
}
|
|
153
153
|
// Children of THIS parent that the user sees: the child's query() and the user's view scopes, as its findOne.
|
|
154
154
|
const children = () => {
|
|
155
|
-
const manager = tx.manager ?? child.dataSource.manager;
|
|
155
|
+
const manager = tx.manager ?? child.dataSource.manager; // a source has no relation, so it is never an inline child
|
|
156
156
|
const qb = manager.getRepository(child.metadata.target).createQueryBuilder('nma_child');
|
|
157
157
|
const restricted = policy.applyScopes(child.resource.query(qb, tx), child, 'view', tx);
|
|
158
158
|
return restricted.andWhere(`nma_child.${inline.link} = :nmaInlineParent`, { nmaInlineParent: linkValue });
|
|
@@ -145,6 +145,12 @@ let AdminPolicy = class AdminPolicy {
|
|
|
145
145
|
this.requireReach(entry, ctx);
|
|
146
146
|
if (operation !== 'view' && entry.schema.readonly)
|
|
147
147
|
throw new AdminForbiddenError(`${entry.schema.label} records are read-only`);
|
|
148
|
+
const source = entry.schema.source;
|
|
149
|
+
if (source && (operation === 'create' || operation === 'update' || operation === 'delete') && !source[operation]) {
|
|
150
|
+
throw new AdminForbiddenError(`${entry.schema.label}: this source does not ${operation} records`);
|
|
151
|
+
}
|
|
152
|
+
if (source && operation === 'purge')
|
|
153
|
+
throw new AdminForbiddenError(`${entry.schema.label}: a source has no trash`);
|
|
148
154
|
if (!this.permissionsOf(ctx).canOn(entry.schema.name, operation)) {
|
|
149
155
|
throw new AdminForbiddenError(`You may not ${operation === 'view' ? 'view' : operation} ${entry.schema.label} records`);
|
|
150
156
|
}
|
|
@@ -261,10 +267,10 @@ let AdminPolicy = class AdminPolicy {
|
|
|
261
267
|
const editable = (name) => (levels.get(name) ?? 'hidden') === 'edit';
|
|
262
268
|
const r = schema.name;
|
|
263
269
|
const permissions = {
|
|
264
|
-
create: schema.creatable && perms.canOn(r, 'create'),
|
|
265
|
-
update: !schema.readonly && perms.canOn(r, 'update'),
|
|
266
|
-
delete: !schema.readonly && perms.canOn(r, 'delete'),
|
|
267
|
-
purge: !schema.readonly && perms.canOn(r, 'purge'),
|
|
270
|
+
create: schema.creatable && (schema.source?.create ?? true) && perms.canOn(r, 'create'),
|
|
271
|
+
update: !schema.readonly && (schema.source?.update ?? true) && perms.canOn(r, 'update'),
|
|
272
|
+
delete: !schema.readonly && (schema.source?.delete ?? true) && perms.canOn(r, 'delete'),
|
|
273
|
+
purge: !schema.readonly && !schema.source && perms.canOn(r, 'purge'),
|
|
268
274
|
};
|
|
269
275
|
const create = permissions.create ? schema.form.create.filter(editable) : [];
|
|
270
276
|
const update = permissions.update ? schema.form.update.filter(editable) : [];
|
|
@@ -429,7 +435,8 @@ let AdminPolicy = class AdminPolicy {
|
|
|
429
435
|
}
|
|
430
436
|
/** Whether a query for `operation` needs restricting at all. */
|
|
431
437
|
scoped(entry, operation, ctx) {
|
|
432
|
-
|
|
438
|
+
// Row scopes are query filters: a source has no query, so they do not apply to it (documented).
|
|
439
|
+
if (!ctx?.permissions || entry.source)
|
|
433
440
|
return false;
|
|
434
441
|
return ctx.permissions.scopes(entry.schema.name, operation) !== 'all' || this.globalScopes(entry, ctx.permissions).length > 0;
|
|
435
442
|
}
|
package/dist/policy/explain.js
CHANGED
|
@@ -104,7 +104,8 @@ async function explainRecord(policy, entry, raw, ctx) {
|
|
|
104
104
|
return { id: raw, exists: false, view: false, update: false, delete: false, reasons: { view: 'missing', update: 'missing', delete: 'missing' } };
|
|
105
105
|
}
|
|
106
106
|
const keys = entry.schema.primaryKeys;
|
|
107
|
-
|
|
107
|
+
// A source's row exists when its own findOne finds it.
|
|
108
|
+
const stored = entry.dataSource ? await entry.dataSource.manager.getRepository(entry.metadata.target).createQueryBuilder('nma_explain').whereInIds([id]).getOne() : await entry.resource.findOne(id, ctx);
|
|
108
109
|
const exists = stored !== null;
|
|
109
110
|
const key = recordIdOf(typeof id === 'object' ? id : { [keys[0]]: id }, keys);
|
|
110
111
|
const inScope = async (operation) => (await policy.allowedIds(entry, [id], operation, ctx)).has(key);
|
|
@@ -17,8 +17,12 @@ export interface RegisteredResource {
|
|
|
17
17
|
schema: ResourceSchema;
|
|
18
18
|
resource: AdminResourceBase<any>;
|
|
19
19
|
className: string;
|
|
20
|
+
/** The entity class; the row class of a source. */
|
|
20
21
|
entity: Function;
|
|
21
|
-
|
|
22
|
+
/** The entity's DataSource; absent for a source (`source: true`). */
|
|
23
|
+
dataSource?: DataSource;
|
|
24
|
+
/** An `@AdminSource`: rows from the class's own findMany/findOne, no table, no transaction. `metadata` is a stand-in built from the row class. */
|
|
25
|
+
source?: true;
|
|
22
26
|
/** Database column and constraint names → entity properties (for mapping constraint errors to fields). */
|
|
23
27
|
dbNames: DbNames;
|
|
24
28
|
metadata: EntityMetadata;
|
|
@@ -97,9 +101,9 @@ export declare class ResourceRegistry implements OnModuleInit {
|
|
|
97
101
|
find(name: string): RegisteredResource | undefined;
|
|
98
102
|
list(): RegisteredResource[];
|
|
99
103
|
/** The resource registered for an entity class on a DataSource (the first one, when several share it). */
|
|
100
|
-
forEntity(entity: Function | string, dataSource: DataSource): RegisteredResource | undefined;
|
|
104
|
+
forEntity(entity: Function | string, dataSource: DataSource | undefined): RegisteredResource | undefined;
|
|
101
105
|
/** How records of an entity are titled: its resource's `title`, or the default for its columns. */
|
|
102
|
-
titleFor(metadata: EntityMetadata, dataSource: DataSource): TitleFn;
|
|
106
|
+
titleFor(metadata: EntityMetadata, dataSource: DataSource | undefined): TitleFn;
|
|
103
107
|
groupList(): RegisteredGroup[];
|
|
104
108
|
/**
|
|
105
109
|
* The group each `@AdminGroup` module configures, by key: the label, icon and order of that key's group, whoever its
|
|
@@ -20,6 +20,8 @@ import { getAdminGroupOptions } from '../decorators/admin-group.js';
|
|
|
20
20
|
import { getAdminResourceDefinition } from '../decorators/admin-resource.js';
|
|
21
21
|
import { AdminNotFoundError } from '../errors.js';
|
|
22
22
|
import { AdminResourceBase } from '../resource/admin-resource-base.js';
|
|
23
|
+
import { AdminSourceBase } from '../resource/admin-source-base.js';
|
|
24
|
+
import { sourceMetadata } from '../schema/source-metadata.js';
|
|
23
25
|
import { buildResourceSchema } from '../schema/build-resource-schema.js';
|
|
24
26
|
import { getAdminFieldOptions } from '../decorators/admin-field.js';
|
|
25
27
|
import { nestedProtected, protectedInside, protectedOption } from '../schema/dto-form.js';
|
|
@@ -87,6 +89,9 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
87
89
|
if (seen.has(instance))
|
|
88
90
|
continue;
|
|
89
91
|
seen.add(instance);
|
|
92
|
+
if (definition.source && !(instance instanceof AdminSourceBase)) {
|
|
93
|
+
throw new Error(`${metatype.name} is decorated with @AdminSource but does not extend AdminSourceBase`);
|
|
94
|
+
}
|
|
90
95
|
if (!(instance instanceof AdminResourceBase)) {
|
|
91
96
|
throw new Error(`${metatype.name} is decorated with @AdminResource but does not extend AdminResourceBase`);
|
|
92
97
|
}
|
|
@@ -168,8 +173,8 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
168
173
|
const child = this.list().find((entry) => entry.entity === entity);
|
|
169
174
|
if (child)
|
|
170
175
|
return child.resource.readQuery(alias, ctx);
|
|
171
|
-
const owner = this.list().find((entry) => entry.dataSource
|
|
172
|
-
const manager = ctx?.manager ?? owner?.dataSource
|
|
176
|
+
const owner = this.list().find((entry) => entry.dataSource?.hasMetadata(entity));
|
|
177
|
+
const manager = ctx?.manager ?? owner?.dataSource?.manager;
|
|
173
178
|
if (!manager)
|
|
174
179
|
throw new Error(`nest-my-admin: no DataSource holds ${entity.name}`);
|
|
175
180
|
return manager.getRepository(entity).createQueryBuilder(alias);
|
|
@@ -266,23 +271,45 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
266
271
|
return key;
|
|
267
272
|
}
|
|
268
273
|
register(className, definition, resource, moduleGroup) {
|
|
269
|
-
const
|
|
274
|
+
const failed = (message) => {
|
|
275
|
+
throw new Error(`${className}: ${message}`);
|
|
276
|
+
};
|
|
270
277
|
let dataSource;
|
|
271
|
-
|
|
272
|
-
|
|
278
|
+
let metadata;
|
|
279
|
+
if (definition.source) {
|
|
280
|
+
// A source has no table: its columns come from the row class, and nothing is attached.
|
|
281
|
+
metadata = sourceMetadata(definition.entity, definition.source.primaryKeys, failed);
|
|
282
|
+
checkSourceConfig(resource, failed);
|
|
273
283
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
284
|
+
else {
|
|
285
|
+
const dataSourceName = definition.dataSource ?? 'default';
|
|
286
|
+
try {
|
|
287
|
+
dataSource = this.moduleRef.get(getDataSourceToken(dataSourceName), { strict: false });
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
throw new Error(`${className}: TypeORM DataSource "${dataSourceName}" not found; is TypeOrmModule.forRoot() imported?`);
|
|
291
|
+
}
|
|
292
|
+
if (!dataSource.hasMetadata(definition.entity)) {
|
|
293
|
+
throw new Error(`${className}: entity ${definition.entity.name} is not registered in DataSource "${dataSourceName}"`);
|
|
294
|
+
}
|
|
295
|
+
metadata = dataSource.getMetadata(definition.entity);
|
|
296
|
+
resource.attachRepository(dataSource.getRepository(definition.entity));
|
|
279
297
|
}
|
|
280
|
-
const metadata = dataSource.getMetadata(definition.entity);
|
|
281
|
-
resource.attachRepository(dataSource.getRepository(definition.entity));
|
|
282
298
|
const order = memberOrder(definition.order, (message) => {
|
|
283
299
|
throw new Error(`${className}: ${message}`);
|
|
284
300
|
});
|
|
285
301
|
const schema = buildResourceSchema({ definition, resource, metadata, moduleGroup, className });
|
|
302
|
+
if (definition.source) {
|
|
303
|
+
// Only the writes the class implements are offered.
|
|
304
|
+
const writes = AdminSourceBase.writesOf(resource);
|
|
305
|
+
if (!writes.create)
|
|
306
|
+
schema.creatable = false;
|
|
307
|
+
if (!writes.create)
|
|
308
|
+
schema.form.create = [];
|
|
309
|
+
if (!writes.update)
|
|
310
|
+
schema.form.update = [];
|
|
311
|
+
schema.source = writes;
|
|
312
|
+
}
|
|
286
313
|
resource.attachUpdateFields(() => schema.form.update);
|
|
287
314
|
checkTabs(schema, resource.list?.tabs, (message) => {
|
|
288
315
|
throw new Error(`${className}: ${message}`);
|
|
@@ -309,6 +336,8 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
309
336
|
}
|
|
310
337
|
// All-or-nothing is a promise only a transaction can keep.
|
|
311
338
|
const atomic = [...actions.values()].find((action) => action.atomic);
|
|
339
|
+
if (atomic && definition.source)
|
|
340
|
+
failed(`@AdminAction "${atomic.name}" is \`atomic\`, which needs a transaction; a source has no DataSource`);
|
|
312
341
|
if (atomic && !this.options.transactions) {
|
|
313
342
|
throw new Error(`${className}: @AdminAction "${atomic.name}" is \`atomic\`, which needs the admin's transactions; they are off (\`transactions: false\`)`);
|
|
314
343
|
}
|
|
@@ -351,8 +380,9 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
351
380
|
resource,
|
|
352
381
|
className,
|
|
353
382
|
entity: definition.entity,
|
|
354
|
-
dataSource,
|
|
355
|
-
dbNames: dbNamesFor(metadata),
|
|
383
|
+
...(dataSource ? { dataSource } : {}),
|
|
384
|
+
dbNames: definition.source ? { columns: new Map(), constraints: new Map() } : dbNamesFor(metadata),
|
|
385
|
+
...(definition.source ? { source: true } : {}),
|
|
356
386
|
metadata,
|
|
357
387
|
relations,
|
|
358
388
|
title,
|
|
@@ -370,6 +400,13 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
370
400
|
...(definition.nav !== undefined ? { navOption: definition.nav } : {}),
|
|
371
401
|
inlines: [],
|
|
372
402
|
});
|
|
403
|
+
// Files belong to a stored record (they are attached, released and swept with it): a source has none.
|
|
404
|
+
if (definition.source) {
|
|
405
|
+
for (const [field, options] of this.resources.get(schema.name).fieldConfig) {
|
|
406
|
+
if (options.widget === 'file' || options.widget === 'image' || options.widget === 'richtext')
|
|
407
|
+
failed(`fields.${field}: the "${options.widget}" widget is not available on an @AdminSource (it needs a database table)`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
373
410
|
}
|
|
374
411
|
/** Points each relation field at the resource of its target entity, now that every resource is registered. */
|
|
375
412
|
/**
|
|
@@ -500,4 +537,30 @@ function checkExport(option, schema, fail) {
|
|
|
500
537
|
fail(`max must be an integer from 1 to ${EXPORT_LIMIT}`);
|
|
501
538
|
return { columns: columns, max: max };
|
|
502
539
|
}
|
|
540
|
+
/** What a source cannot have: everything that is a query on a table or needs a transaction. */
|
|
541
|
+
function checkSourceConfig(resource, fail) {
|
|
542
|
+
const list = resource.list;
|
|
543
|
+
const not = (what) => fail(`${what}: not available on an @AdminSource (it needs a database table)`);
|
|
544
|
+
if (list?.tabs?.length)
|
|
545
|
+
not('list.tabs');
|
|
546
|
+
if (list?.computed && Object.keys(list.computed).length > 0)
|
|
547
|
+
not('list.computed');
|
|
548
|
+
if (list?.pagination === 'keyset')
|
|
549
|
+
not("list.pagination 'keyset'");
|
|
550
|
+
if (list?.count !== undefined && list.count !== 'exact')
|
|
551
|
+
not(`list.count '${list.count}'`);
|
|
552
|
+
if (list?.export)
|
|
553
|
+
not('list.export');
|
|
554
|
+
const layout = resource.form?.layout;
|
|
555
|
+
const main = layout && !Array.isArray(layout) && 'main' in layout ? layout.main : layout;
|
|
556
|
+
const hasInline = (node) => Array.isArray(node) ? node.some(hasInline) : typeof node === 'object' && node !== null && ('inline' in node || Object.values(node).some(hasInline));
|
|
557
|
+
if (hasInline(main ?? []))
|
|
558
|
+
not('form.layout inlines');
|
|
559
|
+
if (layout && !Array.isArray(layout) && 'aside' in layout && layout.aside.some((card) => 'relation' in card && card.relation !== undefined))
|
|
560
|
+
not('form.layout relation aside cards');
|
|
561
|
+
for (const [field, options] of Object.entries((resource.fields ?? {}))) {
|
|
562
|
+
if (options?.history !== undefined)
|
|
563
|
+
not(`fields.${field}.history`);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
503
566
|
//# sourceMappingURL=resource-registry.js.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ObjectLiteral } from 'typeorm';
|
|
2
|
+
import type { AdminContext } from './admin-context.js';
|
|
3
|
+
import { AdminResourceBase, type FindManyResult, type ListParams, type RecordId } from './admin-resource-base.js';
|
|
4
|
+
/**
|
|
5
|
+
* The base of an `@AdminSource` resource: rows that are not database rows (an HTTP API, files, live state). Answer
|
|
6
|
+
* `findMany` (the list: `inMemoryList` does search, filters, sort and paging for rows fetched whole) and `findOne` (one
|
|
7
|
+
* row by id, `null` when there is none). Override `create`, `update` and `delete` to allow them: a source that does not
|
|
8
|
+
* is not offered New, Save or Delete, and the API refuses them (403).
|
|
9
|
+
*
|
|
10
|
+
* There is no DataSource: `ctx.manager` is never set, writes are not wrapped in a transaction, and the TypeORM helpers
|
|
11
|
+
* of AdminResourceBase (`query`, `buildListQuery`, `repository`, `restore`, `purge`) are not used.
|
|
12
|
+
*/
|
|
13
|
+
export declare abstract class AdminSourceBase<T extends ObjectLiteral = ObjectLiteral, Id extends RecordId = RecordId> extends AdminResourceBase<T, Id> {
|
|
14
|
+
abstract findMany(params: ListParams, ctx: AdminContext): Promise<FindManyResult<T>>;
|
|
15
|
+
abstract findOne(id: Id, ctx: AdminContext, options?: {
|
|
16
|
+
withDeleted?: boolean;
|
|
17
|
+
}): Promise<T | null>;
|
|
18
|
+
create(_dto: object, _ctx: AdminContext): Promise<T>;
|
|
19
|
+
update(_id: Id, _dto: object, _ctx: AdminContext): Promise<T>;
|
|
20
|
+
delete(_id: Id, _ctx: AdminContext): Promise<void>;
|
|
21
|
+
restore(_id: Id, _ctx: AdminContext): Promise<T>;
|
|
22
|
+
purge(_id: Id, _ctx: AdminContext): Promise<void>;
|
|
23
|
+
/** @internal Which writes the class allows: those it overrides. */
|
|
24
|
+
static writesOf(resource: AdminSourceBase<any, any>): {
|
|
25
|
+
create: boolean;
|
|
26
|
+
update: boolean;
|
|
27
|
+
delete: boolean;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A page of `rows` as the list asked for it: `params.search` (case-insensitive, any of its fields), `params.filters`,
|
|
32
|
+
* `params.sort` (stable) and `params.page`/`pageSize`. For sources that fetch every row at once (an API answering a
|
|
33
|
+
* few hundred records, a folder of files): return it from `findMany`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function inMemoryList<T extends ObjectLiteral>(rows: readonly T[], params: ListParams): FindManyResult<T>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { AdminForbiddenError } from '../errors.js';
|
|
2
|
+
import { AdminResourceBase } from './admin-resource-base.js';
|
|
3
|
+
/**
|
|
4
|
+
* The base of an `@AdminSource` resource: rows that are not database rows (an HTTP API, files, live state). Answer
|
|
5
|
+
* `findMany` (the list: `inMemoryList` does search, filters, sort and paging for rows fetched whole) and `findOne` (one
|
|
6
|
+
* row by id, `null` when there is none). Override `create`, `update` and `delete` to allow them: a source that does not
|
|
7
|
+
* is not offered New, Save or Delete, and the API refuses them (403).
|
|
8
|
+
*
|
|
9
|
+
* There is no DataSource: `ctx.manager` is never set, writes are not wrapped in a transaction, and the TypeORM helpers
|
|
10
|
+
* of AdminResourceBase (`query`, `buildListQuery`, `repository`, `restore`, `purge`) are not used.
|
|
11
|
+
*/
|
|
12
|
+
export class AdminSourceBase extends AdminResourceBase {
|
|
13
|
+
async create(_dto, _ctx) {
|
|
14
|
+
throw new AdminForbiddenError(`${this.constructor.name} does not create rows`);
|
|
15
|
+
}
|
|
16
|
+
async update(_id, _dto, _ctx) {
|
|
17
|
+
throw new AdminForbiddenError(`${this.constructor.name} does not change rows`);
|
|
18
|
+
}
|
|
19
|
+
async delete(_id, _ctx) {
|
|
20
|
+
throw new AdminForbiddenError(`${this.constructor.name} does not delete rows`);
|
|
21
|
+
}
|
|
22
|
+
async restore(_id, _ctx) {
|
|
23
|
+
throw new AdminForbiddenError(`${this.constructor.name} has no trash`);
|
|
24
|
+
}
|
|
25
|
+
async purge(_id, _ctx) {
|
|
26
|
+
throw new AdminForbiddenError(`${this.constructor.name} has no trash`);
|
|
27
|
+
}
|
|
28
|
+
/** @internal Which writes the class allows: those it overrides. */
|
|
29
|
+
static writesOf(resource) {
|
|
30
|
+
const proto = AdminSourceBase.prototype;
|
|
31
|
+
return { create: resource.create !== proto.create, update: resource.update !== proto.update, delete: resource.delete !== proto.delete };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const comparable = (value) => (value instanceof Date ? value.getTime() : value);
|
|
35
|
+
function compare(a, b) {
|
|
36
|
+
const x = comparable(a);
|
|
37
|
+
const y = comparable(b);
|
|
38
|
+
if (x === y)
|
|
39
|
+
return 0;
|
|
40
|
+
if (x === null || x === undefined)
|
|
41
|
+
return -1;
|
|
42
|
+
if (y === null || y === undefined)
|
|
43
|
+
return 1;
|
|
44
|
+
if (typeof x === 'number' && typeof y === 'number')
|
|
45
|
+
return x - y;
|
|
46
|
+
if (typeof x === 'boolean' && typeof y === 'boolean')
|
|
47
|
+
return Number(x) - Number(y);
|
|
48
|
+
return String(x).localeCompare(String(y), undefined, { numeric: true, sensitivity: 'base' });
|
|
49
|
+
}
|
|
50
|
+
/** A filter value next to a row value: dates and numbers compare as such, the rest as text. */
|
|
51
|
+
function same(row, value) {
|
|
52
|
+
if (row instanceof Date || value instanceof Date)
|
|
53
|
+
return comparable(row) === comparable(value instanceof Date ? value : new Date(String(value)));
|
|
54
|
+
if (typeof row === 'number')
|
|
55
|
+
return row === Number(value);
|
|
56
|
+
if (typeof row === 'boolean')
|
|
57
|
+
return row === (value === true || value === 'true');
|
|
58
|
+
return String(row ?? '') === String(value);
|
|
59
|
+
}
|
|
60
|
+
function matches(row, condition) {
|
|
61
|
+
const actual = row[condition.field];
|
|
62
|
+
const value = condition.value;
|
|
63
|
+
const list = Array.isArray(value) ? value : [value];
|
|
64
|
+
const text = (v) => String(v ?? '').toLocaleLowerCase();
|
|
65
|
+
switch (condition.operator) {
|
|
66
|
+
case 'eq':
|
|
67
|
+
return same(actual, value);
|
|
68
|
+
case 'ne':
|
|
69
|
+
return !same(actual, value);
|
|
70
|
+
case 'in':
|
|
71
|
+
return list.some((item) => same(actual, item));
|
|
72
|
+
case 'nin':
|
|
73
|
+
return !list.some((item) => same(actual, item));
|
|
74
|
+
case 'lt':
|
|
75
|
+
return actual !== null && actual !== undefined && compare(actual, value) < 0;
|
|
76
|
+
case 'lte':
|
|
77
|
+
return actual !== null && actual !== undefined && compare(actual, value) <= 0;
|
|
78
|
+
case 'gt':
|
|
79
|
+
return actual !== null && actual !== undefined && compare(actual, value) > 0;
|
|
80
|
+
case 'gte':
|
|
81
|
+
return actual !== null && actual !== undefined && compare(actual, value) >= 0;
|
|
82
|
+
case 'between':
|
|
83
|
+
return actual !== null && actual !== undefined && compare(actual, list[0]) >= 0 && compare(actual, list[1]) <= 0;
|
|
84
|
+
case 'contains':
|
|
85
|
+
return text(actual).includes(text(value));
|
|
86
|
+
case 'startsWith':
|
|
87
|
+
return text(actual).startsWith(text(value));
|
|
88
|
+
case 'isNull':
|
|
89
|
+
return (value === true || value === 'true') === (actual === null || actual === undefined);
|
|
90
|
+
default:
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* A page of `rows` as the list asked for it: `params.search` (case-insensitive, any of its fields), `params.filters`,
|
|
96
|
+
* `params.sort` (stable) and `params.page`/`pageSize`. For sources that fetch every row at once (an API answering a
|
|
97
|
+
* few hundred records, a folder of files): return it from `findMany`.
|
|
98
|
+
*/
|
|
99
|
+
export function inMemoryList(rows, params) {
|
|
100
|
+
let found = [...rows];
|
|
101
|
+
if (params.search && params.search.term.trim() !== '') {
|
|
102
|
+
const term = params.search.term.trim().toLocaleLowerCase();
|
|
103
|
+
found = found.filter((row) => params.search.fields.some((field) => String(row[field] ?? '').toLocaleLowerCase().includes(term)));
|
|
104
|
+
}
|
|
105
|
+
for (const condition of params.filters)
|
|
106
|
+
found = found.filter((row) => matches(row, condition));
|
|
107
|
+
const { field, direction } = params.sort;
|
|
108
|
+
if (field) {
|
|
109
|
+
const sign = direction === 'desc' ? -1 : 1;
|
|
110
|
+
found = found.map((row, index) => ({ row, index })).sort((a, b) => sign * compare(a.row[field], b.row[field]) || a.index - b.index).map(({ row }) => row);
|
|
111
|
+
}
|
|
112
|
+
const start = (Math.max(1, params.page) - 1) * params.pageSize;
|
|
113
|
+
return { items: found.slice(start, start + params.pageSize), total: found.length };
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=admin-source-base.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ColumnLike } from './column-field.js';
|
|
2
|
+
import type { EntityMetadataLike } from './build-resource-schema.js';
|
|
3
|
+
/**
|
|
4
|
+
* What a source row looks like to the schema builder: one column per property with a class-validator decorator, the
|
|
5
|
+
* primary keys marked, and nothing TypeORM-only (relations, embeddeds, inheritance, uniques). The schema of a source is
|
|
6
|
+
* then built like an entity's, so `list`, `form` and `fields` config are checked the same way.
|
|
7
|
+
*/
|
|
8
|
+
export declare function sourceMetadata(row: Function, primaryKeys: string[], fail: (message: string) => never): EntityMetadataLike & {
|
|
9
|
+
tablePath: string;
|
|
10
|
+
deleteDateColumn: undefined;
|
|
11
|
+
discriminatorColumn: undefined;
|
|
12
|
+
childEntityMetadatas: [];
|
|
13
|
+
embeddeds: [];
|
|
14
|
+
findColumnWithPropertyName(name: string): ColumnLike | undefined;
|
|
15
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { dtoConstraints } from './dto-constraints.js';
|
|
2
|
+
import { dtoOnlyField, dtoPropertyNames } from './dto-fields.js';
|
|
3
|
+
import { didYouMean } from './suggest.js';
|
|
4
|
+
/** The column type a row property of each field type stands for (what `columnToField` reads back). */
|
|
5
|
+
const COLUMN_TYPES = {
|
|
6
|
+
string: 'varchar',
|
|
7
|
+
text: 'text',
|
|
8
|
+
boolean: 'boolean',
|
|
9
|
+
date: 'date',
|
|
10
|
+
datetime: 'datetime',
|
|
11
|
+
json: 'simple-json',
|
|
12
|
+
uuid: 'uuid',
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* What a source row looks like to the schema builder: one column per property with a class-validator decorator, the
|
|
16
|
+
* primary keys marked, and nothing TypeORM-only (relations, embeddeds, inheritance, uniques). The schema of a source is
|
|
17
|
+
* then built like an entity's, so `list`, `form` and `fields` config are checked the same way.
|
|
18
|
+
*/
|
|
19
|
+
export function sourceMetadata(row, primaryKeys, fail) {
|
|
20
|
+
const dto = row;
|
|
21
|
+
const names = dtoPropertyNames(dto);
|
|
22
|
+
if (names.length === 0)
|
|
23
|
+
fail(`row ${row.name}: no property has a class-validator decorator (@IsString(), @IsInt()...), so the source has no fields`);
|
|
24
|
+
if (primaryKeys.length === 0)
|
|
25
|
+
fail('primaryKey: name at least one row property');
|
|
26
|
+
for (const key of primaryKeys) {
|
|
27
|
+
if (!names.includes(key))
|
|
28
|
+
fail(`primaryKey: "${key}" is not a decorated property of ${row.name}${didYouMean(key, names)}`);
|
|
29
|
+
}
|
|
30
|
+
const constraints = dtoConstraints(dto);
|
|
31
|
+
const columns = names.map((name) => {
|
|
32
|
+
const field = dtoOnlyField(dto, name);
|
|
33
|
+
const designType = Reflect.getMetadata('design:type', dto.prototype, name);
|
|
34
|
+
const type = field.type === 'enum'
|
|
35
|
+
? 'simple-enum'
|
|
36
|
+
: field.type === 'number'
|
|
37
|
+
? constraints[name]?.integer
|
|
38
|
+
? 'int'
|
|
39
|
+
: 'double'
|
|
40
|
+
: designType === Object || designType === Array
|
|
41
|
+
? 'simple-json'
|
|
42
|
+
: (COLUMN_TYPES[field.type] ?? 'varchar');
|
|
43
|
+
const primary = primaryKeys.includes(name);
|
|
44
|
+
return {
|
|
45
|
+
propertyName: name,
|
|
46
|
+
propertyPath: name,
|
|
47
|
+
type,
|
|
48
|
+
isNullable: field.nullable && !primary,
|
|
49
|
+
isPrimary: primary,
|
|
50
|
+
isGenerated: false,
|
|
51
|
+
isCreateDate: false,
|
|
52
|
+
isUpdateDate: false,
|
|
53
|
+
isDeleteDate: false,
|
|
54
|
+
isVersion: false,
|
|
55
|
+
isSelect: true,
|
|
56
|
+
...(field.enumValues ? { enum: [...field.enumValues] } : {}),
|
|
57
|
+
target: row,
|
|
58
|
+
};
|
|
59
|
+
});
|
|
60
|
+
return {
|
|
61
|
+
name: row.name,
|
|
62
|
+
target: row,
|
|
63
|
+
tablePath: `source:${row.name}`,
|
|
64
|
+
columns,
|
|
65
|
+
primaryColumns: columns.filter((column) => column.isPrimary),
|
|
66
|
+
relations: [],
|
|
67
|
+
childEntityMetadatas: [],
|
|
68
|
+
embeddeds: [],
|
|
69
|
+
uniques: [],
|
|
70
|
+
indices: [],
|
|
71
|
+
deleteDateColumn: undefined,
|
|
72
|
+
discriminatorColumn: undefined,
|
|
73
|
+
findColumnWithPropertyName: (name) => columns.find((column) => column.propertyName === name),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=source-metadata.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nest-my-admin/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"description": "Django-admin-class admin panel for NestJS + TypeORM",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@nest-my-admin/ui": "0.
|
|
38
|
+
"@nest-my-admin/ui": "0.8.1"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"@nestjs/common": "^11.0.0 || ^12.0.0",
|