@yaks/journal 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 (84) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +522 -2
  3. package/_dist/backed.d.ts +9 -0
  4. package/_dist/backed.d.ts.map +1 -0
  5. package/_dist/batch.d.ts +45 -0
  6. package/_dist/batch.d.ts.map +1 -0
  7. package/_dist/feed.d.ts +108 -0
  8. package/_dist/feed.d.ts.map +1 -0
  9. package/_dist/graph.d.ts +104 -0
  10. package/_dist/graph.d.ts.map +1 -0
  11. package/_dist/kept.d.ts +63 -0
  12. package/_dist/kept.d.ts.map +1 -0
  13. package/_dist/log.d.ts +142 -0
  14. package/_dist/log.d.ts.map +1 -0
  15. package/_dist/merge.d.ts +41 -0
  16. package/_dist/merge.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +101 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/service.d.ts +68 -0
  20. package/_dist/service.d.ts.map +1 -0
  21. package/_dist/tools.d.ts +5 -0
  22. package/_dist/tools.d.ts.map +1 -0
  23. package/_dist/undo.d.ts +48 -0
  24. package/_dist/undo.d.ts.map +1 -0
  25. package/_dist/value.d.ts +6 -0
  26. package/_dist/value.d.ts.map +1 -0
  27. package/_dist/views.d.ts +25 -0
  28. package/_dist/views.d.ts.map +1 -0
  29. package/_dist/vocab.d.ts +7 -0
  30. package/_dist/vocab.d.ts.map +1 -0
  31. package/backed.js +225 -0
  32. package/backed.js.map +1 -0
  33. package/backed.ts +274 -0
  34. package/batch.js +12 -0
  35. package/batch.js.map +1 -0
  36. package/batch.ts +84 -0
  37. package/deno.json +1 -0
  38. package/feed.js +295 -0
  39. package/feed.js.map +1 -0
  40. package/feed.ts +368 -0
  41. package/graph.js +224 -0
  42. package/graph.js.map +1 -0
  43. package/graph.ts +329 -0
  44. package/held.js +25 -0
  45. package/held.js.map +1 -0
  46. package/held.ts +24 -0
  47. package/kept.js +61 -0
  48. package/kept.js.map +1 -0
  49. package/kept.ts +100 -0
  50. package/log.js +1161 -0
  51. package/log.js.map +1 -0
  52. package/log.ts +1299 -0
  53. package/merge.js +158 -0
  54. package/merge.js.map +1 -0
  55. package/merge.ts +185 -0
  56. package/mod.js +101 -0
  57. package/mod.js.map +1 -0
  58. package/mod.ts +102 -0
  59. package/names.js +206 -0
  60. package/names.js.map +1 -0
  61. package/names.ts +230 -0
  62. package/package.json +52 -4
  63. package/page.js +160 -0
  64. package/page.js.map +1 -0
  65. package/page.ts +233 -0
  66. package/service.js +118 -0
  67. package/service.js.map +1 -0
  68. package/service.ts +148 -0
  69. package/tools.js +110 -0
  70. package/tools.js.map +1 -0
  71. package/tools.ts +113 -0
  72. package/undo.js +187 -0
  73. package/undo.js.map +1 -0
  74. package/undo.ts +190 -0
  75. package/value.js +26 -0
  76. package/value.js.map +1 -0
  77. package/value.ts +35 -0
  78. package/views.js +85 -0
  79. package/views.js.map +1 -0
  80. package/views.ts +91 -0
  81. package/vocab.js +20 -0
  82. package/vocab.js.map +1 -0
  83. package/vocab.json +308 -0
  84. package/vocab.ts +22 -0
package/tools.ts ADDED
@@ -0,0 +1,113 @@
1
+ // `@yaks/journal/tools` — what an agent may ask the log: the function behind
2
+ // the `history` declaration in ./vocab.json, because the log answers one
3
+ // question people actually ask: what happened to this, and who did it. And
4
+ // the graph's branches, which its versions make possible (D-395): made,
5
+ // listed, merged, trashed and restored here, read and written through the graph's own
6
+ // tools. A merge with a conflict left writes nothing and answers the
7
+ // conflicts, each side by side, for a person to pick (./merge.ts).
8
+ //
9
+ // The answer is bundles, and each bundle is the transaction: `applied()`
10
+ // rebuilds what a write committed out of the log's own record, so a history row
11
+ // has the same shape as the write that produced it — the components it patched,
12
+ // or `$delete` if it deleted the entity. Which transaction it was — its place in
13
+ // the log, when it committed, whom it acted for and through what — is carried on
14
+ // `_tx`, this package's own word for a committed transaction, so a row reads as
15
+ // the moment it was and draws as one (./views.ts).
16
+ //
17
+ // There is no `undo` tool here and no feed. Undo is `undo(g, j)` in ./undo.ts —
18
+ // a write, and one a server has to decide it offers — and a feed is a cursor a
19
+ // consumer holds, not a question anybody types.
20
+
21
+ import type { Bundle, Comp, Graph, GraphBranches } from 'jsr:@yaks/graph@0.2.36'
22
+ import type { Branch } from 'jsr:@yaks/graph@0.2.36/storage'
23
+ import { argsOf } from '@yaks/graph/call'
24
+ import { Refused } from '@yaks/graph/errors'
25
+ import type { Runs } from 'jsr:@yaks/graph@0.2.36/tools'
26
+ import type { Batch } from './batch.ts'
27
+ import { applied } from './undo.js'
28
+ import { type Choice, merge } from './merge.js'
29
+ import { actorOf } from '@yaks/graph/provenance'
30
+ import { type Bound, logFor } from './graph.js'
31
+
32
+ // Which transaction it was: where it sits in the log, when it committed, whom
33
+ // it acted for and through what.
34
+ let stamp = (b: Batch): Comp => ({
35
+ seq: b.seq,
36
+ at: b.at,
37
+ ...(b.by ? { by: b.by } : {}),
38
+ ...(b.via ? { via: b.via } : {}),
39
+ })
40
+
41
+ // One committed transaction as the patch it applied to one entity, stamped. The
42
+ // log is cut to that entity first, so a transaction that also moved something
43
+ // else reports only this entity's part of it.
44
+ let said = (b: Batch): Bundle[] =>
45
+ applied(b).map((patch) => ({ ...patch, _tx: stamp(b) }))
46
+
47
+ // The graph's branches, or the reason it has none.
48
+ let branches = (graph: Graph) => {
49
+ if (!graph.branches) {
50
+ throw new Refused(
51
+ 'this graph keeps no branches: list @yaks/journal with versions on',
52
+ )
53
+ }
54
+ return graph.branches
55
+ }
56
+
57
+ // A branch tool's answer: what it says about the branches, as data.
58
+ let told = (call: Bundle, value: unknown): Bundle[] => [{
59
+ entity: { eid: '$said' },
60
+ output: { source: call.entity.eid, value },
61
+ }]
62
+
63
+ // The branch `id`, or the refusal that names it.
64
+ let known = async (
65
+ all: GraphBranches,
66
+ id: number,
67
+ trash = false,
68
+ ): Promise<Branch> => {
69
+ let b = (await all.list(trash)).find((b) => b.id == id)
70
+ if (!b) throw new Refused(`no branch ${id}`)
71
+ return b
72
+ }
73
+
74
+ /** The functions behind the tools ./vocab.json declares — read over this
75
+ * host's storage, which is why this export is a factory. */
76
+ export let runs = (host: Bound): Runs => {
77
+ let j = logFor(host)
78
+ return {
79
+ history: (call): Bundle[] | Promise<Bundle[]> => {
80
+ let args = argsOf(call)
81
+ let asked = String(args.entity ?? '').trim()
82
+ if (!asked) throw new Refused('history needs an entity')
83
+ if (host.reader?.tool) return host.reader.tool('history', call)
84
+ let n = args.limit == null ? undefined : Number(args.limit)
85
+ // Newest first: a history is read back from where the entity got to.
86
+ return j.history(asked, n).reverse().flatMap(said)
87
+ },
88
+ branch_new: async (call, graph) => told(call, await branches(graph).make()),
89
+ branch_list: async (call, graph) =>
90
+ told(call, await branches(graph).list(!!argsOf(call).trash)),
91
+ branch_delete: async (call, graph) => {
92
+ let id = Number(argsOf(call).id)
93
+ let all = branches(graph)
94
+ let gone = await known(all, id)
95
+ await all.drop(id)
96
+ return told(call, (await all.list(true)).find((b) => b.id == gone.id))
97
+ },
98
+ branch_restore: async (call, graph) => {
99
+ let id = Number(argsOf(call).id)
100
+ let all = branches(graph)
101
+ await known(all, id, true)
102
+ await all.restore(id)
103
+ return told(call, await known(all, id))
104
+ },
105
+ branch_merge: async (call, graph) => {
106
+ let args = argsOf(call)
107
+ let id = Number(args.id)
108
+ await known(branches(graph), id)
109
+ let picks = (args.pick ?? []) as Choice[]
110
+ return told(call, await merge(graph)(id, picks, actorOf([call])))
111
+ },
112
+ }
113
+ }
package/undo.js ADDED
@@ -0,0 +1,187 @@
1
+ // Walking a recorded transaction in either direction. A recorded transaction
2
+ // carries both sides of every movement, so replaying it forward rebuilds the
3
+ // write that happened and replaying it backward builds the write that reverses
4
+ // it — one function, one argument apart.
5
+ //
6
+ // Forward is what a server pushes to its subscribers: the transaction as
7
+ // committed, as bundles, without reading storage at all. Backward is undo, and
8
+ // undo is an ordinary write — it goes through `apply()` like any other, so it
9
+ // is admitted, guarded, stamped, and journaled in its turn. Undoing an undo is
10
+ // a redo, for free.
11
+ //
12
+ // A deletion walks backward like anything else. The journal knows every
13
+ // component the entity held as it went, so the reversal gives them back, and a
14
+ // write that gives a deleted entity a component is what clears its tombstone
15
+ // (@yaks/graph's mutate phase): it comes back with its eid and its number.
16
+ // Whatever the deletion cascaded is in the same transaction and comes back
17
+ // with it.
18
+ import { CallError } from "@yaks/tools/errors";
19
+ import { token } from "@yaks/graph/sha256";
20
+ import { TOMBSTONE } from "@yaks/graph/bundle";
21
+ /** A refused undo: the transaction deleted an entity whose components the
22
+ * journal never recorded — it was written before the journal began, or only
23
+ * in components the journal skips — so nothing can bring it back, and bringing
24
+ * back the rest would leave whatever pointed at it pointing at a grave. */ export class Final extends Error {
25
+ eid;
26
+ seq;
27
+ /**
28
+ * @param eid the entity the transaction deleted
29
+ * @param seq the transaction it was deleted in
30
+ */ constructor(eid, seq){
31
+ super(`${eid} was deleted in batch #${seq}, and the journal holds none of ` + `its components to bring it back with`), this.eid = eid, this.seq = seq;
32
+ this.name = 'Final';
33
+ }
34
+ }
35
+ // One side of a recorded transaction, as bundles. The deltas are replayed onto
36
+ // a per-entity table of components: forward for the side after, so a
37
+ // component the transaction touched twice comes out where it ended up, and
38
+ // backward for the side before, so it comes out where it started.
39
+ let side = (batch, want, guard = false)=>{
40
+ let back = want == 'before';
41
+ let order = [
42
+ ...new Set(batch.deltas.map((d)=>d.target))
43
+ ];
44
+ let held = new Map();
45
+ // Whether each entity the transaction deleted or brought back lies deleted
46
+ // on this side, and which of them it deleted.
47
+ let grave = new Map();
48
+ let killed = new Set();
49
+ // What the transaction left in each property, hashed: the precondition an
50
+ // undo carries, so that a property somebody else has changed since refuses
51
+ // the whole reversal rather than quietly overwriting it. Walking backward,
52
+ // the first delta to name a property holds the last value the transaction
53
+ // left there, and a component it removed, or an entity it deleted, left
54
+ // nothing in any of them. Only the backward side needs one — replaying
55
+ // forward is a push to subscribers, not a write.
56
+ let was = new Map();
57
+ let guarded = (eid, comp, prop, after)=>{
58
+ if (!guard) return;
59
+ let w = was.get(eid);
60
+ if (!w) was.set(eid, w = {});
61
+ let c = w[comp] ??= {};
62
+ if (!(prop in c)) c[prop] = token(after);
63
+ };
64
+ let of = (eid)=>{
65
+ let t = held.get(eid);
66
+ if (!t) held.set(eid, t = new Map());
67
+ return t;
68
+ };
69
+ for (let d of back ? batch.deltas.toReversed() : batch.deltas){
70
+ if (d.comp == TOMBSTONE) {
71
+ grave.set(d.target, d[want] != null);
72
+ if (d.after != null) killed.add(d.target);
73
+ continue;
74
+ }
75
+ let table = of(d.target);
76
+ if (d.prop == null) {
77
+ let whole = d[want];
78
+ table.set(d.comp, whole == null ? null : {
79
+ ...whole
80
+ });
81
+ for (let prop of Object.keys(whole ?? {})){
82
+ guarded(d.target, d.comp, prop, null);
83
+ }
84
+ continue;
85
+ }
86
+ guarded(d.target, d.comp, d.prop, d.after);
87
+ let cur = table.get(d.comp);
88
+ if (cur === null) continue; // the component is not there on this side
89
+ table.set(d.comp, {
90
+ ...cur ?? {},
91
+ [d.prop]: d[want] ?? null
92
+ });
93
+ }
94
+ let out = [];
95
+ for (let eid of order){
96
+ if (grave.get(eid)) {
97
+ out.push({
98
+ entity: {
99
+ eid
100
+ },
101
+ $delete: true
102
+ });
103
+ continue;
104
+ }
105
+ let table = held.get(eid);
106
+ if (!table?.size) {
107
+ if (back && killed.has(eid)) throw new Final(eid, batch.seq);
108
+ continue;
109
+ }
110
+ let b = {
111
+ entity: {
112
+ eid
113
+ }
114
+ };
115
+ for (let [comp, value] of table){
116
+ // The entity row is the bundle's own identity, not a component beside
117
+ // it: a recorded patch to `entity` merges into the key naming which
118
+ // entity this bundle is about, and never lands on top of the eid. A
119
+ // graph this package journals never records one (the hook skips the
120
+ // entity row), but a log imported from elsewhere can hold them, and a
121
+ // bundle with no eid is not a bundle.
122
+ if (comp == 'entity') {
123
+ if (value) b.entity = {
124
+ ...b.entity,
125
+ ...value
126
+ };
127
+ continue;
128
+ }
129
+ b[comp] = value;
130
+ }
131
+ let w = was.get(eid);
132
+ // A guard names only properties this bundle restores: a component the undo
133
+ // removes whole has no property to hold a token.
134
+ if (w) {
135
+ let mine = {};
136
+ for (let [comp, props] of Object.entries(w)){
137
+ if (b[comp] != null) mine[comp] = props;
138
+ }
139
+ if (Object.keys(mine).length) b.$was = mine;
140
+ }
141
+ out.push(b);
142
+ }
143
+ return out;
144
+ };
145
+ /**
146
+ * The transaction as committed, rebuilt from its deltas — the bundles a server
147
+ * pushes to its subscribers when it reads the feed, with no read of storage at
148
+ * all. They carry what moved, so who wrote it and when, which the `journal_tx`
149
+ * row already holds, are not repeated in them.
150
+ */ export let applied = (batch)=>side(batch, 'after');
151
+ /**
152
+ * The bundles that reverse a transaction: every property back to the value it
153
+ * held, every component that went restored with the properties it had, every
154
+ * component that appeared removed, every entity it deleted given back the
155
+ * components it held, and every entity it brought back deleted again. Throws
156
+ * {@link Final} if the transaction deleted an entity the journal recorded none
157
+ * of the components of.
158
+ */ export let undone = (batch, opts = {})=>side(batch, 'before', opts.guard);
159
+ /**
160
+ * Undo a committed transaction by its `seq`: read it back out of the log, build
161
+ * the inverse from what was written down, and apply it through the graph — so
162
+ * the undo is admitted, stamped and journaled like any other write:
163
+ * `undo(g, j)(7, { by: 'ada' })` reverses transaction 7 as `ada`.
164
+ *
165
+ * Throws {@link Final} if the transaction deleted an entity the journal holds
166
+ * none of the components of, and a plain `Error` if no transaction has that
167
+ * seq. The inverse is applied as trusted, since restoring a property the
168
+ * server owns is the graph's own reconstruction rather than a client's write.
169
+ * Every restored property carries a `$was` precondition, so a property
170
+ * somebody else has changed since refuses the whole reversal instead of being
171
+ * overwritten.
172
+ */ export let undo = (g, j)=>(seq, actor)=>{
173
+ let batch = j.at(seq);
174
+ if (!batch) throw new CallError('batch', `no journal batch #${seq}`);
175
+ let bundles = undone(batch, {
176
+ guard: true
177
+ });
178
+ if (!bundles.length) return [];
179
+ if (actor) bundles[0] = {
180
+ ...bundles[0],
181
+ $actor: actor
182
+ };
183
+ return g.apply(bundles, {
184
+ trusted: true
185
+ });
186
+ };
187
+ //# sourceMappingURL=undo.js.map
package/undo.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"undo.js","sources":["./undo.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,6EAA6E;AAC7E,+EAA+E;AAC/E,yCAAyC;AACzC,EAAE;AACF,yEAAyE;AACzE,+EAA+E;AAC/E,8EAA8E;AAC9E,+EAA+E;AAC/E,oBAAoB;AACpB,EAAE;AACF,wEAAwE;AACxE,+EAA+E;AAC/E,6EAA6E;AAC7E,2EAA2E;AAC3E,2EAA2E;AAC3E,WAAW;AAEX,SAAS,SAAS,kCAAuC;AAEzD,SAAS,KAAK,kCAAuC;AACrD,SAAS,SAAS,kCAAuC;AAIzD;;;yEAGyE,GACzE,OAAO,MAAM,cAAc;;;EACzB;;;GAGC,GACD,YAAY,AAAO,GAAQ,EAAE,AAAO,GAAW,CAAE;IAC/C,KAAK,CACH,GAAG,IAAI,uBAAuB,EAAE,IAAI,gCAAgC,CAAC,GACnE,CAAC,oCAAoC,CAAC,QAHzB,MAAA,UAAiB,MAAA;IAKlC,IAAI,CAAC,IAAI,GAAG;EACd;AACF;AAEA,+EAA+E;AAC/E,qEAAqE;AACrE,2EAA2E;AAC3E,kEAAkE;AAClE,IAAI,OAAO,CACT,OACA,MACA,QAAQ,KAAK;EAEb,IAAI,OAAO,QAAQ;EACnB,IAAI,QAAQ;OAAI,IAAI,IAAI,MAAM,MAAM,CAAC,GAAG,CAAC,CAAC,IAAM,EAAE,MAAM;GAAG;EAC3D,IAAI,OAAO,IAAI;EACf,2EAA2E;EAC3E,8CAA8C;EAC9C,IAAI,QAAQ,IAAI;EAChB,IAAI,SAAS,IAAI;EACjB,0EAA0E;EAC1E,2EAA2E;EAC3E,2EAA2E;EAC3E,0EAA0E;EAC1E,wEAAwE;EACxE,uEAAuE;EACvE,iDAAiD;EACjD,IAAI,MAAM,IAAI;EACd,IAAI,UAAU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AmB,CAAC,CAAC,GACtD,KAAK,OAAO,UAAU,KAAK,KAAK,EAAC;AAEnC;;;;;;;;;;;;;CAaC,GACD,OAAO,IAAI,OACT,CAAC,GAAU,IACX,CAAC,KAAa;IACZ,IAAI,QAAQ,EAAE,EAAE,CAAC;IACjB,IAAI,CAAC,OAAO,MAAM,IAAI,UAAU,SAAS,CAAC,kBAAkB,EAAE,KAAK;IACnE,IAAI,UAAU,OAAO,OAAO;MAAE,OAAO;IAAK;IAC1C,IAAI,CAAC,QAAQ,MAAM,EAAE,OAAO,EAAE;IAC9B,IAAI,OAAO,OAAO,CAAC,EAAE,GAAG;MAAE,GAAG,OAAO,CAAC,EAAE;MAAE,QAAQ;IAAM;IACvD,OAAO,EAAE,KAAK,CAAC,SAAS;MAAE,SAAS;IAAK;EAC1C,EAAC"}
package/undo.ts ADDED
@@ -0,0 +1,190 @@
1
+ // Walking a recorded transaction in either direction. A recorded transaction
2
+ // carries both sides of every movement, so replaying it forward rebuilds the
3
+ // write that happened and replaying it backward builds the write that reverses
4
+ // it — one function, one argument apart.
5
+ //
6
+ // Forward is what a server pushes to its subscribers: the transaction as
7
+ // committed, as bundles, without reading storage at all. Backward is undo, and
8
+ // undo is an ordinary write — it goes through `apply()` like any other, so it
9
+ // is admitted, guarded, stamped, and journaled in its turn. Undoing an undo is
10
+ // a redo, for free.
11
+ //
12
+ // A deletion walks backward like anything else. The journal knows every
13
+ // component the entity held as it went, so the reversal gives them back, and a
14
+ // write that gives a deleted entity a component is what clears its tombstone
15
+ // (@yaks/graph's mutate phase): it comes back with its eid and its number.
16
+ // Whatever the deletion cascaded is in the same transaction and comes back
17
+ // with it.
18
+
19
+ import { CallError } from '@yaks/tools/errors'
20
+ import type { Actor, Bundle, Comp, Eid, Graph, Was } from 'jsr:@yaks/graph@0.2.36'
21
+ import { token } from '@yaks/graph/sha256'
22
+ import { TOMBSTONE } from '@yaks/graph/bundle'
23
+ import type { Batch } from './batch.ts'
24
+ import type { Log } from './log.ts'
25
+
26
+ /** A refused undo: the transaction deleted an entity whose components the
27
+ * journal never recorded — it was written before the journal began, or only
28
+ * in components the journal skips — so nothing can bring it back, and bringing
29
+ * back the rest would leave whatever pointed at it pointing at a grave. */
30
+ export class Final extends Error {
31
+ /**
32
+ * @param eid the entity the transaction deleted
33
+ * @param seq the transaction it was deleted in
34
+ */
35
+ constructor(public eid: Eid, public seq: number) {
36
+ super(
37
+ `${eid} was deleted in batch #${seq}, and the journal holds none of ` +
38
+ `its components to bring it back with`,
39
+ )
40
+ this.name = 'Final'
41
+ }
42
+ }
43
+
44
+ // One side of a recorded transaction, as bundles. The deltas are replayed onto
45
+ // a per-entity table of components: forward for the side after, so a
46
+ // component the transaction touched twice comes out where it ended up, and
47
+ // backward for the side before, so it comes out where it started.
48
+ let side = (
49
+ batch: Batch,
50
+ want: 'before' | 'after',
51
+ guard = false,
52
+ ): Bundle[] => {
53
+ let back = want == 'before'
54
+ let order = [...new Set(batch.deltas.map((d) => d.target))]
55
+ let held = new Map<Eid, Map<string, Comp | null>>()
56
+ // Whether each entity the transaction deleted or brought back lies deleted
57
+ // on this side, and which of them it deleted.
58
+ let grave = new Map<Eid, boolean>()
59
+ let killed = new Set<Eid>()
60
+ // What the transaction left in each property, hashed: the precondition an
61
+ // undo carries, so that a property somebody else has changed since refuses
62
+ // the whole reversal rather than quietly overwriting it. Walking backward,
63
+ // the first delta to name a property holds the last value the transaction
64
+ // left there, and a component it removed, or an entity it deleted, left
65
+ // nothing in any of them. Only the backward side needs one — replaying
66
+ // forward is a push to subscribers, not a write.
67
+ let was = new Map<Eid, Was>()
68
+ let guarded = (eid: Eid, comp: string, prop: string, after: unknown) => {
69
+ if (!guard) return
70
+ let w = was.get(eid)
71
+ if (!w) was.set(eid, w = {})
72
+ let c = w[comp] ??= {}
73
+ if (!(prop in c)) c[prop] = token(after)
74
+ }
75
+ let of = (eid: Eid): Map<string, Comp | null> => {
76
+ let t = held.get(eid)
77
+ if (!t) held.set(eid, t = new Map())
78
+ return t
79
+ }
80
+ for (let d of back ? batch.deltas.toReversed() : batch.deltas) {
81
+ if (d.comp == TOMBSTONE) {
82
+ grave.set(d.target, d[want] != null)
83
+ if (d.after != null) killed.add(d.target)
84
+ continue
85
+ }
86
+ let table = of(d.target)
87
+ if (d.prop == null) {
88
+ let whole = d[want] as Comp | null
89
+ table.set(d.comp, whole == null ? null : { ...whole })
90
+ for (let prop of Object.keys(whole ?? {})) {
91
+ guarded(d.target, d.comp, prop, null)
92
+ }
93
+ continue
94
+ }
95
+ guarded(d.target, d.comp, d.prop, d.after)
96
+ let cur = table.get(d.comp)
97
+ if (cur === null) continue // the component is not there on this side
98
+ table.set(d.comp, { ...(cur ?? {}), [d.prop]: d[want] ?? null })
99
+ }
100
+ let out: Bundle[] = []
101
+ for (let eid of order) {
102
+ if (grave.get(eid)) {
103
+ out.push({ entity: { eid }, $delete: true })
104
+ continue
105
+ }
106
+ let table = held.get(eid)
107
+ if (!table?.size) {
108
+ if (back && killed.has(eid)) throw new Final(eid, batch.seq)
109
+ continue
110
+ }
111
+ let b: Bundle = { entity: { eid } }
112
+ for (let [comp, value] of table) {
113
+ // The entity row is the bundle's own identity, not a component beside
114
+ // it: a recorded patch to `entity` merges into the key naming which
115
+ // entity this bundle is about, and never lands on top of the eid. A
116
+ // graph this package journals never records one (the hook skips the
117
+ // entity row), but a log imported from elsewhere can hold them, and a
118
+ // bundle with no eid is not a bundle.
119
+ if (comp == 'entity') {
120
+ if (value) b.entity = { ...b.entity, ...value }
121
+ continue
122
+ }
123
+ b[comp] = value
124
+ }
125
+ let w = was.get(eid)
126
+ // A guard names only properties this bundle restores: a component the undo
127
+ // removes whole has no property to hold a token.
128
+ if (w) {
129
+ let mine: Was = {}
130
+ for (let [comp, props] of Object.entries(w)) {
131
+ if (b[comp] != null) mine[comp] = props
132
+ }
133
+ if (Object.keys(mine).length) b.$was = mine
134
+ }
135
+ out.push(b)
136
+ }
137
+ return out
138
+ }
139
+
140
+ /**
141
+ * The transaction as committed, rebuilt from its deltas — the bundles a server
142
+ * pushes to its subscribers when it reads the feed, with no read of storage at
143
+ * all. They carry what moved, so who wrote it and when, which the `journal_tx`
144
+ * row already holds, are not repeated in them.
145
+ */
146
+ export let applied = (batch: Batch): Bundle[] => side(batch, 'after')
147
+
148
+ /** How an undo is built. */
149
+ export type UndoneOpts = {
150
+ /** carry a `$was` precondition on every restored property, hashed from the
151
+ * value the transaction left there, so that a property changed since refuses
152
+ * the reversal */
153
+ guard?: boolean
154
+ }
155
+
156
+ /**
157
+ * The bundles that reverse a transaction: every property back to the value it
158
+ * held, every component that went restored with the properties it had, every
159
+ * component that appeared removed, every entity it deleted given back the
160
+ * components it held, and every entity it brought back deleted again. Throws
161
+ * {@link Final} if the transaction deleted an entity the journal recorded none
162
+ * of the components of.
163
+ */
164
+ export let undone = (batch: Batch, opts: UndoneOpts = {}): Bundle[] =>
165
+ side(batch, 'before', opts.guard)
166
+
167
+ /**
168
+ * Undo a committed transaction by its `seq`: read it back out of the log, build
169
+ * the inverse from what was written down, and apply it through the graph — so
170
+ * the undo is admitted, stamped and journaled like any other write:
171
+ * `undo(g, j)(7, { by: 'ada' })` reverses transaction 7 as `ada`.
172
+ *
173
+ * Throws {@link Final} if the transaction deleted an entity the journal holds
174
+ * none of the components of, and a plain `Error` if no transaction has that
175
+ * seq. The inverse is applied as trusted, since restoring a property the
176
+ * server owns is the graph's own reconstruction rather than a client's write.
177
+ * Every restored property carries a `$was` precondition, so a property
178
+ * somebody else has changed since refuses the whole reversal instead of being
179
+ * overwritten.
180
+ */
181
+ export let undo =
182
+ (g: Graph, j: Log) =>
183
+ (seq: number, actor?: Actor): Bundle[] | Promise<Bundle[]> => {
184
+ let batch = j.at(seq)
185
+ if (!batch) throw new CallError('batch', `no journal batch #${seq}`)
186
+ let bundles = undone(batch, { guard: true })
187
+ if (!bundles.length) return []
188
+ if (actor) bundles[0] = { ...bundles[0], $actor: actor }
189
+ return g.apply(bundles, { trusted: true })
190
+ }
package/value.js ADDED
@@ -0,0 +1,26 @@
1
+ // How a property's value is written down. The journal has to hold values of
2
+ // every property type in two columns of its own, so each side of a delta is
3
+ // stored as JSON, with bytes marked by a non-JSON `binary:` prefix: `12` and `"12"` come back as a number and a string rather
4
+ // than as the same string twice, and a boolean survives an adapter that stores
5
+ // it as 0/1.
6
+ //
7
+ // Absence has one representation. A property with no value, a property a patch
8
+ // cleared, and a component that was not there are all `null` here — the same
9
+ // rule a client's JSON follows, where a `null` property is the cleared one.
10
+ import { fromBase64, toBase64 } from "@yaks/fp";
11
+ /** A value as the journal stores it: JSON, marked base64 bytes, or `null`
12
+ * for no value at all. JSON strings include their quotes and cannot collide
13
+ * with the binary prefix. */ export let enc = (v)=>v == null ? null : v instanceof Uint8Array ? `binary:${toBase64(v)}` : JSON.stringify(v);
14
+ /** A stored value read back. Text that is not JSON comes back as itself, so a
15
+ * hand-written row never throws. */ export let dec = (v)=>{
16
+ if (v == null) return null;
17
+ try {
18
+ if (typeof v == 'string' && v.startsWith('binary:')) {
19
+ return fromBase64(v.slice(7));
20
+ }
21
+ return JSON.parse(String(v));
22
+ } catch {
23
+ return v;
24
+ }
25
+ };
26
+ //# sourceMappingURL=value.js.map
package/value.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"value.js","sources":["./value.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,4EAA4E;AAC5E,8HAA8H;AAC9H,+EAA+E;AAC/E,aAAa;AACb,EAAE;AACF,+EAA+E;AAC/E,6EAA6E;AAC7E,4EAA4E;AAE5E,SAAS,UAAU,EAAE,QAAQ,wBAA6B;AAE1D;;2BAE2B,GAC3B,OAAO,IAAI,MAAM,CAAC,IAChB,KAAK,OACD,OACA,aAAa,aACb,CAAC,OAAO,EAAE,SAAS,IAAI,GACvB,KAAK,SAAS,CAAC,GAAE;AAEvB;kCACkC,GAClC,OAAO,IAAI,MAAM,CAAC;EAChB,IAAI,KAAK,MAAM,OAAO;EACtB,IAAI;IACF,IAAI,OAAO,KAAK,YAAY,EAAE,UAAU,CAAC,YAAY;MACnD,OAAO,WAAW,EAAE,KAAK,CAAC;IAC5B;IACA,OAAO,KAAK,KAAK,CAAC,OAAO;EAC3B,EAAE,OAAM;IACN,OAAO;EACT;AACF,EAAC"}
package/value.ts ADDED
@@ -0,0 +1,35 @@
1
+ // How a property's value is written down. The journal has to hold values of
2
+ // every property type in two columns of its own, so each side of a delta is
3
+ // stored as JSON, with bytes marked by a non-JSON `binary:` prefix: `12` and `"12"` come back as a number and a string rather
4
+ // than as the same string twice, and a boolean survives an adapter that stores
5
+ // it as 0/1.
6
+ //
7
+ // Absence has one representation. A property with no value, a property a patch
8
+ // cleared, and a component that was not there are all `null` here — the same
9
+ // rule a client's JSON follows, where a `null` property is the cleared one.
10
+
11
+ import { fromBase64, toBase64 } from '@yaks/fp'
12
+
13
+ /** A value as the journal stores it: JSON, marked base64 bytes, or `null`
14
+ * for no value at all. JSON strings include their quotes and cannot collide
15
+ * with the binary prefix. */
16
+ export let enc = (v: unknown): string | null =>
17
+ v == null
18
+ ? null
19
+ : v instanceof Uint8Array
20
+ ? `binary:${toBase64(v)}`
21
+ : JSON.stringify(v)
22
+
23
+ /** A stored value read back. Text that is not JSON comes back as itself, so a
24
+ * hand-written row never throws. */
25
+ export let dec = (v: unknown): unknown => {
26
+ if (v == null) return null
27
+ try {
28
+ if (typeof v == 'string' && v.startsWith('binary:')) {
29
+ return fromBase64(v.slice(7))
30
+ }
31
+ return JSON.parse(String(v))
32
+ } catch {
33
+ return v
34
+ }
35
+ }
package/views.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * What this package draws. Anywhere: a row of an entity's history (the
3
+ * `history` tool, ./tools.ts) as one line, when · who · what it wrote —
4
+ * `2 minutes ago · yak task new Buy the cake · task; doc: Buy the cake`. In the
5
+ * browsing app: the History page, which the sidebar offers over the days'
6
+ * measurements, loaded when first drawn (./page.ts).
7
+ *
8
+ * @module
9
+ */ import { parse } from "@yaks/query/core";
10
+ import { define } from "@yaks/render";
11
+ // @ts-types="@yaks/ui/lucide"
12
+ import History from "lucide/dist/esm/icons/rotate-ccw-clock.mjs";
13
+ let EID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
14
+ let AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;
15
+ let LONG = 60;
16
+ // A value a line has room for: a word, a number, a short text. Who and when
17
+ // lead the line already, so the entities and moments a write stamps are left
18
+ // to its page; a long text is its opening words.
19
+ let brief = (v)=>{
20
+ if (typeof v == 'number' || typeof v == 'boolean') return String(v);
21
+ if (typeof v != 'string' || !v.trim() || EID.test(v) || AT.test(v)) return;
22
+ let flat = v.replace(/\s+/g, ' ').trim();
23
+ return flat.length > LONG ? `${flat.slice(0, LONG - 1)}…` : flat;
24
+ };
25
+ // What a row wrote, a component apiece: its name, then what it set that a
26
+ // line has room for — `doc: Buy the cake`, `removed claim`, `deleted`.
27
+ let wrote = (b)=>b.$delete ? 'deleted' : Object.entries(b).filter(([c])=>c != 'entity' && c != '_tx' && !c.startsWith('$')).map(([c, v])=>{
28
+ if (v == null) return `removed ${c}`;
29
+ let said = Object.values(v).flatMap((p)=>brief(p) ?? []);
30
+ return said.length ? `${c}: ${said.join(', ')}` : c;
31
+ }).join('; ');
32
+ // One row of a history: when, who, and what it wrote.
33
+ let change = (b, h, s)=>{
34
+ let tx = b._tx;
35
+ let parts = [
36
+ tx.at && h('time', {
37
+ datetime: tx.at
38
+ }, s.when(tx.at)),
39
+ tx.by && s.show(s.get?.(tx.by) ?? {
40
+ entity: {
41
+ eid: tx.by
42
+ }
43
+ }, 'Reference.Inline'),
44
+ wrote(b)
45
+ ].filter((p)=>!!p);
46
+ return h('span', {
47
+ class: 'Change'
48
+ }, ...parts.flatMap((p, i)=>i ? [
49
+ ' · ',
50
+ p
51
+ ] : [
52
+ p
53
+ ]));
54
+ };
55
+ let line = {
56
+ match: parse('._tx'),
57
+ needs: (b)=>[
58
+ b._tx.by
59
+ ].filter((e)=>!!e),
60
+ render: (b, h, ctx)=>change(b, h, ctx)
61
+ };
62
+ /** A history row as one line, in a list or alone. */ export let views = define([
63
+ {
64
+ view: 'Tile',
65
+ ...line
66
+ },
67
+ {
68
+ view: 'Page',
69
+ ...line
70
+ }
71
+ ]);
72
+ /** The page, loaded when first drawn. */ export let inspectViews = ()=>import("./page.js").then((m)=>m.inspectViews);
73
+ /** The page the sidebar offers: what history keeps, over the days. */ export let destinations = [
74
+ {
75
+ key: 'history',
76
+ name: 'History',
77
+ icon: 'history',
78
+ query: '.kept * .order=-kept.day',
79
+ view: 'History.Page'
80
+ }
81
+ ];
82
+ /** The glyph it wears there. */ export let icons = {
83
+ history: History
84
+ };
85
+ //# sourceMappingURL=views.js.map
package/views.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"views.js","sources":["./views.ts"],"names":[],"mappings":"AAAA;;;;;;;;CAQC,GAED,SAAS,KAAK,gCAAqC;AACnD,SAAsB,MAAM,4BAAwD;AAEpF,8BAA8B;AAC9B,OAAO,0DAAoE;AAI3E,IAAI,MAAM;AACV,IAAI,KAAK;AACT,IAAI,OAAO;AAEX,4EAA4E;AAC5E,6EAA6E;AAC7E,iDAAiD;AACjD,IAAI,QAAQ,CAAC;EACX,IAAI,OAAO,KAAK,YAAY,OAAO,KAAK,WAAW,OAAO,OAAO;EACjE,IAAI,OAAO,KAAK,YAAY,CAAC,EAAE,IAAI,MAAM,IAAI,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,IAAI;EACpE,IAAI,OAAO,EAAE,OAAO,CAAC,QAAQ,KAAK,IAAI;EACtC,OAAO,KAAK,MAAM,GAAG,OAAO,GAAG,KAAK,KAAK,CAAC,GAAG,OAAO,GAAG,CAAC,CAAC,GAAG;AAC9D;AAEA,0EAA0E;AAC1E,uEAAuE;AACvE,IAAI,QAAQ,CAAC,IACX,EAAE,OAAO,GAAG,YAAY,OAAO,OAAO,CAAC,GACpC,MAAM,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