@agentshouse/mdruntime 0.1.0-c454894e67f74 → 0.1.0-c4ca57eefb98a

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