@duraxis/orm 0.0.0-stage → 0.2.2

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE +15 -0
  3. package/README.md +57 -2
  4. package/dist/database/duraxis-orm.d.ts +16 -0
  5. package/dist/database/orm-options.d.ts +12 -0
  6. package/dist/decorators/column.decorator.d.ts +2 -0
  7. package/dist/decorators/entity.decorator.d.ts +1 -0
  8. package/dist/decorators/index.decorator.d.ts +13 -0
  9. package/dist/decorators/primary-key.decorator.d.ts +2 -0
  10. package/dist/decorators/relation.decorators.d.ts +19 -0
  11. package/dist/errors/index.d.ts +32 -0
  12. package/dist/index.cjs +1434 -0
  13. package/dist/index.cjs.map +1 -0
  14. package/dist/index.d.ts +27 -0
  15. package/dist/index.js +1388 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/mapping/entity-hydrator.d.ts +11 -0
  18. package/dist/mapping/entity-mapper.d.ts +15 -0
  19. package/dist/mapping/value-transformer.d.ts +6 -0
  20. package/dist/metadata/decorator-metadata.d.ts +50 -0
  21. package/dist/metadata/entity-metadata.d.ts +68 -0
  22. package/dist/metadata/metadata-registry.d.ts +11 -0
  23. package/dist/metadata/metadata-validator.d.ts +4 -0
  24. package/dist/query/find-options.d.ts +21 -0
  25. package/dist/query/query-builder.d.ts +50 -0
  26. package/dist/query/query-mapper.d.ts +14 -0
  27. package/dist/query/where-operator.d.ts +26 -0
  28. package/dist/relations/relation-loader.d.ts +17 -0
  29. package/dist/relations/relation-operations.d.ts +10 -0
  30. package/dist/repository/repository-errors.d.ts +1 -0
  31. package/dist/repository/repository-options.d.ts +8 -0
  32. package/dist/repository/repository.d.ts +35 -0
  33. package/dist/schema/schema-manager.d.ts +12 -0
  34. package/dist/schema/schema-mapper.d.ts +4 -0
  35. package/dist/transactions/orm-transaction.d.ts +15 -0
  36. package/dist/transactions/transaction-context.d.ts +5 -0
  37. package/package.json +59 -3
package/dist/index.js ADDED
@@ -0,0 +1,1388 @@
1
+ import { CommitOutcomeUnknownError, CommitOutcomeUnknownError as CommitOutcomeUnknownError$1, TransactionConflictError, TransactionConflictError as TransactionConflictError$1, UniqueIndexViolationError, normalizeCollection } from "@duraxis/core";
2
+ import { createHash } from "node:crypto";
3
+ // src/metadata/decorator-metadata.ts
4
+ var drafts = /* @__PURE__ */ new WeakMap();
5
+ function ownDraft(entity) {
6
+ return drafts.get(entity);
7
+ }
8
+ function mutableDraft(entity) {
9
+ let draft = drafts.get(entity);
10
+ if (!draft) {
11
+ draft = {
12
+ entityApplications: 0,
13
+ columns: [],
14
+ primaryKeys: [],
15
+ indexes: [],
16
+ relations: [],
17
+ joinTables: []
18
+ };
19
+ drafts.set(entity, draft);
20
+ }
21
+ return draft;
22
+ }
23
+ function entityConstructor(target) {
24
+ const constructor = target.constructor;
25
+ if (typeof constructor != "function") throw new TypeError("Invalid decorator target");
26
+ return constructor;
27
+ }
28
+ function propertyName(value) {
29
+ if (typeof value != "string") throw new TypeError("Symbol entity properties are not supported");
30
+ return value;
31
+ }
32
+ // src/decorators/entity.decorator.ts
33
+ function Entity(name) {
34
+ return (target) => {
35
+ const draft = mutableDraft(target);
36
+ draft.entityApplications++;
37
+ draft.entityName = name ?? target.name;
38
+ };
39
+ }
40
+ // src/decorators/column.decorator.ts
41
+ function Column(options) {
42
+ return (target, key) => {
43
+ mutableDraft(entityConstructor(target)).columns.push({
44
+ property: propertyName(key),
45
+ options: { ...options }
46
+ });
47
+ };
48
+ }
49
+ // src/decorators/primary-key.decorator.ts
50
+ /** Declares the logical record identifier. It is never stored inside the document. */
51
+ function PrimaryKey() {
52
+ return (target, key) => {
53
+ mutableDraft(entityConstructor(target)).primaryKeys.push(propertyName(key));
54
+ };
55
+ }
56
+ // src/decorators/index.decorator.ts
57
+ function Index(nameOrOptions = {}, fields, compositeOptions = {}) {
58
+ if (typeof nameOrOptions == "string") return (target) => {
59
+ mutableDraft(target).indexes.push({
60
+ kind: "composite",
61
+ name: nameOrOptions,
62
+ unique: compositeOptions.unique ?? false,
63
+ fields: (fields ?? []).map((field) => ({
64
+ property: field.property,
65
+ order: field.order ?? "ASC"
66
+ }))
67
+ });
68
+ };
69
+ return (target, key) => {
70
+ mutableDraft(entityConstructor(target)).indexes.push({
71
+ kind: "property",
72
+ property: propertyName(key),
73
+ ...nameOrOptions.name == null ? {} : { name: nameOrOptions.name },
74
+ unique: nameOrOptions.unique ?? false
75
+ });
76
+ };
77
+ }
78
+ // src/decorators/relation.decorators.ts
79
+ function relation(kind, target, inverse, options) {
80
+ return (prototype, key) => {
81
+ mutableDraft(entityConstructor(prototype)).relations.push({
82
+ kind,
83
+ property: propertyName(key),
84
+ target,
85
+ ...inverse ? { inverse } : {},
86
+ ...options?.foreignKey ? { foreignKey: options.foreignKey } : {},
87
+ ...options?.onDelete ? { onDelete: options.onDelete } : {}
88
+ });
89
+ };
90
+ }
91
+ function ManyToOne(target, options) {
92
+ return relation("many-to-one", target, void 0, options);
93
+ }
94
+ function OneToMany(target, inverse) {
95
+ return relation("one-to-many", target, inverse, void 0);
96
+ }
97
+ function OneToOne(target, inverseOrOptions) {
98
+ return typeof inverseOrOptions == "function" ? relation("one-to-one", target, inverseOrOptions, void 0) : relation("one-to-one", target, void 0, inverseOrOptions);
99
+ }
100
+ function ManyToMany(target, inverse) {
101
+ return relation("many-to-many", target, inverse, void 0);
102
+ }
103
+ function JoinTable(options) {
104
+ return (prototype, key) => {
105
+ mutableDraft(entityConstructor(prototype)).joinTables.push({
106
+ property: propertyName(key),
107
+ name: options.name,
108
+ ...options.joinColumn ? { joinColumn: options.joinColumn } : {},
109
+ ...options.inverseJoinColumn ? { inverseJoinColumn: options.inverseJoinColumn } : {}
110
+ });
111
+ };
112
+ }
113
+ // src/errors/index.ts
114
+ var DuraxisOrmError = class extends Error {
115
+ constructor(message, options) {
116
+ super(message, options);
117
+ this.name = new.target.name;
118
+ }
119
+ };
120
+ var EntityNotRegisteredError = class extends DuraxisOrmError {
121
+ constructor(entity) {
122
+ super(`Entity is not registered: ${entity.name || "<anonymous>"}`);
123
+ }
124
+ };
125
+ var InvalidMetadataError = class extends DuraxisOrmError {};
126
+ var MissingPrimaryKeyError = class extends InvalidMetadataError {};
127
+ var DuplicateRecordError = class extends DuraxisOrmError {};
128
+ var RecordNotFoundError = class extends DuraxisOrmError {};
129
+ var InvalidColumnError = class extends DuraxisOrmError {};
130
+ var SchemaViolationError = class extends DuraxisOrmError {};
131
+ var InvalidQueryError = class extends DuraxisOrmError {};
132
+ var UniqueIndexViolationOrmError = class extends DuraxisOrmError {
133
+ constructor(message, cause) {
134
+ super(message, { cause });
135
+ }
136
+ };
137
+ var OrmNotInitializedError = class extends DuraxisOrmError {
138
+ constructor() {
139
+ super("DuraxisORM is not initialized");
140
+ }
141
+ };
142
+ var OrmClosedError = class extends DuraxisOrmError {
143
+ constructor() {
144
+ super("DuraxisORM is closed");
145
+ }
146
+ };
147
+ var TransactionManagerClosedError = class extends DuraxisOrmError {
148
+ constructor() {
149
+ super("ORM transaction manager is no longer active");
150
+ }
151
+ };
152
+ // src/metadata/entity-metadata.ts
153
+ var EntityMetadata = class {
154
+ #byProperty;
155
+ #byField;
156
+ entity;
157
+ collection;
158
+ primaryKey;
159
+ columns;
160
+ indexes;
161
+ relations;
162
+ constructor(options) {
163
+ this.entity = options.entity;
164
+ this.collection = options.collection;
165
+ this.primaryKey = options.primaryKey;
166
+ this.columns = Object.freeze(options.columns.map((column) => Object.freeze({ ...column })));
167
+ this.indexes = Object.freeze(options.indexes.map((index) => Object.freeze({
168
+ ...index,
169
+ fields: Object.freeze(index.fields.map((field) => Object.freeze({ ...field })))
170
+ })));
171
+ this.relations = Object.freeze((options.relations ?? []).map((relation) => Object.freeze({
172
+ ...relation,
173
+ ...relation.joinTable ? { joinTable: Object.freeze({ ...relation.joinTable }) } : {}
174
+ })));
175
+ this.#byProperty = new Map(this.columns.map((column) => [column.property, column]));
176
+ this.#byField = new Map(this.columns.map((column) => [column.field, column]));
177
+ Object.freeze(this);
178
+ }
179
+ columnForProperty(property) {
180
+ return this.#byProperty.get(property);
181
+ }
182
+ columnForField(field) {
183
+ return this.#byField.get(field);
184
+ }
185
+ relationForProperty(property) {
186
+ return this.relations.find((relation) => relation.property == property);
187
+ }
188
+ };
189
+ // src/metadata/metadata-validator.ts
190
+ var NAME$1 = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
191
+ var TYPES = /* @__PURE__ */ new Set([
192
+ "string",
193
+ "number",
194
+ "boolean",
195
+ "date"
196
+ ]);
197
+ function requireName(name, label) {
198
+ if (typeof name != "string" || !NAME$1.test(name)) throw new InvalidMetadataError(`Invalid ${label}: ${String(name)}`);
199
+ }
200
+ function decoratorHierarchy(entity) {
201
+ const result = [];
202
+ let current = entity;
203
+ while (typeof current == "function" && current != Function.prototype) {
204
+ const draft = ownDraft(current);
205
+ if (draft) result.unshift(draft);
206
+ current = Object.getPrototypeOf(current);
207
+ }
208
+ return result;
209
+ }
210
+ function buildEntityMetadata(entity) {
211
+ const own = ownDraft(entity);
212
+ if (!own?.entityName) throw new InvalidMetadataError(`Class ${entity.name} is missing @Entity()`);
213
+ if (own.entityApplications != 1) throw new InvalidMetadataError(`Class ${entity.name} has duplicate @Entity() decorators`);
214
+ requireName(own.entityName, "entity name");
215
+ const drafts = decoratorHierarchy(entity);
216
+ const columns = [];
217
+ const byProperty = /* @__PURE__ */ new Map();
218
+ const byField = /* @__PURE__ */ new Map();
219
+ const primaryKeys = [];
220
+ for (const draft of drafts) {
221
+ for (const key of draft.primaryKeys) {
222
+ requireName(key, "primary-key property");
223
+ primaryKeys.push(key);
224
+ }
225
+ for (const column of draft.columns) {
226
+ requireName(column.property, "column property");
227
+ const field = column.options.name ?? column.property;
228
+ requireName(field, "persisted column name");
229
+ if (!TYPES.has(column.options.type)) throw new InvalidMetadataError(`Invalid column type for ${column.property}`);
230
+ if (byProperty.has(column.property)) throw new InvalidMetadataError(`Duplicate column property: ${column.property}`);
231
+ if (byField.has(field)) throw new InvalidMetadataError(`Duplicate persisted column name: ${field}`);
232
+ const metadata = {
233
+ property: column.property,
234
+ field,
235
+ type: column.options.type,
236
+ required: column.options.required ?? false,
237
+ nullable: column.options.nullable ?? false
238
+ };
239
+ columns.push(metadata);
240
+ byProperty.set(column.property, metadata);
241
+ byField.set(field, metadata);
242
+ }
243
+ }
244
+ if (primaryKeys.length == 0) throw new MissingPrimaryKeyError(`Entity ${entity.name} must declare exactly one primary key`);
245
+ if (primaryKeys.length != 1) throw new InvalidMetadataError(`Entity ${entity.name} declares multiple primary keys`);
246
+ const primaryKey = primaryKeys[0];
247
+ if (byProperty.has(primaryKey)) throw new InvalidMetadataError(`Primary key ${primaryKey} must not also be declared as a persisted column`);
248
+ const indexes = [];
249
+ const indexNames = /* @__PURE__ */ new Set();
250
+ for (const draft of drafts) for (const index of draft.indexes) {
251
+ const name = index.kind == "property" ? index.name ?? index.property : index.name;
252
+ requireName(name, "index name");
253
+ if (indexNames.has(name)) throw new InvalidMetadataError(`Duplicate index name: ${name}`);
254
+ indexNames.add(name);
255
+ const fields = index.kind == "property" ? [{
256
+ property: index.property,
257
+ order: "ASC"
258
+ }] : index.fields;
259
+ if (fields.length == 0) throw new InvalidMetadataError(`Index ${name} has no fields`);
260
+ const seen = /* @__PURE__ */ new Set();
261
+ const mapped = fields.map((part) => {
262
+ requireName(part.property, `property in index ${name}`);
263
+ const column = byProperty.get(part.property);
264
+ if (!column) throw new InvalidMetadataError(`Index ${name} references unknown column property: ${part.property}`);
265
+ if (seen.has(part.property)) throw new InvalidMetadataError(`Index ${name} repeats property: ${part.property}`);
266
+ seen.add(part.property);
267
+ if (part.order != "ASC" && part.order != "DESC") throw new InvalidMetadataError(`Invalid order in index ${name}`);
268
+ return {
269
+ property: column.property,
270
+ field: column.field,
271
+ order: part.order
272
+ };
273
+ });
274
+ indexes.push({
275
+ name,
276
+ unique: index.unique,
277
+ fields: mapped
278
+ });
279
+ }
280
+ return new EntityMetadata({
281
+ entity,
282
+ collection: own.entityName,
283
+ primaryKey,
284
+ columns,
285
+ indexes,
286
+ relations: []
287
+ });
288
+ }
289
+ // src/metadata/metadata-registry.ts
290
+ var NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
291
+ function selectedProperty(selector) {
292
+ let selected;
293
+ selector(new Proxy(Object.create(null), { get(_target, property) {
294
+ if (typeof property != "string") throw new InvalidMetadataError("Invalid inverse selector");
295
+ selected = property;
296
+ return property;
297
+ } }));
298
+ if (!selected || !NAME.test(selected)) throw new InvalidMetadataError("Inverse relation selector must select one property");
299
+ return selected;
300
+ }
301
+ function defaultJoinField(entity) {
302
+ return `${entity.name.charAt(0).toLowerCase()}${entity.name.slice(1)}Id`;
303
+ }
304
+ var MetadataRegistry = class {
305
+ #metadata = /* @__PURE__ */ new Map();
306
+ #collections = /* @__PURE__ */ new Map();
307
+ #finalized = false;
308
+ constructor(entities = []) {
309
+ for (const entity of entities) this.register(entity);
310
+ }
311
+ register(entity) {
312
+ if (this.#finalized) throw new InvalidMetadataError("Metadata registry is finalized");
313
+ const existing = this.#metadata.get(entity);
314
+ if (existing) return existing;
315
+ const metadata = buildEntityMetadata(entity);
316
+ const collectionOwner = this.#collections.get(metadata.collection);
317
+ if (collectionOwner && collectionOwner != entity) throw new InvalidMetadataError(`Duplicate entity collection: ${metadata.collection}`);
318
+ this.#metadata.set(entity, metadata);
319
+ this.#collections.set(metadata.collection, entity);
320
+ return metadata;
321
+ }
322
+ finalize() {
323
+ const preliminary = /* @__PURE__ */ new Map();
324
+ for (const raw of this.#metadata.values()) {
325
+ const metadata = raw;
326
+ const relations = [];
327
+ const drafts = decoratorHierarchy(metadata.entity);
328
+ const relationDrafts = drafts.flatMap((draft) => draft.relations);
329
+ const joinTables = drafts.flatMap((draft) => draft.joinTables);
330
+ const properties = /* @__PURE__ */ new Set();
331
+ for (const draft of relationDrafts) {
332
+ if (!NAME.test(draft.property) || properties.has(draft.property)) throw new InvalidMetadataError(`Invalid or duplicate relation: ${draft.property}`);
333
+ properties.add(draft.property);
334
+ const target = draft.target();
335
+ if (typeof target != "function" || !this.#metadata.has(target)) throw new InvalidMetadataError(`Relation ${metadata.collection}.${draft.property} targets an unregistered entity`);
336
+ const targetMetadata = this.get(target);
337
+ const column = draft.foreignKey ? metadata.columnForProperty(draft.foreignKey) : void 0;
338
+ const owner = draft.kind == "many-to-one" || draft.kind == "one-to-one" && !!draft.foreignKey;
339
+ if (owner && draft.property.length > 61) throw new InvalidMetadataError(`Owning relation name is too long: ${draft.property}`);
340
+ if (owner && (!column || column.type != "string")) throw new InvalidMetadataError(`Owning relation ${metadata.collection}.${draft.property} requires a string foreign-key column`);
341
+ if (draft.onDelete == "SET_NULL" && !column?.nullable) throw new InvalidMetadataError(`SET_NULL relation ${metadata.collection}.${draft.property} requires a nullable column`);
342
+ const join = joinTables.find((item) => item.property == draft.property);
343
+ if (join && draft.kind != "many-to-many") throw new InvalidMetadataError(`@JoinTable is only valid on ManyToMany relations`);
344
+ if (join && !NAME.test(join.name)) throw new InvalidMetadataError(`Invalid join table name: ${join.name}`);
345
+ relations.push({
346
+ kind: draft.kind,
347
+ property: draft.property,
348
+ target,
349
+ targetCollection: targetMetadata.collection,
350
+ ...draft.inverse ? { inverseProperty: selectedProperty(draft.inverse) } : {},
351
+ owner: owner || !!join,
352
+ ...draft.foreignKey ? { foreignKeyProperty: draft.foreignKey } : {},
353
+ ...column ? { foreignKeyField: column.field } : {},
354
+ required: column?.required ?? false,
355
+ nullable: column?.nullable ?? false,
356
+ onDelete: draft.onDelete ?? (draft.kind == "many-to-many" ? "CASCADE" : "RESTRICT"),
357
+ ...join ? { joinTable: {
358
+ name: join.name,
359
+ ownerField: join.joinColumn ?? defaultJoinField(metadata.entity),
360
+ inverseField: join.inverseJoinColumn ?? defaultJoinField(target)
361
+ } } : {}
362
+ });
363
+ }
364
+ for (const join of joinTables) if (!relationDrafts.some((relation) => relation.property == join.property)) throw new InvalidMetadataError(`@JoinTable has no relation: ${join.property}`);
365
+ preliminary.set(metadata.entity, relations);
366
+ }
367
+ for (const raw of this.#metadata.values()) {
368
+ const metadata = raw;
369
+ for (const relation of preliminary.get(metadata.entity) ?? []) {
370
+ if (!relation.inverseProperty) continue;
371
+ const inverse = preliminary.get(relation.target)?.find((candidate) => candidate.property == relation.inverseProperty);
372
+ if (!inverse || inverse.target != metadata.entity) throw new InvalidMetadataError(`Invalid inverse relation ${metadata.collection}.${relation.property}`);
373
+ if (relation.kind == "many-to-many") {
374
+ if (inverse.kind != "many-to-many") throw new InvalidMetadataError("ManyToMany inverse must also be ManyToMany");
375
+ if (relation.owner && inverse.owner) throw new InvalidMetadataError("Only one ManyToMany side may declare @JoinTable");
376
+ if (!relation.owner && !inverse.owner) throw new InvalidMetadataError("One ManyToMany side must declare @JoinTable");
377
+ } else if (relation.kind == "one-to-many") {
378
+ if (inverse.kind != "many-to-one" || !inverse.owner) throw new InvalidMetadataError("OneToMany inverse must be an owning ManyToOne");
379
+ } else if (relation.kind == "one-to-one" && relation.owner == inverse.owner) throw new InvalidMetadataError("Exactly one OneToOne side must own the relation");
380
+ }
381
+ }
382
+ for (const [entity, raw] of [...this.#metadata]) {
383
+ const metadata = raw;
384
+ const relations = (preliminary.get(entity) ?? []).map((relation) => {
385
+ if (relation.kind != "many-to-many" || relation.joinTable) return relation;
386
+ const inverse = preliminary.get(relation.target).find((candidate) => candidate.property == relation.inverseProperty);
387
+ return {
388
+ ...relation,
389
+ joinTable: inverse.joinTable
390
+ };
391
+ });
392
+ this.#metadata.set(entity, new EntityMetadata({
393
+ entity: metadata.entity,
394
+ collection: metadata.collection,
395
+ primaryKey: metadata.primaryKey,
396
+ columns: metadata.columns,
397
+ indexes: metadata.indexes,
398
+ relations
399
+ }));
400
+ }
401
+ this.#finalized = true;
402
+ return this;
403
+ }
404
+ get(entity) {
405
+ const metadata = this.#metadata.get(entity);
406
+ if (!metadata) throw new EntityNotRegisteredError(entity);
407
+ return metadata;
408
+ }
409
+ has(entity) {
410
+ return this.#metadata.has(entity);
411
+ }
412
+ all() {
413
+ return Object.freeze([...this.#metadata.values()].map((metadata) => metadata));
414
+ }
415
+ get finalized() {
416
+ return this.#finalized;
417
+ }
418
+ };
419
+ // src/mapping/value-transformer.ts
420
+ var ValueTransformer = class {
421
+ toDocument(column, value) {
422
+ if (value === null) {
423
+ if (!column.nullable) throw new InvalidColumnError(`Column ${column.property} is not nullable`);
424
+ return null;
425
+ }
426
+ switch (column.type) {
427
+ case "string": return typeof value != "string" ? this.invalid(column, "string") : value;
428
+ case "number": return typeof value != "number" || !Number.isFinite(value) ? this.invalid(column, "finite number") : Object.is(value, -0) ? 0 : value;
429
+ case "boolean": return typeof value != "boolean" ? this.invalid(column, "boolean") : value;
430
+ case "date": return !(value instanceof Date) || !Number.isFinite(value.getTime()) ? this.invalid(column, "valid Date") : value.toISOString();
431
+ }
432
+ }
433
+ fromDocument(column, value) {
434
+ if (value === null) {
435
+ if (!column.nullable) throw new InvalidColumnError(`Stored column ${column.field} is not nullable`);
436
+ return null;
437
+ }
438
+ if (column.type == "date") {
439
+ if (typeof value != "string") return this.invalid(column, "canonical date string");
440
+ const date = new Date(value);
441
+ return !Number.isFinite(date.getTime()) || date.toISOString() != value ? this.invalid(column, "canonical date string") : date;
442
+ }
443
+ return this.toDocument(column, value);
444
+ }
445
+ invalid(column, expected) {
446
+ throw new InvalidColumnError(`Column ${column.property} must be a ${expected}`);
447
+ }
448
+ };
449
+ // src/mapping/entity-hydrator.ts
450
+ var EntityHydrator = class {
451
+ metadata;
452
+ transformer;
453
+ constructor(metadata, transformer = new ValueTransformer()) {
454
+ this.metadata = metadata;
455
+ this.transformer = transformer;
456
+ }
457
+ hydrate(id, document) {
458
+ const entity = Object.create(this.metadata.entity.prototype);
459
+ this.define(entity, this.metadata.primaryKey, id);
460
+ for (const column of this.metadata.columns) if (Object.hasOwn(document, column.field)) this.define(entity, column.property, this.transformer.fromDocument(column, document[column.field]));
461
+ return entity;
462
+ }
463
+ create(data) {
464
+ const entity = Object.create(this.metadata.entity.prototype);
465
+ const allowed = /* @__PURE__ */ new Set([this.metadata.primaryKey, ...this.metadata.columns.map((column) => column.property)]);
466
+ for (const key of allowed) {
467
+ const descriptor = Object.getOwnPropertyDescriptor(data, key);
468
+ if (descriptor && "value" in descriptor && descriptor.value !== void 0) this.define(entity, key, descriptor.value);
469
+ }
470
+ return entity;
471
+ }
472
+ define(target, property, value) {
473
+ Object.defineProperty(target, property, {
474
+ value,
475
+ enumerable: true,
476
+ configurable: true,
477
+ writable: true
478
+ });
479
+ }
480
+ };
481
+ // src/mapping/entity-mapper.ts
482
+ var EntityMapper = class {
483
+ metadata;
484
+ #transformer = new ValueTransformer();
485
+ #hydrator;
486
+ constructor(metadata) {
487
+ this.metadata = metadata;
488
+ this.#hydrator = new EntityHydrator(metadata, this.#transformer);
489
+ }
490
+ create(data) {
491
+ return this.#hydrator.create(data);
492
+ }
493
+ serialize(entity) {
494
+ const id = this.ownValue(entity, this.metadata.primaryKey);
495
+ if (typeof id != "string" || id.length == 0) throw new MissingPrimaryKeyError(`Primary key ${this.metadata.primaryKey} must be a non-empty string`);
496
+ const document = {};
497
+ for (const column of this.metadata.columns) {
498
+ const descriptor = Object.getOwnPropertyDescriptor(entity, column.property);
499
+ if (!descriptor || !("value" in descriptor) || descriptor.value === void 0) {
500
+ if (column.required) throw new InvalidColumnError(`Missing required column: ${column.property}`);
501
+ continue;
502
+ }
503
+ document[column.field] = this.#transformer.toDocument(column, descriptor.value);
504
+ }
505
+ return {
506
+ id,
507
+ document
508
+ };
509
+ }
510
+ hydrate(id, document) {
511
+ return this.#hydrator.hydrate(id, document);
512
+ }
513
+ ownValue(entity, property) {
514
+ const descriptor = Object.getOwnPropertyDescriptor(entity, property);
515
+ if (!descriptor || !("value" in descriptor)) return void 0;
516
+ return descriptor.value;
517
+ }
518
+ };
519
+ // src/query/query-builder.ts
520
+ var QueryBuilder = class QueryBuilder {
521
+ mapper;
522
+ executor;
523
+ collection;
524
+ state;
525
+ constructor(mapper, executor, collection, state = { orderBy: [] }) {
526
+ this.mapper = mapper;
527
+ this.executor = executor;
528
+ this.collection = collection;
529
+ this.state = state;
530
+ }
531
+ where(property, operator, ...value) {
532
+ return this.with({ where: this.mapper.comparison(property, operator, value[0]) });
533
+ }
534
+ andWhere(property, operator, ...value) {
535
+ return this.combine("and", this.mapper.comparison(property, operator, value[0]));
536
+ }
537
+ orWhere(property, operator, ...value) {
538
+ return this.combine("or", this.mapper.comparison(property, operator, value[0]));
539
+ }
540
+ andWhereGroup(where) {
541
+ return this.combine("and", this.mapper.where(where));
542
+ }
543
+ orWhereGroup(where) {
544
+ return this.combine("or", this.mapper.where(where));
545
+ }
546
+ notWhere(where) {
547
+ return this.combine("and", {
548
+ type: "not",
549
+ predicate: this.mapper.where(where)
550
+ });
551
+ }
552
+ orderBy(property, direction) {
553
+ const field = this.mapper.field(property);
554
+ return this.with({ orderBy: [...this.state.orderBy.filter((order) => order.field != field), {
555
+ field,
556
+ direction
557
+ }] });
558
+ }
559
+ select(properties) {
560
+ return this.with({ projection: properties.map((property) => {
561
+ const field = this.mapper.field(property);
562
+ if (field == "$id") throw new Error("Primary key is always selected");
563
+ return field;
564
+ }) });
565
+ }
566
+ limit(limit) {
567
+ return this.with({ limit });
568
+ }
569
+ cursor(cursor) {
570
+ return this.with({ cursor });
571
+ }
572
+ withSignal(signal) {
573
+ return this.with({ signal });
574
+ }
575
+ async getMany() {
576
+ return (await this.executor.queryRows(this.toLogicalQuery(), this.state.signal)).map(this.executor.hydrate);
577
+ }
578
+ async getOne() {
579
+ const rows = await this.executor.queryRows({
580
+ ...this.toLogicalQuery(),
581
+ limit: 1
582
+ }, this.state.signal);
583
+ return rows[0] ? this.executor.hydrate(rows[0]) : null;
584
+ }
585
+ async getCount() {
586
+ const query = this.toLogicalQuery();
587
+ return this.executor.count({
588
+ collection: query.collection,
589
+ ...query.where ? { where: query.where } : {}
590
+ }, this.state.signal);
591
+ }
592
+ async getPage() {
593
+ const page = await this.executor.queryPage(this.toLogicalQuery(), this.state.signal);
594
+ return {
595
+ items: page.rows.map(this.executor.hydrate),
596
+ nextCursor: page.nextCursor
597
+ };
598
+ }
599
+ explain() {
600
+ return this.executor.explain(this.toLogicalQuery());
601
+ }
602
+ toLogicalQuery() {
603
+ return {
604
+ collection: this.collection,
605
+ ...this.state.where ? { where: this.state.where } : {},
606
+ ...this.state.orderBy.length ? { orderBy: this.state.orderBy } : {},
607
+ ...this.state.projection ? { projection: this.state.projection } : {},
608
+ ...this.state.limit == null ? {} : { limit: this.state.limit },
609
+ ...this.state.cursor == null ? {} : { cursor: this.state.cursor }
610
+ };
611
+ }
612
+ combine(type, predicate) {
613
+ return this.with({ where: this.state.where ? {
614
+ type,
615
+ predicates: [this.state.where, predicate]
616
+ } : predicate });
617
+ }
618
+ with(changes) {
619
+ return new QueryBuilder(this.mapper, this.executor, this.collection, {
620
+ ...this.state,
621
+ ...changes
622
+ });
623
+ }
624
+ };
625
+ // src/query/query-mapper.ts
626
+ var OPERATORS = /* @__PURE__ */ new Set([
627
+ "eq",
628
+ "ne",
629
+ "gt",
630
+ "gte",
631
+ "lt",
632
+ "lte",
633
+ "in",
634
+ "isNull",
635
+ "isMissing"
636
+ ]);
637
+ function isRecord(value) {
638
+ return typeof value == "object" && value != null && !Array.isArray(value) && !(value instanceof Date);
639
+ }
640
+ var QueryMapper = class {
641
+ metadata;
642
+ constructor(metadata) {
643
+ this.metadata = metadata;
644
+ }
645
+ map(options = {}) {
646
+ if (options.limit != null && (!Number.isSafeInteger(options.limit) || options.limit < 0 || options.limit > 1e6)) throw new InvalidQueryError("Invalid query limit");
647
+ if (options.projection?.length == 0) throw new InvalidQueryError("Projection cannot be empty");
648
+ if (options.cursor != null && (options.cursor.length == 0 || options.cursor.length > 16384)) throw new InvalidQueryError("Invalid query cursor");
649
+ const where = options.where ? this.where(options.where) : void 0;
650
+ const orderBy = [];
651
+ for (const [property, direction] of Object.entries(options.orderBy ?? {})) {
652
+ if (direction !== "ASC" && direction !== "DESC") throw new InvalidQueryError(`Invalid order for ${property}`);
653
+ orderBy.push({
654
+ field: this.field(property),
655
+ direction
656
+ });
657
+ }
658
+ const projection = options.projection?.map((property) => {
659
+ const field = this.field(property);
660
+ if (field == "$id") throw new InvalidQueryError("Primary key is always returned separately");
661
+ return field;
662
+ });
663
+ return {
664
+ collection: this.metadata.collection,
665
+ ...where == null ? {} : { where },
666
+ ...orderBy.length == 0 ? {} : { orderBy },
667
+ ...projection == null ? {} : { projection },
668
+ ...options.limit == null ? {} : { limit: options.limit },
669
+ ...options.cursor == null ? {} : { cursor: options.cursor }
670
+ };
671
+ }
672
+ where(where) {
673
+ if (!isRecord(where)) throw new InvalidQueryError("Where clause must be an object");
674
+ const predicates = [];
675
+ for (const [property, condition] of Object.entries(where)) if (property == "AND" || property == "OR") {
676
+ if (!Array.isArray(condition) || condition.length == 0) throw new InvalidQueryError(`${property} requires at least one predicate`);
677
+ predicates.push({
678
+ type: property == "AND" ? "and" : "or",
679
+ predicates: condition.map((item) => this.where(item))
680
+ });
681
+ } else if (property == "NOT") predicates.push({
682
+ type: "not",
683
+ predicate: this.where(condition)
684
+ });
685
+ else predicates.push(...this.condition(property, condition));
686
+ if (predicates.length == 0) throw new InvalidQueryError("Where clause cannot be empty");
687
+ return predicates.length == 1 ? predicates[0] : {
688
+ type: "and",
689
+ predicates
690
+ };
691
+ }
692
+ comparison(property, operator, value) {
693
+ const field = this.field(property);
694
+ if ([
695
+ "eq",
696
+ "ne",
697
+ "gt",
698
+ "gte",
699
+ "lt",
700
+ "lte"
701
+ ].includes(operator)) return {
702
+ type: "comparison",
703
+ field,
704
+ operator,
705
+ value: this.scalar(property, value)
706
+ };
707
+ if (operator == "in") {
708
+ if (!Array.isArray(value) || value.length == 0) throw new InvalidQueryError(`IN on ${property} requires a non-empty array`);
709
+ return {
710
+ type: "in",
711
+ field,
712
+ values: value.map((item) => this.scalar(property, item))
713
+ };
714
+ }
715
+ if (operator == "isNull" || operator == "isMissing") return {
716
+ type: operator,
717
+ field
718
+ };
719
+ throw new InvalidQueryError(`Unknown query operator: ${operator}`);
720
+ }
721
+ field(property) {
722
+ if (property == this.metadata.primaryKey) return "$id";
723
+ const column = this.metadata.columnForProperty(property);
724
+ if (!column) throw new InvalidQueryError(`Unknown entity property: ${property}`);
725
+ return column.field;
726
+ }
727
+ condition(property, condition) {
728
+ this.field(property);
729
+ if (!isRecord(condition)) return [this.comparison(property, "eq", condition)];
730
+ const entries = Object.entries(condition);
731
+ if (entries.length == 0) throw new InvalidQueryError(`Empty condition for ${property}`);
732
+ return entries.map(([operator, value]) => {
733
+ if (!OPERATORS.has(operator)) throw new InvalidQueryError(`Unknown query operator: ${operator}`);
734
+ if ((operator == "isNull" || operator == "isMissing") && value !== true) throw new InvalidQueryError(`${operator} must be true`);
735
+ return this.comparison(property, operator, value);
736
+ });
737
+ }
738
+ scalar(property, value) {
739
+ if (property == this.metadata.primaryKey) {
740
+ if (typeof value == "string") return value;
741
+ throw new InvalidQueryError("Primary-key comparisons require a string");
742
+ }
743
+ const column = this.metadata.columnForProperty(property);
744
+ if (!column) throw new InvalidQueryError(`Unknown entity property: ${property}`);
745
+ if (value === null) {
746
+ if (column.nullable) return null;
747
+ throw new InvalidQueryError(`Column ${property} is not nullable`);
748
+ }
749
+ if (column.type == "date" && value instanceof Date && Number.isFinite(value.getTime())) return value;
750
+ if (column.type == "string" && typeof value == "string") return value;
751
+ if (column.type == "boolean" && typeof value == "boolean") return value;
752
+ if (column.type == "number" && typeof value == "number" && Number.isFinite(value)) return value;
753
+ throw new InvalidQueryError(`Invalid query value for ${property}`);
754
+ }
755
+ };
756
+ // src/relations/relation-loader.ts
757
+ var BATCH_SIZE = 64;
758
+ var MAX_DEPTH = 8;
759
+ var MAX_RELATED_ENTITIES = 1e5;
760
+ var RelationLoader = class {
761
+ metadata;
762
+ runtime;
763
+ #loaded = 0;
764
+ constructor(metadata, runtime) {
765
+ this.metadata = metadata;
766
+ this.runtime = runtime;
767
+ }
768
+ async load(entities, requested, signal) {
769
+ if (!requested || entities.length == 0) return entities;
770
+ await this.loadLevel(this.metadata, entities, requested, signal, 0, /* @__PURE__ */ new Set());
771
+ return entities;
772
+ }
773
+ async loadLevel(metadata, entities, requested, signal, depth, path) {
774
+ if (depth >= MAX_DEPTH) throw new Error(`Relation depth exceeds ${MAX_DEPTH}`);
775
+ for (const [property, nested] of Object.entries(requested)) {
776
+ if (!nested) continue;
777
+ signal?.throwIfAborted();
778
+ const relation = metadata.relationForProperty(property);
779
+ if (!relation) throw new Error(`Unknown relation: ${metadata.collection}.${property}`);
780
+ const edge = `${metadata.collection}.${property}`;
781
+ if (path.has(edge)) continue;
782
+ const related = await this.loadRelation(metadata, entities, relation, signal);
783
+ this.#loaded += related.length;
784
+ if (this.#loaded > MAX_RELATED_ENTITIES) throw new Error("Related entity expansion limit exceeded");
785
+ if (nested !== true && related.length) {
786
+ const target = this.runtime.registry.get(relation.target);
787
+ await this.loadLevel(target, related, nested, signal, depth + 1, /* @__PURE__ */ new Set([...path, edge]));
788
+ }
789
+ }
790
+ }
791
+ async loadRelation(metadata, entities, relation, signal) {
792
+ const target = this.runtime.registry.get(relation.target);
793
+ const targetMapper = new EntityMapper(target);
794
+ const related = /* @__PURE__ */ new Map();
795
+ if (relation.kind == "many-to-one" || relation.kind == "one-to-one" && relation.owner) {
796
+ const ids = this.values(entities, relation.foreignKeyProperty);
797
+ for (const row of await this.byIds(target.collection, ids, signal)) related.set(row.id, targetMapper.hydrate(row.id, row.document));
798
+ for (const entity of entities) {
799
+ const id = this.value(entity, relation.foreignKeyProperty);
800
+ this.define(entity, relation.property, typeof id == "string" ? related.get(id) ?? null : null);
801
+ }
802
+ return [...related.values()];
803
+ }
804
+ if (relation.kind == "one-to-many" || relation.kind == "one-to-one") {
805
+ const inverse = target.relationForProperty(relation.inverseProperty);
806
+ if (!inverse?.foreignKeyField) throw new Error(`Relation ${metadata.collection}.${relation.property} has no owning inverse`);
807
+ const ownerIds = this.values(entities, metadata.primaryKey);
808
+ const rows = await this.queryBatches(target.collection, inverse.foreignKeyField, ownerIds, signal);
809
+ const groups = /* @__PURE__ */ new Map();
810
+ for (const row of rows) {
811
+ const entity = targetMapper.hydrate(row.id, row.document);
812
+ related.set(row.id, entity);
813
+ const owner = row.document[inverse.foreignKeyField];
814
+ if (typeof owner == "string") groups.set(owner, [...groups.get(owner) ?? [], entity]);
815
+ }
816
+ for (const entity of entities) {
817
+ const id = this.value(entity, metadata.primaryKey);
818
+ const matches = typeof id == "string" ? groups.get(id) ?? [] : [];
819
+ this.define(entity, relation.property, relation.kind == "one-to-many" ? matches : matches[0] ?? null);
820
+ }
821
+ return [...related.values()];
822
+ }
823
+ const join = relation.joinTable;
824
+ const localField = relation.owner ? join.ownerField : join.inverseField;
825
+ const remoteField = relation.owner ? join.inverseField : join.ownerField;
826
+ const ownerIds = this.values(entities, metadata.primaryKey);
827
+ const junctions = await this.queryBatches(join.name, localField, ownerIds, signal);
828
+ const remoteIds = /* @__PURE__ */ new Set();
829
+ for (const row of junctions) {
830
+ const id = row.document[remoteField];
831
+ if (typeof id == "string") remoteIds.add(id);
832
+ }
833
+ for (const row of await this.byIds(target.collection, remoteIds, signal)) related.set(row.id, targetMapper.hydrate(row.id, row.document));
834
+ const groups = /* @__PURE__ */ new Map();
835
+ for (const row of junctions) {
836
+ const local = row.document[localField];
837
+ const remote = row.document[remoteField];
838
+ const entity = typeof remote == "string" ? related.get(remote) : void 0;
839
+ if (typeof local == "string" && entity) groups.set(local, [...groups.get(local) ?? [], entity]);
840
+ }
841
+ for (const entity of entities) {
842
+ const id = this.value(entity, metadata.primaryKey);
843
+ this.define(entity, relation.property, typeof id == "string" ? groups.get(id) ?? [] : []);
844
+ }
845
+ return [...related.values()];
846
+ }
847
+ byIds(collection, ids, signal) {
848
+ return this.queryBatches(collection, "$id", ids, signal);
849
+ }
850
+ async queryBatches(collection, field, values, signal) {
851
+ const all = [...values];
852
+ const rows = [];
853
+ for (let offset = 0; offset < all.length; offset += BATCH_SIZE) {
854
+ signal?.throwIfAborted();
855
+ const batch = all.slice(offset, offset + BATCH_SIZE);
856
+ if (!batch.length) continue;
857
+ const query = {
858
+ collection,
859
+ where: {
860
+ type: "in",
861
+ field,
862
+ values: batch
863
+ }
864
+ };
865
+ const source = this.runtime.transaction ? this.runtime.transaction.query(query, { signal }) : this.runtime.database.query(query, { signal });
866
+ for await (const row of source) rows.push(row);
867
+ }
868
+ return rows;
869
+ }
870
+ values(entities, property) {
871
+ const result = /* @__PURE__ */ new Set();
872
+ for (const entity of entities) {
873
+ const value = this.value(entity, property);
874
+ if (typeof value == "string") result.add(value);
875
+ }
876
+ return result;
877
+ }
878
+ value(entity, property) {
879
+ const descriptor = Object.getOwnPropertyDescriptor(entity, property);
880
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
881
+ }
882
+ define(entity, property, value) {
883
+ Object.defineProperty(entity, property, {
884
+ value,
885
+ enumerable: true,
886
+ configurable: true,
887
+ writable: true
888
+ });
889
+ }
890
+ };
891
+ // src/relations/relation-operations.ts
892
+ function associationId(ownerId, inverseId) {
893
+ return createHash("sha256").update(JSON.stringify([ownerId, inverseId])).digest("hex");
894
+ }
895
+ var RelationOperations = class {
896
+ metadata;
897
+ relation;
898
+ write;
899
+ constructor(metadata, relation, write) {
900
+ this.metadata = metadata;
901
+ this.relation = relation;
902
+ this.write = write;
903
+ if (relation.kind != "many-to-many" || !relation.joinTable) throw new Error(`Relation ${metadata.collection}.${relation.property} is not ManyToMany`);
904
+ }
905
+ async add(sourceId, targetId) {
906
+ await this.write(async (tx) => {
907
+ if (!await tx.getDocument(this.metadata.collection, sourceId)) throw new RecordNotFoundError(`Record not found: ${this.metadata.collection}/${sourceId}`);
908
+ if (!await tx.getDocument(this.relation.targetCollection, targetId)) throw new RecordNotFoundError(`Record not found: ${this.relation.targetCollection}/${targetId}`);
909
+ const join = this.relation.joinTable;
910
+ const ownerId = this.relation.owner ? sourceId : targetId;
911
+ const inverseId = this.relation.owner ? targetId : sourceId;
912
+ const id = associationId(ownerId, inverseId);
913
+ if (await tx.getDocument(join.name, id)) throw new DuplicateRecordError(`Relation already exists: ${join.name}/${id}`);
914
+ tx.putDocument(join.name, id, {
915
+ [join.ownerField]: ownerId,
916
+ [join.inverseField]: inverseId
917
+ });
918
+ });
919
+ }
920
+ async remove(sourceId, targetId) {
921
+ let removed = false;
922
+ await this.write(async (tx) => {
923
+ const id = associationId(this.relation.owner ? sourceId : targetId, this.relation.owner ? targetId : sourceId);
924
+ if (!await tx.getDocument(this.relation.joinTable.name, id)) return;
925
+ tx.deleteDocument(this.relation.joinTable.name, id);
926
+ removed = true;
927
+ });
928
+ return removed;
929
+ }
930
+ };
931
+ // src/repository/repository.ts
932
+ var Repository = class {
933
+ metadata;
934
+ runtime;
935
+ #entityMapper;
936
+ #queryMapper;
937
+ constructor(metadata, runtime) {
938
+ this.metadata = metadata;
939
+ this.runtime = runtime;
940
+ this.#entityMapper = new EntityMapper(metadata);
941
+ this.#queryMapper = new QueryMapper(metadata);
942
+ }
943
+ create(data) {
944
+ this.runtime.assertUsable();
945
+ return this.#entityMapper.create(data);
946
+ }
947
+ async insert(entity) {
948
+ this.runtime.assertUsable();
949
+ const serialized = this.#entityMapper.serialize(entity);
950
+ await this.write(async (tx) => {
951
+ if (await tx.getDocument(this.metadata.collection, serialized.id) != null) throw new DuplicateRecordError(`Record already exists: ${this.metadata.collection}/${serialized.id}`);
952
+ tx.putDocument(this.metadata.collection, serialized.id, serialized.document);
953
+ });
954
+ return entity;
955
+ }
956
+ save(entity) {
957
+ return this.upsert(entity);
958
+ }
959
+ async update(id, changes) {
960
+ this.runtime.assertUsable();
961
+ let updated;
962
+ await this.write(async (tx) => {
963
+ const document = await tx.getDocument(this.metadata.collection, id);
964
+ if (!document) throw new RecordNotFoundError(`Record not found: ${this.metadata.collection}/${id}`);
965
+ const entity = this.#entityMapper.hydrate(id, document);
966
+ const primaryChange = Object.getOwnPropertyDescriptor(changes, this.metadata.primaryKey);
967
+ if (primaryChange && "value" in primaryChange && primaryChange.value !== void 0 && primaryChange.value !== id) throw new InvalidColumnError("Primary key cannot be changed by update()");
968
+ for (const column of this.metadata.columns) {
969
+ const descriptor = Object.getOwnPropertyDescriptor(changes, column.property);
970
+ if (descriptor && "value" in descriptor && descriptor.value !== void 0) Object.defineProperty(entity, column.property, {
971
+ value: descriptor.value,
972
+ enumerable: true,
973
+ configurable: true,
974
+ writable: true
975
+ });
976
+ }
977
+ const serialized = this.#entityMapper.serialize(entity);
978
+ tx.putDocument(this.metadata.collection, id, serialized.document);
979
+ updated = entity;
980
+ });
981
+ if (!updated) throw new Error("Update completed without an entity result");
982
+ return updated;
983
+ }
984
+ async upsert(entity) {
985
+ this.runtime.assertUsable();
986
+ const serialized = this.#entityMapper.serialize(entity);
987
+ await this.write((tx) => {
988
+ tx.putDocument(this.metadata.collection, serialized.id, serialized.document);
989
+ });
990
+ return entity;
991
+ }
992
+ async delete(id) {
993
+ this.runtime.assertUsable();
994
+ let deleted = false;
995
+ await this.write(async (tx) => {
996
+ if (await tx.getDocument(this.metadata.collection, id) == null) return;
997
+ tx.deleteDocument(this.metadata.collection, id);
998
+ deleted = true;
999
+ });
1000
+ return deleted;
1001
+ }
1002
+ async findById(id, options = {}) {
1003
+ this.runtime.assertUsable();
1004
+ if (this.runtime.transaction) {
1005
+ const document = await this.runtime.transaction.getDocument(this.metadata.collection, id);
1006
+ if (!document) return null;
1007
+ const entity = this.#entityMapper.hydrate(id, document);
1008
+ await this.loadRelations([entity], options.relations, options.signal);
1009
+ return entity;
1010
+ }
1011
+ const row = (await this.runtime.database.queryPage({
1012
+ collection: this.metadata.collection,
1013
+ where: {
1014
+ type: "comparison",
1015
+ field: "$id",
1016
+ operator: "eq",
1017
+ value: id
1018
+ },
1019
+ limit: 1
1020
+ }, { signal: options.signal })).rows[0];
1021
+ if (!row) return null;
1022
+ const entity = this.#entityMapper.hydrate(row.id, row.document);
1023
+ await this.loadRelations([entity], options.relations, options.signal);
1024
+ return entity;
1025
+ }
1026
+ async findOne(options = {}) {
1027
+ const rows = await this.queryRows({
1028
+ ...this.mapFind(options),
1029
+ limit: 1
1030
+ }, options.signal);
1031
+ if (!rows[0]) return null;
1032
+ const entity = this.hydrate(rows[0]);
1033
+ await this.loadRelations([entity], options.relations, options.signal);
1034
+ return entity;
1035
+ }
1036
+ async find(options = {}) {
1037
+ const entities = (await this.queryRows(this.mapFind(options), options.signal)).map((row) => this.hydrate(row));
1038
+ await this.loadRelations(entities, options.relations, options.signal);
1039
+ return entities;
1040
+ }
1041
+ async findPage(options) {
1042
+ const page = await this.queryPage(this.mapFind(options), options.signal);
1043
+ const items = page.rows.map((row) => this.hydrate(row));
1044
+ await this.loadRelations(items, options.relations, options.signal);
1045
+ return {
1046
+ items,
1047
+ nextCursor: page.nextCursor
1048
+ };
1049
+ }
1050
+ async exists(options = {}) {
1051
+ return await this.findOne(options) != null;
1052
+ }
1053
+ async count(options = {}) {
1054
+ const query = this.#queryMapper.map(options);
1055
+ let count = 0;
1056
+ for await (const _row of this.sourceQuery(query, options.signal)) count++;
1057
+ return count;
1058
+ }
1059
+ createQueryBuilder() {
1060
+ this.runtime.assertUsable();
1061
+ return new QueryBuilder(this.#queryMapper, {
1062
+ queryRows: (query, signal) => this.queryRows(query, signal),
1063
+ queryPage: (query, signal) => this.queryPage(query, signal),
1064
+ count: async (query, signal) => {
1065
+ let count = 0;
1066
+ for await (const _row of this.sourceQuery(query, signal)) count++;
1067
+ return count;
1068
+ },
1069
+ hydrate: (row) => this.hydrate(row),
1070
+ explain: (query) => this.runtime.database.explain(query)
1071
+ }, this.metadata.collection);
1072
+ }
1073
+ relations(property) {
1074
+ this.runtime.assertUsable();
1075
+ const relation = this.metadata.relationForProperty(property);
1076
+ if (!relation) throw new Error(`Unknown relation: ${this.metadata.collection}.${property}`);
1077
+ return new RelationOperations(this.metadata, relation, (action) => this.write(action));
1078
+ }
1079
+ hydrate(row) {
1080
+ return this.#entityMapper.hydrate(row.id, row.document);
1081
+ }
1082
+ loadRelations(entities, relations, signal) {
1083
+ return new RelationLoader(this.metadata, this.runtime).load(entities, relations, signal);
1084
+ }
1085
+ mapFind(options) {
1086
+ const query = this.#queryMapper.map(options);
1087
+ if (!query.projection || !options.relations) return query;
1088
+ const projection = new Set(query.projection);
1089
+ for (const [property, enabled] of Object.entries(options.relations)) {
1090
+ if (!enabled) continue;
1091
+ const relation = this.metadata.relationForProperty(property);
1092
+ if (relation?.owner && relation.foreignKeyField) projection.add(relation.foreignKeyField);
1093
+ }
1094
+ return {
1095
+ ...query,
1096
+ projection: [...projection]
1097
+ };
1098
+ }
1099
+ async queryRows(query, signal) {
1100
+ this.runtime.assertUsable();
1101
+ const rows = [];
1102
+ for await (const row of this.sourceQuery(query, signal)) rows.push(row);
1103
+ return rows;
1104
+ }
1105
+ queryPage(query, signal) {
1106
+ this.runtime.assertUsable();
1107
+ return this.runtime.transaction ? this.runtime.transaction.queryPage(query, { signal }) : this.runtime.database.queryPage(query, { signal });
1108
+ }
1109
+ sourceQuery(query, signal) {
1110
+ this.runtime.assertUsable();
1111
+ return this.runtime.transaction ? this.runtime.transaction.query(query, { signal }) : this.runtime.database.query(query, { signal });
1112
+ }
1113
+ async write(action) {
1114
+ try {
1115
+ if (this.runtime.transaction) await action(this.runtime.transaction);
1116
+ else await this.runtime.database.transaction(action);
1117
+ } catch (cause) {
1118
+ if (cause instanceof UniqueIndexViolationError) throw new UniqueIndexViolationOrmError(cause.message, cause);
1119
+ throw cause;
1120
+ }
1121
+ }
1122
+ };
1123
+ // src/schema/schema-mapper.ts
1124
+ function mapEntitySchema(metadata) {
1125
+ const relationIndexes = metadata.relations.filter((relation) => relation.kind == "one-to-one" && relation.owner).map((relation) => ({
1126
+ name: `unique_${relation.property}`,
1127
+ unique: true,
1128
+ fields: [{
1129
+ field: relation.foreignKeyField,
1130
+ order: "ASC"
1131
+ }]
1132
+ }));
1133
+ return {
1134
+ name: metadata.collection,
1135
+ fields: Object.fromEntries(metadata.columns.map((column) => [column.field, {
1136
+ type: column.type,
1137
+ required: column.required,
1138
+ nullable: column.nullable
1139
+ }])),
1140
+ allowAdditionalFields: false,
1141
+ indexes: [...metadata.indexes.map((index) => ({
1142
+ name: index.name,
1143
+ unique: index.unique,
1144
+ fields: index.fields.map((field) => ({
1145
+ field: field.field,
1146
+ order: field.order
1147
+ }))
1148
+ })), ...relationIndexes],
1149
+ foreignKeys: metadata.relations.filter((relation) => relation.owner && relation.foreignKeyField).map((relation) => ({
1150
+ name: relation.property,
1151
+ field: relation.foreignKeyField,
1152
+ references: {
1153
+ collection: relation.targetCollection,
1154
+ field: "$id"
1155
+ },
1156
+ onDelete: relation.onDelete
1157
+ }))
1158
+ };
1159
+ }
1160
+ function mapJunctionSchemas(metadata) {
1161
+ const schemas = /* @__PURE__ */ new Map();
1162
+ for (const entity of metadata) for (const relation of entity.relations) {
1163
+ if (relation.kind != "many-to-many" || !relation.owner || !relation.joinTable) continue;
1164
+ const join = relation.joinTable;
1165
+ if (join.ownerField == join.inverseField) throw new Error(`Join table ${join.name} uses the same field for both sides`);
1166
+ if (schemas.has(join.name)) throw new Error(`Duplicate join table: ${join.name}`);
1167
+ schemas.set(join.name, {
1168
+ name: join.name,
1169
+ fields: {
1170
+ [join.ownerField]: {
1171
+ type: "string",
1172
+ required: true,
1173
+ nullable: false
1174
+ },
1175
+ [join.inverseField]: {
1176
+ type: "string",
1177
+ required: true,
1178
+ nullable: false
1179
+ }
1180
+ },
1181
+ allowAdditionalFields: false,
1182
+ indexes: [
1183
+ {
1184
+ name: "owner",
1185
+ unique: false,
1186
+ field: join.ownerField
1187
+ },
1188
+ {
1189
+ name: "inverse",
1190
+ unique: false,
1191
+ field: join.inverseField
1192
+ },
1193
+ {
1194
+ name: "pair",
1195
+ unique: true,
1196
+ fields: [{
1197
+ field: join.ownerField,
1198
+ order: "ASC"
1199
+ }, {
1200
+ field: join.inverseField,
1201
+ order: "ASC"
1202
+ }]
1203
+ }
1204
+ ],
1205
+ foreignKeys: [{
1206
+ name: "owner",
1207
+ field: join.ownerField,
1208
+ references: {
1209
+ collection: entity.collection,
1210
+ field: "$id"
1211
+ },
1212
+ onDelete: "CASCADE"
1213
+ }, {
1214
+ name: "inverse",
1215
+ field: join.inverseField,
1216
+ references: {
1217
+ collection: relation.targetCollection,
1218
+ field: "$id"
1219
+ },
1220
+ onDelete: "CASCADE"
1221
+ }]
1222
+ });
1223
+ }
1224
+ return [...schemas.values()];
1225
+ }
1226
+ // src/schema/schema-manager.ts
1227
+ function same(left, right) {
1228
+ return JSON.stringify(left) == JSON.stringify(right);
1229
+ }
1230
+ function indexMap(definition) {
1231
+ return new Map(definition.indexes.map((index) => [index.name, index]));
1232
+ }
1233
+ var SchemaManager = class {
1234
+ database;
1235
+ registry;
1236
+ mode;
1237
+ constructor(database, registry, mode) {
1238
+ this.database = database;
1239
+ this.registry = registry;
1240
+ this.mode = mode;
1241
+ }
1242
+ async initialize() {
1243
+ const persisted = new Map((await this.database.getCollectionDefinitions()).map((definition) => [definition.name, normalizeCollection(definition)]));
1244
+ const expectedSchemas = [...this.registry.all().map((metadata) => mapEntitySchema(metadata)), ...mapJunctionSchemas(this.registry.all())].map((schema) => normalizeCollection(schema));
1245
+ const missing = expectedSchemas.filter((schema) => !persisted.has(schema.name));
1246
+ if (missing.length && this.mode == "validate") throw new SchemaViolationError(`Missing collection: ${missing[0].name}`);
1247
+ if (missing.length) {
1248
+ await this.mutate(() => this.database.defineCollections(missing), `Could not create collections: ${missing.map((schema) => schema.name).join(", ")}`);
1249
+ for (const schema of missing) persisted.set(schema.name, schema);
1250
+ }
1251
+ for (const expected of expectedSchemas) {
1252
+ const current = persisted.get(expected.name);
1253
+ if (!current) throw new SchemaViolationError(`Missing collection: ${expected.name}`);
1254
+ this.validateFields(expected, current);
1255
+ if (!same(expected.foreignKeys ?? [], current.foreignKeys ?? [])) throw new SchemaViolationError(`Incompatible foreign keys: ${expected.name}`);
1256
+ const actualIndexes = indexMap(current);
1257
+ for (const expectedIndex of expected.indexes) {
1258
+ const actual = actualIndexes.get(expectedIndex.name);
1259
+ if (!actual) {
1260
+ if (this.mode == "validate") throw new SchemaViolationError(`Missing index: ${expected.name}/${expectedIndex.name}`);
1261
+ await this.mutate(() => this.database.addIndex(expected.name, expectedIndex), `Could not create index: ${expected.name}/${expectedIndex.name}`);
1262
+ continue;
1263
+ }
1264
+ if (!same(actual, expectedIndex)) throw new SchemaViolationError(`Incompatible index: ${expected.name}/${expectedIndex.name}`);
1265
+ }
1266
+ }
1267
+ }
1268
+ validateFields(expected, actual) {
1269
+ if (expected.allowAdditionalFields != actual.allowAdditionalFields || !same(expected.fields ?? {}, actual.fields ?? {})) throw new SchemaViolationError(`Incompatible collection schema: ${expected.name}`);
1270
+ }
1271
+ async mutate(operation, message) {
1272
+ try {
1273
+ await operation();
1274
+ } catch (cause) {
1275
+ if (cause instanceof TransactionConflictError$1 || cause instanceof CommitOutcomeUnknownError$1 || cause instanceof SchemaViolationError) throw cause;
1276
+ throw new SchemaViolationError(message, { cause });
1277
+ }
1278
+ }
1279
+ };
1280
+ // src/transactions/orm-transaction.ts
1281
+ var OrmTransactionManager = class {
1282
+ database;
1283
+ transaction;
1284
+ registry;
1285
+ #repositories = /* @__PURE__ */ new Map();
1286
+ #active = true;
1287
+ constructor(database, transaction, registry) {
1288
+ this.database = database;
1289
+ this.transaction = transaction;
1290
+ this.registry = registry;
1291
+ }
1292
+ getRepository(entity) {
1293
+ this.assertActive();
1294
+ const cached = this.#repositories.get(entity);
1295
+ if (cached) return cached;
1296
+ const repository = new Repository(this.registry.get(entity), {
1297
+ database: this.database,
1298
+ transaction: this.transaction,
1299
+ registry: this.registry,
1300
+ assertUsable: () => this.assertActive()
1301
+ });
1302
+ this.#repositories.set(entity, repository);
1303
+ return repository;
1304
+ }
1305
+ close() {
1306
+ this.#active = false;
1307
+ this.#repositories.clear();
1308
+ }
1309
+ assertActive() {
1310
+ if (!this.#active) throw new TransactionManagerClosedError();
1311
+ }
1312
+ };
1313
+ // src/database/duraxis-orm.ts
1314
+ var DuraxisORM = class {
1315
+ options;
1316
+ #registry;
1317
+ #repositories = /* @__PURE__ */ new Map();
1318
+ #lifecycle = "new";
1319
+ #initialization;
1320
+ constructor(options) {
1321
+ this.options = options;
1322
+ this.#registry = new MetadataRegistry(options.entities).finalize();
1323
+ }
1324
+ initialize() {
1325
+ if (this.#lifecycle == "closed") return Promise.reject(new OrmClosedError());
1326
+ if (this.#lifecycle == "initialized") return Promise.resolve();
1327
+ if (this.#initialization) return this.#initialization;
1328
+ this.#lifecycle = "initializing";
1329
+ this.#initialization = (async () => {
1330
+ try {
1331
+ await new SchemaManager(this.options.database, this.#registry, this.options.schema?.mode ?? "validate").initialize();
1332
+ if (this.#lifecycle == "closed") throw new OrmClosedError();
1333
+ this.#lifecycle = "initialized";
1334
+ } catch (error) {
1335
+ if (this.#lifecycle != "closed") this.#lifecycle = "new";
1336
+ this.#initialization = void 0;
1337
+ throw error;
1338
+ }
1339
+ })();
1340
+ return this.#initialization;
1341
+ }
1342
+ getRepository(entity) {
1343
+ this.assertReady();
1344
+ const cached = this.#repositories.get(entity);
1345
+ if (cached) return cached;
1346
+ const repository = new Repository(this.#registry.get(entity), {
1347
+ database: this.options.database,
1348
+ registry: this.#registry,
1349
+ assertUsable: () => this.assertReady()
1350
+ });
1351
+ this.#repositories.set(entity, repository);
1352
+ return repository;
1353
+ }
1354
+ async transaction(callback) {
1355
+ this.assertReady();
1356
+ try {
1357
+ return await this.options.database.transaction(async (transaction) => {
1358
+ const manager = new OrmTransactionManager(this.options.database, transaction, this.#registry);
1359
+ try {
1360
+ return await callback(manager);
1361
+ } finally {
1362
+ manager.close();
1363
+ }
1364
+ });
1365
+ } catch (cause) {
1366
+ if (cause instanceof UniqueIndexViolationError) throw new UniqueIndexViolationOrmError(cause.message, cause);
1367
+ throw cause;
1368
+ }
1369
+ }
1370
+ async close() {
1371
+ if (this.#lifecycle == "closed") return;
1372
+ const initialization = this.#initialization;
1373
+ if (initialization) await initialization.catch(() => void 0);
1374
+ this.#lifecycle = "closed";
1375
+ this.#repositories.clear();
1376
+ if (this.options.closeDatabase || this.options.closeStorage) await this.options.database.close({ closeStorage: this.options.closeStorage ?? false });
1377
+ }
1378
+ get metadata() {
1379
+ return this.#registry;
1380
+ }
1381
+ assertReady() {
1382
+ if (this.#lifecycle == "closed") throw new OrmClosedError();
1383
+ if (this.#lifecycle != "initialized") throw new OrmNotInitializedError();
1384
+ }
1385
+ };
1386
+ export { Column, CommitOutcomeUnknownError, DuplicateRecordError, DuraxisORM, DuraxisOrmError, Entity, EntityHydrator, EntityMapper, EntityMetadata, EntityNotRegisteredError, Index, InvalidColumnError, InvalidMetadataError, InvalidQueryError, JoinTable, ManyToMany, ManyToOne, MetadataRegistry, MissingPrimaryKeyError, OneToMany, OneToOne, OrmClosedError, OrmNotInitializedError, OrmTransactionManager, PrimaryKey, QueryBuilder, RecordNotFoundError, RelationLoader, RelationOperations, Repository, SchemaManager, SchemaViolationError, TransactionConflictError, TransactionManagerClosedError, UniqueIndexViolationOrmError, ValueTransformer };
1387
+
1388
+ //# sourceMappingURL=index.js.map