mvc-kit 2.12.0 → 2.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/agent-config/bin/postinstall.mjs +5 -3
  2. package/agent-config/bin/setup.mjs +3 -4
  3. package/agent-config/claude-code/agents/mvc-kit-architect.md +14 -0
  4. package/agent-config/claude-code/skills/guide/api-reference.md +24 -2
  5. package/agent-config/lib/install-claude.mjs +10 -33
  6. package/dist/Model.cjs +9 -1
  7. package/dist/Model.cjs.map +1 -1
  8. package/dist/Model.d.ts +1 -1
  9. package/dist/Model.d.ts.map +1 -1
  10. package/dist/Model.js +9 -1
  11. package/dist/Model.js.map +1 -1
  12. package/dist/ViewModel.cjs +9 -1
  13. package/dist/ViewModel.cjs.map +1 -1
  14. package/dist/ViewModel.d.ts +1 -1
  15. package/dist/ViewModel.d.ts.map +1 -1
  16. package/dist/ViewModel.js +9 -1
  17. package/dist/ViewModel.js.map +1 -1
  18. package/dist/index.d.ts +1 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/mvc-kit.cjs +3 -0
  21. package/dist/mvc-kit.cjs.map +1 -1
  22. package/dist/mvc-kit.js +3 -0
  23. package/dist/mvc-kit.js.map +1 -1
  24. package/dist/produceDraft.cjs +105 -0
  25. package/dist/produceDraft.cjs.map +1 -0
  26. package/dist/produceDraft.d.ts +19 -0
  27. package/dist/produceDraft.d.ts.map +1 -0
  28. package/dist/produceDraft.js +105 -0
  29. package/dist/produceDraft.js.map +1 -0
  30. package/package.json +4 -2
  31. package/src/Channel.md +408 -0
  32. package/src/Channel.test.ts +957 -0
  33. package/src/Channel.ts +429 -0
  34. package/src/Collection.md +533 -0
  35. package/src/Collection.test.ts +1559 -0
  36. package/src/Collection.ts +653 -0
  37. package/src/Controller.md +306 -0
  38. package/src/Controller.test.ts +380 -0
  39. package/src/Controller.ts +90 -0
  40. package/src/EventBus.md +308 -0
  41. package/src/EventBus.test.ts +295 -0
  42. package/src/EventBus.ts +110 -0
  43. package/src/Feed.md +218 -0
  44. package/src/Feed.test.ts +442 -0
  45. package/src/Feed.ts +101 -0
  46. package/src/Model.md +524 -0
  47. package/src/Model.test.ts +642 -0
  48. package/src/Model.ts +260 -0
  49. package/src/Pagination.md +168 -0
  50. package/src/Pagination.test.ts +244 -0
  51. package/src/Pagination.ts +92 -0
  52. package/src/Pending.md +380 -0
  53. package/src/Pending.test.ts +1719 -0
  54. package/src/Pending.ts +390 -0
  55. package/src/PersistentCollection.md +183 -0
  56. package/src/PersistentCollection.test.ts +649 -0
  57. package/src/PersistentCollection.ts +375 -0
  58. package/src/Resource.ViewModel.test.ts +503 -0
  59. package/src/Resource.md +239 -0
  60. package/src/Resource.test.ts +786 -0
  61. package/src/Resource.ts +231 -0
  62. package/src/Selection.md +155 -0
  63. package/src/Selection.test.ts +326 -0
  64. package/src/Selection.ts +117 -0
  65. package/src/Service.md +440 -0
  66. package/src/Service.test.ts +241 -0
  67. package/src/Service.ts +72 -0
  68. package/src/Sorting.md +170 -0
  69. package/src/Sorting.test.ts +334 -0
  70. package/src/Sorting.ts +135 -0
  71. package/src/Trackable.md +166 -0
  72. package/src/Trackable.test.ts +236 -0
  73. package/src/Trackable.ts +129 -0
  74. package/src/ViewModel.async.test.ts +813 -0
  75. package/src/ViewModel.derived.test.ts +1583 -0
  76. package/src/ViewModel.md +1111 -0
  77. package/src/ViewModel.test.ts +1236 -0
  78. package/src/ViewModel.ts +800 -0
  79. package/src/bindPublicMethods.test.ts +126 -0
  80. package/src/bindPublicMethods.ts +48 -0
  81. package/src/env.d.ts +5 -0
  82. package/src/errors.test.ts +155 -0
  83. package/src/errors.ts +133 -0
  84. package/src/index.ts +49 -0
  85. package/src/produceDraft.md +90 -0
  86. package/src/produceDraft.test.ts +394 -0
  87. package/src/produceDraft.ts +168 -0
  88. package/src/react/components/CardList.md +97 -0
  89. package/src/react/components/CardList.test.tsx +142 -0
  90. package/src/react/components/CardList.tsx +68 -0
  91. package/src/react/components/DataTable.md +179 -0
  92. package/src/react/components/DataTable.test.tsx +599 -0
  93. package/src/react/components/DataTable.tsx +267 -0
  94. package/src/react/components/InfiniteScroll.md +116 -0
  95. package/src/react/components/InfiniteScroll.test.tsx +218 -0
  96. package/src/react/components/InfiniteScroll.tsx +70 -0
  97. package/src/react/components/types.ts +90 -0
  98. package/src/react/derived.test.tsx +261 -0
  99. package/src/react/guards.ts +24 -0
  100. package/src/react/index.ts +40 -0
  101. package/src/react/provider.test.tsx +143 -0
  102. package/src/react/provider.tsx +55 -0
  103. package/src/react/strict-mode.test.tsx +266 -0
  104. package/src/react/types.ts +25 -0
  105. package/src/react/use-event-bus.md +214 -0
  106. package/src/react/use-event-bus.test.tsx +168 -0
  107. package/src/react/use-event-bus.ts +40 -0
  108. package/src/react/use-instance.md +204 -0
  109. package/src/react/use-instance.test.tsx +350 -0
  110. package/src/react/use-instance.ts +60 -0
  111. package/src/react/use-local.md +457 -0
  112. package/src/react/use-local.rapid-remount.test.tsx +503 -0
  113. package/src/react/use-local.test.tsx +692 -0
  114. package/src/react/use-local.ts +165 -0
  115. package/src/react/use-model.md +364 -0
  116. package/src/react/use-model.test.tsx +394 -0
  117. package/src/react/use-model.ts +161 -0
  118. package/src/react/use-singleton.md +415 -0
  119. package/src/react/use-singleton.test.tsx +296 -0
  120. package/src/react/use-singleton.ts +69 -0
  121. package/src/react/use-subscribe-only.ts +39 -0
  122. package/src/react/use-teardown.md +169 -0
  123. package/src/react/use-teardown.test.tsx +86 -0
  124. package/src/react/use-teardown.ts +27 -0
  125. package/src/react-native/NativeCollection.test.ts +250 -0
  126. package/src/react-native/NativeCollection.ts +138 -0
  127. package/src/react-native/index.ts +1 -0
  128. package/src/singleton.md +310 -0
  129. package/src/singleton.test.ts +204 -0
  130. package/src/singleton.ts +70 -0
  131. package/src/types.ts +70 -0
  132. package/src/walkPrototypeChain.ts +22 -0
  133. package/src/web/IndexedDBCollection.test.ts +235 -0
  134. package/src/web/IndexedDBCollection.ts +66 -0
  135. package/src/web/WebStorageCollection.test.ts +214 -0
  136. package/src/web/WebStorageCollection.ts +116 -0
  137. package/src/web/idb.ts +184 -0
  138. package/src/web/index.ts +2 -0
  139. package/src/wrapAsyncMethods.ts +249 -0
@@ -0,0 +1,653 @@
1
+ import type { Listener, Subscribable } from './types';
2
+ import { bindPublicMethods } from './bindPublicMethods';
3
+
4
+ const __DEV__ = typeof __MVC_KIT_DEV__ !== 'undefined' && __MVC_KIT_DEV__;
5
+ const PROTECTED_KEYS = new Set(['addCleanup']);
6
+
7
+ function freeze<T>(obj: T): T {
8
+ return __DEV__ ? Object.freeze(obj) as T : obj;
9
+ }
10
+
11
+ type CollectionState<T> = T[];
12
+ type CollectionListener<T> = Listener<CollectionState<T>>;
13
+
14
+ /**
15
+ * Reactive typed array with CRUD and query methods.
16
+ */
17
+ export class Collection<T extends { id: string | number }> implements Subscribable<CollectionState<T>> {
18
+ /** Maximum number of items before FIFO eviction. 0 = unlimited. */
19
+ static MAX_SIZE = 0;
20
+ /** Time-to-live in milliseconds. 0 = no expiry. */
21
+ static TTL = 0;
22
+
23
+ private _items: readonly T[] = [];
24
+ private _disposed = false;
25
+ private _listeners = new Set<CollectionListener<T>>();
26
+ private _index = new Map<T['id'], T>();
27
+ private _abortController: AbortController | null = null;
28
+ private _cleanups: (() => void)[] | null = null;
29
+ private _timestamps: Map<T['id'], number> | null = null;
30
+ private _evictionTimer: ReturnType<typeof setTimeout> | null = null;
31
+
32
+ constructor(initialItems: T[] = []) {
33
+ let result = [...initialItems];
34
+
35
+ if (this._ttl > 0) {
36
+ this._timestamps = new Map();
37
+ const now = Date.now();
38
+ for (const item of result) {
39
+ this._timestamps.set(item.id, now);
40
+ }
41
+ }
42
+
43
+ if (this._maxSize > 0 && result.length > this._maxSize) {
44
+ // FIFO: trim from the front (oldest items)
45
+ const excess = result.length - this._maxSize;
46
+ const evicted = result.slice(0, excess);
47
+ result = result.slice(excess);
48
+ for (const item of evicted) {
49
+ this._timestamps?.delete(item.id);
50
+ }
51
+ }
52
+
53
+ this._items = freeze(result);
54
+ this._rebuildIndex();
55
+ this._scheduleEvictionTimer();
56
+ bindPublicMethods(this, Object.prototype, PROTECTED_KEYS);
57
+ }
58
+
59
+ /**
60
+ * Alias for Subscribable compatibility.
61
+ */
62
+ get state(): T[] {
63
+ return this._items as T[];
64
+ }
65
+
66
+ /** The raw array of items. */
67
+ get items(): T[] {
68
+ return this._items as T[];
69
+ }
70
+
71
+ /** Number of items in the collection. */
72
+ get length(): number {
73
+ return this._items.length;
74
+ }
75
+
76
+ /** Whether this instance has been disposed. */
77
+ get disposed(): boolean {
78
+ return this._disposed;
79
+ }
80
+
81
+ /** AbortSignal that fires when this instance is disposed. Lazily created. */
82
+ get disposeSignal(): AbortSignal {
83
+ if (!this._abortController) {
84
+ this._abortController = new AbortController();
85
+ }
86
+ return this._abortController.signal;
87
+ }
88
+
89
+ // ── Config Accessors ──
90
+
91
+ private get _maxSize(): number {
92
+ return (this.constructor as typeof Collection).MAX_SIZE;
93
+ }
94
+
95
+ private get _ttl(): number {
96
+ return (this.constructor as typeof Collection).TTL;
97
+ }
98
+
99
+ // ── CRUD Methods (notify listeners) ──
100
+
101
+ /**
102
+ * Add one or more items. Items with existing IDs are silently skipped.
103
+ */
104
+ add(...items: T[]): void {
105
+ if (this._disposed) {
106
+ throw new Error('Cannot add to disposed Collection');
107
+ }
108
+
109
+ if (items.length === 0) {
110
+ return;
111
+ }
112
+
113
+ // Fast path: single item (most common case)
114
+ if (items.length === 1) {
115
+ const item = items[0];
116
+ if (this._index.has(item.id)) return;
117
+ const prev = this._items;
118
+ let result = [...prev, item];
119
+ this._index.set(item.id, item);
120
+ if (this._timestamps) this._timestamps.set(item.id, Date.now());
121
+ if (this._maxSize > 0 && result.length > this._maxSize) {
122
+ result = this._evictForCapacity(result);
123
+ }
124
+ this._items = freeze(result);
125
+ this._notify(prev);
126
+ this._scheduleEvictionTimer();
127
+ return;
128
+ }
129
+
130
+ // Multi-item path
131
+ const seen = new Set<T['id']>();
132
+ const newItems: T[] = [];
133
+ for (const item of items) {
134
+ if (!this._index.has(item.id) && !seen.has(item.id)) {
135
+ newItems.push(item);
136
+ seen.add(item.id);
137
+ }
138
+ }
139
+ if (newItems.length === 0) return;
140
+
141
+ const prev = this._items;
142
+ let result = [...prev, ...newItems];
143
+
144
+ for (const item of newItems) {
145
+ this._index.set(item.id, item);
146
+ }
147
+
148
+ // Record timestamps for TTL
149
+ if (this._timestamps) {
150
+ const now = Date.now();
151
+ for (const item of newItems) {
152
+ this._timestamps.set(item.id, now);
153
+ }
154
+ }
155
+
156
+ // Enforce capacity before freeze/notify
157
+ if (this._maxSize > 0 && result.length > this._maxSize) {
158
+ result = this._evictForCapacity(result);
159
+ }
160
+
161
+ this._items = freeze(result);
162
+ this._notify(prev);
163
+ this._scheduleEvictionTimer();
164
+ }
165
+
166
+ /**
167
+ * Add or replace items by ID. Existing items are replaced in-place
168
+ * (preserving array position); new items are appended. Deduplicates
169
+ * input — last occurrence wins. No-op if nothing changed (reference
170
+ * comparison).
171
+ */
172
+ upsert(...items: T[]): void {
173
+ if (this._disposed) {
174
+ throw new Error('Cannot upsert on disposed Collection');
175
+ }
176
+ if (items.length === 0) return;
177
+
178
+ // Fast path: single item (most common case — channel messages, real-time updates)
179
+ if (items.length === 1) {
180
+ const item = items[0];
181
+ const existing = this._index.get(item.id);
182
+
183
+ if (existing) {
184
+ // Replace in-place — skip if same reference
185
+ if (existing === item) return;
186
+ const prev = this._items;
187
+ const idx = this._items.indexOf(existing);
188
+ const newItems = [...prev];
189
+ newItems[idx] = item;
190
+ this._index.set(item.id, item);
191
+ if (this._timestamps) this._timestamps.set(item.id, Date.now());
192
+ this._items = freeze(newItems);
193
+ this._notify(prev);
194
+ } else {
195
+ // New item — append (with capacity enforcement)
196
+ const prev = this._items;
197
+ let result = [...prev, item];
198
+ this._index.set(item.id, item);
199
+ if (this._timestamps) this._timestamps.set(item.id, Date.now());
200
+ if (this._maxSize > 0 && result.length > this._maxSize) {
201
+ result = this._evictForCapacity(result);
202
+ }
203
+ this._items = freeze(result);
204
+ this._notify(prev);
205
+ this._scheduleEvictionTimer();
206
+ }
207
+ return;
208
+ }
209
+
210
+ // Multi-item path: deduplicate input — last occurrence wins
211
+ const incoming = new Map<T['id'], T>();
212
+ for (const item of items) {
213
+ incoming.set(item.id, item);
214
+ }
215
+
216
+ const prev = this._items;
217
+ let changed = false;
218
+ const replaced = new Set<T['id']>();
219
+ const newArray: T[] = [];
220
+
221
+ // Replace existing items in-place
222
+ for (const existing of prev) {
223
+ if (incoming.has(existing.id)) {
224
+ const replacement = incoming.get(existing.id)!;
225
+ if (replacement !== existing) changed = true;
226
+ newArray.push(replacement);
227
+ replaced.add(existing.id);
228
+ } else {
229
+ newArray.push(existing);
230
+ }
231
+ }
232
+
233
+ // Append genuinely new items
234
+ for (const [id, item] of incoming) {
235
+ if (!replaced.has(id)) {
236
+ newArray.push(item);
237
+ changed = true;
238
+ }
239
+ }
240
+
241
+ if (!changed) return;
242
+
243
+ // Record/refresh timestamps for TTL (upsert refreshes existing)
244
+ if (this._timestamps) {
245
+ const now = Date.now();
246
+ for (const [id] of incoming) {
247
+ this._timestamps.set(id, now);
248
+ }
249
+ }
250
+
251
+ for (const [id, item] of incoming) {
252
+ this._index.set(id, item);
253
+ }
254
+
255
+ // Enforce capacity before freeze/notify
256
+ let result = newArray;
257
+ if (this._maxSize > 0 && result.length > this._maxSize) {
258
+ result = this._evictForCapacity(result);
259
+ }
260
+
261
+ this._items = freeze(result);
262
+ this._notify(prev);
263
+ this._scheduleEvictionTimer();
264
+ }
265
+
266
+ /**
267
+ * Remove items by id(s).
268
+ */
269
+ remove(...ids: T['id'][]): void {
270
+ if (this._disposed) {
271
+ throw new Error('Cannot remove from disposed Collection');
272
+ }
273
+
274
+ if (ids.length === 0) {
275
+ return;
276
+ }
277
+
278
+ // Fast path: single id (most common case)
279
+ if (ids.length === 1) {
280
+ const id = ids[0];
281
+ if (!this._index.has(id)) return;
282
+ const prev = this._items;
283
+ this._items = freeze(prev.filter(item => item.id !== id));
284
+ this._index.delete(id);
285
+ this._timestamps?.delete(id);
286
+ this._notify(prev);
287
+ this._scheduleEvictionTimer();
288
+ return;
289
+ }
290
+
291
+ // Multi-id path
292
+ const idSet = new Set(ids);
293
+ const filtered = this._items.filter(item => !idSet.has(item.id));
294
+
295
+ if (filtered.length === this._items.length) {
296
+ return; // No items removed
297
+ }
298
+
299
+ const prev = this._items;
300
+ this._items = freeze(filtered);
301
+
302
+ for (const id of ids) {
303
+ this._index.delete(id);
304
+ this._timestamps?.delete(id);
305
+ }
306
+
307
+ this._notify(prev);
308
+ this._scheduleEvictionTimer();
309
+ }
310
+
311
+ /**
312
+ * Update an item by id with partial changes.
313
+ */
314
+ update(id: T['id'], changes: Partial<T>): void {
315
+ if (this._disposed) {
316
+ throw new Error('Cannot update disposed Collection');
317
+ }
318
+
319
+ // O(1) existence check via index Map
320
+ const existing = this._index.get(id);
321
+ if (!existing) return;
322
+
323
+ // Check if anything actually changed (before any array work)
324
+ const keys = Object.keys(changes) as (keyof T)[];
325
+ const hasChanges = keys.some(key => changes[key] !== existing[key]);
326
+ if (!hasChanges) return;
327
+
328
+ const updated = { ...existing, ...changes, id };
329
+ const prev = this._items;
330
+ const idx = this._items.indexOf(existing);
331
+ const newItems = [...prev];
332
+ newItems[idx] = updated;
333
+ this._items = freeze(newItems);
334
+ this._index.set(id, updated);
335
+
336
+ this._notify(prev);
337
+ }
338
+
339
+ /**
340
+ * Replace all items.
341
+ */
342
+ reset(items: T[]): void {
343
+ if (this._disposed) {
344
+ throw new Error('Cannot reset disposed Collection');
345
+ }
346
+
347
+ const prev = this._items;
348
+
349
+ // Record timestamps for TTL
350
+ if (this._timestamps) {
351
+ this._timestamps.clear();
352
+ const now = Date.now();
353
+ for (const item of items) {
354
+ this._timestamps.set(item.id, now);
355
+ }
356
+ }
357
+
358
+ let result = [...items];
359
+
360
+ // Enforce capacity before freeze/notify
361
+ if (this._maxSize > 0 && result.length > this._maxSize) {
362
+ result = this._evictForCapacity(result);
363
+ }
364
+
365
+ this._items = freeze(result);
366
+ this._rebuildIndex();
367
+
368
+ this._notify(prev);
369
+ this._scheduleEvictionTimer();
370
+ }
371
+
372
+ /**
373
+ * Remove all items.
374
+ */
375
+ clear(): void {
376
+ if (this._disposed) {
377
+ throw new Error('Cannot clear disposed Collection');
378
+ }
379
+
380
+ if (this._items.length === 0) {
381
+ return;
382
+ }
383
+
384
+ const prev = this._items;
385
+ this._items = freeze([] as T[]);
386
+ this._index.clear();
387
+ this._timestamps?.clear();
388
+ this._clearEvictionTimer();
389
+
390
+ this._notify(prev);
391
+ }
392
+
393
+ /**
394
+ * Snapshot current state, apply callback mutations, and return a rollback function.
395
+ * Rollback restores items to pre-callback state regardless of later mutations.
396
+ */
397
+ optimistic(callback: () => void): () => void {
398
+ if (this._disposed) {
399
+ throw new Error('Cannot perform optimistic update on disposed Collection');
400
+ }
401
+
402
+ const snapshot = this._items;
403
+ const timestampSnapshot = this._timestamps ? new Map(this._timestamps) : null;
404
+ callback();
405
+
406
+ let rolledBack = false;
407
+ return () => {
408
+ if (rolledBack || this._disposed) return;
409
+ rolledBack = true;
410
+
411
+ const prev = this._items;
412
+ this._items = snapshot;
413
+ if (timestampSnapshot) {
414
+ this._timestamps = timestampSnapshot;
415
+ }
416
+ this._rebuildIndex();
417
+ this._notify(prev);
418
+ this._scheduleEvictionTimer();
419
+ };
420
+ }
421
+
422
+ // ── Query Methods (pure, no notification) ──
423
+
424
+ /**
425
+ * Get item by id.
426
+ */
427
+ get(id: T['id']): T | undefined {
428
+ return this._index.get(id);
429
+ }
430
+
431
+ /**
432
+ * Check if item exists by id.
433
+ */
434
+ has(id: T['id']): boolean {
435
+ return this._index.has(id);
436
+ }
437
+
438
+ /**
439
+ * Find first item matching predicate.
440
+ */
441
+ find(predicate: (item: T) => boolean): T | undefined {
442
+ return this._items.find(predicate);
443
+ }
444
+
445
+ /**
446
+ * Filter items matching predicate.
447
+ */
448
+ filter(predicate: (item: T) => boolean): T[] {
449
+ return this._items.filter(predicate) as T[];
450
+ }
451
+
452
+ /**
453
+ * Return sorted copy.
454
+ */
455
+ sorted(compareFn: (a: T, b: T) => number): T[] {
456
+ return [...this._items].sort(compareFn);
457
+ }
458
+
459
+ /**
460
+ * Map items to new array.
461
+ */
462
+ map<U>(fn: (item: T) => U): U[] {
463
+ return this._items.map(fn);
464
+ }
465
+
466
+ // ── Subscribable interface ──
467
+
468
+ /** Subscribes to state changes. Returns an unsubscribe function. */
469
+ subscribe(listener: CollectionListener<T>): () => void {
470
+ if (this._disposed) {
471
+ return () => {};
472
+ }
473
+
474
+ this._listeners.add(listener);
475
+
476
+ return () => {
477
+ this._listeners.delete(listener);
478
+ };
479
+ }
480
+
481
+ /** Tears down the instance, releasing all subscriptions and resources. */
482
+ dispose(): void {
483
+ if (this._disposed) {
484
+ return;
485
+ }
486
+
487
+ this._disposed = true;
488
+ this._clearEvictionTimer();
489
+ this._abortController?.abort();
490
+ if (this._cleanups) {
491
+ for (const fn of this._cleanups) fn();
492
+ this._cleanups = null;
493
+ }
494
+ this.onDispose?.();
495
+ this._listeners.clear();
496
+ this._index.clear();
497
+ this._timestamps?.clear();
498
+ }
499
+
500
+ /** Registers a cleanup function to be called on dispose. @protected */
501
+ protected addCleanup(fn: () => void): void {
502
+ if (!this._cleanups) {
503
+ this._cleanups = [];
504
+ }
505
+ this._cleanups.push(fn);
506
+ }
507
+
508
+ /** Lifecycle hook called during dispose(). Override for custom teardown. @protected */
509
+ protected onDispose?(): void;
510
+
511
+ /**
512
+ * Called before items are auto-evicted by capacity or TTL.
513
+ * Override to filter which items get evicted, or veto entirely.
514
+ *
515
+ * @param items - Candidates for eviction
516
+ * @param reason - Why eviction is happening
517
+ * @returns void to proceed with all, false to veto, or T[] subset to evict only those
518
+ */
519
+ protected onEvict?(items: T[], reason: 'capacity' | 'ttl'): T[] | false | void;
520
+
521
+ private _notify(prev: readonly T[]): void {
522
+ for (const listener of this._listeners) {
523
+ listener(this._items as T[], prev as T[]);
524
+ }
525
+ }
526
+
527
+ private _rebuildIndex(): void {
528
+ this._index.clear();
529
+ for (const item of this._items) {
530
+ this._index.set(item.id, item);
531
+ }
532
+ }
533
+
534
+ // ── Eviction Internals ──
535
+
536
+ private _evictForCapacity(items: T[]): T[] {
537
+ const excess = items.length - this._maxSize;
538
+ if (excess <= 0) return items;
539
+
540
+ const candidates = items.slice(0, excess);
541
+ const toEvict = this._applyOnEvict(candidates, 'capacity');
542
+
543
+ if (toEvict === false) return items; // veto
544
+
545
+ if (toEvict.length === 0) return items; // nothing to evict
546
+
547
+ const evictIds = new Set(toEvict.map(item => item.id));
548
+ const result = items.filter(item => !evictIds.has(item.id));
549
+
550
+ // Clean up index and timestamps for evicted items
551
+ for (const item of toEvict) {
552
+ this._index.delete(item.id);
553
+ this._timestamps?.delete(item.id);
554
+ }
555
+
556
+ return result;
557
+ }
558
+
559
+ private _applyOnEvict(candidates: T[], reason: 'capacity' | 'ttl'): T[] | false {
560
+ if (!this.onEvict) return candidates;
561
+
562
+ const result = this.onEvict(candidates, reason);
563
+ if (result === false) {
564
+ // DEV warning when veto causes collection to exceed 2x MAX_SIZE
565
+ if (__DEV__ && reason === 'capacity' && this._maxSize > 0) {
566
+ const currentSize = this._items.length + candidates.length;
567
+ if (currentSize > this._maxSize * 2) {
568
+ console.warn(
569
+ `[mvc-kit] Collection exceeded 2x MAX_SIZE (${currentSize}/${this._maxSize}). ` +
570
+ `onEvict is vetoing eviction — this may cause unbounded growth.`
571
+ );
572
+ }
573
+ }
574
+ return false;
575
+ }
576
+ if (Array.isArray(result)) {
577
+ // Only include items that are actually in the current items
578
+ const candidateIds = new Set(candidates.map(c => c.id));
579
+ return result.filter(item => candidateIds.has(item.id));
580
+ }
581
+ return candidates; // void = proceed with all
582
+ }
583
+
584
+ private _sweepExpired(): void {
585
+ if (this._disposed || !this._timestamps || this._ttl <= 0) return;
586
+
587
+ const now = Date.now();
588
+ const ttl = this._ttl;
589
+ const expired: T[] = [];
590
+
591
+ for (const item of this._items) {
592
+ const ts = this._timestamps.get(item.id);
593
+ if (ts !== undefined && (now - ts) >= ttl) {
594
+ expired.push(item);
595
+ }
596
+ }
597
+
598
+ if (expired.length === 0) {
599
+ this._scheduleEvictionTimer();
600
+ return;
601
+ }
602
+
603
+ const toEvict = this._applyOnEvict(expired, 'ttl');
604
+
605
+ if (toEvict === false) {
606
+ this._scheduleEvictionTimer();
607
+ return;
608
+ }
609
+
610
+ if (toEvict.length === 0) {
611
+ this._scheduleEvictionTimer();
612
+ return;
613
+ }
614
+
615
+ const evictIds = new Set(toEvict.map(item => item.id));
616
+ const prev = this._items;
617
+ this._items = freeze(
618
+ (prev as T[]).filter((item: T) => !evictIds.has(item.id))
619
+ );
620
+
621
+ for (const item of toEvict) {
622
+ this._index.delete(item.id);
623
+ this._timestamps.delete(item.id);
624
+ }
625
+
626
+ this._notify(prev);
627
+ this._scheduleEvictionTimer();
628
+ }
629
+
630
+ private _scheduleEvictionTimer(): void {
631
+ this._clearEvictionTimer();
632
+
633
+ if (this._disposed || !this._timestamps || this._ttl <= 0 || this._timestamps.size === 0) return;
634
+
635
+ const now = Date.now();
636
+ const ttl = this._ttl;
637
+ let earliest = Infinity;
638
+
639
+ for (const ts of this._timestamps.values()) {
640
+ if (ts < earliest) earliest = ts;
641
+ }
642
+
643
+ const delay = Math.max(0, (earliest + ttl) - now);
644
+ this._evictionTimer = setTimeout(() => this._sweepExpired(), delay);
645
+ }
646
+
647
+ private _clearEvictionTimer(): void {
648
+ if (this._evictionTimer !== null) {
649
+ clearTimeout(this._evictionTimer);
650
+ this._evictionTimer = null;
651
+ }
652
+ }
653
+ }