@yaks/sqlite 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 (289) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1596 -2
  3. package/_dist/archetype.d.ts +75 -0
  4. package/_dist/archetype.d.ts.map +1 -0
  5. package/_dist/branches.d.ts +23 -0
  6. package/_dist/branches.d.ts.map +1 -0
  7. package/_dist/budget.d.ts +52 -0
  8. package/_dist/budget.d.ts.map +1 -0
  9. package/_dist/bundle.d.ts +2 -0
  10. package/_dist/bundle.d.ts.map +1 -0
  11. package/_dist/cache.d.ts +24 -0
  12. package/_dist/cache.d.ts.map +1 -0
  13. package/_dist/catalog.d.ts +9 -0
  14. package/_dist/catalog.d.ts.map +1 -0
  15. package/_dist/check.d.ts +4 -0
  16. package/_dist/check.d.ts.map +1 -0
  17. package/_dist/db.d.ts +36 -0
  18. package/_dist/db.d.ts.map +1 -0
  19. package/_dist/ddl.d.ts +143 -0
  20. package/_dist/ddl.d.ts.map +1 -0
  21. package/_dist/doom.d.ts +22 -0
  22. package/_dist/doom.d.ts.map +1 -0
  23. package/_dist/follow.d.ts +74 -0
  24. package/_dist/follow.d.ts.map +1 -0
  25. package/_dist/history-shapes.d.ts +3 -0
  26. package/_dist/history-shapes.d.ts.map +1 -0
  27. package/_dist/history.d.ts +18 -0
  28. package/_dist/history.d.ts.map +1 -0
  29. package/_dist/inspect.d.ts +43 -0
  30. package/_dist/inspect.d.ts.map +1 -0
  31. package/_dist/jsonb.d.ts +17 -0
  32. package/_dist/jsonb.d.ts.map +1 -0
  33. package/_dist/layout.d.ts +7 -0
  34. package/_dist/layout.d.ts.map +1 -0
  35. package/_dist/ledger.d.ts +41 -0
  36. package/_dist/ledger.d.ts.map +1 -0
  37. package/_dist/meta.d.ts +89 -0
  38. package/_dist/meta.d.ts.map +1 -0
  39. package/_dist/migration.d.ts +41 -0
  40. package/_dist/migration.d.ts.map +1 -0
  41. package/_dist/mod.d.ts +201 -0
  42. package/_dist/mod.d.ts.map +1 -0
  43. package/_dist/mode.d.ts +14 -0
  44. package/_dist/mode.d.ts.map +1 -0
  45. package/_dist/overlay.d.ts +30 -0
  46. package/_dist/overlay.d.ts.map +1 -0
  47. package/_dist/owe.d.ts +180 -0
  48. package/_dist/owe.d.ts.map +1 -0
  49. package/_dist/physical.d.ts +89 -0
  50. package/_dist/physical.d.ts.map +1 -0
  51. package/_dist/point.d.ts +10 -0
  52. package/_dist/point.d.ts.map +1 -0
  53. package/_dist/raise.d.ts +22 -0
  54. package/_dist/raise.d.ts.map +1 -0
  55. package/_dist/read-db.d.ts +9 -0
  56. package/_dist/read-db.d.ts.map +1 -0
  57. package/_dist/read-store.d.ts +10 -0
  58. package/_dist/read-store.d.ts.map +1 -0
  59. package/_dist/read.d.ts +59 -0
  60. package/_dist/read.d.ts.map +1 -0
  61. package/_dist/reader.d.ts +11 -0
  62. package/_dist/reader.d.ts.map +1 -0
  63. package/_dist/rules.d.ts +19 -0
  64. package/_dist/rules.d.ts.map +1 -0
  65. package/_dist/service.d.ts +12 -0
  66. package/_dist/service.d.ts.map +1 -0
  67. package/_dist/shape.d.ts +12 -0
  68. package/_dist/shape.d.ts.map +1 -0
  69. package/_dist/statements.d.ts +4 -0
  70. package/_dist/statements.d.ts.map +1 -0
  71. package/_dist/survey.d.ts +31 -0
  72. package/_dist/survey.d.ts.map +1 -0
  73. package/_dist/tools.d.ts +15 -0
  74. package/_dist/tools.d.ts.map +1 -0
  75. package/_dist/trash.d.ts +18 -0
  76. package/_dist/trash.d.ts.map +1 -0
  77. package/_dist/unit.d.ts +11 -0
  78. package/_dist/unit.d.ts.map +1 -0
  79. package/_dist/vocab.d.ts +6 -0
  80. package/_dist/vocab.d.ts.map +1 -0
  81. package/_dist/write.d.ts +169 -0
  82. package/_dist/write.d.ts.map +1 -0
  83. package/answer.js +110 -0
  84. package/answer.js.map +1 -0
  85. package/answer.ts +122 -0
  86. package/archetype.js +730 -0
  87. package/archetype.js.map +1 -0
  88. package/archetype.ts +790 -0
  89. package/binary_cases.ts +240 -0
  90. package/branches.js +195 -0
  91. package/branches.js.map +1 -0
  92. package/branches.ts +257 -0
  93. package/budget.js +89 -0
  94. package/budget.js.map +1 -0
  95. package/budget.ts +117 -0
  96. package/builtin.js +34 -0
  97. package/builtin.js.map +1 -0
  98. package/builtin.ts +31 -0
  99. package/bundle.js +21 -0
  100. package/bundle.js.map +1 -0
  101. package/bundle.ts +22 -0
  102. package/buried.js +95 -0
  103. package/buried.js.map +1 -0
  104. package/buried.ts +124 -0
  105. package/cache.js +153 -0
  106. package/cache.js.map +1 -0
  107. package/cache.ts +154 -0
  108. package/cache_worker.ts +16 -0
  109. package/catalog.js +173 -0
  110. package/catalog.js.map +1 -0
  111. package/catalog.ts +224 -0
  112. package/check.js +80 -0
  113. package/check.js.map +1 -0
  114. package/check.ts +92 -0
  115. package/checkpoint.js +98 -0
  116. package/checkpoint.js.map +1 -0
  117. package/checkpoint.ts +129 -0
  118. package/checkpoint_worker.ts +37 -0
  119. package/db.js +170 -0
  120. package/db.js.map +1 -0
  121. package/db.ts +173 -0
  122. package/ddl.js +1441 -0
  123. package/ddl.js.map +1 -0
  124. package/ddl.ts +1508 -0
  125. package/deno.json +1 -0
  126. package/doom.js +59 -0
  127. package/doom.js.map +1 -0
  128. package/doom.ts +75 -0
  129. package/driver.js +69 -0
  130. package/driver.js.map +1 -0
  131. package/driver.ts +101 -0
  132. package/error.js +30 -0
  133. package/error.js.map +1 -0
  134. package/error.ts +46 -0
  135. package/ffi/LICENSE +202 -0
  136. package/ffi/blob.js +99 -0
  137. package/ffi/blob.js.map +1 -0
  138. package/ffi/blob.ts +156 -0
  139. package/ffi/constants.js +65 -0
  140. package/ffi/constants.js.map +1 -0
  141. package/ffi/constants.ts +67 -0
  142. package/ffi/database.js +613 -0
  143. package/ffi/database.js.map +1 -0
  144. package/ffi/database.ts +931 -0
  145. package/ffi/ffi.js +535 -0
  146. package/ffi/ffi.js.map +1 -0
  147. package/ffi/ffi.ts +604 -0
  148. package/ffi/mod.js +15 -0
  149. package/ffi/mod.js.map +1 -0
  150. package/ffi/mod.ts +28 -0
  151. package/ffi/statement.js +555 -0
  152. package/ffi/statement.js.map +1 -0
  153. package/ffi/statement.ts +788 -0
  154. package/ffi/util.js +32 -0
  155. package/ffi/util.js.map +1 -0
  156. package/ffi/util.ts +48 -0
  157. package/follow.js +342 -0
  158. package/follow.js.map +1 -0
  159. package/follow.ts +401 -0
  160. package/history-branch.js +166 -0
  161. package/history-branch.js.map +1 -0
  162. package/history-branch.ts +140 -0
  163. package/history-shapes.js +254 -0
  164. package/history-shapes.js.map +1 -0
  165. package/history-shapes.ts +268 -0
  166. package/history.js +620 -0
  167. package/history.js.map +1 -0
  168. package/history.ts +674 -0
  169. package/inspect.js +120 -0
  170. package/inspect.js.map +1 -0
  171. package/inspect.ts +164 -0
  172. package/jsonb.js +73 -0
  173. package/jsonb.js.map +1 -0
  174. package/jsonb.ts +108 -0
  175. package/layout.js +22 -0
  176. package/layout.js.map +1 -0
  177. package/layout.ts +26 -0
  178. package/ledger.js +210 -0
  179. package/ledger.js.map +1 -0
  180. package/ledger.ts +210 -0
  181. package/legacy.js +4 -0
  182. package/legacy.js.map +1 -0
  183. package/legacy.ts +3 -0
  184. package/maintenance.js +148 -0
  185. package/maintenance.js.map +1 -0
  186. package/maintenance.ts +154 -0
  187. package/measure.js +133 -0
  188. package/measure.js.map +1 -0
  189. package/measure.ts +167 -0
  190. package/measure_worker.ts +18 -0
  191. package/memo.js +1250 -0
  192. package/memo.js.map +1 -0
  193. package/memo.ts +1480 -0
  194. package/meta.js +265 -0
  195. package/meta.js.map +1 -0
  196. package/meta.ts +321 -0
  197. package/migration.js +272 -0
  198. package/migration.js.map +1 -0
  199. package/migration.ts +286 -0
  200. package/mod.js +1103 -0
  201. package/mod.js.map +1 -0
  202. package/mod.ts +1762 -0
  203. package/mode.js +192 -0
  204. package/mode.js.map +1 -0
  205. package/mode.ts +207 -0
  206. package/native.js +544 -0
  207. package/native.js.map +1 -0
  208. package/native.ts +544 -0
  209. package/overlay.js +408 -0
  210. package/overlay.js.map +1 -0
  211. package/overlay.ts +485 -0
  212. package/owe.js +719 -0
  213. package/owe.js.map +1 -0
  214. package/owe.ts +873 -0
  215. package/package.json +99 -4
  216. package/physical.js +350 -0
  217. package/physical.js.map +1 -0
  218. package/physical.ts +434 -0
  219. package/plan.js +78 -0
  220. package/plan.js.map +1 -0
  221. package/plan.ts +104 -0
  222. package/point.js +81 -0
  223. package/point.js.map +1 -0
  224. package/point.ts +52 -0
  225. package/population.js +639 -0
  226. package/population.js.map +1 -0
  227. package/population.ts +630 -0
  228. package/purge.js +117 -0
  229. package/purge.js.map +1 -0
  230. package/purge.ts +127 -0
  231. package/raise.js +270 -0
  232. package/raise.js.map +1 -0
  233. package/raise.ts +316 -0
  234. package/read-db.js +381 -0
  235. package/read-db.js.map +1 -0
  236. package/read-db.ts +282 -0
  237. package/read-store.js +74 -0
  238. package/read-store.js.map +1 -0
  239. package/read-store.ts +86 -0
  240. package/read.js +1100 -0
  241. package/read.js.map +1 -0
  242. package/read.ts +1441 -0
  243. package/reader.js +141 -0
  244. package/reader.js.map +1 -0
  245. package/reader.ts +159 -0
  246. package/rules.js +88 -0
  247. package/rules.js.map +1 -0
  248. package/rules.ts +113 -0
  249. package/service.js +27 -0
  250. package/service.js.map +1 -0
  251. package/service.ts +41 -0
  252. package/shape.js +76 -0
  253. package/shape.js.map +1 -0
  254. package/shape.ts +108 -0
  255. package/sparse_presence_fixture.ts +45 -0
  256. package/sqlitepath.js +24 -0
  257. package/sqlitepath.js.map +1 -0
  258. package/sqlitepath.ts +29 -0
  259. package/statements.js +78 -0
  260. package/statements.js.map +1 -0
  261. package/statements.ts +96 -0
  262. package/survey.js +135 -0
  263. package/survey.js.map +1 -0
  264. package/survey.ts +196 -0
  265. package/tools.js +17 -0
  266. package/tools.js.map +1 -0
  267. package/tools.ts +50 -0
  268. package/trash.js +144 -0
  269. package/trash.js.map +1 -0
  270. package/trash.ts +187 -0
  271. package/unit.js +215 -0
  272. package/unit.js.map +1 -0
  273. package/unit.ts +211 -0
  274. package/versions.js +115 -0
  275. package/versions.js.map +1 -0
  276. package/versions.ts +110 -0
  277. package/vocab.js +19 -0
  278. package/vocab.js.map +1 -0
  279. package/vocab.json +27 -0
  280. package/vocab.ts +19 -0
  281. package/watch.js +33 -0
  282. package/watch.js.map +1 -0
  283. package/watch.ts +42 -0
  284. package/write.js +1164 -0
  285. package/write.js.map +1 -0
  286. package/write.ts +1356 -0
  287. package/written.js +200 -0
  288. package/written.js.map +1 -0
  289. package/written.ts +202 -0
package/memo.js ADDED
@@ -0,0 +1,1250 @@
1
+ // Whole entities a store has read, kept in memory while nothing has written
2
+ // them: the hero a page relays ten times a second is read once, not once per
3
+ // relay. An entity is let go when a write through this package names it
4
+ // (`writes`); every entity is let go when a statement writes a component table
5
+ // any other way and when the schema moves. When another connection commits
6
+ // (@yaks/sql `revision`'s `outside`), a file's log of which entity each write
7
+ // named (./written.ts) says which to let go; where it can't say, every one.
8
+ //
9
+ // A transaction can roll back what it wrote, so its known writes stay in its
10
+ // pending image until commit. A getter for stored components can read that
11
+ // image while classification is still owed; a whole or dynamic read uses SQL.
12
+ // A write this package cannot attribute leaves the image unknown until the
13
+ // transaction ends. The transactions
14
+ // are the ones this connection says: `begin` and savepoints through `query`,
15
+ // and the driver's own `tx`.
16
+ //
17
+ // Spines (./write.ts `spines`: an eid's integer id, number and grave) are kept
18
+ // for the connection too, so the patches one transaction makes read each
19
+ // entity's spine once. A statement that may move one lets every spine go,
20
+ // except a plain mint, which this package tells (`spined().learn`), and a
21
+ // write that names its entities (`writes`), which lets just theirs go; those
22
+ // kept during a transaction go if it rolls back.
23
+ //
24
+ // So are the classes births finish in (`classed`): the archetype an entity
25
+ // first written holding some tables was pointed at by the end of its
26
+ // transaction, so the next birth of that shape is minted in it (./write.ts
27
+ // `Births`). A class learned while a transaction is open goes if it rolls
28
+ // back, since the descriptor it names may go with it.
29
+ //
30
+ // A query's rows are kept too, once it is asked again, while no table its
31
+ // answer stands on has been written (`answer`, `basis`): a page walking back
32
+ // over tiles it has watched asks them again for nothing while nobody has
33
+ // written a place. Every write
34
+ // statement moves its table's count, so nothing a write says has to be
35
+ // trusted; what memory can't follow (text, nearness, edges, computed and
36
+ // derived properties, time phrases) is read every time. An answer about each
37
+ // entity alone stands through a patch or a removal whose entities it selects
38
+ // neither before nor after (`local`, `stand`).
39
+ // Whole and named gets with SQL-state-only derivations use that same bounded
40
+ // answer pool through one global data revision; every mutation ends reuse.
41
+ //
42
+ // What a patch leaves an entity holding is worked out from what memory held
43
+ // and what the patch said, the way a read returns it (`patch`), and kept once
44
+ // the transaction commits: an entity written is not read back to be known. A
45
+ // value a read could return differently (a number into a text column, a
46
+ // derived property, a default the clock fills) leaves the entity to be read,
47
+ // though which components it holds is still known. What memory says an entity
48
+ // holds is the patch's to choose its statements by (./write.ts `patch`'s
49
+ // `had`).
50
+ //
51
+ // Every driver naming one connection (@yaks/sql `Driver.connection`) tells one
52
+ // memory what it ran, so a write through any of them is seen by all.
53
+ //
54
+ // A get naming components is cut from a whole entity held, or from one held
55
+ // in part: what earlier gets naming at least those read, together. Returned
56
+ // bundles are copies, made without a look at each value where what memory
57
+ // holds is JSON; dynamic components (computed, or derived from anything but this
58
+ // connection's rows) are read again on every hit, of the entities holding
59
+ // them. Bounded by bytes (`memoized`'s `memory`) and by an entity for every
60
+ // 2 KiB of them, the longest unread let go first; a scan is read through, not
61
+ // kept.
62
+ import { comps, dead } from "@yaks/graph/bundle";
63
+ import { and, bare, drifts } from "@yaks/query";
64
+ import { col, revision } from "@yaks/sql/core";
65
+ import { derivedOf, storedOnly, tablesOf } from "@yaks/sql/query";
66
+ import { filter } from "@yaks/match";
67
+ import { tables } from "./layout.js";
68
+ import { BESIDE } from "./history.js";
69
+ import { copied, packed } from "./answer.js";
70
+ import { follows, newest, since } from "./written.js";
71
+ import { surveyed } from "./survey.js";
72
+ /** What a store's memory of whole entities keeps, in bytes, unless its opener
73
+ * says otherwise (./mod.ts `Opts.memory`): what a Durable Object can spare. */ export const MEMORY = 4 << 20;
74
+ const SPINES = 8192, CLASSES = 256;
75
+ // Answers are bounded by count, and one too large to keep is read every time.
76
+ const ANSWERS = 256, ANSWER = 16 << 10;
77
+ // How many queries asked once are remembered, waiting to be asked again.
78
+ const ASKED = 4 * ANSWERS;
79
+ // A cache proof only classifies vocabulary paths. Associations and extension
80
+ // paths belong to the compiler; an unroutable one declines the proof.
81
+ let routed = (vocab, path, facet = false)=>{
82
+ try {
83
+ return vocab.aim(path.join('.'), facet);
84
+ } catch {
85
+ return undefined;
86
+ }
87
+ };
88
+ /**
89
+ * The tables a query's answer stands on, or `undefined` for one memory can't
90
+ * follow: text, nearness, backlinks, edges, walks and rule clauses; a path
91
+ * nothing declares; a computed or derived property; a time phrase, whose
92
+ * answer moves with the clock. Every answer stands on the graves and, where
93
+ * it is `catalogued`, on the archetype catalog. One that requires no component
94
+ * row (`!product`, `.doc|!doc`) may take in any new entity, so it stands on
95
+ * every entity. A number or an eid moving lets every answer go (`moves`).
96
+ */ export let basis = (vocab, q, derived = {}, catalogued = false, within = false)=>{
97
+ let out = new Set([
98
+ 'tombstone'
99
+ ]);
100
+ let path = (segs, facet = false)=>{
101
+ // A backlink is no path aim() answers: say so without the refusal.
102
+ if (!vocab.comp(segs[0]) && vocab.assoc(segs[0])) return false;
103
+ let hops = routed(vocab, segs, facet);
104
+ if (!hops) return false;
105
+ for (let { comp, prop } of hops){
106
+ out.add(comp);
107
+ if (comp == 'entity') continue;
108
+ if (!vocab.comp(comp) || vocab.comp(comp).computed) return false;
109
+ if (prop && (vocab.prop(comp, prop)?.computed || derived[`${comp}.${prop}`])) return false;
110
+ }
111
+ return true;
112
+ };
113
+ let visit = (c)=>{
114
+ switch(c.kind){
115
+ case 'and':
116
+ case 'or':
117
+ return c.clauses.every(visit);
118
+ case 'pred':
119
+ if (catalogued && bare(c)) out.add('archetype');
120
+ return !c.where && path(c.path, bare(c));
121
+ case 'fields':
122
+ return c.fields.every((f)=>path(f.path));
123
+ case 'distinct':
124
+ case 'tally':
125
+ return path(c.path);
126
+ case 'order':
127
+ return path(c.value.replace(/^-/, '').split('.'));
128
+ case 'count':
129
+ case 'limit':
130
+ case 'after':
131
+ case 'every':
132
+ case 'never':
133
+ return true;
134
+ default:
135
+ return false;
136
+ }
137
+ };
138
+ let scalar = (p)=>{
139
+ let leaf = vocab.aim(p.path.join('.'), bare(p)).at(-1);
140
+ return leaf && vocab.prop(leaf.comp, leaf.prop)?.scalar;
141
+ };
142
+ // Whether a clause holds only for an entity with a row of some component:
143
+ // one it must hold (`.doc`, parsed as `!` with no value) or a value it must
144
+ // have, under every arm of an `or`. An absence (`!doc`, `= ''`) is not one.
145
+ let anchored = (c)=>c.kind == 'and' ? c.clauses.some(anchored) : c.kind == 'or' ? c.clauses.length > 0 && c.clauses.every(anchored) : c.kind == 'pred' && !c.not && c.path[0] != 'entity' && (c.op == '!' ? !c.value : [
146
+ '=',
147
+ '~=',
148
+ '<',
149
+ '<=',
150
+ '>',
151
+ '>='
152
+ ].includes(c.op) && !(c.value?.kind == 'scalar' && c.value.raw == ''));
153
+ if (!visit(q) || drifts(q, scalar)) return undefined;
154
+ if (!within && !anchored(q)) out.add('entity');
155
+ return [
156
+ ...out
157
+ ];
158
+ };
159
+ // A local identity selection reads no referenced target and has no window.
160
+ export let simple = (vocab, query)=>{
161
+ let visit = (c)=>{
162
+ if (c.kind == 'and' || c.kind == 'or') return c.clauses.every(visit);
163
+ if (c.kind == 'every') return true;
164
+ if (c.kind != 'pred' || c.where) return false;
165
+ let hops = routed(vocab, c.path, bare(c)), h = hops?.[0];
166
+ return hops?.length == 1 && !!h && (!h.prop || vocab.prop(h.comp, h.prop)?.category != 'ref');
167
+ };
168
+ return visit(query);
169
+ };
170
+ /**
171
+ * Whether what a query selects is told by each entity alone: every path ends
172
+ * on the entity's own components, through no reference, and no `.after`
173
+ * cursor, whose anchor ranks by values a write may move. A write that leaves
174
+ * every entity it moved unselected before and after then moves nothing in its
175
+ * answer. The query is one `basis` follows.
176
+ */ export let local = (vocab, q)=>{
177
+ let own = (segs, facet = false)=>{
178
+ let hops = routed(vocab, segs, facet);
179
+ return !!hops && hops.length <= 1;
180
+ };
181
+ let visit = (c)=>{
182
+ switch(c.kind){
183
+ case 'and':
184
+ case 'or':
185
+ return c.clauses.every(visit);
186
+ case 'pred':
187
+ return own(c.path, bare(c));
188
+ case 'fields':
189
+ return c.fields.every((f)=>own(f.path));
190
+ case 'order':
191
+ return own(c.value.replace(/^-/, '').split('.'));
192
+ case 'count':
193
+ case 'limit':
194
+ return true;
195
+ default:
196
+ return false;
197
+ }
198
+ };
199
+ return visit(q);
200
+ };
201
+ // A necessary owner test can rule a write out even when the exact predicate
202
+ // follows references. Every referent table remains a strict dependency: a
203
+ // write there can change a selected owner's answer without touching it.
204
+ export let rooted = (vocab, query)=>{
205
+ let strict = new Set();
206
+ let path = (segs, facet = false)=>{
207
+ let hops = vocab.aim(segs.join('.'), facet);
208
+ for (let h of hops.slice(1))strict.add(h.comp);
209
+ return hops.length <= 1;
210
+ };
211
+ // A predicate the proof cannot test stands as true, the empty conjunction,
212
+ // wherever it sits. `every` is a projection, which @yaks/match drops at the
213
+ // top and refuses inside a disjunction.
214
+ let visit = (c, shapes = false)=>{
215
+ if (c.kind == 'and' || c.kind == 'or') {
216
+ return {
217
+ ...c,
218
+ clauses: c.clauses.map((c)=>visit(c, shapes))
219
+ };
220
+ }
221
+ if (c.kind == 'pred') {
222
+ return path(c.path, bare(c)) && (!shapes || !vocab.aim(c.path.join('.'), bare(c))[0].prop) ? c : and();
223
+ }
224
+ if (c.kind == 'fields') {
225
+ c.fields.forEach((f)=>path(f.path));
226
+ return {
227
+ kind: 'every'
228
+ };
229
+ }
230
+ if (c.kind == 'order') {
231
+ path(c.value.replace(/^-/, '').split('.'));
232
+ return {
233
+ kind: 'every'
234
+ };
235
+ }
236
+ if ([
237
+ 'every',
238
+ 'count',
239
+ 'limit'
240
+ ].includes(c.kind)) return c;
241
+ throw new Error('not an owner-local proof');
242
+ };
243
+ try {
244
+ return {
245
+ test: filter({
246
+ ...query,
247
+ clauses: query.clauses.map((c)=>visit(c))
248
+ }, vocab),
249
+ shape: filter({
250
+ ...query,
251
+ clauses: query.clauses.map((c)=>visit(c, true))
252
+ }, vocab),
253
+ strict: [
254
+ ...strict
255
+ ]
256
+ };
257
+ } catch {
258
+ return undefined;
259
+ }
260
+ };
261
+ // The blob table a content-addressed property's text is read from.
262
+ const BLOBS = 'blob_text';
263
+ // An entity a transaction wrote whose state memory can't work out.
264
+ const LOST = Symbol('lost');
265
+ // A component a patch gave an entity whose values memory can't work out: the
266
+ // entity holds one, which is what a patch's statements are chosen by, but
267
+ // nothing a read asks is answered from it.
268
+ const HOLE = '\0hole';
269
+ let holed = (b)=>comps(b).some(([, c])=>c != null && HOLE in c);
270
+ // By connection (@yaks/sql `Driver.connection`): every driver speaking
271
+ // through one tells the same memory what it ran.
272
+ let connections = new WeakMap();
273
+ let told = new WeakSet();
274
+ let connect = (driver)=>{
275
+ let at = driver.connection ?? driver;
276
+ let c = connections.get(at) ?? opened();
277
+ connections.set(at, c);
278
+ if (!told.has(driver)) {
279
+ told.add(driver);
280
+ tell(driver, c);
281
+ }
282
+ return c;
283
+ };
284
+ /** Let go of everything the connection `driver` is holds: what it reads now
285
+ * reads otherwise, as a mode's driver bound to another mode does (./mode.ts). */ export let turned = (driver)=>connections.get(driver.connection ?? driver)?.moved?.();
286
+ let opened = ()=>({
287
+ kept: new Set(),
288
+ depth: 0,
289
+ writing: 0,
290
+ dirty: new Set(),
291
+ blind: false,
292
+ spines: new Map(),
293
+ since: new Set(),
294
+ classes: new Map(),
295
+ learned: new Set(),
296
+ classedAt: -1,
297
+ versions: new Map(),
298
+ shifts: 0,
299
+ answered: [],
300
+ seen: -1,
301
+ schema: -1
302
+ });
303
+ // Have `driver` tell the connection `c` each statement and transaction it runs.
304
+ let tell = (driver, c)=>{
305
+ // What a rolled-back transaction had kept of spines and answers may be gone
306
+ // with it.
307
+ let undone = ()=>{
308
+ for (let eid of c.since)c.spines.delete(eid);
309
+ c.since.clear();
310
+ for (let shape of c.learned)c.classes.delete(shape);
311
+ c.learned.clear();
312
+ for (let [answers, key] of c.answered)answers.delete(key);
313
+ c.answered = [];
314
+ for (let k of c.kept){
315
+ for (let eid of k.after.keys())k.after.set(eid, LOST);
316
+ }
317
+ c.cursor = c.began;
318
+ };
319
+ let begin = ()=>{
320
+ if (!c.depth++) c.began = c.cursor;
321
+ };
322
+ let ended = (committed)=>{
323
+ if (!committed) undone();
324
+ for (let k of c.kept){
325
+ if (committed && !c.blind) k.commit();
326
+ k.after.clear();
327
+ k.afterPart.clear();
328
+ }
329
+ c.depth = 0;
330
+ c.dirty.clear();
331
+ c.blind = false;
332
+ c.since.clear();
333
+ c.learned.clear();
334
+ c.answered = [];
335
+ };
336
+ let bump = (table)=>c.versions.set(table, (c.versions.get(table) ?? 0) + 1);
337
+ let unspine = ()=>{
338
+ c.spines.clear();
339
+ c.since.clear();
340
+ };
341
+ // The blob table holds text by its address (@yaks/blob): a row added there
342
+ // is text no entity read before, since an address is written after its
343
+ // text, so only a write changing or removing one moves what memory holds.
344
+ let adds = (s)=>s.t == 'insert' && s.into == BLOBS;
345
+ // Whether a write may move an id, a number or a grave: anything but a plain
346
+ // mint into `entity` and a pointer to its archetype.
347
+ let moves = (s)=>s.t == 'insert' ? s.into == 'tombstone' || s.into == 'entity' && (!!s.or || !!s.upsert?.some((u)=>u.set)) : s.t == 'update' ? s.table == 'tombstone' || s.table == 'entity' && Object.keys(s.set).some((k)=>k != 'archetype') : s.t == 'delete' && (s.from == 'entity' || s.from == 'tombstone');
348
+ let forget = (table)=>{
349
+ let held = false;
350
+ for (let k of c.kept){
351
+ if (table && !k.tables.has(table)) continue;
352
+ k.clear();
353
+ held = true;
354
+ }
355
+ if (held && c.depth) c.blind = true;
356
+ };
357
+ let held = (w)=>w.t == 'insert' && w.into.endsWith(BESIDE) ? {
358
+ ...w,
359
+ into: w.into.slice(0, -BESIDE.length)
360
+ } : w.t == 'update' && w.table.endsWith(BESIDE) ? {
361
+ ...w,
362
+ table: w.table.slice(0, -BESIDE.length)
363
+ } : w.t == 'delete' && w.from.endsWith(BESIDE) ? {
364
+ ...w,
365
+ from: w.from.slice(0, -BESIDE.length)
366
+ } : w;
367
+ // Everything read may read otherwise now: the schema moved, or a mode's
368
+ // driver was bound to another mode (./mode.ts, `turned`).
369
+ let moved = c.moved = ()=>{
370
+ forget();
371
+ grew();
372
+ };
373
+ // A table or index made now holds no row: what memory holds of each entity
374
+ // stands, while what was answered or learned of the schema may not.
375
+ let grew = ()=>{
376
+ unspine();
377
+ c.classes.clear();
378
+ c.learned.clear();
379
+ for (let k of c.kept)k.answers.clear();
380
+ };
381
+ let observe = (s)=>{
382
+ if (s.t == 'raw') return s.origin && observe(s.origin);
383
+ if (s.t == 'begin' || s.t == 'savepoint') begin();
384
+ else if (s.t == 'commit') ended(true);
385
+ else if (s.t == 'rollback') s.to ? undone() : ended(false);
386
+ else if (s.t == 'release' && --c.depth <= 0) ended(true);
387
+ else if (s.t == 'insert' || s.t == 'update' || s.t == 'delete') {
388
+ // A write beside a component's table (./history.ts) is, to what memory
389
+ // holds, a write of it: on a branch it is the component's whole state.
390
+ s = held(s);
391
+ let table = s.t == 'insert' ? s.into : s.t == 'update' ? s.table : s.from;
392
+ bump(table);
393
+ if (moves(s)) {
394
+ c.shifts++;
395
+ // A write that says which entities it wrote (`writes`) lets go of
396
+ // just their spines.
397
+ if (!c.writing) unspine();
398
+ // A number, an eid or an id itself moved: what any answer ordered,
399
+ // paged or compared a reference by.
400
+ if (table == 'entity') {
401
+ for (let k of c.kept)k.answers.clear();
402
+ }
403
+ }
404
+ if (!c.writing && !adds(s)) forget(table);
405
+ } else if (s.t == 'create table' || s.t == 'create index') grew();
406
+ else if (s.t.startsWith('create ') || s.t == 'alter table' || s.t == 'drop') moved();
407
+ };
408
+ let query = driver.query.bind(driver);
409
+ driver.query = (s)=>{
410
+ let rows = query(s);
411
+ observe(s);
412
+ return rows;
413
+ };
414
+ if (driver.run) {
415
+ let run = driver.run.bind(driver);
416
+ driver.run = (s)=>{
417
+ let n = run(s);
418
+ observe(s);
419
+ return n;
420
+ };
421
+ }
422
+ // A driver's own transaction is synchronous: it has ended when `tx`
423
+ // returns, whatever its body left running.
424
+ if (driver.tx) {
425
+ let tx = driver.tx.bind(driver);
426
+ driver.tx = (body)=>{
427
+ begin();
428
+ let committed = false;
429
+ try {
430
+ let out = tx(body);
431
+ committed = true;
432
+ return out;
433
+ } finally{
434
+ // One nested in another rolls back to where it began.
435
+ if (--c.depth <= 0) ended(committed);
436
+ else if (!committed) undone();
437
+ }
438
+ };
439
+ }
440
+ };
441
+ // Bring what memory holds of the connection `c` past what other connections
442
+ // committed since it last looked: let go of the entities the file's log says
443
+ // they wrote (./written.ts), or of every one where it can't say, as when the
444
+ // schema moved, which nothing logs.
445
+ let follow = (driver, c)=>{
446
+ let now = revision(driver, 'outside');
447
+ if (now == c.seen) return;
448
+ let schema = revision(driver, 'schema');
449
+ // A store in memory keeps no log: its one connection sees every statement.
450
+ let logged = !!driver.file && [
451
+ ...c.kept
452
+ ].every((k)=>k.logged && k.follows(schema));
453
+ let written = logged && schema == c.schema && c.cursor != null ? since(driver, c.cursor) : undefined;
454
+ for (let k of c.kept)k.drop(written?.eids);
455
+ if (written) {
456
+ for (let eid of written.eids)c.spines.delete(eid);
457
+ } else {
458
+ c.spines.clear();
459
+ c.since.clear();
460
+ }
461
+ c.cursor = written ? written.at : logged ? newest(driver) : undefined;
462
+ c.seen = now;
463
+ c.schema = schema;
464
+ };
465
+ /** The spines kept for the connection `driver` is. */ export let spined = (driver)=>{
466
+ let c = connect(driver);
467
+ let keep = (eid, spine)=>{
468
+ c.spines.delete(eid);
469
+ c.spines.set(eid, spine);
470
+ if (c.depth) c.since.add(eid);
471
+ if (c.spines.size > SPINES) c.spines.delete(c.spines.keys().next().value);
472
+ };
473
+ return {
474
+ get: (eids, read)=>{
475
+ follow(driver, c);
476
+ let out = new Map();
477
+ let missing = eids.filter((eid)=>{
478
+ let held = c.spines.get(eid);
479
+ if (held) out.set(eid, {
480
+ ...held
481
+ });
482
+ return !held;
483
+ });
484
+ if (missing.length) {
485
+ for (let [eid, spine] of read(missing)){
486
+ out.set(eid, spine);
487
+ keep(eid, {
488
+ ...spine
489
+ });
490
+ }
491
+ }
492
+ return out;
493
+ },
494
+ learn: (eid, spine)=>keep(eid, {
495
+ ...spine
496
+ })
497
+ };
498
+ };
499
+ /** The classes kept for the connection `driver` is. */ export let classed = (driver)=>{
500
+ let c = connect(driver);
501
+ // Another connection's commit or a schema change may have moved the file
502
+ // under what was learned.
503
+ let current = ()=>{
504
+ let now = revision(driver, 'outside');
505
+ if (now == c.classedAt) return;
506
+ c.classes.clear();
507
+ c.learned.clear();
508
+ c.classedAt = now;
509
+ };
510
+ return {
511
+ get: (shape)=>{
512
+ current();
513
+ return c.classes.get(shape);
514
+ },
515
+ learn: (shape, id)=>{
516
+ current();
517
+ c.classes.delete(shape);
518
+ c.classes.set(shape, id);
519
+ if (c.depth) c.learned.add(shape);
520
+ if (c.classes.size > CLASSES) {
521
+ c.classes.delete(c.classes.keys().next().value);
522
+ }
523
+ }
524
+ };
525
+ };
526
+ // What a bundle takes in memory, about as many bytes as its JSON spelled out
527
+ // in UTF-16, worked out without spelling it: a bundle may hold a transcript.
528
+ let sizeOf = (b)=>chars(b) * 2;
529
+ let chars = (value)=>{
530
+ if (typeof value == 'string') return value.length + 2;
531
+ if (value == null || typeof value != 'object') return String(value).length;
532
+ if (ArrayBuffer.isView(value)) return value.byteLength;
533
+ let n = 2;
534
+ if (Array.isArray(value)) {
535
+ for (let v of value)n += chars(v) + 1;
536
+ } else {
537
+ for (let [k, v] of Object.entries(value))n += k.length + 4 + chars(v);
538
+ }
539
+ return n;
540
+ };
541
+ // What `cloned` answers for a value it leaves to structuredClone.
542
+ const OTHER = Symbol('other');
543
+ // A JSON value copied: primitives, plain objects and arrays, each object met
544
+ // once. Anything else (a Date, bytes, a Map, a hole, an object met twice) is
545
+ // OTHER, since structuredClone copies those as a read of them expects.
546
+ let cloned = (value, seen)=>{
547
+ if (typeof value != 'object' || value === null) {
548
+ return typeof value == 'function' || typeof value == 'symbol' ? OTHER : value;
549
+ }
550
+ if (seen.has(value)) return OTHER;
551
+ seen.add(value);
552
+ let proto = Object.getPrototypeOf(value);
553
+ if (proto == Array.prototype) {
554
+ let from = value, out = new Array(from.length);
555
+ for(let i = 0; i < from.length; i++){
556
+ let v = i in from ? cloned(from[i], seen) : OTHER;
557
+ if (v === OTHER) return OTHER;
558
+ out[i] = v;
559
+ }
560
+ return out;
561
+ }
562
+ if (proto != Object.prototype && proto != null) return OTHER;
563
+ let out = {};
564
+ for (let key of Object.keys(value)){
565
+ let v = cloned(value[key], seen);
566
+ if (v === OTHER) return OTHER;
567
+ out[key] = v;
568
+ }
569
+ return out;
570
+ };
571
+ // The components `names` of a bundle copied as JSON, or undefined where one
572
+ // holds anything else.
573
+ let json = (b, names)=>{
574
+ let out = {}, seen = new Set();
575
+ for (let name of names){
576
+ let comp = cloned(b[name], seen);
577
+ if (comp === OTHER) return undefined;
578
+ out[name] = comp;
579
+ }
580
+ return out;
581
+ };
582
+ // A copy of a value that is JSON and shares no object.
583
+ let dup = (value)=>{
584
+ if (typeof value != 'object' || value === null) return value;
585
+ if (Array.isArray(value)) return value.map(dup);
586
+ let out = {};
587
+ for(let key in value)out[key] = dup(value[key]);
588
+ return out;
589
+ };
590
+ // The bundles memory holds that are JSON throughout and share no object
591
+ // (`json` made them), whose copies need not look at each value. No caller
592
+ // is handed one.
593
+ let trees = new WeakSet();
594
+ // What memory holds of a bundle it is given: a copy, marked when it is JSON.
595
+ let kept = (b)=>{
596
+ let tree = json(b, Object.keys(b));
597
+ if (!tree) return structuredClone(b);
598
+ trees.add(tree);
599
+ return tree;
600
+ };
601
+ // Copy only the facets this read exposes, each value fresh. Values other than
602
+ // JSON keep structuredClone's semantics, shared references included, across
603
+ // the selected bundle.
604
+ let copy = (b, wanted, omitted = [])=>{
605
+ let names = Object.keys(b).filter((name)=>(!omitted.length || !omitted.includes(name)) && (!wanted || name == 'entity' || name == 'tombstone' || wanted.has(name)));
606
+ if (trees.has(b)) {
607
+ let out = {};
608
+ for (let name of names)out[name] = dup(b[name]);
609
+ return out;
610
+ }
611
+ return json(b, names) ?? structuredClone(Object.fromEntries(names.map((n)=>[
612
+ n,
613
+ b[n]
614
+ ])));
615
+ };
616
+ /** The memory of whole entities for a store bound to `driver` and `vocab`,
617
+ * keeping up to `memory` bytes of them. */ export let memoized = (driver, vocab, given, memory = MEMORY)=>{
618
+ let derived = given ?? {};
619
+ let c = connect(driver);
620
+ let count = Math.floor(memory / 2048);
621
+ // A read of more entities than this is a scan: what it reads is not kept,
622
+ // so it does not push out what is read again and again.
623
+ let scan = Math.floor(count / 4);
624
+ let own = new Set([
625
+ 'entity',
626
+ 'tombstone',
627
+ BLOBS,
628
+ ...tables(vocab)
629
+ ]);
630
+ let through = Object.values(derived).flatMap((d)=>storedOnly(d, vocab) ? tablesOf(d.expr(col('__owner'))) ?? [] : []);
631
+ // Whether the log follows the tables kept here, while the schema stands:
632
+ // as the file's survey says where it is current (./survey.ts), or else as
633
+ // the file itself does.
634
+ let logs;
635
+ let k = {
636
+ held: new Map(),
637
+ part: new Map(),
638
+ sizes: new Map(),
639
+ bytes: 0,
640
+ answers: new Map(),
641
+ asked: new Set(),
642
+ after: new Map(),
643
+ afterPart: new Map(),
644
+ tables: new Set([
645
+ ...own,
646
+ ...through
647
+ ]),
648
+ logged: through.every((name)=>own.has(name)),
649
+ follows: (schema)=>{
650
+ if (logs?.schema !== schema) {
651
+ let found = surveyed(driver, vocab, given);
652
+ logs = {
653
+ schema,
654
+ follows: found ? !found.unlogged.length : follows(driver, [
655
+ ...k.tables
656
+ ].filter((name)=>name != BLOBS))
657
+ };
658
+ }
659
+ return logs.follows;
660
+ },
661
+ clear: ()=>{
662
+ k.held.clear();
663
+ k.part.clear();
664
+ k.sizes.clear();
665
+ k.bytes = 0;
666
+ },
667
+ drop: (eids)=>{
668
+ k.answers.clear();
669
+ if (!eids) k.clear();
670
+ for (let eid of eids ?? k.after.keys()){
671
+ if (eids) evict(eid);
672
+ if (k.after.has(eid)) k.after.set(eid, LOST);
673
+ }
674
+ },
675
+ // What a transaction writing more than a scan reads is not kept either.
676
+ commit: ()=>{
677
+ if (k.after.size > scan) return;
678
+ for (let [eid, b] of k.after){
679
+ if (b !== LOST && !(b && holed(b))) hold(eid, b, k.afterPart.get(eid));
680
+ }
681
+ trim();
682
+ }
683
+ };
684
+ c.kept.add(k);
685
+ let evict = (eid)=>{
686
+ k.bytes -= k.sizes.get(eid) ?? 0;
687
+ k.sizes.delete(eid);
688
+ k.held.delete(eid);
689
+ k.part.delete(eid);
690
+ };
691
+ // Held whole, or in part: only the components `asked` names. What memory
692
+ // already holds of it in part still stands, since nothing wrote it, and
693
+ // is held beside them: two reads naming different components of one
694
+ // entity are each answered from memory.
695
+ let hold = (eid, b, asked)=>{
696
+ let had = k.part.get(eid), was = k.held.get(eid);
697
+ if (b && asked && had && was) {
698
+ b = {
699
+ ...was,
700
+ ...b
701
+ };
702
+ asked = new Set([
703
+ ...had,
704
+ ...asked
705
+ ]);
706
+ }
707
+ evict(eid);
708
+ let size = b ? sizeOf(b) : 64;
709
+ k.sizes.set(eid, size);
710
+ k.bytes += size;
711
+ k.held.set(eid, b && kept(b));
712
+ if (asked) k.part.set(eid, asked);
713
+ };
714
+ // Whether memory holds what a read asks of an entity: all of it, or the
715
+ // components `wanted` names.
716
+ let holds = (eid, wanted)=>{
717
+ let part = k.part.get(eid);
718
+ if (!k.held.has(eid)) return false;
719
+ if (!part) return true;
720
+ if (!wanted) return false;
721
+ for (let name of wanted)if (!part.has(name)) return false;
722
+ return true;
723
+ };
724
+ // Oldest first, through one iterator: V8 keeps the slot of each entry a Map
725
+ // deletes until it rehashes, and a fresh iterator steps over every such slot
726
+ // before the oldest entry left, so an iterator per eviction stepped over the
727
+ // same slots again for each entry a large bundle evicted.
728
+ let trim = ()=>{
729
+ let oldest = k.held.keys();
730
+ while(k.held.size > count || k.bytes > memory){
731
+ evict(oldest.next().value);
732
+ }
733
+ };
734
+ let providers = derivedOf(vocab, derived);
735
+ let dynamic = new Set(Object.entries(providers).filter(([, d])=>!storedOnly(d, vocab)).map(([p])=>p.split('.')[0]));
736
+ for (let name of vocab.comps){
737
+ if (vocab.comp(name)?.computed || vocab.props(name).some((p)=>vocab.prop(name, p)?.computed && !derived[`${name}.${p}`]?.stable)) dynamic.add(name);
738
+ }
739
+ let writes = (body, eids, mints = false)=>{
740
+ c.writing++;
741
+ let shifts = c.shifts;
742
+ let out;
743
+ try {
744
+ out = body();
745
+ } catch (error) {
746
+ // What it wrote before it failed is not known: keep nothing until
747
+ // its transaction ends.
748
+ k.clear();
749
+ for (let other of c.kept)other.clear();
750
+ if (c.shifts != shifts) {
751
+ c.spines.clear();
752
+ c.since.clear();
753
+ }
754
+ if (c.depth) c.blind = true;
755
+ throw error;
756
+ } finally{
757
+ c.writing--;
758
+ }
759
+ let gone = (other, eid)=>{
760
+ other.bytes -= other.sizes.get(eid) ?? 0;
761
+ other.sizes.delete(eid);
762
+ other.held.delete(eid);
763
+ other.part.delete(eid);
764
+ other.afterPart.delete(eid);
765
+ if (c.depth) other.after.set(eid, LOST);
766
+ };
767
+ for (let eid of eids(out)){
768
+ for (let other of c.kept)gone(other, eid);
769
+ if (c.depth) c.dirty.add(eid);
770
+ // An id, a number or a grave it moved is one of these entities'.
771
+ if (c.shifts != shifts) c.spines.delete(eid);
772
+ }
773
+ if (typeof mints == 'function' ? mints(out) : mints) {
774
+ // What it minted is not named: neither is whose spine it moved.
775
+ if (c.shifts != shifts) {
776
+ c.spines.clear();
777
+ c.since.clear();
778
+ }
779
+ for (let other of c.kept){
780
+ for (let [eid, b] of other.held)if (!b) gone(other, eid);
781
+ for (let [eid, b] of other.after)if (b === null) gone(other, eid);
782
+ }
783
+ if (c.depth) c.blind = true;
784
+ }
785
+ return out;
786
+ };
787
+ // What an entity held before this transaction's next patch: what its
788
+ // patches so far left it, or what memory held while nothing wrote it.
789
+ let prior = (eid)=>k.afterPart.has(eid) ? LOST : k.after.has(eid) ? k.after.get(eid) : c.dirty.has(eid) || !holds(eid) ? LOST : k.held.get(eid);
790
+ let numbered = !!vocab.prop('entity', 'num');
791
+ let typed = !!vocab.comp('archetype');
792
+ // A component's stored properties, where what a patch gives them is what a
793
+ // read returns: not one with a derived property, which a read works out
794
+ // itself, unless it is read again on every hit anyway.
795
+ let shapes = new Map();
796
+ let shape = (name)=>{
797
+ if (!shapes.has(name)) {
798
+ let props = vocab.comp(name) && k.tables.has(name) ? vocab.props(name).map((p)=>vocab.prop(name, p)) : undefined;
799
+ let exact = props && (dynamic.has(name) || !props.some((p)=>p.computed || derived[`${name}.${p.prop}`]));
800
+ shapes.set(name, props && exact ? new Map(props.filter((p)=>!p.computed).map((p)=>[
801
+ p.prop,
802
+ p
803
+ ])) : null);
804
+ }
805
+ return shapes.get(name);
806
+ };
807
+ // A value as a read returns it once a patch has stored it, where that is
808
+ // certain: what SQLite would convert on the way in is not.
809
+ let cast = (p, v)=>{
810
+ if (v == null) return null;
811
+ if (p.category == 'ref') return typeof v == 'string' ? v : LOST;
812
+ if (p.scalar == 'jsonb') {
813
+ let text = JSON.stringify(v);
814
+ return text === undefined ? LOST : JSON.parse(text);
815
+ }
816
+ if (p.scalar == 'binary') return v instanceof Uint8Array ? v.slice() : LOST;
817
+ if (p.scalar == 'bool') return typeof v == 'boolean' ? v : LOST;
818
+ if (p.affinity == 'text') return typeof v == 'string' ? v : LOST;
819
+ if (p.affinity == 'integer' || p.affinity == 'real') {
820
+ return typeof v == 'number' && Number.isFinite(v) && !Object.is(v, -0) && (!Number.isInteger(v) || Number.isSafeInteger(v)) ? v : LOST;
821
+ }
822
+ return LOST;
823
+ };
824
+ // What one bundle of a patch leaves an entity holding, from what it held
825
+ // (`null`: nothing) and the spine the patch minted or numbered for it.
826
+ // Memory owns both snapshots. A patch replaces each changed component
827
+ // and reads copy the values they hand out, so untouched values can be shared.
828
+ let fold = (base, b, mint)=>{
829
+ let out = base ? {
830
+ ...base
831
+ } : mint ? {
832
+ entity: {
833
+ eid: b.entity.eid
834
+ }
835
+ } : null;
836
+ if (!out) return comps(b).length || b.entity.archetype ? LOST : null;
837
+ if (mint && numbered && mint.num != null) {
838
+ out.entity = {
839
+ ...out.entity,
840
+ num: mint.num,
841
+ ...mint.prefix == null ? {} : {
842
+ prefix: mint.prefix
843
+ }
844
+ };
845
+ }
846
+ if (typed && b.entity.archetype !== undefined) {
847
+ let { archetype: _, ...entity } = out.entity;
848
+ out.entity = b.entity.archetype == null ? entity : {
849
+ ...entity,
850
+ archetype: String(b.entity.archetype)
851
+ };
852
+ }
853
+ // A patch writes no rows to the dead (./write.ts `patch`).
854
+ if ('tombstone' in out) return out;
855
+ for (let [name, comp] of comps(b)){
856
+ if (comp == null) {
857
+ delete out[name];
858
+ continue;
859
+ }
860
+ out[name] = put(out[name], name, comp);
861
+ }
862
+ return out;
863
+ };
864
+ // What a component holds once a patch gives it `comp`, from what it held.
865
+ let put = (had, name, comp)=>{
866
+ let props = shape(name);
867
+ if (!props) return {
868
+ [HOLE]: true
869
+ };
870
+ let next = had ? {
871
+ ...had
872
+ } : {};
873
+ // A row this patch brings takes each default it does not give.
874
+ for (let [p, prop] of had ? [] : props){
875
+ if (p in comp) continue;
876
+ let d = prop.default;
877
+ let v = !d ? null : 'now' in d ? LOST : cast(prop, d.value);
878
+ if (v === LOST) return {
879
+ [HOLE]: true
880
+ };
881
+ if (v != null) next[p] = v;
882
+ }
883
+ for (let [p, v] of Object.entries(comp)){
884
+ let prop = props.get(p);
885
+ let value = prop ? cast(prop, v) : LOST;
886
+ if (value === LOST) return {
887
+ [HOLE]: true
888
+ };
889
+ if (value == null) delete next[p];
890
+ else next[p] = value;
891
+ }
892
+ return next;
893
+ };
894
+ // An answer whose query the entities a patch moved were selected by neither
895
+ // before nor after it stands where it stood: its tables moved, its rows did
896
+ // not. `before` is the tables' counts the patch began at.
897
+ let stand = (was, now, before)=>{
898
+ let selects = (a, b)=>b === LOST || b === undefined || b != null && (holed(b) ? a.shape?.(b) ?? true : a.test(b));
899
+ for (let a of k.answers.values()){
900
+ if (a.tables.some(([t, n])=>(before.get(t) ?? 0) != n)) continue;
901
+ if (a.tables.every(([t, n])=>(c.versions.get(t) ?? 0) == n)) continue;
902
+ if (a.prove) {
903
+ Object.assign(a, a.prove());
904
+ delete a.prove;
905
+ }
906
+ if (!a.test) continue;
907
+ if (a.strict?.some((t)=>(before.get(t) ?? 0) != (c.versions.get(t) ?? 0))) {
908
+ continue;
909
+ }
910
+ let moved = [
911
+ ...now.keys()
912
+ ].some((eid)=>{
913
+ let before = was.get(eid), after = now.get(eid);
914
+ if (a.membership) {
915
+ if ([
916
+ before,
917
+ after
918
+ ].some((b)=>typeof b == 'symbol' || b === undefined || b && holed(b) && (a.shape?.(b) ?? true))) return true;
919
+ return selects(a, before) != selects(a, after);
920
+ }
921
+ return selects(a, before) || selects(a, after);
922
+ });
923
+ if (!moved) a.tables = a.tables.map(([t])=>[
924
+ t,
925
+ c.versions.get(t) ?? 0
926
+ ]);
927
+ }
928
+ };
929
+ // Another connection's commit, or anything else this one cannot see.
930
+ let sync = ()=>follow(driver, c);
931
+ // A stable relation can change when another entity is patched. Such
932
+ // components refresh on every miss; only this global revision can reuse the
933
+ // completed answer. Unproven providers remain uncached.
934
+ let related = Object.entries(providers).filter(([, d])=>!storedOnly(d, vocab));
935
+ let reusable = new Set(related.filter(([, d])=>d.stable).map(([p])=>p.split('.')[0]));
936
+ let safe = (rows, comps)=>{
937
+ let names = new Set(rows.flatMap((b)=>Object.keys(b)));
938
+ if ([
939
+ ...names
940
+ ].some((n)=>vocab.comp(n)?.computed || vocab.props(n).some((p)=>{
941
+ let ref = vocab.prop(n, p)?.ref;
942
+ return ref && vocab.comp(ref)?.computed;
943
+ }))) return false;
944
+ let reads = related.filter(([p, d])=>names.has(p.split('.')[0]) && (!!comps || d.whole !== false));
945
+ return reads.length > 0 && reads.every(([, d])=>d.stable);
946
+ };
947
+ let remember = (key, a)=>{
948
+ k.answers.set(key, a);
949
+ if (c.depth) c.answered.push([
950
+ k.answers,
951
+ key
952
+ ]);
953
+ if (k.answers.size > ANSWERS) {
954
+ k.answers.delete(k.answers.keys().next().value);
955
+ }
956
+ };
957
+ let getting = (get, eids, comps, refresh = true)=>{
958
+ // A get naming components is answered from an entity held whole, or
959
+ // held in part with them, cut to them. What one reads is held in part,
960
+ // unless it says all there is: an entity storage lacks, or a dead one.
961
+ let wanted = comps && new Set(comps);
962
+ // This transaction already knows the aspects its own patches produced.
963
+ // A whole read can use them when none are missing or need deriving.
964
+ let written = new Map();
965
+ if (c.depth && !c.blind && !comps?.some((n)=>dynamic.has(n))) {
966
+ for (let eid of eids){
967
+ let b = k.after.get(eid), part = k.afterPart.get(eid);
968
+ if (b === undefined || b === LOST || part && !comps?.every((n)=>part.has(n))) continue;
969
+ if (b && (comps ? comps.some((n)=>b[n] != null && HOLE in b[n]) : typed && !b.entity.archetype || holed(b) || Object.keys(b).some((n)=>dynamic.has(n)))) continue;
970
+ written.set(eid, b);
971
+ }
972
+ }
973
+ let missing = [
974
+ ...new Set(eids)
975
+ ].filter((eid)=>!written.has(eid) && !holds(eid, wanted));
976
+ let read = new Set(missing);
977
+ let fresh = new Map((missing.length ? get(missing, comps) : []).map((b)=>[
978
+ b.entity.eid,
979
+ b
980
+ ]));
981
+ if (!c.blind && missing.length <= scan) {
982
+ for (let eid of missing){
983
+ if (c.dirty.has(eid)) continue;
984
+ let b = fresh.get(eid) ?? null;
985
+ hold(eid, b, wanted && b && !dead(b) ? wanted : undefined);
986
+ }
987
+ }
988
+ let hits = eids.filter((eid)=>!written.has(eid) && !read.has(eid) && k.held.get(eid));
989
+ // A hit's dynamic components are read now, in one statement, of the hits
990
+ // holding any.
991
+ let changing = refresh && (!wanted || [
992
+ ...wanted
993
+ ].some((name)=>dynamic.has(name)));
994
+ let stale = new Map((changing ? hits : []).flatMap((eid)=>{
995
+ let names = Object.keys(k.held.get(eid)).filter((name)=>dynamic.has(name) && (!wanted || wanted.has(name)));
996
+ return names.length ? [
997
+ [
998
+ eid,
999
+ names
1000
+ ]
1001
+ ] : [];
1002
+ }));
1003
+ let names = [
1004
+ ...new Set([
1005
+ ...stale.values()
1006
+ ].flat())
1007
+ ];
1008
+ let current = new Map((names.length ? get([
1009
+ ...stale.keys()
1010
+ ], names) : []).map((b)=>[
1011
+ b.entity.eid,
1012
+ b
1013
+ ]));
1014
+ let out = eids.flatMap((eid)=>{
1015
+ if (written.has(eid)) {
1016
+ let b = written.get(eid);
1017
+ return b ? [
1018
+ copy(b, wanted)
1019
+ ] : [];
1020
+ }
1021
+ if (read.has(eid)) return fresh.has(eid) ? [
1022
+ fresh.get(eid)
1023
+ ] : [];
1024
+ let held = k.held.get(eid);
1025
+ k.held.delete(eid);
1026
+ k.held.set(eid, held);
1027
+ if (!held) return [];
1028
+ let b = copy(held, wanted, names), now = current.get(eid);
1029
+ return [
1030
+ now ? Object.assign(b, now) : b
1031
+ ];
1032
+ });
1033
+ trim();
1034
+ return out;
1035
+ };
1036
+ let viewed = (keyOf, run, comps)=>{
1037
+ sync();
1038
+ if (!reusable.size || comps && !comps.some((n)=>reusable.has(n))) return run();
1039
+ let key = keyOf();
1040
+ let limit = ANSWER - key.length * 2;
1041
+ if (limit <= 0) return run();
1042
+ let epoch = revision(driver, 'data');
1043
+ let held = k.answers.get(key);
1044
+ if (held?.epoch == epoch) {
1045
+ k.answers.delete(key);
1046
+ k.answers.set(key, held);
1047
+ return copied(held.rows);
1048
+ }
1049
+ if (held) k.answers.delete(key);
1050
+ let rows = run();
1051
+ if (!safe(rows, comps) || epoch != revision(driver, 'data')) return rows;
1052
+ if (!held && !k.asked.delete(key)) {
1053
+ k.asked.add(key);
1054
+ if (k.asked.size > ASKED) k.asked.delete(k.asked.values().next().value);
1055
+ return rows;
1056
+ }
1057
+ let kept = packed(rows, limit);
1058
+ if (kept) remember(key, {
1059
+ tables: [],
1060
+ epoch,
1061
+ rows: kept
1062
+ });
1063
+ return rows;
1064
+ };
1065
+ let stored = new Set([
1066
+ 'tombstone',
1067
+ ...tables(vocab)
1068
+ ]);
1069
+ return {
1070
+ pointed: (eid, archetype)=>{
1071
+ let b = k.after.get(eid);
1072
+ if (b && b !== LOST) {
1073
+ k.after.set(eid, {
1074
+ ...b,
1075
+ entity: {
1076
+ ...b.entity,
1077
+ archetype
1078
+ }
1079
+ });
1080
+ }
1081
+ },
1082
+ presence: (eid, tables)=>{
1083
+ sync();
1084
+ if (c.blind || !tables.every((name)=>stored.has(name))) {
1085
+ return undefined;
1086
+ }
1087
+ let b = prior(eid);
1088
+ return b === LOST || b == null ? undefined : tables.filter((name)=>b[name] != null);
1089
+ },
1090
+ answer: (key, dependencies, run, prove)=>{
1091
+ if (!dependencies) return run();
1092
+ sync();
1093
+ let current = (table)=>c.versions.get(table) ?? 0;
1094
+ let held = k.answers.get(key);
1095
+ if (held && held.tables.every(([t, n])=>current(t) == n)) {
1096
+ k.answers.delete(key);
1097
+ k.answers.set(key, held);
1098
+ return copied(held.rows);
1099
+ }
1100
+ if (held) k.answers.delete(key);
1101
+ else if (!k.asked.delete(key)) {
1102
+ k.asked.add(key);
1103
+ if (k.asked.size > ASKED) {
1104
+ k.asked.delete(k.asked.values().next().value);
1105
+ }
1106
+ return run();
1107
+ }
1108
+ let tables = dependencies();
1109
+ if (!tables) return run();
1110
+ let at = tables.map((t)=>[
1111
+ t,
1112
+ current(t)
1113
+ ]);
1114
+ let rows = run();
1115
+ if (at.some(([t, n])=>current(t) != n)) return rows;
1116
+ let kept = packed(rows, ANSWER);
1117
+ if (!kept) return rows;
1118
+ remember(key, {
1119
+ tables: at,
1120
+ rows: kept,
1121
+ prove: ()=>{
1122
+ let { query, membership, strict, shape } = prove?.() ?? {};
1123
+ let proof = typeof query == 'function' || !query ? undefined : rooted(vocab, query);
1124
+ return {
1125
+ test: typeof query == 'function' ? query : proof?.test,
1126
+ shape: shape ?? proof?.shape,
1127
+ membership: membership && (typeof query == 'function' || !!query && local(vocab, query)),
1128
+ strict: [
1129
+ ...new Set([
1130
+ ...strict ?? [],
1131
+ ...proof?.strict ?? []
1132
+ ])
1133
+ ]
1134
+ };
1135
+ }
1136
+ });
1137
+ return rows;
1138
+ },
1139
+ get: (get, eids, comps, refresh = true)=>{
1140
+ sync();
1141
+ return getting(get, eids, comps, refresh);
1142
+ },
1143
+ view: viewed,
1144
+ writes,
1145
+ removes: (eids, at, body)=>{
1146
+ sync();
1147
+ let was = new Map(eids.map((eid)=>[
1148
+ eid,
1149
+ prior(eid)
1150
+ ]));
1151
+ let before = new Map(c.versions);
1152
+ writes(body, ()=>eids);
1153
+ if (!c.depth || c.blind) return;
1154
+ // What each holds once buried: its grave, and nothing else.
1155
+ let buried = (eid, b)=>({
1156
+ entity: b ? {
1157
+ ...b.entity
1158
+ } : {
1159
+ eid
1160
+ },
1161
+ tombstone: {
1162
+ deleted_at: at
1163
+ }
1164
+ });
1165
+ let now = new Map();
1166
+ for (let [eid, b] of was){
1167
+ now.set(eid, b === LOST || b == null ? b : buried(eid, b));
1168
+ }
1169
+ for (let [eid, b] of now){
1170
+ k.after.set(eid, b && b !== LOST ? {
1171
+ entity: b.entity,
1172
+ tombstone: {}
1173
+ } : b);
1174
+ }
1175
+ stand(was, now, before);
1176
+ },
1177
+ patch: (bundles, body)=>{
1178
+ sync();
1179
+ let eids = [
1180
+ ...new Set(bundles.map((b)=>b.entity.eid))
1181
+ ];
1182
+ let partial = new Map(eids.flatMap((eid)=>{
1183
+ let names = k.afterPart.get(eid) ?? (!c.dirty.has(eid) ? k.part.get(eid) : undefined);
1184
+ let b = k.afterPart.has(eid) ? k.after.get(eid) : k.held.get(eid);
1185
+ return names && b && b !== LOST ? [
1186
+ [
1187
+ eid,
1188
+ {
1189
+ names: new Set(names),
1190
+ b
1191
+ }
1192
+ ]
1193
+ ] : [];
1194
+ }));
1195
+ // What each held before, taken before the write lets it go.
1196
+ let now = new Map(eids.map((eid)=>[
1197
+ eid,
1198
+ prior(eid)
1199
+ ]));
1200
+ let known = (eid, name)=>{
1201
+ let b = now.get(eid);
1202
+ if (b === LOST || b === undefined || c.blind) return undefined;
1203
+ let held = b?.[name];
1204
+ // A row whose values memory can't work out vouches for none of them.
1205
+ return held == null ? null : HOLE in held ? {} : held;
1206
+ };
1207
+ let shifts = c.shifts, before = new Map(c.versions);
1208
+ let born = writes(()=>body(known), (born)=>[
1209
+ ...eids,
1210
+ ...born.map((e)=>e.eid)
1211
+ ]);
1212
+ if (!c.depth || c.blind) return born;
1213
+ // A number the patch took away, or one it gave an entity a reference
1214
+ // minted, is not in what it said.
1215
+ if (c.shifts != shifts) return born;
1216
+ let minted = new Map(born.map((e)=>[
1217
+ e.eid,
1218
+ e
1219
+ ]));
1220
+ // An entity the patch minted or first numbered held nothing before it.
1221
+ for (let eid of minted.keys())if (now.has(eid)) now.set(eid, null);
1222
+ let was = new Map(now);
1223
+ for (let b of bundles){
1224
+ let eid = b.entity.eid, base = now.get(eid);
1225
+ let part = partial.get(eid);
1226
+ if (part) {
1227
+ // Unknown aspects stay unknown. Only values whose entire aspect
1228
+ // was read can be folded through a patch without another lookup.
1229
+ let patch = Object.fromEntries(Object.entries(b).filter(([name])=>name == 'entity' || part.names.has(name)));
1230
+ let next = fold(part.b, patch);
1231
+ now.set(eid, next);
1232
+ if (next && next !== LOST) {
1233
+ partial.set(eid, {
1234
+ names: part.names,
1235
+ b: next
1236
+ });
1237
+ }
1238
+ k.afterPart.set(eid, part.names);
1239
+ } else {
1240
+ now.set(eid, base === LOST ? LOST : fold(base, b, minted.get(eid)));
1241
+ }
1242
+ }
1243
+ for (let [eid, b] of now)k.after.set(eid, b);
1244
+ // A spine a reference minted holds what memory can't say.
1245
+ if (born.every((e)=>now.has(e.eid))) stand(was, now, before);
1246
+ return born;
1247
+ }
1248
+ };
1249
+ };
1250
+ //# sourceMappingURL=memo.js.map