@yaks/ram 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/store.js ADDED
@@ -0,0 +1,985 @@
1
+ import { preserving, trashLimit, trashOrder } from "@yaks/graph/trash";
2
+ import { isPromise, same } from "@yaks/fp";
3
+ import { comps, dead, reserved as metadata, TOMBSTONE, tombstoned } from "@yaks/graph/bundle";
4
+ import { only } from "@yaks/graph/read";
5
+ import { clash, renumbering, seriesOf, stating } from "@yaks/graph/storage";
6
+ import { index, keyOf, matcher, rows as answer, statusOf } from "@yaks/match";
7
+ import { extendsVocab, relabelsVocab } from "@yaks/vocab";
8
+ import { bindings } from "./rules.js";
9
+ import { records } from "./records.js";
10
+ // A deleted entity keeps its identity and a tombstone, and nothing else, until
11
+ // `revive` brings it back.
12
+ let buried = (b)=>b?.[TOMBSTONE] != null;
13
+ let NONE = new Map();
14
+ let file = (byKey, key, eid, b)=>{
15
+ let at = byKey.get(key);
16
+ if (!at) byKey.set(key, at = new Map());
17
+ at.set(eid, b);
18
+ };
19
+ let unfile = (byKey, key, eid)=>{
20
+ let at = byKey.get(key);
21
+ if (at?.delete(eid) && !at.size) byKey.delete(key);
22
+ };
23
+ // The band a value files under in a number index: the whole number at or below
24
+ // it, read the way a number comparison reads it (@yaks/match), so every value a
25
+ // range selects is in one of the bands the range spans.
26
+ let bandOf = (v)=>{
27
+ if (v == null) return undefined;
28
+ let n = Math.floor(Number(v));
29
+ return Number.isNaN(n) ? undefined : n;
30
+ };
31
+ // One property of a record, or undefined.
32
+ let valueOf = (b, comp, prop)=>b?.[comp]?.[prop];
33
+ // A vocabulary snapshot never changes: resolve its status-bearing components once,
34
+ // rather than inspect every component of every row each time it is gathered.
35
+ let ladders = new WeakMap();
36
+ let statusesOf = (vocab)=>{
37
+ let held = ladders.get(vocab);
38
+ if (!held) {
39
+ ladders.set(vocab, held = vocab.all.filter((n)=>vocab.comp(n)?.ladder));
40
+ }
41
+ return held;
42
+ };
43
+ let binariesOf = (vocab)=>vocab.all.flatMap((comp)=>{
44
+ let props = vocab.props(comp).filter((p)=>vocab.prop(comp, p)?.scalar == 'binary');
45
+ return props.length ? [
46
+ {
47
+ comp,
48
+ props
49
+ }
50
+ ] : [];
51
+ });
52
+ let uniqueIn = (vocab)=>vocab.all.some((name)=>vocab.indexes(name).some((i)=>i.unique));
53
+ /**
54
+ * A store over a Map of bundles, bound to a vocabulary once. It is the storage
55
+ * a client graph and a fast test run on:
56
+ *
57
+ * ```ts
58
+ * import { graph } from '@yaks/graph'
59
+ * import { loadVocab } from '@yaks/vocab'
60
+ * import { docDoc } from '@yaks/doc'
61
+ * import { ram } from '@yaks/ram'
62
+ *
63
+ * let vocab = loadVocab([docDoc])
64
+ * let g = graph({ storage: ram(vocab), vocab })
65
+ * g.apply([{ entity: { eid: 'b1' }, doc: { title: 'Dune' } }])
66
+ * g.read('.kind=doc')
67
+ * ```
68
+ */ export let ram = (vocab, base = {})=>{
69
+ let rows = records(()=>vocab);
70
+ // Compact identity reservations survive payload eviction. They are not query rows.
71
+ let cold = new Map();
72
+ // What a query reads instead of every row: the entities wearing each
73
+ // component, and — for each property a query has asked for by value — the
74
+ // entities by the key their value files under (@yaks/match `keyOf`), or for
75
+ // each number a query has asked for a range of, by band (`bandOf`).
76
+ let worn = new Map();
77
+ let filed = new Map();
78
+ let banded = new Map();
79
+ let uniques = new Map();
80
+ let uniqueOf = (comp)=>{
81
+ let key = vocab.stored(comp);
82
+ let got = uniques.get(key);
83
+ if (!got) {
84
+ uniques.set(key, got = !vocab.comp(comp) ? [] : vocab.indexes(comp).filter((i)=>i.unique).map((index)=>({
85
+ comp,
86
+ index,
87
+ held: new Map()
88
+ })));
89
+ }
90
+ return got;
91
+ };
92
+ let hasUnique = uniqueIn(vocab);
93
+ let uniqueKey = (b, comp, props, present = [])=>{
94
+ if (!b?.[comp] || present.some((p)=>valueOf(b, comp, p) == null)) {
95
+ return undefined;
96
+ }
97
+ let values = props.map((p)=>keyOf(valueOf(b, comp, p)));
98
+ return values.some((v)=>v === undefined) ? undefined : JSON.stringify(values);
99
+ };
100
+ // Each series' last number, by letter.
101
+ let highs = new Map();
102
+ // The entities each number was given to, any letter, a tombstone's and an
103
+ // evicted payload's included. Never pruned: an entry is checked against the
104
+ // entity's own pair when asked (`holders`), so one given away since says
105
+ // nothing.
106
+ let given = new Map();
107
+ let pairOf = (eid)=>{
108
+ let e = rows.get(eid)?.entity ?? cold.get(eid);
109
+ return !e ? undefined : e.num == null ? null : {
110
+ num: e.num,
111
+ prefix: e.prefix ?? null
112
+ };
113
+ };
114
+ let holders = (num)=>[
115
+ ...given.get(num) ?? []
116
+ ].flatMap((eid)=>{
117
+ let pair = pairOf(eid);
118
+ return pair?.num === num ? [
119
+ {
120
+ eid,
121
+ ...pair
122
+ }
123
+ ] : [];
124
+ });
125
+ // When each tombstone was laid, keyed by the record itself, so a rollback
126
+ // that puts an earlier record back takes the time with it.
127
+ let laid = new WeakMap();
128
+ // The undo log: for each entity a transaction is about to change, the record
129
+ // it held first. Replayed backwards, it is the rollback.
130
+ let log = [];
131
+ let trash = new Map();
132
+ let trashLog = [];
133
+ let depth = 0;
134
+ let save = (eid)=>log.push([
135
+ eid,
136
+ rows.get(eid),
137
+ cold.get(eid)
138
+ ]);
139
+ // Back to where the log stood at `mark`, and the numbering with it.
140
+ let rewind = (mark, minted)=>{
141
+ while(log.length > mark){
142
+ let [eid, rec, identity] = log.pop();
143
+ if (identity) cold.set(eid, identity);
144
+ else cold.delete(eid);
145
+ put(eid, rec);
146
+ }
147
+ highs = minted.highs;
148
+ };
149
+ let counted = ()=>({
150
+ highs: new Map(highs)
151
+ });
152
+ // One entity's record replaced, or dropped, and every index moved with it.
153
+ // Every write goes through here, a rollback's included, so an index never
154
+ // disagrees with the rows.
155
+ let put = (eid, b)=>{
156
+ let was = rows.get(eid);
157
+ let checks = [];
158
+ // Components are immutable; their unique keys stay held by the same eid
159
+ // when another component changes. Row-bearing indexes still move below.
160
+ if (hasUnique) {
161
+ for(let comp in was){
162
+ if (was[comp] !== b?.[comp]) checks.push(...uniqueOf(comp));
163
+ }
164
+ for(let comp in b){
165
+ if (!was || !(comp in was)) checks.push(...uniqueOf(comp));
166
+ }
167
+ }
168
+ for (let { comp, index, held } of checks){
169
+ let key = uniqueKey(b, comp, index.props, index.present);
170
+ if (key !== undefined && held.has(key) && held.get(key) != eid) {
171
+ throw new Error(`unique constraint failed: ${comp}.${index.props.join(', ')}`);
172
+ }
173
+ }
174
+ if (b) {
175
+ let at = laid.get(b);
176
+ b = rows.set(eid, b);
177
+ if (at != null) laid.set(b, at);
178
+ } else rows.delete(eid);
179
+ let num = b?.entity.num;
180
+ if (num != null) given.set(num, (given.get(num) ?? new Set()).add(eid));
181
+ for (let { comp, index, held } of checks){
182
+ let from = uniqueKey(was, comp, index.props, index.present);
183
+ let to = uniqueKey(b, comp, index.props, index.present);
184
+ if (from !== undefined && from != to) held.delete(from);
185
+ if (to !== undefined) held.set(to, eid);
186
+ }
187
+ if (was) {
188
+ for(let name in was){
189
+ if (name != 'entity' && !(b && name in b)) {
190
+ worn.get(vocab.stored(name))?.delete(eid);
191
+ }
192
+ }
193
+ }
194
+ if (b) {
195
+ for(let name in b){
196
+ if (name == 'entity') continue;
197
+ let key = vocab.stored(name);
198
+ let at = worn.get(key);
199
+ if (!at) worn.set(key, at = new Map());
200
+ at.set(eid, b);
201
+ }
202
+ }
203
+ for (let [comp, prop, byKey] of filed.values()){
204
+ let from = keyOf(valueOf(was, comp, prop));
205
+ let to = keyOf(valueOf(b, comp, prop));
206
+ if (from !== undefined && from !== to) unfile(byKey, from, eid);
207
+ if (to !== undefined) file(byKey, to, eid, b);
208
+ }
209
+ for (let [comp, prop, byBand] of banded.values()){
210
+ let from = bandOf(valueOf(was, comp, prop));
211
+ let to = bandOf(valueOf(b, comp, prop));
212
+ if (from !== undefined && from !== to) unfile(byBand, from, eid);
213
+ if (to !== undefined) file(byBand, to, eid, b);
214
+ }
215
+ };
216
+ let holdersOf = (comp)=>worn.get(vocab.stored(comp)) ?? NONE;
217
+ let keyFor = (comp, prop)=>`${vocab.stored(comp)}.${vocab.stored(comp, prop)}`;
218
+ // The keyed index over one property: filed from the component index the
219
+ // first time a query asks for it, and kept by `put` from then on.
220
+ let keys = (comp, prop)=>{
221
+ let at = keyFor(comp, prop);
222
+ let held = filed.get(at);
223
+ if (held) return held[2];
224
+ let byKey = new Map();
225
+ filed.set(at, [
226
+ comp,
227
+ prop,
228
+ byKey
229
+ ]);
230
+ for (let [eid, b] of holdersOf(comp)){
231
+ let key = keyOf(valueOf(b, comp, prop));
232
+ if (key !== undefined) file(byKey, key, eid, b);
233
+ }
234
+ return byKey;
235
+ };
236
+ // The number index over one property, filed the same way the first time a
237
+ // query asks for a range of it.
238
+ let bands = (comp, prop)=>{
239
+ let at = keyFor(comp, prop);
240
+ let held = banded.get(at);
241
+ if (held) return held[2];
242
+ let byBand = new Map();
243
+ banded.set(at, [
244
+ comp,
245
+ prop,
246
+ byBand
247
+ ]);
248
+ for (let [eid, b] of holdersOf(comp)){
249
+ let band = bandOf(valueOf(b, comp, prop));
250
+ if (band !== undefined) file(byBand, band, eid, b);
251
+ }
252
+ return byBand;
253
+ };
254
+ // The bands a range spans: counted off one by one when there are fewer of
255
+ // them than bands filed, else picked out of the ones filed.
256
+ let ranged = (comp, prop, lo, hi)=>{
257
+ let byBand = bands(comp, prop);
258
+ let a = Math.floor(lo);
259
+ let z = Math.floor(hi);
260
+ let out = [];
261
+ if (z - a < byBand.size) {
262
+ for(let k = a; k <= z; k++){
263
+ let at = byBand.get(k);
264
+ if (at) out.push(at);
265
+ }
266
+ } else {
267
+ for (let [k, at] of byBand)if (k >= a && k <= z) out.push(at);
268
+ }
269
+ return out;
270
+ };
271
+ // What one read sees: every row, by id, by component and by value, and what
272
+ // a batch under evaluation removed. A fresh view per read, so what a run
273
+ // keeps against it (a walk's closure) never outlives the rows it was worked
274
+ // out from.
275
+ let view = (gone)=>{
276
+ let list;
277
+ return {
278
+ get list () {
279
+ return list ??= [
280
+ ...rows.values()
281
+ ];
282
+ },
283
+ of: (eid)=>rows.get(eid),
284
+ wearing: holdersOf,
285
+ keyed: (comp, prop, key)=>keys(comp, prop).get(key) ?? NONE,
286
+ ranged,
287
+ gone
288
+ };
289
+ };
290
+ // Resolve storage policy once per component, not on every moving cell.
291
+ // Existing components keep their policy when the vocabulary grows.
292
+ let cells = new Map();
293
+ let cellsOf = (comp)=>{
294
+ let held = cells.get(comp);
295
+ if (!held) {
296
+ let refs = new Set();
297
+ let kept = new Set();
298
+ for (let name of vocab.props(comp)){
299
+ let prop = vocab.prop(comp, name);
300
+ if (prop.category == 'ref') refs.add(name);
301
+ if (!prop.computed || base.adopt) kept.add(name);
302
+ }
303
+ cells.set(comp, held = {
304
+ refs,
305
+ kept
306
+ });
307
+ }
308
+ return held;
309
+ };
310
+ let isRef = (comp, prop)=>cellsOf(comp).refs.has(prop);
311
+ // The properties of a patch this vocabulary stores. A component whose patch
312
+ // names none is still a component: its presence is the fact. A store that
313
+ // mirrors another graph keeps the computed values that graph sent, since it
314
+ // holds no rule to derive them.
315
+ // Bytes cross the storage boundary by value, just as a database BLOB does.
316
+ // Keep the ordinary immutable-bundle path allocation-free.
317
+ let binary = binariesOf(vocab);
318
+ let detached = (b)=>{
319
+ let out = b;
320
+ for (let { comp, props } of binary){
321
+ let held = b[comp];
322
+ if (!held) continue;
323
+ for (let prop of props){
324
+ let value = held[prop];
325
+ if (value instanceof Uint8Array) {
326
+ if (out === b) out = {
327
+ ...b
328
+ };
329
+ if (out[comp] === held) out[comp] = {
330
+ ...held
331
+ };
332
+ out[comp][prop] = value.slice();
333
+ }
334
+ }
335
+ }
336
+ return out;
337
+ };
338
+ // Reads carry the computed values a server would send, without storing
339
+ // them. Compute against the whole index before cutting requested components.
340
+ let statuses = statusesOf(vocab);
341
+ let derived = Object.entries(base.computed ?? {}).map(([path, read])=>[
342
+ ...path.split('.'),
343
+ read
344
+ ]);
345
+ let computed = (b, among, names)=>{
346
+ let out = b;
347
+ for (let name of statuses){
348
+ if (names && !names.includes(name)) continue;
349
+ let value = b[name];
350
+ if (!value) continue;
351
+ out = {
352
+ ...out,
353
+ [name]: {
354
+ ...value,
355
+ status: statusOf(vocab, name, b)
356
+ }
357
+ };
358
+ }
359
+ for (let [name, prop, read] of derived){
360
+ if (names && !names.includes(name)) continue;
361
+ if (!b[name]) continue;
362
+ let value = read(b, among);
363
+ let comp = {
364
+ ...out[name]
365
+ };
366
+ if (value == null) delete comp[prop];
367
+ else comp[prop] = value;
368
+ out = {
369
+ ...out,
370
+ [name]: comp
371
+ };
372
+ }
373
+ return out;
374
+ };
375
+ // Remove hidden relations before the matcher can inspect a value or follow
376
+ // a reference. Every index for this read is built from this visible dataset.
377
+ // A deleted entity is judged by its history (@yaks/sql `ghostly`), and
378
+ // this store keeps none, so no scope sees it here.
379
+ let visible = (opts)=>{
380
+ let scope = opts.visibility;
381
+ if (!scope) return view();
382
+ let source = view();
383
+ let screen = {
384
+ now: opts.now ?? base.now,
385
+ exactIds: true
386
+ };
387
+ let allowed = scope.entity ? matcher(scope.entity, vocab, screen)(source) : source.list;
388
+ let components = Object.entries(scope.components ?? {}).map(([name, q])=>[
389
+ name,
390
+ new Set(matcher(q, vocab, screen)(source).map((b)=>b.entity.eid))
391
+ ]);
392
+ let present = new Set(allowed.map((b)=>b.entity.eid));
393
+ return index(allowed.map((b)=>{
394
+ let out = {
395
+ ...b
396
+ };
397
+ for (let [name, owners] of components){
398
+ if (!owners.has(b.entity.eid)) delete out[name];
399
+ }
400
+ for (let [name, value] of comps(out)){
401
+ if (!value) continue;
402
+ for (let prop of vocab.props(name)){
403
+ if (isRef(name, prop) && typeof value[prop] == 'string' && !present.has(value[prop])) {
404
+ let comp = {
405
+ ...out[name]
406
+ };
407
+ delete comp[prop];
408
+ out[name] = comp;
409
+ }
410
+ }
411
+ }
412
+ // Archetype metadata describes stored components, not this caller's view.
413
+ let { archetype: _, ...entity } = b.entity;
414
+ out.entity = entity;
415
+ return out;
416
+ }));
417
+ };
418
+ let read = (query, opts = {}, comps)=>{
419
+ let among = visible(opts);
420
+ let found = matcher(query, vocab, {
421
+ now: opts.now ?? base.now,
422
+ storageOrder: opts.storageOrder,
423
+ unordered: opts.unordered,
424
+ eids: opts.eids,
425
+ graves: opts.graves,
426
+ computed: base.computed
427
+ })(among);
428
+ let gathered = statuses.length || derived.length ? found.map((b)=>computed(b, among, comps)) : found;
429
+ return (comps ? gathered.map(only(new Set(comps))) : gathered).map(detached);
430
+ };
431
+ // The raw-rows path: one `{ eid }` per match, or an aggregate's rows in the
432
+ // shape @yaks/sql returns, so a caller reads the same shape from either
433
+ // storage.
434
+ let raw = (query, opts = {})=>answer(query, vocab, {
435
+ now: opts.now ?? base.now,
436
+ storageOrder: opts.storageOrder,
437
+ unordered: opts.unordered,
438
+ eids: opts.eids,
439
+ graves: opts.graves,
440
+ computed: base.computed
441
+ })(visible(opts)).map((row)=>{
442
+ if (!Object.values(row).some((v)=>v instanceof Uint8Array)) return row;
443
+ return Object.fromEntries(Object.entries(row).map(([key, value])=>[
444
+ key,
445
+ value instanceof Uint8Array ? value.slice() : value
446
+ ]));
447
+ });
448
+ // The series an entity is numbered in, where this store numbers by series
449
+ // (@yaks/id `seriesOf`).
450
+ let series = base.number ? seriesOf(vocab, base.number === true ? undefined : base.number) : undefined;
451
+ // The next number in a series, past the last it gave, stepping over one an
452
+ // entity holds in it.
453
+ let nextIn = (prefix)=>{
454
+ let n = (highs.get(prefix) ?? 0) + 1;
455
+ while(holders(n).some((h)=>clash(h, {
456
+ prefix,
457
+ num: n
458
+ })))n++;
459
+ highs.set(prefix, n);
460
+ return n;
461
+ };
462
+ // The number an identity gets when no bundle states one: the next this
463
+ // store has to give, in the series its components pick where it numbers by
464
+ // series, or none in a store mirroring another graph, which waits to be
465
+ // told.
466
+ let numbered = (held)=>{
467
+ if (base.adopt || !series) return {};
468
+ let prefix = series(held);
469
+ return prefix ? {
470
+ num: nextIn(prefix),
471
+ prefix
472
+ } : {};
473
+ };
474
+ let patch = (bundles)=>{
475
+ let born = [];
476
+ // New identities need no component indexes until their payload is ready.
477
+ let reserved = new Map();
478
+ let keep = (eid, b)=>reserved.has(eid) ? reserved.set(eid, b) : put(eid, b);
479
+ // The pair each bundle states for its entity: one to take, or `null` for
480
+ // none. A mirror is told it, whatever its vocabulary says; any other store
481
+ // takes one where its vocabulary declares numbers (@yaks/id), and checks
482
+ // it first, against every pair its entities hold.
483
+ let stated = new Map();
484
+ let told = base.adopt || !!vocab.prop('entity', 'num');
485
+ for (let b of told ? bundles : []){
486
+ if (buried(rows.get(b.entity.eid))) continue;
487
+ let pair = stating(b.entity, pairOf(b.entity.eid));
488
+ if (pair !== undefined) stated.set(b.entity.eid, pair);
489
+ }
490
+ if (!base.adopt && stated.size) {
491
+ let held = new Map();
492
+ for (let pair of stated.values()){
493
+ if (pair) held.set(pair.num, holders(pair.num));
494
+ }
495
+ renumbering(stated, pairOf, held);
496
+ }
497
+ // A stated pair, as an identity carries it; the next number this store
498
+ // gives stays past every one it holds.
499
+ let take = (eid)=>{
500
+ let pair = stated.get(eid);
501
+ if (pair == null) return {};
502
+ if (pair.prefix) {
503
+ highs.set(pair.prefix, Math.max(highs.get(pair.prefix) ?? 0, pair.num));
504
+ }
505
+ return pair.prefix ? pair : {
506
+ num: pair.num
507
+ };
508
+ };
509
+ let unnumbered = ({ num: _, prefix: __, ...entity })=>entity;
510
+ // Only a numbered store needs to plan which components determine the
511
+ // series of a new identity. Reference-only identities wait for a bundle.
512
+ let giving = new Map();
513
+ if (series && !base.adopt) {
514
+ for (let b of bundles){
515
+ for(let name in b){
516
+ if (metadata(name) || b[name] == null) continue;
517
+ let eid = b.entity.eid;
518
+ let held = giving.get(eid);
519
+ if (held) held.push(name);
520
+ else giving.set(eid, [
521
+ name
522
+ ]);
523
+ }
524
+ }
525
+ }
526
+ // An eid a reference only names gets a record to hold the pointer and no
527
+ // number, until a bundle of its own arrives (@yaks/sqlite `patch`): one
528
+ // giving it a component, or one stating its number.
529
+ // Create a record for every eid this write touches or points at, so that a
530
+ // reference may name a target created by the same write, in any order.
531
+ let birth = (eid)=>{
532
+ let rec = reserved.get(eid) ?? rows.get(eid);
533
+ let told = stated.has(eid);
534
+ if (rec) {
535
+ let was = pairOf(eid) ?? null;
536
+ let now = stated.get(eid) ?? null;
537
+ if (told && (was?.num !== now?.num || (was?.prefix ?? null) !== now?.prefix)) {
538
+ // A pair stated for an entity holding another: changed, or cleared
539
+ // by `null`.
540
+ save(eid);
541
+ let entity = {
542
+ ...unnumbered(rec.entity),
543
+ ...take(eid)
544
+ };
545
+ keep(eid, {
546
+ ...rec,
547
+ entity
548
+ });
549
+ } else if (// A record numbered nothing so far is numbered when a bundle of its
550
+ // own gives the first component in its series.
551
+ !told && !base.adopt && giving.has(eid) && !!series && !buried(rec) && rec.entity.num == null && !!series(giving.get(eid) ?? [])) {
552
+ let entity = {
553
+ ...rec.entity,
554
+ ...numbered([
555
+ ...comps(rec).map(([name])=>name),
556
+ ...giving.get(eid) ?? []
557
+ ])
558
+ };
559
+ if (entity.num == null) return;
560
+ save(eid);
561
+ keep(eid, {
562
+ ...rec,
563
+ entity
564
+ });
565
+ born.push(entity);
566
+ }
567
+ return;
568
+ }
569
+ save(eid);
570
+ let identity = cold.get(eid);
571
+ cold.delete(eid);
572
+ let entity = identity ? told ? {
573
+ ...unnumbered(identity),
574
+ ...take(eid)
575
+ } : identity : {
576
+ eid,
577
+ ...told ? take(eid) : giving.has(eid) ? numbered(giving.get(eid) ?? []) : {}
578
+ };
579
+ reserved.set(eid, {
580
+ entity
581
+ });
582
+ if (!identity) born.push(entity);
583
+ };
584
+ for (let b of bundles){
585
+ if (buried(rows.get(b.entity.eid))) continue;
586
+ birth(b.entity.eid);
587
+ for (let [name, comp] of comps(b)){
588
+ for(let prop in comp){
589
+ let val = comp[prop];
590
+ if (val != null && isRef(name, prop)) birth(String(val));
591
+ }
592
+ }
593
+ }
594
+ for (let b of bundles){
595
+ let eid = b.entity.eid;
596
+ let rec = reserved.get(eid) ?? rows.get(eid);
597
+ let was = rec;
598
+ let patches = comps(b);
599
+ let archetype = b.entity.archetype;
600
+ if (rec && archetype !== undefined && archetype !== rec.entity.archetype) {
601
+ let entity = {
602
+ ...rec.entity,
603
+ archetype
604
+ };
605
+ rec = {
606
+ ...rec,
607
+ entity
608
+ };
609
+ }
610
+ if (!rec) continue;
611
+ let held = buried(rec) ? rec : merged(rec, patches);
612
+ if (reserved.delete(eid)) {
613
+ put(eid, held);
614
+ continue;
615
+ }
616
+ if (held == was) continue;
617
+ save(eid);
618
+ put(eid, held);
619
+ }
620
+ for (let [eid, rec] of reserved)put(eid, rec);
621
+ return born;
622
+ };
623
+ // The record a patch leaves. A null component drops the row; anything else
624
+ // merges in, so an omitted property keeps what it held and a null one clears
625
+ // it. A patch that changes nothing leaves the very record it found: an
626
+ // unchanged write is no write.
627
+ let merged = (rec, patches)=>{
628
+ let held = rec;
629
+ let own = ()=>held == rec ? held = {
630
+ ...rec
631
+ } : held;
632
+ for (let [name, comp] of patches){
633
+ let was = held[name];
634
+ if (comp == null) {
635
+ if (was !== undefined) delete own()[name];
636
+ continue;
637
+ }
638
+ let next = was ?? {};
639
+ let kept = cellsOf(name).kept;
640
+ for(let p in comp){
641
+ if (!kept.has(p)) continue;
642
+ let value = comp[p];
643
+ if (value == null ? !Object.hasOwn(next, p) : Object.hasOwn(next, p) && same(next[p], value)) continue;
644
+ if (next === was) next = {
645
+ ...was
646
+ };
647
+ if (value == null) delete next[p];
648
+ else {
649
+ // Bytes retain the storage boundary's by-value ownership.
650
+ next[p] = value instanceof Uint8Array && vocab.prop(name, p)?.scalar == 'binary' ? value.slice() : value;
651
+ }
652
+ }
653
+ if (next !== was) own()[name] = next;
654
+ }
655
+ return held;
656
+ };
657
+ // The records themselves. A record is never mutated once stored, so the one a
658
+ // read hands back is safe to keep, and costs no copy; a record cut to the
659
+ // named components is a copy only when it carries others.
660
+ let get = (eids, names, opts = {})=>{
661
+ let cut = only(names ? new Set(names) : null);
662
+ let out = [];
663
+ // Plain committed gets need neither a matcher view nor its closures.
664
+ let among = opts.visibility || statuses.length || derived.length ? visible(opts) : undefined;
665
+ let scoped = opts.visibility ? new Map(among.list.map((b)=>[
666
+ b.entity.eid,
667
+ b
668
+ ])) : rows;
669
+ for (let eid of eids){
670
+ let rec = scoped.get(eid);
671
+ if (rec) {
672
+ out.push(detached(cut(among ? computed(rec, among, names) : rec)));
673
+ }
674
+ }
675
+ return out;
676
+ };
677
+ // The batch folded in, the matches asked, the log rewound. What the batch
678
+ // took a component off is its own list, since a removed component leaves
679
+ // nothing in a row to ask about; one written again later in the batch is
680
+ // not gone. A deleted entity is removed, and matches nothing.
681
+ let ask = (matches, bundles)=>{
682
+ if (!matches.length) return [];
683
+ let mark = log.length;
684
+ let minted = counted();
685
+ try {
686
+ tx.remove(bundles.filter(dead).map((b)=>b.entity));
687
+ patch(bundles.filter((b)=>!dead(b)));
688
+ let gone = new Map();
689
+ for (let b of bundles){
690
+ for (let [name, c] of comps(b)){
691
+ let at = gone.get(name) ?? new Set();
692
+ if (c == null) gone.set(name, at.add(b.entity.eid));
693
+ else at.delete(b.entity.eid);
694
+ }
695
+ }
696
+ let anchor = bundles.length ? new Set(bundles.map((b)=>b.entity.eid)) : undefined;
697
+ return bindings(matches, view((comp)=>gone.get(comp)), anchor, vocab, {
698
+ now: base.now,
699
+ computed: base.computed
700
+ });
701
+ } finally{
702
+ rewind(mark, minted);
703
+ }
704
+ };
705
+ // Resolve deletion through the same reference indexes queries use.
706
+ let doom = (eids)=>{
707
+ let cascade = vocab.deaths('cascade');
708
+ let soft = [
709
+ ...vocab.deaths('release'),
710
+ ...vocab.deaths('detach')
711
+ ];
712
+ if ([
713
+ ...cascade,
714
+ ...soft
715
+ ].some(([c, p])=>base.computed?.[`${c}.${p}`])) {
716
+ return null;
717
+ }
718
+ let owners = (targets, props)=>{
719
+ let found = new Map();
720
+ for (let [comp, prop] of props){
721
+ if (!worn.has(vocab.stored(comp))) continue;
722
+ let held = keys(comp, prop);
723
+ for (let target of targets){
724
+ for (let [eid, b] of held.get(keyOf(target)) ?? NONE){
725
+ found.set(eid, b);
726
+ }
727
+ }
728
+ }
729
+ return [
730
+ ...found.values()
731
+ ].sort((a, b)=>(a.entity.num ?? 0) - (b.entity.num ?? 0));
732
+ };
733
+ let gone = eids.map((eid)=>({
734
+ eid,
735
+ depth: 0
736
+ }));
737
+ let dead = new Set(eids);
738
+ let front = eids;
739
+ for(let depth = 1; front.length; depth++){
740
+ let next = [];
741
+ for (let b of owners(front, cascade)){
742
+ let eid = b.entity.eid;
743
+ if (dead.has(eid)) continue;
744
+ dead.add(eid);
745
+ gone.push({
746
+ eid,
747
+ depth
748
+ });
749
+ next.push(eid);
750
+ }
751
+ front = next;
752
+ }
753
+ let targets = [
754
+ ...dead
755
+ ];
756
+ let loose = [];
757
+ for (let b of owners(targets, soft)){
758
+ let eid = b.entity.eid;
759
+ if (dead.has(eid)) continue;
760
+ for (let [comp, prop] of soft){
761
+ let target = valueOf(b, comp, prop);
762
+ if (target != null && dead.has(String(target))) {
763
+ loose.push({
764
+ eid,
765
+ comp,
766
+ prop
767
+ });
768
+ }
769
+ }
770
+ }
771
+ return {
772
+ gone,
773
+ loose
774
+ };
775
+ };
776
+ let tx = {
777
+ read,
778
+ doom,
779
+ get,
780
+ bindings: ask,
781
+ patch,
782
+ evict: (eids)=>{
783
+ for (let eid of eids){
784
+ let rec = rows.get(eid);
785
+ if (!rec || buried(rec)) continue;
786
+ save(eid);
787
+ let { num, prefix } = rec.entity;
788
+ cold.set(eid, {
789
+ eid,
790
+ num,
791
+ ...prefix == null ? {} : {
792
+ prefix
793
+ }
794
+ });
795
+ put(eid, undefined);
796
+ }
797
+ },
798
+ remove: (entities)=>{
799
+ for (let { eid } of entities){
800
+ let entity = rows.get(eid)?.entity ?? cold.get(eid);
801
+ if (!entity) continue;
802
+ save(eid);
803
+ cold.delete(eid);
804
+ let grave = tombstoned(entity);
805
+ laid.set(grave, new Date().toISOString());
806
+ put(eid, grave);
807
+ }
808
+ },
809
+ discard: (entities)=>{
810
+ for (let { eid } of entities){
811
+ save(eid);
812
+ cold.delete(eid);
813
+ put(eid, undefined);
814
+ }
815
+ },
816
+ prune: (eids)=>{
817
+ let retained = new Set([
818
+ ...trash.values()
819
+ ].flatMap((r)=>r.bundles.map((b)=>b.entity.eid)));
820
+ for (let eid of eids){
821
+ if (retained.has(eid)) continue;
822
+ save(eid);
823
+ cold.delete(eid);
824
+ put(eid, undefined);
825
+ }
826
+ },
827
+ revive: (eids)=>{
828
+ for (let eid of eids){
829
+ let rec = rows.get(eid);
830
+ if (!rec || !buried(rec)) continue;
831
+ save(eid);
832
+ put(eid, {
833
+ entity: rec.entity
834
+ });
835
+ }
836
+ }
837
+ };
838
+ // Tombstones laid before `before` that no stored reference names, oldest
839
+ // first. The cursor is the last grave's time and eid, which still marks
840
+ // the place once that grave is pruned.
841
+ let graves = (before, page)=>{
842
+ let refs = vocab.refProps().filter(([c, p])=>!vocab.prop(c, p)?.computed);
843
+ let named = (eid)=>[
844
+ ...trash.values()
845
+ ].some((r)=>r.bundles.some((b)=>b.entity.eid == eid)) || refs.some(([c, p])=>worn.has(vocab.stored(c)) && !!keys(c, p).get(keyOf(eid))?.size);
846
+ let mark = (at, eid)=>JSON.stringify([
847
+ at,
848
+ eid
849
+ ]);
850
+ let found = [
851
+ ...rows
852
+ ].flatMap(([eid, b])=>{
853
+ let at = laid.get(b);
854
+ return at != null && at < before ? [
855
+ mark(at, eid)
856
+ ] : [];
857
+ }).sort().filter((m)=>page.after == null || m > page.after);
858
+ let seen = found.slice(0, page.limit);
859
+ let eids = seen.map((m)=>JSON.parse(m)[1]).filter((e)=>page.referenced || !named(e));
860
+ return seen.length < page.limit ? {
861
+ eids
862
+ } : {
863
+ eids,
864
+ next: seen.at(-1)
865
+ };
866
+ };
867
+ return {
868
+ extend: (next)=>{
869
+ if (next === vocab) return true;
870
+ if (depth || !extendsVocab(vocab, next)) return false;
871
+ for (let name of next.all){
872
+ if (vocab.comp(name)) continue;
873
+ cells.delete(name);
874
+ uniques.delete(next.stored(name));
875
+ }
876
+ vocab = next;
877
+ hasUnique = uniqueIn(vocab);
878
+ binary = binariesOf(vocab);
879
+ statuses = statusesOf(vocab);
880
+ return true;
881
+ },
882
+ reload: (next)=>{
883
+ if (next === vocab) return true;
884
+ if (depth || !relabelsVocab(vocab, next)) return false;
885
+ let before = [
886
+ ...rows
887
+ ].map(([eid, b])=>[
888
+ eid,
889
+ laid.get(b)
890
+ ]);
891
+ vocab = next;
892
+ hasUnique = uniqueIn(vocab);
893
+ binary = binariesOf(vocab);
894
+ statuses = statusesOf(vocab);
895
+ rows.relabel();
896
+ for (let index of [
897
+ worn,
898
+ filed,
899
+ banded,
900
+ uniques,
901
+ cells
902
+ ])index.clear();
903
+ for (let [eid, at] of before){
904
+ let row = rows.get(eid);
905
+ if (at != null) laid.set(row, at);
906
+ rows.delete(eid);
907
+ put(eid, row);
908
+ }
909
+ return true;
910
+ },
911
+ // A computed override may read another component, even when its named
912
+ // component is absent, so only a stored property's value says it is worn.
913
+ worn: (comp, prop)=>!!vocab.prop(comp, prop) && !vocab.prop(comp, prop)?.computed && !base.computed?.[`${comp}.${prop}`],
914
+ install: ()=>{},
915
+ read,
916
+ rows: raw,
917
+ get,
918
+ buried: graves,
919
+ purgeTrash: (id)=>{
920
+ for (let [key, entry] of trash){
921
+ let bundles = typeof id == 'string' ? key == id ? [] : entry.bundles : entry.bundles.filter((b)=>!id.includes(b.entity.eid));
922
+ if (bundles.length == entry.bundles.length) continue;
923
+ if (depth) trashLog.push([
924
+ key,
925
+ entry
926
+ ]);
927
+ if (bundles.length) trash.set(key, {
928
+ ...entry,
929
+ bundles
930
+ });
931
+ else trash.delete(key);
932
+ }
933
+ },
934
+ trash: (eids, page = {})=>{
935
+ let cursor = page.before ?? (page.after ? trash.get(page.after) : undefined);
936
+ if (page.after && !cursor) return [];
937
+ return structuredClone([
938
+ ...trash.values()
939
+ ].filter((r)=>(!eids || r.bundles.some((b)=>eids.includes(b.entity.eid))) && (!page.id || r.id == page.id) && (!cursor || trashOrder(r, cursor) > 0)).sort(trashOrder).slice(0, trashLimit(page)));
940
+ },
941
+ tx: (body)=>{
942
+ // A nested transaction is a savepoint: it rolls back to where it opened,
943
+ // and its entries stay in the log for the outer one to undo in its turn.
944
+ let trashMark = trashLog.length;
945
+ let mark = log.length;
946
+ let minted = counted();
947
+ depth++;
948
+ let undo = (e)=>{
949
+ while(trashLog.length > trashMark){
950
+ let [id, entry] = trashLog.pop();
951
+ if (entry) trash.set(id, entry);
952
+ else trash.delete(id);
953
+ }
954
+ rewind(mark, minted);
955
+ depth--;
956
+ throw e;
957
+ };
958
+ let done = (out)=>{
959
+ if (--depth == 0) log.length = trashLog.length = 0;
960
+ return out;
961
+ };
962
+ try {
963
+ let out = body(preserving(tx, vocab, (id, at, bundles)=>{
964
+ let before = trash.get(id);
965
+ trashLog.push([
966
+ id,
967
+ before
968
+ ]);
969
+ trash.set(id, {
970
+ id,
971
+ at,
972
+ bundles: [
973
+ ...before?.bundles ?? [],
974
+ ...bundles
975
+ ]
976
+ });
977
+ }));
978
+ return isPromise(out) ? out.then(done, undo) : done(out);
979
+ } catch (e) {
980
+ return undo(e);
981
+ }
982
+ }
983
+ };
984
+ };
985
+ //# sourceMappingURL=store.js.map