@yaks/lens 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 (54) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +228 -2
  3. package/_dist/compile.d.ts +30 -0
  4. package/_dist/compile.d.ts.map +1 -0
  5. package/_dist/described.d.ts +12 -0
  6. package/_dist/described.d.ts.map +1 -0
  7. package/_dist/document.d.ts +59 -0
  8. package/_dist/document.d.ts.map +1 -0
  9. package/_dist/graph.d.ts +3 -0
  10. package/_dist/graph.d.ts.map +1 -0
  11. package/_dist/mod.d.ts +7 -0
  12. package/_dist/mod.d.ts.map +1 -0
  13. package/_dist/plugin.d.ts +9 -0
  14. package/_dist/plugin.d.ts.map +1 -0
  15. package/_dist/steps.d.ts +10 -0
  16. package/_dist/steps.d.ts.map +1 -0
  17. package/_dist/view.d.ts +40 -0
  18. package/_dist/view.d.ts.map +1 -0
  19. package/_dist/vocab.d.ts +4 -0
  20. package/_dist/vocab.d.ts.map +1 -0
  21. package/compile.js +318 -0
  22. package/compile.js.map +1 -0
  23. package/compile.ts +290 -0
  24. package/deno.json +1 -0
  25. package/described.js +80 -0
  26. package/described.js.map +1 -0
  27. package/described.ts +85 -0
  28. package/document.js +268 -0
  29. package/document.js.map +1 -0
  30. package/document.ts +335 -0
  31. package/graph.js +5 -0
  32. package/graph.js.map +1 -0
  33. package/graph.ts +4 -0
  34. package/mod.js +7 -0
  35. package/mod.js.map +1 -0
  36. package/mod.ts +6 -0
  37. package/package.json +28 -4
  38. package/plugin.js +454 -0
  39. package/plugin.js.map +1 -0
  40. package/plugin.ts +597 -0
  41. package/schema.js +61 -0
  42. package/schema.js.map +1 -0
  43. package/schema.ts +53 -0
  44. package/steps.js +35 -0
  45. package/steps.js.map +1 -0
  46. package/steps.ts +47 -0
  47. package/tools.fixture.json +190 -0
  48. package/view.js +430 -0
  49. package/view.js.map +1 -0
  50. package/view.ts +448 -0
  51. package/vocab.js +11 -0
  52. package/vocab.js.map +1 -0
  53. package/vocab.json +34 -0
  54. package/vocab.ts +8 -0
package/view.ts ADDED
@@ -0,0 +1,448 @@
1
+ import type { Bundle, Comp } from 'jsr:@yaks/graph@0.2.36'
2
+ import { Stale } from '@yaks/graph/errors'
3
+ import { token } from '@yaks/graph/sha256'
4
+ import { matcher } from '@yaks/match'
5
+ import { parse } from '@yaks/query'
6
+ import type { PropSchema, Vocab } from 'jsr:@yaks/vocab@0.2.36'
7
+
8
+ /** A scalar view has one canonical path, a retired default, or a referenced mark. */
9
+ export type ViewProp =
10
+ | { path: string; convert?: 'milliseconds' }
11
+ | { retired: unknown }
12
+ | { ack: { component: string; ref: string; mark: string; order: string } }
13
+ export type ComponentView = {
14
+ from: string
15
+ declaration: PropSchema
16
+ match: string
17
+ props: Record<string, ViewProp>
18
+ }
19
+ /** Facts are supplied by the graph boundary; compiled translations perform no I/O. */
20
+ export type Facts = {
21
+ facts?: Bundle[]
22
+ vocab?: Vocab
23
+ now?: number
24
+ patch?: boolean
25
+ migrate?: boolean
26
+ canonical?: boolean
27
+ }
28
+ let comp = (b: Bundle | undefined, c: string) => b?.[c] as Comp | undefined
29
+ let value = (b: Bundle | undefined, path: string) => {
30
+ let [c, p] = path.split('.')
31
+ return comp(b, c)?.[p]
32
+ }
33
+ function fail(message: string): never {
34
+ throw new Error(`Lens: ${message}`)
35
+ }
36
+ let scalar = (
37
+ v: unknown,
38
+ mapping: Extract<ViewProp, { path: string }>,
39
+ inverse = false,
40
+ ) => {
41
+ if (v == null || !mapping.convert) return v
42
+ if (inverse) {
43
+ if (typeof v != 'number' || !Number.isFinite(v)) {
44
+ fail('expected milliseconds')
45
+ }
46
+ return new Date(v).toISOString()
47
+ }
48
+ if (typeof v != 'string' || !Number.isFinite(Date.parse(v))) {
49
+ fail('expected date-time')
50
+ }
51
+ return Date.parse(v)
52
+ }
53
+ let marked = (
54
+ prop: Extract<ViewProp, { ack: object }>,
55
+ eid: string,
56
+ facts: Bundle[],
57
+ ) =>
58
+ facts.filter((r) =>
59
+ comp(r, prop.ack.component)?.[prop.ack.ref] == eid && !!r[prop.ack.mark]
60
+ )
61
+ .toSorted((a, b) =>
62
+ String(value(b, prop.ack.order) ?? '').localeCompare(
63
+ String(value(a, prop.ack.order) ?? ''),
64
+ ) || b.entity.eid.localeCompare(a.entity.eid)
65
+ )
66
+
67
+ export let viewSources = (view: ComponentView): string[] => [view.from]
68
+ export let viewDependencies = (view: ComponentView): string[] => [
69
+ ...new Set([
70
+ ...parse(view.match).clauses.flatMap((c) =>
71
+ 'path' in c ? c.path.slice(0, 1) : []
72
+ ),
73
+ ...Object.values(view.props).flatMap((p) =>
74
+ 'path' in p
75
+ ? [p.path.split('.')[0]]
76
+ : 'ack' in p
77
+ ? [p.ack.component, p.ack.mark, p.ack.order.split('.')[0]]
78
+ : []
79
+ ),
80
+ ]),
81
+ ]
82
+ export let validateView = (v: ComponentView): void => {
83
+ if (
84
+ !v || !/^[A-Za-z_]\w*$/.test(v.from) || !v.declaration?.properties ||
85
+ !v.match || !v.props
86
+ ) fail('invalid component view')
87
+ parse(v.match)
88
+ for (let [name, p] of Object.entries(v.props)) {
89
+ if (!v.declaration.properties[name]) {
90
+ fail(`undeclared view property ${v.from}.${name}`)
91
+ }
92
+ if ('path' in p) {
93
+ if (!/^\w+\.\w+$/.test(p.path) || p.path.split('.')[0] == v.from) {
94
+ fail('view path must name a canonical comp.prop')
95
+ }
96
+ if (p.convert && p.convert != 'milliseconds') {
97
+ fail('unknown scalar conversion')
98
+ }
99
+ } else if ('ack' in p) {
100
+ if (
101
+ !p.ack.component || !p.ack.ref || !p.ack.mark ||
102
+ !/^\w+\.\w+$/.test(p.ack.order)
103
+ ) fail('invalid acknowledgement relation')
104
+ } else if (!('retired' in p)) fail('unknown view property mapping')
105
+ }
106
+ for (let name of Object.keys(v.declaration.properties)) {
107
+ if (!v.props[name]) fail(`unmapped view property ${v.from}.${name}`)
108
+ }
109
+ }
110
+
111
+ export let getViews = (
112
+ rows: Bundle[],
113
+ views: ComponentView[],
114
+ ctx: Facts = {},
115
+ ): Bundle[] => {
116
+ if (!views.length) return rows
117
+ let facts = ctx.facts ?? rows
118
+ let at = new Map(facts.map((r) => [r.entity.eid, r]))
119
+ let out = rows
120
+ for (let v of views.toReversed()) {
121
+ if (!ctx.vocab) fail('component views need the canonical vocabulary')
122
+ let belongs = matcher(parse(v.match), ctx.vocab, { now: ctx.now })
123
+ out = out.map((row) => {
124
+ let held = at.get(row.entity.eid)
125
+ let whole = ctx.patch ? merge(held, row) : row
126
+ if (whole[v.from]) {
127
+ // Expansion leaves source rows readable until the rehearsed mover
128
+ // contracts them. The same pure move reconstructs them without writes.
129
+ let moved = putViews([whole], [v], {
130
+ ...ctx,
131
+ facts: [
132
+ whole,
133
+ ...facts.filter((r) => r.entity.eid != whole.entity.eid),
134
+ ],
135
+ migrate: true,
136
+ })
137
+ whole = merge(whole, moved[0])
138
+ let restored = new Map(facts.map((r) => [r.entity.eid, r]))
139
+ for (let patch of moved.slice(1)) {
140
+ restored.set(
141
+ patch.entity.eid,
142
+ merge(restored.get(patch.entity.eid), patch),
143
+ )
144
+ }
145
+ facts = [...restored.values()]
146
+ }
147
+ let { [v.from]: _, ...canonical } = row
148
+ if (!belongs([whole]).length) {
149
+ let removed = row[v.from] === null ||
150
+ Object.values(v.props).some((p) =>
151
+ 'path' in p && row[p.path.split('.')[0]] === null
152
+ )
153
+ return ctx.patch && (removed || held && belongs([held]).length)
154
+ ? { ...canonical, [v.from]: null } as Bundle
155
+ : canonical as Bundle
156
+ }
157
+ let props: Comp = {}
158
+ for (let [name, p] of Object.entries(v.props)) {
159
+ if ('path' in p) {
160
+ let got = scalar(value(whole, p.path), p, true)
161
+ if (got !== undefined) props[name] = got
162
+ } else if ('retired' in p) props[name] = p.retired
163
+ else {props[name] = marked(p, row.entity.eid, facts)[0]?.entity.eid ??
164
+ null}
165
+ }
166
+ return { ...canonical, [v.from]: props } as Bundle
167
+ })
168
+ // A request mark patch changes its addressed source view too.
169
+ if (ctx.patch) {
170
+ let have = new Set(out.map((r) => r.entity.eid))
171
+ for (let p of Object.values(v.props)) {
172
+ if (!('ack' in p)) continue
173
+ for (let row of rows) {
174
+ if (!(p.ack.mark in row) && !(p.ack.component in row)) continue
175
+ let eid = comp(row, p.ack.component)?.[p.ack.ref] ??
176
+ comp(at.get(row.entity.eid), p.ack.component)?.[p.ack.ref]
177
+ if (typeof eid != 'string' || have.has(eid)) continue
178
+ let source = at.get(eid)
179
+ if (!source || !belongs([source]).length) continue
180
+ let virtual = getViews([source], [v], { ...ctx, patch: false })[0]
181
+ out.push({ entity: source.entity, [v.from]: virtual[v.from] })
182
+ have.add(eid)
183
+ }
184
+ }
185
+ }
186
+ }
187
+ return out
188
+ }
189
+ let merge = (held: Bundle | undefined, patch: Bundle): Bundle => {
190
+ let out = { ...held, ...patch } as Bundle
191
+ for (let [c, p] of Object.entries(patch)) {
192
+ if (p === null) delete out[c]
193
+ else if (c != 'entity' && !c.startsWith('$') && p && typeof p == 'object') {
194
+ out[c] = { ...comp(held, c), ...p }
195
+ }
196
+ }
197
+ return out
198
+ }
199
+
200
+ /** Whole-change translation allows an old property to write a referenced entity.
201
+ * Every generated patch retains the source actor and canonical preconditions. */
202
+ export let putViews = (
203
+ rows: Bundle[],
204
+ views: ComponentView[],
205
+ ctx: Facts = {},
206
+ ): Bundle[] => {
207
+ let out = rows
208
+ let facts = ctx.facts ?? []
209
+ let at = new Map(facts.map((r) => [r.entity.eid, r]))
210
+ for (let v of views) {
211
+ out = out.flatMap((row) => {
212
+ let source = row[v.from] as Comp | null | undefined
213
+ let guarded = row.$was?.[v.from]
214
+ if (source === undefined && !guarded) return [row]
215
+ let { [v.from]: _, ...rest } = row
216
+ let patch = rest as Bundle
217
+ let was = { ...row.$was }
218
+ delete was[v.from]
219
+ if (row.$was) patch.$was = was
220
+ let extra: Bundle[] = []
221
+ let held = at.get(row.entity.eid)
222
+ let old = guarded
223
+ ? getViews(held ? [held] : [], [v], { ...ctx, patch: false })[0]
224
+ : undefined
225
+ for (let [name, p] of Object.entries(v.props)) {
226
+ if (guarded && Object.hasOwn(guarded, name)) {
227
+ let current = comp(old, v.from)?.[name] ?? null
228
+ if (token(current) != guarded[name]) {
229
+ throw new Stale(row.entity.eid, v.from, name, current)
230
+ }
231
+ if ('path' in p) {
232
+ let [c, prop] = p.path.split('.')
233
+ patch.$was = {
234
+ ...patch.$was,
235
+ [c]: { ...patch.$was?.[c], [prop]: token(value(held, p.path)) },
236
+ }
237
+ }
238
+ }
239
+ if (
240
+ source === undefined ||
241
+ source !== null && !Object.hasOwn(source, name)
242
+ ) continue
243
+ let got = source === null ? null : source[name]
244
+ if ('retired' in p) continue
245
+ if ('path' in p) {
246
+ let [c, prop] = p.path.split('.')
247
+ if (ctx.migrate) {
248
+ let clock = Object.values(v.props).find((p) =>
249
+ 'path' in p && p.convert == 'milliseconds'
250
+ )
251
+ if (clock && 'path' in clock) {
252
+ let oldTimeName = Object.keys(v.props).find((k) =>
253
+ v.props[k] === clock
254
+ )!
255
+ if (
256
+ value(held, clock.path) != null &&
257
+ Number(value(held, clock.path)) >=
258
+ Number(scalar(source?.[oldTimeName], clock))
259
+ ) continue
260
+ }
261
+ }
262
+ let current = comp(patch, c)
263
+ let next = scalar(got, p)
264
+ if (
265
+ !ctx.migrate && current && Object.hasOwn(current, prop) &&
266
+ JSON.stringify(current[prop]) != JSON.stringify(next)
267
+ ) fail(`conflicting writes to ${v.from}.${name} and ${p.path}`)
268
+ patch[c] = { ...current, [prop]: next }
269
+ continue
270
+ }
271
+ if (ctx.migrate && got == null) continue
272
+ let targets = got === null
273
+ ? marked(p, row.entity.eid, facts)
274
+ : [at.get(String(got))]
275
+ if (
276
+ got !== null &&
277
+ (!targets[0] ||
278
+ comp(targets[0], p.ack.component)?.[p.ack.ref] != row.entity.eid)
279
+ ) fail('acknowledgement must address its source entity')
280
+ for (let target of targets) {
281
+ if (!target || ctx.migrate && target[p.ack.mark]) continue
282
+ let mark: Comp | null = got === null ? null : {}
283
+ if (ctx.migrate && mark) {
284
+ let atProp = Object.entries(v.props).find(([, mapping]) =>
285
+ 'path' in mapping && mapping.convert == 'milliseconds'
286
+ )?.[0]
287
+ mark = {
288
+ ...comp(held, 'created'),
289
+ ...comp(held, 'updated'),
290
+ ...(atProp && source?.[atProp] ? { at: source[atProp] } : {}),
291
+ }
292
+ }
293
+ extra.push({
294
+ entity: target.entity,
295
+ [p.ack.mark]: mark,
296
+ ...(row.$actor ? { $actor: row.$actor } : {}),
297
+ $was: {
298
+ [p.ack.component]: { [p.ack.ref]: token(row.entity.eid) },
299
+ [p.ack.mark]: Object.fromEntries(
300
+ ['at', 'by', 'via'].map((
301
+ k,
302
+ ) => [k, token(comp(target, p.ack.mark)?.[k])]),
303
+ ),
304
+ },
305
+ })
306
+ }
307
+ }
308
+ if (source === null) {
309
+ for (let p of Object.values(v.props)) {
310
+ if ('path' in p) patch[p.path.split('.')[0]] = null
311
+ }
312
+ }
313
+ if (source) {
314
+ for (let name of Object.keys(source)) {
315
+ if (!v.props[name]) fail(`unknown view property ${v.from}.${name}`)
316
+ }
317
+ }
318
+ return [patch, ...extra]
319
+ })
320
+ }
321
+ return out
322
+ }
323
+
324
+ /** A normal write consumes any pending source it depends on. Partial writes
325
+ * first carry the whole canonical fact across; clearing a view cannot revive
326
+ * the old stored value on the next read. The shell preserves generated historic
327
+ * stamps after admission, never stamps supplied by the caller. */
328
+ export let stageViews = (
329
+ rows: Bundle[],
330
+ views: ComponentView[],
331
+ ctx: Facts = {},
332
+ ): Bundle[] => {
333
+ let translated = ctx.canonical ? rows : putViews(rows, views, ctx)
334
+ if (
335
+ ctx.migrate || !ctx.vocab || !views.some((v) => ctx.vocab!.comp(v.from))
336
+ ) return translated
337
+ let facts = ctx.facts ?? []
338
+ let at = new Map(facts.map((r) => [r.entity.eid, r]))
339
+ let bases: Bundle[] = []
340
+ for (let v of views) {
341
+ if (!ctx.vocab.comp(v.from)) continue
342
+ for (let held of facts) {
343
+ if (!held[v.from]) continue
344
+ let incoming = rows.find((r) =>
345
+ r.entity.eid == held.entity.eid &&
346
+ (v.from in r || Object.values(v.props).some((p) =>
347
+ 'path' in p && p.path.split('.')[0] in r
348
+ ))
349
+ )
350
+ let related = rows.find((r) =>
351
+ Object.values(v.props).some((p) =>
352
+ 'ack' in p && p.ack.mark in r &&
353
+ (at.get(r.entity.eid)?.[p.ack.component] as Comp | undefined)
354
+ ?.[p.ack.ref] == held.entity.eid
355
+ )
356
+ )
357
+ let writer = incoming ?? related
358
+ if (!writer) continue
359
+ let source = { ...comp(held, v.from) }
360
+ // A clear means the legacy acknowledgement is deliberately forgotten.
361
+ for (let [name, p] of Object.entries(v.props)) {
362
+ if (
363
+ 'ack' in p &&
364
+ (incoming?.[v.from] === null ||
365
+ comp(incoming, v.from)?.[name] === null ||
366
+ related?.[p.ack.mark] === null &&
367
+ source[name] == related.entity.eid)
368
+ ) delete source[name]
369
+ }
370
+ // Held components supply facts, not extra writes on the source.
371
+ let moved = putViews(
372
+ [{ entity: { eid: held.entity.eid }, [v.from]: source }],
373
+ [v],
374
+ {
375
+ ...ctx,
376
+ migrate: true,
377
+ },
378
+ )
379
+ let base = moved[0]
380
+ base[v.from] = null
381
+ base.$actor = writer.$actor
382
+ base.$was = {
383
+ [v.from]: Object.fromEntries(
384
+ Object.keys(v.declaration.properties ?? {}).map((
385
+ p,
386
+ ) => [p, token(comp(held, v.from)?.[p])]),
387
+ ),
388
+ }
389
+ for (let p of Object.values(v.props)) {
390
+ if ('path' in p) {
391
+ let [c, name] = p.path.split('.')
392
+ base.$was[c] = {
393
+ ...base.$was[c],
394
+ [name]: token(comp(held, c)?.[name]),
395
+ }
396
+ }
397
+ }
398
+ bases.push(base)
399
+ for (let mark of moved.slice(1)) {
400
+ let mapping = Object.values(v.props).find((p) =>
401
+ 'ack' in p && p.ack.mark in mark
402
+ ) as Extract<ViewProp, { ack: object }>
403
+ bases.push({
404
+ ...mark,
405
+ [mapping.ack.mark]: {},
406
+ $actor: writer.$actor,
407
+ $lensKeep: {
408
+ component: mapping.ack.mark,
409
+ value: mark[mapping.ack.mark],
410
+ },
411
+ })
412
+ }
413
+ }
414
+ }
415
+ if (!bases.length) return translated
416
+ let out = new Map<string, Bundle>()
417
+ let merge = (b: Bundle) => {
418
+ let held = out.get(b.entity.eid)
419
+ if (!held) {
420
+ out.set(b.entity.eid, b)
421
+ return
422
+ }
423
+ let next = { ...held, ...b }
424
+ for (let [c, props] of Object.entries(b)) {
425
+ if (
426
+ c != 'entity' && props && typeof props == 'object' && !c.startsWith('$')
427
+ ) next[c] = { ...held[c] as object, ...props }
428
+ }
429
+ if (held.$was || b.$was) {
430
+ next.$was = { ...held.$was }
431
+ for (let [c, props] of Object.entries(b.$was ?? {})) {
432
+ next.$was[c] = { ...next.$was[c], ...props }
433
+ }
434
+ }
435
+ // Repeating an acknowledgement already represented by the source keeps
436
+ // its historical stamps; an explicit clear still clears it.
437
+ let historic = held.$lensKeep as
438
+ | { component: string; value: Comp }
439
+ | undefined
440
+ if (historic && b[historic.component] !== null) {
441
+ next[historic.component] = {}
442
+ }
443
+ if (historic && b[historic.component] === null) delete next.$lensKeep
444
+ out.set(b.entity.eid, next)
445
+ }
446
+ for (let b of [...bases, ...translated]) merge(b)
447
+ return [...out.values()]
448
+ }
package/vocab.js ADDED
@@ -0,0 +1,11 @@
1
+ import doc from './vocab.json' with {
2
+ type: 'json'
3
+ };
4
+ import manifest from './package.json' with {
5
+ type: 'json'
6
+ };
7
+ /** The private `_lens{package, step, ops}` vocabulary. */ export let docs = [
8
+ doc
9
+ ];
10
+ /** This package's description, from its manifest. */ export let description = manifest.description;
11
+ //# sourceMappingURL=vocab.js.map
package/vocab.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.js","sources":["./vocab.ts"],"names":[],"mappings":"AACA,OAAO,SAAS,oBAAoB;EAAE,MAAM;AAAO,EAAC;AACpD,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAE3D,wDAAwD,GACxD,OAAO,IAAI,OAAmB;EAAC;CAAgB,CAAA;AAC/C,mDAAmD,GACnD,OAAO,IAAI,cAAsB,SAAS,WAAW,CAAA"}
package/vocab.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "$id": "urn:uuid:22e6bf4d-8dfd-413c-b1d4-cb8ce8d8e4be",
3
+ "$defs": {
4
+ "_lens": {
5
+ "$id": "urn:uuid:a1c160ab-ceef-4529-adb8-60a89108256c",
6
+ "component": true,
7
+ "journal": false,
8
+ "type": "object",
9
+ "wire": false,
10
+ "identity": ["package", "step"],
11
+ "description": "One immutable forward step in a package's vocabulary, named by a UTC YYYYMMDDHHMMSS timestamp.",
12
+ "properties": {
13
+ "package": {
14
+ "$id": "urn:uuid:79725c80-a180-493e-8efc-7939614be83a",
15
+ "type": "string",
16
+ "ref": "_namespace",
17
+ "death": "cascade",
18
+ "description": "The namespace whose vocabulary changes."
19
+ },
20
+ "step": {
21
+ "$id": "urn:uuid:8ab6ca4c-95f2-45c7-bc85-52c74f04a22f",
22
+ "type": "integer",
23
+ "minimum": 0,
24
+ "description": "The UTC YYYYMMDDHHMMSS timestamp; landed pilot steps retain their original zero-based names."
25
+ },
26
+ "ops": {
27
+ "$id": "urn:uuid:2ad3c41e-668e-4b05-be08-961d4426807b",
28
+ "type": "array",
29
+ "description": "The operations in this step, in order."
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }
package/vocab.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
2
+ import doc from './vocab.json' with { type: 'json' }
3
+ import manifest from './package.json' with { type: 'json' }
4
+
5
+ /** The private `_lens{package, step, ops}` vocabulary. */
6
+ export let docs: VocabDoc[] = [doc as VocabDoc]
7
+ /** This package's description, from its manifest. */
8
+ export let description: string = manifest.description