@yaks/blob 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 (172) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +946 -2
  3. package/_dist/accepts.d.ts +38 -0
  4. package/_dist/accepts.d.ts.map +1 -0
  5. package/_dist/artifact.d.ts +29 -0
  6. package/_dist/artifact.d.ts.map +1 -0
  7. package/_dist/attachment.d.ts +53 -0
  8. package/_dist/attachment.d.ts.map +1 -0
  9. package/_dist/backend.d.ts +20 -0
  10. package/_dist/backend.d.ts.map +1 -0
  11. package/_dist/broken.d.ts +24 -0
  12. package/_dist/broken.d.ts.map +1 -0
  13. package/_dist/browser.d.ts +27 -0
  14. package/_dist/browser.d.ts.map +1 -0
  15. package/_dist/compare.d.ts +4 -0
  16. package/_dist/compare.d.ts.map +1 -0
  17. package/_dist/content_type.d.ts +20 -0
  18. package/_dist/content_type.d.ts.map +1 -0
  19. package/_dist/graph.d.ts +13 -0
  20. package/_dist/graph.d.ts.map +1 -0
  21. package/_dist/hydrate.d.ts +36 -0
  22. package/_dist/hydrate.d.ts.map +1 -0
  23. package/_dist/identify.d.ts +7 -0
  24. package/_dist/identify.d.ts.map +1 -0
  25. package/_dist/image.d.ts +37 -0
  26. package/_dist/image.d.ts.map +1 -0
  27. package/_dist/keywords.d.ts +10 -0
  28. package/_dist/keywords.d.ts.map +1 -0
  29. package/_dist/mime.d.ts +2 -0
  30. package/_dist/mime.d.ts.map +1 -0
  31. package/_dist/mod.d.ts +97 -0
  32. package/_dist/mod.d.ts.map +1 -0
  33. package/_dist/object-put.d.ts +2 -0
  34. package/_dist/object-put.d.ts.map +1 -0
  35. package/_dist/object.d.ts +175 -0
  36. package/_dist/object.d.ts.map +1 -0
  37. package/_dist/parts.d.ts +91 -0
  38. package/_dist/parts.d.ts.map +1 -0
  39. package/_dist/plugin.d.ts +38 -0
  40. package/_dist/plugin.d.ts.map +1 -0
  41. package/_dist/png.d.ts +14 -0
  42. package/_dist/png.d.ts.map +1 -0
  43. package/_dist/props.d.ts +20 -0
  44. package/_dist/props.d.ts.map +1 -0
  45. package/_dist/representation.d.ts +17 -0
  46. package/_dist/representation.d.ts.map +1 -0
  47. package/_dist/representation_rules.d.ts +3 -0
  48. package/_dist/representation_rules.d.ts.map +1 -0
  49. package/_dist/routes.d.ts +65 -0
  50. package/_dist/routes.d.ts.map +1 -0
  51. package/_dist/serve.d.ts +29 -0
  52. package/_dist/serve.d.ts.map +1 -0
  53. package/_dist/sha256.d.ts +26 -0
  54. package/_dist/sha256.d.ts.map +1 -0
  55. package/_dist/sqlite.d.ts +57 -0
  56. package/_dist/sqlite.d.ts.map +1 -0
  57. package/_dist/store.d.ts +41 -0
  58. package/_dist/store.d.ts.map +1 -0
  59. package/_dist/stream.d.ts +91 -0
  60. package/_dist/stream.d.ts.map +1 -0
  61. package/_dist/upload.d.ts +114 -0
  62. package/_dist/upload.d.ts.map +1 -0
  63. package/_dist/value.d.ts +62 -0
  64. package/_dist/value.d.ts.map +1 -0
  65. package/_dist/vocab.d.ts +13 -0
  66. package/_dist/vocab.d.ts.map +1 -0
  67. package/accepts.js +76 -0
  68. package/accepts.js.map +1 -0
  69. package/accepts.ts +95 -0
  70. package/artifact.js +50 -0
  71. package/artifact.js.map +1 -0
  72. package/artifact.ts +93 -0
  73. package/attachment.js +190 -0
  74. package/attachment.js.map +1 -0
  75. package/attachment.ts +201 -0
  76. package/backend.js +37 -0
  77. package/backend.js.map +1 -0
  78. package/backend.ts +44 -0
  79. package/broken.js +278 -0
  80. package/broken.js.map +1 -0
  81. package/broken.ts +217 -0
  82. package/browser.js +124 -0
  83. package/browser.js.map +1 -0
  84. package/browser.ts +179 -0
  85. package/compare.js +82 -0
  86. package/compare.js.map +1 -0
  87. package/compare.ts +90 -0
  88. package/content_type.js +43 -0
  89. package/content_type.js.map +1 -0
  90. package/content_type.ts +58 -0
  91. package/deno.json +1 -0
  92. package/fixed.js +53 -0
  93. package/fixed.js.map +1 -0
  94. package/fixed.ts +61 -0
  95. package/graph.js +15 -0
  96. package/graph.js.map +1 -0
  97. package/graph.ts +22 -0
  98. package/hydrate.js +69 -0
  99. package/hydrate.js.map +1 -0
  100. package/hydrate.ts +72 -0
  101. package/identify.js +38 -0
  102. package/identify.js.map +1 -0
  103. package/identify.ts +50 -0
  104. package/image.js +111 -0
  105. package/image.js.map +1 -0
  106. package/image.ts +120 -0
  107. package/keywords.js +28 -0
  108. package/keywords.js.map +1 -0
  109. package/keywords.ts +28 -0
  110. package/meta/blob.vocab.json +17 -0
  111. package/mime.js +72 -0
  112. package/mime.js.map +1 -0
  113. package/mime.ts +73 -0
  114. package/mod.js +97 -0
  115. package/mod.js.map +1 -0
  116. package/mod.ts +115 -0
  117. package/object-put.js +90 -0
  118. package/object-put.js.map +1 -0
  119. package/object-put.ts +114 -0
  120. package/object.js +369 -0
  121. package/object.js.map +1 -0
  122. package/object.ts +592 -0
  123. package/package.json +84 -4
  124. package/parts.js +354 -0
  125. package/parts.js.map +1 -0
  126. package/parts.ts +423 -0
  127. package/plugin.js +158 -0
  128. package/plugin.js.map +1 -0
  129. package/plugin.ts +184 -0
  130. package/png.js +74 -0
  131. package/png.js.map +1 -0
  132. package/png.ts +58 -0
  133. package/props.js +32 -0
  134. package/props.js.map +1 -0
  135. package/props.ts +47 -0
  136. package/purge.js +65 -0
  137. package/purge.js.map +1 -0
  138. package/purge.ts +72 -0
  139. package/representation.js +34 -0
  140. package/representation.js.map +1 -0
  141. package/representation.ts +44 -0
  142. package/representation_rules.js +44 -0
  143. package/representation_rules.js.map +1 -0
  144. package/representation_rules.ts +57 -0
  145. package/routes.js +454 -0
  146. package/routes.js.map +1 -0
  147. package/routes.ts +575 -0
  148. package/serve.js +196 -0
  149. package/serve.js.map +1 -0
  150. package/serve.ts +242 -0
  151. package/sha256.js +185 -0
  152. package/sha256.js.map +1 -0
  153. package/sha256.ts +210 -0
  154. package/sqlite.js +201 -0
  155. package/sqlite.js.map +1 -0
  156. package/sqlite.ts +250 -0
  157. package/store.js +40 -0
  158. package/store.js.map +1 -0
  159. package/store.ts +93 -0
  160. package/stream.js +203 -0
  161. package/stream.js.map +1 -0
  162. package/stream.ts +256 -0
  163. package/upload.js +256 -0
  164. package/upload.js.map +1 -0
  165. package/upload.ts +404 -0
  166. package/value.js +234 -0
  167. package/value.js.map +1 -0
  168. package/value.ts +281 -0
  169. package/vocab.js +27 -0
  170. package/vocab.js.map +1 -0
  171. package/vocab.json +123 -0
  172. package/vocab.ts +32 -0
package/sha256.ts ADDED
@@ -0,0 +1,210 @@
1
+ // SHA-256 as a state carried from one piece of bytes to the next. An upload in
2
+ // parts is checked against its file's hash as each part passes (parts.ts), so
3
+ // the whole is never read back to be hashed: each part is hashed on from the
4
+ // state the bytes before it left, and the states chain. WebCrypto hashes only
5
+ // bytes held whole in memory and gives no state to carry, so this is FIPS
6
+ // 180-4 written out: the same digest, as lowercase hex, and the same state the
7
+ // served client records at each part's start (workers/yak/public/client.js).
8
+
9
+ // The first 32 bits of the fractional parts of the cube roots of the first 64
10
+ // primes.
11
+ let K = new Uint32Array([
12
+ 0x428a2f98,
13
+ 0x71374491,
14
+ 0xb5c0fbcf,
15
+ 0xe9b5dba5,
16
+ 0x3956c25b,
17
+ 0x59f111f1,
18
+ 0x923f82a4,
19
+ 0xab1c5ed5,
20
+ 0xd807aa98,
21
+ 0x12835b01,
22
+ 0x243185be,
23
+ 0x550c7dc3,
24
+ 0x72be5d74,
25
+ 0x80deb1fe,
26
+ 0x9bdc06a7,
27
+ 0xc19bf174,
28
+ 0xe49b69c1,
29
+ 0xefbe4786,
30
+ 0x0fc19dc6,
31
+ 0x240ca1cc,
32
+ 0x2de92c6f,
33
+ 0x4a7484aa,
34
+ 0x5cb0a9dc,
35
+ 0x76f988da,
36
+ 0x983e5152,
37
+ 0xa831c66d,
38
+ 0xb00327c8,
39
+ 0xbf597fc7,
40
+ 0xc6e00bf3,
41
+ 0xd5a79147,
42
+ 0x06ca6351,
43
+ 0x14292967,
44
+ 0x27b70a85,
45
+ 0x2e1b2138,
46
+ 0x4d2c6dfc,
47
+ 0x53380d13,
48
+ 0x650a7354,
49
+ 0x766a0abb,
50
+ 0x81c2c92e,
51
+ 0x92722c85,
52
+ 0xa2bfe8a1,
53
+ 0xa81a664b,
54
+ 0xc24b8b70,
55
+ 0xc76c51a3,
56
+ 0xd192e819,
57
+ 0xd6990624,
58
+ 0xf40e3585,
59
+ 0x106aa070,
60
+ 0x19a4c116,
61
+ 0x1e376c08,
62
+ 0x2748774c,
63
+ 0x34b0bcb5,
64
+ 0x391c0cb3,
65
+ 0x4ed8aa4a,
66
+ 0x5b9cca4f,
67
+ 0x682e6ff3,
68
+ 0x748f82ee,
69
+ 0x78a5636f,
70
+ 0x84c87814,
71
+ 0x8cc70208,
72
+ 0x90befffa,
73
+ 0xa4506ceb,
74
+ 0xbef9a3f7,
75
+ 0xc67178f2,
76
+ ])
77
+
78
+ /** The state before any bytes, SHA-256's initial hash value, as hex. */
79
+ export let START =
80
+ '6a09e667bb67ae853c6ef372a54ff53a510e527f9b05688c1f83d9ab5be0cd19'
81
+
82
+ let hex = (h: Uint32Array) =>
83
+ [...h].map((v) => v.toString(16).padStart(8, '0')).join('')
84
+
85
+ let words = (state: string) => {
86
+ if (!/^[0-9a-f]{64}$/.test(state)) throw new Error(`no state: ${state}`)
87
+ return Uint32Array.from(
88
+ { length: 8 },
89
+ (_, i) => parseInt(state.slice(i * 8, i * 8 + 8), 16),
90
+ )
91
+ }
92
+
93
+ // Each 64-byte block of `b` from `at` to `end` folded into `h`.
94
+ let blocks = (
95
+ h: Uint32Array,
96
+ w: Uint32Array,
97
+ b: Uint8Array,
98
+ at: number,
99
+ end: number,
100
+ ) => {
101
+ for (let i = at; i < end; i += 64) {
102
+ for (let t = 0; t < 16; t++) {
103
+ let j = i + t * 4
104
+ w[t] = (b[j] << 24) | (b[j + 1] << 16) | (b[j + 2] << 8) | b[j + 3]
105
+ }
106
+ for (let t = 16; t < 64; t++) {
107
+ let x = w[t - 15], y = w[t - 2]
108
+ let s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3)
109
+ let s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^
110
+ (y >>> 10)
111
+ w[t] = (w[t - 16] + s0 + w[t - 7] + s1) | 0
112
+ }
113
+ let [a, b1, c, d, e, f, g, k] = h
114
+ for (let t = 0; t < 64; t++) {
115
+ let S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^
116
+ ((e >>> 25) | (e << 7))
117
+ let t1 = (k + S1 + ((e & f) ^ (~e & g)) + K[t] + w[t]) | 0
118
+ let S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^
119
+ ((a >>> 22) | (a << 10))
120
+ let t2 = (S0 + ((a & b1) ^ (a & c) ^ (b1 & c))) | 0
121
+ k = g
122
+ g = f
123
+ f = e
124
+ e = (d + t1) | 0
125
+ d = c
126
+ c = b1
127
+ b1 = a
128
+ a = (t1 + t2) | 0
129
+ }
130
+ h[0] += a
131
+ h[1] += b1
132
+ h[2] += c
133
+ h[3] += d
134
+ h[4] += e
135
+ h[5] += f
136
+ h[6] += g
137
+ h[7] += k
138
+ }
139
+ }
140
+
141
+ /** Bytes hashed a piece at a time: `add` each, then `end` once. */
142
+ export type Hasher = {
143
+ add: (bytes: Uint8Array) => void
144
+ end: (total?: number) => string
145
+ }
146
+
147
+ /**
148
+ * Bytes hashed on from `from`, a piece at a time with `add`. `end()` answers
149
+ * the state after them, which only whole 64-byte blocks leave; given `total`,
150
+ * the length of everything hashed since {@link START}, it answers the
151
+ * finished digest instead.
152
+ */
153
+ export let hasher = (from = START): Hasher => {
154
+ let h = words(from)
155
+ let w = new Uint32Array(64)
156
+ let carry = new Uint8Array(64)
157
+ let held = 0
158
+ return {
159
+ add: (b: Uint8Array) => {
160
+ let at = 0
161
+ if (held) {
162
+ at = Math.min(64 - held, b.length)
163
+ carry.set(b.subarray(0, at), held)
164
+ held += at
165
+ if (held < 64) return
166
+ blocks(h, w, carry, 0, 64)
167
+ held = 0
168
+ }
169
+ let whole = b.length - ((b.length - at) % 64)
170
+ blocks(h, w, b, at, whole)
171
+ carry.set(b.subarray(whole))
172
+ held = b.length - whole
173
+ },
174
+ end: (total?: number) => {
175
+ if (total == null) {
176
+ if (held) throw new Error('a state is only left by whole blocks')
177
+ return hex(h)
178
+ }
179
+ // What was left, a 1 bit, zeros, and the length in bits as 64.
180
+ let tail = new Uint8Array(held < 56 ? 64 : 128)
181
+ tail.set(carry.subarray(0, held))
182
+ tail[held] = 0x80
183
+ let view = new DataView(tail.buffer)
184
+ view.setUint32(tail.length - 8, Math.floor(total / 2 ** 29))
185
+ view.setUint32(tail.length - 4, (total * 8) >>> 0)
186
+ blocks(h, w, tail, 0, tail.length)
187
+ return hex(h)
188
+ },
189
+ }
190
+ }
191
+
192
+ /**
193
+ * `bytes` hashed on from `from`: the state after them, or with `total`, the
194
+ * digest of everything hashed since {@link START}.
195
+ *
196
+ * ```ts
197
+ * import { equal } from '@yaks/testing'
198
+ * import { address, encode, fold, START } from '@yaks/blob'
199
+ *
200
+ * let text = 'a'.repeat(64) + 'and the rest'
201
+ * let half = fold(START, encode('a'.repeat(64)))
202
+ * equal(fold(half, encode('and the rest'), 76), address(text))
203
+ * equal(fold(START, encode(text), 76), address(text))
204
+ * ```
205
+ */
206
+ export let fold = (from: string, bytes: Uint8Array, total?: number): string => {
207
+ let h = hasher(from)
208
+ h.add(bytes)
209
+ return h.end(total)
210
+ }
package/sqlite.js ADDED
@@ -0,0 +1,201 @@
1
+ // The byte store that lives in the database the rows already live in: one table
2
+ // of `(sha, value)` beside the component tables. It is the one to reach for
3
+ // first — the bytes land in the same transaction as the row that addresses
4
+ // them, so a committed document can never point at a value that was not
5
+ // written, and there is no second thing to back up.
6
+ //
7
+ // It also gives the read side something no other store can: the resolution is a
8
+ // SQL expression, so a query and a whole-entity read both get text without a
9
+ // second round trip. {@link blobRead} builds that expression as an @yaks/sql
10
+ // read override, one per content-addressed property, with its smaller half —
11
+ // an address resolved to its text — for the places that already hold an
12
+ // address, chiefly a full-text index's triggers and the view it reads back
13
+ // through.
14
+ //
15
+ // The table holds text, not bytes — which is what lets the read be an ordinary
16
+ // string expression — so this store is for prose. Binary content belongs in the
17
+ // file or object stores, whose bytes never have to be read by SQL.
18
+ //
19
+ // Every name in the layout is configurable because this table is often one an
20
+ // application already has: point {@link Layout} at it and the existing rows are
21
+ // readable as they stand.
22
+ import { after } from "@yaks/fp";
23
+ import { among, and, array, col, eq, field, not, select, sub, table, val } from "@yaks/sql/core";
24
+ import { bodies } from "./props.js";
25
+ import { encode } from "./store.js";
26
+ let named = (l = {})=>({
27
+ table: l.table ?? 'blob_text',
28
+ key: l.key ?? 'sha',
29
+ value: l.value ?? 'value'
30
+ });
31
+ // This table's column is text, so bytes that are not valid UTF-8 have no
32
+ // representation in it. Refusing them here is the difference between a store
33
+ // that cannot hold an object and one that holds a mangled copy: the address
34
+ // would return bytes that do not hash to it, breaking the one thing content
35
+ // addressing promises.
36
+ let strict = new TextDecoder('utf-8', {
37
+ fatal: true
38
+ });
39
+ let asText = (bytes)=>{
40
+ try {
41
+ return strict.decode(bytes);
42
+ } catch {
43
+ throw new Error('@yaks/blob: this store holds text and these bytes are not UTF-8 — ' + 'binary belongs in a directory or a bucket');
44
+ }
45
+ };
46
+ /**
47
+ * The statement creating the blob table: an address, and the text stored under
48
+ * it. Run it beside a storage adapter's own schema.
49
+ */ export let blobSchema = (layout = {})=>{
50
+ let l = named(layout);
51
+ return [
52
+ {
53
+ t: 'create table',
54
+ name: l.table,
55
+ ifNot: true,
56
+ cols: [
57
+ {
58
+ name: l.key,
59
+ type: 'text',
60
+ pk: true
61
+ },
62
+ {
63
+ name: l.value,
64
+ type: 'text',
65
+ notNull: true
66
+ }
67
+ ]
68
+ }
69
+ ];
70
+ };
71
+ /**
72
+ * The statement letting go of the objects `shas` names, except each a column
73
+ * of `held` still names: one scan of each holding table, whatever the count.
74
+ */ export let dropSql = (shas, held, layout = {})=>{
75
+ let l = named(layout);
76
+ let listed = array(shas);
77
+ return {
78
+ t: 'delete',
79
+ from: l.table,
80
+ where: and(among(col(l.key), listed), ...held.map(({ comp, prop })=>not(among(col(l.key), select({
81
+ cols: [
82
+ col(field(prop))
83
+ ],
84
+ from: table(comp),
85
+ where: among(col(field(prop)), listed)
86
+ })))))
87
+ };
88
+ };
89
+ /**
90
+ * A {@link Blobs} over a SQLite table. Writes use the store's atomic boundary:
91
+ * nested writes share the graph's transaction; independent writes await a
92
+ * competing writer without holding their thread. Writing one address twice
93
+ * keeps one copy of its bytes. An optional reader answers committed reads;
94
+ * reads inside the owning transaction stay on its connection.
95
+ */ export let sqliteBlobs = (db, layout = {}, read)=>{
96
+ let l = named(layout);
97
+ let row = (sha)=>after((db.inside && !db.inside() && read ? read : db).query(select({
98
+ cols: [
99
+ col(l.value)
100
+ ],
101
+ from: table(l.table),
102
+ where: eq(col(l.key), val(sha))
103
+ })), (rows)=>rows[0]?.[l.value]);
104
+ return {
105
+ transactional: true,
106
+ has: (sha)=>after(row(sha), (value)=>value != null),
107
+ get: (sha)=>after(row(sha), (found)=>found == null ? undefined : encode(String(found))),
108
+ put: (sha, bytes)=>{
109
+ let text = asText(bytes);
110
+ return db.atomic(()=>{
111
+ db.query({
112
+ t: 'insert',
113
+ or: 'ignore',
114
+ into: l.table,
115
+ cols: [
116
+ l.key,
117
+ l.value
118
+ ],
119
+ rows: [
120
+ [
121
+ val(sha),
122
+ val(text)
123
+ ]
124
+ ]
125
+ });
126
+ });
127
+ },
128
+ drop: (shas, held)=>{
129
+ if (!shas.length) return;
130
+ return db.atomic(()=>{
131
+ // Tables are raised by their first write, so an absent one holds no bytes.
132
+ let tables = new Set(db.query(select({
133
+ cols: [
134
+ col('name')
135
+ ],
136
+ from: table('sqlite_master'),
137
+ where: eq(col('type'), val('table'))
138
+ })).map((r)=>String(r.name)));
139
+ let named = held.filter(({ comp })=>tables.has(comp));
140
+ db.query(dropSql(shas, named, layout));
141
+ });
142
+ }
143
+ };
144
+ };
145
+ // The text an address stands for: one row of the blob table, found by its key.
146
+ let textExpr = (l)=>(address)=>sub(select({
147
+ cols: [
148
+ col(l.value, '__b')
149
+ ],
150
+ from: table(l.table, '__b'),
151
+ where: eq(col(l.key, '__b'), address)
152
+ }));
153
+ // The read expression for one property: the stored text, found by joining the
154
+ // address its column holds to the blob table. It is written self-contained — it
155
+ // names its own component table rather than assuming the query already joined
156
+ // one — so the same expression serves a filter predicate, a dereferenced path,
157
+ // and a whole-entity read.
158
+ let readExpr = (l, comp, prop)=>(owner)=>textExpr(l)(sub(select({
159
+ cols: [
160
+ col(prop, '__c')
161
+ ],
162
+ from: table(comp, '__c'),
163
+ where: eq(col('entity', '__c'), owner)
164
+ })));
165
+ /**
166
+ * The read side, as @yaks/sql read overrides: one entry per content-addressed
167
+ * property, each resolving the stored address to its text in the statement
168
+ * itself (`expr`), and resolving an address already in hand (`text`: an FTS5
169
+ * trigger's `new."body"`, a view column). Pass them to a compile (or to
170
+ * `@yaks/sqlite`'s `storage()`, which passes them on to the query, the
171
+ * whole-entity read and the `doc_value` view; and to @yaks/fts `schema()`, so
172
+ * a search index holds words rather than addresses) and a body property reads
173
+ * as text everywhere:
174
+ *
175
+ * ```ts
176
+ * import { loadVocab } from '@yaks/vocab'
177
+ * import { storage } from '@yaks/sqlite'
178
+ * import { open } from '@yaks/sqlite/db'
179
+ * import { blobKeywords, blobRead } from '@yaks/blob'
180
+ *
181
+ * let body = { type: 'string', store: 'blob' }
182
+ * let post = { component: true, type: 'object', properties: { body } }
183
+ * let vocab = loadVocab([{ $defs: { post } }], [blobKeywords])
184
+ * let store = storage(open(':memory:'), vocab, { derived: blobRead(vocab) })
185
+ * ```
186
+ *
187
+ * Merge them with any overrides of your own — the registry is a plain object
188
+ * keyed `comp.prop`.
189
+ */ export let blobRead = (vocab, layout = {})=>{
190
+ let l = named(layout);
191
+ return Object.fromEntries(bodies(vocab).map(({ comp, prop })=>[
192
+ `${comp}.${prop}`,
193
+ {
194
+ tag: 'text',
195
+ stable: true,
196
+ expr: readExpr(l, comp, prop),
197
+ text: textExpr(l)
198
+ }
199
+ ]));
200
+ };
201
+ //# sourceMappingURL=sqlite.js.map
package/sqlite.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite.js","sources":["./sqlite.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,4EAA4E;AAC5E,2EAA2E;AAC3E,wEAAwE;AACxE,oDAAoD;AACpD,EAAE;AACF,gFAAgF;AAChF,6EAA6E;AAC7E,6EAA6E;AAC7E,6EAA6E;AAC7E,wEAAwE;AACxE,2EAA2E;AAC3E,WAAW;AACX,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,mEAAmE;AACnE,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,0BAA0B;AAI1B,SAAS,KAAK,wBAA6B;AAC3C,SACE,KAAK,EACL,GAAG,EACH,KAAK,EACL,GAAG,EAEH,EAAE,EAEF,KAAK,EACL,GAAG,EAEH,MAAM,EAEN,GAAG,EACH,KAAK,EACL,GAAG,8BAC6B;AAClC,SAAS,MAAM,qBAA+B;AAC9C,SAAqB,MAAM,qBAAoB;AAkB/C,IAAI,QAAQ,CAAC,IAAY,CAAC,CAAC,GAAY,CAAC;IACtC,OAAO,EAAE,KAAK,IAAI;IAClB,KAAK,EAAE,GAAG,IAAI;IACd,OAAO,EAAE,KAAK,IAAI;EACpB,CAAC;AAED,yEAAyE;AACzE,6EAA6E;AAC7E,4EAA4E;AAC5E,4EAA4E;AAC5E,uBAAuB;AACvB,IAAI,SAAS,IAAI,YAAY,SAAS;EAAE,OAAO;AAAK;AACpD,IAAI,SAAS,CAAC;EACZ,IAAI;IACF,OAAO,OAAO,MAAM,CAAC;EACvB,EAAE,OAAM;IACN,MAAM,IAAI,MACR,uEACE;EAEN;AACF;AA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,MAAM;MAClB,OAAO,GAAG,IAAI,UAAU,QAAQ;IAClC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,IAAI,WAAW,CAAC,OAAc,SAAiB,CAAC,CAAC;EACtD,IAAI,IAAI,MAAM;EACd,OAAO,OAAO,WAAW,CACvB,OAAO,OAAO,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,GAAK;MACpC,GAAG,KAAK,CAAC,EAAE,MAAM;MACjB;QACE,KAAK;QACL,QAAQ;QACR,MAAM,SAAS,GAAG,MAAM;QACxB,MAAM,SAAS;MACjB;KACD;AAEL,EAAC"}
package/sqlite.ts ADDED
@@ -0,0 +1,250 @@
1
+ // The byte store that lives in the database the rows already live in: one table
2
+ // of `(sha, value)` beside the component tables. It is the one to reach for
3
+ // first — the bytes land in the same transaction as the row that addresses
4
+ // them, so a committed document can never point at a value that was not
5
+ // written, and there is no second thing to back up.
6
+ //
7
+ // It also gives the read side something no other store can: the resolution is a
8
+ // SQL expression, so a query and a whole-entity read both get text without a
9
+ // second round trip. {@link blobRead} builds that expression as an @yaks/sql
10
+ // read override, one per content-addressed property, with its smaller half —
11
+ // an address resolved to its text — for the places that already hold an
12
+ // address, chiefly a full-text index's triggers and the view it reads back
13
+ // through.
14
+ //
15
+ // The table holds text, not bytes — which is what lets the read be an ordinary
16
+ // string expression — so this store is for prose. Binary content belongs in the
17
+ // file or object stores, whose bytes never have to be read by SQL.
18
+ //
19
+ // Every name in the layout is configurable because this table is often one an
20
+ // application already has: point {@link Layout} at it and the existing rows are
21
+ // readable as they stand.
22
+
23
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
24
+ import type { Statements } from 'jsr:@yaks/sql@0.2.36'
25
+ import { after } from '@yaks/fp'
26
+ import {
27
+ among,
28
+ and,
29
+ array,
30
+ col,
31
+ type Derived,
32
+ eq,
33
+ type Expr,
34
+ field,
35
+ not,
36
+ type Row,
37
+ select,
38
+ type Stmt,
39
+ sub,
40
+ table,
41
+ val,
42
+ } from '@yaks/sql/core'
43
+ import { bodies, type Body } from './props.js'
44
+ import { type Blobs, encode } from './store.js'
45
+
46
+ /**
47
+ * Where the blob table is and what its two columns are called. The defaults
48
+ * describe the table {@link blobSchema} creates; an application pointing this
49
+ * at a table it already has names that table's columns instead.
50
+ */
51
+ export type Layout = {
52
+ /** the table holding the objects (default `blob_text`) */
53
+ table?: string
54
+ /** the column holding an object's address (default `sha`) */
55
+ key?: string
56
+ /** the column holding its text (default `value`) */
57
+ value?: string
58
+ }
59
+
60
+ type Named = Required<Layout>
61
+
62
+ let named = (l: Layout = {}): Named => ({
63
+ table: l.table ?? 'blob_text',
64
+ key: l.key ?? 'sha',
65
+ value: l.value ?? 'value',
66
+ })
67
+
68
+ // This table's column is text, so bytes that are not valid UTF-8 have no
69
+ // representation in it. Refusing them here is the difference between a store
70
+ // that cannot hold an object and one that holds a mangled copy: the address
71
+ // would return bytes that do not hash to it, breaking the one thing content
72
+ // addressing promises.
73
+ let strict = new TextDecoder('utf-8', { fatal: true })
74
+ let asText = (bytes: Uint8Array): string => {
75
+ try {
76
+ return strict.decode(bytes)
77
+ } catch {
78
+ throw new Error(
79
+ '@yaks/blob: this store holds text and these bytes are not UTF-8 — ' +
80
+ 'binary belongs in a directory or a bucket',
81
+ )
82
+ }
83
+ }
84
+
85
+ /**
86
+ * The statement creating the blob table: an address, and the text stored under
87
+ * it. Run it beside a storage adapter's own schema.
88
+ */
89
+ export let blobSchema = (layout: Layout = {}): Stmt[] => {
90
+ let l = named(layout)
91
+ return [{
92
+ t: 'create table',
93
+ name: l.table,
94
+ ifNot: true,
95
+ cols: [
96
+ { name: l.key, type: 'text', pk: true },
97
+ { name: l.value, type: 'text', notNull: true },
98
+ ],
99
+ }]
100
+ }
101
+
102
+ /**
103
+ * The statement letting go of the objects `shas` names, except each a column
104
+ * of `held` still names: one scan of each holding table, whatever the count.
105
+ */
106
+ export let dropSql = (
107
+ shas: string[],
108
+ held: Body[],
109
+ layout: Layout = {},
110
+ ): Stmt => {
111
+ let l = named(layout)
112
+ let listed = array(shas)
113
+ return {
114
+ t: 'delete',
115
+ from: l.table,
116
+ where: and(
117
+ among(col(l.key), listed),
118
+ ...held.map(({ comp, prop }) =>
119
+ not(among(
120
+ col(l.key),
121
+ select({
122
+ cols: [col(field(prop))],
123
+ from: table(comp),
124
+ where: among(col(field(prop)), listed),
125
+ }),
126
+ ))
127
+ ),
128
+ ),
129
+ }
130
+ }
131
+
132
+ /**
133
+ * A {@link Blobs} over a SQLite table. Writes use the store's atomic boundary:
134
+ * nested writes share the graph's transaction; independent writes await a
135
+ * competing writer without holding their thread. Writing one address twice
136
+ * keeps one copy of its bytes. An optional reader answers committed reads;
137
+ * reads inside the owning transaction stay on its connection.
138
+ */
139
+ export let sqliteBlobs = (
140
+ db: Statements,
141
+ layout: Layout = {},
142
+ read?: { query: (statement: Stmt) => Row[] | Promise<Row[]> },
143
+ ): Blobs => {
144
+ let l = named(layout)
145
+ let row = (sha: string) =>
146
+ after(
147
+ (db.inside && !db.inside() && read ? read : db).query(select({
148
+ cols: [col(l.value)],
149
+ from: table(l.table),
150
+ where: eq(col(l.key), val(sha)),
151
+ })),
152
+ (rows) => rows[0]?.[l.value],
153
+ )
154
+ return {
155
+ transactional: true,
156
+ has: (sha) => after(row(sha), (value) => value != null),
157
+ get: (sha) =>
158
+ after(
159
+ row(sha),
160
+ (found) => found == null ? undefined : encode(String(found)),
161
+ ),
162
+ put: (sha, bytes) => {
163
+ let text = asText(bytes)
164
+ return db.atomic(() => {
165
+ db.query({
166
+ t: 'insert',
167
+ or: 'ignore',
168
+ into: l.table,
169
+ cols: [l.key, l.value],
170
+ rows: [[val(sha), val(text)]],
171
+ })
172
+ })
173
+ },
174
+ drop: (shas, held) => {
175
+ if (!shas.length) return
176
+ return db.atomic(() => {
177
+ // Tables are raised by their first write, so an absent one holds no bytes.
178
+ let tables = new Set(
179
+ db.query(select({
180
+ cols: [col('name')],
181
+ from: table('sqlite_master'),
182
+ where: eq(col('type'), val('table')),
183
+ })).map((r) => String(r.name)),
184
+ )
185
+ let named = held.filter(({ comp }) => tables.has(comp))
186
+ db.query(dropSql(shas, named, layout))
187
+ })
188
+ },
189
+ }
190
+ }
191
+
192
+ // The text an address stands for: one row of the blob table, found by its key.
193
+ let textExpr = (l: Named) => (address: Expr): Expr =>
194
+ sub(select({
195
+ cols: [col(l.value, '__b')],
196
+ from: table(l.table, '__b'),
197
+ where: eq(col(l.key, '__b'), address),
198
+ }))
199
+
200
+ // The read expression for one property: the stored text, found by joining the
201
+ // address its column holds to the blob table. It is written self-contained — it
202
+ // names its own component table rather than assuming the query already joined
203
+ // one — so the same expression serves a filter predicate, a dereferenced path,
204
+ // and a whole-entity read.
205
+ let readExpr = (l: Named, comp: string, prop: string) => (owner: Expr) =>
206
+ textExpr(l)(sub(select({
207
+ cols: [col(prop, '__c')],
208
+ from: table(comp, '__c'),
209
+ where: eq(col('entity', '__c'), owner),
210
+ })))
211
+
212
+ /**
213
+ * The read side, as @yaks/sql read overrides: one entry per content-addressed
214
+ * property, each resolving the stored address to its text in the statement
215
+ * itself (`expr`), and resolving an address already in hand (`text`: an FTS5
216
+ * trigger's `new."body"`, a view column). Pass them to a compile (or to
217
+ * `@yaks/sqlite`'s `storage()`, which passes them on to the query, the
218
+ * whole-entity read and the `doc_value` view; and to @yaks/fts `schema()`, so
219
+ * a search index holds words rather than addresses) and a body property reads
220
+ * as text everywhere:
221
+ *
222
+ * ```ts
223
+ * import { loadVocab } from '@yaks/vocab'
224
+ * import { storage } from '@yaks/sqlite'
225
+ * import { open } from '@yaks/sqlite/db'
226
+ * import { blobKeywords, blobRead } from '@yaks/blob'
227
+ *
228
+ * let body = { type: 'string', store: 'blob' }
229
+ * let post = { component: true, type: 'object', properties: { body } }
230
+ * let vocab = loadVocab([{ $defs: { post } }], [blobKeywords])
231
+ * let store = storage(open(':memory:'), vocab, { derived: blobRead(vocab) })
232
+ * ```
233
+ *
234
+ * Merge them with any overrides of your own — the registry is a plain object
235
+ * keyed `comp.prop`.
236
+ */
237
+ export let blobRead = (vocab: Vocab, layout: Layout = {}): Derived => {
238
+ let l = named(layout)
239
+ return Object.fromEntries(
240
+ bodies(vocab).map(({ comp, prop }) => [
241
+ `${comp}.${prop}`,
242
+ {
243
+ tag: 'text' as const,
244
+ stable: true,
245
+ expr: readExpr(l, comp, prop),
246
+ text: textExpr(l),
247
+ },
248
+ ]),
249
+ )
250
+ }