@agentshouse/mdruntime 0.1.0-ca4dc698bd0c4 → 0.1.0-ca6edc1abd618

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