@mikro-orm/core 7.0.0-dev.66 → 7.0.0-dev.67

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.
@@ -1,5 +1,5 @@
1
- import type { EntityDTO, EntityKey, FilterQuery, Loaded, LoadedCollection, Populate } from '../typings.js';
2
- import { ArrayCollection } from './ArrayCollection.js';
1
+ import { inspect } from 'node:util';
2
+ import type { EntityDTO, EntityKey, EntityProperty, FilterQuery, IPrimaryKey, Loaded, LoadedCollection, Populate, Primary } from '../typings.js';
3
3
  import { Reference } from './Reference.js';
4
4
  import type { Transaction } from '../connections/Connection.js';
5
5
  import type { CountOptions, FindOptions } from '../drivers/IDatabaseDriver.js';
@@ -9,10 +9,18 @@ export interface MatchingOptions<T extends object, P extends string = never> ext
9
9
  store?: boolean;
10
10
  ctx?: Transaction;
11
11
  }
12
- export declare class Collection<T extends object, O extends object = object> extends ArrayCollection<T, O> {
12
+ export declare class Collection<T extends object, O extends object = object> {
13
+ readonly owner: O;
14
+ [k: number]: T;
15
+ protected readonly items: Set<T>;
16
+ protected initialized: boolean;
17
+ protected dirty: boolean;
18
+ protected partial: boolean;
19
+ protected snapshot: T[] | undefined;
13
20
  private readonly?;
21
+ protected _count?: number;
22
+ private _property?;
14
23
  private _populated?;
15
- private _snapshot?;
16
24
  constructor(owner: O, items?: T[], initialized?: boolean);
17
25
  /**
18
26
  * Creates new Collection instance, assigns it to the owning entity and sets the items to it (propagating them to their inverse sides)
@@ -41,57 +49,117 @@ export declare class Collection<T extends object, O extends object = object> ext
41
49
  toJSON<TT extends T>(): EntityDTO<TT>[];
42
50
  add<TT extends T>(entity: TT | Reference<TT> | Iterable<TT | Reference<TT>>, ...entities: (TT | Reference<TT>)[]): number;
43
51
  /**
44
- * @inheritDoc
52
+ * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
53
+ * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
54
+ * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
55
+ * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
45
56
  */
46
57
  remove<TT extends T>(entity: TT | Reference<TT> | Iterable<TT | Reference<TT>> | ((item: TT) => boolean), ...entities: (TT | Reference<TT>)[]): number;
47
58
  contains<TT extends T>(item: TT | Reference<TT>, check?: boolean): boolean;
48
59
  count(): number;
49
60
  isEmpty(): boolean;
61
+ shouldPopulate(populated?: boolean): boolean;
62
+ populated(populated?: boolean | undefined): void;
63
+ init<TT extends T, P extends string = never>(options?: InitCollectionOptions<TT, P>): Promise<LoadedCollection<Loaded<TT, P>>>;
64
+ private getEntityManager;
65
+ private createCondition;
66
+ private createOrderBy;
67
+ private createManyToManyCondition;
68
+ private createLoadCountCondition;
69
+ private checkInitialized;
70
+ /**
71
+ * re-orders items after searching with `$in` operator
72
+ */
73
+ private reorderItems;
74
+ private cancelOrphanRemoval;
75
+ private validateModification;
76
+ toArray<TT extends T>(): EntityDTO<TT>[];
77
+ getIdentifiers<U extends IPrimaryKey = Primary<T> & IPrimaryKey>(field?: string | string[]): U[];
78
+ /**
79
+ * @internal
80
+ */
81
+ addWithoutPropagation(entity: T): void;
82
+ set(items: Iterable<T | Reference<T>>): void;
83
+ private compare;
84
+ /**
85
+ * @internal
86
+ */
87
+ hydrate(items: T[], forcePropagate?: boolean, partial?: boolean): void;
88
+ /**
89
+ * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
90
+ * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
91
+ * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
92
+ * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
93
+ */
94
+ removeAll(): void;
95
+ /**
96
+ * @internal
97
+ */
98
+ removeWithoutPropagation(entity: T): void;
50
99
  /**
51
- * @inheritDoc
100
+ * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
101
+ * If end is null it returns all elements from start to the end of the collection.
52
102
  */
53
103
  slice(start?: number, end?: number): T[];
54
104
  /**
55
- * @inheritDoc
105
+ * Tests for the existence of an element that satisfies the given predicate.
56
106
  */
57
107
  exists(cb: (item: T) => boolean): boolean;
58
108
  /**
59
- * @inheritDoc
109
+ * Returns the first element of this collection that satisfies the predicate.
60
110
  */
61
111
  find(cb: (item: T, index: number) => boolean): T | undefined;
62
112
  /**
63
- * @inheritDoc
113
+ * Extracts a subset of the collection items.
64
114
  */
65
115
  filter(cb: (item: T, index: number) => boolean): T[];
66
116
  /**
67
- * @inheritDoc
117
+ * Maps the collection items based on your provided mapper function.
68
118
  */
69
119
  map<R>(mapper: (item: T, index: number) => R): R[];
70
120
  /**
71
- * @inheritDoc
121
+ * Maps the collection items based on your provided mapper function to a single object.
122
+ */
123
+ reduce<R>(cb: (obj: R, item: T, index: number) => R, initial?: R): R;
124
+ /**
125
+ * Maps the collection items to a dictionary, indexed by the key you specify.
126
+ * If there are more items with the same key, only the first one will be present.
72
127
  */
73
128
  indexBy<K1 extends keyof T, K2 extends keyof T = never>(key: K1): Record<T[K1] & PropertyKey, T>;
74
129
  /**
75
- * @inheritDoc
130
+ * Maps the collection items to a dictionary, indexed by the key you specify.
131
+ * If there are more items with the same key, only the first one will be present.
76
132
  */
77
133
  indexBy<K1 extends keyof T, K2 extends keyof T = never>(key: K1, valueKey: K2): Record<T[K1] & PropertyKey, T[K2]>;
78
- shouldPopulate(populated?: boolean): boolean;
79
- populated(populated?: boolean | undefined): void;
80
- init<TT extends T, P extends string = never>(options?: InitCollectionOptions<TT, P>): Promise<LoadedCollection<Loaded<TT, P>>>;
81
- private getEntityManager;
82
- private createCondition;
83
- private createOrderBy;
84
- private createManyToManyCondition;
85
- private createLoadCountCondition;
86
- private modify;
87
- private checkInitialized;
134
+ isInitialized(fully?: boolean): boolean;
135
+ isDirty(): boolean;
136
+ isPartial(): boolean;
137
+ setDirty(dirty?: boolean): void;
138
+ get length(): number;
139
+ [Symbol.iterator](): IterableIterator<T>;
88
140
  /**
89
- * re-orders items after searching with `$in` operator
141
+ * @internal
90
142
  */
91
- private reorderItems;
92
- private cancelOrphanRemoval;
93
- private validateItemType;
94
- private validateModification;
143
+ takeSnapshot(forcePropagate?: boolean): void;
144
+ /**
145
+ * @internal
146
+ */
147
+ getSnapshot(): T[] | undefined;
148
+ /**
149
+ * @internal
150
+ */
151
+ get property(): EntityProperty;
152
+ /**
153
+ * @internal
154
+ */
155
+ set property(prop: EntityProperty);
156
+ protected propagate(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
157
+ protected propagateToInverseSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
158
+ protected propagateToOwningSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
159
+ protected shouldPropagateToCollection(collection: Collection<O, T>, method: 'add' | 'remove' | 'takeSnapshot'): boolean;
160
+ protected incrementCount(value: number): void;
161
+ /** @ignore */
162
+ [inspect.custom](depth?: number): string;
95
163
  }
96
164
  export interface InitCollectionOptions<T, P extends string = never, F extends string = '*', E extends string = never> extends EntityLoaderOptions<T, F, E> {
97
165
  dataloader?: boolean;
@@ -1,17 +1,29 @@
1
- import { ArrayCollection } from './ArrayCollection.js';
1
+ import { inspect } from 'node:util';
2
2
  import { Utils } from '../utils/Utils.js';
3
- import { ValidationError } from '../errors.js';
3
+ import { MetadataError, ValidationError } from '../errors.js';
4
4
  import { DataloaderType, ReferenceKind } from '../enums.js';
5
5
  import { Reference } from './Reference.js';
6
- import { helper } from './wrap.js';
6
+ import { helper, wrap } from './wrap.js';
7
7
  import { QueryHelper } from '../utils/QueryHelper.js';
8
- export class Collection extends ArrayCollection {
8
+ export class Collection {
9
+ owner;
10
+ items = new Set();
11
+ initialized = true;
12
+ dirty = false;
13
+ partial = false; // mark partially loaded collections, propagation is disabled for those
14
+ snapshot = []; // used to create a diff of the collection at commit time, undefined marks overridden values so we need to wipe when flushing
9
15
  readonly;
16
+ _count;
17
+ _property;
10
18
  _populated;
11
- // this is for some reason needed for TS, otherwise it can fail with `Type instantiation is excessively deep and possibly infinite.`
12
- _snapshot;
13
19
  constructor(owner, items, initialized = true) {
14
- super(owner, items);
20
+ this.owner = owner;
21
+ /* v8 ignore next 5 */
22
+ if (items) {
23
+ let i = 0;
24
+ this.items = new Set(items);
25
+ this.items.forEach(item => this[i++] = item);
26
+ }
15
27
  this.initialized = !!items || initialized;
16
28
  }
17
29
  /**
@@ -54,7 +66,7 @@ export class Collection extends ArrayCollection {
54
66
  */
55
67
  async loadItems(options) {
56
68
  await this.load(options);
57
- return super.getItems();
69
+ return this.getItems(false);
58
70
  }
59
71
  /**
60
72
  * Gets the count of collection items from database instead of counting loaded items.
@@ -105,24 +117,42 @@ export class Collection extends ArrayCollection {
105
117
  if (check) {
106
118
  this.checkInitialized();
107
119
  }
108
- return super.getItems();
120
+ return [...this.items];
109
121
  }
110
122
  toJSON() {
111
123
  if (!this.isInitialized()) {
112
124
  return [];
113
125
  }
114
- return super.toJSON();
126
+ return this.toArray();
115
127
  }
116
128
  add(entity, ...entities) {
117
129
  entities = Utils.asArray(entity).concat(entities);
118
130
  const unwrapped = entities.map(i => Reference.unwrapReference(i));
119
- unwrapped.forEach(entity => this.validateItemType(entity));
120
- const added = this.modify('add', unwrapped);
131
+ this.validateModification(unwrapped);
132
+ const em = this.getEntityManager(entities, false);
133
+ let added = 0;
134
+ for (const item of entities) {
135
+ const entity = Reference.unwrapReference(item);
136
+ if (!this.contains(entity, false)) {
137
+ this.incrementCount(1);
138
+ this[this.items.size] = entity;
139
+ this.items.add(entity);
140
+ added++;
141
+ this.dirty = true;
142
+ this.propagate(entity, 'add');
143
+ }
144
+ }
145
+ if (this.property.kind === ReferenceKind.ONE_TO_MANY && em) {
146
+ em.persist(entities);
147
+ }
121
148
  this.cancelOrphanRemoval(unwrapped);
122
149
  return added;
123
150
  }
124
151
  /**
125
- * @inheritDoc
152
+ * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
153
+ * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
154
+ * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
155
+ * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
126
156
  */
127
157
  remove(entity, ...entities) {
128
158
  if (entity instanceof Function) {
@@ -134,72 +164,50 @@ export class Collection extends ArrayCollection {
134
164
  }
135
165
  return removed;
136
166
  }
167
+ this.checkInitialized();
137
168
  entities = Utils.asArray(entity).concat(entities);
138
169
  const unwrapped = entities.map(i => Reference.unwrapReference(i));
139
- const removed = this.modify('remove', unwrapped);
140
- const em = this.getEntityManager(unwrapped, false);
141
- if (this.property.orphanRemoval && em) {
142
- for (const item of unwrapped) {
143
- em.getUnitOfWork().scheduleOrphanRemoval(item);
170
+ this.validateModification(unwrapped);
171
+ const em = this.getEntityManager(entities, false);
172
+ let removed = 0;
173
+ for (const item of entities) {
174
+ if (!item) {
175
+ continue;
176
+ }
177
+ const entity = Reference.unwrapReference(item);
178
+ if (this.items.delete(entity)) {
179
+ this.incrementCount(-1);
180
+ delete this[this.items.size]; // remove last item
181
+ this.propagate(entity, 'remove');
182
+ removed++;
183
+ this.dirty = true;
184
+ }
185
+ if (this.property.orphanRemoval && em) {
186
+ em.getUnitOfWork().scheduleOrphanRemoval(entity);
144
187
  }
145
188
  }
189
+ if (this.property.kind === ReferenceKind.ONE_TO_MANY && !this.property.orphanRemoval && em) {
190
+ em.persist(entities);
191
+ }
192
+ if (removed > 0) {
193
+ Object.assign(this, [...this.items]); // reassign array access
194
+ }
146
195
  return removed;
147
196
  }
148
197
  contains(item, check = true) {
149
198
  if (check) {
150
199
  this.checkInitialized();
151
200
  }
152
- return super.contains(item);
201
+ const entity = Reference.unwrapReference(item);
202
+ return this.items.has(entity);
153
203
  }
154
204
  count() {
155
205
  this.checkInitialized();
156
- return super.count();
206
+ return this.items.size;
157
207
  }
158
208
  isEmpty() {
159
209
  this.checkInitialized();
160
- return super.isEmpty();
161
- }
162
- /**
163
- * @inheritDoc
164
- */
165
- slice(start, end) {
166
- this.checkInitialized();
167
- return super.slice(start, end);
168
- }
169
- /**
170
- * @inheritDoc
171
- */
172
- exists(cb) {
173
- this.checkInitialized();
174
- return super.exists(cb);
175
- }
176
- /**
177
- * @inheritDoc
178
- */
179
- find(cb) {
180
- this.checkInitialized();
181
- return super.find(cb);
182
- }
183
- /**
184
- * @inheritDoc
185
- */
186
- filter(cb) {
187
- this.checkInitialized();
188
- return super.filter(cb);
189
- }
190
- /**
191
- * @inheritDoc
192
- */
193
- map(mapper) {
194
- this.checkInitialized();
195
- return super.map(mapper);
196
- }
197
- /**
198
- * @inheritDoc
199
- */
200
- indexBy(key, valueKey) {
201
- this.checkInitialized();
202
- return super.indexBy(key, valueKey);
210
+ return this.count() === 0;
203
211
  }
204
212
  shouldPopulate(populated) {
205
213
  if (!this.isInitialized(true)) {
@@ -267,10 +275,8 @@ export class Collection extends ArrayCollection {
267
275
  getEntityManager(items = [], required = true) {
268
276
  const wrapped = helper(this.owner);
269
277
  let em = wrapped.__em;
270
- // console.log('wat 1', em, this.owner);
271
278
  if (!em) {
272
279
  for (const i of items) {
273
- // console.log('wat 2', i, i && helper(i).__em);
274
280
  if (i && helper(i).__em) {
275
281
  em = helper(i).__em;
276
282
  break;
@@ -322,20 +328,6 @@ export class Collection extends ArrayCollection {
322
328
  }
323
329
  return cond;
324
330
  }
325
- modify(method, items) {
326
- if (method === 'remove') {
327
- this.checkInitialized();
328
- }
329
- this.validateModification(items);
330
- const modified = super[method](items);
331
- if (modified > 0) {
332
- this.setDirty();
333
- }
334
- if (this.property.kind === ReferenceKind.ONE_TO_MANY && (method === 'add' || !this.property.orphanRemoval)) {
335
- this.getEntityManager(items, false)?.persist(items);
336
- }
337
- return modified;
338
- }
339
331
  checkInitialized() {
340
332
  if (!this.isInitialized()) {
341
333
  throw new Error(`Collection<${this.property.type}> of entity ${this.owner.constructor.name}[${helper(this.owner).getSerializedPrimaryKey()}] not initialized`);
@@ -358,32 +350,362 @@ export class Collection extends ArrayCollection {
358
350
  em.getUnitOfWork().cancelOrphanRemoval(item);
359
351
  }
360
352
  }
361
- validateItemType(item) {
362
- if (!Utils.isEntity(item)) {
363
- throw ValidationError.notEntity(this.owner, this.property, item);
364
- }
365
- }
366
353
  validateModification(items) {
367
354
  if (this.readonly) {
368
355
  throw ValidationError.cannotModifyReadonlyCollection(this.owner, this.property);
369
356
  }
370
- // currently we allow persisting to inverse sides only in SQL drivers
371
- if (this.property.pivotTable || !this.property.mappedBy) {
372
- return;
373
- }
374
357
  const check = (item) => {
375
- if (!item || helper(item).__initialized) {
358
+ if (!item) {
359
+ return false;
360
+ }
361
+ if (!Utils.isEntity(item)) {
362
+ throw ValidationError.notEntity(this.owner, this.property, item);
363
+ }
364
+ // currently we allow persisting to inverse sides only in SQL drivers
365
+ if (this.property.pivotTable || !this.property.mappedBy) {
366
+ return false;
367
+ }
368
+ if (helper(item).__initialized) {
376
369
  return false;
377
370
  }
378
371
  return !item[this.property.mappedBy] && this.property.kind === ReferenceKind.MANY_TO_MANY;
379
372
  };
380
373
  // throw if we are modifying inverse side of M:N collection when owning side is initialized (would be ignored when persisting)
381
- if (items.find(item => check(item))) {
374
+ if (items.some(item => check(item))) {
382
375
  throw ValidationError.cannotModifyInverseCollection(this.owner, this.property);
383
376
  }
384
377
  }
378
+ toArray() {
379
+ if (this.items.size === 0) {
380
+ return [];
381
+ }
382
+ return this.map(item => wrap(item).toJSON());
383
+ }
384
+ getIdentifiers(field) {
385
+ const items = this.getItems();
386
+ const targetMeta = this.property.targetMeta;
387
+ if (items.length === 0) {
388
+ return [];
389
+ }
390
+ field ??= targetMeta.compositePK ? targetMeta.primaryKeys : (targetMeta.serializedPrimaryKey ?? targetMeta.primaryKeys[0]);
391
+ const cb = (i, f) => {
392
+ if (Utils.isEntity(i[f], true)) {
393
+ return wrap(i[f], true).getPrimaryKey();
394
+ }
395
+ return i[f];
396
+ };
397
+ return items.map(i => {
398
+ if (Array.isArray(field)) {
399
+ return field.map(f => cb(i, f));
400
+ }
401
+ return cb(i, field);
402
+ });
403
+ }
404
+ /**
405
+ * @internal
406
+ */
407
+ addWithoutPropagation(entity) {
408
+ if (!this.contains(entity, false)) {
409
+ this.incrementCount(1);
410
+ this[this.items.size] = entity;
411
+ this.items.add(entity);
412
+ this.dirty = true;
413
+ }
414
+ }
415
+ set(items) {
416
+ if (!this.initialized) {
417
+ this.initialized = true;
418
+ this.snapshot = undefined;
419
+ }
420
+ if (this.compare(Utils.asArray(items).map(item => Reference.unwrapReference(item)))) {
421
+ return;
422
+ }
423
+ this.remove(this.items);
424
+ this.add(items);
425
+ }
426
+ compare(items) {
427
+ if (items.length !== this.items.size) {
428
+ return false;
429
+ }
430
+ let idx = 0;
431
+ for (const item of this.items) {
432
+ if (item !== items[idx++]) {
433
+ return false;
434
+ }
435
+ }
436
+ return true;
437
+ }
438
+ /**
439
+ * @internal
440
+ */
441
+ hydrate(items, forcePropagate, partial) {
442
+ for (let i = 0; i < this.items.size; i++) {
443
+ delete this[i];
444
+ }
445
+ this.initialized = true;
446
+ this.partial = !!partial;
447
+ this.items.clear();
448
+ this._count = 0;
449
+ this.add(items);
450
+ this.takeSnapshot(forcePropagate);
451
+ }
452
+ /**
453
+ * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
454
+ * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
455
+ * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
456
+ * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
457
+ */
458
+ removeAll() {
459
+ if (!this.initialized) {
460
+ this.initialized = true;
461
+ this.snapshot = undefined;
462
+ }
463
+ this.remove(this.items);
464
+ this.dirty = true;
465
+ }
466
+ /**
467
+ * @internal
468
+ */
469
+ removeWithoutPropagation(entity) {
470
+ if (!this.items.delete(entity)) {
471
+ return;
472
+ }
473
+ this.incrementCount(-1);
474
+ delete this[this.items.size];
475
+ Object.assign(this, [...this.items]);
476
+ this.dirty = true;
477
+ }
478
+ /**
479
+ * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
480
+ * If end is null it returns all elements from start to the end of the collection.
481
+ */
482
+ slice(start = 0, end) {
483
+ this.checkInitialized();
484
+ let index = 0;
485
+ end ??= this.items.size;
486
+ const items = [];
487
+ for (const item of this.items) {
488
+ if (index === end) {
489
+ break;
490
+ }
491
+ if (index >= start && index < end) {
492
+ items.push(item);
493
+ }
494
+ index++;
495
+ }
496
+ return items;
497
+ }
498
+ /**
499
+ * Tests for the existence of an element that satisfies the given predicate.
500
+ */
501
+ exists(cb) {
502
+ this.checkInitialized();
503
+ for (const item of this.items) {
504
+ if (cb(item)) {
505
+ return true;
506
+ }
507
+ }
508
+ return false;
509
+ }
510
+ /**
511
+ * Returns the first element of this collection that satisfies the predicate.
512
+ */
513
+ find(cb) {
514
+ this.checkInitialized();
515
+ let index = 0;
516
+ for (const item of this.items) {
517
+ if (cb(item, index++)) {
518
+ return item;
519
+ }
520
+ }
521
+ return undefined;
522
+ }
523
+ /**
524
+ * Extracts a subset of the collection items.
525
+ */
526
+ filter(cb) {
527
+ this.checkInitialized();
528
+ const items = [];
529
+ let index = 0;
530
+ for (const item of this.items) {
531
+ if (cb(item, index++)) {
532
+ items.push(item);
533
+ }
534
+ }
535
+ return items;
536
+ }
537
+ /**
538
+ * Maps the collection items based on your provided mapper function.
539
+ */
540
+ map(mapper) {
541
+ this.checkInitialized();
542
+ const items = [];
543
+ let index = 0;
544
+ for (const item of this.items) {
545
+ items.push(mapper(item, index++));
546
+ }
547
+ return items;
548
+ }
549
+ /**
550
+ * Maps the collection items based on your provided mapper function to a single object.
551
+ */
552
+ reduce(cb, initial = {}) {
553
+ this.checkInitialized();
554
+ let index = 0;
555
+ for (const item of this.items) {
556
+ initial = cb(initial, item, index++);
557
+ }
558
+ return initial;
559
+ }
560
+ /**
561
+ * Maps the collection items to a dictionary, indexed by the key you specify.
562
+ * If there are more items with the same key, only the first one will be present.
563
+ */
564
+ indexBy(key, valueKey) {
565
+ return this.reduce((obj, item) => {
566
+ obj[item[key]] ??= valueKey ? item[valueKey] : item;
567
+ return obj;
568
+ }, {});
569
+ }
570
+ isInitialized(fully = false) {
571
+ if (!this.initialized || !fully) {
572
+ return this.initialized;
573
+ }
574
+ for (const item of this.items) {
575
+ if (!helper(item).__initialized) {
576
+ return false;
577
+ }
578
+ }
579
+ return true;
580
+ }
581
+ isDirty() {
582
+ return this.dirty;
583
+ }
584
+ isPartial() {
585
+ return this.partial;
586
+ }
587
+ setDirty(dirty = true) {
588
+ this.dirty = dirty;
589
+ }
590
+ get length() {
591
+ return this.count();
592
+ }
593
+ *[Symbol.iterator]() {
594
+ for (const item of this.getItems()) {
595
+ yield item;
596
+ }
597
+ }
598
+ /**
599
+ * @internal
600
+ */
601
+ takeSnapshot(forcePropagate) {
602
+ this.snapshot = [...this.items];
603
+ this.dirty = false;
604
+ if (this.property.owner || forcePropagate) {
605
+ this.items.forEach(item => {
606
+ this.propagate(item, 'takeSnapshot');
607
+ });
608
+ }
609
+ }
610
+ /**
611
+ * @internal
612
+ */
613
+ getSnapshot() {
614
+ return this.snapshot;
615
+ }
616
+ /**
617
+ * @internal
618
+ */
619
+ get property() {
620
+ if (!this._property) {
621
+ const meta = wrap(this.owner, true).__meta;
622
+ /* v8 ignore next 3 */
623
+ if (!meta) {
624
+ throw MetadataError.fromUnknownEntity(this.owner.constructor.name, 'Collection.property getter, maybe you just forgot to initialize the ORM?');
625
+ }
626
+ this._property = meta.relations.find(prop => this.owner[prop.name] === this);
627
+ }
628
+ return this._property;
629
+ }
630
+ /**
631
+ * @internal
632
+ */
633
+ set property(prop) {
634
+ this._property = prop;
635
+ }
636
+ propagate(item, method) {
637
+ if (this.property.owner && this.property.inversedBy) {
638
+ this.propagateToInverseSide(item, method);
639
+ }
640
+ else if (!this.property.owner && this.property.mappedBy) {
641
+ this.propagateToOwningSide(item, method);
642
+ }
643
+ }
644
+ propagateToInverseSide(item, method) {
645
+ const collection = item[this.property.inversedBy];
646
+ if (this.shouldPropagateToCollection(collection, method)) {
647
+ method = method === 'takeSnapshot' ? method : (method + 'WithoutPropagation');
648
+ collection[method](this.owner);
649
+ }
650
+ }
651
+ propagateToOwningSide(item, method) {
652
+ const mappedBy = this.property.mappedBy;
653
+ const collection = item[mappedBy];
654
+ if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
655
+ if (this.shouldPropagateToCollection(collection, method)) {
656
+ collection[method](this.owner);
657
+ }
658
+ }
659
+ else if (this.property.kind === ReferenceKind.ONE_TO_MANY && method !== 'takeSnapshot') {
660
+ const prop2 = this.property.targetMeta.properties[mappedBy];
661
+ const owner = prop2.mapToPk ? helper(this.owner).getPrimaryKey() : this.owner;
662
+ const value = method === 'add' ? owner : null;
663
+ if (this.property.orphanRemoval && method === 'remove') {
664
+ // cache the PK before we propagate, as its value might be needed when flushing
665
+ helper(item).__pk = helper(item).getPrimaryKey();
666
+ }
667
+ if (!prop2.nullable && prop2.deleteRule !== 'cascade' && method === 'remove') {
668
+ if (!this.property.orphanRemoval) {
669
+ throw ValidationError.cannotRemoveFromCollectionWithoutOrphanRemoval(this.owner, this.property);
670
+ }
671
+ return;
672
+ }
673
+ // skip if already propagated
674
+ if (Reference.unwrapReference(item[mappedBy]) !== value) {
675
+ item[mappedBy] = value;
676
+ }
677
+ }
678
+ }
679
+ shouldPropagateToCollection(collection, method) {
680
+ if (!collection) {
681
+ return false;
682
+ }
683
+ switch (method) {
684
+ case 'add':
685
+ return !collection.contains(this.owner, false);
686
+ case 'remove':
687
+ return collection.isInitialized() && collection.contains(this.owner, false);
688
+ case 'takeSnapshot':
689
+ return collection.isDirty();
690
+ }
691
+ }
692
+ incrementCount(value) {
693
+ if (typeof this._count === 'number' && this.initialized) {
694
+ this._count += value;
695
+ }
696
+ }
697
+ /** @ignore */
698
+ [inspect.custom](depth = 2) {
699
+ const object = { ...this };
700
+ const hidden = ['items', 'owner', '_property', '_count', 'snapshot', '_populated', '_lazyInitialized', '_em', 'readonly', 'partial'];
701
+ hidden.forEach(k => delete object[k]);
702
+ const ret = inspect(object, { depth });
703
+ const name = `${this.constructor.name}<${this.property?.type ?? 'unknown'}>`;
704
+ return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
705
+ }
385
706
  }
386
707
  Object.defineProperties(Collection.prototype, {
387
708
  $: { get() { return this; } },
388
709
  get: { get() { return () => this; } },
710
+ __collection: { value: true, enumerable: false, writable: false },
389
711
  });
package/entity/index.d.ts CHANGED
@@ -4,7 +4,6 @@ export * from './EntityValidator.js';
4
4
  export * from './EntityAssigner.js';
5
5
  export * from './EntityHelper.js';
6
6
  export * from './EntityFactory.js';
7
- export * from './ArrayCollection.js';
8
7
  export * from './Collection.js';
9
8
  export * from './EntityLoader.js';
10
9
  export * from './Reference.js';
package/entity/index.js CHANGED
@@ -4,7 +4,6 @@ export * from './EntityValidator.js';
4
4
  export * from './EntityAssigner.js';
5
5
  export * from './EntityHelper.js';
6
6
  export * from './EntityFactory.js';
7
- export * from './ArrayCollection.js';
8
7
  export * from './Collection.js';
9
8
  export * from './EntityLoader.js';
10
9
  export * from './Reference.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
3
  "type": "module",
4
- "version": "7.0.0-dev.66",
4
+ "version": "7.0.0-dev.67",
5
5
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
6
6
  "exports": {
7
7
  "./package.json": "./package.json",
@@ -52,7 +52,7 @@
52
52
  "access": "public"
53
53
  },
54
54
  "dependencies": {
55
- "mikro-orm": "7.0.0-dev.66"
55
+ "mikro-orm": "7.0.0-dev.67"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "dataloader": "2.2.3"
@@ -1,118 +0,0 @@
1
- import { inspect } from 'node:util';
2
- import type { EntityDTO, EntityProperty, IPrimaryKey, Primary } from '../typings.js';
3
- import { Reference } from './Reference.js';
4
- export declare class ArrayCollection<T extends object, O extends object> {
5
- readonly owner: O;
6
- protected readonly items: Set<T>;
7
- protected initialized: boolean;
8
- protected dirty: boolean;
9
- protected partial: boolean;
10
- protected snapshot: T[] | undefined;
11
- protected _count?: number;
12
- private _property?;
13
- constructor(owner: O, items?: T[]);
14
- loadCount(): Promise<number>;
15
- getItems(): T[];
16
- toArray<TT extends T>(): EntityDTO<TT>[];
17
- toJSON(): EntityDTO<T>[];
18
- getIdentifiers<U extends IPrimaryKey = Primary<T> & IPrimaryKey>(field?: string | string[]): U[];
19
- add(entity: T | Reference<T> | Iterable<T | Reference<T>>, ...entities: (T | Reference<T>)[]): number;
20
- /**
21
- * @internal
22
- */
23
- addWithoutPropagation(entity: T): void;
24
- set(items: Iterable<T | Reference<T>>): void;
25
- private compare;
26
- /**
27
- * @internal
28
- */
29
- hydrate(items: T[], forcePropagate?: boolean, partial?: boolean): void;
30
- /**
31
- * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
32
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
33
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
34
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
35
- */
36
- remove(entity: T | Reference<T> | Iterable<T | Reference<T>>, ...entities: (T | Reference<T>)[]): number;
37
- /**
38
- * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
39
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
40
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
41
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
42
- */
43
- removeAll(): void;
44
- /**
45
- * @internal
46
- */
47
- removeWithoutPropagation(entity: T): void;
48
- contains(item: T | Reference<T>, check?: boolean): boolean;
49
- /**
50
- * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
51
- * If end is null it returns all elements from start to the end of the collection.
52
- */
53
- slice(start?: number, end?: number): T[];
54
- /**
55
- * Tests for the existence of an element that satisfies the given predicate.
56
- */
57
- exists(cb: (item: T) => boolean): boolean;
58
- /**
59
- * Returns the first element of this collection that satisfies the predicate.
60
- */
61
- find(cb: (item: T, index: number) => boolean): T | undefined;
62
- /**
63
- * Extracts a subset of the collection items.
64
- */
65
- filter(cb: (item: T, index: number) => boolean): T[];
66
- /**
67
- * Maps the collection items based on your provided mapper function.
68
- */
69
- map<R>(mapper: (item: T, index: number) => R): R[];
70
- /**
71
- * Maps the collection items based on your provided mapper function to a single object.
72
- */
73
- reduce<R>(cb: (obj: R, item: T, index: number) => R, initial?: R): R;
74
- /**
75
- * Maps the collection items to a dictionary, indexed by the key you specify.
76
- * If there are more items with the same key, only the first one will be present.
77
- */
78
- indexBy<K1 extends keyof T, K2 extends keyof T = never>(key: K1): Record<T[K1] & PropertyKey, T>;
79
- /**
80
- * Maps the collection items to a dictionary, indexed by the key you specify.
81
- * If there are more items with the same key, only the first one will be present.
82
- */
83
- indexBy<K1 extends keyof T, K2 extends keyof T = never>(key: K1, valueKey: K2): Record<T[K1] & PropertyKey, T[K2]>;
84
- count(): number;
85
- isInitialized(fully?: boolean): boolean;
86
- isDirty(): boolean;
87
- isPartial(): boolean;
88
- isEmpty(): boolean;
89
- setDirty(dirty?: boolean): void;
90
- get length(): number;
91
- [Symbol.iterator](): IterableIterator<T>;
92
- /**
93
- * @internal
94
- */
95
- takeSnapshot(forcePropagate?: boolean): void;
96
- /**
97
- * @internal
98
- */
99
- getSnapshot(): T[] | undefined;
100
- /**
101
- * @internal
102
- */
103
- get property(): EntityProperty;
104
- /**
105
- * @internal
106
- */
107
- set property(prop: EntityProperty);
108
- protected propagate(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
109
- protected propagateToInverseSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
110
- protected propagateToOwningSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
111
- protected shouldPropagateToCollection(collection: ArrayCollection<O, T>, method: 'add' | 'remove' | 'takeSnapshot'): boolean;
112
- protected incrementCount(value: number): void;
113
- /** @ignore */
114
- [inspect.custom](depth?: number): string;
115
- }
116
- export interface ArrayCollection<T, O> {
117
- [k: number]: T;
118
- }
@@ -1,410 +0,0 @@
1
- import { inspect } from 'node:util';
2
- import { Reference } from './Reference.js';
3
- import { helper, wrap } from './wrap.js';
4
- import { MetadataError, ValidationError } from '../errors.js';
5
- import { ReferenceKind } from '../enums.js';
6
- import { Utils } from '../utils/Utils.js';
7
- export class ArrayCollection {
8
- owner;
9
- items = new Set();
10
- initialized = true;
11
- dirty = false;
12
- partial = false; // mark partially loaded collections, propagation is disabled for those
13
- snapshot = []; // used to create a diff of the collection at commit time, undefined marks overridden values so we need to wipe when flushing
14
- _count;
15
- _property;
16
- constructor(owner, items) {
17
- this.owner = owner;
18
- /* v8 ignore next 5 */
19
- if (items) {
20
- let i = 0;
21
- this.items = new Set(items);
22
- this.items.forEach(item => this[i++] = item);
23
- }
24
- }
25
- async loadCount() {
26
- return this.items.size;
27
- }
28
- getItems() {
29
- return [...this.items];
30
- }
31
- toArray() {
32
- if (this.items.size === 0) {
33
- return [];
34
- }
35
- return this.map(item => wrap(item).toJSON());
36
- }
37
- toJSON() {
38
- return this.toArray();
39
- }
40
- getIdentifiers(field) {
41
- const items = this.getItems();
42
- const targetMeta = this.property.targetMeta;
43
- if (items.length === 0) {
44
- return [];
45
- }
46
- field ??= targetMeta.compositePK ? targetMeta.primaryKeys : (targetMeta.serializedPrimaryKey ?? targetMeta.primaryKeys[0]);
47
- const cb = (i, f) => {
48
- if (Utils.isEntity(i[f], true)) {
49
- return wrap(i[f], true).getPrimaryKey();
50
- }
51
- return i[f];
52
- };
53
- return items.map(i => {
54
- if (Array.isArray(field)) {
55
- return field.map(f => cb(i, f));
56
- }
57
- return cb(i, field);
58
- });
59
- }
60
- add(entity, ...entities) {
61
- entities = Utils.asArray(entity).concat(entities);
62
- let added = 0;
63
- for (const item of entities) {
64
- const entity = Reference.unwrapReference(item);
65
- if (!this.contains(entity, false)) {
66
- this.incrementCount(1);
67
- this[this.items.size] = entity;
68
- this.items.add(entity);
69
- added++;
70
- this.propagate(entity, 'add');
71
- }
72
- }
73
- return added;
74
- }
75
- /**
76
- * @internal
77
- */
78
- addWithoutPropagation(entity) {
79
- if (!this.contains(entity, false)) {
80
- this.incrementCount(1);
81
- this[this.items.size] = entity;
82
- this.items.add(entity);
83
- this.dirty = true;
84
- }
85
- }
86
- set(items) {
87
- if (!this.initialized) {
88
- this.initialized = true;
89
- this.snapshot = undefined;
90
- }
91
- if (this.compare(Utils.asArray(items).map(item => Reference.unwrapReference(item)))) {
92
- return;
93
- }
94
- this.remove(this.items);
95
- this.add(items);
96
- }
97
- compare(items) {
98
- if (items.length !== this.items.size) {
99
- return false;
100
- }
101
- let idx = 0;
102
- for (const item of this.items) {
103
- if (item !== items[idx++]) {
104
- return false;
105
- }
106
- }
107
- return true;
108
- }
109
- /**
110
- * @internal
111
- */
112
- hydrate(items, forcePropagate, partial) {
113
- for (let i = 0; i < this.items.size; i++) {
114
- delete this[i];
115
- }
116
- this.initialized = true;
117
- this.partial = !!partial;
118
- this.items.clear();
119
- this._count = 0;
120
- this.add(items);
121
- this.takeSnapshot(forcePropagate);
122
- }
123
- /**
124
- * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
125
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
126
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
127
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
128
- */
129
- remove(entity, ...entities) {
130
- entities = Utils.asArray(entity).concat(entities);
131
- let removed = 0;
132
- for (const item of entities) {
133
- if (!item) {
134
- continue;
135
- }
136
- const entity = Reference.unwrapReference(item);
137
- if (this.items.delete(entity)) {
138
- this.incrementCount(-1);
139
- delete this[this.items.size]; // remove last item
140
- this.propagate(entity, 'remove');
141
- removed++;
142
- }
143
- }
144
- if (removed > 0) {
145
- Object.assign(this, [...this.items]); // reassign array access
146
- }
147
- return removed;
148
- }
149
- /**
150
- * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
151
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
152
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
153
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
154
- */
155
- removeAll() {
156
- if (!this.initialized) {
157
- this.initialized = true;
158
- this.snapshot = undefined;
159
- }
160
- this.remove(this.items);
161
- this.setDirty();
162
- }
163
- /**
164
- * @internal
165
- */
166
- removeWithoutPropagation(entity) {
167
- if (!this.items.delete(entity)) {
168
- return;
169
- }
170
- this.incrementCount(-1);
171
- delete this[this.items.size];
172
- Object.assign(this, [...this.items]);
173
- this.dirty = true;
174
- }
175
- contains(item, check) {
176
- const entity = Reference.unwrapReference(item);
177
- return this.items.has(entity);
178
- }
179
- /**
180
- * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
181
- * If end is null it returns all elements from start to the end of the collection.
182
- */
183
- slice(start = 0, end) {
184
- let index = 0;
185
- end ??= this.items.size;
186
- const items = [];
187
- for (const item of this.items) {
188
- if (index === end) {
189
- break;
190
- }
191
- if (index >= start && index < end) {
192
- items.push(item);
193
- }
194
- index++;
195
- }
196
- return items;
197
- }
198
- /**
199
- * Tests for the existence of an element that satisfies the given predicate.
200
- */
201
- exists(cb) {
202
- for (const item of this.items) {
203
- if (cb(item)) {
204
- return true;
205
- }
206
- }
207
- return false;
208
- }
209
- /**
210
- * Returns the first element of this collection that satisfies the predicate.
211
- */
212
- find(cb) {
213
- let index = 0;
214
- for (const item of this.items) {
215
- if (cb(item, index++)) {
216
- return item;
217
- }
218
- }
219
- return undefined;
220
- }
221
- /**
222
- * Extracts a subset of the collection items.
223
- */
224
- filter(cb) {
225
- const items = [];
226
- let index = 0;
227
- for (const item of this.items) {
228
- if (cb(item, index++)) {
229
- items.push(item);
230
- }
231
- }
232
- return items;
233
- }
234
- /**
235
- * Maps the collection items based on your provided mapper function.
236
- */
237
- map(mapper) {
238
- const items = [];
239
- let index = 0;
240
- for (const item of this.items) {
241
- items.push(mapper(item, index++));
242
- }
243
- return items;
244
- }
245
- /**
246
- * Maps the collection items based on your provided mapper function to a single object.
247
- */
248
- reduce(cb, initial = {}) {
249
- let index = 0;
250
- for (const item of this.items) {
251
- initial = cb(initial, item, index++);
252
- }
253
- return initial;
254
- }
255
- /**
256
- * Maps the collection items to a dictionary, indexed by the key you specify.
257
- * If there are more items with the same key, only the first one will be present.
258
- */
259
- indexBy(key, valueKey) {
260
- return this.reduce((obj, item) => {
261
- obj[item[key]] ??= valueKey ? item[valueKey] : item;
262
- return obj;
263
- }, {});
264
- }
265
- count() {
266
- return this.items.size;
267
- }
268
- isInitialized(fully = false) {
269
- if (!this.initialized || !fully) {
270
- return this.initialized;
271
- }
272
- for (const item of this.items) {
273
- if (!helper(item).__initialized) {
274
- return false;
275
- }
276
- }
277
- return true;
278
- }
279
- isDirty() {
280
- return this.dirty;
281
- }
282
- isPartial() {
283
- return this.partial;
284
- }
285
- isEmpty() {
286
- return this.count() === 0;
287
- }
288
- setDirty(dirty = true) {
289
- this.dirty = dirty;
290
- }
291
- get length() {
292
- return this.count();
293
- }
294
- *[Symbol.iterator]() {
295
- for (const item of this.getItems()) {
296
- yield item;
297
- }
298
- }
299
- /**
300
- * @internal
301
- */
302
- takeSnapshot(forcePropagate) {
303
- this.snapshot = [...this.items];
304
- this.setDirty(false);
305
- if (this.property.owner || forcePropagate) {
306
- this.items.forEach(item => {
307
- this.propagate(item, 'takeSnapshot');
308
- });
309
- }
310
- }
311
- /**
312
- * @internal
313
- */
314
- getSnapshot() {
315
- return this.snapshot;
316
- }
317
- /**
318
- * @internal
319
- */
320
- get property() {
321
- if (!this._property) {
322
- const meta = wrap(this.owner, true).__meta;
323
- /* v8 ignore next 3 */
324
- if (!meta) {
325
- throw MetadataError.fromUnknownEntity(this.owner.constructor.name, 'Collection.property getter, maybe you just forgot to initialize the ORM?');
326
- }
327
- this._property = meta.relations.find(prop => this.owner[prop.name] === this);
328
- }
329
- return this._property;
330
- }
331
- /**
332
- * @internal
333
- */
334
- set property(prop) {
335
- this._property = prop;
336
- }
337
- propagate(item, method) {
338
- if (this.property.owner && this.property.inversedBy) {
339
- this.propagateToInverseSide(item, method);
340
- }
341
- else if (!this.property.owner && this.property.mappedBy) {
342
- this.propagateToOwningSide(item, method);
343
- }
344
- }
345
- propagateToInverseSide(item, method) {
346
- const collection = item[this.property.inversedBy];
347
- if (this.shouldPropagateToCollection(collection, method)) {
348
- method = method === 'takeSnapshot' ? method : (method + 'WithoutPropagation');
349
- collection[method](this.owner);
350
- }
351
- }
352
- propagateToOwningSide(item, method) {
353
- const mappedBy = this.property.mappedBy;
354
- const collection = item[mappedBy];
355
- if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
356
- if (this.shouldPropagateToCollection(collection, method)) {
357
- collection[method](this.owner);
358
- }
359
- }
360
- else if (this.property.kind === ReferenceKind.ONE_TO_MANY && method !== 'takeSnapshot') {
361
- const prop2 = this.property.targetMeta.properties[mappedBy];
362
- const owner = prop2.mapToPk ? helper(this.owner).getPrimaryKey() : this.owner;
363
- const value = method === 'add' ? owner : null;
364
- if (this.property.orphanRemoval && method === 'remove') {
365
- // cache the PK before we propagate, as its value might be needed when flushing
366
- helper(item).__pk = helper(item).getPrimaryKey();
367
- }
368
- if (!prop2.nullable && prop2.deleteRule !== 'cascade' && method === 'remove') {
369
- if (!this.property.orphanRemoval) {
370
- throw ValidationError.cannotRemoveFromCollectionWithoutOrphanRemoval(this.owner, this.property);
371
- }
372
- return;
373
- }
374
- // skip if already propagated
375
- if (Reference.unwrapReference(item[mappedBy]) !== value) {
376
- item[mappedBy] = value;
377
- }
378
- }
379
- }
380
- shouldPropagateToCollection(collection, method) {
381
- if (!collection) {
382
- return false;
383
- }
384
- switch (method) {
385
- case 'add':
386
- return !collection.contains(this.owner, false);
387
- case 'remove':
388
- return collection.isInitialized() && collection.contains(this.owner, false);
389
- case 'takeSnapshot':
390
- return collection.isDirty();
391
- }
392
- }
393
- incrementCount(value) {
394
- if (typeof this._count === 'number' && this.initialized) {
395
- this._count += value;
396
- }
397
- }
398
- /** @ignore */
399
- [inspect.custom](depth = 2) {
400
- const object = { ...this };
401
- const hidden = ['items', 'owner', '_property', '_count', 'snapshot', '_populated', '_snapshot', '_lazyInitialized', '_em', 'readonly', 'partial'];
402
- hidden.forEach(k => delete object[k]);
403
- const ret = inspect(object, { depth });
404
- const name = `${this.constructor.name}<${this.property?.type ?? 'unknown'}>`;
405
- return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
406
- }
407
- }
408
- Object.defineProperties(ArrayCollection.prototype, {
409
- __collection: { value: true, enumerable: false, writable: false },
410
- });