@yaks/reach 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/mod.js ADDED
@@ -0,0 +1,1297 @@
1
+ // A graph made of graphs. An entity is one eid wherever it is kept, so the
2
+ // recipe one member holds and the loan another holds about it are one entity
3
+ // wearing two components. A read that names no member is therefore one
4
+ // question asked of every member, answered as one bundle per eid; a write is
5
+ // split by component and each part sent to the member that word lives in.
6
+ //
7
+ // A member is a value: it reads a line, applies bundles, and says its own
8
+ // words. Where it is (a Durable Object, a remote host, a graph in memory) is
9
+ // the caller's business; everything here is the fan-out, the split a mixed
10
+ // filter needs, the merge, and the routing of a write.
11
+ //
12
+ // The split is here and not in a member: a member refuses a word it never
13
+ // planted ("unknown prop: .book"), so `.recipe&.book` cannot be asked of
14
+ // either whole. The line is cut on its own `&` seams, one part per component
15
+ // named, each part asked of every member that speaks it, and the eids in
16
+ // common are the answer. For a disjunction, the alternatives contribute
17
+ // their union of eids. Every member reads ordinary filter lines.
18
+ //
19
+ // Two things this does that no single member can. An order over a spanning
20
+ // answer is settled over the merged bundles, with @yaks/match: each member can
21
+ // only order what it holds. And the vocabulary is the union of what the
22
+ // members declare, the language a merged bundle is written in.
23
+ import { archetypes } from "@yaks/archetype";
24
+ import { edges, stated as statedEdges } from "@yaks/edge";
25
+ import { callerAlias, dead } from "@yaks/graph/bundle";
26
+ import { status } from "@yaks/graph/errors";
27
+ import { derivedEid, identities, isAlias, resolve } from "@yaks/graph/identity";
28
+ import { flat, projection } from "@yaks/graph/read";
29
+ import { keys } from "@yaks/key";
30
+ import { matcher, rows } from "@yaks/match";
31
+ import { and, bareLine, directive, parse, stringify, tokens, windowOf } from "@yaks/query";
32
+ import { CallError } from "@yaks/tools/errors";
33
+ import { loadVocab } from "@yaks/vocab";
34
+ /** Where a bundle's `entity`, and so its `num`, lives when that is a remote
35
+ * member rather than the caller's own graph (`_stores.entity`). A `num` is
36
+ * its store's own, so one from elsewhere is shown with its home.
37
+ *
38
+ * ```ts
39
+ * import { homeOf } from '@yaks/reach'
40
+ * import { assertEquals } from '@std/assert'
41
+ *
42
+ * let eid = 'a3f19c02-4b00-4000-8000-000000000001'
43
+ * assertEquals(
44
+ * homeOf({ entity: { eid, num: 12 }, _stores: { entity: 'yaks.app' } }),
45
+ * 'yaks.app',
46
+ * )
47
+ * assertEquals(homeOf({ entity: { eid, num: 5 } }), undefined)
48
+ * ```
49
+ */ export let homeOf = (b)=>{
50
+ let at = b._stores?.entity;
51
+ return typeof at == 'string' ? at : undefined;
52
+ };
53
+ /** A member's frame as a watch says it: its revisions under the member's
54
+ * `at`, since a revision orders one store's frames and no other's.
55
+ *
56
+ * ```ts
57
+ * import { named } from '@yaks/reach'
58
+ * import { assertEquals } from '@std/assert'
59
+ *
60
+ * assertEquals(
61
+ * named({ bundles: [], revision: 7, since: 6 }, 'home/books'),
62
+ * { bundles: [], revision: { 'home/books': 7 }, since: { 'home/books': 6 } },
63
+ * )
64
+ * ```
65
+ */ export let named = (frame, at)=>{
66
+ let out = {
67
+ ...frame
68
+ };
69
+ if (typeof frame.revision == 'number') out.revision = {
70
+ [at]: frame.revision
71
+ };
72
+ if (typeof frame.since == 'number') out.since = {
73
+ [at]: frame.since
74
+ };
75
+ return out;
76
+ };
77
+ /** A refusal of the caller's own line. */ let refuse = (text)=>new CallError('arguments', text);
78
+ // A member answering 503 is not one with nothing to say: the caller is told,
79
+ // and asks again.
80
+ let down = (e)=>e != null && typeof e == 'object' && 'status' in e && e.status === 503;
81
+ // An error a vocabulary raised reading the caller's line is that line refused.
82
+ let refusing = (e)=>status(e) < 500 ? refuse(e.message) : e;
83
+ // The words a dotted segment can open with that belong to the whole line: the
84
+ // grammar's own riders, its aggregates, and the spine every member's entities
85
+ // share (`.entity.eid=`, which is what `id=` becomes). `.edges`, a retired
86
+ // rider that parses to nothing, is still the line's rather than a component.
87
+ // Everything else after a dot is a component, and it is the segment's part.
88
+ let RIDERS = [
89
+ 'order',
90
+ 'near',
91
+ 'limit',
92
+ 'after',
93
+ 'edges',
94
+ 'kind',
95
+ 'fields'
96
+ ];
97
+ let AGGS = [
98
+ 'count',
99
+ 'distinct',
100
+ 'tally'
101
+ ];
102
+ let LINE = [
103
+ 'entity',
104
+ ...RIDERS,
105
+ ...AGGS
106
+ ];
107
+ let firstWord = (seg)=>/^[.!?]([a-z0-9_]+)/i.exec(seg)?.[1] ?? '';
108
+ // The part a segment belongs to: the component it names, or '' for a segment
109
+ // that is the whole line's business — `id=`, `limit=`, a bare word, a rider.
110
+ let partOf = (seg)=>{
111
+ if (!/^[.!?]/.test(seg)) return '';
112
+ let word = firstWord(seg);
113
+ return LINE.includes(word) ? '' : word;
114
+ };
115
+ // Groups and quoted values stay whole. An OR run also stays one part: its
116
+ // alternatives are asked together, rather than intersected as separate parts.
117
+ let segsOf = (line)=>{
118
+ let segs = [];
119
+ for (let tok of tokens(bareLine(line))){
120
+ let last = segs.length - 1;
121
+ if (last >= 0 && (tok == '|' || segs[last].endsWith('|'))) {
122
+ segs[last] += tok;
123
+ } else segs.push(tok);
124
+ }
125
+ return segs;
126
+ };
127
+ let aggOf = (line)=>segsOf(line).map(firstWord).find((w)=>AGGS.includes(w));
128
+ let limitOf = (line)=>Number(segsOf(line).find((s)=>/^\.?limit=/.test(s))?.split('=')[1]) || undefined;
129
+ // Does this line ask for every component? `*` is a directive in the grammar
130
+ // (@yaks/query), not a word cut out of the line, so this asks the parser
131
+ // rather than the text, the same question @yaks/graph `wanted` asks. A line
132
+ // handed over in pieces need not parse; one that does not asks for nothing
133
+ // wider than what it named.
134
+ let every = (line)=>{
135
+ try {
136
+ return parse(line).clauses.some((c)=>c.kind == 'every');
137
+ } catch {
138
+ return false;
139
+ }
140
+ };
141
+ // The directives that settle a sequence rather than a set. An `.order=` moves
142
+ // that decision past the merge: the property it names may be a word only
143
+ // another member speaks, so no member can be asked to sort by it, and none may
144
+ // cut its answer short, or the rows the order wanted would be gone before the
145
+ // merge saw them. So when the caller asks for an order, these leave the
146
+ // per-member lines and @yaks/match settles them once, over the merged bundles.
147
+ let ORDERS = [
148
+ 'order',
149
+ 'limit',
150
+ 'after'
151
+ ];
152
+ let orderWord = (seg)=>{
153
+ let w = /^\.([a-z0-9_]+)(?:\[last\])?=/i.exec(seg)?.[1] ?? '';
154
+ return ORDERS.includes(w) ? w : '';
155
+ };
156
+ let window = (line)=>{
157
+ let segs = segsOf(line).filter(orderWord);
158
+ return {
159
+ segs,
160
+ order: segs.some((s)=>orderWord(s) == 'order')
161
+ };
162
+ };
163
+ // The order and its window, over the merged bundles, in the union's words.
164
+ // @yaks/match evaluates the same grammar a store compiles to SQL, so a line
165
+ // ordered here and one ordered in one member agree. A directive this
166
+ // vocabulary cannot answer exactly refuses the caller's line, as a single
167
+ // member would: an answer quietly in some other order would be worse.
168
+ let sorting = (orders, vocab)=>{
169
+ if (!orders.order) return (bundles)=>bundles;
170
+ try {
171
+ return matcher(orders.segs.join('&'), vocab);
172
+ } catch (e) {
173
+ throw refusing(e);
174
+ }
175
+ };
176
+ // The component an order reads. A store sorts by a column it never answers,
177
+ // but the merge can only sort what it holds, so this rides the gather whether
178
+ // or not the caller asked to see it, and leaves before the answer does
179
+ // (`unasked`).
180
+ let orderedBy = (orders, vocab)=>{
181
+ let seg = orders.segs.find((s)=>orderWord(s) == 'order');
182
+ let path = seg?.slice(seg.indexOf('=') + 1).replace(/^-/, '');
183
+ return path ? vocab.aim(path)[0]?.comp ?? null : null;
184
+ };
185
+ /** A filter line cut into parts: the segments that name each component, and
186
+ * the ones that ride with every part. A part whose every segment is a request
187
+ * (`?loan`) narrows nothing: it asks for the component, so it is fetched and
188
+ * never intersected.
189
+ *
190
+ * ```ts
191
+ * import { assertEquals } from '@std/assert'
192
+ * let { parts, global } = split('.book&?loan&.limit=5')
193
+ * assertEquals([...parts.keys()], ['book', 'loan'])
194
+ * assertEquals(parts.get('loan')?.asks, true)
195
+ * assertEquals(global, ['.limit=5'])
196
+ * ```
197
+ */ export let split = (line)=>{
198
+ let parts = new Map();
199
+ let global = [];
200
+ for (let seg of segsOf(line)){
201
+ let key = partOf(seg);
202
+ if (!key) global.push(seg);
203
+ else {
204
+ let one = parts.get(key) ?? {
205
+ segs: [],
206
+ asks: true
207
+ };
208
+ one.segs.push(seg);
209
+ one.asks &&= seg.startsWith('?');
210
+ parts.set(key, one);
211
+ }
212
+ }
213
+ return {
214
+ parts,
215
+ global
216
+ };
217
+ };
218
+ // Only the head of a path is in the store being asked. A reverse clause's
219
+ // child condition is about a different row, not another top-level filter.
220
+ let head = (c)=>{
221
+ if (c.kind != 'pred' && c.kind != 'walk') return;
222
+ let name = c.path[0];
223
+ if (!LINE.includes(name)) return name;
224
+ };
225
+ let namesIn = (c)=>{
226
+ if (c.kind == 'or' || c.kind == 'and') return c.clauses.flatMap(namesIn);
227
+ let name = head(c);
228
+ return name ? [
229
+ name
230
+ ] : [];
231
+ };
232
+ let disjunction = (line)=>{
233
+ if (!line.includes('|')) return;
234
+ let q = parse(bareLine(line));
235
+ if (q.clauses.some((c)=>c.kind == 'or')) return q;
236
+ };
237
+ /** The words a line names that another member keeps (`uses`, word → its
238
+ * home), in the line's order.
239
+ *
240
+ * ```ts
241
+ * import { assertEquals } from '@std/assert'
242
+ * assertEquals(borrowed('.fire&?doc&.ash', { ash: 'a', fire: 'b' }), [
243
+ * 'fire',
244
+ * 'ash',
245
+ * ])
246
+ * assertEquals(borrowed('.constructor', {}), [])
247
+ * ```
248
+ */ export let borrowed = (line, uses)=>{
249
+ let q;
250
+ try {
251
+ q = disjunction(line);
252
+ } catch {
253
+ // Syntax refusals still come from the read door.
254
+ }
255
+ let names = q ? new Set(namesIn(q)) : split(line).parts.keys();
256
+ return [
257
+ ...names
258
+ ].filter((name)=>Object.hasOwn(uses, name));
259
+ };
260
+ /** Whether a line names a word another member keeps, which one member cannot
261
+ * answer alone.
262
+ *
263
+ * ```ts
264
+ * import { assertEquals } from '@std/assert'
265
+ * assertEquals(borrows('.fire&?doc', { fire: 'probe' }), true)
266
+ * assertEquals(borrows('.doc&.limit=5', { fire: 'probe' }), false)
267
+ * ```
268
+ */ export let borrows = (line, uses)=>borrowed(line, uses).length > 0;
269
+ /** A page speaks each borrowed component as its home declares it. A draft's
270
+ * own documents can still carry the declaration from its source manifest. */ export let withBorrowedDocs = (own, homes)=>{
271
+ if (!homes.length) return own;
272
+ let borrowed = new Set(homes.flatMap((doc)=>Object.entries(doc.$defs ?? {}).filter(([, def])=>def.component === true).map(([name])=>name)));
273
+ return [
274
+ ...own.map((doc)=>{
275
+ let defs = Object.entries(doc.$defs ?? {});
276
+ let local = defs.filter(([name, def])=>def.component !== true || !borrowed.has(name));
277
+ return local.length == defs.length ? doc : {
278
+ ...doc,
279
+ $defs: Object.fromEntries(local)
280
+ };
281
+ }),
282
+ ...homes
283
+ ];
284
+ };
285
+ let eidOf = (b)=>b.entity?.eid ?? '';
286
+ // The ranking a text query painted on its hits (a query-only `rank`), kept
287
+ // off the candidate rows: the composing read addresses eids and carries no
288
+ // text pred, so the snippet and the score would be lost between the two
289
+ // halves of one search.
290
+ let ranksIn = (heard)=>{
291
+ let ranks = new Map();
292
+ for (let h of heard){
293
+ for (let b of h.bundles){
294
+ if (b.rank && !ranks.has(eidOf(b))) ranks.set(eidOf(b), b.rank);
295
+ }
296
+ }
297
+ return ranks;
298
+ };
299
+ // The eids one fan-out selects, in the order the answer keeps. Ranked hits
300
+ // interleave: a score is one member's own measure and means nothing beside
301
+ // another's, so the merge takes each member's best, then each one's second,
302
+ // the only ordering they all agree with. Everything else is member by member,
303
+ // each in its own order.
304
+ let ordered = (heard)=>{
305
+ let lists = heard.map((h)=>h.bundles);
306
+ let ranked = lists.some((bundles)=>bundles.some((b)=>'rank' in b));
307
+ let out = [];
308
+ if (ranked) {
309
+ for(let i = 0; i < Math.max(0, ...lists.map((l)=>l.length)); i++){
310
+ for (let bundles of lists)if (bundles[i]) out.push(eidOf(bundles[i]));
311
+ }
312
+ } else for (let bundles of lists)for (let b of bundles)out.push(eidOf(b));
313
+ return [
314
+ ...new Set(out.filter(Boolean))
315
+ ];
316
+ };
317
+ // One component's properties as its schema declares them: property → the type
318
+ // word, which is all a disagreement is read out of.
319
+ let propsOf = (schema)=>Object.fromEntries(Object.entries(schema.properties ?? {}).map(([prop, p])=>[
320
+ prop,
321
+ p.enum ? p.enum.join('|') : String(p.type ?? '?')
322
+ ]));
323
+ let spaceOf = (m)=>m.space ?? m.at;
324
+ // Where one name means two things: the same word declared in two spaces with
325
+ // a property they spell differently. Within a space a word has one home and
326
+ // the other members use it, so a disagreement can only be across spaces, and
327
+ // there the name is two words. Properties only one side declares agree by
328
+ // construction: a vocabulary only ever grows.
329
+ let apartIn = (vocabs)=>{
330
+ let seen = new Map();
331
+ for (let { m, doc } of vocabs){
332
+ for (let [name, schema] of Object.entries(doc.$defs ?? {})){
333
+ let by = seen.get(name) ?? new Map();
334
+ seen.set(name, by);
335
+ by.set(spaceOf(m), {
336
+ ...by.get(spaceOf(m)),
337
+ ...propsOf(schema)
338
+ });
339
+ }
340
+ }
341
+ let apart = new Set();
342
+ for (let [name, by] of seen){
343
+ let sides = [
344
+ ...by.values()
345
+ ];
346
+ for(let i = 0; i < sides.length; i++){
347
+ for(let j = i + 1; j < sides.length; j++){
348
+ for (let [prop, type] of Object.entries(sides[i])){
349
+ if (sides[j][prop] && sides[j][prop] != type) apart.add(name);
350
+ }
351
+ }
352
+ }
353
+ }
354
+ return apart;
355
+ };
356
+ // `_stores`, on a bundle that must say where it lives: its pieces live in
357
+ // more than one place, or its number is a remote member's (`entity`).
358
+ let storesOf = (where)=>where.entity || new Set(Object.values(where)).size > 1 ? {
359
+ _stores: where
360
+ } : {};
361
+ let optional = (c)=>c.kind == 'pred' && c.op == '?' && c.path.length == 1 && !c.where && !c.not;
362
+ let oneWord = (c)=>{
363
+ if (c.kind != 'and' && c.kind != 'or') return head(c);
364
+ let [first, ...rest] = c.clauses.map(oneWord);
365
+ return first && rest.every((word)=>word == first) ? first : undefined;
366
+ };
367
+ let selectionOf = (clauses, rides = [])=>{
368
+ let by = new Map();
369
+ let global = [
370
+ ...rides
371
+ ];
372
+ let mixed = [];
373
+ for (let c of clauses){
374
+ if (optional(c)) continue;
375
+ let name = oneWord(c);
376
+ if (name) by.set(name, [
377
+ ...by.get(name) ?? [],
378
+ c
379
+ ]);
380
+ else if (c.kind == 'or') mixed.push(c.clauses);
381
+ else global.push(c);
382
+ }
383
+ let ask = (cs, name)=>({
384
+ kind: 'ask',
385
+ name,
386
+ line: stringify(and(...cs))
387
+ });
388
+ let parts = [
389
+ ...by
390
+ ].map(([name, cs])=>ask([
391
+ ...cs,
392
+ ...global
393
+ ], name));
394
+ for (let arms of mixed){
395
+ parts.push({
396
+ kind: 'or',
397
+ parts: arms.map((c)=>selectionOf(c.kind == 'and' ? c.clauses : [
398
+ c
399
+ ], global))
400
+ });
401
+ }
402
+ if (parts.length == 1) return parts[0];
403
+ if (parts.length) return {
404
+ kind: 'and',
405
+ parts
406
+ };
407
+ return ask(global.length ? global : parse('.entity').clauses);
408
+ };
409
+ let selectors = (clauses)=>selectionOf(clauses.filter((c)=>!directive(c) || c.kind == 'near'));
410
+ let intersect = ([first, ...rest])=>rest.reduce((kept, set)=>{
411
+ let have = new Set(set);
412
+ return kept.filter((e)=>have.has(e));
413
+ }, first ?? []);
414
+ let selected = async (selection, ask)=>{
415
+ if (selection.kind == 'ask') return ask(selection.name, selection.line);
416
+ let sets = await Promise.all(selection.parts.map((p)=>selected(p, ask)));
417
+ return selection.kind == 'or' ? [
418
+ ...new Set(sets.flat())
419
+ ] : intersect(sets);
420
+ };
421
+ /** A composition over a shared language: the operations every set of
422
+ * members is asked through. */ export let reach = (words)=>{
423
+ let { core, hidden = ()=>false, silent = ()=>{}, stops = ()=>false } = words;
424
+ let union = words.union ?? ((defs)=>loadVocab([
425
+ ...core.docs,
426
+ {
427
+ title: 'space',
428
+ $defs: defs
429
+ }
430
+ ]));
431
+ // One line, asked of every member at once. One that refuses contributes
432
+ // nothing (the word is another's, or this one is not the caller's to read),
433
+ // but a line every member refuses is a line nobody can answer, and then the
434
+ // first member's refusal is what the caller reads. A member that is down,
435
+ // or that `stops` the read, fails it: its rows exist and were not sent.
436
+ let asked = async (members, line, said, live = false)=>{
437
+ let tried = await Promise.all(members.map(async (m)=>{
438
+ try {
439
+ let out = await m.read(line, {
440
+ said,
441
+ live
442
+ });
443
+ return {
444
+ at: m.at,
445
+ bundles: Array.isArray(out) ? out : []
446
+ };
447
+ } catch (e) {
448
+ // A member left out of the merge is a quieter answer, never a silent
449
+ // one; one answering 503 is not left out at all.
450
+ silent(e, m);
451
+ return {
452
+ at: m.at,
453
+ why: e
454
+ };
455
+ }
456
+ }));
457
+ let gone = tried.find((t)=>'why' in t && (down(t.why) || stops(t.why)));
458
+ if (gone) throw gone.why;
459
+ let heard = tried.filter((t)=>'bundles' in t);
460
+ if (!heard.length && tried.length) {
461
+ throw tried[0].why;
462
+ }
463
+ return heard;
464
+ };
465
+ // A member's own word is the most specific thing said about a row, wherever
466
+ // it was said (@yaks/vocab kindOf), so a member's kind outranks a core kind
467
+ // from another, and the union decides the rest. Between two members' words
468
+ // the filter decides, and `must` names the components it required:
469
+ // `?loan&.book` asks for books, so a book is what each answer is. `at` is
470
+ // the member whose word won, whose archetype the composed bundle carries.
471
+ let kindFrom = (kinds, comps, must = [])=>{
472
+ let own = kinds.filter(([, k])=>k && !core.kinds.includes(k));
473
+ let said = own.find(([, k])=>must.includes(k)) ?? own[0];
474
+ return {
475
+ kind: said?.[1] ?? core.kinds.find((k)=>k in comps) ?? 'entity',
476
+ at: said?.[0] ?? kinds[0]?.[0]
477
+ };
478
+ };
479
+ // What every member holds about these eids, gathered in one fan-out: the
480
+ // components, the kind each member called the row, and where each component
481
+ // lives. The read composes bundles out of it; the write routes by it.
482
+ // `apart` names the words kept per space rather than merged, because one
483
+ // name meaning two things is two answers, not one bundle.
484
+ let gathered = async (members, eids, apart = new Set(), said, live = false)=>{
485
+ let held = new Map();
486
+ if (!eids.length) return held;
487
+ let spaces = new Map(members.map((m)=>[
488
+ m.at,
489
+ spaceOf(m)
490
+ ]));
491
+ let remote = new Set(members.filter((m)=>m.remote).map((m)=>m.at));
492
+ let heard = await asked(members, `.entity.eid=${eids.join(',')}`, said, live);
493
+ for (let { at, bundles } of heard){
494
+ for (let row of bundles){
495
+ let eid = eidOf(row);
496
+ if (!eid) continue;
497
+ // The spine is held once, here: its archetype is the answering
498
+ // member's and is chosen with the kind, so no merge of the components
499
+ // may spell it a second time.
500
+ let { archetype, ...spine } = row.entity;
501
+ // A member composed of others (yaks.app across its stores) says
502
+ // where within it each piece lives, which is said here within it.
503
+ let inner = row._stores ?? {};
504
+ let within = (name)=>inner[name] ? `${at}/${inner[name]}` : at;
505
+ let one = held.get(eid);
506
+ if (!one) {
507
+ one = {
508
+ entity: spine,
509
+ comps: {},
510
+ kinds: {},
511
+ arch: {},
512
+ home: {},
513
+ where: {},
514
+ split: {}
515
+ };
516
+ if (remote.has(at) || inner.entity) {
517
+ one.where.entity = within('entity');
518
+ }
519
+ held.set(eid, one);
520
+ }
521
+ if (archetype != null) one.arch[at] ??= archetype;
522
+ for (let [name, comp] of Object.entries(row)){
523
+ if (name == 'kind' || name == 'entity' || name == '_stores') continue;
524
+ if (apart.has(name)) {
525
+ one.split[name] ??= {};
526
+ one.split[name][spaces.get(at) ?? at] ??= {
527
+ at,
528
+ where: within(name),
529
+ comp
530
+ };
531
+ continue;
532
+ }
533
+ if (name in one.comps) continue;
534
+ one.comps[name] = comp;
535
+ one.home[name] = at;
536
+ one.where[name] = within(name);
537
+ }
538
+ one.kinds[at] ??= String(row.kind ?? '');
539
+ }
540
+ }
541
+ return held;
542
+ };
543
+ /** One bundle per eid, out of every member that holds a piece of it. The
544
+ * first member that answers a component owns it here; `entity` is the
545
+ * first member's, whose archetype comes from the member whose word named
546
+ * the kind. `_stores` says which member holds which component, and rides
547
+ * on a bundle that spans two or wears a remote member's piece; it names
548
+ * `entity` too when the spine, and so the `num`, is a remote member's. */ let gatheredRows = async (members, eids, ask = {})=>{
549
+ let { want = null, apart = new Set(), said, must, live = false } = ask;
550
+ let spaces = new Map(members.map((m)=>[
551
+ m.at,
552
+ spaceOf(m)
553
+ ]));
554
+ let held = await gathered(members, eids, apart, said, live);
555
+ let keeps = (name)=>!want || want.has(name);
556
+ let bundle = (one, extra, home, space)=>{
557
+ let comps = Object.fromEntries([
558
+ ...Object.entries(one.comps).filter(([n])=>keeps(n)),
559
+ ...Object.entries(extra).filter(([n])=>keeps(n))
560
+ ]);
561
+ let where = Object.fromEntries(Object.entries({
562
+ ...one.where,
563
+ ...home
564
+ }).filter(([n])=>n == 'entity' || keeps(n)));
565
+ let said = kindFrom(Object.entries(one.kinds).filter(([at])=>!space || spaces.get(at) == space), comps, must);
566
+ let archetype = said.at ? one.arch[said.at] : undefined;
567
+ return {
568
+ kind: said.kind,
569
+ entity: archetype ? {
570
+ ...one.entity,
571
+ archetype
572
+ } : one.entity,
573
+ // Two spaces mean two things by this word, so the row says which one
574
+ // it is answering for.
575
+ ...space ? {
576
+ space
577
+ } : {},
578
+ ...comps,
579
+ ...storesOf(where)
580
+ };
581
+ };
582
+ let parted = (one, space)=>{
583
+ let mine = Object.entries(one.split).flatMap(([n, by])=>space ? by[space] ? [
584
+ [
585
+ n,
586
+ by[space]
587
+ ]
588
+ ] : [] : Object.values(by).map((h)=>[
589
+ n,
590
+ h
591
+ ]));
592
+ return bundle(one, Object.fromEntries(mine.map(([n, h])=>[
593
+ n,
594
+ h.comp
595
+ ])), Object.fromEntries(mine.map(([n, h])=>[
596
+ n,
597
+ h.where
598
+ ])), space);
599
+ };
600
+ let bundles = eids.filter((e)=>held.has(e)).flatMap((eid)=>{
601
+ let one = held.get(eid);
602
+ // The spaces this entity wears a disputed word in. None, and the bundle
603
+ // is one; two, and it is one per space: the same eid, answered twice,
604
+ // because the name is not one word.
605
+ let spaces = [
606
+ ...new Set(Object.entries(one.split).filter(([n])=>keeps(n)).flatMap(([, by])=>Object.keys(by)))
607
+ ];
608
+ return spaces.length < 2 ? [
609
+ parted(one)
610
+ ] : spaces.map((space)=>parted(one, space));
611
+ });
612
+ return {
613
+ bundles,
614
+ held
615
+ };
616
+ };
617
+ let composed = async (members, eids, ask)=>(await gatheredRows(members, eids, ask)).bundles;
618
+ let located = async (members, eids, ask)=>{
619
+ let { bundles, held } = await gatheredRows(members, eids, ask);
620
+ let sources = new Set();
621
+ for (let row of held.values()){
622
+ for (let source of Object.keys(row.kinds))sources.add(source);
623
+ }
624
+ return {
625
+ bundles,
626
+ sources
627
+ };
628
+ };
629
+ // Every word in reach as one vocabulary: the core plus each member's own. A
630
+ // word two members declare is loaded once, from its first declarer: a word
631
+ // has one home, and @yaks/vocab refuses a name declared twice.
632
+ let unioned = (docs)=>{
633
+ let defs = {};
634
+ for (let doc of docs){
635
+ for (let [name, schema] of Object.entries(doc.$defs ?? {})){
636
+ if (name in defs || core.all.includes(name)) continue;
637
+ defs[name] = schema;
638
+ }
639
+ }
640
+ return union(defs, docs);
641
+ };
642
+ let declarations = (members)=>Promise.all(members.map(async (m)=>({
643
+ m,
644
+ doc: await m.vocab()
645
+ })));
646
+ /** Which members declare which word, in member order, so the first
647
+ * declarer is the word's home; the words two spaces mean two things by
648
+ * (`apart`); and the union of every member's words (`vocab`).
649
+ *
650
+ * A core word is nobody's: a member that held it before the core said it
651
+ * keeps it in its own graph, but every other member speaks the core's, so
652
+ * it is not that member's to home. */ let spoken = async (members, own)=>{
653
+ own ??= await declarations(members);
654
+ let words = new Map();
655
+ for (let { m, doc } of own){
656
+ for (let w of Object.keys(doc.$defs ?? {})){
657
+ if (core.all.includes(w)) continue;
658
+ words.set(w, [
659
+ ...words.get(w) ?? [],
660
+ m
661
+ ]);
662
+ }
663
+ }
664
+ return {
665
+ words,
666
+ apart: apartIn(own),
667
+ vocab: unioned(own.map((o)=>o.doc))
668
+ };
669
+ };
670
+ // The line's `.fields` projection in the union's words, or none. A path
671
+ // those words cannot read is the caller's line refused, as a member
672
+ // refuses it.
673
+ let planned = (line, vocab)=>{
674
+ try {
675
+ return projection(vocab, bareLine(line));
676
+ } catch (e) {
677
+ throw refusing(e);
678
+ }
679
+ };
680
+ // A `.fields` projection over the merge. The members chose the entities and
681
+ // the merge holds them whole, so each entity a path reaches is gathered
682
+ // here, hop by hop and from every member, and the paths are read off the
683
+ // lot the way a store reads them off its own rows.
684
+ let projected = async (members, vocab, p, found, live)=>{
685
+ if (!found.length) return [];
686
+ let held = new Map(found.map((b)=>[
687
+ eidOf(b),
688
+ b
689
+ ]));
690
+ let read = rows({
691
+ kind: 'and',
692
+ clauses: [
693
+ ...parse(`.entity.eid=${[
694
+ ...held.keys()
695
+ ].join(',')}`).clauses,
696
+ ...p.query.clauses.filter((c)=>c.kind == 'fields')
697
+ ]
698
+ }, vocab);
699
+ let seen = new Set(held.keys());
700
+ while(true){
701
+ let got = read([
702
+ ...held.values()
703
+ ]);
704
+ let more = [
705
+ ...new Set(got.flatMap((r)=>p.reaches.map((c)=>r[c])))
706
+ ].filter((e)=>typeof e == 'string' && !seen.has(e));
707
+ if (!more.length) {
708
+ return flat(p.fold(got)).map((b)=>{
709
+ let kind = held.get(eidOf(b))?.kind;
710
+ return kind ? {
711
+ kind,
712
+ ...b
713
+ } : b;
714
+ });
715
+ }
716
+ for (let e of more)seen.add(e);
717
+ for (let b of (await composed(members, more, {
718
+ live
719
+ }))){
720
+ held.set(eidOf(b), b);
721
+ }
722
+ }
723
+ };
724
+ // A component off a merged bundle the caller's own line would not carry:
725
+ // one it did not name when it named any (@yaks/graph `wanted`), or one the
726
+ // members' answers leave off unless named (`hidden`).
727
+ let unasked = (comp, want, line)=>{
728
+ let kept = (want ? want.has(comp) : true) && !hidden(comp, line);
729
+ return (b)=>{
730
+ if (kept) return b;
731
+ let out = {
732
+ ...b
733
+ };
734
+ let homes = Object.entries(b._stores ?? {}).filter(([name])=>name != comp);
735
+ delete out[comp];
736
+ delete out._stores;
737
+ return {
738
+ ...out,
739
+ ...storesOf(Object.fromEntries(homes))
740
+ };
741
+ };
742
+ };
743
+ /** The read, whole. One member and this is that member's own answer,
744
+ * untouched. Several, and the line is split, each part asked of the members
745
+ * that speak it, the eids in common taken (a filter's `&` is an
746
+ * intersection), and the bundles composed.
747
+ *
748
+ * A window is the one place the split shows: `limit=` bounds each part
749
+ * before the parts meet. Unless the caller asked for an order, and then the
750
+ * sequence is nobody's to cut until the bundles are one: the order and the
751
+ * window run over the merged answer, in the union's words. */ let read = async (members, line, live = false)=>{
752
+ if (members.length == 1) return await members[0].read(line, {
753
+ live
754
+ });
755
+ let or = disjunction(line);
756
+ let shaped = or ? stringify(or) : line;
757
+ let agg = aggOf(shaped);
758
+ if (agg && agg != 'count') {
759
+ throw refuse(`a ${agg} reads one app at a time and this reads them all — ask for ` + 'the rows and reduce them');
760
+ }
761
+ let { parts, global } = split(shaped);
762
+ let orders = window(shaped);
763
+ // A projection is read off the merge (`projected`), so the members are
764
+ // asked only which entities the filter selects.
765
+ let plain = global.filter((s)=>!AGGS.includes(firstWord(s)) && !(orders.order && orderWord(s)) && firstWord(s) != 'fields');
766
+ // Which members a word is asked of: the ones whose vocabulary declares
767
+ // it, and every member for a word nobody declares, which is the core's
768
+ // and spoken everywhere.
769
+ let { words, apart, vocab } = await spoken(members);
770
+ let sorted = sorting(orders, vocab);
771
+ let p = planned(line, vocab);
772
+ let speak = (name)=>words.get(name) ?? members;
773
+ let need = [
774
+ ...parts
775
+ ].filter(([, part])=>!part.asks);
776
+ let lines = need.length ? need.map(([name, part])=>[
777
+ speak(name),
778
+ [
779
+ ...part.segs,
780
+ ...plain
781
+ ].join('&')
782
+ ]) : [
783
+ [
784
+ members,
785
+ plain.join('&')
786
+ ]
787
+ ];
788
+ let ranks = new Map();
789
+ let matches = async (who, query)=>{
790
+ let heard = await asked(who, query, undefined, live);
791
+ for (let [eid, rank] of ranksIn(heard))ranks.set(eid, rank);
792
+ return ordered(heard);
793
+ };
794
+ let eids = or ? await selected(selectors(or.clauses), (name, query)=>matches(name ? speak(name) : members, `${query}&.fields=entity.eid`)) : intersect(await Promise.all(lines.map(([who, query])=>matches(who, query))));
795
+ let { limit, after } = or ? windowOf(or) : {
796
+ limit: limitOf(line)
797
+ };
798
+ // An OR's window belongs to the union, not to any arm. An eid cursor
799
+ // already identifies the anchor in that sequence; a numeric cursor needs
800
+ // the composed spine. An explicit order is settled on the merged rows.
801
+ let numeric = or && !orders.order && typeof after == 'number';
802
+ if (or && agg == 'count') return {
803
+ count: eids.length
804
+ };
805
+ if (!orders.order && !numeric) {
806
+ let start = typeof after == 'string' ? eids.indexOf(after) + 1 : 0;
807
+ eids = eids.slice(start, limit == null ? undefined : start + limit);
808
+ }
809
+ if (agg == 'count') return {
810
+ count: eids.length
811
+ };
812
+ // The bundle is read from the members that speak a word the line named,
813
+ // and carries those components (@yaks/graph `wanted`). A part this cannot
814
+ // confirm is a component asks for the whole bundle rather than guess, and
815
+ // `*` is the grammar's widest projection. A `.fields` projection reads
816
+ // its properties off the whole merge, wherever they live.
817
+ let named = or ? [
818
+ ...new Set(namesIn(or))
819
+ ] : [
820
+ ...parts.keys()
821
+ ];
822
+ let want = named.length && !every(line) && !p && named.every((n)=>words.has(n) || core.all.includes(n)) ? new Set(named) : null;
823
+ // In reach order, whatever order the line names its words in: the first
824
+ // member holding the entity gives its spine, and so its `num`.
825
+ let by = orderedBy(orders, vocab);
826
+ let asks = new Set([
827
+ ...named,
828
+ ...by ? [
829
+ by
830
+ ] : []
831
+ ].flatMap(speak));
832
+ let from = !or && named.length && !p ? members.filter((m)=>asks.has(m)) : members;
833
+ let bundles = await composed(from, eids, {
834
+ want: want && by ? new Set([
835
+ ...want,
836
+ by
837
+ ]) : want,
838
+ apart,
839
+ said: by ? `${line}&?${by}` : line,
840
+ must: or ? or.clauses.flatMap((c)=>!optional(c) && head(c) ? [
841
+ head(c)
842
+ ] : []) : need.map(([name])=>name),
843
+ live
844
+ });
845
+ let out = sorted(bundles.map((b)=>{
846
+ let rank = ranks.get(eidOf(b));
847
+ return rank ? {
848
+ ...b,
849
+ rank
850
+ } : b;
851
+ }));
852
+ if (numeric) {
853
+ let start = out.findIndex((b)=>b.entity.num == after) + 1;
854
+ out = out.slice(start, limit == null ? undefined : start + limit);
855
+ }
856
+ if (p) return await projected(members, vocab, p, out, live);
857
+ return by ? out.map(unasked(by, want, line)) : out;
858
+ };
859
+ /** The batch, split by component into one part per member, with every
860
+ * `$alias` minted once for all of them. `key` derives the mints, so the
861
+ * same batch sent again mints the same eids. */ let routed = async (members, named, bundles, key, defaultSpace)=>{
862
+ // A sandboxed copy owns only writes aimed at it, and a write aimed at a
863
+ // member stays in its space: spaces share no home, so another space's
864
+ // declarer, holder or mate is never where a part goes. Every routing
865
+ // decision chooses from the same eligible members.
866
+ members = members.filter((m)=>(!m.sandboxed || m == named) && (!named || spaceOf(m) == spaceOf(named)));
867
+ let scope = await declarations(members);
868
+ let target = scope.find(({ m })=>m === named);
869
+ let own = target?.doc.local ? [
870
+ target
871
+ ] : scope.filter(({ doc })=>!doc.local);
872
+ members = own.map(({ m })=>m);
873
+ let { words, apart, vocab } = await spoken(members, own);
874
+ let { entities, eids, aliases } = await minted(bundles, vocab, key, async (eids)=>{
875
+ let held = await gathered(members, eids);
876
+ return [
877
+ ...held.values()
878
+ ].map((b)=>({
879
+ entity: b.entity,
880
+ ...b.comps
881
+ }));
882
+ });
883
+ // Where the entity already lives, read only when the answer depends on
884
+ // it: a death fans out to whoever holds the eid, and a shared word with no
885
+ // member named goes to the one that already wears it.
886
+ let asking = entities.flatMap((e, i)=>eids[i] && (dead(e) || !named && Object.keys(e).some((k)=>isComp(k) && !words.has(k))) ? [
887
+ eids[i]
888
+ ] : []);
889
+ let held = await gathered(members, asking);
890
+ let by = (label)=>members.find((m)=>m.at == label);
891
+ // What `$app` takes for a member: its name, or its `at` where another
892
+ // member answers to the same name, as two spaces' `recipes` do.
893
+ let called = (m)=>members.filter((o)=>(o.name ?? o.at) == (m.name ?? m.at)).length > 1 ? m.at : m.name ?? m.at;
894
+ let slugs = (ms = members)=>ms.length > 3 ? `${ms.length} candidate apps` : ms.map(called).join(', ');
895
+ let onBundle = (m)=>m ? `on the bundle, as "$app": "${called(m)}"` : 'on the bundle with $app';
896
+ let remembered;
897
+ let preferred = ()=>remembered ??= (members.length > 1 ? defaultSpace?.() : undefined)?.then((space)=>{
898
+ let there = members.filter((m)=>spaceOf(m) == space);
899
+ return there.length == 1 ? there[0] : undefined;
900
+ }) ?? Promise.resolve(undefined);
901
+ let available = ()=>{
902
+ if (!members.length) throw refuse('no app in reach — deploy an app first');
903
+ };
904
+ // The one member a bundle that cannot be split goes to.
905
+ let only = async ()=>{
906
+ if (named) return named;
907
+ if (members.length == 1) return members[0];
908
+ let there = await preferred();
909
+ if (there) return there;
910
+ available();
911
+ throw refuse(`name the app this goes in ${onBundle(members[0])} — ${slugs()}`);
912
+ };
913
+ let home = async (name, eid, mates)=>{
914
+ let declared = words.get(name) ?? [];
915
+ let mine = eid ? held.get(eid)?.home ?? {} : {};
916
+ if (declared.length) {
917
+ // A word has one home: the first member to declare it. A second
918
+ // member declaring the same word is a use of it, and its writes land
919
+ // in the home. Where the entity already wears the word wins over
920
+ // birth order, and a named member wins over both when it is one of
921
+ // the declarers, since across spaces two members may mean two things
922
+ // by one name.
923
+ let where = mine[name] && by(mine[name]);
924
+ if (where && declared.includes(where)) return where;
925
+ if (named && declared.includes(named)) return named;
926
+ // Across spaces the shapes may disagree, and then the name is two
927
+ // words: nothing here can pick between them, so the caller does.
928
+ let homes = [
929
+ ...new Set(declared.map(spaceOf))
930
+ ].map((s)=>declared.find((m)=>spaceOf(m) == s));
931
+ if (apart.has(name) && homes.length > 1) {
932
+ let there = await preferred();
933
+ if (there && declared.includes(there)) return there;
934
+ throw refuse(`${name} has different declarations across spaces; name an app ` + `${onBundle(homes[0])} — ${slugs(homes)}`);
935
+ }
936
+ return declared[0];
937
+ }
938
+ if (named) return named;
939
+ let where = mine[name] && by(mine[name]);
940
+ if (where) return where;
941
+ let holders = [
942
+ ...new Set(Object.values(mine))
943
+ ].map(by).filter(Boolean);
944
+ if (holders.length == 1) return holders[0];
945
+ // A title beside a recipe is the recipe's title: a shared word with
946
+ // nowhere else to go rides with the member whose own words are in the
947
+ // same bundle, which is what makes writing a new entity one call.
948
+ if (mates.length == 1) return mates[0];
949
+ if (members.length == 1) return members[0];
950
+ if (!holders.length && !mates.length) {
951
+ let there = await preferred();
952
+ if (there) return there;
953
+ }
954
+ available();
955
+ throw refuse(`which app should ${name} go in? name it ${onBundle(mates[0] ?? members[0])} — ${slugs(mates.length ? mates : members)}`);
956
+ };
957
+ let parts = new Map();
958
+ let add = (m, e)=>parts.set(m, [
959
+ ...parts.get(m) ?? [],
960
+ e
961
+ ]);
962
+ for (let [i, e] of entities.entries()){
963
+ let eid = eids[i];
964
+ if (!eid) {
965
+ add(await only(), e);
966
+ continue;
967
+ }
968
+ // Death is the whole entity's, so it goes wherever the entity is: every
969
+ // member holding a piece of it, and the one named when none does yet.
970
+ if (dead(e)) {
971
+ let holders = [
972
+ ...new Set(Object.values(held.get(eid)?.home ?? {}))
973
+ ].map(by).filter(Boolean);
974
+ for (let m of holders.length ? holders : [
975
+ await only()
976
+ ]){
977
+ add(m, {
978
+ entity: {
979
+ eid
980
+ },
981
+ tombstone: {}
982
+ });
983
+ }
984
+ continue;
985
+ }
986
+ // A `$was` guard rides with the component it guards, whether or not
987
+ // this batch also writes that component: a precondition that lost its
988
+ // part would silently stop guarding.
989
+ let guards = e.$was ?? {};
990
+ let names = [
991
+ ...new Set([
992
+ ...Object.keys(e).filter(isComp),
993
+ ...Object.keys(guards)
994
+ ])
995
+ ];
996
+ let mine = new Map();
997
+ let take = (m, name)=>mine.set(m, [
998
+ ...mine.get(m) ?? [],
999
+ name
1000
+ ]);
1001
+ // The members' own words first: they are what a shared word rides with.
1002
+ for (let name of names.filter((n)=>words.has(n))){
1003
+ take(await home(name, eid, []), name);
1004
+ }
1005
+ let mates = [
1006
+ ...mine.keys()
1007
+ ];
1008
+ for (let name of names.filter((n)=>!words.has(n))){
1009
+ take(await home(name, eid, mates), name);
1010
+ }
1011
+ for (let [m, keys] of mine){
1012
+ let was = Object.fromEntries(Object.entries(guards).filter(([n])=>keys.includes(n)));
1013
+ add(m, {
1014
+ entity: {
1015
+ ...e.entity,
1016
+ eid
1017
+ },
1018
+ ...Object.fromEntries(keys.filter((n)=>n in e).map((n)=>[
1019
+ n,
1020
+ e[n]
1021
+ ])),
1022
+ ...Object.keys(was).length ? {
1023
+ $was: was
1024
+ } : {},
1025
+ // and the alias the caller named it by, which every part carries:
1026
+ // it is how a store tells an id this picked from one the caller
1027
+ // wrote down (@yaks/alias).
1028
+ ...typeof e.$alias == 'string' ? {
1029
+ $alias: e.$alias
1030
+ } : {}
1031
+ });
1032
+ }
1033
+ }
1034
+ return {
1035
+ parts: [
1036
+ ...parts
1037
+ ].map(([member, entities])=>({
1038
+ member,
1039
+ entities
1040
+ })),
1041
+ aliases
1042
+ };
1043
+ };
1044
+ /** The write, whole: routed, rehearsed in every member, then committed. A
1045
+ * refusal in any member leaves every other unwritten, because the rehearsal
1046
+ * went first; a single part needs no second round trip, since its commit is
1047
+ * its rehearsal. A refusal after the rehearsal may follow another part's
1048
+ * commit, so it comes back marked `partial`: the caller must not send the
1049
+ * batch again. `check` stops at the rehearsal, which is then the answer. */ let written = async (members, named, bundles, opts = {})=>{
1050
+ let { key, check = false, defaultSpace } = opts;
1051
+ if (!bundles.length) {
1052
+ return {
1053
+ bundles: [],
1054
+ aliases: {},
1055
+ where: ''
1056
+ };
1057
+ }
1058
+ let { parts, aliases } = await routed(members, named, bundles, key, defaultSpace);
1059
+ if (!parts.length) {
1060
+ throw refuse('No bundle has a change to route. Send a component patch, ' + 'a $delete, or a $was guard alongside the entity address. ' + 'For example, bundles: [{"entity":{"eid":"<eid>"},"doc":{"title":"…"}}].');
1061
+ }
1062
+ if (parts.length > 1 && !check) {
1063
+ await Promise.all(parts.map((p)=>p.member.apply(p.entities, true)));
1064
+ }
1065
+ let outs = await Promise.all(parts.map((p)=>p.member.apply(p.entities, check))).catch((e)=>{
1066
+ throw parts.length > 1 && !check ? Object.assign(e, {
1067
+ partial: true
1068
+ }) : e;
1069
+ });
1070
+ let applied = outs.flat();
1071
+ // Where a `$alias` landed. A member may put a bundle somewhere other than
1072
+ // the id minted for it: one carrying a name somebody already holds is a
1073
+ // patch of that entity (@yaks/alias), and the batch as applied says so.
1074
+ for (let b of applied){
1075
+ if (callerAlias(b.$alias)) aliases[b.$alias] = b.entity.eid;
1076
+ }
1077
+ return {
1078
+ bundles: applied,
1079
+ aliases,
1080
+ where: parts.map((p)=>p.member.at).join(' and ')
1081
+ };
1082
+ };
1083
+ /** The read, live. One member and this is that member's own watch. With
1084
+ * several, each member that speaks a word the line names watches its part
1085
+ * of the line, and any frame one sends is news: the line is read again,
1086
+ * whole, and its answer sent with `reset` when it moved. So a watch answers
1087
+ * exactly what the read does, its merge, order and count included. Reads
1088
+ * the news raises while one is out share the next. Each frame's revisions
1089
+ * are under their members' `at` ({@link named}); a read again says the
1090
+ * newest each member's news had said when it began, which its rows are no
1091
+ * older than. */ let watch = (members, line, sink)=>{
1092
+ let [one] = members;
1093
+ if (members.length == 1 && one.watch) {
1094
+ return one.watch(line, (frame)=>sink(named(frame, one.at)));
1095
+ }
1096
+ let closed = false, reading = false, again = false;
1097
+ let said;
1098
+ let heard = {};
1099
+ let send = (frame, key)=>{
1100
+ if (closed || key == said) return;
1101
+ said = key;
1102
+ sink(frame);
1103
+ };
1104
+ let ask = async ()=>{
1105
+ if (reading) return void (again = true);
1106
+ reading = true;
1107
+ do {
1108
+ again = false;
1109
+ let at = {
1110
+ ...heard
1111
+ };
1112
+ try {
1113
+ let out = await read(members, line, true);
1114
+ let frame = Array.isArray(out) ? {
1115
+ bundles: out,
1116
+ reset: true
1117
+ } : out;
1118
+ let key = JSON.stringify(frame);
1119
+ if (Object.keys(at).length) frame = {
1120
+ ...frame,
1121
+ revision: at
1122
+ };
1123
+ send(frame, key);
1124
+ } catch (e) {
1125
+ send({
1126
+ refused: e
1127
+ }, `refused ${e?.message}`);
1128
+ }
1129
+ }while (again && !closed)
1130
+ reading = false;
1131
+ };
1132
+ let stops = [];
1133
+ void ask();
1134
+ void news(members, line).then((lines)=>{
1135
+ for (let [m, part] of lines){
1136
+ if (closed) continue;
1137
+ stops.push(m.watch(part, (frame)=>{
1138
+ let revision = named(frame, m.at).revision;
1139
+ for (let [at, n] of Object.entries(revision ?? {})){
1140
+ heard[at] = Math.max(heard[at] ?? n, n);
1141
+ }
1142
+ void ask();
1143
+ }));
1144
+ }
1145
+ }, (e)=>send({
1146
+ refused: e
1147
+ }, `refused ${e?.message}`));
1148
+ return ()=>{
1149
+ closed = true;
1150
+ for (let stop of stops)stop();
1151
+ };
1152
+ };
1153
+ // Who tells a watch across members that its answer may have moved, and
1154
+ // what each watches: every member speaking a word the line names, its part
1155
+ // of the line (a request, `?loan`, as the presence of the word), with the
1156
+ // filters every part rides with. A line naming no word is watched whole by
1157
+ // every member. Riders and reductions shape an answer, not which rows
1158
+ // move it, so they stay out.
1159
+ let news = async (members, line)=>{
1160
+ let live = members.filter((m)=>m.watch);
1161
+ let or = disjunction(line);
1162
+ if (or) {
1163
+ let { words } = await spoken(live);
1164
+ let homes = (name)=>name && words.get(name) || live;
1165
+ let watch = (s)=>s.kind == 'ask' ? homes(s.name).map((m)=>[
1166
+ m,
1167
+ s.line
1168
+ ]) : s.parts.flatMap(watch);
1169
+ return [
1170
+ ...watch(selectors(or.clauses)),
1171
+ ...or.clauses.filter(optional).flatMap((c)=>homes(head(c)).map((m)=>[
1172
+ m,
1173
+ `.${head(c)}`
1174
+ ]))
1175
+ ];
1176
+ }
1177
+ let { parts, global } = split(line);
1178
+ let rides = global.filter((s)=>![
1179
+ ...RIDERS,
1180
+ ...AGGS
1181
+ ].includes(firstWord(s)));
1182
+ if (!parts.size) return live.map((m)=>[
1183
+ m,
1184
+ rides.join('&') || '.entity'
1185
+ ]);
1186
+ let { words } = await spoken(live);
1187
+ return [
1188
+ ...parts
1189
+ ].flatMap(([name, part])=>{
1190
+ let segs = part.asks ? [
1191
+ `.${name}`
1192
+ ] : part.segs;
1193
+ let one = [
1194
+ ...segs,
1195
+ ...rides
1196
+ ].join('&');
1197
+ return (words.get(name) ?? live).map((m)=>[
1198
+ m,
1199
+ one
1200
+ ]);
1201
+ });
1202
+ };
1203
+ return {
1204
+ read,
1205
+ watch,
1206
+ composed,
1207
+ located,
1208
+ routed,
1209
+ written,
1210
+ spoken
1211
+ };
1212
+ };
1213
+ // The keys of a bundle that name no component: its address and its death.
1214
+ // Everything a `$` opens is the wire's own (`$was`, `$delete`, `$actor`).
1215
+ let NOT_A_COMP = [
1216
+ 'entity',
1217
+ 'tombstone'
1218
+ ];
1219
+ let isComp = (k)=>!NOT_A_COMP.includes(k) && !k.startsWith('$');
1220
+ // Every `$alias` in the batch, minted here. A bundle that lands in two members
1221
+ // must land under one eid, so content-addressed ids are derived by the same
1222
+ // rules as a store, the rest are minted, and every member gets the one
1223
+ // answer. A bundle with no address at all is minted the same way.
1224
+ let minted = async (bundles, vocab, key, held)=>{
1225
+ let ordinal = 0;
1226
+ let mint = ()=>key ? derivedEid(JSON.stringify([
1227
+ 'outbox',
1228
+ key,
1229
+ ordinal++
1230
+ ])) : crypto.randomUUID();
1231
+ let stated = bundles.map((e)=>{
1232
+ let eid = e.entity?.eid;
1233
+ if (typeof eid == 'string') return e;
1234
+ // An eid is the only address that holds across members: a num is one
1235
+ // store's, so a bundle naming one names nothing here, and minting an eid
1236
+ // for it would write a new entity where the caller meant an existing one.
1237
+ if (e.entity?.num != null) {
1238
+ throw refuse('entity.num addresses nothing here — name the entity by its eid');
1239
+ }
1240
+ return {
1241
+ ...e,
1242
+ entity: {
1243
+ ...e.entity,
1244
+ eid: mint()
1245
+ }
1246
+ };
1247
+ });
1248
+ let derive = {
1249
+ ...identities(vocab),
1250
+ ...vocab.comp('archetype') ? archetypes().derive : {},
1251
+ ...edges(vocab).derive,
1252
+ ...keys(vocab).derive
1253
+ };
1254
+ // The store sees only the tombstone. Check the relation before the router
1255
+ // discards it, so an unknown relation cannot mint a fresh id for a drop.
1256
+ let drops = stated.filter((b)=>dead(b) && b.edge && isAlias(b.entity.eid));
1257
+ if (drops.length) statedEdges(vocab)(drops);
1258
+ let resolved = await resolve(stated, vocab, derive, mint, held);
1259
+ let aliases = Object.fromEntries(resolved.flatMap((e)=>callerAlias(e.$alias) ? [
1260
+ [
1261
+ e.$alias,
1262
+ e.entity.eid
1263
+ ]
1264
+ ] : []));
1265
+ let eids = resolved.map((e)=>e.entity.eid);
1266
+ // An alias stands wherever an eid goes (a ref property, an edge's end, a
1267
+ // nested bundle's address), so the swap is the whole batch's, by value.
1268
+ let swap = (v)=>typeof v == 'string' ? Object.hasOwn(aliases, v) ? aliases[v] : v : Array.isArray(v) ? v.map(swap) : v && typeof v == 'object' ? Object.fromEntries(Object.entries(v).map(([k, x])=>[
1269
+ k,
1270
+ swap(x)
1271
+ ])) : v;
1272
+ let entities = stated.map((e, i)=>{
1273
+ let one = swap(resolved[i]);
1274
+ if (!eids[i]) return one;
1275
+ // The alias rides along. A store's own mint phase reads `$alias` to tell
1276
+ // an id the graph picked from one a caller wrote down, which decides
1277
+ // whether a name somebody already holds moves this entity onto theirs or
1278
+ // is refused as a clash.
1279
+ let said = e.entity?.eid;
1280
+ return {
1281
+ ...one,
1282
+ entity: {
1283
+ ...one.entity,
1284
+ eid: eids[i]
1285
+ },
1286
+ ...typeof said == 'string' && said.startsWith('$') ? {
1287
+ $alias: said
1288
+ } : {}
1289
+ };
1290
+ });
1291
+ return {
1292
+ entities,
1293
+ eids,
1294
+ aliases
1295
+ };
1296
+ };
1297
+ //# sourceMappingURL=mod.js.map