@yaks/member 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.
Files changed (86) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +471 -2
  3. package/_dist/asking.d.ts +4 -0
  4. package/_dist/asking.d.ts.map +1 -0
  5. package/_dist/comp.d.ts +14 -0
  6. package/_dist/comp.d.ts.map +1 -0
  7. package/_dist/deny.d.ts +19 -0
  8. package/_dist/deny.d.ts.map +1 -0
  9. package/_dist/graph.d.ts +4 -0
  10. package/_dist/graph.d.ts.map +1 -0
  11. package/_dist/guard.d.ts +45 -0
  12. package/_dist/guard.d.ts.map +1 -0
  13. package/_dist/keywords.d.ts +80 -0
  14. package/_dist/keywords.d.ts.map +1 -0
  15. package/_dist/mod.d.ts +112 -0
  16. package/_dist/mod.d.ts.map +1 -0
  17. package/_dist/owns.d.ts +18 -0
  18. package/_dist/owns.d.ts.map +1 -0
  19. package/_dist/pace.d.ts +48 -0
  20. package/_dist/pace.d.ts.map +1 -0
  21. package/_dist/personal.d.ts +46 -0
  22. package/_dist/personal.d.ts.map +1 -0
  23. package/_dist/plugin.d.ts +32 -0
  24. package/_dist/plugin.d.ts.map +1 -0
  25. package/_dist/policy.d.ts +35 -0
  26. package/_dist/policy.d.ts.map +1 -0
  27. package/_dist/privacy.d.ts +55 -0
  28. package/_dist/privacy.d.ts.map +1 -0
  29. package/_dist/roles.d.ts +20 -0
  30. package/_dist/roles.d.ts.map +1 -0
  31. package/_dist/vocab.d.ts +10 -0
  32. package/_dist/vocab.d.ts.map +1 -0
  33. package/_dist/words.d.ts +53 -0
  34. package/_dist/words.d.ts.map +1 -0
  35. package/asking.js +65 -0
  36. package/asking.js.map +1 -0
  37. package/asking.ts +77 -0
  38. package/comp.js +43 -0
  39. package/comp.js.map +1 -0
  40. package/comp.ts +52 -0
  41. package/deno.json +1 -0
  42. package/deny.js +31 -0
  43. package/deny.js.map +1 -0
  44. package/deny.ts +45 -0
  45. package/graph.js +6 -0
  46. package/graph.js.map +1 -0
  47. package/graph.ts +16 -0
  48. package/guard.js +265 -0
  49. package/guard.js.map +1 -0
  50. package/guard.ts +327 -0
  51. package/keywords.js +170 -0
  52. package/keywords.js.map +1 -0
  53. package/keywords.ts +190 -0
  54. package/meta/member.vocab.json +70 -0
  55. package/mod.js +112 -0
  56. package/mod.js.map +1 -0
  57. package/mod.ts +113 -0
  58. package/owns.js +12 -0
  59. package/owns.js.map +1 -0
  60. package/owns.ts +23 -0
  61. package/pace.js +189 -0
  62. package/pace.js.map +1 -0
  63. package/pace.ts +195 -0
  64. package/package.json +33 -4
  65. package/personal.js +448 -0
  66. package/personal.js.map +1 -0
  67. package/personal.ts +550 -0
  68. package/plugin.js +63 -0
  69. package/plugin.js.map +1 -0
  70. package/plugin.ts +62 -0
  71. package/policy.js +115 -0
  72. package/policy.js.map +1 -0
  73. package/policy.ts +176 -0
  74. package/privacy.js +293 -0
  75. package/privacy.js.map +1 -0
  76. package/privacy.ts +379 -0
  77. package/roles.js +164 -0
  78. package/roles.js.map +1 -0
  79. package/roles.ts +245 -0
  80. package/vocab.js +19 -0
  81. package/vocab.js.map +1 -0
  82. package/vocab.json +272 -0
  83. package/vocab.ts +20 -0
  84. package/words.js +75 -0
  85. package/words.js.map +1 -0
  86. package/words.ts +123 -0
package/personal.ts ADDED
@@ -0,0 +1,550 @@
1
+ // A person's private rows and aspects, and rows kept to readers holding a
2
+ // level on the app. App roles never confer ownership.
3
+ import { after } from '@yaks/fp'
4
+ import { absent, and, eq, or, present } from '@yaks/query/core'
5
+ import { actorOf as writerOf } from '@yaks/graph/provenance'
6
+ import { dead } from '@yaks/graph/bundle'
7
+ import { isPromise } from '@yaks/fp'
8
+ import type {
9
+ Bundle,
10
+ Comp,
11
+ HookContext,
12
+ Plugin,
13
+ ReadOpts,
14
+ ReadTx,
15
+ Tx,
16
+ } from 'jsr:@yaks/graph@0.2.36'
17
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
18
+ import { Denied } from './deny.js'
19
+ import { asking, top } from './asking.js'
20
+ import { readersIn, shownIn } from './keywords.js'
21
+ import { type Declared, kept, privacy } from './privacy.js'
22
+ import { type Level, LEVELS, stands } from './words.js'
23
+
24
+ /** Component → owner: `entity` keeps just this aspect private on the person's
25
+ * entity; a local reference property makes the entire entity private. */
26
+ export type Personal = Record<string, string>
27
+
28
+ /** Derived component → reference property whose source owns its visibility. */
29
+ export type PersonalSources = Record<string, string>
30
+
31
+ // Component → owner as the vocabulary declares it, then as the host overrides.
32
+ let said = (
33
+ vocab: Vocab,
34
+ overrides: Personal,
35
+ ): Record<string, unknown> => ({
36
+ ...Object.fromEntries(vocab.all.flatMap((name) => {
37
+ let owner = vocab.comp(name)?.keywords.personal
38
+ return owner === undefined ? [] : [[name, owner]]
39
+ })),
40
+ ...overrides,
41
+ })
42
+
43
+ // The owner property the guide declares, offered wherever one is missing.
44
+ let BY = '{"type": "string", "ref": "entity", "death": "keep"}'
45
+
46
+ /**
47
+ * Every `personal` declaration no row could be kept private by, as sentences
48
+ * naming the component and what to write instead, the way @yaks/vocab's
49
+ * `storable` answers. A deploy holding any is refused, and
50
+ * {@link personalsIn} serves none.
51
+ *
52
+ * ```ts
53
+ * import { assertEquals } from '@std/assert'
54
+ * import { loadVocab, type PropSchema } from '@yaks/vocab'
55
+ * import { memberKeywords, unowned } from '@yaks/member'
56
+ * let note = (by: PropSchema) =>
57
+ * loadVocab({
58
+ * $defs: {
59
+ * note: {
60
+ * component: true,
61
+ * type: 'object',
62
+ * personal: 'by',
63
+ * properties: { by },
64
+ * },
65
+ * },
66
+ * }, [memberKeywords])
67
+ * assertEquals(unowned(note({ type: 'string', ref: 'entity', death: 'keep' })), [])
68
+ * assertEquals(unowned(note({ type: 'string' })), [
69
+ * 'note.personal names by, which is no reference — declare "by": ' +
70
+ * '{"type": "string", "ref": "entity", "death": "keep"}, or say ' +
71
+ * '"personal": "entity" for a component on the person\'s own entity',
72
+ * ])
73
+ * ```
74
+ */
75
+ export let unowned = (vocab: Vocab, overrides: Personal = {}): string[] =>
76
+ Object.entries(said(vocab, overrides)).flatMap(([name, owner]) => {
77
+ if (!vocab.comp(name)) return [`${name}.personal names no component`]
78
+ if (owner == 'entity') return []
79
+ let prop = typeof owner == 'string' ? vocab.prop(name, owner) : undefined
80
+ if (prop?.ref) return []
81
+ let entity = '"personal": "entity" for a component on the person\'s own ' +
82
+ 'entity'
83
+ return [
84
+ typeof owner != 'string'
85
+ ? `${name}.personal is ${JSON.stringify(owner)} — say ${entity}, or ` +
86
+ `name a property of ${name} declared ${BY}`
87
+ : `${name}.personal names ${owner}, which is ${
88
+ prop ? 'no reference' : `no property of ${name}`
89
+ } — declare "${owner}": ${BY}, or say ${entity}`,
90
+ ]
91
+ })
92
+
93
+ /** Read the policy declarations, refusing the vocabulary when any is no
94
+ * owner ({@link unowned}) before a row is served. */
95
+ export let personalsIn = (vocab: Vocab, overrides: Personal = {}): Personal => {
96
+ let errors = unowned(vocab, overrides)
97
+ if (errors.length) throw new Error(errors.join('; '))
98
+ return said(vocab, overrides) as Personal
99
+ }
100
+
101
+ let caller = (opts: ReadOpts) =>
102
+ opts.person !== undefined && !opts.administrative
103
+
104
+ // The level a read carries, as the host verified it; anything else is none.
105
+ let vouched = (l: unknown): Level | null =>
106
+ LEVELS.includes(l as Level) ? l as Level : null
107
+
108
+ /** What an entity's privacy is reckoned from (./privacy.ts), as
109
+ * {@link personal} is given it: the vocabulary's `personal` and `readers`
110
+ * declarations, the host's own, and what inherits its source's. */
111
+ export let declarationsOf = (
112
+ vocab: Vocab,
113
+ declared: Personal = {},
114
+ through: PersonalSources = {},
115
+ ): Declared => ({
116
+ owners: Object.entries(personalsIn(vocab, declared)).filter(([, by]) =>
117
+ by != 'entity'
118
+ ),
119
+ through: Object.entries(through),
120
+ floors: Object.entries(readersIn(vocab)),
121
+ vocab,
122
+ })
123
+
124
+ /** Protect person-owned data at reads and at every transaction write,
125
+ * including changes made by rules and reference cascades, and keep each entity
126
+ * wearing a component its vocabulary declares `readers` from every reader
127
+ * below that floor. Trusted server writes and explicitly vouched
128
+ * administrative reads are the only bypasses. */
129
+ export let personal = (
130
+ vocab: Vocab,
131
+ declared: Personal = {},
132
+ through: PersonalSources = {},
133
+ ): Plugin => {
134
+ let owners = personalsIn(vocab, declared)
135
+ let entries = Object.entries(owners)
136
+ let inherited = Object.entries(through)
137
+ for (let [name, prop] of inherited) {
138
+ if (!vocab.prop(name, prop)?.ref) {
139
+ throw new Error(
140
+ `${name}.${prop} must reference an entity to inherit visibility`,
141
+ )
142
+ }
143
+ }
144
+ let floors = Object.entries(readersIn(vocab))
145
+ let shown = Object.entries(shownIn(vocab))
146
+ if (floors.some(([, asked]) => typeof asked != 'string') && !kept(vocab)) {
147
+ // Conditions are matched where an entity's privacy is reckoned; a store
148
+ // that keeps none could only read them by hiding the whole component.
149
+ throw new Error('readers conditions need a vocabulary that keeps _privacy')
150
+ }
151
+ let asks = floors.map(([name, asked]) => ({
152
+ name,
153
+ ask: asking(asked, vocab),
154
+ top: top(asked),
155
+ }))
156
+ // What a write's ownership is checked by, and what a read's visibility is.
157
+ let owned = [...new Set([...Object.keys(owners), ...Object.keys(through)])]
158
+ let comps = [...owned, ...floors.map(([name]) => name)]
159
+ let entityOwned = entries.filter(([, by]) => by != 'entity')
160
+ // The components that may be kept from this reader: those whose readers'
161
+ // highest floor it does not stand on. One that asks by conditions is kept
162
+ // whole where the store reads by its declarations, never by its privacy.
163
+ let unseen = (opts: ReadOpts) =>
164
+ asks.filter(({ top }) =>
165
+ !stands(opts.person ?? null, vouched(opts.level), top)
166
+ ).map(({ name }) => name)
167
+ // The components this reader reads entities without: those `shown` to a
168
+ // floor it does not stand on.
169
+ let withheld = (opts: ReadOpts) =>
170
+ shown.filter(([, f]) =>
171
+ !stands(opts.person ?? null, vouched(opts.level), f)
172
+ )
173
+ .map(([name]) => name)
174
+ // Whether a row is kept from this reader: by a component asking a floor it
175
+ // does not stand on, or by another person's private one.
176
+ let foreign = (row: Bundle, opts: ReadOpts) =>
177
+ asks.some(({ name, ask }) => {
178
+ let floor = row[name] != null && ask(row)
179
+ return floor && !stands(opts.person ?? null, vouched(opts.level), floor)
180
+ }) ||
181
+ entityOwned.some(([name, by]) => {
182
+ let c = row[name] as Comp | undefined
183
+ return c && (!opts.person || c[by] != opts.person)
184
+ })
185
+ // The entities `who` may see: each holds no private component, or holds it
186
+ // as theirs, and holds none kept from them.
187
+ let mine = (who: string | null | undefined, hidden: string[]) =>
188
+ and(
189
+ ...hidden.map((name) => absent(name)),
190
+ ...entityOwned.map(([name, by]) =>
191
+ who ? or(absent(name), eq(`${name}.${by}`, who)) : absent(name)
192
+ ),
193
+ ...inherited.map(([name, prop]) => {
194
+ let source = `${name}.${prop}`
195
+ return or(
196
+ absent(name),
197
+ and(
198
+ present(source),
199
+ ...hidden.map((kept) => absent(`${source}.${kept}`)),
200
+ ...entityOwned.map(([owner, by]) =>
201
+ who
202
+ ? or(
203
+ absent(`${source}.${owner}`),
204
+ eq(`${source}.${owner}.${by}`, who),
205
+ )
206
+ : absent(`${source}.${owner}`)
207
+ ),
208
+ ),
209
+ )
210
+ }),
211
+ )
212
+ // Each entity's privacy, kept where the vocabulary declares `_privacy`
213
+ // (./privacy.ts). A store is read by it once it holds no entity whose
214
+ // privacy is missing or stale, and by the declarations until then: asked
215
+ // again after a write that could complete it (./privacy.ts `keeping`).
216
+ let keeps = kept(vocab)
217
+ ? privacy(declarationsOf(vocab, declared, through))
218
+ : undefined
219
+ let ready = false, asked = false
220
+ let stored = (tx: ReadTx): boolean => {
221
+ if (!keeps || ready) return ready
222
+ if (asked) return false
223
+ asked = true
224
+ let none = keeps.current((line, opts, comps) => tx.read(line, opts, comps))
225
+ if (isPromise(none)) {
226
+ none.then((v) => ready ||= v, () => asked = false)
227
+ return false
228
+ }
229
+ return ready = none
230
+ }
231
+ // The entities this reader sees: by their privacy, or by the declarations.
232
+ let sight = (opts: ReadOpts, tx: ReadTx, hidden: string[]) =>
233
+ stored(tx)
234
+ ? keeps!.seen(opts.person, vouched(opts.level))
235
+ : mine(opts.person, hidden)
236
+ let check = (
237
+ bundles: Bundle[],
238
+ tx: Tx,
239
+ person: string | null,
240
+ bind = false,
241
+ born = new Set<string>(),
242
+ held = new Map<string, Bundle | undefined>(),
243
+ ) => {
244
+ let missing = [...new Set(bundles.map((b) => b.entity.eid))]
245
+ .filter((eid) => !held.has(eid))
246
+ return after(missing.length ? tx.get(missing, owned) : [], (rows) => {
247
+ for (let eid of missing) held.set(eid, undefined)
248
+ for (let row of rows) held.set(row.entity.eid, row)
249
+ return bundles.map((bundle) => {
250
+ let b = bundle
251
+ let eid = b.entity.eid
252
+ let row = held.get(eid)
253
+ if (!row) born.add(eid)
254
+ for (let [name, by] of entries) {
255
+ let was = row?.[name] as Comp | null | undefined
256
+ let patch = b[name] as Comp | null | undefined
257
+ let touched = Object.hasOwn(b, name)
258
+ let refuse = () => {
259
+ throw new Denied(person, eid, 'person', 'write', name)
260
+ }
261
+ if (by == 'entity') {
262
+ if (
263
+ (touched || was && (dead(b) ||
264
+ entityOwned.some(([comp]) => b[comp] != null))) &&
265
+ (!person || eid != person)
266
+ ) refuse()
267
+ continue
268
+ }
269
+ if (was) {
270
+ // Every aspect of a private entity belongs to its owner. Dropping
271
+ // the ownership component could publish its other aspects.
272
+ if (!person || was[by] != person) refuse()
273
+ if (
274
+ touched && (patch == null ||
275
+ Object.hasOwn(patch, by) && patch[by] != was[by])
276
+ ) refuse()
277
+ } else if (patch) {
278
+ // Private ownership is chosen at birth. An editor cannot hide an
279
+ // existing public person or game row by claiming its identity.
280
+ if (
281
+ row && !born.has(eid) && !entityOwned.some(([comp]) => row[comp])
282
+ ) refuse()
283
+ if (!person || patch[by] != null && patch[by] != person) refuse()
284
+ if (patch[by] == null) {
285
+ if (!bind) refuse()
286
+ b = { ...b, [name]: { ...patch, [by]: person } }
287
+ }
288
+ }
289
+ }
290
+ return b
291
+ })
292
+ })
293
+ }
294
+ // What a reader is not shown of an entity it sees: another person's own
295
+ // aspect, and what is withheld below its floor. The entity's archetype
296
+ // would name them, so it goes with them.
297
+ let conceal = (
298
+ b: Bundle,
299
+ opts: ReadOpts,
300
+ aside: string[],
301
+ row?: Bundle,
302
+ ): Bundle => {
303
+ let kept = [
304
+ ...entries.flatMap(([name, by]) =>
305
+ by == 'entity' && b.entity.eid != opts.person ? [name] : []
306
+ ),
307
+ ...aside,
308
+ ]
309
+ if (!kept.some((name) => Object.hasOwn(b, name) || row?.[name])) return b
310
+ let out = { ...b }
311
+ for (let name of kept) delete out[name]
312
+ if (kept.some((name) => row?.[name] || b[name])) {
313
+ out.entity = { ...out.entity }
314
+ delete out.entity.archetype
315
+ }
316
+ return out
317
+ }
318
+ return {
319
+ name: '@yaks/member/personal',
320
+ admission: () => true,
321
+ reads: (opts) =>
322
+ (entries.length > 0 || inherited.length > 0 || floors.length > 0 ||
323
+ shown.length > 0) &&
324
+ caller(opts),
325
+ scope: ({ opts, tx }) => {
326
+ if (!caller(opts)) return undefined
327
+ let who = opts.person
328
+ let hidden = unseen(opts), aside = withheld(opts)
329
+ if (
330
+ !entries.length && !inherited.length && !hidden.length && !aside.length
331
+ ) return undefined
332
+ return {
333
+ entity: sight(opts, tx, hidden),
334
+ components: Object.fromEntries([
335
+ ...entries.filter(([, by]) => by == 'entity')
336
+ .map(([name]) => [
337
+ name,
338
+ and(who ? eq('entity.eid', who) : absent('entity')),
339
+ ]),
340
+ // Every entity has an `entity`, so no row shows these.
341
+ ...aside.map((name) => [name, and(absent('entity'))]),
342
+ ]),
343
+ }
344
+ },
345
+ wants: (
346
+ bundles,
347
+ ) => [{ eids: bundles.map((b) => b.entity.eid), comps: owned }],
348
+ authorize: (bundles, tx, _error, context) =>
349
+ context?.trusted || !entries.length
350
+ ? bundles
351
+ : check(bundles, tx, writerOf(bundles).by ?? null, true),
352
+ track: (tx, found, context?: HookContext) => {
353
+ let by = writerOf(context?.bundles ?? []).by ?? null
354
+ let born = new Set<string>()
355
+ // All writes cross this tracker. Retain the ownership state it has
356
+ // checked, including known absence, for later writes in this transaction.
357
+ let held = new Map<string, Bundle | undefined>()
358
+ for (let b of context?.bundles ?? []) {
359
+ let row = found(b.entity.eid)
360
+ if (row !== undefined) held.set(b.entity.eid, row ?? undefined)
361
+ }
362
+ let remember = (bundles: Bundle[]) => {
363
+ for (let b of bundles) {
364
+ let eid = b.entity.eid
365
+ if (dead(b)) {
366
+ held.delete(eid)
367
+ born.delete(eid)
368
+ continue
369
+ }
370
+ let row = { ...(held.get(eid) ?? { entity: b.entity }) }
371
+ for (let name of owned) {
372
+ if (!Object.hasOwn(b, name)) continue
373
+ let patch = b[name] as Comp | null
374
+ if (patch == null) delete row[name]
375
+ else row[name] = { ...row[name] as Comp | undefined, ...patch }
376
+ }
377
+ held.set(eid, row)
378
+ }
379
+ }
380
+ let inspect = (b: Bundle[]) =>
381
+ context?.trusted || !entries.length
382
+ ? b
383
+ : check(b, tx, by, false, born, held)
384
+ let inspected: Tx = {
385
+ ...tx,
386
+ patch: (bundles) =>
387
+ after(
388
+ inspect(bundles),
389
+ (checked) =>
390
+ after(tx.patch(checked), (made) => {
391
+ remember(checked)
392
+ return made
393
+ }),
394
+ ),
395
+ remove: (entities) =>
396
+ after(
397
+ inspect(entities.map((entity) => ({ entity, $delete: true }))),
398
+ () =>
399
+ after(tx.remove(entities), (removed) => {
400
+ for (let { eid } of entities) {
401
+ held.delete(eid)
402
+ born.delete(eid)
403
+ }
404
+ return removed
405
+ }),
406
+ ),
407
+ }
408
+ if (!keeps) return { tx: inspected, flush: (b) => b }
409
+ return keeps.keeping(tx, inspected, () => asked = false)
410
+ },
411
+ // Subscription relays and coverage carry patches, whose owner need not be
412
+ // present. Consult canonical rows instead of trusting incoming bylines.
413
+ // Rows the store read under this scope are already what it allows.
414
+ // An entity the answer itself carries is one the reader can resolve: a
415
+ // rehearsal's batch was rolled back, so what it created is in no row, yet
416
+ // its references to that are the ids it would have written.
417
+ answer: ({ opts, tx, screened }, bundles) => {
418
+ if (!caller(opts) || !bundles.length) return bundles
419
+ let hidden = unseen(opts), aside = withheld(opts)
420
+ // A screened answer's rows hold none of what is kept from this reader.
421
+ // A subscription's coverage names its components all the same.
422
+ if (screened) {
423
+ return entries.length || aside.length
424
+ ? bundles.map((b) => conceal(b, opts, aside))
425
+ : bundles
426
+ }
427
+ if (
428
+ !entries.length && !inherited.length && !hidden.length && !aside.length
429
+ ) return bundles
430
+ let carried = new Map(bundles.map((b) => [b.entity.eid, b]))
431
+ return after(tx.get(bundles.map((b) => b.entity.eid), comps), (rows) => {
432
+ let held = new Map(rows.map((b) => [b.entity.eid, b]))
433
+ let targets = [
434
+ ...new Set(
435
+ bundles.flatMap((b) =>
436
+ inherited.flatMap(([name, prop]) => {
437
+ let target = ((held.get(b.entity.eid) ?? b)[name] as
438
+ | Comp
439
+ | undefined)?.[prop]
440
+ return typeof target == 'string' ? [target] : []
441
+ })
442
+ ),
443
+ ),
444
+ ]
445
+ return after(tx.get(targets, comps), (sources) => {
446
+ let byId = new Map([
447
+ ...carried,
448
+ ...sources.map((b) => [b.entity.eid, b] as const),
449
+ ])
450
+ let visible = bundles.flatMap((b) => {
451
+ let row = held.get(b.entity.eid)
452
+ if (foreign(row ?? b, opts)) return []
453
+ if (
454
+ inherited.some(([name, prop]) => {
455
+ let comp = (row ?? b)[name] as Comp | undefined
456
+ if (!comp) return false
457
+ let source = byId.get(String(comp[prop]))
458
+ return !source || dead(source) ||
459
+ foreign(source, opts)
460
+ })
461
+ ) return []
462
+ return [conceal(b, opts, aside, row)]
463
+ })
464
+ if (!entityOwned.length && !inherited.length && !hidden.length) {
465
+ return visible
466
+ }
467
+ let references = (b: Bundle) =>
468
+ Object.entries(b).flatMap(([name, value]) => {
469
+ if (
470
+ name == 'entity' || !value || typeof value != 'object' ||
471
+ !vocab.comp(name)
472
+ ) return []
473
+ let c = value as Comp
474
+ return vocab.props(name).flatMap((prop) =>
475
+ vocab.prop(name, prop)?.category == 'ref' &&
476
+ typeof c[prop] == 'string'
477
+ ? [[name, prop, c[prop] as string]]
478
+ : []
479
+ )
480
+ })
481
+ let targets = [
482
+ ...new Set(
483
+ visible.flatMap((b) => references(b).map(([, , eid]) => eid)),
484
+ ),
485
+ ]
486
+ if (!targets.length) return visible
487
+ return after(
488
+ tx.get(targets, comps, {
489
+ visibility: { entity: sight(opts, tx, hidden) },
490
+ }),
491
+ (rows) => {
492
+ // A deleted target holds nothing left to say whose it was. Its
493
+ // history does, so the store is asked under this scope, which sees
494
+ // one it would have seen as it last was (@yaks/sql `ghostly`).
495
+ let gone = rows.filter(dead).map((b) => b.entity.eid)
496
+ let seen = gone.length
497
+ ? tx.get(gone, [], {
498
+ visibility: { entity: sight(opts, tx, hidden) },
499
+ })
500
+ : []
501
+ return after(seen, (seen) => {
502
+ let allowed = new Set(
503
+ [
504
+ ...rows.filter((b) => !dead(b) && !foreign(b, opts)),
505
+ ...seen,
506
+ ...visible,
507
+ ]
508
+ .map((b) => b.entity.eid),
509
+ )
510
+ let retained = [
511
+ ...new Set(
512
+ visible.flatMap((b) =>
513
+ references(b).filter(([name, prop, eid]) =>
514
+ !allowed.has(eid) &&
515
+ vocab.prop(name, prop)?.death == 'keep'
516
+ ).map(([, , eid]) => eid)
517
+ ),
518
+ ),
519
+ ]
520
+ return after(
521
+ retained.length ? tx.get(retained, []) : [],
522
+ (local) => {
523
+ let present = new Set(local.map((b) => b.entity.eid))
524
+ return visible.map((b) => {
525
+ let out = b
526
+ for (let [name, prop, eid] of references(b)) {
527
+ // Retained references can name another store. A missing
528
+ // target carries no local private data to conceal; a
529
+ // target present here must still pass its visibility.
530
+ let external = !present.has(eid) &&
531
+ vocab.prop(name, prop)?.death == 'keep'
532
+ if (!allowed.has(eid) && !external) {
533
+ out = {
534
+ ...out,
535
+ [name]: { ...out[name] as Comp, [prop]: null },
536
+ }
537
+ }
538
+ }
539
+ return out
540
+ })
541
+ },
542
+ )
543
+ })
544
+ },
545
+ )
546
+ })
547
+ })
548
+ },
549
+ }
550
+ }
package/plugin.js ADDED
@@ -0,0 +1,63 @@
1
+ // The package as a @yaks/graph plugin: the three components, and the write
2
+ // guard over them.
3
+ //
4
+ // The guard has to be told which app it decides for, because "may this be
5
+ // written?" is a question about an app and the graph itself holds only rows. So
6
+ // the plugin is built with that app named, the way an application names its own
7
+ // subject — and, optionally, the space whose owners own it. It is handed the
8
+ // vocabulary the graph was loaded with too, since a component may declare who
9
+ // writes it (`floor`) and how often (`pace`).
10
+ //
11
+ // Seeding. A graph with the guard installed and an empty roster admits nobody:
12
+ // there is no owner yet, so there is nobody allowed to write the row that makes
13
+ // one. That is not a bug to route around, it is what a bootstrap is — so write
14
+ // the first owner before installing the guard, and install it after:
15
+ //
16
+ // let g = graph({ storage, vocab })
17
+ // g.apply([{ entity: { eid: 'm1' }, member: { space, person: dana,
18
+ // role: 'owner' } }])
19
+ // g.use(members({ app, space, vocab }))
20
+ //
21
+ // From there the roster maintains itself: an owner adds the next one.
22
+ import { memberDoc } from "./comp.js";
23
+ import { guarding, wanting } from "./guard.js";
24
+ /**
25
+ * The membership plugin: the `member`, `grant` and `access` components, and a
26
+ * `precondition` hook that refuses a write the principal's role or grant does
27
+ * not allow, or that comes sooner than its component's pace.
28
+ *
29
+ * ```ts
30
+ * import { loadVocab } from '@yaks/vocab'
31
+ * import { graph } from '@yaks/graph'
32
+ * import { ram } from '@yaks/ram'
33
+ * import { memberDoc, memberKeywords, members } from '@yaks/member'
34
+ *
35
+ * let vocab = loadVocab([memberDoc], [memberKeywords])
36
+ * let guard = members({ app: 'list', space: 'club', vocab })
37
+ * let g = graph({ storage: ram(vocab), vocab, plugins: [guard] })
38
+ * ```
39
+ *
40
+ * Reads are not checked here — a query never reaches `apply()`. The HTTP layer
41
+ * calls
42
+ * {@link https://jsr.io/@yaks/member/doc/~/policy | policy}`(storage).canRead`
43
+ * before it answers one.
44
+ *
45
+ * ## The effect hook this package leaves unregistered
46
+ * Adding someone to a roster usually means messaging them. That is a
47
+ * `created('member')` handler on
48
+ * {@link https://jsr.io/@yaks/effects | @yaks/effects} — it runs after the
49
+ * commit, so the row exists before the message goes out, and it is isolated, so
50
+ * a mail server that is down does not refuse the write. This package ships no
51
+ * such handler; `@yaks/mail` provides one.
52
+ */ export let members = (where)=>({
53
+ name: '@yaks/member',
54
+ admission: ()=>true,
55
+ vocab: [
56
+ memberDoc
57
+ ],
58
+ hooks: {
59
+ precondition: guarding(where)
60
+ },
61
+ wants: wanting(where)
62
+ });
63
+ //# sourceMappingURL=plugin.js.map
package/plugin.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sources":["./plugin.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,mBAAmB;AACnB,EAAE;AACF,0EAA0E;AAC1E,gFAAgF;AAChF,gFAAgF;AAChF,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,qEAAqE;AACrE,EAAE;AACF,sCAAsC;AACtC,qEAAqE;AACrE,mCAAmC;AACnC,0CAA0C;AAC1C,EAAE;AACF,sEAAsE;AAGtE,SAAS,SAAS,oBAAmB;AACrC,SAAqB,QAAQ,EAAE,OAAO,qBAAoB;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,OAAO,IAAI,UAAU,CAAC,QAAyB,CAAC;IAC9C,MAAM;IACN,WAAW,IAAM;IACjB,OAAO;MAAC;KAAU;IAClB,OAAO;MAAE,cAAc,SAAS;IAAO;IACvC,OAAO,QAAQ;EACjB,CAAC,EAAC"}
package/plugin.ts ADDED
@@ -0,0 +1,62 @@
1
+ // The package as a @yaks/graph plugin: the three components, and the write
2
+ // guard over them.
3
+ //
4
+ // The guard has to be told which app it decides for, because "may this be
5
+ // written?" is a question about an app and the graph itself holds only rows. So
6
+ // the plugin is built with that app named, the way an application names its own
7
+ // subject — and, optionally, the space whose owners own it. It is handed the
8
+ // vocabulary the graph was loaded with too, since a component may declare who
9
+ // writes it (`floor`) and how often (`pace`).
10
+ //
11
+ // Seeding. A graph with the guard installed and an empty roster admits nobody:
12
+ // there is no owner yet, so there is nobody allowed to write the row that makes
13
+ // one. That is not a bug to route around, it is what a bootstrap is — so write
14
+ // the first owner before installing the guard, and install it after:
15
+ //
16
+ // let g = graph({ storage, vocab })
17
+ // g.apply([{ entity: { eid: 'm1' }, member: { space, person: dana,
18
+ // role: 'owner' } }])
19
+ // g.use(members({ app, space, vocab }))
20
+ //
21
+ // From there the roster maintains itself: an owner adds the next one.
22
+
23
+ import type { Plugin } from 'jsr:@yaks/graph@0.2.36'
24
+ import { memberDoc } from './comp.js'
25
+ import { type Guard, guarding, wanting } from './guard.js'
26
+
27
+ /**
28
+ * The membership plugin: the `member`, `grant` and `access` components, and a
29
+ * `precondition` hook that refuses a write the principal's role or grant does
30
+ * not allow, or that comes sooner than its component's pace.
31
+ *
32
+ * ```ts
33
+ * import { loadVocab } from '@yaks/vocab'
34
+ * import { graph } from '@yaks/graph'
35
+ * import { ram } from '@yaks/ram'
36
+ * import { memberDoc, memberKeywords, members } from '@yaks/member'
37
+ *
38
+ * let vocab = loadVocab([memberDoc], [memberKeywords])
39
+ * let guard = members({ app: 'list', space: 'club', vocab })
40
+ * let g = graph({ storage: ram(vocab), vocab, plugins: [guard] })
41
+ * ```
42
+ *
43
+ * Reads are not checked here — a query never reaches `apply()`. The HTTP layer
44
+ * calls
45
+ * {@link https://jsr.io/@yaks/member/doc/~/policy | policy}`(storage).canRead`
46
+ * before it answers one.
47
+ *
48
+ * ## The effect hook this package leaves unregistered
49
+ * Adding someone to a roster usually means messaging them. That is a
50
+ * `created('member')` handler on
51
+ * {@link https://jsr.io/@yaks/effects | @yaks/effects} — it runs after the
52
+ * commit, so the row exists before the message goes out, and it is isolated, so
53
+ * a mail server that is down does not refuse the write. This package ships no
54
+ * such handler; `@yaks/mail` provides one.
55
+ */
56
+ export let members = (where: Guard): Plugin => ({
57
+ name: '@yaks/member',
58
+ admission: () => true,
59
+ vocab: [memberDoc],
60
+ hooks: { precondition: guarding(where) },
61
+ wants: wanting(where),
62
+ })