@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/mod.js ADDED
@@ -0,0 +1,1103 @@
1
+ import { purgeHistory, retained } from "./purge.js";
2
+ import { preserving } from "@yaks/graph/trash";
3
+ import { purgeTrashSql, retainSql, trashed } from "./trash.js";
4
+ import { cardinality, population, torn } from "./population.js";
5
+ // @yaks/sqlite — a storage adapter that turns the yaks query/vocabulary/SQL
6
+ // stack into a working SQLite-backed store. It composes three sibling packages:
7
+ //
8
+ // @yaks/query parses a query string into an AST
9
+ // @yaks/vocab describes a component vocabulary and interrogates it
10
+ // @yaks/sql compiles an AST + a vocabulary into SQL + bound params
11
+ //
12
+ // and adds the two halves those packages leave to a backend: DDL (the schema a
13
+ // vocabulary implies) and writes (a patch applied to that schema). The reads it
14
+ // gets for free — it runs @yaks/sql's compiled statement and gathers the rows.
15
+ //
16
+ // Both halves are the reference every SQLite-shaped adapter shares. The schema
17
+ // is one derivation, and so is the write: ./write.ts builds each write as a
18
+ // self-sufficient statement — an owner id is a subquery, never a value looked up
19
+ // first — so the same statements this package runs one at a time are the ones
20
+ // @yaks/d1 gathers into a single batch.
21
+ //
22
+ // The model is the yaks entity graph: everything is an entity (a string id)
23
+ // carrying components (a row per component table). An entity is what its
24
+ // components make it — a blog post is a `doc` plus a `post`; a product is a
25
+ // `doc` plus a `price`. Each component covers one aspect of an entity; the set
26
+ // of components an entity carries is its identity. A read returns a bundle (an
27
+ // entity with its components gathered); a write takes a batch of bundles and
28
+ // patches them in — omitted properties untouched, a null property cleared, a
29
+ // null component dropped.
30
+ //
31
+ // It implements @yaks/graph's `Storage`, which is where the responsibilities
32
+ // divide: this package owns the bytes (schema, rows, identity, transactions)
33
+ // and @yaks/graph owns the decisions (admission, preconditions, which entities
34
+ // a delete takes with it, provenance). Point `graph()` at a store from here
35
+ // and the two halves are the whole thing.
36
+ //
37
+ // Beside the graph it keeps one thing of its own: `server_meta`, the key/value
38
+ // a store writes about itself — its lineage epoch, a sweep's mark — read and
39
+ // written through ./meta.ts, and carried by no bundle.
40
+ //
41
+ // The adapter is bound to a driver and a vocabulary once, by `storage()`, and
42
+ // reads and writes bundles from then on. The driver is any object with
43
+ // `query`/`exec` (@yaks/sql `Driver`) — an in-process SQLite for a test, a pooled
44
+ // handle for a server — so nothing here names a concrete SQLite library.
45
+ import { relabelsVocab } from "@yaks/vocab";
46
+ import { bare } from "@yaks/query";
47
+ import { filter } from "@yaks/match";
48
+ import { backingsIn, derivedIn } from "@yaks/sql";
49
+ import { erect, idOf, literals, sourceScreen, worn } from "@yaks/sql";
50
+ import { after, sleep } from "@yaks/fp";
51
+ import { context, scope } from "@yaks/trace";
52
+ import { analyzable, analyzed, anyStanding, built, emptied, fit, grown, indexed, logged, respine, retabled, retired, standing, tabled } from "./ddl.js";
53
+ import { analyzedAt, epoch, installation, installed, meta, SCHEMA } from "./meta.js";
54
+ import { admitted, ast, get, read, rows, screened, Unpointed } from "./read.js";
55
+ import { doom } from "./doom.js";
56
+ import { exclusive, unit, unwaiting } from "./unit.js";
57
+ import { enter } from "@yaks/graph/enter";
58
+ import { branching, unborn } from "./branches.js";
59
+ import { busy } from "./error.js";
60
+ import { options } from "./reader.js";
61
+ import { catalog, setOf } from "./catalog.js";
62
+ import { backfill, classify, entomb, heldBy, ledger, pendingShapes } from "./archetype.js";
63
+ import { componentTables, objects, shape, sole } from "./physical.js";
64
+ import { analyze, build, forgo, reshape, statistics, upkeep as daily } from "./owe.js";
65
+ import { maintenance } from "./maintenance.js";
66
+ import { plan } from "./plan.js";
67
+ import { births, erase, patch, prune, remove, revive, spines } from "./write.js";
68
+ import { burying } from "./buried.js";
69
+ import { located, measure } from "./measure.js";
70
+ import { bindings } from "./rules.js";
71
+ import { basis, local, memoized, rooted, simple } from "./memo.js";
72
+ import { listed, revision, storeAs } from "@yaks/sql";
73
+ import { bindStorage, readingVocab } from "./shape.js";
74
+ export { bindStorage, identified, layoutOf, wordColumns } from "./shape.js";
75
+ import { newest, watch } from "./watch.js";
76
+ import { gotten, metered, named } from "./budget.js";
77
+ import { comps, dead } from "@yaks/graph/bundle";
78
+ import { holds, raise, raisedIn, recorded, units, unraised } from "./raise.js";
79
+ import { tables } from "./layout.js";
80
+ import { raisedSurvey, surveyed } from "./survey.js";
81
+ import { Refused } from "@yaks/graph/errors";
82
+ import { historySchema, keep, reshapes, SEEDING, seeds, unseeded, within } from "./history.js";
83
+ import { add } from "./follow.js";
84
+ import { sha256 } from "@yaks/graph/sha256";
85
+ export { beside, BRANCH, BRANCHES, FROM, historySchema, keeps, SEEDING, ticked, TO } from "./history.js";
86
+ export { backfill, componentTables, drift, entomb, heldBy, ledger, mend, reclassify, reclassifyAll } from "./archetype.js";
87
+ export { statements } from "./statements.js";
88
+ import { statements } from "./statements.js";
89
+ import { checks as diagnostics } from "./check.js";
90
+ import { migrations } from "./migration.js";
91
+ export { catalog } from "./catalog.js";
92
+ export { pointSql } from "./point.js";
93
+ export { deletions, identity, inspect } from "./inspect.js";
94
+ export { asked, checks, columns, defined, heard, objects, pinned, sole } from "./physical.js";
95
+ export { GONE, OVER, overlay } from "./overlay.js";
96
+ export { bindings, matched } from "./rules.js";
97
+ export * from "./bundle.js";
98
+ export { holds, lazy, raise, RAISED, recorded, rests, stood, unraised } from "./raise.js";
99
+ export { analyzed, built, FIT, fit, fitting, grown, indexed, logged, META, orphaned, refit, respine, respined, retabled, retired, schema, standing, tabled, unfit, unresolved } from "./ddl.js";
100
+ export { EPOCH, epoch, epochAt, installed, meta, printed, REQUIRED, requirements, requires } from "./meta.js";
101
+ export { decoded, isJsonb, jsonIn, jsonOut, projected } from "./jsonb.js";
102
+ export { compSql, get, OWNER, read, rows, setSql, spine, tagOf } from "./read.js";
103
+ export { buried, dropSql, erase, eraseSql, minted, mintSql, numberSql, patch, patchSql, prune, pruneSql, remove, removeSql, revive, spines, touched, unburySql, upsertSql } from "./write.js";
104
+ // The read options a statement is the same under (@yaks/graph `ReadOpts`).
105
+ const UNREAD = new Set([
106
+ 'person',
107
+ 'level',
108
+ 'administrative',
109
+ 'native',
110
+ 'durable',
111
+ 'patch',
112
+ 'speaks',
113
+ 'now',
114
+ 'storageOrder',
115
+ 'unordered'
116
+ ]);
117
+ // A read's options without what its caller is doing around it: the activity
118
+ // it runs under (`parent`, new with every request) and when it stops waiting
119
+ // (`signal`). A read here is synchronous and traced by its unit, so neither is
120
+ // an input of the answer, and a read made under them shares every answer and
121
+ // statement kept for the same read made without.
122
+ let asking = (o)=>{
123
+ if (!o) return o;
124
+ let { signal: _signal, parent: _parent, ...rest } = o;
125
+ return rest;
126
+ };
127
+ // The effective read options are data; order of object keys is immaterial,
128
+ // while arrays, query clauses, paths and literal token strings keep order.
129
+ // Every read keys its options, so an array of plain values is written whole by
130
+ // `JSON.stringify` and only objects are taken apart.
131
+ let plain = (v)=>!v || typeof v != 'object';
132
+ let keyed = (value)=>{
133
+ if (plain(value)) return JSON.stringify(value);
134
+ let v = value;
135
+ if (typeof v.toJSON == 'function') return keyed(v.toJSON());
136
+ if (Array.isArray(v)) {
137
+ return v.every(plain) ? JSON.stringify(v) : `[${v.map((x)=>keyed(x) ?? 'null').join(',')}]`;
138
+ }
139
+ let out = [];
140
+ for (let k of Object.keys(v).sort()){
141
+ let got = keyed(v[k]);
142
+ if (got !== undefined) out.push(`${JSON.stringify(k)}:${got}`);
143
+ }
144
+ return `{${out.join(',')}}`;
145
+ };
146
+ // The tables of versions a store with history keeps (./history.ts), made where
147
+ // missing and typed as the live tables stand now, and each one just made
148
+ // given the live rows as the versions they are so far: here, or, `paced`, a
149
+ // page at a time through maintain() (./maintenance.ts).
150
+ let versioned = (driver, vocab, paced)=>{
151
+ let had = new Set(objects(driver, {
152
+ type: 'table'
153
+ }).map((o)=>o.name));
154
+ let stood = standing(driver, vocab);
155
+ let typed = (comp, c)=>{
156
+ let found = stood[comp]?.cols.find((r)=>r.name == c);
157
+ return found ? String(found.type ?? '') : undefined;
158
+ };
159
+ let left = add(driver, historySchema(vocab, typed));
160
+ let made = (name)=>!had.has(name);
161
+ let seed = paced ? reshapes(vocab, made) : seeds(vocab, made);
162
+ for (let s of holds(driver, vocab, seed))driver.query(s);
163
+ // Only a live table that stands holds rows to take.
164
+ let comps = paced ? unseeded(vocab, made).filter((c)=>had.has(c)) : [];
165
+ if (comps.length) {
166
+ // An install while pages are still owed adds its tables behind them.
167
+ let owed = meta(driver).get(SEEDING);
168
+ let was = owed ? JSON.parse(owed) : {
169
+ comps: [],
170
+ after: 0
171
+ };
172
+ meta(driver).set(SEEDING, JSON.stringify({
173
+ ...was,
174
+ comps: [
175
+ ...was.comps,
176
+ ...comps
177
+ ]
178
+ }));
179
+ }
180
+ return left;
181
+ };
182
+ /**
183
+ * Bind a store to a driver and a vocabulary — a {@link Storage} @yaks/graph
184
+ * can apply bundles to. `base` options (a derived-property registry, a fixed
185
+ * `now` for time phrases) ride every read; a per-call `opts` merges over them.
186
+ */ export let storage = (driver, vocab, base = {})=>{
187
+ // Binding asks the file nothing: the store is bound on its first use, once
188
+ // it knows how the file lays its words out (./shape.ts).
189
+ let store;
190
+ let at = ()=>store ??= bound(driver, bindStorage(driver, vocab), base);
191
+ return new Proxy({}, {
192
+ get: (target, k)=>{
193
+ if (k != 'reload') return Reflect.get(target, k) ?? Reflect.get(at(), k);
194
+ return (next)=>{
195
+ let old = bindStorage(driver, vocab);
196
+ let fresh = bindStorage(driver, next);
197
+ if (!relabelsVocab(old, fresh)) {
198
+ bindStorage(driver, vocab);
199
+ return false;
200
+ }
201
+ let options = {
202
+ ...base,
203
+ ...base.derived ? {
204
+ derived: derivedIn(base.derived, vocab, next)
205
+ } : {},
206
+ ...base.backed ? {
207
+ backed: backingsIn(base.backed, vocab, next)
208
+ } : {}
209
+ };
210
+ try {
211
+ store = bound(driver, fresh, options);
212
+ } catch (error) {
213
+ bindStorage(driver, vocab);
214
+ throw error;
215
+ }
216
+ base = options;
217
+ vocab = next;
218
+ return true;
219
+ };
220
+ },
221
+ has: (target, k)=>Reflect.has(target, k) || Reflect.has(at(), k),
222
+ ownKeys: (target)=>[
223
+ ...new Set([
224
+ ...Reflect.ownKeys(at()),
225
+ ...Reflect.ownKeys(target)
226
+ ])
227
+ ],
228
+ getOwnPropertyDescriptor: (target, k)=>Reflect.getOwnPropertyDescriptor(target, k) ?? Reflect.getOwnPropertyDescriptor(at(), k)
229
+ });
230
+ };
231
+ let bound = (driver, vocab, base)=>{
232
+ let effective = options(driver, vocab, base);
233
+ if (base.history) keep(driver, vocab, base.history, base.mode);
234
+ // What a store with history adds beside its own schema, run and printed
235
+ // with it.
236
+ let besides = base.history ? historySchema(vocab) : [];
237
+ let printed = ()=>{
238
+ let own = plan(vocab, base.derived, !!driver.file).print;
239
+ return besides.length ? sha256(`${own};history`) : own;
240
+ };
241
+ // Whether this store keeps each entity's archetype pointer in step with
242
+ // its rows: every store does, whatever its vocabulary declares, since every
243
+ // whole read and removal goes by the pointer. A mode's store reads
244
+ // what an entity held then, which no pointer says (./mode.ts).
245
+ let keeping = !base.mode;
246
+ // What the connection's open transaction wrote that no pointer says yet
247
+ // (./archetype.ts `ledger`).
248
+ let book = keeping ? ledger(driver) : undefined;
249
+ let owing = ()=>book?.owed() ?? [];
250
+ // All handles on this connection see the open writer's rows, including a
251
+ // graph's scope reads through the outer store rather than its tx handle.
252
+ let upkeep = maintenance(driver, vocab);
253
+ let migrating = ()=>!!base.deferred && upkeep.pending();
254
+ let unindexed = Object.assign(()=>undefined, {
255
+ pending: {
256
+ ids: [],
257
+ matching: ()=>[]
258
+ }
259
+ });
260
+ let opts = ()=>({
261
+ ...effective(),
262
+ ...migrating() ? {
263
+ archetypes: unindexed
264
+ } : {},
265
+ ...!migrating() && book?.owed().length ? {
266
+ archetypes: catalog(driver, ()=>pendingShapes(driver, book))
267
+ } : {}
268
+ });
269
+ // Who says what an entity holds where its pointer does not: the open
270
+ // transaction's ledger, or the mode this connection reads (`base.held`).
271
+ let unsettled = book ? {
272
+ wrote: book.wrote,
273
+ held: (rows)=>{
274
+ let known = new Map(rows.flatMap(({ eid, id, pointed })=>{
275
+ let tables = book.held(eid, pointed);
276
+ return tables ? [
277
+ [
278
+ id,
279
+ tables
280
+ ]
281
+ ] : [];
282
+ }));
283
+ let missing = rows.filter((r)=>!known.has(r.id)).map((r)=>r.id);
284
+ if (missing.length && migrating()) {
285
+ for (let [id, tables] of upkeep.held(missing)){
286
+ known.set(id, [
287
+ ...tables
288
+ ]);
289
+ }
290
+ }
291
+ return known;
292
+ }
293
+ } : base.held && {
294
+ // No pointer says what an entity held then.
295
+ wrote: ()=>true,
296
+ held: (rows, names)=>base.held(rows.map((r)=>r.id), names)
297
+ };
298
+ // What an install answers for, as its receipt marks it: the print, and the
299
+ // count and length of what it makes, of what rests on the tables first
300
+ // writes raised (./raise.ts), and of the `strays` beside them.
301
+ let marked = (strays)=>{
302
+ let { made, raised, on } = plan(vocab, base.derived, !!driver.file);
303
+ let stand = raisedIn(driver, vocab);
304
+ let answers = [
305
+ ...made,
306
+ ...raised.flatMap((s, i)=>on[i].length && on[i].every((c)=>stand.has(c)) ? [
307
+ s.name
308
+ ] : [])
309
+ ];
310
+ return [
311
+ printed(),
312
+ shape(driver, [
313
+ ...answers,
314
+ ...strays
315
+ ]),
316
+ ...strays
317
+ ].join(' ');
318
+ };
319
+ // Everything a component's first write may make (./raise.ts): the store's
320
+ // own schema, and what its host keeps beside it over component tables.
321
+ let makes = ()=>units(vocab, base.derived, !!driver.file, base.over?.(vocab));
322
+ // Raise the tables of `given` the file lacks, keeping the survey and an
323
+ // install receipt that stood before standing after.
324
+ let raising = (given)=>{
325
+ let before = surveyed(driver, vocab, base.derived);
326
+ let receipt = installation(driver);
327
+ let strays = receipt?.schema.split(' ').slice(2) ?? [];
328
+ let current = receipt?.schema == marked(strays);
329
+ let stats = receipt?.statistics;
330
+ let had = stats && new Set(analyzable(driver));
331
+ let made = raise(driver, vocab, given, makes());
332
+ raisedSurvey(driver, vocab, base.derived, before, made);
333
+ if (!made.length) return made;
334
+ // An install receipt that stood before stands after: what a first write
335
+ // makes is no change an install answers for. Its statistics remember the
336
+ // tables made as empty, as they were when an install made them.
337
+ let schema = current ? marked(strays) : receipt?.schema;
338
+ if (stats && schema) {
339
+ let fresh = analyzable(driver).filter((t)=>!had.has(t));
340
+ analyzedAt(driver, schema, emptied(stats, fresh));
341
+ } else if (current) meta(driver).set(SCHEMA, schema);
342
+ return made;
343
+ };
344
+ // The bundles a write names, ready to be written: each component one gives
345
+ // a value whose table waits for its first write is raised first, in the
346
+ // write's transaction (./raise.ts); a component one takes away that has no
347
+ // table is left out, since no entity wears it.
348
+ let readied = (bundles)=>{
349
+ let given = new Set(), taken = false;
350
+ for (let b of bundles){
351
+ for (let [name, c] of comps(b)){
352
+ if (c == null) taken = true;
353
+ else given.add(name);
354
+ }
355
+ }
356
+ if (given.size && unraised(driver, vocab).some((c)=>given.has(c))) {
357
+ raising(given);
358
+ }
359
+ if (!taken) return bundles;
360
+ let missing = new Set(unraised(driver, vocab));
361
+ if (!missing.size) return bundles;
362
+ return bundles.map((b)=>{
363
+ let gone = comps(b).filter(([n, c])=>c == null && missing.has(n));
364
+ if (!gone.length) return b;
365
+ let kept = {
366
+ ...b
367
+ };
368
+ for (let [n] of gone)delete kept[n];
369
+ return kept;
370
+ });
371
+ };
372
+ let identity = (eids, comps)=>get(driver, vocab, eids, opts(), comps, unsettled);
373
+ let report = base.report ?? logged;
374
+ // Whether this store's vocabulary declares archetypes, so its queries are
375
+ // planned by them and its reads show them. Their descriptors are never
376
+ // numbered: no component of theirs declares a letter.
377
+ let classified = !!vocab.comp('archetype') && keeping;
378
+ let memo = memoized(driver, vocab, base.derived, base.memory);
379
+ // A query's rows, from memory while the tables its answer stands on are
380
+ // unwritten (./memo.ts `answer`), in the one snapshot that decides both. A
381
+ // Where a caller's options leave a read's entities as the store's own get
382
+ // reads them, the get to read them through.
383
+ let policies = (o, within = false)=>{
384
+ let tables = new Set(within ? [
385
+ 'tombstone'
386
+ ] : [
387
+ 'entity',
388
+ 'tombstone'
389
+ ]);
390
+ let scope = o.visibility;
391
+ for (let query of [
392
+ scope?.entity,
393
+ ...Object.values(scope?.components ?? {})
394
+ ]){
395
+ if (!query) continue;
396
+ let names = basis(vocab, ast(query), base.derived, false, within);
397
+ if (!names) return undefined;
398
+ for (let name of names)tables.add(name);
399
+ }
400
+ for (let name of Object.keys(scope?.components ?? {}))tables.add(name);
401
+ return [
402
+ ...tables
403
+ ];
404
+ };
405
+ let reading = (o, fetch = cached)=>({
406
+ fetch: (eids, comps)=>fetch(eids, comps, false),
407
+ permit: (eids, components, run, graves)=>{
408
+ if (!eids.length) return [];
409
+ let selected = new Set(eids);
410
+ let queries = [
411
+ o.visibility?.entity,
412
+ ...components.map((c)=>o.visibility?.components?.[c])
413
+ ].filter((q)=>!!q);
414
+ let compiled = queries.map((q)=>tested(ast(q), true));
415
+ let tests = compiled.every((t)=>!!t) ? compiled : undefined;
416
+ let test = tests && ((b)=>selected.has(b.entity.eid) && tests.every((t)=>t(b)));
417
+ let names = queries.flatMap((q)=>basis(vocab, ast(q), base.derived) ?? []);
418
+ if (tests && policies(o)) {
419
+ let found = fetch(eids, [
420
+ ...new Set(names)
421
+ ]);
422
+ // A deleted entity is judged by its history, which only the store's
423
+ // statement reads (@yaks/sql `ghostly`).
424
+ let history = Object.values(o.backed ?? base.backed ?? {}).some((b)=>b.held && b.about);
425
+ if (!graves || !found.some(dead) || !history) {
426
+ return found.filter((b)=>!dead(b) && test(b)).map((b)=>({
427
+ eid: b.entity.eid
428
+ }));
429
+ }
430
+ }
431
+ return memo.answer(JSON.stringify([
432
+ 'permit',
433
+ eids,
434
+ components,
435
+ o.visibility,
436
+ !!graves
437
+ ]), ()=>policies(o), run, ()=>({
438
+ query: graves ? undefined : test,
439
+ membership: true
440
+ }));
441
+ }
442
+ });
443
+ let known = (o)=>Object.keys(o).every((k)=>UNREAD.has(k) || k == 'visibility');
444
+ let virtual = (eids, o)=>Object.values(o.tags ?? {}).some((tag)=>eids.some((eid)=>idOf(tag, eid) != null));
445
+ let reused = (eids, comps, o, run, pending = owing())=>{
446
+ if (!policies(o) || virtual(eids, o)) return run();
447
+ // Registries are fixed per store. A per-call replacement is unknown and
448
+ // bypasses reuse; the remaining effective inputs belong in the key, the
449
+ // long lists of names as their numbers (@yaks/sql `listed`).
450
+ let key = ()=>{
451
+ let { derived: _d, backed: _b, tags: _t, extend: _e, archetypes: _a, absent, missingIndexes, ...inputs } = o;
452
+ return keyed([
453
+ 'get',
454
+ eids,
455
+ comps,
456
+ inputs,
457
+ pending,
458
+ listed(absent),
459
+ listed(missingIndexes)
460
+ ]);
461
+ };
462
+ return memo.view(key, run, comps);
463
+ };
464
+ let kept = (fetch, eids, comps, refresh = true, pending = owing())=>{
465
+ let o = opts();
466
+ let run = ()=>o.visibility || virtual(eids, o) ? fetch(eids, comps) : memo.get(fetch, eids, comps, refresh);
467
+ return refresh ? reused(eids, comps, o, run, pending) : run();
468
+ };
469
+ let cached = (eids, comps, refresh = true)=>kept(identity, eids, comps, refresh);
470
+ let viewed = (eids, comps, o, fetch = cached, pending = owing(), answered = false)=>{
471
+ let effective = {
472
+ ...opts(),
473
+ ...o
474
+ };
475
+ let eligible = known(o);
476
+ // With no policy to apply, an option the statement is the same under
477
+ // leaves an identity read as memory holds it.
478
+ if (!effective.visibility && eligible) return fetch(eids, comps);
479
+ let run = ()=>get(driver, vocab, eids, effective, comps, unsettled, eligible && !base.visibility && !virtual(eids, effective) ? reading(effective, fetch) : undefined, answered);
480
+ return eligible ? reused(eids, comps, effective, run, pending) : run();
481
+ };
482
+ let fetched = (o = {}, fetch = cached, pending = owing)=>Object.keys(o).every((k)=>k != 'now' && (UNREAD.has(k) || k == 'visibility')) ? (eids, comps, answered)=>viewed(eids, comps, o, fetch, pending(), answered) : undefined;
483
+ let tests = new WeakMap();
484
+ let tested = (query, exactIds = false)=>{
485
+ let known = Object.isFrozen(query) ? tests.get(query) : undefined;
486
+ if (known?.has(exactIds)) return known.get(exactIds);
487
+ let test;
488
+ if (basis(vocab, query, base.derived) && local(vocab, query)) {
489
+ try {
490
+ test = filter(query, vocab, {
491
+ exactIds
492
+ });
493
+ } catch {
494
+ // SQL decides predicates the local matcher cannot judge.
495
+ }
496
+ }
497
+ if (Object.isFrozen(query)) {
498
+ if (!known) tests.set(query, known = new Map());
499
+ known.set(exactIds, test);
500
+ }
501
+ return test;
502
+ };
503
+ let resolved = (query, o)=>{
504
+ if (!o.visibility?.entity) return undefined;
505
+ let operands = new Set();
506
+ let visit = (c)=>{
507
+ if (c.kind == 'and' || c.kind == 'or') return c.clauses.forEach(visit);
508
+ // A path through a reference, or one read from the far side
509
+ // (`.members_space.member.person=P`), compares no reference of its own.
510
+ if (c.kind != 'pred' || c.where || c.op != '=' || !literals(c.value)?.length || c.path.length > 2 || vocab.assoc(c.path[0])) return;
511
+ let hops = vocab.aim(c.path.join('.'), bare(c)), h = hops[0];
512
+ let prop = h && vocab.prop(h.comp, h.prop);
513
+ if (hops.length != 1 || !prop?.ref || prop.computed || base.derived?.[`${h.comp}.${h.prop}`] || vocab.comp(prop.ref)?.computed) return;
514
+ for (let eid of literals(c.value))operands.add(eid);
515
+ };
516
+ visit(query);
517
+ if (!operands.size) return undefined;
518
+ let eids = [
519
+ ...operands
520
+ ];
521
+ // A deleted entity the scope sees is admitted too, so its history is
522
+ // asked by its id (@yaks/sql `ghostly`).
523
+ let allowed = reading(o).permit(eids, [], ()=>driver.query(admitted(eids, sourceScreen(readingVocab(driver, vocab), {
524
+ ...opts(),
525
+ ...o,
526
+ graves: true
527
+ }))), true);
528
+ let ids = spines(driver, allowed.map((r)=>String(r.eid)));
529
+ return Object.fromEntries(eids.map((eid)=>[
530
+ eid,
531
+ ids.get(eid)?.id ?? null
532
+ ]));
533
+ };
534
+ let asked = (query, o = {})=>{
535
+ let catalogued = keeping;
536
+ let owing = catalogued && !!book?.owed().length;
537
+ // A read asking for graves is the statement's: it alone judges the
538
+ // deleted (@yaks/sql `ghostly`).
539
+ if (o.visibility && !owing && !o.graves && simple(vocab, query) && !Object.keys(o.visibility.components ?? {}).length && (!o.visibility.entity || local(vocab, ast(o.visibility.entity))) && policies(o) && basis(vocab, query, base.derived, catalogued)) {
540
+ let { visibility: _visibility, ...plain } = o;
541
+ let raw = asked(query, plain);
542
+ let permitted = new Set(reading(o).permit(raw.map((r)=>String(r.eid)), [], ()=>[]).map((r)=>String(r.eid)));
543
+ return raw.filter((r)=>permitted.has(String(r.eid)));
544
+ }
545
+ // What a caller's options change of the statement: its order of pages; a
546
+ // `now` matters only to time phrases, which are read every time.
547
+ let unread = Object.keys(o).some((k)=>!UNREAD.has(k) && k != 'visibility');
548
+ let tables;
549
+ let dependencies = ()=>{
550
+ tables = basis(vocab, query, base.derived, catalogued);
551
+ if (o.visibility) {
552
+ let scoped = policies(o, !!tables && !tables.includes('entity'));
553
+ tables = tables && scoped ? [
554
+ ...new Set([
555
+ ...tables,
556
+ ...scoped
557
+ ])
558
+ ] : undefined;
559
+ }
560
+ return tables;
561
+ };
562
+ let key = JSON.stringify([
563
+ query,
564
+ !!o.storageOrder,
565
+ !!o.unordered,
566
+ o.visibility
567
+ ]);
568
+ let prove = ()=>{
569
+ // A retained proof reads the same query and policy even if a caller
570
+ // later edits the AST or visibility object it handed this read.
571
+ let [query, , , visibility] = JSON.parse(key);
572
+ let o = {
573
+ visibility
574
+ };
575
+ let standing = query;
576
+ let strict;
577
+ let shape;
578
+ let identities = (c)=>c.kind == 'and' || c.kind == 'or' ? c.clauses.every(identities) : c.kind == 'pred' && !c.where || c.kind == 'every';
579
+ let fixed = (c)=>{
580
+ if (c.kind == 'and' || c.kind == 'or') return c.clauses.every(fixed);
581
+ if (c.kind != 'pred') return true;
582
+ let leaf = vocab.aim(c.path.join('.'), bare(c)).at(-1);
583
+ return !leaf || vocab.prop(leaf.comp, leaf.prop)?.category != 'ref' || !c.not && c.op == '=' && !!literals(c.value)?.length;
584
+ };
585
+ if (o.visibility) {
586
+ let policy = o.visibility.entity;
587
+ let proof = basis(vocab, query, base.derived) && rooted(vocab, query);
588
+ // Aspect policies can change what a predicate reads. A whole-entity
589
+ // policy instead composes with an ordinary local membership test.
590
+ if (!Object.keys(o.visibility.components ?? {}).length && (local(vocab, query) || !!proof) && (!policy || local(vocab, ast(policy)))) {
591
+ let ordinary = tested(query) ?? (proof ? proof.test : undefined);
592
+ if (ordinary && !fixed(query)) ordinary = undefined;
593
+ let allowed = policy && tested(ast(policy), true);
594
+ standing = ordinary && (!policy || allowed) ? (b)=>ordinary(b) && (!allowed || allowed(b)) : undefined;
595
+ if (standing && proof) shape = proof.shape;
596
+ // A reference's target can become hidden without its source changing.
597
+ // Local source predicates cannot prove that policy change irrelevant.
598
+ if (!simple(vocab, query)) {
599
+ let scope = policies(o, !!tables && !tables.includes('entity'));
600
+ strict = scope && [
601
+ ...new Set([
602
+ ...scope,
603
+ ...proof ? proof.strict : []
604
+ ])
605
+ ];
606
+ }
607
+ } else standing = undefined;
608
+ }
609
+ return {
610
+ query: standing,
611
+ membership: identities(query) && local(vocab, query),
612
+ strict,
613
+ shape
614
+ };
615
+ };
616
+ return unit(driver, ()=>memo.answer(key, owing || unread ? undefined : dependencies, ()=>rows(driver, vocab, query, {
617
+ ...opts(),
618
+ ...o,
619
+ references: resolved(query, o) ?? o.references
620
+ }), prove), 'read');
621
+ };
622
+ let holding = (eids)=>{
623
+ if (!base.held) return heldBy(driver, eids, book, mend);
624
+ let ids = [
625
+ ...spines(driver, eids).values()
626
+ ].map((r)=>r.id);
627
+ return [
628
+ ...new Set([
629
+ ...base.held(ids, tables(vocab)).values()
630
+ ].flat())
631
+ ];
632
+ };
633
+ let graves = burying(driver, vocab);
634
+ let tx = {
635
+ read: (query, signalled, comps)=>{
636
+ let o = asking(signalled);
637
+ return metered(()=>read(driver, vocab, query, {
638
+ ...opts(),
639
+ ...o
640
+ }, comps, (q)=>asked(q, o), fetched(o), unsettled), {
641
+ what: named(query)
642
+ });
643
+ },
644
+ get: identity,
645
+ // The cascade reads the file as this snapshot's reads do (./reader.ts):
646
+ // a property read as derived has no column there to point back through.
647
+ doom: (eids)=>{
648
+ let o = opts();
649
+ return doom(driver, vocab, eids, {
650
+ absent: o.absent,
651
+ lacking: Object.keys(o.derived ?? {}),
652
+ unindexed: o.missingIndexes
653
+ });
654
+ },
655
+ // A rule reads the file as this snapshot's reads do: a word no write
656
+ // has raised a table for, or a property derived from one, reads as worn
657
+ // by nobody (./raise.ts).
658
+ bindings: (matches, bundles, covers)=>bindings(driver, vocab, matches, bundles, covers, opts()),
659
+ patch: (given)=>{
660
+ let bundles = readied(given);
661
+ return made(memo.patch(bundles, (known)=>patch(driver, vocab, bundles, base.number, undefined, known, undefined, undefined, base.names)));
662
+ },
663
+ remove: (entities)=>{
664
+ let at = new Date().toISOString();
665
+ memo.removes(entities.map((e)=>e.eid), at, ()=>remove(driver, vocab, entities, holding(entities.map((e)=>e.eid)), at));
666
+ },
667
+ // Bookkeeping leaves whole: rows, identity and all (./write.ts `erase`).
668
+ discard: (entities)=>{
669
+ let eids = entities.map((e)=>e.eid);
670
+ memo.writes(()=>erase(driver, entities, holding(eids)), ()=>eids);
671
+ },
672
+ revive: (eids)=>memo.writes(()=>revive(driver, eids), ()=>eids),
673
+ prune: (eids)=>memo.writes(()=>prune(driver, vocab, eids), ()=>eids),
674
+ buried: (before, page)=>graves(before, page)
675
+ };
676
+ // An entity met with no archetype to go by is a failure: every door
677
+ // classifies what it wrote before its unit closes. It is reported, and
678
+ // repaired by classifying it from the rows it holds, the one place a table
679
+ // is asked what it holds (./archetype.ts `classify`).
680
+ // One wording, so it is one bug wherever it is told; the entities ride
681
+ // beside it.
682
+ let lost = (eids)=>report(Object.assign(new Error('entities had no archetype, and were classified from the rows held'), {
683
+ name: 'Unpointed',
684
+ eids: eids.slice(0, 8)
685
+ }));
686
+ let mend = (eids)=>{
687
+ if (!migrating()) lost(eids);
688
+ memo.writes(()=>unit(driver, ()=>classify(driver, eids)), ()=>eids, true);
689
+ };
690
+ // A read, and once more after the repair where it met such an entity. A
691
+ // store that cannot write (a mode's) only reports.
692
+ let mending = (read)=>{
693
+ try {
694
+ return read();
695
+ } catch (e) {
696
+ if (!(e instanceof Unpointed) || !keeping) throw e;
697
+ mend(e.eids);
698
+ return read();
699
+ }
700
+ };
701
+ // Every unit keeps every pointer in step, whichever door wrote:
702
+ // @yaks/graph's tracker, a hook writing through a detached transaction, a
703
+ // script patching through `tx`. The connection's ledger hears each row that
704
+ // came or went and each pointer written (./archetype.ts `ledger`); what it
705
+ // still owes when the body returns is classified in the same unit, each
706
+ // entity from its pointer and what the ledger heard, so no table is read.
707
+ // Through the graph that is nothing, since its tracker points every entity
708
+ // it moved, so its writes gain no read. Removal clears the tables its
709
+ // entities hold (`heldBy`); the dead no pointer has been written for since
710
+ // are pointed at the tombstone set (`entomb`), which reads nothing.
711
+ //
712
+ // A unit opened inside another (a graph applied in a caller's transaction)
713
+ // shares the ledger, which follows the connection's savepoints: it reads
714
+ // and removes what an entity holds rather than what its pointer said before
715
+ // the outer one began, and settles whatever the transaction owes so far.
716
+ let tracked = (book)=>{
717
+ let l = book;
718
+ // A birth is minted in the class its shape last finished in, and its
719
+ // pointer is written again only where it finishes elsewhere.
720
+ let remembered = births(driver);
721
+ let born = {
722
+ ...remembered,
723
+ born: (eid, tables, id)=>{
724
+ remembered.born(eid, tables, id);
725
+ l.born(eid);
726
+ }
727
+ };
728
+ let owed = l.owed;
729
+ // An entity whose rows moved in this transaction is read from what it
730
+ // holds; every other one as its pointer says, or from memory.
731
+ let getting = (eids, comps, refresh = true)=>{
732
+ let pending = owed();
733
+ let moving = new Set(pending);
734
+ let moved = eids.filter((eid)=>moving.has(eid));
735
+ if (!moved.length) return cached(eids, comps, refresh);
736
+ let rest = eids.filter((eid)=>!moving.has(eid));
737
+ let at = new Map([
738
+ ...kept((ids, names)=>get(driver, vocab, ids, opts(), names, unsettled), moved, comps, refresh, pending),
739
+ ...rest.length ? cached(rest, comps, refresh) : []
740
+ ].map((b)=>[
741
+ b.entity.eid,
742
+ b
743
+ ]));
744
+ return eids.flatMap((eid)=>at.get(eid) ?? []);
745
+ };
746
+ let settle = ()=>{
747
+ let dead = l.buried();
748
+ // A birth minted in the class it finished in owes no pointer, and
749
+ // nothing is asked of the file for it.
750
+ let owed = l.owed().filter((eid)=>{
751
+ let held = l.held(eid, null);
752
+ if (!held || !remembered.settled(eid, held)) return true;
753
+ if (classified) memo.pointed(eid, setOf(driver, held).eid);
754
+ l.pointed(eid);
755
+ return false;
756
+ });
757
+ if (!dead.length && !owed.length) return;
758
+ let unknown = [];
759
+ memo.writes(()=>{
760
+ let buried = entomb(driver, dead);
761
+ let sorted = classify(driver, owed, (eid, pointed)=>{
762
+ let held = l.held(eid, pointed);
763
+ if (!held) unknown.push(eid);
764
+ return held;
765
+ }, remembered.finished);
766
+ return buried || sorted;
767
+ }, // A pointer is part of what a read gives only where the store shows
768
+ // archetypes: elsewhere what memory holds of these entities stands.
769
+ ()=>classified ? [
770
+ ...dead,
771
+ ...owed
772
+ ] : [], // A class first worn mints its descriptor (./archetype.ts), an
773
+ // entity the write does not name; one a store shows no reader of.
774
+ (minted)=>classified && minted);
775
+ if (unknown.length && !migrating()) lost(unknown);
776
+ for (let eid of [
777
+ ...dead,
778
+ ...owed
779
+ ])l.pointed(eid);
780
+ };
781
+ return {
782
+ tx: {
783
+ ...tx,
784
+ get: (eids, comps)=>mending(()=>getting(eids, comps)),
785
+ // Queries overlay the shapes the open writer knows on its catalog;
786
+ // no intermediate classification is persisted to answer a read.
787
+ read: (query, signalled, comps)=>{
788
+ if (!owed().length) {
789
+ return mending(()=>tx.read(query, signalled, comps));
790
+ }
791
+ let o = asking(signalled);
792
+ let archetypes = migrating() ? unindexed : catalog(driver, pendingShapes(driver, book));
793
+ let bound = {
794
+ ...opts(),
795
+ ...o,
796
+ archetypes
797
+ };
798
+ return metered(()=>mending(()=>read(driver, vocab, query, bound, comps, (q)=>rows(driver, vocab, q, bound), fetched(o, getting, owed), unsettled)), {
799
+ what: named(query)
800
+ });
801
+ },
802
+ patch: (given)=>{
803
+ let bundles = readied(given);
804
+ let minted = made(memo.patch(bundles, (known)=>patch(driver, vocab, bundles, base.number, l.moved, known, born, unsettled, base.names)));
805
+ for (let b of bundles){
806
+ if (b.entity.archetype !== undefined) l.pointed(b.entity.eid);
807
+ }
808
+ return minted;
809
+ },
810
+ prune: (eids)=>{
811
+ settle();
812
+ tx.prune(eids);
813
+ },
814
+ remove: (entities)=>{
815
+ let eids = entities.map((e)=>e.eid);
816
+ let at = new Date().toISOString();
817
+ memo.removes(eids, at, ()=>remove(driver, vocab, entities, heldBy(driver, eids, l, mend), at));
818
+ for (let eid of eids)l.removed(eid);
819
+ },
820
+ // Erased, an entity leaves nothing to point: the ledger forgets it.
821
+ discard: (entities)=>{
822
+ let eids = entities.map((e)=>e.eid);
823
+ memo.writes(()=>erase(driver, entities, heldBy(driver, eids, l, mend)), ()=>eids);
824
+ for (let eid of eids)l.pointed(eid);
825
+ },
826
+ revive: (eids)=>memo.writes(()=>revive(driver, eids, l.moved), ()=>eids)
827
+ },
828
+ settle
829
+ };
830
+ };
831
+ // A file store is brought to its schema by its host as it opens
832
+ // (./follow.ts), never by an operation.
833
+ // In-memory stores are private scratch values and may prepare themselves.
834
+ let ready = false;
835
+ let prepare = ()=>base.deferred ? upkeep.prepare() : backfill(driver);
836
+ // A store numbering by series moves a spine that keeps a number unique on
837
+ // its own (./ddl.ts `respine`), before the indexes on it are raised. The
838
+ // move writes only the numbered rows, once each, and no reference to them
839
+ // is checked, so a Durable Object's directory of 43,000 moves in its
840
+ // install. A file's spine is moved by its host's migration.
841
+ let respining = ()=>!!base.number && !driver.file && sole(driver);
842
+ // Counts eager are made by install; lazy ones by the first count asked, but
843
+ // where they stand, install mends what keeps them, as a new print
844
+ // (`POPULATION_VERSION`) owes.
845
+ let counted = ()=>{
846
+ if (!classified || base.counts != 'eager' && !torn(driver)) return;
847
+ unit(driver, ()=>population(driver));
848
+ };
849
+ let install = (beside = [])=>{
850
+ storeAs(driver, vocab);
851
+ let left = [];
852
+ let mark = marked;
853
+ let print = printed();
854
+ let receipt;
855
+ let matches = ()=>{
856
+ receipt = installation(driver);
857
+ let was = receipt?.schema;
858
+ return was == mark(was?.split(' ').slice(2) ?? []) && !respining();
859
+ };
860
+ // The fast path only reads. A changed file is inspected again *after*
861
+ // taking its write lock, and tables, growth and indexes commit together.
862
+ let unchanged = matches();
863
+ if (!unchanged) {
864
+ let clean = false;
865
+ let seal = ()=>{
866
+ epoch(driver);
867
+ recorded(driver);
868
+ if (keeping) prepare();
869
+ receipt = {
870
+ schema: mark(componentTables(driver, plan(vocab, base.derived, !!driver.file).made)),
871
+ statistics: receipt?.statistics
872
+ };
873
+ meta(driver).set(SCHEMA, receipt.schema);
874
+ };
875
+ let make = ()=>unit(driver, ()=>{
876
+ if (matches()) return;
877
+ // Retired first: a component may take a name an index held.
878
+ for (let stmt of base.partial ? [] : retired(driver, vocab)){
879
+ driver.query(stmt);
880
+ }
881
+ // A component's own objects wait for its first write (./raise.ts).
882
+ let tables = holds(driver, vocab, retabled(driver, vocab, base.derived));
883
+ erect(driver, tables);
884
+ let after = (comp)=>[
885
+ ...tables,
886
+ ...indexed(vocab, true),
887
+ ...beside
888
+ ].filter((s)=>(s.t == 'create index' || s.t == 'create trigger') && s.on == comp);
889
+ let kept = new Set();
890
+ let unfit = fit(driver, vocab, (comp, r)=>{
891
+ let owes = reshape(driver, comp, r, after(comp), base.sizes);
892
+ if (owes) kept.add(comp);
893
+ return owes;
894
+ });
895
+ forgo(driver, kept);
896
+ left = [
897
+ ...unfit,
898
+ ...respining() ? respine(driver) : [],
899
+ ...build(driver, holds(driver, vocab, built(driver, vocab)), base.sizes, base.deferred),
900
+ ...besides.length ? versioned(driver, vocab, !!base.paced) : []
901
+ ];
902
+ left.forEach(report);
903
+ clean = !left.length;
904
+ // Memory templates keep schema, never a store's lineage identity.
905
+ if (driver.file && clean) seal();
906
+ });
907
+ // Tables are rebuilt with foreign keys on. A rebuilt table is a
908
+ // component's: it references `entity` and nothing references it, so
909
+ // dropping it checks nothing and each row put back finds its entity.
910
+ // The pragma is never set here: SQLite ignores it inside a transaction,
911
+ // and workerd holds one open from a turn's first write, so an `on` after
912
+ // the rebuild could leave a Durable Object without its keys.
913
+ // Templates are only for fresh in-memory files; file installs always
914
+ // inspect their standing schema under BEGIN IMMEDIATE.
915
+ let fresh = !installed(driver) && !anyStanding(driver, vocab);
916
+ fresh && driver.template ? driver.template(print, make) : make();
917
+ if (!driver.file) {
918
+ unit(driver, ()=>{
919
+ epoch(driver);
920
+ recorded(driver);
921
+ if (keeping) prepare();
922
+ if (fresh || clean) {
923
+ receipt = {
924
+ schema: mark(componentTables(driver, plan(vocab, base.derived, !!driver.file).made)),
925
+ statistics: receipt?.statistics
926
+ };
927
+ meta(driver).set(SCHEMA, receipt.schema);
928
+ }
929
+ });
930
+ }
931
+ }
932
+ counted();
933
+ let owe = ()=>{
934
+ let statistics = analyzed(driver, receipt?.statistics, unchanged);
935
+ if (statistics && receipt) analyzedAt(driver, receipt.schema, statistics);
936
+ };
937
+ // A file asks what it owes without the write lock, and takes it only when
938
+ // there is a receipt to write and nobody holds it: beside another
939
+ // connection's writer the open goes on without waiting, and the next open
940
+ // finds the same debt from the file (./owe.ts).
941
+ let owing = ()=>analyzed(driver, receipt?.statistics, unchanged);
942
+ if (driver.statistics && !driver.file) unit(driver, owe);
943
+ else if (driver.statistics && unit(driver, owing, 'read')) {
944
+ try {
945
+ unwaiting(driver, ()=>unit(driver, owe));
946
+ } catch (e) {
947
+ if (!busy(e)) throw e;
948
+ }
949
+ }
950
+ ready = true;
951
+ return left;
952
+ };
953
+ let ensure = ()=>{
954
+ if (driver.file || ready) return;
955
+ if (base.schemaReady?.()) ready = true;
956
+ else install();
957
+ };
958
+ // What a write minted: on a branch, each pointed as main sees it.
959
+ let made = base.mode && 'branch' in base.mode ? (minted)=>(unborn(driver, minted.map((e)=>e.eid)), minted) : (minted)=>minted;
960
+ // A store with history has branches; a mode's store is a branch's,
961
+ // or reads the past.
962
+ let branches = base.history && !base.mode ? branching(driver, vocab, base.history, opts) : undefined;
963
+ return {
964
+ ...branches ? {
965
+ branches
966
+ } : {},
967
+ statements: keeping ? Object.assign(statements(driver), {
968
+ archetypes: true
969
+ }) : base.mode ? {
970
+ ...statements(driver),
971
+ archetypes: false,
972
+ // A mode's driver is bound to another mode under the store
973
+ // (./mode.ts).
974
+ get mode () {
975
+ return base.mode;
976
+ }
977
+ } : statements(driver),
978
+ checks: diagnostics(driver),
979
+ migrations: migrations(driver),
980
+ maintain: upkeep.work,
981
+ revision: ()=>revision(driver, 'data'),
982
+ newest: (comp)=>newest(driver, vocab, comp),
983
+ ...driver.watch ? {
984
+ watch: (comp, heard)=>watch(driver, vocab, comp, heard)
985
+ } : {},
986
+ worn: worn(vocab, base.derived),
987
+ // A caller replaying these statements over a standing file must add new
988
+ // columns before creating their indexes. `schema()` alone describes a
989
+ // fresh file; it cannot see what a standing table still lacks.
990
+ ddl: ()=>[
991
+ ...tabled(vocab, base.derived, !!driver.file),
992
+ ...grown(vocab, standing(driver, vocab)),
993
+ ...indexed(vocab, true)
994
+ ],
995
+ grown: ()=>grown(vocab, standing(driver, vocab)),
996
+ print: printed,
997
+ install,
998
+ raise: (comps = tables(vocab))=>{
999
+ ensure();
1000
+ return unit(driver, ()=>raising(comps));
1001
+ },
1002
+ analyze: (tables = Infinity)=>{
1003
+ if (driver.statistics) daily(driver, [
1004
+ statistics
1005
+ ], Date.now());
1006
+ let left = installation(driver)?.statistics?.owed?.length ?? 0;
1007
+ for(let n = 0; n < tables && left; n++)left = analyze(driver) ?? 0;
1008
+ return left;
1009
+ },
1010
+ read: (query, o, comps)=>{
1011
+ ensure();
1012
+ return metered(()=>mending(()=>unit(driver, ()=>tx.read(query, o, comps), 'read')), {
1013
+ what: named(query)
1014
+ });
1015
+ },
1016
+ rows: (query, signalled)=>{
1017
+ ensure();
1018
+ let o = asking(signalled);
1019
+ let parsed = ast(query);
1020
+ if (classified && !owing().length && base.counts != 'eager' && cardinality(parsed, vocab, {
1021
+ ...opts(),
1022
+ ...o
1023
+ })) {
1024
+ unit(driver, ()=>population(driver));
1025
+ }
1026
+ return metered(()=>mending(()=>asked(parsed, o)), {
1027
+ what: named(query)
1028
+ });
1029
+ },
1030
+ screen: (query, o)=>{
1031
+ ensure();
1032
+ return screened(driver, vocab, query, {
1033
+ ...opts(),
1034
+ ...asking(o)
1035
+ });
1036
+ },
1037
+ buried: (before, page)=>{
1038
+ ensure();
1039
+ return unit(driver, ()=>graves(before, page), 'read');
1040
+ },
1041
+ get file () {
1042
+ return located(driver);
1043
+ },
1044
+ measure: (signal)=>measure(driver, signal),
1045
+ get: (eids, comps, o)=>{
1046
+ if (!eids.length) return [];
1047
+ ensure();
1048
+ return metered(()=>mending(()=>unit(driver, ()=>viewed(eids, comps, asking(o) ?? {}), 'read')), {
1049
+ what: gotten(eids)
1050
+ });
1051
+ },
1052
+ purgeHistory: (eids)=>unit(driver, ()=>purgeHistory(driver, vocab, eids, opts())),
1053
+ retained: (values)=>unit(driver, ()=>retained(driver, values), 'read'),
1054
+ purgeTrash: (id)=>unit(driver, ()=>{
1055
+ driver.query(purgeTrashSql(id));
1056
+ }),
1057
+ trash: (eids, page)=>unit(driver, ()=>trashed(driver, vocab, eids, page), 'read'),
1058
+ tx: (body, { wait } = {})=>exclusive(driver, ()=>{
1059
+ if (base.mode && 'at' in base.mode) {
1060
+ throw new Refused(`as of transaction ${base.mode.at} the graph is read only`);
1061
+ }
1062
+ ensure();
1063
+ let run = (begun)=>unit(driver, ()=>{
1064
+ begun();
1065
+ return within(driver, (clock)=>{
1066
+ let cached = (t)=>({
1067
+ ...t,
1068
+ get: (eids, comps)=>kept(t.get, eids, comps),
1069
+ ...base.history ? {
1070
+ clock
1071
+ } : {}
1072
+ });
1073
+ let retaining = (t)=>preserving(t, vocab, (id, at, rows)=>{
1074
+ for (let stmt of retainSql(id, at, rows))driver.query(stmt);
1075
+ });
1076
+ if (!book) return body(retaining(cached(tx)));
1077
+ let { tx: t, settle } = tracked(book);
1078
+ let tracing = context();
1079
+ // An async body settles what it owes before the unit closes, as the
1080
+ // unit waits for it (./unit.ts).
1081
+ return after(body(retaining(base.history ? {
1082
+ ...t,
1083
+ clock
1084
+ } : t)), (out)=>{
1085
+ if (tracing) scope(tracing, settle);
1086
+ else settle();
1087
+ return out;
1088
+ });
1089
+ });
1090
+ }, 'write', {
1091
+ wait: false,
1092
+ report
1093
+ });
1094
+ return wait === false ? run(()=>{}) : enter(run, (ms)=>sleep(ms, undefined, base.clock));
1095
+ })
1096
+ };
1097
+ };
1098
+ export * from "./migration.js";
1099
+ export { add, follow, forget, grow, lacking, printFor, printOf, shed, unseat } from "./follow.js";
1100
+ export { doom } from "./doom.js";
1101
+ export { branch, branching, branchOf, seeding, Unseeded } from "./branches.js";
1102
+ export { moded } from "./mode.js";
1103
+ //# sourceMappingURL=mod.js.map