@agentshouse/mdruntime 0.1.0-cb0eb0d87ff49 → 0.1.0-cb122f2ba154d

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 (230) hide show
  1. package/README.md +18 -15
  2. package/dist/adapter.d.ts +91 -34
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/attached-model.d.ts +5 -1
  5. package/dist/attached-model.d.ts.map +1 -1
  6. package/dist/attached-model.js +38 -4
  7. package/dist/binary.d.ts +0 -5
  8. package/dist/binary.d.ts.map +1 -1
  9. package/dist/binary.js +1 -1
  10. package/dist/bootstrap.d.ts +27 -8
  11. package/dist/bootstrap.d.ts.map +1 -1
  12. package/dist/bootstrap.js +174 -98
  13. package/dist/chain.d.ts +11 -0
  14. package/dist/chain.d.ts.map +1 -0
  15. package/dist/chain.js +64 -0
  16. package/dist/change-set.d.ts +9 -16
  17. package/dist/change-set.d.ts.map +1 -1
  18. package/dist/change-set.js +11 -88
  19. package/dist/change.d.ts +31 -1
  20. package/dist/change.d.ts.map +1 -1
  21. package/dist/change.js +10 -1
  22. package/dist/client.d.ts +18 -6
  23. package/dist/client.d.ts.map +1 -1
  24. package/dist/client.js +97 -10
  25. package/dist/collection.d.ts +11 -19
  26. package/dist/collection.d.ts.map +1 -1
  27. package/dist/collection.js +53 -289
  28. package/dist/compile.d.ts +16 -0
  29. package/dist/compile.d.ts.map +1 -0
  30. package/dist/compile.js +771 -0
  31. package/dist/connection.d.ts +38 -11
  32. package/dist/connection.d.ts.map +1 -1
  33. package/dist/connection.js +3134 -858
  34. package/dist/conversation.d.ts +22 -6
  35. package/dist/conversation.d.ts.map +1 -1
  36. package/dist/conversation.js +461 -131
  37. package/dist/digest.d.ts +7 -0
  38. package/dist/digest.d.ts.map +1 -0
  39. package/dist/digest.js +113 -0
  40. package/dist/durability.d.ts +5 -1
  41. package/dist/durability.d.ts.map +1 -1
  42. package/dist/durability.js +5 -0
  43. package/dist/entry.d.ts +4 -1
  44. package/dist/entry.d.ts.map +1 -1
  45. package/dist/entry.js +18 -23
  46. package/dist/file.d.ts +2 -19
  47. package/dist/file.d.ts.map +1 -1
  48. package/dist/file.js +7 -122
  49. package/dist/fulltext.d.ts +27 -0
  50. package/dist/fulltext.d.ts.map +1 -0
  51. package/dist/fulltext.js +370 -0
  52. package/dist/host.d.ts +12 -2
  53. package/dist/host.d.ts.map +1 -1
  54. package/dist/host.js +121 -13
  55. package/dist/identity.d.ts +0 -1
  56. package/dist/identity.d.ts.map +1 -1
  57. package/dist/identity.js +0 -3
  58. package/dist/index.d.ts +13 -9
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +5 -1
  61. package/dist/live.d.ts +22 -0
  62. package/dist/live.d.ts.map +1 -0
  63. package/dist/live.js +124 -0
  64. package/dist/media.d.ts +8 -0
  65. package/dist/media.d.ts.map +1 -0
  66. package/dist/media.js +208 -0
  67. package/dist/memory.d.ts +10 -4
  68. package/dist/memory.d.ts.map +1 -1
  69. package/dist/memory.js +88 -27
  70. package/dist/messages.d.ts +28 -0
  71. package/dist/messages.d.ts.map +1 -0
  72. package/dist/messages.js +90 -0
  73. package/dist/model.d.ts +9 -2
  74. package/dist/model.d.ts.map +1 -1
  75. package/dist/model.js +8 -2
  76. package/dist/name.d.ts +4 -0
  77. package/dist/name.d.ts.map +1 -0
  78. package/dist/name.js +122 -0
  79. package/dist/observation.d.ts +15 -0
  80. package/dist/observation.d.ts.map +1 -1
  81. package/dist/observation.js +93 -3
  82. package/dist/opened.d.ts +22 -0
  83. package/dist/opened.d.ts.map +1 -0
  84. package/dist/opened.js +107 -0
  85. package/dist/outcome.d.ts +45 -4
  86. package/dist/outcome.d.ts.map +1 -1
  87. package/dist/outcome.js +39 -0
  88. package/dist/overlay.d.ts +3 -5
  89. package/dist/overlay.d.ts.map +1 -1
  90. package/dist/overlay.js +95 -156
  91. package/dist/paths.d.ts +1 -0
  92. package/dist/paths.d.ts.map +1 -1
  93. package/dist/paths.js +4 -0
  94. package/dist/query.d.ts +39 -2
  95. package/dist/query.d.ts.map +1 -1
  96. package/dist/query.js +48 -7
  97. package/dist/reach.d.ts +18 -6
  98. package/dist/reach.d.ts.map +1 -1
  99. package/dist/reach.js +224 -70
  100. package/dist/react.d.ts +5 -3
  101. package/dist/react.d.ts.map +1 -1
  102. package/dist/react.js +7 -17
  103. package/dist/readiness.d.ts +63 -0
  104. package/dist/readiness.d.ts.map +1 -0
  105. package/dist/readiness.js +33 -0
  106. package/dist/reads.d.ts +11 -0
  107. package/dist/reads.d.ts.map +1 -0
  108. package/dist/reads.js +91 -0
  109. package/dist/recovery.d.ts +2 -2
  110. package/dist/recovery.d.ts.map +1 -1
  111. package/dist/recovery.js +8 -7
  112. package/dist/refresh.d.ts +16 -15
  113. package/dist/refresh.d.ts.map +1 -1
  114. package/dist/refresh.js +113 -50
  115. package/dist/replica.d.ts +56 -33
  116. package/dist/replica.d.ts.map +1 -1
  117. package/dist/replica.js +298 -179
  118. package/dist/room-draft.d.ts +34 -4
  119. package/dist/room-draft.d.ts.map +1 -1
  120. package/dist/room-draft.js +105 -31
  121. package/dist/rows.d.ts +38 -29
  122. package/dist/rows.d.ts.map +1 -1
  123. package/dist/rows.js +173 -94
  124. package/dist/save.d.ts +53 -14
  125. package/dist/save.d.ts.map +1 -1
  126. package/dist/save.js +529 -185
  127. package/dist/search.d.ts +32 -43
  128. package/dist/search.d.ts.map +1 -1
  129. package/dist/search.js +37 -170
  130. package/dist/seed.d.ts +16 -0
  131. package/dist/seed.d.ts.map +1 -0
  132. package/dist/seed.js +75 -0
  133. package/dist/shared.d.ts +8 -3
  134. package/dist/shared.d.ts.map +1 -1
  135. package/dist/shared.js +129 -66
  136. package/dist/status.d.ts +9 -0
  137. package/dist/status.d.ts.map +1 -1
  138. package/dist/status.js +3 -1
  139. package/dist/store.d.ts +100 -86
  140. package/dist/store.d.ts.map +1 -1
  141. package/dist/store.js +331 -632
  142. package/dist/stored.d.ts +135 -0
  143. package/dist/stored.d.ts.map +1 -0
  144. package/dist/stored.js +568 -0
  145. package/dist/tables.d.ts +352 -0
  146. package/dist/tables.d.ts.map +1 -0
  147. package/dist/tables.js +621 -0
  148. package/dist/turn.d.ts +5 -3
  149. package/dist/turn.d.ts.map +1 -1
  150. package/dist/turn.js +51 -21
  151. package/dist/validation.d.ts +30 -0
  152. package/dist/validation.d.ts.map +1 -0
  153. package/dist/validation.js +162 -0
  154. package/dist/windows.d.ts +22 -0
  155. package/dist/windows.d.ts.map +1 -0
  156. package/dist/windows.js +89 -0
  157. package/dist/wire.d.ts +168 -32
  158. package/dist/wire.d.ts.map +1 -1
  159. package/dist/wire.js +56 -31
  160. package/dist/words.d.ts +19 -0
  161. package/dist/words.d.ts.map +1 -0
  162. package/dist/words.js +156 -0
  163. package/package.json +18 -19
  164. package/AGENTS.md +0 -309
  165. package/dist/chat/acts.d.ts +0 -33
  166. package/dist/chat/acts.d.ts.map +0 -1
  167. package/dist/chat/acts.js +0 -36
  168. package/dist/chat/context.d.ts +0 -3
  169. package/dist/chat/context.d.ts.map +0 -1
  170. package/dist/chat/context.js +0 -10
  171. package/dist/chat/input.d.ts +0 -9
  172. package/dist/chat/input.d.ts.map +0 -1
  173. package/dist/chat/input.js +0 -99
  174. package/dist/chat/kit.d.ts +0 -60
  175. package/dist/chat/kit.d.ts.map +0 -1
  176. package/dist/chat/kit.js +0 -123
  177. package/dist/chat/lasting.d.ts +0 -6
  178. package/dist/chat/lasting.d.ts.map +0 -1
  179. package/dist/chat/lasting.js +0 -19
  180. package/dist/chat/list.d.ts +0 -26
  181. package/dist/chat/list.d.ts.map +0 -1
  182. package/dist/chat/list.js +0 -62
  183. package/dist/chat/markdown.d.ts +0 -20
  184. package/dist/chat/markdown.d.ts.map +0 -1
  185. package/dist/chat/markdown.js +0 -188
  186. package/dist/chat/message.d.ts +0 -6
  187. package/dist/chat/message.d.ts.map +0 -1
  188. package/dist/chat/message.js +0 -192
  189. package/dist/chat/messages.d.ts +0 -21
  190. package/dist/chat/messages.d.ts.map +0 -1
  191. package/dist/chat/messages.js +0 -151
  192. package/dist/chat/name.d.ts +0 -6
  193. package/dist/chat/name.d.ts.map +0 -1
  194. package/dist/chat/name.js +0 -37
  195. package/dist/chat/opened.d.ts +0 -11
  196. package/dist/chat/opened.d.ts.map +0 -1
  197. package/dist/chat/opened.js +0 -17
  198. package/dist/chat/overlay.d.ts +0 -31
  199. package/dist/chat/overlay.d.ts.map +0 -1
  200. package/dist/chat/overlay.js +0 -97
  201. package/dist/chat/parts.d.ts +0 -57
  202. package/dist/chat/parts.d.ts.map +0 -1
  203. package/dist/chat/parts.js +0 -119
  204. package/dist/chat/process.d.ts +0 -20
  205. package/dist/chat/process.d.ts.map +0 -1
  206. package/dist/chat/process.js +0 -32
  207. package/dist/chat/provider.d.ts +0 -63
  208. package/dist/chat/provider.d.ts.map +0 -1
  209. package/dist/chat/provider.js +0 -620
  210. package/dist/chat/question.d.ts +0 -9
  211. package/dist/chat/question.d.ts.map +0 -1
  212. package/dist/chat/question.js +0 -80
  213. package/dist/chat/questions.d.ts +0 -31
  214. package/dist/chat/questions.d.ts.map +0 -1
  215. package/dist/chat/questions.js +0 -111
  216. package/dist/chat/read.d.ts +0 -5
  217. package/dist/chat/read.d.ts.map +0 -1
  218. package/dist/chat/read.js +0 -13
  219. package/dist/chat/ready.d.ts +0 -33
  220. package/dist/chat/ready.d.ts.map +0 -1
  221. package/dist/chat/ready.js +0 -91
  222. package/dist/chat/style.d.ts +0 -4
  223. package/dist/chat/style.d.ts.map +0 -1
  224. package/dist/chat/style.js +0 -302
  225. package/dist/chat.d.ts +0 -14
  226. package/dist/chat.d.ts.map +0 -1
  227. package/dist/chat.js +0 -8
  228. package/dist/read-side.d.ts +0 -25
  229. package/dist/read-side.d.ts.map +0 -1
  230. package/dist/read-side.js +0 -639
@@ -0,0 +1,771 @@
1
+ import { ARRAY_INDEX, parse, pointerSegments } from '@agentshouse/mdmodel';
2
+ import { binaryRecord } from './binary.js';
3
+ import { documentKey, kindOf, pathOfKey, placedOf, roomOfKey } from './rows.js';
4
+ import { byCodePoint, compared, cursorOf, FROM_START, MAXIMUM_WINDOW, } from './windows.js';
5
+ const VISIBLE = (alias) => `${alias}.visible = 1 AND ${alias}.present = 1 AND ${alias}.queried = 1`;
6
+ function fragment(sql, bind = []) {
7
+ return { sql, bind };
8
+ }
9
+ function joined(parts, separator) {
10
+ return {
11
+ sql: parts.map((part) => part.sql).join(separator),
12
+ bind: parts.flatMap((part) => part.bind),
13
+ };
14
+ }
15
+ function balanced(parts, separator) {
16
+ if (parts.length === 1)
17
+ return grouped(parts[0]);
18
+ const half = Math.ceil(parts.length / 2);
19
+ return grouped(joined([balanced(parts.slice(0, half), separator), balanced(parts.slice(half), separator)], separator));
20
+ }
21
+ function all(parts) {
22
+ return parts.length === 0 ? fragment('1') : balanced(parts, ' AND ');
23
+ }
24
+ function any(parts) {
25
+ return parts.length === 0 ? fragment('0') : balanced(parts, ' OR ');
26
+ }
27
+ function grouped(part) {
28
+ return { sql: `(${part.sql})`, bind: part.bind };
29
+ }
30
+ function list(values) {
31
+ return fragment(`(${values.map(() => '?').join(', ')})`, values);
32
+ }
33
+ function sqlValue(value) {
34
+ if (value === null)
35
+ return { kind: 'null', value: null };
36
+ if (typeof value === 'boolean')
37
+ return { kind: 'boolean', value: value ? 1 : 0 };
38
+ if (typeof value === 'number')
39
+ return { kind: 'number', value };
40
+ return { kind: 'string', value };
41
+ }
42
+ function same(alias, value) {
43
+ const held = sqlValue(value);
44
+ return held.kind === 'null'
45
+ ? fragment(`${alias}.kind = 'null'`)
46
+ : fragment(`${alias}.kind = ? AND ${alias}.value = ?`, [held.kind, held.value]);
47
+ }
48
+ const BOUNDS = { gt: '>', gte: '>=', lt: '<', lte: '<=' };
49
+ function pointed(alias, field, reach) {
50
+ const { keys, places, glob } = placedOf(field, reach);
51
+ return fragment(`${alias}.keys = ? AND ${alias}.places ${glob ? 'GLOB' : '='} ?`, [keys, places]);
52
+ }
53
+ function heldValues(doc, field, alias, where) {
54
+ return joined([
55
+ fragment(`SELECT 1 FROM replica_values ${alias} WHERE ${alias}.doc = ${doc}.id AND `),
56
+ grouped(pointed(alias, field, 'value')),
57
+ fragment(' AND '),
58
+ grouped(where),
59
+ ], '');
60
+ }
61
+ function exists(part) {
62
+ return { sql: `EXISTS (${part.sql})`, bind: part.bind };
63
+ }
64
+ function itemOf(held, where) {
65
+ return exists(joined([
66
+ fragment(`SELECT 1 FROM replica_values i WHERE i.doc = ${held}.doc AND i.keys = ${held}.keys AND i.places = ${held}.places AND i.item >= 0 AND `),
67
+ grouped(where),
68
+ ], ''));
69
+ }
70
+ function matching(held, values) {
71
+ return any(values.map((value) => any([
72
+ same(held, value),
73
+ all([fragment(`${held}.kind = 'array'`), itemOf(held, same('i', value))]),
74
+ ])));
75
+ }
76
+ function tested(doc, field, test) {
77
+ const reached = exists(heldValues(doc, field, 'r', fragment('r.item = -1')));
78
+ if (test.op === 'exists')
79
+ return test.exists ? reached : fragment(`NOT ${reached.sql}`, reached.bind);
80
+ if (test.op === 'eq' || test.op === 'in') {
81
+ const values = test.op === 'eq' ? [test.value] : test.values;
82
+ return exists(heldValues(doc, field, 'v', any(values.map((value) => same('v', value)))));
83
+ }
84
+ if (test.op === 'ne' || test.op === 'nin') {
85
+ const values = test.op === 'ne' ? [test.value] : test.values;
86
+ const unmatched = matching('h', values);
87
+ return any([
88
+ fragment(`NOT ${reached.sql}`, reached.bind),
89
+ exists(heldValues(doc, field, 'h', all([fragment('h.item = -1'), fragment(`NOT (${unmatched.sql})`, unmatched.bind)]))),
90
+ ]);
91
+ }
92
+ if (test.op === 'range') {
93
+ return exists(heldValues(doc, field, 'v', all([
94
+ fragment('v.item = -1'),
95
+ ...test.bounds.map(([operator, bound]) => {
96
+ const held = sqlValue(bound);
97
+ return fragment(`v.kind = ? AND v.value ${BOUNDS[operator]} ?`, [
98
+ held.kind,
99
+ held.value,
100
+ ]);
101
+ }),
102
+ ])));
103
+ }
104
+ if (test.op === 'all') {
105
+ return exists(heldValues(doc, field, 'h', all([
106
+ fragment("h.item = -1 AND h.kind = 'array'"),
107
+ ...test.values.map((value) => itemOf('h', same('i', value))),
108
+ ])));
109
+ }
110
+ return exists(heldValues(doc, field, 'v', fragment("v.item = -1 AND v.kind = 'array' AND v.size = ?", [test.size])));
111
+ }
112
+ function conditioned(doc, condition) {
113
+ if ('every' in condition)
114
+ return all(condition.every.map((one) => conditioned(doc, one)));
115
+ if ('some' in condition)
116
+ return any(condition.some.map((one) => conditioned(doc, one)));
117
+ return tested(doc, condition.field, condition.test);
118
+ }
119
+ function located(bound, alias) {
120
+ if (bound.rooms.length === 0)
121
+ return fragment("''");
122
+ return fragment(`CASE ${alias}.key ${bound.rooms.map(() => 'WHEN ? THEN ?').join(' ')} END`, bound.rooms.flatMap(({ key, locator }) => [key, locator]));
123
+ }
124
+ function reached(bound, alias) {
125
+ const reach = bound.reach;
126
+ if (reach === null)
127
+ return fragment('1');
128
+ const rooms = reach.rooms.flatMap((locator) => {
129
+ const key = bound.keys.get(locator);
130
+ return key === undefined ? [] : [key];
131
+ });
132
+ const documents = reach.documents.flatMap((held) => {
133
+ const key = bound.keys.get(roomOfKey(held));
134
+ return key === undefined ? [] : [[key, pathOfKey(held)]];
135
+ });
136
+ const areas = reach.areas.flatMap((area) => {
137
+ const key = bound.keys.get(area.room);
138
+ return key === undefined ? [] : [{ key, path: area.path, types: area.types }];
139
+ });
140
+ const beneath = (area) => fragment(`${alias}.key = ? AND (${alias}.path = ? OR (${alias}.path >= ? AND ${alias}.path < ?))`, [area.key, area.path, `${area.path}/`, `${area.path}0`]);
141
+ const typed = (types) => fragment(`${alias}.type IN ${list(types).sql}`, types);
142
+ const outside = any(areas.map((area) => area.types.length === 0
143
+ ? beneath(area)
144
+ : all([beneath(area), fragment(`NOT ${grouped(typed(area.types)).sql}`, area.types)])));
145
+ return all([
146
+ any([
147
+ ...(rooms.length === 0 ? [] : [fragment(`${alias}.key IN ${list(rooms).sql}`, rooms)]),
148
+ ...(documents.length === 0
149
+ ? []
150
+ : [
151
+ fragment(`EXISTS (SELECT 1 FROM json_each(?) j WHERE j.value ->> 0 = ${alias}.key AND j.value ->> 1 = ${alias}.path)`, [JSON.stringify(documents)]),
152
+ ]),
153
+ ...areas.flatMap((area) => area.types.length === 0 ? [] : [all([beneath(area), typed(area.types)])]),
154
+ ]),
155
+ ...(areas.length === 0 ? [] : [fragment(`NOT ${grouped(outside).sql}`, outside.bind)]),
156
+ ]);
157
+ }
158
+ function scoped(alias, scope) {
159
+ return all([
160
+ ...(scope.types === null
161
+ ? []
162
+ : [fragment(`${alias}.type IN ${list(scope.types).sql}`, scope.types)]),
163
+ ...(scope.pathPrefix === null || scope.pathPrefix === ''
164
+ ? []
165
+ : [
166
+ fragment(`${alias}.path >= ? AND ${alias}.path < ?`, [
167
+ `${scope.pathPrefix}/`,
168
+ `${scope.pathPrefix}0`,
169
+ ]),
170
+ ]),
171
+ ...(scope.where === null ? [] : [conditioned(alias, scope.where)]),
172
+ ]);
173
+ }
174
+ function related(bound, plan) {
175
+ const parts = [];
176
+ if (plan.hop !== null) {
177
+ parts.push(exists(joined([
178
+ fragment(`SELECT 1 FROM replica_links l JOIN replica_entries m ON m.key = d.key AND m.path = l.target AND ${VISIBLE('m')} WHERE l.doc = d.id AND l.kind = 'field' AND`),
179
+ grouped(pointed('l', plan.hop.field, 'link')),
180
+ fragment('AND'),
181
+ grouped(all([scoped('m', plan.hop), reached(bound, 'm')])),
182
+ ], ' ')));
183
+ }
184
+ if (plan.backlinks !== null) {
185
+ const field = plan.backlinks.field;
186
+ parts.push(exists(joined([
187
+ fragment(`SELECT 1 FROM replica_links l JOIN replica_entries s ON s.id = l.doc AND ${VISIBLE('s')} WHERE l.key = d.key AND l.target = d.path AND l.kind = 'field' AND`),
188
+ ...(field === null ? [] : [grouped(pointed('l', field, 'link')), fragment('AND')]),
189
+ grouped(all([scoped('s', plan.backlinks), reached(bound, 's')])),
190
+ ], ' ')));
191
+ }
192
+ return parts;
193
+ }
194
+ function filtered(bound, plan) {
195
+ const keys = bound.rooms.map(({ key }) => key);
196
+ return all([
197
+ fragment(`d.key IN ${list(keys).sql} AND ${VISIBLE('d')}`, keys),
198
+ ...(plan.paths === null ? [] : [fragment(`d.path IN ${list(plan.paths).sql}`, plan.paths)]),
199
+ ...(plan.folder === null ? [] : [fragment('d.folder = ?', [plan.folder])]),
200
+ reached(bound, 'd'),
201
+ scoped('d', plan.root),
202
+ ...related(bound, plan),
203
+ ]);
204
+ }
205
+ function orderingOf(options) {
206
+ const stringSort = options.stringSort ?? 'locale';
207
+ const collated = stringSort === 'locale';
208
+ return {
209
+ direction: options.direction,
210
+ nulls: options.nulls ?? 'first',
211
+ stringSort,
212
+ locale: collated ? options.locale : undefined,
213
+ localeOptions: collated
214
+ ? options.localeOptions
215
+ : undefined,
216
+ };
217
+ }
218
+ const GROUP_ORDER = {
219
+ direction: 'asc',
220
+ nulls: 'first',
221
+ stringSort: 'locale',
222
+ locale: undefined,
223
+ localeOptions: undefined,
224
+ };
225
+ const GROUP_TIES = {
226
+ direction: 'asc',
227
+ nulls: 'last',
228
+ stringSort: 'lexical',
229
+ locale: undefined,
230
+ localeOptions: undefined,
231
+ };
232
+ function classOf(value, ordering) {
233
+ if (value === null || value === undefined) {
234
+ return { placement: ordering.nulls === 'first' ? 0 : 2, klass: 0, scalar: null };
235
+ }
236
+ if (typeof value === 'boolean')
237
+ return { placement: 1, klass: 1, scalar: value ? 1 : 0 };
238
+ if (typeof value === 'number')
239
+ return { placement: 1, klass: 1, scalar: value };
240
+ if (typeof value === 'string')
241
+ return { placement: 1, klass: 2, scalar: value };
242
+ return { placement: 1, klass: 3, scalar: JSON.stringify(value) };
243
+ }
244
+ function placement(term) {
245
+ const nulls = term.ordering.nulls === 'first' ? 0 : 2;
246
+ return fragment(`CASE WHEN ${term.kind.sql} IS NULL OR ${term.kind.sql} = 'null' THEN ${nulls} ELSE 1 END`, [...term.kind.bind, ...term.kind.bind]);
247
+ }
248
+ function klass(term) {
249
+ return fragment(`CASE ${term.kind.sql} WHEN 'boolean' THEN 1 WHEN 'number' THEN 1 WHEN 'string' THEN 2 WHEN 'array' THEN 3 ELSE 4 END`, term.kind.bind);
250
+ }
251
+ function classed(term, which) {
252
+ const kinds = which === 1 ? "('boolean', 'number')" : which === 2 ? "('string')" : "('array')";
253
+ return fragment(`(CASE WHEN ${term.kind.sql} IN ${kinds} THEN ${term.value.sql} END)`, [
254
+ ...term.kind.bind,
255
+ ...term.value.bind,
256
+ ]);
257
+ }
258
+ function collated(bound, term, which) {
259
+ if (which === 1)
260
+ return '';
261
+ const name = bound.collate(term.ordering, which === 3, term.total === true);
262
+ return name === null ? '' : ` COLLATE ${name}`;
263
+ }
264
+ function sorted(bound, term) {
265
+ const direction = term.ordering.direction === 'desc' ? 'DESC' : 'ASC';
266
+ return joined([
267
+ placement(term),
268
+ fragment(`${klass(term).sql} ${direction}`, klass(term).bind),
269
+ ...[1, 2, 3].map((which) => {
270
+ const value = classed(term, which);
271
+ return fragment(`${value.sql}${collated(bound, term, which)} ${direction}`, value.bind);
272
+ }),
273
+ ], ', ');
274
+ }
275
+ function beyond(bound, term, value) {
276
+ const held = classOf(value, term.ordering);
277
+ const place = placement(term);
278
+ if (held.placement !== 1) {
279
+ return {
280
+ beyond: fragment(`${place.sql} > ${held.placement}`, place.bind),
281
+ equal: fragment(`${place.sql} = ${held.placement}`, place.bind),
282
+ };
283
+ }
284
+ const after = term.ordering.direction === 'desc' ? '<' : '>';
285
+ const kind = klass(term);
286
+ const scalar = classed(term, held.klass);
287
+ const collation = collated(bound, term, held.klass);
288
+ return {
289
+ beyond: any([
290
+ fragment(`${place.sql} > 1`, place.bind),
291
+ all([
292
+ fragment(`${place.sql} = 1`, place.bind),
293
+ any([
294
+ fragment(`${kind.sql} ${after} ${held.klass}`, kind.bind),
295
+ all([
296
+ fragment(`${kind.sql} = ${held.klass}`, kind.bind),
297
+ fragment(`${scalar.sql} ${after} ?${collation}`, [...scalar.bind, held.scalar]),
298
+ ]),
299
+ ]),
300
+ ]),
301
+ ]),
302
+ equal: all([
303
+ fragment(`${place.sql} = 1 AND ${kind.sql} = ${held.klass}`, [...place.bind, ...kind.bind]),
304
+ fragment(`${scalar.sql} = ?${collation}`, [...scalar.bind, held.scalar]),
305
+ ]),
306
+ };
307
+ }
308
+ function following(parts, tie) {
309
+ let condition = tie;
310
+ for (const part of [...parts].reverse()) {
311
+ condition = any([part.beyond, all([part.equal, condition])]);
312
+ }
313
+ return condition;
314
+ }
315
+ function keyTerm(bound, key, ordering, index) {
316
+ if (key.of === 'field') {
317
+ const alias = `o${index}`;
318
+ return {
319
+ term: { ordering, kind: fragment(`${alias}.kind`), value: fragment(`${alias}.value`) },
320
+ join: joined([
321
+ fragment(`LEFT JOIN replica_values ${alias} ON ${alias}.doc = d.id AND `),
322
+ grouped(pointed(alias, key.field, 'exact')),
323
+ fragment(` AND ${alias}.item = -1 AND ${alias}.kind NOT IN ('object', 'undefined')`),
324
+ ], ''),
325
+ };
326
+ }
327
+ const expression = key.of === 'room'
328
+ ? located(bound, 'd')
329
+ : key.of === 'path'
330
+ ? fragment('d.path')
331
+ : key.of === 'type'
332
+ ? fragment('d.type')
333
+ : fragment('d.folder');
334
+ return {
335
+ term: {
336
+ ordering,
337
+ kind: fragment(`(CASE WHEN ${expression.sql} IS NULL THEN 'null' ELSE 'string' END)`, expression.bind),
338
+ value: expression,
339
+ },
340
+ join: null,
341
+ };
342
+ }
343
+ function decoded(kind, value) {
344
+ if (kind === 'string')
345
+ return value;
346
+ if (kind === 'number')
347
+ return typeof value === 'bigint' ? Number(value) : value;
348
+ if (kind === 'boolean')
349
+ return Number(value) === 1;
350
+ if (kind === 'array')
351
+ return JSON.parse(value);
352
+ return null;
353
+ }
354
+ function decodedKey(key, row, index) {
355
+ if (key.of === 'field') {
356
+ const kind = row[`k${index}`];
357
+ return kind === null || kind === undefined ? undefined : decoded(kind, row[`v${index}`]);
358
+ }
359
+ return row[`v${index}`] ?? null;
360
+ }
361
+ const registered = new WeakMap();
362
+ function hashed(text) {
363
+ let hash = 0x811c9dc5;
364
+ for (let index = 0; index < text.length; index += 1) {
365
+ hash ^= text.charCodeAt(index);
366
+ hash = Math.imul(hash, 0x01000193);
367
+ }
368
+ return (hash >>> 0).toString(36);
369
+ }
370
+ function collating(connection) {
371
+ let held = registered.get(connection);
372
+ if (held === undefined) {
373
+ held = new Set();
374
+ registered.set(connection, held);
375
+ }
376
+ const names = held;
377
+ return (ordering, lists, total) => {
378
+ if (!lists && ordering.stringSort !== 'locale')
379
+ return null;
380
+ const inner = lists
381
+ ? {
382
+ ...ordering,
383
+ direction: 'asc',
384
+ nulls: ordering.direction === 'desc'
385
+ ? ordering.nulls === 'first'
386
+ ? 'last'
387
+ : 'first'
388
+ : ordering.nulls,
389
+ }
390
+ : ordering;
391
+ const spec = JSON.stringify([
392
+ lists,
393
+ total,
394
+ inner.nulls,
395
+ inner.stringSort,
396
+ inner.locale ?? null,
397
+ inner.localeOptions ?? null,
398
+ ]);
399
+ const name = `mdr_${lists ? 'l' : 's'}${hashed(spec)}`;
400
+ if (!names.has(name)) {
401
+ const collator = new Intl.Collator(inner.locale, inner.localeOptions);
402
+ connection.collate(name, lists
403
+ ? (left, right) => Math.sign(compared(JSON.parse(left), JSON.parse(right), inner)) || (total ? Math.sign(byCodePoint(left, right)) : 0)
404
+ : (left, right) => Math.sign(collator.compare(left, right)));
405
+ names.add(name);
406
+ }
407
+ return name;
408
+ };
409
+ }
410
+ function bodied(shape) {
411
+ return shape.sections !== null || shape.preamble || shape.markdown;
412
+ }
413
+ function masked(pointers) {
414
+ const root = { whole: false, members: new Map() };
415
+ for (const pointer of pointers) {
416
+ let mask = root;
417
+ for (const token of pointerSegments(pointer)) {
418
+ const next = mask.members.get(token) ?? { whole: false, members: new Map() };
419
+ mask.members.set(token, next);
420
+ mask = next;
421
+ }
422
+ mask.whole = true;
423
+ }
424
+ return root;
425
+ }
426
+ function merged(left, right) {
427
+ if (left === undefined)
428
+ return right;
429
+ const members = new Map(left.members);
430
+ for (const [token, mask] of right.members)
431
+ members.set(token, merged(members.get(token), mask));
432
+ return { whole: left.whole || right.whole, members };
433
+ }
434
+ function cut(value, mask) {
435
+ if (mask.whole)
436
+ return value;
437
+ if (Array.isArray(value)) {
438
+ const each = {
439
+ whole: false,
440
+ members: new Map([...mask.members].filter(([token]) => !ARRAY_INDEX.test(token))),
441
+ };
442
+ const kept = [];
443
+ value.forEach((item, index) => {
444
+ const part = cut(item, merged(mask.members.get(String(index)), each));
445
+ if (part !== undefined)
446
+ kept[index] = part;
447
+ });
448
+ return kept.length === 0 ? undefined : kept;
449
+ }
450
+ if (typeof value !== 'object' || value === null)
451
+ return undefined;
452
+ const kept = Object.entries(value).flatMap(([key, held]) => {
453
+ const member = mask.members.get(key);
454
+ const part = member === undefined ? undefined : cut(held, member);
455
+ return part === undefined ? [] : [[key, part]];
456
+ });
457
+ return kept.length === 0 ? undefined : Object.fromEntries(kept);
458
+ }
459
+ function sectionsOf(sections, names) {
460
+ if (names === 'all')
461
+ return sections;
462
+ return Object.fromEntries(names.flatMap((name) => (Object.hasOwn(sections, name) ? [[name, sections[name]]] : [])));
463
+ }
464
+ function documentOf(shape, room, row, linked) {
465
+ const path = row.path;
466
+ const type = row.type;
467
+ const fileId = row.file_id ?? null;
468
+ const revision = row.revision ?? null;
469
+ if (type === null) {
470
+ const binary = row.binary === null ? null : JSON.parse(row.binary);
471
+ const content = row.content ?? null;
472
+ return {
473
+ room,
474
+ path,
475
+ ...(binary === null
476
+ ? {}
477
+ : {
478
+ binaryFile: binaryRecord(path, binary, revision ?? undefined),
479
+ }),
480
+ ...(shape.markdown && content !== null ? { markdown: content } : {}),
481
+ ...(shape.fileId ? { fileId } : {}),
482
+ ...(shape.revision ? { revision } : {}),
483
+ };
484
+ }
485
+ const read = bodied(shape) ? parse(row.content, path) : null;
486
+ const body = read?.ok === true ? read.document : null;
487
+ const fields = JSON.parse(row.fields ?? '{}');
488
+ return {
489
+ room,
490
+ path,
491
+ type,
492
+ ...(shape.fields === null
493
+ ? {}
494
+ : {
495
+ fields: shape.fields === 'all'
496
+ ? fields
497
+ : (cut(fields, masked(shape.fields)) ?? {}),
498
+ }),
499
+ ...(shape.sections === null || body === null
500
+ ? {}
501
+ : { sections: sectionsOf(body.sections, shape.sections) }),
502
+ ...(shape.preamble && body !== null ? { preamble: body.preamble } : {}),
503
+ ...(shape.markdown && body !== null ? { markdown: body.content } : {}),
504
+ ...(shape.backlinks ? { backlinks: linked.get(documentKey(room, path)) ?? [] } : {}),
505
+ ...(shape.change
506
+ ? {
507
+ change: row.change === null ? null : JSON.parse(row.change),
508
+ }
509
+ : {}),
510
+ ...(shape.fileId ? { fileId } : {}),
511
+ ...(shape.revision ? { revision } : {}),
512
+ };
513
+ }
514
+ function backlinksOf(connection, bound, rows) {
515
+ const linked = new Map();
516
+ const byKey = new Map();
517
+ for (const row of rows) {
518
+ const key = Number(row.key);
519
+ const held = byKey.get(key) ?? [];
520
+ held.push(row.path);
521
+ byKey.set(key, held);
522
+ }
523
+ for (const [key, targets] of byKey) {
524
+ const reach = reached(bound, 's');
525
+ const room = bound.rooms.find((one) => one.key === key).locator;
526
+ const found = connection.rows(`SELECT target, path, type, field FROM (SELECT l.target, s.path, s.type, l.field, ROW_NUMBER() OVER (PARTITION BY l.target ORDER BY s.path, l.field) AS rank FROM (SELECT DISTINCT doc, target, field FROM replica_links WHERE key = ? AND kind = 'field' AND target IN (SELECT value FROM json_each(?))) l JOIN replica_entries s ON s.id = l.doc AND ${VISIBLE('s')} WHERE ${reach.sql}) WHERE rank <= ? ORDER BY target, path, field`, [key, JSON.stringify(targets), ...reach.bind, MAXIMUM_WINDOW]);
527
+ for (const row of found) {
528
+ const at = documentKey(room, row.target);
529
+ const held = linked.get(at) ?? [];
530
+ held.push({ path: row.path, type: row.type, field: row.field });
531
+ linked.set(at, held);
532
+ }
533
+ }
534
+ return linked;
535
+ }
536
+ function documents(connection, bound, plan, shape, budget) {
537
+ const terms = shape.orderBy.map(({ key, options }, index) => keyTerm(bound, key, orderingOf(options), index));
538
+ const filter = filtered(bound, plan);
539
+ const cursor = plan.after?.values ?? null;
540
+ const room = located(bound, 'd');
541
+ const tie = cursor === null
542
+ ? null
543
+ : (() => {
544
+ const key = cursor[shape.orderBy.length];
545
+ return any([
546
+ fragment(`${room.sql} > ?`, [...room.bind, roomOfKey(key)]),
547
+ fragment(`${room.sql} = ? AND d.path > ?`, [
548
+ ...room.bind,
549
+ roomOfKey(key),
550
+ pathOfKey(key),
551
+ ]),
552
+ ]);
553
+ })();
554
+ const after = cursor === null || tie === null
555
+ ? null
556
+ : following(terms.map(({ term }, index) => beyond(bound, term, cursor[index])), tie);
557
+ const selected = joined([
558
+ fragment('SELECT d.id, d.key, d.path, d.type, d.binary, d.revision, d.fields, d.change, d.file_id'),
559
+ ...terms.map(({ term }, index) => joined([
560
+ fragment(`, ${term.kind.sql} AS k${index}`, term.kind.bind),
561
+ fragment(`, ${term.value.sql} AS v${index}`, term.value.bind),
562
+ ], '')),
563
+ fragment(' FROM replica_entries d'),
564
+ ...terms.flatMap(({ join }) => (join === null ? [] : [fragment(' '), join])),
565
+ fragment(' WHERE '),
566
+ after === null ? filter : all([filter, after]),
567
+ fragment(' ORDER BY '),
568
+ joined([...terms.map(({ term }) => sorted(bound, term)), room, fragment('d.path')], ', '),
569
+ ...(plan.limit === null ? [] : [fragment(' LIMIT ?', [plan.limit + 1])]),
570
+ ], '');
571
+ const rows = connection.rows(selected.sql, selected.bind);
572
+ const windowed = plan.limit === null ? rows : rows.slice(0, plan.limit);
573
+ const kept = bodied(shape) ? withContent(connection, windowed, budget) : windowed;
574
+ const cut = kept.length;
575
+ const roomOf = new Map(bound.rooms.map(({ key, locator }) => [key, locator]));
576
+ const linked = shape.backlinks ? backlinksOf(connection, bound, kept) : new Map();
577
+ const found = kept.map((row) => documentOf(shape, roomOf.get(Number(row.key)), row, linked));
578
+ const last = kept.at(-1);
579
+ const cursorAt = (row) => cursorOf([
580
+ ...shape.orderBy.map(({ key }, index) => decodedKey(key, row, index)),
581
+ documentKey(roomOf.get(Number(row.key)), row.path),
582
+ ]);
583
+ const more = cut < windowed.length && last !== undefined ? cursorAt(last) : undefined;
584
+ const next = more !== undefined || plan.limit === null || rows.length <= plan.limit
585
+ ? undefined
586
+ : last === undefined
587
+ ? (plan.after?.text ?? FROM_START)
588
+ : cursorAt(last);
589
+ const total = plan.total
590
+ ? (() => {
591
+ const counted = joined([fragment('SELECT count(*) AS held FROM replica_entries d WHERE '), filter], '');
592
+ return Number(connection.rows(counted.sql, counted.bind)[0].held);
593
+ })()
594
+ : undefined;
595
+ return {
596
+ documents: found,
597
+ ...(next === undefined ? {} : { next }),
598
+ ...(more === undefined ? {} : { more }),
599
+ ...(total === undefined ? {} : { total }),
600
+ };
601
+ }
602
+ function withContent(connection, rows, budget) {
603
+ if (rows.length === 0)
604
+ return rows;
605
+ const ids = rows.map((row) => row.id);
606
+ const sizes = new Map(connection
607
+ .rows(`SELECT id, octet_length(content) AS size FROM replica_entries WHERE id IN ${list(ids).sql}`, ids)
608
+ .map((row) => [row.id, Number(row.size ?? 0)]));
609
+ let cut = rows.length;
610
+ let spent = 0;
611
+ for (let at = 0; budget !== null && at < rows.length; at += 1) {
612
+ const size = sizes.get(rows[at].id) ?? 0;
613
+ if (at > 0 && spent + size > budget) {
614
+ cut = at;
615
+ break;
616
+ }
617
+ spent += size;
618
+ }
619
+ const kept = rows.slice(0, cut);
620
+ const read = kept.map((row) => row.id);
621
+ const held = new Map(connection
622
+ .rows(`SELECT id, content FROM replica_entries WHERE id IN ${list(read).sql}`, read)
623
+ .map((row) => [row.id, row.content]));
624
+ return kept.map((row) => ({ ...row, content: held.get(row.id) ?? null }));
625
+ }
626
+ function storedFolders(bound, plan) {
627
+ if (plan.paths !== null || plan.hop !== null || plan.backlinks !== null)
628
+ return null;
629
+ const whole = bound.rooms.filter(({ locator }) => bound.reach === null || bound.reach.rooms.includes(locator));
630
+ if (whole.length === 0)
631
+ return null;
632
+ const keys = whole.map(({ key }) => key);
633
+ const prefix = plan.root.pathPrefix;
634
+ const fenced = (bound.reach?.areas ?? []).flatMap((area) => {
635
+ const key = bound.keys.get(area.room);
636
+ return key === undefined
637
+ ? []
638
+ : [
639
+ fragment('NOT (f.key = ? AND (f.path = ? OR (f.path >= ? AND f.path < ?)))', [
640
+ key,
641
+ area.path,
642
+ `${area.path}/`,
643
+ `${area.path}0`,
644
+ ]),
645
+ ];
646
+ });
647
+ return all([
648
+ fragment(`f.key IN ${list(keys).sql} AND f.layer = 0 AND f.present = 1`, keys),
649
+ ...fenced,
650
+ ...(prefix === null || prefix === ''
651
+ ? []
652
+ : [
653
+ fragment('(f.path = ? OR (f.path >= ? AND f.path < ?))', [
654
+ prefix,
655
+ `${prefix}/`,
656
+ `${prefix}0`,
657
+ ]),
658
+ ]),
659
+ ...(plan.folder === null ? [] : [fragment('f.path = ?', [plan.folder])]),
660
+ ]);
661
+ }
662
+ function groups(connection, bound, plan, shape) {
663
+ const keyed = shape.groupBy.map((key, index) => {
664
+ const { term, join } = keyTerm(bound, key, GROUP_ORDER, index);
665
+ const kind = fragment(`COALESCE(${term.kind.sql}, 'null')`, term.kind.bind);
666
+ return { term: { ...term, kind }, join };
667
+ });
668
+ const filter = filtered(bound, plan);
669
+ const inner = joined([
670
+ fragment('SELECT '),
671
+ joined(keyed.map(({ term }, index) => joined([
672
+ fragment(`${term.kind.sql} AS k${index}`, term.kind.bind),
673
+ fragment(`, ${term.value.sql} AS v${index}`, term.value.bind),
674
+ ], '')), ', '),
675
+ fragment(', 1 AS n FROM replica_entries d'),
676
+ ...keyed.flatMap(({ join }) => (join === null ? [] : [fragment(' '), join])),
677
+ fragment(' WHERE '),
678
+ filter,
679
+ ], '');
680
+ const folders = shape.groupBy.length === 1 && shape.groupBy[0].of === 'folder'
681
+ ? storedFolders(bound, plan)
682
+ : null;
683
+ const source = folders === null
684
+ ? inner
685
+ : joined([
686
+ inner,
687
+ fragment(" UNION ALL SELECT 'string' AS k0, f.path AS v0, 0 AS n FROM replica_folders f WHERE "),
688
+ folders,
689
+ ], '');
690
+ const columns = keyed.map((_, index) => `k${index}, v${index}`).join(', ');
691
+ const counted = {
692
+ ordering: { ...GROUP_ORDER },
693
+ kind: fragment("'number'"),
694
+ value: fragment('n'),
695
+ };
696
+ const outer = (index, ordering) => ({
697
+ ordering,
698
+ kind: fragment(`k${index}`),
699
+ value: fragment(`v${index}`),
700
+ });
701
+ const ordered = shape.orderBy.map(({ by, direction }) => by === 'count'
702
+ ? { ...counted, ordering: { ...GROUP_ORDER, direction } }
703
+ : outer(by, { ...GROUP_ORDER, direction }));
704
+ const ties = keyed.flatMap((_, index) => [
705
+ { ...outer(index, GROUP_TIES), total: true },
706
+ { ordering: GROUP_TIES, kind: fragment("'string'"), value: fragment(`k${index}`) },
707
+ ]);
708
+ const cursor = plan.after?.values ?? null;
709
+ const tieValues = cursor === null
710
+ ? null
711
+ : cursor[shape.orderBy.length].flatMap((value) => [
712
+ value,
713
+ kindOf(value ?? null),
714
+ ]);
715
+ const after = cursor === null || tieValues === null
716
+ ? null
717
+ : following(ordered.map((term, index) => beyond(bound, term, cursor[index])), following(ties.slice(0, -1).map((term, index) => beyond(bound, term, tieValues[index])), beyond(bound, ties.at(-1), tieValues.at(-1)).beyond));
718
+ const grouping = joined([fragment(`SELECT ${columns}, sum(n) AS n FROM (`), source, fragment(`) GROUP BY ${columns}`)], '');
719
+ const windowed = joined([
720
+ fragment('SELECT * FROM ('),
721
+ grouping,
722
+ fragment(')'),
723
+ ...(after === null ? [] : [fragment(' WHERE '), after]),
724
+ fragment(' ORDER BY '),
725
+ joined([...ordered, ...ties].map((term) => sorted(bound, term)), ', '),
726
+ ...(plan.limit === null ? [] : [fragment(' LIMIT ?', [plan.limit + 1])]),
727
+ ], '');
728
+ const rows = connection.rows(windowed.sql, windowed.bind);
729
+ const kept = plan.limit === null ? rows : rows.slice(0, plan.limit);
730
+ const keyOf = (row) => keyed.map((_, index) => decoded(row[`k${index}`], row[`v${index}`]));
731
+ const found = kept.map((row) => ({ key: keyOf(row), count: Number(row.n) }));
732
+ const last = kept.at(-1);
733
+ const next = plan.limit === null || rows.length <= plan.limit
734
+ ? undefined
735
+ : last === undefined
736
+ ? (plan.after?.text ?? FROM_START)
737
+ : cursorOf([
738
+ ...shape.orderBy.map(({ by }) => by === 'count' ? Number(last.n) : decoded(last[`k${by}`], last[`v${by}`])),
739
+ keyOf(last),
740
+ ]);
741
+ const total = plan.total
742
+ ? Number(connection.rows(joined([fragment('SELECT count(*) AS held FROM ('), grouping, fragment(')')], '').sql, grouping.bind)[0].held)
743
+ : undefined;
744
+ return {
745
+ groups: found,
746
+ ...(next === undefined ? {} : { next }),
747
+ ...(total === undefined ? {} : { total }),
748
+ };
749
+ }
750
+ function boundOf(connection, plan, rooms) {
751
+ return {
752
+ rooms: [...rooms].sort((left, right) => left.locator < right.locator ? -1 : left.locator > right.locator ? 1 : 0),
753
+ keys: new Map(rooms.map(({ locator, key }) => [locator, key])),
754
+ reach: plan.reach,
755
+ collate: collating(connection),
756
+ };
757
+ }
758
+ export function selected(connection, plan, rooms) {
759
+ return filtered(boundOf(connection, plan, rooms), plan);
760
+ }
761
+ export function answerQuery(connection, plan, rooms, budget = null) {
762
+ const bound = boundOf(connection, plan, rooms);
763
+ if (rooms.length === 0) {
764
+ return plan.shape.kind === 'groups'
765
+ ? { groups: [], ...(plan.total ? { total: 0 } : {}) }
766
+ : { documents: [], ...(plan.total ? { total: 0 } : {}) };
767
+ }
768
+ return plan.shape.kind === 'groups'
769
+ ? groups(connection, bound, plan, plan.shape)
770
+ : documents(connection, bound, plan, plan.shape, budget);
771
+ }