@murumets-ee/entity 0.1.0
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/LICENSE +94 -0
- package/README.md +15 -0
- package/dist/admin/index.d.ts +510 -0
- package/dist/admin/index.js +1 -0
- package/dist/index.d.ts +1027 -0
- package/dist/index.js +64 -0
- package/dist/query/index.d.ts +417 -0
- package/dist/query/index.js +6 -0
- package/dist/refs/index.d.ts +263 -0
- package/dist/refs/index.js +1 -0
- package/package.json +44 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Elastic License 2.0 (ELv2)
|
|
2
|
+
|
|
3
|
+
URL: https://www.elastic.co/licensing/elastic-license
|
|
4
|
+
|
|
5
|
+
## Acceptance
|
|
6
|
+
|
|
7
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
8
|
+
|
|
9
|
+
## Copyright License
|
|
10
|
+
|
|
11
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
12
|
+
non-sublicensable, non-transferable license to use, copy, distribute, make
|
|
13
|
+
available, and prepare derivative works of the software, in each case subject
|
|
14
|
+
to the limitations and conditions below.
|
|
15
|
+
|
|
16
|
+
## Limitations
|
|
17
|
+
|
|
18
|
+
You may not provide the software to third parties as a hosted or managed
|
|
19
|
+
service, where the service provides users with access to any substantial set
|
|
20
|
+
of the features or functionality of the software.
|
|
21
|
+
|
|
22
|
+
You may not move, change, disable, or circumvent the license key functionality
|
|
23
|
+
in the software, and you may not remove or obscure any functionality in the
|
|
24
|
+
software that is protected by the license key.
|
|
25
|
+
|
|
26
|
+
You may not alter, remove, or obscure any licensing, copyright, or other
|
|
27
|
+
notices of the licensor in the software. Any use of the licensor's trademarks
|
|
28
|
+
is subject to applicable law.
|
|
29
|
+
|
|
30
|
+
## Patents
|
|
31
|
+
|
|
32
|
+
The licensor grants you a license, under any patent claims the licensor can
|
|
33
|
+
license, or becomes able to license, to make, have made, use, sell, offer for
|
|
34
|
+
sale, import and have imported the software, in each case subject to the
|
|
35
|
+
limitations and conditions in this license. This license does not cover any
|
|
36
|
+
patent claims that you cause to be infringed by modifications or additions to
|
|
37
|
+
the software. If you or your company make any written claim that the software
|
|
38
|
+
infringes or contributes to infringement of any patent, your patent license
|
|
39
|
+
for the software granted under these terms ends immediately. If your company
|
|
40
|
+
makes such a claim, your patent license ends immediately for work on behalf
|
|
41
|
+
of your company.
|
|
42
|
+
|
|
43
|
+
## Notices
|
|
44
|
+
|
|
45
|
+
You must ensure that anyone who gets a copy of any part of the software from
|
|
46
|
+
you also gets a copy of these terms.
|
|
47
|
+
|
|
48
|
+
If you modify the software, you must include in any modified copies of the
|
|
49
|
+
software prominent notices stating that you have modified the software.
|
|
50
|
+
|
|
51
|
+
## No Other Rights
|
|
52
|
+
|
|
53
|
+
These terms do not imply any licenses other than those expressly granted in
|
|
54
|
+
these terms.
|
|
55
|
+
|
|
56
|
+
## Termination
|
|
57
|
+
|
|
58
|
+
If you use the software in violation of these terms, such use is not licensed,
|
|
59
|
+
and your licenses will automatically terminate. If the licensor provides you
|
|
60
|
+
with a notice of your violation, and you cease all violation of this license
|
|
61
|
+
no later than 30 days after you receive that notice, your licenses will be
|
|
62
|
+
reinstated retroactively. However, if you violate these terms after such
|
|
63
|
+
reinstatement, any additional violation of these terms will cause your
|
|
64
|
+
licenses to terminate automatically and permanently.
|
|
65
|
+
|
|
66
|
+
## No Liability
|
|
67
|
+
|
|
68
|
+
As far as the law allows, the software comes as is, without any warranty or
|
|
69
|
+
condition, and the licensor will not be liable to you for any damages arising
|
|
70
|
+
out of these terms or the use or nature of the software, under any kind of
|
|
71
|
+
legal claim.
|
|
72
|
+
|
|
73
|
+
## Definitions
|
|
74
|
+
|
|
75
|
+
The **licensor** is the entity offering these terms, and the **software** is
|
|
76
|
+
the software the licensor makes available under these terms, including any
|
|
77
|
+
portion of it.
|
|
78
|
+
|
|
79
|
+
**you** refers to the individual or entity agreeing to these terms.
|
|
80
|
+
|
|
81
|
+
**your company** is any legal entity, sole proprietorship, or other kind of
|
|
82
|
+
organization that you work for, plus all organizations that have control over,
|
|
83
|
+
are under the control of, or are under common control with that organization.
|
|
84
|
+
**control** means ownership of substantially all the assets of an entity, or
|
|
85
|
+
the power to direct the management and policies of an entity (for example, by
|
|
86
|
+
voting right, contract, or otherwise). Control can be direct or indirect.
|
|
87
|
+
|
|
88
|
+
**your licenses** are all the licenses granted to you for the software under
|
|
89
|
+
these terms.
|
|
90
|
+
|
|
91
|
+
**use** means anything you do with the software requiring one of your
|
|
92
|
+
licenses.
|
|
93
|
+
|
|
94
|
+
**trademark** means trademarks, service marks, and similar rights.
|
package/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# @murumets-ee/entity
|
|
2
|
+
|
|
3
|
+
Entity definition, field builders, behaviors, admin client, query client, and schema generation.
|
|
4
|
+
|
|
5
|
+
Part of [Lumi CMS](https://github.com/murumets-ee/lumi-cms) — a modular, type-safe CMS toolkit for Node.js.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @murumets-ee/entity
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## License
|
|
14
|
+
|
|
15
|
+
[Elastic License 2.0 (ELv2)](../../LICENSE)
|
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
import { SQL } from 'drizzle-orm';
|
|
2
|
+
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* In-memory TTL cache for COUNT(*) query results.
|
|
6
|
+
*
|
|
7
|
+
* Reduces database load on paginated list pages where the total count
|
|
8
|
+
* is recalculated on every pagination/sort/search interaction. The cache
|
|
9
|
+
* is per-process (not shared across workers) with a short TTL (default 5s)
|
|
10
|
+
* so counts are at most a few seconds stale.
|
|
11
|
+
*
|
|
12
|
+
* Cache keys include the entity name + serialized WHERE clause, so filtered
|
|
13
|
+
* and unfiltered counts are cached independently.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Interface for count cache implementations.
|
|
17
|
+
* Used in client configs to avoid TypeScript private-field structural incompatibility
|
|
18
|
+
* across separate .d.ts files.
|
|
19
|
+
*/
|
|
20
|
+
interface CountCacheLike {
|
|
21
|
+
get(key: string): number | undefined;
|
|
22
|
+
set(key: string, count: number): void;
|
|
23
|
+
invalidate(prefix: string): void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Cursor-based (keyset) pagination utilities.
|
|
28
|
+
*
|
|
29
|
+
* Cursor pagination avoids the performance cliff of OFFSET at scale (1M+ rows).
|
|
30
|
+
* Instead of `OFFSET N`, it uses a WHERE condition:
|
|
31
|
+
* `WHERE (sortField < lastValue) OR (sortField = lastValue AND id < lastId)`
|
|
32
|
+
* which Postgres can serve from an index in constant time.
|
|
33
|
+
*
|
|
34
|
+
* The cursor is opaque to the client — base64-encoded JSON.
|
|
35
|
+
*
|
|
36
|
+
* Security:
|
|
37
|
+
* - `field` must be whitelisted against the entity's actual fields
|
|
38
|
+
* - `id` must be a valid UUID
|
|
39
|
+
* - `value` is parameterized (never interpolated into SQL)
|
|
40
|
+
* - Malformed cursors return null (caller returns 400)
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/** Cursor input for keyset pagination. */
|
|
44
|
+
interface CursorInput {
|
|
45
|
+
/** Sort field name (e.g. 'createdAt'). Must be a real column on the entity. */
|
|
46
|
+
field: string;
|
|
47
|
+
/** Last seen value of the sort field. */
|
|
48
|
+
value: string | number;
|
|
49
|
+
/** Sort direction — must match the ORDER BY direction. */
|
|
50
|
+
direction: 'asc' | 'desc';
|
|
51
|
+
/** Tie-breaker: last seen entity ID. Required for non-unique sort fields. */
|
|
52
|
+
id?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Optional admin UI configuration for entities.
|
|
57
|
+
* Controls how entities appear in the admin sidebar, list pages, and forms.
|
|
58
|
+
*/
|
|
59
|
+
interface EntityAdminConfig {
|
|
60
|
+
/** Sidebar section: 'content' | 'structure' | custom string. Default: 'content' */
|
|
61
|
+
group?: string;
|
|
62
|
+
/** Plural display name for sidebar + list pages. Default: title-cased pluralized entity name */
|
|
63
|
+
label?: string;
|
|
64
|
+
/** Singular label for "New X" button. Default: title-cased entity name */
|
|
65
|
+
labelSingular?: string;
|
|
66
|
+
/** Lucide icon name as string, e.g. 'file-text' */
|
|
67
|
+
icon?: string;
|
|
68
|
+
/** Description shown on list page */
|
|
69
|
+
description?: string;
|
|
70
|
+
/** Form layout. Default: 'single' */
|
|
71
|
+
layout?: 'single' | 'two-column';
|
|
72
|
+
/** Fields to hide in the form */
|
|
73
|
+
hiddenFields?: string[];
|
|
74
|
+
/** Columns to hide in the list */
|
|
75
|
+
hiddenColumns?: string[];
|
|
76
|
+
/** Per-field label/description/placeholder overrides */
|
|
77
|
+
fieldOverrides?: Record<string, {
|
|
78
|
+
label?: string;
|
|
79
|
+
description?: string;
|
|
80
|
+
placeholder?: string;
|
|
81
|
+
}>;
|
|
82
|
+
/** Default list sort field. Default: 'createdAt' */
|
|
83
|
+
defaultSort?: string;
|
|
84
|
+
/** Default list sort direction. Default: 'desc' */
|
|
85
|
+
defaultSortDirection?: 'asc' | 'desc';
|
|
86
|
+
/** List page size. Default: 20 */
|
|
87
|
+
pageSize?: number;
|
|
88
|
+
/** For block editor: fields to show in Puck root config */
|
|
89
|
+
rootFields?: string[];
|
|
90
|
+
/** Suppress "New" button in the list page */
|
|
91
|
+
disableCreate?: boolean;
|
|
92
|
+
/** Order within sidebar group. Default: 0 */
|
|
93
|
+
sortOrder?: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Field type definitions
|
|
98
|
+
* These define the structure and configuration for all field types
|
|
99
|
+
*/
|
|
100
|
+
interface BaseFieldConfig {
|
|
101
|
+
required?: boolean;
|
|
102
|
+
default?: unknown;
|
|
103
|
+
translatable?: boolean;
|
|
104
|
+
indexed?: boolean;
|
|
105
|
+
unique?: boolean;
|
|
106
|
+
access?: {
|
|
107
|
+
view?: string;
|
|
108
|
+
edit?: string;
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
interface IdField extends BaseFieldConfig {
|
|
112
|
+
type: 'id';
|
|
113
|
+
}
|
|
114
|
+
interface TextField extends BaseFieldConfig {
|
|
115
|
+
type: 'text';
|
|
116
|
+
maxLength?: number;
|
|
117
|
+
minLength?: number;
|
|
118
|
+
pattern?: RegExp;
|
|
119
|
+
}
|
|
120
|
+
interface NumberField extends BaseFieldConfig {
|
|
121
|
+
type: 'number';
|
|
122
|
+
min?: number;
|
|
123
|
+
max?: number;
|
|
124
|
+
integer?: boolean;
|
|
125
|
+
}
|
|
126
|
+
interface BooleanField extends BaseFieldConfig {
|
|
127
|
+
type: 'boolean';
|
|
128
|
+
}
|
|
129
|
+
interface DateField extends BaseFieldConfig {
|
|
130
|
+
type: 'date';
|
|
131
|
+
minDate?: Date;
|
|
132
|
+
maxDate?: Date;
|
|
133
|
+
}
|
|
134
|
+
interface SelectField extends BaseFieldConfig {
|
|
135
|
+
type: 'select';
|
|
136
|
+
options: readonly string[];
|
|
137
|
+
}
|
|
138
|
+
interface ReferenceField extends BaseFieldConfig {
|
|
139
|
+
type: 'reference';
|
|
140
|
+
entity: string;
|
|
141
|
+
cardinality: 'one' | 'many';
|
|
142
|
+
onDelete?: 'cascade' | 'set-null' | 'restrict';
|
|
143
|
+
}
|
|
144
|
+
interface MediaField extends BaseFieldConfig {
|
|
145
|
+
type: 'media';
|
|
146
|
+
accept?: string[];
|
|
147
|
+
maxSize?: number;
|
|
148
|
+
}
|
|
149
|
+
interface RichTextField extends BaseFieldConfig {
|
|
150
|
+
type: 'richtext';
|
|
151
|
+
blocks?: string[];
|
|
152
|
+
}
|
|
153
|
+
interface SlugField extends BaseFieldConfig {
|
|
154
|
+
type: 'slug';
|
|
155
|
+
from: string;
|
|
156
|
+
unique?: boolean;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Minimal block definition reference — used by BlocksField to type-check allowed blocks.
|
|
160
|
+
* The full BlockDefinition (with label, etc.) lives in @murumets-ee/content.
|
|
161
|
+
*/
|
|
162
|
+
interface BlockDefinitionRef {
|
|
163
|
+
slug: string;
|
|
164
|
+
fields: Record<string, FieldConfig>;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Blocks field — ordered array of typed content blocks.
|
|
168
|
+
* Each block instance stores its data in {entity}_layout table.
|
|
169
|
+
*
|
|
170
|
+
* @property blocks - Allowed block definitions
|
|
171
|
+
* @property min/max - Block count constraints
|
|
172
|
+
* @property localized - true = per-locale layouts, false = shared layout with translated content (default)
|
|
173
|
+
*/
|
|
174
|
+
interface JsonField extends BaseFieldConfig {
|
|
175
|
+
type: 'json';
|
|
176
|
+
}
|
|
177
|
+
interface BlocksField extends BaseFieldConfig {
|
|
178
|
+
type: 'blocks';
|
|
179
|
+
blocks: readonly BlockDefinitionRef[];
|
|
180
|
+
min?: number;
|
|
181
|
+
max?: number;
|
|
182
|
+
localized?: boolean;
|
|
183
|
+
}
|
|
184
|
+
type FieldConfig = IdField | TextField | NumberField | BooleanField | DateField | SelectField | ReferenceField | MediaField | RichTextField | SlugField | JsonField | BlocksField;
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Behavior system
|
|
188
|
+
* Behaviors add common functionality to entities (fields + hooks)
|
|
189
|
+
*
|
|
190
|
+
* @typeParam F - The field map this behavior contributes. Defaults to
|
|
191
|
+
* Record<string, FieldConfig> for backward compatibility.
|
|
192
|
+
*/
|
|
193
|
+
|
|
194
|
+
interface Behavior<F extends Record<string, FieldConfig> = Record<string, FieldConfig>> {
|
|
195
|
+
name: string;
|
|
196
|
+
fields?: F;
|
|
197
|
+
hooks?: {
|
|
198
|
+
beforeCreate?: (data: Record<string, unknown>) => Promise<Record<string, unknown>>;
|
|
199
|
+
afterCreate?: (entity: Record<string, unknown>) => Promise<void>;
|
|
200
|
+
beforeUpdate?: (id: string, data: Record<string, unknown>) => Promise<Record<string, unknown>>;
|
|
201
|
+
afterUpdate?: (entity: Record<string, unknown>) => Promise<void>;
|
|
202
|
+
beforeDelete?: (id: string) => Promise<void>;
|
|
203
|
+
afterDelete?: (id: string) => Promise<void>;
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Entity definition API
|
|
209
|
+
* The core function for defining entities with full type inference.
|
|
210
|
+
*
|
|
211
|
+
* The generic parameters are inferred from the call site:
|
|
212
|
+
* - F is inferred from `definition.fields`
|
|
213
|
+
* - B is inferred from `definition.behaviors` (as a tuple)
|
|
214
|
+
*
|
|
215
|
+
* The returned Entity carries the complete field map:
|
|
216
|
+
* { id: IdField } & BehaviorFields & UserFields
|
|
217
|
+
*/
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* A fully resolved entity with merged behavior fields.
|
|
221
|
+
* @typeParam AllFields - The complete field map (id + behaviors + user fields).
|
|
222
|
+
*/
|
|
223
|
+
interface Entity<AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>> {
|
|
224
|
+
name: string;
|
|
225
|
+
kind?: 'collection' | 'singleton';
|
|
226
|
+
fields: Record<string, FieldConfig>;
|
|
227
|
+
behaviors?: Behavior[];
|
|
228
|
+
scope?: 'global' | 'team' | 'user';
|
|
229
|
+
access?: {
|
|
230
|
+
view?: string;
|
|
231
|
+
create?: string;
|
|
232
|
+
update?: string;
|
|
233
|
+
delete?: string;
|
|
234
|
+
};
|
|
235
|
+
/** Admin UI configuration — controls sidebar, list, and form display */
|
|
236
|
+
admin?: EntityAdminConfig;
|
|
237
|
+
allFields: AllFields;
|
|
238
|
+
hooks: Behavior['hooks'];
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Type inference utilities for the entity system.
|
|
243
|
+
* Maps field configurations to TypeScript types at compile time.
|
|
244
|
+
*
|
|
245
|
+
* Design principles:
|
|
246
|
+
* - Keep type nesting shallow (no recursive types beyond bounded tuple walking)
|
|
247
|
+
* - Use intermediate aliases to aid TS performance
|
|
248
|
+
* - All types are pure — zero runtime footprint
|
|
249
|
+
*
|
|
250
|
+
* Usage:
|
|
251
|
+
* const Article = defineEntity({ ... })
|
|
252
|
+
* type ArticleDTO = InferEntity<typeof Article>
|
|
253
|
+
*/
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Maps a single FieldConfig to its TypeScript output type.
|
|
257
|
+
* Each branch is a shallow comparison — no recursion.
|
|
258
|
+
*/
|
|
259
|
+
type FieldToTS<F extends FieldConfig> = F extends IdField ? string : F extends TextField ? string : F extends NumberField ? number : F extends BooleanField ? boolean : F extends DateField ? Date | string : F extends SelectField ? F['options'][number] : F extends ReferenceField ? F['cardinality'] extends 'many' ? string[] : string : F extends MediaField ? string : F extends RichTextField ? Record<string, unknown>[] : F extends SlugField ? string : F extends JsonField ? Record<string, unknown> : F extends BlocksField ? Array<{
|
|
260
|
+
_block: string;
|
|
261
|
+
_id: string;
|
|
262
|
+
[key: string]: unknown;
|
|
263
|
+
}> : never;
|
|
264
|
+
/**
|
|
265
|
+
* Extract keys of fields where `required` is literally `true`.
|
|
266
|
+
* Fields without `required` or with `required?: false` are optional.
|
|
267
|
+
*/
|
|
268
|
+
type RequiredFieldKeys<Fields extends Record<string, FieldConfig>> = {
|
|
269
|
+
[K in keyof Fields]: Fields[K]['required'] extends true ? K : never;
|
|
270
|
+
}[keyof Fields];
|
|
271
|
+
type OptionalFieldKeys<Fields extends Record<string, FieldConfig>> = {
|
|
272
|
+
[K in keyof Fields]: Fields[K]['required'] extends true ? never : K;
|
|
273
|
+
}[keyof Fields];
|
|
274
|
+
/**
|
|
275
|
+
* Maps a full field record to its TypeScript output type.
|
|
276
|
+
* Required fields are non-nullable; optional fields are `T | null | undefined`.
|
|
277
|
+
*
|
|
278
|
+
* The `id` field is always `string` and always present.
|
|
279
|
+
* The `id` key from Fields is excluded to avoid duplication since
|
|
280
|
+
* we hardcode `{ id: string }` at the front.
|
|
281
|
+
*/
|
|
282
|
+
type InferEntityDTO<Fields extends Record<string, FieldConfig>> = {
|
|
283
|
+
id: string;
|
|
284
|
+
} & {
|
|
285
|
+
[K in Exclude<RequiredFieldKeys<Fields>, 'id'>]: FieldToTS<Fields[K]>;
|
|
286
|
+
} & {
|
|
287
|
+
[K in OptionalFieldKeys<Fields>]?: FieldToTS<Fields[K]> | null;
|
|
288
|
+
};
|
|
289
|
+
/** Fields that are auto-generated and should not appear in create input. */
|
|
290
|
+
type AutoGeneratedFields = 'id' | 'createdAt' | 'updatedAt' | 'createdBy' | 'updatedBy' | '_version';
|
|
291
|
+
/**
|
|
292
|
+
* The input type for creating an entity.
|
|
293
|
+
* - Omits auto-generated fields (id, timestamps, version)
|
|
294
|
+
* - Required fields stay required; optional fields stay optional
|
|
295
|
+
*/
|
|
296
|
+
type InferCreateInput<Fields extends Record<string, FieldConfig>> = Omit<{
|
|
297
|
+
[K in Exclude<RequiredFieldKeys<Fields>, 'id'>]: FieldToTS<Fields[K]>;
|
|
298
|
+
} & {
|
|
299
|
+
[K in OptionalFieldKeys<Fields>]?: FieldToTS<Fields[K]> | null;
|
|
300
|
+
}, AutoGeneratedFields>;
|
|
301
|
+
/** Fields that cannot be changed after creation. */
|
|
302
|
+
type ImmutableFields = 'id' | 'createdAt' | 'createdBy';
|
|
303
|
+
type InferUpdateInput<Fields extends Record<string, FieldConfig>> = Partial<Omit<InferEntityDTO<Fields>, ImmutableFields>>;
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Minimal logger interface compatible with Pino.
|
|
307
|
+
*
|
|
308
|
+
* Defined locally to avoid a circular build dependency:
|
|
309
|
+
* entity → logging → core → entity.
|
|
310
|
+
*
|
|
311
|
+
* Any Pino logger instance satisfies this interface via structural typing.
|
|
312
|
+
*/
|
|
313
|
+
interface Logger {
|
|
314
|
+
info(obj: Record<string, unknown>, msg: string): void;
|
|
315
|
+
debug?(obj: Record<string, unknown>, msg: string): void;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* AdminClient - Full CRUD with server-only enforcement
|
|
320
|
+
* CRITICAL: This file MUST NOT be imported in client code
|
|
321
|
+
*/
|
|
322
|
+
|
|
323
|
+
interface AdminClientConfig<AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>> {
|
|
324
|
+
entity: Entity<AllFields>;
|
|
325
|
+
db: PostgresJsDatabase;
|
|
326
|
+
logger?: Logger;
|
|
327
|
+
/** Optional count cache for COUNT(*) query optimization. */
|
|
328
|
+
countCache?: CountCacheLike;
|
|
329
|
+
}
|
|
330
|
+
interface FindManyOptions {
|
|
331
|
+
where?: SQL | undefined;
|
|
332
|
+
limit?: number;
|
|
333
|
+
offset?: number;
|
|
334
|
+
orderBy?: SQL | SQL[];
|
|
335
|
+
locale?: string;
|
|
336
|
+
/** Default content locale. For localized blocks, NULL rows (from initial create)
|
|
337
|
+
* are only returned as fallback when locale matches defaultLocale. */
|
|
338
|
+
defaultLocale?: string;
|
|
339
|
+
/**
|
|
340
|
+
* Cursor-based (keyset) pagination. When provided, replaces OFFSET with a
|
|
341
|
+
* WHERE condition for O(1) page access at any depth. The `offset` option
|
|
342
|
+
* is ignored when `cursor` is set.
|
|
343
|
+
*
|
|
344
|
+
* The cursor `field` must be a real column on the entity table.
|
|
345
|
+
*/
|
|
346
|
+
cursor?: CursorInput;
|
|
347
|
+
}
|
|
348
|
+
interface CountOptions {
|
|
349
|
+
where?: SQL | undefined;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* AdminClient - Full CRUD operations with security enforcement
|
|
353
|
+
*
|
|
354
|
+
* Security layers:
|
|
355
|
+
* 1. Runtime check: typeof window !== 'undefined' → throw (allows CLI scripts)
|
|
356
|
+
* 2. Uses read-write DB connection
|
|
357
|
+
* 3. Validation with Zod before every write
|
|
358
|
+
* 4. Hook execution (beforeCreate, afterCreate, etc.)
|
|
359
|
+
*
|
|
360
|
+
* Note: We don't use 'server-only' import because it blocks CLI scripts.
|
|
361
|
+
* Next.js bundler protection comes from subpath exports (@murumets-ee/core/clients).
|
|
362
|
+
*
|
|
363
|
+
* Phase 1: Core CRUD + hooks + validation
|
|
364
|
+
* Phase 2 (TODO): Access control, request context, scoping
|
|
365
|
+
*
|
|
366
|
+
* @typeParam AllFields - The entity's complete field map. Inferred automatically
|
|
367
|
+
* when constructing via `createAdminClient(entity)`.
|
|
368
|
+
*/
|
|
369
|
+
declare class AdminClient<AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>> {
|
|
370
|
+
private entity;
|
|
371
|
+
private db;
|
|
372
|
+
private logger?;
|
|
373
|
+
private createSchema;
|
|
374
|
+
private updateSchema;
|
|
375
|
+
private table;
|
|
376
|
+
private countCache?;
|
|
377
|
+
constructor(config: AdminClientConfig<AllFields>);
|
|
378
|
+
/**
|
|
379
|
+
* Create a new entity
|
|
380
|
+
*
|
|
381
|
+
* Flow:
|
|
382
|
+
* 1. Validate input with Zod
|
|
383
|
+
* 2. Execute beforeCreate hooks
|
|
384
|
+
* 3. Prepare data for insert
|
|
385
|
+
* 4. Insert into database
|
|
386
|
+
* 5. Execute afterCreate hooks
|
|
387
|
+
* 6. Shape DTO and return
|
|
388
|
+
*/
|
|
389
|
+
create(data: InferCreateInput<AllFields>): Promise<InferEntityDTO<AllFields>>;
|
|
390
|
+
/**
|
|
391
|
+
* Find entity by ID
|
|
392
|
+
*/
|
|
393
|
+
findById(id: string, options?: {
|
|
394
|
+
locale?: string;
|
|
395
|
+
defaultLocale?: string;
|
|
396
|
+
}): Promise<InferEntityDTO<AllFields> | null>;
|
|
397
|
+
/**
|
|
398
|
+
* Find multiple entities
|
|
399
|
+
*/
|
|
400
|
+
findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]>;
|
|
401
|
+
/**
|
|
402
|
+
* Count entities matching optional conditions
|
|
403
|
+
*/
|
|
404
|
+
count(options?: CountOptions): Promise<number>;
|
|
405
|
+
/**
|
|
406
|
+
* Update entity by ID
|
|
407
|
+
*
|
|
408
|
+
* Flow:
|
|
409
|
+
* 1. Validate input with Zod
|
|
410
|
+
* 2. Execute beforeUpdate hooks
|
|
411
|
+
* 3. Prepare data for update
|
|
412
|
+
* 4. Update in database
|
|
413
|
+
* 5. Execute afterUpdate hooks
|
|
414
|
+
* 6. Shape DTO and return
|
|
415
|
+
*/
|
|
416
|
+
update(id: string, data: InferUpdateInput<AllFields>, options?: {
|
|
417
|
+
locale?: string;
|
|
418
|
+
}): Promise<InferEntityDTO<AllFields>>;
|
|
419
|
+
/**
|
|
420
|
+
* Delete entity by ID.
|
|
421
|
+
*
|
|
422
|
+
* Checks entity_refs for incoming references first — throws
|
|
423
|
+
* ReferencedEntityError if this entity is still used somewhere.
|
|
424
|
+
*/
|
|
425
|
+
delete(id: string): Promise<void>;
|
|
426
|
+
/**
|
|
427
|
+
* Prepare data for insert — every field is a real column.
|
|
428
|
+
*/
|
|
429
|
+
private prepareDataForInsert;
|
|
430
|
+
/**
|
|
431
|
+
* Prepare data for update — every field is a real column.
|
|
432
|
+
* Standard column SET, no JSONB merge needed.
|
|
433
|
+
*/
|
|
434
|
+
private prepareDataForUpdate;
|
|
435
|
+
/**
|
|
436
|
+
* Merge translations into entities for the specified locale.
|
|
437
|
+
* Reads translatable field values from real columns on the translation row.
|
|
438
|
+
*/
|
|
439
|
+
private mergeTranslations;
|
|
440
|
+
/**
|
|
441
|
+
* Save translation for an entity.
|
|
442
|
+
* Each translatable field is a real column on the translation table.
|
|
443
|
+
*/
|
|
444
|
+
saveTranslation(entityId: string, locale: string, translations: Record<string, unknown>): Promise<void>;
|
|
445
|
+
/**
|
|
446
|
+
* PHASE 3: Delete translation(s) for an entity
|
|
447
|
+
* If locale is provided, deletes specific locale; otherwise deletes all translations
|
|
448
|
+
*/
|
|
449
|
+
deleteTranslation(entityId: string, locale?: string): Promise<void>;
|
|
450
|
+
/**
|
|
451
|
+
* Save block-level translations for an entity.
|
|
452
|
+
* For each block in each blocks field, extracts translatable field values
|
|
453
|
+
* and upserts them into {entity}_layout_translations.
|
|
454
|
+
*
|
|
455
|
+
* Block _id must match an existing layout row ID.
|
|
456
|
+
*/
|
|
457
|
+
saveBlockTranslations(entityId: string, locale: string, data: Record<string, unknown>): Promise<void>;
|
|
458
|
+
/**
|
|
459
|
+
* Save per-locale blocks for an entity.
|
|
460
|
+
* Used for entities with `localized: true` on their blocks field — each locale gets
|
|
461
|
+
* its own independent block layout rows in the layout table.
|
|
462
|
+
*/
|
|
463
|
+
saveLocalizedBlocks(entityId: string, locale: string, data: Record<string, unknown>): Promise<void>;
|
|
464
|
+
/**
|
|
465
|
+
* Get all blocks field names for this entity.
|
|
466
|
+
*/
|
|
467
|
+
private getBlocksFields;
|
|
468
|
+
/**
|
|
469
|
+
* Save blocks for an entity after create/update.
|
|
470
|
+
* For each blocks field, writes rows to {entity}_layout table.
|
|
471
|
+
*/
|
|
472
|
+
private saveBlocks;
|
|
473
|
+
/**
|
|
474
|
+
* Load blocks for one or more entities from the layout table.
|
|
475
|
+
*
|
|
476
|
+
* Handles both block translation modes:
|
|
477
|
+
* - Shared layout (localized: false): loads locale=NULL rows, merges translations,
|
|
478
|
+
* clears untranslated translatable fields to '' (strict mode for admin editing)
|
|
479
|
+
* - Per-locale layout (localized: true): loads rows matching the provided locale only
|
|
480
|
+
*
|
|
481
|
+
* @param entityIds - Entity IDs to load blocks for
|
|
482
|
+
* @param locale - Content locale (omit for default locale / base data)
|
|
483
|
+
* @param options.defaultLocale - Default locale; NULL rows fall back only for this locale
|
|
484
|
+
*/
|
|
485
|
+
private loadBlocks;
|
|
486
|
+
/**
|
|
487
|
+
* Attach loaded blocks to shaped DTOs.
|
|
488
|
+
*/
|
|
489
|
+
private attachBlocks;
|
|
490
|
+
/**
|
|
491
|
+
* Sync outgoing references in entity_refs after create/update.
|
|
492
|
+
*
|
|
493
|
+
* - 'create': inserts all refs (entity is new, no existing refs)
|
|
494
|
+
* - 'update': deletes refs for changed ref-bearing fields, then inserts new ones
|
|
495
|
+
*
|
|
496
|
+
* Gracefully skips if entity_refs table is not registered (e.g. before migration).
|
|
497
|
+
*/
|
|
498
|
+
private syncRefs;
|
|
499
|
+
/**
|
|
500
|
+
* Build a cache key for a count query.
|
|
501
|
+
* Key format: `entityName` for unfiltered, `entityName:where_sql` for filtered.
|
|
502
|
+
*/
|
|
503
|
+
private buildCountCacheKey;
|
|
504
|
+
/**
|
|
505
|
+
* Invalidate all count cache entries for this entity.
|
|
506
|
+
*/
|
|
507
|
+
private invalidateCountCache;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
export { AdminClient, type AdminClientConfig, type CountCacheLike, type CountOptions, type FindManyOptions };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{schemaRegistry as R}from"@murumets-ee/db";import{and as C,eq as m,inArray as E,isNull as D,or as Y,sql as ee}from"drizzle-orm";import{and as Q,gt as q,lt as J,or as W,eq as K}from"drizzle-orm";function B(o,e){let t=o[e.field];if(!t)return null;let i=e.direction==="desc"?J:q,n=i(t,e.value);if(!e.id)return n;let r=o.id;if(!r)return n;let c=i(r,e.id);return W(n,Q(K(t,e.value),c))}function v(o,e,t){if(!e)return null;let s={},i=t?.select||Object.keys(o.allFields);for(let n of i){if(!t?.includeInternal&&n.startsWith("_"))continue;let r=o.allFields[n];r&&r.type!=="blocks"&&(s[n]=e[n])}return s}function _(o,e,t){return e.map(s=>v(o,s,t))}var A=class extends Error{entityName;entityId;usages;constructor(e,t,s){let i=s.length;super(`Cannot delete ${e} '${t}': referenced by ${i} other entit${i===1?"y":"ies"}`),this.name="ReferencedEntityError",this.entityName=e,this.entityId=t,this.usages=s}};var V=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function N(o,e){let t=[],s=new Set;function i(n,r,c){if(!V.test(c))return;let a=`${n}|${r}|${c}`;s.has(a)||(s.add(a),t.push({sourceField:n,targetEntity:r,targetId:c}))}for(let[n,r]of Object.entries(o)){let c=e[n];if(c!=null)switch(r.type){case"media":{typeof c=="string"&&i(n,"media",c);break}case"reference":{let a=r;if(a.cardinality==="many"&&Array.isArray(c))for(let l of c)typeof l=="string"&&i(n,a.entity,l);else typeof c=="string"&&i(n,a.entity,c);break}case"blocks":{let a=r;if(!Array.isArray(c))break;for(let l of c){let g=l,p=g._block;if(!p)continue;let d=a.blocks.find(f=>f.slug===p);if(d)for(let[f,y]of Object.entries(d.fields)){let u=g[f];if(u!=null&&(y.type==="media"&&typeof u=="string"&&i(n,"media",u),y.type==="reference")){let w=y;if(w.cardinality==="many"&&Array.isArray(u))for(let b of u)typeof b=="string"&&i(n,w.entity,b);else typeof u=="string"&&i(n,w.entity,u)}}}break}}}return t}import{and as X,eq as $}from"drizzle-orm";import{index as z,pgTable as G,unique as H,uuid as S,varchar as O}from"drizzle-orm/pg-core";var k=G("entity_refs",{sourceEntity:O("source_entity",{length:100}).notNull(),sourceId:S("source_id").notNull(),sourceField:O("source_field",{length:100}).notNull(),targetEntity:O("target_entity",{length:100}).notNull(),targetId:S("target_id").notNull()},o=>[H("uq_entity_refs").on(o.sourceEntity,o.sourceId,o.sourceField,o.targetEntity,o.targetId),z("idx_entity_refs_target").on(o.targetEntity,o.targetId),z("idx_entity_refs_source").on(o.sourceEntity,o.sourceId)]);async function L(o,e,t){return await t.select({sourceEntity:k.sourceEntity,sourceId:k.sourceId,sourceField:k.sourceField}).from(k).where(X($(k.targetEntity,o),$(k.targetId,e)))}import{z as h}from"zod";function U(o){let e;switch(o.type){case"id":e=h.string().uuid();break;case"text":e=h.string(),o.maxLength&&(e=e.max(o.maxLength)),o.minLength&&(e=e.min(o.minLength)),o.pattern&&(e=e.regex(o.pattern));break;case"number":e=h.number(),o.integer&&(e=e.int()),o.min!==void 0&&(e=e.min(o.min)),o.max!==void 0&&(e=e.max(o.max));break;case"boolean":e=h.boolean();break;case"date":e=h.date().or(h.string().datetime());break;case"select":e=h.enum(o.options);break;case"reference":o.cardinality==="many"?e=h.array(h.string().uuid()):e=h.string().uuid();break;case"media":e=h.string().uuid();break;case"richtext":e=h.union([h.string(),h.array(h.record(h.unknown()))]);break;case"slug":e=h.string().regex(/^[a-z0-9-]+$/);break;case"json":e=h.record(h.unknown());break;case"blocks":e=h.array(h.object({_block:h.string()}).passthrough());break;default:e=h.unknown()}return o.required||(e=e.nullable().optional()),o.default!==void 0&&(e=e.default(o.default)),e}function P(o){let e={},t=new Set(["id","createdAt","updatedAt","createdBy","_version"]);for(let[s,i]of Object.entries(o.allFields))t.has(s)||(e[s]=U(i));return h.object(e)}function M(o){let e={},t=new Set(["id","createdAt","createdBy","updatedAt","updatedBy","_version"]);for(let[s,i]of Object.entries(o.allFields))if(!t.has(s)){let n=U(i);e[s]=n.optional()}return h.object(e)}var x=class{entity;db;logger;createSchema;updateSchema;table;countCache;constructor(e){if(typeof window<"u")throw new Error("AdminClient cannot be used in browser code. Use QueryClient for frontend data access.");this.entity=e.entity,this.db=e.db,this.logger=e.logger,this.countCache=e.countCache,this.createSchema=P(e.entity),this.updateSchema=M(e.entity);let t=R.get(e.entity.name);if(!t)throw new Error(`Schema for entity '${e.entity.name}' not found in registry. Ensure schemas are generated and registered before creating AdminClient.`);this.table=t}async create(e){this.logger?.info({entity:this.entity.name},"Creating entity");let t=e;if(this.entity.hooks?.beforeCreate){let r=await this.entity.hooks.beforeCreate(t);t=r!==void 0?r:t}t=this.createSchema.parse(t);let s=this.prepareDataForInsert(t),[i]=await this.db.insert(this.table).values(s).returning();await this.saveBlocks(i.id,t),await this.syncRefs(i.id,t,"create"),this.entity.hooks?.afterCreate&&await this.entity.hooks.afterCreate(i),this.invalidateCountCache();let n=v(this.entity,i);if(n&&this.getBlocksFields().length>0){let r=await this.loadBlocks([n.id]);this.attachBlocks([n],r)}return n}async findById(e,t){this.logger?.info({entity:this.entity.name,id:e},"Finding entity by ID");let[s]=await this.db.select().from(this.table).where(m(this.table.id,e));if(!s)return null;let i=v(this.entity,s);if(!i)return null;if(this.getBlocksFields().length>0){let n=await this.loadBlocks([i.id],t?.locale,{defaultLocale:t?.defaultLocale});this.attachBlocks([i],n)}if(t?.locale){let[n]=await this.mergeTranslations([i],t.locale);return n}return i}async findMany(e){this.logger?.info({entity:this.entity.name,options:e},"Finding entities");let t=this.db.select().from(this.table).$dynamic(),s=[];if(e?.where&&s.push(e.where),e?.cursor){let r=this.entity.allFields;if(!(e.cursor.field in r)&&e.cursor.field!=="id")throw new Error(`Invalid cursor field: '${e.cursor.field}' is not a field on '${this.entity.name}'`);let c=B(this.table,e.cursor);c&&s.push(c)}if(s.length>0&&(t=t.where(C(...s))),e?.limit&&(t=t.limit(e.limit)),e?.offset&&!e?.cursor&&(t=t.offset(e.offset)),e?.orderBy){let r=Array.isArray(e.orderBy)?e.orderBy:[e.orderBy];t=t.orderBy(...r)}let i=await t,n=_(this.entity,i).filter(r=>r!==null);if(this.getBlocksFields().length>0&&n.length>0){let r=n.map(a=>a.id),c=await this.loadBlocks(r,e?.locale,{defaultLocale:e?.defaultLocale});this.attachBlocks(n,c)}return e?.locale?await this.mergeTranslations(n,e.locale):n}async count(e){this.logger?.info({entity:this.entity.name,options:e},"Counting entities");let t=this.buildCountCacheKey(e?.where);if(this.countCache){let r=this.countCache.get(t);if(r!==void 0)return this.logger?.debug?.({entity:this.entity.name,cached:r},"Count cache hit"),r}let s=this.db.select({count:ee`count(*)`}).from(this.table).$dynamic();e?.where&&(s=s.where(e.where));let[i]=await s,n=Number(i.count);return this.countCache&&this.countCache.set(t,n),n}async update(e,t,s){this.logger?.info({entity:this.entity.name,id:e},"Updating entity");let i=t;if(this.entity.hooks?.beforeUpdate){let a=await this.entity.hooks.beforeUpdate(e,i);i=a!==void 0?a:i}i=this.updateSchema.parse(i);let n=this.prepareDataForUpdate(i),r;if(Object.keys(n).length>0){let[a]=await this.db.update(this.table).set(n).where(m(this.table.id,e)).returning();r=a}else{let[a]=await this.db.select().from(this.table).where(m(this.table.id,e));r=a}await this.saveBlocks(e,i,s),await this.syncRefs(e,i,"update"),this.entity.hooks?.afterUpdate&&await this.entity.hooks.afterUpdate(r);let c=v(this.entity,r);if(c&&this.getBlocksFields().length>0){let a=await this.loadBlocks([e]);this.attachBlocks([c],a)}return c}async delete(e){this.logger?.info({entity:this.entity.name,id:e},"Deleting entity");let t=await L(this.entity.name,e,this.db);if(t.length>0)throw new A(this.entity.name,e,t);this.entity.hooks?.beforeDelete&&await this.entity.hooks.beforeDelete(e),await this.db.delete(this.table).where(m(this.table.id,e)),await this.db.delete(k).where(C(m(k.sourceEntity,this.entity.name),m(k.sourceId,e))),this.entity.hooks?.afterDelete&&await this.entity.hooks.afterDelete(e),this.invalidateCountCache()}prepareDataForInsert(e){let t={};for(let[s,i]of Object.entries(e)){let n=this.entity.allFields[s];n&&s!=="id"&&n.type!=="blocks"&&(t[s]=i)}return t}prepareDataForUpdate(e){let t={};for(let[s,i]of Object.entries(e)){let n=this.entity.allFields[s];n&&s!=="id"&&n.type!=="blocks"&&(t[s]=i)}return t}async mergeTranslations(e,t){if(!e.length)return e;let s=`${this.entity.name}_translations`,i=R.get(s);if(!i)return e;let n=e.map(l=>l.id),r=await this.db.select().from(i).where(C(E(i.entityId,n),m(i.locale,t))),c=Object.entries(this.entity.allFields).filter(([l,g])=>g.translatable).map(([l])=>l),a=new Map;for(let l of r){let g={};for(let p of c){let d=l[p];d!=null&&(g[p]=d)}a.set(l.entityId,g)}return e.map(l=>{let g=a.get(l.id);return g?{...l,...g}:l})}async saveTranslation(e,t,s){this.logger?.info({entity:this.entity.name,entityId:e,locale:t},"Saving translation");let i=`${this.entity.name}_translations`,n=R.get(i);if(!n)throw new Error(`Translation table ${i} not found in schema registry`);let r=Object.entries(this.entity.allFields).filter(([l,g])=>g.translatable).map(([l])=>l);if(r.length===0)throw new Error(`Entity ${this.entity.name} has no translatable fields`);let c={entityId:e,locale:t},a={};for(let l of r)s[l]!==void 0&&(c[l]=s[l],a[l]=s[l]);await this.db.insert(n).values(c).onConflictDoUpdate({target:[n.entityId,n.locale],set:a}),this.logger?.info({entity:this.entity.name,entityId:e,locale:t},"Translation saved")}async deleteTranslation(e,t){this.logger?.info({entity:this.entity.name,entityId:e,locale:t},"Deleting translation");let s=`${this.entity.name}_translations`,i=R.get(s);if(!i)throw new Error(`Translation table ${s} not found in schema registry`);t?(await this.db.delete(i).where(C(m(i.entityId,e),m(i.locale,t))),this.logger?.info({entity:this.entity.name,entityId:e,locale:t},"Translation deleted")):(await this.db.delete(i).where(m(i.entityId,e)),this.logger?.info({entity:this.entity.name,entityId:e},"All translations deleted"))}async saveBlockTranslations(e,t,s){this.logger?.info({entity:this.entity.name,entityId:e,locale:t},"Saving block translations");let i=this.getBlocksFields();if(i.length===0)return;let n=R.get(`${this.entity.name}_layout_translations`);if(!n)return;let r=R.get(`${this.entity.name}_layout`);if(r){for(let{name:c,config:a}of i){let l=s[c];if(!Array.isArray(l))continue;let g=a.blocks;if(!g)continue;let p=await this.db.select({id:r.id,blockType:r.blockType}).from(r).where(C(m(r.entityId,e),m(r.fieldName,c),D(r.locale))).orderBy(r.sortOrder);for(let d=0;d<l.length;d++){let f=l[d],y=f._block;if(!y)continue;let u=p[d];if(!u||u.blockType!==y)continue;let w=g.find(F=>F.slug===y);if(!w)continue;let b={};for(let[F,T]of Object.entries(w.fields))T.translatable&&f[F]!==void 0&&(b[F]=f[F]);Object.keys(b).length!==0&&await this.db.insert(n).values({layoutId:u.id,locale:t,fields:b}).onConflictDoUpdate({target:[n.layoutId,n.locale],set:{fields:b}})}}this.logger?.info({entity:this.entity.name,entityId:e,locale:t},"Block translations saved")}}async saveLocalizedBlocks(e,t,s){this.logger?.info({entity:this.entity.name,entityId:e,locale:t},"Saving localized blocks"),await this.saveBlocks(e,s,{locale:t})}getBlocksFields(){return Object.entries(this.entity.allFields).filter(([e,t])=>t.type==="blocks").map(([e,t])=>({name:e,config:t}))}async saveBlocks(e,t,s){let i=this.getBlocksFields();if(i.length===0)return;let n=R.get(`${this.entity.name}_layout`);if(n)for(let{name:r,config:c}of i){let a=t[r];if(!Array.isArray(a))continue;let l="localized"in c&&c.localized===!0,g=l?s?.locale??null:null,p=[m(n.entityId,e),m(n.fieldName,r)];g?p.push(m(n.locale,g)):l||p.push(D(n.locale)),await this.db.delete(n).where(C(...p));for(let d=0;d<a.length;d++){let f=a[d],y=f._block;if(!y)continue;let{_block:u,_id:w,...b}=f;await this.db.insert(n).values({entityId:e,fieldName:r,blockType:y,sortOrder:d,data:b,locale:g})}}}async loadBlocks(e,t,s){let i=this.getBlocksFields();if(i.length===0||e.length===0)return new Map;let n=R.get(`${this.entity.name}_layout`);if(!n)return new Map;let r=i.filter(({config:l})=>!("localized"in l&&l.localized)),c=i.filter(({config:l})=>"localized"in l&&l.localized),a=new Map;if(r.length>0){let l=await this.db.select().from(n).where(C(E(n.entityId,e),D(n.locale))).orderBy(n.sortOrder),g;if(t&&l.length>0){let d=R.get(`${this.entity.name}_layout_translations`);if(d){let f=l.map(u=>u.id),y=await this.db.select().from(d).where(C(E(d.layoutId,f),m(d.locale,t)));g=new Map;for(let u of y)g.set(u.layoutId,u.fields??{})}}let p=new Map;for(let{config:d}of r){let f=d.blocks;if(f)for(let y of f)p.set(y.slug,y.fields)}for(let d of l){let f=d.entityId,y=d.fieldName;a.has(f)||a.set(f,{});let u=a.get(f);u[y]||(u[y]=[]);let w=d.data??{},b=g?.get(d.id),F={_block:d.blockType,_id:d.id,...w,...b??{}};if(t){let T=d.blockType,I=p.get(T);if(I)for(let[j,Z]of Object.entries(I))Z.translatable&&!b?.[j]&&(F[j]="")}u[y].push(F)}}if(c.length>0){let l=!t||t===s?.defaultLocale,g=t?l?Y(m(n.locale,t),D(n.locale)):m(n.locale,t):D(n.locale),p=await this.db.select().from(n).where(C(E(n.entityId,e),g)).orderBy(n.sortOrder),d=new Map;for(let f of p){let y=`${f.entityId}::${f.fieldName}`;d.has(y)||d.set(y,{localeRows:[],nullRows:[]});let u=d.get(y);f.locale?u.localeRows.push(f):u.nullRows.push(f)}for(let[,{localeRows:f,nullRows:y}]of d){let u=f.length>0?f:y;for(let w of u){let b=w.entityId,F=w.fieldName;a.has(b)||a.set(b,{});let T=a.get(b);T[F]||(T[F]=[]);let I=w.data??{};T[F].push({_block:w.blockType,_id:w.id,...I})}}}return a}attachBlocks(e,t){let s=this.getBlocksFields();if(s.length!==0)for(let i of e){let n=i.id,r=t.get(n)??{};for(let{name:c}of s)i[c]=r[c]??[]}}async syncRefs(e,t,s){if(!R.has("entity_refs"))return;let i=this.entity.allFields;if(s==="update"){let r=Object.keys(t).filter(c=>{let a=i[c];return a&&(a.type==="media"||a.type==="reference"||a.type==="blocks")});r.length>0&&await this.db.delete(k).where(C(m(k.sourceEntity,this.entity.name),m(k.sourceId,e),E(k.sourceField,r)))}let n=N(i,t);n.length>0&&await this.db.insert(k).values(n.map(r=>({sourceEntity:this.entity.name,sourceId:e,sourceField:r.sourceField,targetEntity:r.targetEntity,targetId:r.targetId}))).onConflictDoNothing()}buildCountCacheKey(e){return e?`${this.entity.name}:${String(e)}`:this.entity.name}invalidateCountCache(){this.countCache?.invalidate(this.entity.name)}};export{x as AdminClient};
|