@murumets-ee/entity 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/index.d.mts +452 -0
- package/dist/admin/index.d.mts.map +1 -0
- package/dist/admin/index.mjs +2 -0
- package/dist/admin/index.mjs.map +1 -0
- package/dist/index.d.mts +903 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +65 -0
- package/dist/index.mjs.map +1 -0
- package/dist/query/index.d.mts +362 -0
- package/dist/query/index.d.mts.map +1 -0
- package/dist/query/index.mjs +7 -0
- package/dist/query/index.mjs.map +1 -0
- package/dist/refs/index.d.mts +249 -0
- package/dist/refs/index.d.mts.map +1 -0
- package/dist/refs/index.mjs +2 -0
- package/dist/refs/index.mjs.map +1 -0
- package/package.json +13 -13
- package/dist/admin/index.d.ts +0 -510
- package/dist/admin/index.js +0 -1
- package/dist/index.d.ts +0 -1027
- package/dist/index.js +0 -64
- package/dist/query/index.d.ts +0 -417
- package/dist/query/index.js +0 -6
- package/dist/refs/index.d.ts +0 -263
- package/dist/refs/index.js +0 -1
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { SQL } from "drizzle-orm";
|
|
2
|
+
import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
3
|
+
|
|
4
|
+
//#region src/count-cache.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* In-memory TTL cache for COUNT(*) query results.
|
|
7
|
+
*
|
|
8
|
+
* Reduces database load on paginated list pages where the total count
|
|
9
|
+
* is recalculated on every pagination/sort/search interaction. The cache
|
|
10
|
+
* is per-process (not shared across workers) with a short TTL (default 5s)
|
|
11
|
+
* so counts are at most a few seconds stale.
|
|
12
|
+
*
|
|
13
|
+
* Cache keys include the entity name + serialized WHERE clause, so filtered
|
|
14
|
+
* and unfiltered counts are cached independently.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Interface for count cache implementations.
|
|
18
|
+
* Used in client configs to avoid TypeScript private-field structural incompatibility
|
|
19
|
+
* across separate .d.ts files.
|
|
20
|
+
*/
|
|
21
|
+
interface CountCacheLike {
|
|
22
|
+
get(key: string): number | undefined;
|
|
23
|
+
set(key: string, count: number): void;
|
|
24
|
+
invalidate(prefix: string): void;
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/cursor.d.ts
|
|
28
|
+
/** Cursor input for keyset pagination. */
|
|
29
|
+
interface CursorInput {
|
|
30
|
+
/** Sort field name (e.g. 'createdAt'). Must be a real column on the entity. */
|
|
31
|
+
field: string;
|
|
32
|
+
/** Last seen value of the sort field. */
|
|
33
|
+
value: string | number;
|
|
34
|
+
/** Sort direction — must match the ORDER BY direction. */
|
|
35
|
+
direction: 'asc' | 'desc';
|
|
36
|
+
/** Tie-breaker: last seen entity ID. Required for non-unique sort fields. */
|
|
37
|
+
id?: string;
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/admin-config.d.ts
|
|
41
|
+
/**
|
|
42
|
+
* Optional admin UI configuration for entities.
|
|
43
|
+
* Controls how entities appear in the admin sidebar, list pages, and forms.
|
|
44
|
+
*/
|
|
45
|
+
interface EntityAdminConfig {
|
|
46
|
+
/** Sidebar section: 'content' | 'structure' | custom string. Default: 'content' */
|
|
47
|
+
group?: string;
|
|
48
|
+
/** Plural display name for sidebar + list pages. Default: title-cased pluralized entity name */
|
|
49
|
+
label?: string;
|
|
50
|
+
/** Singular label for "New X" button. Default: title-cased entity name */
|
|
51
|
+
labelSingular?: string;
|
|
52
|
+
/** Lucide icon name as string, e.g. 'file-text' */
|
|
53
|
+
icon?: string;
|
|
54
|
+
/** Description shown on list page */
|
|
55
|
+
description?: string;
|
|
56
|
+
/** Form layout. Default: 'single' */
|
|
57
|
+
layout?: 'single' | 'two-column';
|
|
58
|
+
/** Fields to hide in the form */
|
|
59
|
+
hiddenFields?: string[];
|
|
60
|
+
/** Columns to hide in the list */
|
|
61
|
+
hiddenColumns?: string[];
|
|
62
|
+
/** Per-field label/description/placeholder overrides */
|
|
63
|
+
fieldOverrides?: Record<string, {
|
|
64
|
+
label?: string;
|
|
65
|
+
description?: string;
|
|
66
|
+
placeholder?: string;
|
|
67
|
+
}>;
|
|
68
|
+
/** Default list sort field. Default: 'createdAt' */
|
|
69
|
+
defaultSort?: string;
|
|
70
|
+
/** Default list sort direction. Default: 'desc' */
|
|
71
|
+
defaultSortDirection?: 'asc' | 'desc';
|
|
72
|
+
/** List page size. Default: 20 */
|
|
73
|
+
pageSize?: number;
|
|
74
|
+
/** For block editor: fields to show in Puck root config */
|
|
75
|
+
rootFields?: string[];
|
|
76
|
+
/** Suppress "New" button in the list page */
|
|
77
|
+
disableCreate?: boolean;
|
|
78
|
+
/** Order within sidebar group. Default: 0 */
|
|
79
|
+
sortOrder?: number;
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
//#region src/fields/base.d.ts
|
|
83
|
+
/**
|
|
84
|
+
* Field type definitions
|
|
85
|
+
* These define the structure and configuration for all field types
|
|
86
|
+
*/
|
|
87
|
+
interface BaseFieldConfig {
|
|
88
|
+
required?: boolean;
|
|
89
|
+
default?: unknown;
|
|
90
|
+
translatable?: boolean;
|
|
91
|
+
indexed?: boolean;
|
|
92
|
+
unique?: boolean;
|
|
93
|
+
access?: {
|
|
94
|
+
view?: string;
|
|
95
|
+
edit?: string;
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
interface IdField extends BaseFieldConfig {
|
|
99
|
+
type: 'id';
|
|
100
|
+
}
|
|
101
|
+
interface TextField extends BaseFieldConfig {
|
|
102
|
+
type: 'text';
|
|
103
|
+
maxLength?: number;
|
|
104
|
+
minLength?: number;
|
|
105
|
+
pattern?: RegExp;
|
|
106
|
+
}
|
|
107
|
+
interface NumberField extends BaseFieldConfig {
|
|
108
|
+
type: 'number';
|
|
109
|
+
min?: number;
|
|
110
|
+
max?: number;
|
|
111
|
+
integer?: boolean;
|
|
112
|
+
}
|
|
113
|
+
interface BooleanField extends BaseFieldConfig {
|
|
114
|
+
type: 'boolean';
|
|
115
|
+
}
|
|
116
|
+
interface DateField extends BaseFieldConfig {
|
|
117
|
+
type: 'date';
|
|
118
|
+
minDate?: Date;
|
|
119
|
+
maxDate?: Date;
|
|
120
|
+
}
|
|
121
|
+
interface SelectField extends BaseFieldConfig {
|
|
122
|
+
type: 'select';
|
|
123
|
+
options: readonly string[];
|
|
124
|
+
}
|
|
125
|
+
interface ReferenceField extends BaseFieldConfig {
|
|
126
|
+
type: 'reference';
|
|
127
|
+
entity: string;
|
|
128
|
+
cardinality: 'one' | 'many';
|
|
129
|
+
onDelete?: 'cascade' | 'set-null' | 'restrict';
|
|
130
|
+
}
|
|
131
|
+
interface MediaField extends BaseFieldConfig {
|
|
132
|
+
type: 'media';
|
|
133
|
+
accept?: string[];
|
|
134
|
+
maxSize?: number;
|
|
135
|
+
}
|
|
136
|
+
interface RichTextField extends BaseFieldConfig {
|
|
137
|
+
type: 'richtext';
|
|
138
|
+
blocks?: string[];
|
|
139
|
+
}
|
|
140
|
+
interface SlugField extends BaseFieldConfig {
|
|
141
|
+
type: 'slug';
|
|
142
|
+
from: string;
|
|
143
|
+
unique?: boolean;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Minimal block definition reference — used by BlocksField to type-check allowed blocks.
|
|
147
|
+
* The full BlockDefinition (with label, etc.) lives in @murumets-ee/content.
|
|
148
|
+
*/
|
|
149
|
+
interface BlockDefinitionRef {
|
|
150
|
+
slug: string;
|
|
151
|
+
fields: Record<string, FieldConfig>;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Blocks field — ordered array of typed content blocks.
|
|
155
|
+
* Each block instance stores its data in {entity}_layout table.
|
|
156
|
+
*
|
|
157
|
+
* @property blocks - Allowed block definitions
|
|
158
|
+
* @property min/max - Block count constraints
|
|
159
|
+
* @property localized - true = per-locale layouts, false = shared layout with translated content (default)
|
|
160
|
+
*/
|
|
161
|
+
interface JsonField extends BaseFieldConfig {
|
|
162
|
+
type: 'json';
|
|
163
|
+
}
|
|
164
|
+
interface BlocksField extends BaseFieldConfig {
|
|
165
|
+
type: 'blocks';
|
|
166
|
+
blocks: readonly BlockDefinitionRef[];
|
|
167
|
+
min?: number;
|
|
168
|
+
max?: number;
|
|
169
|
+
localized?: boolean;
|
|
170
|
+
}
|
|
171
|
+
type FieldConfig = IdField | TextField | NumberField | BooleanField | DateField | SelectField | ReferenceField | MediaField | RichTextField | SlugField | JsonField | BlocksField;
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/behaviors/types.d.ts
|
|
174
|
+
interface Behavior<F extends Record<string, FieldConfig> = Record<string, FieldConfig>> {
|
|
175
|
+
name: string;
|
|
176
|
+
fields?: F;
|
|
177
|
+
hooks?: {
|
|
178
|
+
beforeCreate?: (data: Record<string, unknown>) => Promise<Record<string, unknown>>;
|
|
179
|
+
afterCreate?: (entity: Record<string, unknown>) => Promise<void>;
|
|
180
|
+
beforeUpdate?: (id: string, data: Record<string, unknown>) => Promise<Record<string, unknown>>;
|
|
181
|
+
afterUpdate?: (entity: Record<string, unknown>) => Promise<void>;
|
|
182
|
+
beforeDelete?: (id: string) => Promise<void>;
|
|
183
|
+
afterDelete?: (id: string) => Promise<void>;
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
//#endregion
|
|
187
|
+
//#region src/define-entity.d.ts
|
|
188
|
+
/**
|
|
189
|
+
* A fully resolved entity with merged behavior fields.
|
|
190
|
+
* @typeParam AllFields - The complete field map (id + behaviors + user fields).
|
|
191
|
+
*/
|
|
192
|
+
interface Entity<AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>> {
|
|
193
|
+
name: string;
|
|
194
|
+
kind?: 'collection' | 'singleton';
|
|
195
|
+
fields: Record<string, FieldConfig>;
|
|
196
|
+
behaviors?: Behavior[];
|
|
197
|
+
scope?: 'global' | 'team' | 'user';
|
|
198
|
+
access?: {
|
|
199
|
+
view?: string;
|
|
200
|
+
create?: string;
|
|
201
|
+
update?: string;
|
|
202
|
+
delete?: string;
|
|
203
|
+
};
|
|
204
|
+
/** Admin UI configuration — controls sidebar, list, and form display */
|
|
205
|
+
admin?: EntityAdminConfig;
|
|
206
|
+
allFields: AllFields;
|
|
207
|
+
hooks: Behavior['hooks'];
|
|
208
|
+
}
|
|
209
|
+
//#endregion
|
|
210
|
+
//#region src/types/infer.d.ts
|
|
211
|
+
/**
|
|
212
|
+
* Maps a single FieldConfig to its TypeScript output type.
|
|
213
|
+
* Each branch is a shallow comparison — no recursion.
|
|
214
|
+
*/
|
|
215
|
+
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<{
|
|
216
|
+
_block: string;
|
|
217
|
+
_id: string;
|
|
218
|
+
[key: string]: unknown;
|
|
219
|
+
}> : never;
|
|
220
|
+
/**
|
|
221
|
+
* Extract keys of fields where `required` is literally `true`.
|
|
222
|
+
* Fields without `required` or with `required?: false` are optional.
|
|
223
|
+
*/
|
|
224
|
+
type RequiredFieldKeys<Fields extends Record<string, FieldConfig>> = { [K in keyof Fields]: Fields[K]['required'] extends true ? K : never }[keyof Fields];
|
|
225
|
+
type OptionalFieldKeys<Fields extends Record<string, FieldConfig>> = { [K in keyof Fields]: Fields[K]['required'] extends true ? never : K }[keyof Fields];
|
|
226
|
+
/**
|
|
227
|
+
* Maps a full field record to its TypeScript output type.
|
|
228
|
+
* Required fields are non-nullable; optional fields are `T | null | undefined`.
|
|
229
|
+
*
|
|
230
|
+
* The `id` field is always `string` and always present.
|
|
231
|
+
* The `id` key from Fields is excluded to avoid duplication since
|
|
232
|
+
* we hardcode `{ id: string }` at the front.
|
|
233
|
+
*/
|
|
234
|
+
type InferEntityDTO<Fields extends Record<string, FieldConfig>> = {
|
|
235
|
+
id: string;
|
|
236
|
+
} & { [K in Exclude<RequiredFieldKeys<Fields>, 'id'>]: FieldToTS<Fields[K]> } & { [K in OptionalFieldKeys<Fields>]?: FieldToTS<Fields[K]> | null };
|
|
237
|
+
/** Fields that are auto-generated and should not appear in create input. */
|
|
238
|
+
type AutoGeneratedFields = 'id' | 'createdAt' | 'updatedAt' | 'createdBy' | 'updatedBy' | '_version';
|
|
239
|
+
/**
|
|
240
|
+
* The input type for creating an entity.
|
|
241
|
+
* - Omits auto-generated fields (id, timestamps, version)
|
|
242
|
+
* - Required fields stay required; optional fields stay optional
|
|
243
|
+
*/
|
|
244
|
+
type InferCreateInput<Fields extends Record<string, FieldConfig>> = Omit<{ [K in Exclude<RequiredFieldKeys<Fields>, 'id'>]: FieldToTS<Fields[K]> } & { [K in OptionalFieldKeys<Fields>]?: FieldToTS<Fields[K]> | null }, AutoGeneratedFields>;
|
|
245
|
+
/** Fields that cannot be changed after creation. */
|
|
246
|
+
type ImmutableFields = 'id' | 'createdAt' | 'createdBy';
|
|
247
|
+
type InferUpdateInput<Fields extends Record<string, FieldConfig>> = Partial<Omit<InferEntityDTO<Fields>, ImmutableFields>>;
|
|
248
|
+
//#endregion
|
|
249
|
+
//#region src/types/logger.d.ts
|
|
250
|
+
/**
|
|
251
|
+
* Minimal logger interface compatible with Pino.
|
|
252
|
+
*
|
|
253
|
+
* Defined locally to avoid a circular build dependency:
|
|
254
|
+
* entity → logging → core → entity.
|
|
255
|
+
*
|
|
256
|
+
* Any Pino logger instance satisfies this interface via structural typing.
|
|
257
|
+
*/
|
|
258
|
+
interface Logger {
|
|
259
|
+
info(obj: Record<string, unknown>, msg: string): void;
|
|
260
|
+
debug?(obj: Record<string, unknown>, msg: string): void;
|
|
261
|
+
}
|
|
262
|
+
//#endregion
|
|
263
|
+
//#region src/admin/client.d.ts
|
|
264
|
+
interface AdminClientConfig<AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>> {
|
|
265
|
+
entity: Entity<AllFields>;
|
|
266
|
+
db: PostgresJsDatabase;
|
|
267
|
+
logger?: Logger;
|
|
268
|
+
/** Optional count cache for COUNT(*) query optimization. */
|
|
269
|
+
countCache?: CountCacheLike;
|
|
270
|
+
}
|
|
271
|
+
interface FindManyOptions {
|
|
272
|
+
where?: SQL | undefined;
|
|
273
|
+
limit?: number;
|
|
274
|
+
offset?: number;
|
|
275
|
+
orderBy?: SQL | SQL[];
|
|
276
|
+
locale?: string;
|
|
277
|
+
/** Default content locale. For localized blocks, NULL rows (from initial create)
|
|
278
|
+
* are only returned as fallback when locale matches defaultLocale. */
|
|
279
|
+
defaultLocale?: string;
|
|
280
|
+
/**
|
|
281
|
+
* Cursor-based (keyset) pagination. When provided, replaces OFFSET with a
|
|
282
|
+
* WHERE condition for O(1) page access at any depth. The `offset` option
|
|
283
|
+
* is ignored when `cursor` is set.
|
|
284
|
+
*
|
|
285
|
+
* The cursor `field` must be a real column on the entity table.
|
|
286
|
+
*/
|
|
287
|
+
cursor?: CursorInput;
|
|
288
|
+
}
|
|
289
|
+
interface CountOptions {
|
|
290
|
+
where?: SQL | undefined;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* AdminClient - Full CRUD operations with security enforcement
|
|
294
|
+
*
|
|
295
|
+
* Security layers:
|
|
296
|
+
* 1. Runtime check: typeof window !== 'undefined' → throw (allows CLI scripts)
|
|
297
|
+
* 2. Uses read-write DB connection
|
|
298
|
+
* 3. Validation with Zod before every write
|
|
299
|
+
* 4. Hook execution (beforeCreate, afterCreate, etc.)
|
|
300
|
+
*
|
|
301
|
+
* Note: We don't use 'server-only' import because it blocks CLI scripts.
|
|
302
|
+
* Next.js bundler protection comes from subpath exports (@murumets-ee/core/clients).
|
|
303
|
+
*
|
|
304
|
+
* Phase 1: Core CRUD + hooks + validation
|
|
305
|
+
* Phase 2 (TODO): Access control, request context, scoping
|
|
306
|
+
*
|
|
307
|
+
* @typeParam AllFields - The entity's complete field map. Inferred automatically
|
|
308
|
+
* when constructing via `createAdminClient(entity)`.
|
|
309
|
+
*/
|
|
310
|
+
declare class AdminClient<AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>> {
|
|
311
|
+
private entity;
|
|
312
|
+
private db;
|
|
313
|
+
private logger?;
|
|
314
|
+
private createSchema;
|
|
315
|
+
private updateSchema;
|
|
316
|
+
private table;
|
|
317
|
+
private countCache?;
|
|
318
|
+
constructor(config: AdminClientConfig<AllFields>);
|
|
319
|
+
/**
|
|
320
|
+
* Create a new entity
|
|
321
|
+
*
|
|
322
|
+
* Flow:
|
|
323
|
+
* 1. Validate input with Zod
|
|
324
|
+
* 2. Execute beforeCreate hooks
|
|
325
|
+
* 3. Prepare data for insert
|
|
326
|
+
* 4. Insert into database
|
|
327
|
+
* 5. Execute afterCreate hooks
|
|
328
|
+
* 6. Shape DTO and return
|
|
329
|
+
*/
|
|
330
|
+
create(data: InferCreateInput<AllFields>): Promise<InferEntityDTO<AllFields>>;
|
|
331
|
+
/**
|
|
332
|
+
* Find entity by ID
|
|
333
|
+
*/
|
|
334
|
+
findById(id: string, options?: {
|
|
335
|
+
locale?: string;
|
|
336
|
+
defaultLocale?: string;
|
|
337
|
+
}): Promise<InferEntityDTO<AllFields> | null>;
|
|
338
|
+
/**
|
|
339
|
+
* Find multiple entities
|
|
340
|
+
*/
|
|
341
|
+
findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]>;
|
|
342
|
+
/**
|
|
343
|
+
* Count entities matching optional conditions
|
|
344
|
+
*/
|
|
345
|
+
count(options?: CountOptions): Promise<number>;
|
|
346
|
+
/**
|
|
347
|
+
* Update entity by ID
|
|
348
|
+
*
|
|
349
|
+
* Flow:
|
|
350
|
+
* 1. Validate input with Zod
|
|
351
|
+
* 2. Execute beforeUpdate hooks
|
|
352
|
+
* 3. Prepare data for update
|
|
353
|
+
* 4. Update in database
|
|
354
|
+
* 5. Execute afterUpdate hooks
|
|
355
|
+
* 6. Shape DTO and return
|
|
356
|
+
*/
|
|
357
|
+
update(id: string, data: InferUpdateInput<AllFields>, options?: {
|
|
358
|
+
locale?: string;
|
|
359
|
+
}): Promise<InferEntityDTO<AllFields>>;
|
|
360
|
+
/**
|
|
361
|
+
* Delete entity by ID.
|
|
362
|
+
*
|
|
363
|
+
* Checks entity_refs for incoming references first — throws
|
|
364
|
+
* ReferencedEntityError if this entity is still used somewhere.
|
|
365
|
+
*/
|
|
366
|
+
delete(id: string): Promise<void>;
|
|
367
|
+
/**
|
|
368
|
+
* Prepare data for insert — every field is a real column.
|
|
369
|
+
*/
|
|
370
|
+
private prepareDataForInsert;
|
|
371
|
+
/**
|
|
372
|
+
* Prepare data for update — every field is a real column.
|
|
373
|
+
* Standard column SET, no JSONB merge needed.
|
|
374
|
+
*/
|
|
375
|
+
private prepareDataForUpdate;
|
|
376
|
+
/**
|
|
377
|
+
* Merge translations into entities for the specified locale.
|
|
378
|
+
* Reads translatable field values from real columns on the translation row.
|
|
379
|
+
*/
|
|
380
|
+
private mergeTranslations;
|
|
381
|
+
/**
|
|
382
|
+
* Save translation for an entity.
|
|
383
|
+
* Each translatable field is a real column on the translation table.
|
|
384
|
+
*/
|
|
385
|
+
saveTranslation(entityId: string, locale: string, translations: Record<string, unknown>): Promise<void>;
|
|
386
|
+
/**
|
|
387
|
+
* PHASE 3: Delete translation(s) for an entity
|
|
388
|
+
* If locale is provided, deletes specific locale; otherwise deletes all translations
|
|
389
|
+
*/
|
|
390
|
+
deleteTranslation(entityId: string, locale?: string): Promise<void>;
|
|
391
|
+
/**
|
|
392
|
+
* Save block-level translations for an entity.
|
|
393
|
+
* For each block in each blocks field, extracts translatable field values
|
|
394
|
+
* and upserts them into {entity}_layout_translations.
|
|
395
|
+
*
|
|
396
|
+
* Block _id must match an existing layout row ID.
|
|
397
|
+
*/
|
|
398
|
+
saveBlockTranslations(entityId: string, locale: string, data: Record<string, unknown>): Promise<void>;
|
|
399
|
+
/**
|
|
400
|
+
* Save per-locale blocks for an entity.
|
|
401
|
+
* Used for entities with `localized: true` on their blocks field — each locale gets
|
|
402
|
+
* its own independent block layout rows in the layout table.
|
|
403
|
+
*/
|
|
404
|
+
saveLocalizedBlocks(entityId: string, locale: string, data: Record<string, unknown>): Promise<void>;
|
|
405
|
+
/**
|
|
406
|
+
* Get all blocks field names for this entity.
|
|
407
|
+
*/
|
|
408
|
+
private getBlocksFields;
|
|
409
|
+
/**
|
|
410
|
+
* Save blocks for an entity after create/update.
|
|
411
|
+
* For each blocks field, writes rows to {entity}_layout table.
|
|
412
|
+
*/
|
|
413
|
+
private saveBlocks;
|
|
414
|
+
/**
|
|
415
|
+
* Load blocks for one or more entities from the layout table.
|
|
416
|
+
*
|
|
417
|
+
* Handles both block translation modes:
|
|
418
|
+
* - Shared layout (localized: false): loads locale=NULL rows, merges translations,
|
|
419
|
+
* clears untranslated translatable fields to '' (strict mode for admin editing)
|
|
420
|
+
* - Per-locale layout (localized: true): loads rows matching the provided locale only
|
|
421
|
+
*
|
|
422
|
+
* @param entityIds - Entity IDs to load blocks for
|
|
423
|
+
* @param locale - Content locale (omit for default locale / base data)
|
|
424
|
+
* @param options.defaultLocale - Default locale; NULL rows fall back only for this locale
|
|
425
|
+
*/
|
|
426
|
+
private loadBlocks;
|
|
427
|
+
/**
|
|
428
|
+
* Attach loaded blocks to shaped DTOs.
|
|
429
|
+
*/
|
|
430
|
+
private attachBlocks;
|
|
431
|
+
/**
|
|
432
|
+
* Sync outgoing references in entity_refs after create/update.
|
|
433
|
+
*
|
|
434
|
+
* - 'create': inserts all refs (entity is new, no existing refs)
|
|
435
|
+
* - 'update': deletes refs for changed ref-bearing fields, then inserts new ones
|
|
436
|
+
*
|
|
437
|
+
* Gracefully skips if entity_refs table is not registered (e.g. before migration).
|
|
438
|
+
*/
|
|
439
|
+
private syncRefs;
|
|
440
|
+
/**
|
|
441
|
+
* Build a cache key for a count query.
|
|
442
|
+
* Key format: `entityName` for unfiltered, `entityName:where_sql` for filtered.
|
|
443
|
+
*/
|
|
444
|
+
private buildCountCacheKey;
|
|
445
|
+
/**
|
|
446
|
+
* Invalidate all count cache entries for this entity.
|
|
447
|
+
*/
|
|
448
|
+
private invalidateCountCache;
|
|
449
|
+
}
|
|
450
|
+
//#endregion
|
|
451
|
+
export { AdminClient, type AdminClientConfig, type CountCacheLike, type CountOptions, type FindManyOptions };
|
|
452
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/count-cache.ts","../../src/cursor.ts","../../src/admin-config.ts","../../src/fields/base.ts","../../src/behaviors/types.ts","../../src/define-entity.ts","../../src/types/infer.ts","../../src/types/logger.ts","../../src/admin/client.ts"],"mappings":";;;;;;;;;AAiBA;;;;;;;;;;;UAAiB,cAAA;EACf,GAAA,CAAI,GAAA;EACJ,GAAA,CAAI,GAAA,UAAa,KAAA;EACjB,UAAA,CAAW,MAAA;AAAA;;;;UCKI,WAAA;;EAEf,KAAA;EAF0B;EAI1B,KAAA;EAJ0B;EAM1B,SAAA;EAFA;EAIA,EAAA;AAAA;;;;;;;UC7Be,iBAAA;EFaA;EEXf,KAAA;;EAEA,KAAA;EFUA;EERA,aAAA;EFSA;EEPA,IAAA;EFOiB;EELjB,WAAA;EFMW;EEJX,MAAA;EFIyB;EEFzB,YAAA;;EAEA,aAAA;EDKe;ECHf,cAAA,GAAiB,MAAA;IAAiB,KAAA;IAAgB,WAAA;IAAsB,WAAA;EAAA;EDSxE;ECPA,WAAA;EDSE;ECPF,oBAAA;;EAEA,QAAA;;EAEA,UAAA;EA1BgC;EA4BhC,aAAA;EAVuB;EAYvB,SAAA;AAAA;;;;;;;UC7Be,eAAA;EACf,QAAA;EACA,OAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;EACA,MAAA;IACE,IAAA;IACA,IAAA;EAAA;AAAA;AAAA,UAIa,OAAA,SAAgB,eAAA;EAC/B,IAAA;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AA;ELzpBR;;AAGR;;;;;;;;;;EAHQ,QKytBQ,UAAA;EL5sBmB;;;EAAA,QK+2BzB,YAAA;EL72BR;;;;;AAWF;;;EAXE,QK04Bc,QAAA;EL93BV;AAGN;;;EAHM,QKw7BI,kBAAA;ELr7B2B;;;EAAA,QK+7B3B,oBAAA;AAAA"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{schemaRegistry as e}from"@murumets-ee/db";import{and as t,eq as n,gt as r,inArray as i,isNull as a,lt as o,or as s,sql as c}from"drizzle-orm";import{index as l,pgTable as u,unique as d,uuid as f,varchar as p}from"drizzle-orm/pg-core";import{z as m}from"zod";function h(e,i){let a=e[i.field];if(!a)return null;let c=i.direction===`desc`?o:r,l=c(a,i.value);if(!i.id)return l;let u=e.id;if(!u)return l;let d=c(u,i.id);return s(l,t(n(a,i.value),d))}function g(e,t,n){if(!t)return null;let r={},i=n?.select||Object.keys(e.allFields);for(let a of i){if(!n?.includeInternal&&a.startsWith(`_`))continue;let i=e.allFields[a];i&&i.type!==`blocks`&&(r[a]=t[a])}return r}function _(e,t,n){return t.map(t=>g(e,t,n))}var v=class extends Error{entityName;entityId;usages;constructor(e,t,n){let r=n.length;super(`Cannot delete ${e} '${t}': referenced by ${r} other entit${r===1?`y`:`ies`}`),this.name=`ReferencedEntityError`,this.entityName=e,this.entityId=t,this.usages=n}};const y=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function b(e,t){let n=[],r=new Set;function i(e,t,i){if(!y.test(i))return;let a=`${e}|${t}|${i}`;r.has(a)||(r.add(a),n.push({sourceField:e,targetEntity:t,targetId:i}))}for(let[n,r]of Object.entries(e)){let e=t[n];if(e!=null)switch(r.type){case`media`:typeof e==`string`&&i(n,`media`,e);break;case`reference`:{let t=r;if(t.cardinality===`many`&&Array.isArray(e))for(let r of e)typeof r==`string`&&i(n,t.entity,r);else typeof e==`string`&&i(n,t.entity,e);break}case`blocks`:{let t=r;if(!Array.isArray(e))break;for(let r of e){let e=r,a=e._block;if(!a)continue;let o=t.blocks.find(e=>e.slug===a);if(o)for(let[t,r]of Object.entries(o.fields)){let a=e[t];if(a!=null&&(r.type===`media`&&typeof a==`string`&&i(n,`media`,a),r.type===`reference`)){let e=r;if(e.cardinality===`many`&&Array.isArray(a))for(let t of a)typeof t==`string`&&i(n,e.entity,t);else typeof a==`string`&&i(n,e.entity,a)}}}break}}}return n}const x=u(`entity_refs`,{sourceEntity:p(`source_entity`,{length:100}).notNull(),sourceId:f(`source_id`).notNull(),sourceField:p(`source_field`,{length:100}).notNull(),targetEntity:p(`target_entity`,{length:100}).notNull(),targetId:f(`target_id`).notNull()},e=>[d(`uq_entity_refs`).on(e.sourceEntity,e.sourceId,e.sourceField,e.targetEntity,e.targetId),l(`idx_entity_refs_target`).on(e.targetEntity,e.targetId),l(`idx_entity_refs_source`).on(e.sourceEntity,e.sourceId)]);async function S(e,r,i){return await i.select({sourceEntity:x.sourceEntity,sourceId:x.sourceId,sourceField:x.sourceField}).from(x).where(t(n(x.targetEntity,e),n(x.targetId,r)))}function C(e){let t;switch(e.type){case`id`:t=m.string().uuid();break;case`text`:t=m.string(),e.maxLength&&(t=t.max(e.maxLength)),e.minLength&&(t=t.min(e.minLength)),e.pattern&&(t=t.regex(e.pattern));break;case`number`:t=m.number(),e.integer&&(t=t.int()),e.min!==void 0&&(t=t.min(e.min)),e.max!==void 0&&(t=t.max(e.max));break;case`boolean`:t=m.boolean();break;case`date`:t=m.date().or(m.string().datetime());break;case`select`:t=m.enum(e.options);break;case`reference`:t=e.cardinality===`many`?m.array(m.string().uuid()):m.string().uuid();break;case`media`:t=m.string().uuid();break;case`richtext`:t=m.union([m.string(),m.array(m.record(m.unknown()))]);break;case`slug`:t=m.string().regex(/^[a-z0-9-]+$/);break;case`json`:t=m.record(m.unknown());break;case`blocks`:t=m.array(m.object({_block:m.string()}).passthrough());break;default:t=m.unknown()}return e.required||(t=t.nullable().optional()),e.default!==void 0&&(t=t.default(e.default)),t}function w(e){let t={},n=new Set([`id`,`createdAt`,`updatedAt`,`createdBy`,`_version`]);for(let[r,i]of Object.entries(e.allFields))n.has(r)||(t[r]=C(i));return m.object(t)}function T(e){let t={},n=new Set([`id`,`createdAt`,`createdBy`,`updatedAt`,`updatedBy`,`_version`]);for(let[r,i]of Object.entries(e.allFields))n.has(r)||(t[r]=C(i).optional());return m.object(t)}var E=class{entity;db;logger;createSchema;updateSchema;table;countCache;constructor(t){if(typeof window<`u`)throw Error(`AdminClient cannot be used in browser code. Use QueryClient for frontend data access.`);this.entity=t.entity,this.db=t.db,this.logger=t.logger,this.countCache=t.countCache,this.createSchema=w(t.entity),this.updateSchema=T(t.entity);let n=e.get(t.entity.name);if(!n)throw Error(`Schema for entity '${t.entity.name}' not found in registry. Ensure schemas are generated and registered before creating AdminClient.`);this.table=n}async create(e){this.logger?.info({entity:this.entity.name},`Creating entity`);let t=e;if(this.entity.hooks?.beforeCreate){let e=await this.entity.hooks.beforeCreate(t);t=e===void 0?t:e}t=this.createSchema.parse(t);let n=this.prepareDataForInsert(t),[r]=await this.db.insert(this.table).values(n).returning();await this.saveBlocks(r.id,t),await this.syncRefs(r.id,t,`create`),this.entity.hooks?.afterCreate&&await this.entity.hooks.afterCreate(r),this.invalidateCountCache();let i=g(this.entity,r);if(i&&this.getBlocksFields().length>0){let e=await this.loadBlocks([i.id]);this.attachBlocks([i],e)}return i}async findById(e,t){this.logger?.info({entity:this.entity.name,id:e},`Finding entity by ID`);let[r]=await this.db.select().from(this.table).where(n(this.table.id,e));if(!r)return null;let i=g(this.entity,r);if(!i)return null;if(this.getBlocksFields().length>0){let e=await this.loadBlocks([i.id],t?.locale,{defaultLocale:t?.defaultLocale});this.attachBlocks([i],e)}if(t?.locale){let[e]=await this.mergeTranslations([i],t.locale);return e}return i}async findMany(e){this.logger?.info({entity:this.entity.name,options:e},`Finding entities`);let n=this.db.select().from(this.table).$dynamic(),r=[];if(e?.where&&r.push(e.where),e?.cursor){let t=this.entity.allFields;if(!(e.cursor.field in t)&&e.cursor.field!==`id`)throw Error(`Invalid cursor field: '${e.cursor.field}' is not a field on '${this.entity.name}'`);let n=h(this.table,e.cursor);n&&r.push(n)}if(r.length>0&&(n=n.where(t(...r))),e?.limit&&(n=n.limit(e.limit)),e?.offset&&!e?.cursor&&(n=n.offset(e.offset)),e?.orderBy){let t=Array.isArray(e.orderBy)?e.orderBy:[e.orderBy];n=n.orderBy(...t)}let i=await n,a=_(this.entity,i).filter(e=>e!==null);if(this.getBlocksFields().length>0&&a.length>0){let t=a.map(e=>e.id),n=await this.loadBlocks(t,e?.locale,{defaultLocale:e?.defaultLocale});this.attachBlocks(a,n)}return e?.locale?await this.mergeTranslations(a,e.locale):a}async count(e){this.logger?.info({entity:this.entity.name,options:e},`Counting entities`);let t=this.buildCountCacheKey(e?.where);if(this.countCache){let e=this.countCache.get(t);if(e!==void 0)return this.logger?.debug?.({entity:this.entity.name,cached:e},`Count cache hit`),e}let n=this.db.select({count:c`count(*)`}).from(this.table).$dynamic();e?.where&&(n=n.where(e.where));let[r]=await n,i=Number(r.count);return this.countCache&&this.countCache.set(t,i),i}async update(e,t,r){this.logger?.info({entity:this.entity.name,id:e},`Updating entity`);let i=t;if(this.entity.hooks?.beforeUpdate){let t=await this.entity.hooks.beforeUpdate(e,i);i=t===void 0?i:t}i=this.updateSchema.parse(i);let a=this.prepareDataForUpdate(i),o;if(Object.keys(a).length>0){let[t]=await this.db.update(this.table).set(a).where(n(this.table.id,e)).returning();o=t}else{let[t]=await this.db.select().from(this.table).where(n(this.table.id,e));o=t}await this.saveBlocks(e,i,r),await this.syncRefs(e,i,`update`),this.entity.hooks?.afterUpdate&&await this.entity.hooks.afterUpdate(o);let s=g(this.entity,o);if(s&&this.getBlocksFields().length>0){let t=await this.loadBlocks([e]);this.attachBlocks([s],t)}return s}async delete(e){this.logger?.info({entity:this.entity.name,id:e},`Deleting entity`);let r=await S(this.entity.name,e,this.db);if(r.length>0)throw new v(this.entity.name,e,r);this.entity.hooks?.beforeDelete&&await this.entity.hooks.beforeDelete(e),await this.db.delete(this.table).where(n(this.table.id,e)),await this.db.delete(x).where(t(n(x.sourceEntity,this.entity.name),n(x.sourceId,e))),this.entity.hooks?.afterDelete&&await this.entity.hooks.afterDelete(e),this.invalidateCountCache()}prepareDataForInsert(e){let t={};for(let[n,r]of Object.entries(e)){let e=this.entity.allFields[n];e&&n!==`id`&&e.type!==`blocks`&&(t[n]=r)}return t}prepareDataForUpdate(e){let t={};for(let[n,r]of Object.entries(e)){let e=this.entity.allFields[n];e&&n!==`id`&&e.type!==`blocks`&&(t[n]=r)}return t}async mergeTranslations(r,a){if(!r.length)return r;let o=`${this.entity.name}_translations`,s=e.get(o);if(!s)return r;let c=r.map(e=>e.id),l=await this.db.select().from(s).where(t(i(s.entityId,c),n(s.locale,a))),u=Object.entries(this.entity.allFields).filter(([e,t])=>t.translatable).map(([e])=>e),d=new Map;for(let e of l){let t={};for(let n of u){let r=e[n];r!=null&&(t[n]=r)}d.set(e.entityId,t)}return r.map(e=>{let t=d.get(e.id);return t?{...e,...t}:e})}async saveTranslation(t,n,r){this.logger?.info({entity:this.entity.name,entityId:t,locale:n},`Saving translation`);let i=`${this.entity.name}_translations`,a=e.get(i);if(!a)throw Error(`Translation table ${i} not found in schema registry`);let o=Object.entries(this.entity.allFields).filter(([e,t])=>t.translatable).map(([e])=>e);if(o.length===0)throw Error(`Entity ${this.entity.name} has no translatable fields`);let s={entityId:t,locale:n},c={};for(let e of o)r[e]!==void 0&&(s[e]=r[e],c[e]=r[e]);await this.db.insert(a).values(s).onConflictDoUpdate({target:[a.entityId,a.locale],set:c}),this.logger?.info({entity:this.entity.name,entityId:t,locale:n},`Translation saved`)}async deleteTranslation(r,i){this.logger?.info({entity:this.entity.name,entityId:r,locale:i},`Deleting translation`);let a=`${this.entity.name}_translations`,o=e.get(a);if(!o)throw Error(`Translation table ${a} not found in schema registry`);i?(await this.db.delete(o).where(t(n(o.entityId,r),n(o.locale,i))),this.logger?.info({entity:this.entity.name,entityId:r,locale:i},`Translation deleted`)):(await this.db.delete(o).where(n(o.entityId,r)),this.logger?.info({entity:this.entity.name,entityId:r},`All translations deleted`))}async saveBlockTranslations(r,i,o){this.logger?.info({entity:this.entity.name,entityId:r,locale:i},`Saving block translations`);let s=this.getBlocksFields();if(s.length===0)return;let c=e.get(`${this.entity.name}_layout_translations`);if(!c)return;let l=e.get(`${this.entity.name}_layout`);if(l){for(let{name:e,config:u}of s){let s=o[e];if(!Array.isArray(s))continue;let d=u.blocks;if(!d)continue;let f=await this.db.select({id:l.id,blockType:l.blockType}).from(l).where(t(n(l.entityId,r),n(l.fieldName,e),a(l.locale))).orderBy(l.sortOrder);for(let e=0;e<s.length;e++){let t=s[e],n=t._block;if(!n)continue;let r=f[e];if(!r||r.blockType!==n)continue;let a=d.find(e=>e.slug===n);if(!a)continue;let o={};for(let[e,n]of Object.entries(a.fields))n.translatable&&t[e]!==void 0&&(o[e]=t[e]);Object.keys(o).length!==0&&await this.db.insert(c).values({layoutId:r.id,locale:i,fields:o}).onConflictDoUpdate({target:[c.layoutId,c.locale],set:{fields:o}})}}this.logger?.info({entity:this.entity.name,entityId:r,locale:i},`Block translations saved`)}}async saveLocalizedBlocks(e,t,n){this.logger?.info({entity:this.entity.name,entityId:e,locale:t},`Saving localized blocks`),await this.saveBlocks(e,n,{locale:t})}getBlocksFields(){return Object.entries(this.entity.allFields).filter(([e,t])=>t.type===`blocks`).map(([e,t])=>({name:e,config:t}))}async saveBlocks(r,i,o){let s=this.getBlocksFields();if(s.length===0)return;let c=e.get(`${this.entity.name}_layout`);if(c)for(let{name:e,config:l}of s){let s=i[e];if(!Array.isArray(s))continue;let u=`localized`in l&&l.localized===!0,d=u?o?.locale??null:null,f=[n(c.entityId,r),n(c.fieldName,e)];d?f.push(n(c.locale,d)):u||f.push(a(c.locale)),await this.db.delete(c).where(t(...f));for(let t=0;t<s.length;t++){let n=s[t],i=n._block;if(!i)continue;let{_block:a,_id:o,...l}=n;await this.db.insert(c).values({entityId:r,fieldName:e,blockType:i,sortOrder:t,data:l,locale:d})}}}async loadBlocks(r,o,c){let l=this.getBlocksFields();if(l.length===0||r.length===0)return new Map;let u=e.get(`${this.entity.name}_layout`);if(!u)return new Map;let d=l.filter(({config:e})=>!(`localized`in e&&e.localized)),f=l.filter(({config:e})=>`localized`in e&&e.localized),p=new Map;if(d.length>0){let s=await this.db.select().from(u).where(t(i(u.entityId,r),a(u.locale))).orderBy(u.sortOrder),c;if(o&&s.length>0){let r=e.get(`${this.entity.name}_layout_translations`);if(r){let e=s.map(e=>e.id),a=await this.db.select().from(r).where(t(i(r.layoutId,e),n(r.locale,o)));c=new Map;for(let e of a)c.set(e.layoutId,e.fields??{})}}let l=new Map;for(let{config:e}of d){let t=e.blocks;if(t)for(let e of t)l.set(e.slug,e.fields)}for(let e of s){let t=e.entityId,n=e.fieldName;p.has(t)||p.set(t,{});let r=p.get(t);r[n]||(r[n]=[]);let i=e.data??{},a=c?.get(e.id),s={_block:e.blockType,_id:e.id,...i,...a??{}};if(o){let t=e.blockType,n=l.get(t);if(n)for(let[e,t]of Object.entries(n))t.translatable&&!a?.[e]&&(s[e]=``)}r[n].push(s)}}if(f.length>0){let e=!o||o===c?.defaultLocale,l=o?e?s(n(u.locale,o),a(u.locale)):n(u.locale,o):a(u.locale),d=await this.db.select().from(u).where(t(i(u.entityId,r),l)).orderBy(u.sortOrder),f=new Map;for(let e of d){let t=`${e.entityId}::${e.fieldName}`;f.has(t)||f.set(t,{localeRows:[],nullRows:[]});let n=f.get(t);e.locale?n.localeRows.push(e):n.nullRows.push(e)}for(let[,{localeRows:e,nullRows:t}]of f){let n=e.length>0?e:t;for(let e of n){let t=e.entityId,n=e.fieldName;p.has(t)||p.set(t,{});let r=p.get(t);r[n]||(r[n]=[]);let i=e.data??{};r[n].push({_block:e.blockType,_id:e.id,...i})}}}return p}attachBlocks(e,t){let n=this.getBlocksFields();if(n.length!==0)for(let r of e){let e=r.id,i=t.get(e)??{};for(let{name:e}of n)r[e]=i[e]??[]}}async syncRefs(r,a,o){if(!e.has(`entity_refs`))return;let s=this.entity.allFields;if(o===`update`){let e=Object.keys(a).filter(e=>{let t=s[e];return t&&(t.type===`media`||t.type===`reference`||t.type===`blocks`)});e.length>0&&await this.db.delete(x).where(t(n(x.sourceEntity,this.entity.name),n(x.sourceId,r),i(x.sourceField,e)))}let c=b(s,a);c.length>0&&await this.db.insert(x).values(c.map(e=>({sourceEntity:this.entity.name,sourceId:r,sourceField:e.sourceField,targetEntity:e.targetEntity,targetId:e.targetId}))).onConflictDoNothing()}buildCountCacheKey(e){return e?`${this.entity.name}:${String(e)}`:this.entity.name}invalidateCountCache(){this.countCache?.invalidate(this.entity.name)}};export{E as AdminClient};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|