@agentshouse/mdruntime 0.1.0-c698c0ebd65bd → 0.1.0-c6dd3e87e3f5e

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