@elaraai/e3 1.0.98 → 1.0.100

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 (146) hide show
  1. package/README.md +4 -5
  2. package/dist/src/browser.d.ts +2 -0
  3. package/dist/src/browser.d.ts.map +1 -1
  4. package/dist/src/browser.js +6 -0
  5. package/dist/src/browser.js.map +1 -1
  6. package/dist/src/environment-capture.d.ts +21 -0
  7. package/dist/src/environment-capture.d.ts.map +1 -1
  8. package/dist/src/environment-capture.js +48 -0
  9. package/dist/src/environment-capture.js.map +1 -1
  10. package/dist/src/export.d.ts +10 -5
  11. package/dist/src/export.d.ts.map +1 -1
  12. package/dist/src/export.js +31 -47
  13. package/dist/src/export.js.map +1 -1
  14. package/dist/src/export.spec.js +27 -16
  15. package/dist/src/export.spec.js.map +1 -1
  16. package/dist/src/function.d.ts.map +1 -1
  17. package/dist/src/function.js.map +1 -1
  18. package/dist/src/functions-cache.d.ts +60 -0
  19. package/dist/src/functions-cache.d.ts.map +1 -0
  20. package/dist/src/functions-cache.js +165 -0
  21. package/dist/src/functions-cache.js.map +1 -0
  22. package/dist/src/functions-link.spec.js +191 -12
  23. package/dist/src/functions-link.spec.js.map +1 -1
  24. package/dist/src/functions-resolve.d.ts +52 -23
  25. package/dist/src/functions-resolve.d.ts.map +1 -1
  26. package/dist/src/functions-resolve.js +244 -96
  27. package/dist/src/functions-resolve.js.map +1 -1
  28. package/dist/src/index.d.ts +8 -61
  29. package/dist/src/index.d.ts.map +1 -1
  30. package/dist/src/index.js +3 -8
  31. package/dist/src/index.js.map +1 -1
  32. package/dist/src/internal.d.ts +53 -0
  33. package/dist/src/internal.d.ts.map +1 -0
  34. package/dist/src/internal.js +29 -0
  35. package/dist/src/internal.js.map +1 -0
  36. package/dist/src/lazy-build.d.ts +25 -0
  37. package/dist/src/lazy-build.d.ts.map +1 -0
  38. package/dist/src/lazy-build.js +56 -0
  39. package/dist/src/lazy-build.js.map +1 -0
  40. package/dist/src/lazy-build.spec.d.ts +6 -0
  41. package/dist/src/lazy-build.spec.d.ts.map +1 -0
  42. package/dist/src/lazy-build.spec.js +153 -0
  43. package/dist/src/lazy-build.spec.js.map +1 -0
  44. package/dist/src/migration.d.ts +20 -163
  45. package/dist/src/migration.d.ts.map +1 -1
  46. package/dist/src/migration.js +37 -34
  47. package/dist/src/migration.js.map +1 -1
  48. package/dist/src/migration.spec.js +83 -78
  49. package/dist/src/migration.spec.js.map +1 -1
  50. package/dist/src/mutation-programs.spec.js +211 -118
  51. package/dist/src/mutation-programs.spec.js.map +1 -1
  52. package/dist/src/mutation.d.ts +37 -141
  53. package/dist/src/mutation.d.ts.map +1 -1
  54. package/dist/src/mutation.js +66 -28
  55. package/dist/src/mutation.js.map +1 -1
  56. package/dist/src/open-beast-link.spec.js +1 -1
  57. package/dist/src/open-beast-link.spec.js.map +1 -1
  58. package/dist/src/output.js.map +1 -1
  59. package/dist/src/package.d.ts +2 -38
  60. package/dist/src/package.d.ts.map +1 -1
  61. package/dist/src/package.js +42 -175
  62. package/dist/src/package.js.map +1 -1
  63. package/dist/src/record-area.d.ts +49 -37
  64. package/dist/src/record-area.d.ts.map +1 -1
  65. package/dist/src/record-area.js +211 -131
  66. package/dist/src/record-area.js.map +1 -1
  67. package/dist/src/record-area.spec.js +79 -62
  68. package/dist/src/record-area.spec.js.map +1 -1
  69. package/dist/src/record-arguments.d.ts +55 -0
  70. package/dist/src/record-arguments.d.ts.map +1 -0
  71. package/dist/src/record-arguments.js +72 -0
  72. package/dist/src/record-arguments.js.map +1 -0
  73. package/dist/src/record-builders.d.ts +547 -0
  74. package/dist/src/record-builders.d.ts.map +1 -0
  75. package/dist/src/record-builders.js +112 -0
  76. package/dist/src/record-builders.js.map +1 -0
  77. package/dist/src/record-declared.spec.d.ts +6 -0
  78. package/dist/src/record-declared.spec.d.ts.map +1 -0
  79. package/dist/src/record-declared.spec.js +251 -0
  80. package/dist/src/record-declared.spec.js.map +1 -0
  81. package/dist/src/record-guards.d.ts +114 -1
  82. package/dist/src/record-guards.d.ts.map +1 -1
  83. package/dist/src/record-guards.js +153 -2
  84. package/dist/src/record-guards.js.map +1 -1
  85. package/dist/src/record-index.d.ts +128 -350
  86. package/dist/src/record-index.d.ts.map +1 -1
  87. package/dist/src/record-index.js +44 -481
  88. package/dist/src/record-index.js.map +1 -1
  89. package/dist/src/record-index.spec.js +124 -90
  90. package/dist/src/record-index.spec.js.map +1 -1
  91. package/dist/src/record-interval.d.ts +57 -36
  92. package/dist/src/record-interval.d.ts.map +1 -1
  93. package/dist/src/record-interval.js +136 -94
  94. package/dist/src/record-interval.js.map +1 -1
  95. package/dist/src/record-interval.spec.js +48 -27
  96. package/dist/src/record-interval.spec.js.map +1 -1
  97. package/dist/src/record-keys.d.ts +146 -0
  98. package/dist/src/record-keys.d.ts.map +1 -0
  99. package/dist/src/record-keys.js +178 -0
  100. package/dist/src/record-keys.js.map +1 -0
  101. package/dist/src/record-nested-programs.d.ts +1457 -0
  102. package/dist/src/record-nested-programs.d.ts.map +1 -0
  103. package/dist/src/record-nested-programs.js +1974 -0
  104. package/dist/src/record-nested-programs.js.map +1 -0
  105. package/dist/src/record-nested.d.ts +284 -0
  106. package/dist/src/record-nested.d.ts.map +1 -0
  107. package/dist/src/record-nested.js +304 -0
  108. package/dist/src/record-nested.js.map +1 -0
  109. package/dist/src/record-nested.spec.d.ts +6 -0
  110. package/dist/src/record-nested.spec.d.ts.map +1 -0
  111. package/dist/src/record-nested.spec.js +1032 -0
  112. package/dist/src/record-nested.spec.js.map +1 -0
  113. package/dist/src/record-patches.d.ts +25 -0
  114. package/dist/src/record-patches.d.ts.map +1 -0
  115. package/dist/src/record-patches.js +27 -0
  116. package/dist/src/record-patches.js.map +1 -0
  117. package/dist/src/record-programs.d.ts +192 -26
  118. package/dist/src/record-programs.d.ts.map +1 -1
  119. package/dist/src/record-programs.js +858 -350
  120. package/dist/src/record-programs.js.map +1 -1
  121. package/dist/src/record-programs.spec.d.ts +6 -0
  122. package/dist/src/record-programs.spec.d.ts.map +1 -0
  123. package/dist/src/record-programs.spec.js +242 -0
  124. package/dist/src/record-programs.spec.js.map +1 -0
  125. package/dist/src/record-series.d.ts +101 -97
  126. package/dist/src/record-series.d.ts.map +1 -1
  127. package/dist/src/record-series.js +198 -149
  128. package/dist/src/record-series.js.map +1 -1
  129. package/dist/src/record-series.spec.js +241 -120
  130. package/dist/src/record-series.spec.js.map +1 -1
  131. package/dist/src/record-tiles.d.ts +328 -37
  132. package/dist/src/record-tiles.d.ts.map +1 -1
  133. package/dist/src/record-tiles.js +289 -100
  134. package/dist/src/record-tiles.js.map +1 -1
  135. package/dist/src/record.d.ts +66 -12
  136. package/dist/src/record.d.ts.map +1 -1
  137. package/dist/src/record.js +103 -34
  138. package/dist/src/record.js.map +1 -1
  139. package/dist/src/record.spec.js +48 -63
  140. package/dist/src/record.spec.js.map +1 -1
  141. package/dist/src/task.d.ts.map +1 -1
  142. package/dist/src/task.js +4 -1
  143. package/dist/src/task.js.map +1 -1
  144. package/dist/src/types.d.ts +103 -37
  145. package/dist/src/types.d.ts.map +1 -1
  146. package/package.json +7 -3
@@ -0,0 +1,1974 @@
1
+ /**
2
+ * Copyright (c) 2025 Elara AI Pty Ltd
3
+ * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details.
4
+ */
5
+ /**
6
+ * The East programs a nested series index's declaration builds (#1434): a
7
+ * row's entries, `(K, V) → Dict<IK, P>`, and its lean form, `(K, V) → V`.
8
+ *
9
+ * A row's nodes are walked a group at a time ({@link NestedGroup}): the row
10
+ * itself, then each group's nodes from its parent group's — a node's child
11
+ * rows under its field, and beside `recursive()` every row beneath them
12
+ * through it, by East's `flattenTree`. Each node carries its path, the Dict
13
+ * keys from the row down, and the node above it. Of a collection's group:
14
+ *
15
+ * - each item is filed by #1433's levels (`eventFilings`), carrying the item;
16
+ * - each node's totals are kept a summary tile at a time;
17
+ * - an item rolled up is filed under every ancestor too, and each ancestor
18
+ * keeps its subtree's totals;
19
+ * - a collection of values rolled up keeps every parent's subtotals, composed
20
+ * bottom-up by East's `toTree` over the nodes from the row down to it, each
21
+ * node's result carrying its subtree's subtotals to its parent.
22
+ *
23
+ * A write is maintained by its patch where the patch can say what it touched
24
+ * ({@link nestedEntries}' `byPatch`). The patch is walked along the
25
+ * declaration — each collection's Dict patch, and each child-rows
26
+ * collection's, down through the child rows it updates — to the row before
27
+ * and after holding only the items it names, and the child rows it inserts or
28
+ * deletes whole. Their entries are compared, with the totals of only the
29
+ * summary tiles they touch and the subtotals of only the tiles they touch at
30
+ * each level. A replace on the way — which a recursive type's patch always is
31
+ * — leaves the row to be compared whole.
32
+ *
33
+ * The functions here are typed East over fixed shapes, or factories of one
34
+ * from a declaration's types. A program holds once each function its parts
35
+ * share, however many collections call it: it binds the tiles' steps, filing
36
+ * and sharing an item out, and the totals' and subtotals' functions in its kit
37
+ * ({@link programKit}), which every part is given, and each group's part binds
38
+ * the group's walk once for its collections ({@link groupEntries}). A node is
39
+ * read and rebuilt, and an item placed in its place's variants, by the names a
40
+ * declaration gives, through East's own builders for names held as values
41
+ * (`East.field`, `East.withField`, `East.inCase`), which check each name
42
+ * against its type as the program is built.
43
+ *
44
+ * @packageDocumentation
45
+ */
46
+ import { ArrayType, BooleanType, DateTimeType, DictType, East, FloatType, FunctionType, IntegerType, NullType, OptionType, SetType, StringType, StructType, VariantType, none, printType, some, variant, } from '@elaraai/east';
47
+ import { NestedEntryKeyType, NestedEntryType, NestedSpanKeyType, RecordLevelType, RecordNestedItemType, RecordNestedPathType, RecordNestedRunType, RecordNestedTotalsType, RecordRollupType, RecordSummaryTotalsType, nestedSpanName, } from '@elaraai/e3-types';
48
+ import { checkNested } from './record-nested.js';
49
+ import { INDEX_PURITY, checkEntryParams, checkPure, functionAt, indexRunner, indexedEntry, onlyOptions, sameEastType, signatureOf, } from './record-guards.js';
50
+ import { fieldReader } from './record-keys.js';
51
+ import { patchTypeOf } from './record-patches.js';
52
+ import { RECORD_TILES, TILE_FNS, TileFilingType, TileShareType, TileStepFnType, checkTile, } from './record-tiles.js';
53
+ import { summaryMerge } from './record-series.js';
54
+ import { lazyBuilds } from './lazy-build.js';
55
+ // ── Fixed shapes ──────────────────────────────────────────────────────────────
56
+ /** A node's keys, from the row down to it, as a row's tree is walked: an Array, which a key may not hold. */
57
+ const KeysType = ArrayType(StringType);
58
+ /** A node of a row's tree: its keys, and its group, which tells nodes of two groups at one path apart. */
59
+ const NodeKeyType = StructType({ path: KeysType, group: IntegerType });
60
+ /**
61
+ * A node of a group, as the walk gives it: its keys, the node above it — none
62
+ * for the row — and the node itself.
63
+ *
64
+ * @param node - The group's node type
65
+ * @returns The struct type
66
+ */
67
+ function NodeAtType(node) {
68
+ return StructType({ path: KeysType, parent: OptionType(NodeKeyType), node });
69
+ }
70
+ /**
71
+ * A node of a group: `(keys, parent, node) → NodeAt`.
72
+ *
73
+ * @param node - The group's node type
74
+ * @returns The constructor
75
+ */
76
+ function nodeAtOf(node) {
77
+ const type = NodeAtType(node);
78
+ return East.function([KeysType, OptionType(NodeKeyType), node], type, (_$, path, parent, at) => ({ path, parent, node: at }));
79
+ }
80
+ /** No totals: a tile's before any item touches it. */
81
+ const NO_TOTALS = { count: 0n, ms: 0n, values: none };
82
+ // ── The tiles totals are worked out at ────────────────────────────────────────
83
+ /** A write's summary tiles, and their span: from the first's start to the last's end. */
84
+ const SpanType = StructType({ tiles: SetType(DateTimeType), from: DateTimeType, to: DateTimeType });
85
+ /**
86
+ * The summary tiles totals are worked out at: `all`, as a row's entries are;
87
+ * `only` a write's — those the items its patch names touch — outside whose
88
+ * span an item touches none of them.
89
+ */
90
+ const WithinType = VariantType({ all: NullType, only: SpanType });
91
+ /** The epoch: either end of no tiles' span. */
92
+ const EPOCH = new Date(0);
93
+ // ── The tiles subtotals are worked out at ─────────────────────────────────────
94
+ /**
95
+ * The tiles a parent's subtotals are worked out at: `all`, as a row's entries
96
+ * are; `only` a write's, by level — the tiles of each level the values its
97
+ * patch names fall in, and their span. A value in none of them moves none of
98
+ * the subtotals the write compares.
99
+ */
100
+ const SubtotalTilesType = VariantType({ all: NullType, only: DictType(RecordLevelType, SpanType) });
101
+ // ── Parents' subtotals: composed bottom-up ────────────────────────────────────
102
+ /** A node of the tree from a row down to a collection of values rolled up: where it is, the node above it, and its own values as Floats. */
103
+ const SubtotalNodeType = StructType({ key: NodeKeyType, parent: OptionType(NodeKeyType), own: DictType(DateTimeType, FloatType) });
104
+ /** What a node draws by one rollup, at one level, in one tile. */
105
+ const DrawKeyType = StructType({ rollup: RecordRollupType, level: RecordLevelType, tile: DateTimeType });
106
+ /** A parent's subtotal: its path, the rollup, the level and the tile. */
107
+ const SubtotalKeyType = StructType({ path: RecordNestedPathType, rollup: RecordRollupType, level: RecordLevelType, tile: DateTimeType });
108
+ /** A node's result, carried to its parent: what it draws, and the subtotals of every parent at or beneath it. */
109
+ const ComposedType = StructType({ draws: DictType(DrawKeyType, FloatType), subtotals: DictType(SubtotalKeyType, FloatType) });
110
+ /** What a node's own values in a tile come to, before a rollup's fold picks one: their sum and how many, the least, the greatest and the latest. */
111
+ const FoldedType = StructType({ sum: FloatType, n: IntegerType, min: FloatType, max: FloatType, last: FloatType });
112
+ /** What a parent's children draw in a tile come to, before a rollup's aggregate picks one. */
113
+ const GatheredType = StructType({ sum: FloatType, n: IntegerType, min: FloatType, max: FloatType });
114
+ /** A level, as an index keeps it. */
115
+ function levelOf(tile) {
116
+ return variant(tile, null);
117
+ }
118
+ /** The groups from the row down to one, the row's first. */
119
+ function chainTo(decl, group) {
120
+ const chain = [];
121
+ for (let at = decl.groups[group]; at !== undefined; at = at.parent === undefined ? undefined : decl.groups[at.parent.group]) {
122
+ chain.unshift(at);
123
+ }
124
+ return chain;
125
+ }
126
+ /**
127
+ * A collection's values as Floats: `(Dict<DateTime, V>) → Dict<DateTime,
128
+ * Float>`, an Integer's converted — the declaration checked they are numbers.
129
+ *
130
+ * @param valueType - The values' type
131
+ * @param numeric - Their kind
132
+ * @returns The conversion, at the values' own type
133
+ */
134
+ function floatsOf(valueType, numeric) {
135
+ return functionAt(numeric === 'Integer' ? NESTED_FNS.integersAsFloats : NESTED_FNS.floatsAsFloats, [DictType(DateTimeType, valueType)], DictType(DateTimeType, FloatType));
136
+ }
137
+ /**
138
+ * A node's field: `(N) → T`, the field named, which the declaration checked
139
+ * is of the type given — read through a recursive node.
140
+ *
141
+ * @param nodeType - The node's type: a Struct, or a RecursiveType of one
142
+ * @param field - The field
143
+ * @param type - Its type
144
+ * @returns The reader
145
+ */
146
+ function fieldOf(nodeType, field, type) {
147
+ const read = type;
148
+ return functionAt(East.function([nodeType], read, (_$, node) => East.field(node, field, read)), [nodeType], type);
149
+ }
150
+ /**
151
+ * A node rebuilt: `(N) → N`, each field named given what its function makes
152
+ * of the node, every other field as it is — a field at a time, each step
153
+ * calling the one before it.
154
+ *
155
+ * @param nodeType - The node's type: a Struct, or a RecursiveType of one
156
+ * @param fields - The fields rebuilt, each by a function of the node
157
+ * @returns The rebuild
158
+ */
159
+ function rebuiltNode(nodeType, fields) {
160
+ return Object.entries(fields).reduce((before, [field, make]) => East.function([nodeType], nodeType, ($, node) => {
161
+ const earlier = $.const(before);
162
+ const value = $.const(make);
163
+ const held = $.let(earlier(node));
164
+ return East.withField(held, field, value(node));
165
+ }), East.function([nodeType], nodeType, (_$, node) => node));
166
+ }
167
+ /**
168
+ * A node with one field replaced: `(N, F) → N`.
169
+ *
170
+ * @param nodeType - The node's type: a Struct, or a RecursiveType of one
171
+ * @param field - The field
172
+ * @param type - Its type, `F`
173
+ * @returns The rebuild
174
+ */
175
+ function withField(nodeType, field, type) {
176
+ return East.function([nodeType, type], nodeType, (_$, node, value) => East.withField(node, field, value));
177
+ }
178
+ /**
179
+ * An item of a collection as its entry carries it: `(I) → P`, the item placed
180
+ * in the variants of the collection's place, nesting as the declaration
181
+ * nests (`.item .members .load 0.82`) — a case at a time, from the item out,
182
+ * each step calling the one before it.
183
+ *
184
+ * @param decl - The declaration
185
+ * @param collection - The collection
186
+ * @param itemType - Its items' type
187
+ * @param entryValue - The entry value, `P`
188
+ * @returns The placing
189
+ */
190
+ function placedItem(decl, collection, itemType, entryValue) {
191
+ // The cases from the item out: its field in its group's places, then each rows field in its parent's.
192
+ const cases = [];
193
+ for (let group = decl.groups[collection.group], name = collection.field;;) {
194
+ cases.push({ name, type: group.places });
195
+ if (group.parent === undefined)
196
+ break;
197
+ name = group.parent.field;
198
+ group = decl.groups[group.parent.group];
199
+ }
200
+ cases.push({ name: 'item', type: entryValue });
201
+ const placed = cases.reduce((inner, at) => East.function([itemType], at.type, ($, item) => {
202
+ const within = $.const(inner);
203
+ return East.inCase(at.type, at.name, within(item));
204
+ }), East.function([itemType], itemType, (_$, item) => item));
205
+ return functionAt(placed, [itemType], entryValue);
206
+ }
207
+ /** The empty collection a lean node holds in place of a listed one: `(N) → Dict<…>`, empty. */
208
+ function emptied(nodeType, type) {
209
+ return East.function([nodeType], type, () => new Map());
210
+ }
211
+ /**
212
+ * A node of a collection's own group, its values as Floats: `(N) → Dict<DateTime, Float>`.
213
+ *
214
+ * @param nodeType - The group's node type
215
+ * @param collection - The collection, whose group it is
216
+ * @param numeric - Its values' kind
217
+ * @returns The node's values
218
+ */
219
+ function valuesAsFloats(nodeType, collection, numeric) {
220
+ const holding = fieldOf(nodeType, collection.field, DictType(DateTimeType, collection.valueType));
221
+ const asFloats = floatsOf(collection.valueType, numeric);
222
+ return East.function([nodeType], DictType(DateTimeType, FloatType), ($, node) => {
223
+ const held = $.const(holding);
224
+ const floats = $.const(asFloats);
225
+ return floats(held(node));
226
+ });
227
+ }
228
+ /** A node above a collection's group, which holds none of its values: `(N) → Dict<DateTime, Float>`, empty. */
229
+ function noValues(nodeType) {
230
+ return East.function([nodeType], DictType(DateTimeType, FloatType), () => new Map());
231
+ }
232
+ // ── A row's nodes ─────────────────────────────────────────────────────────────
233
+ /**
234
+ * Each group's nodes from the row: `(V) → Array<NodeAt>`, the row's own the
235
+ * row, and each other group's its parent group's nodes' child rows under its
236
+ * field — beside `recursive()`, with every row beneath them through it, by
237
+ * `flattenTree` — each with its keys and the node above it.
238
+ */
239
+ function groupNodes(decl, rowType) {
240
+ const nodes = [];
241
+ for (const group of decl.groups) {
242
+ const nodeAt = ArrayType(NodeAtType(group.type));
243
+ const make = nodeAtOf(group.type);
244
+ if (group.parent === undefined) {
245
+ nodes.push(East.function([rowType], nodeAt, ($, row) => {
246
+ const at = $.const(make);
247
+ return [at([], none, row)];
248
+ }));
249
+ continue;
250
+ }
251
+ const parent = decl.groups[group.parent.group];
252
+ const above = nodes[parent.index];
253
+ const rowsOf = fieldOf(parent.type, group.parent.field, DictType(StringType, group.type));
254
+ const parentGroup = BigInt(parent.index);
255
+ const ownGroup = BigInt(group.index);
256
+ if (group.through === undefined) {
257
+ nodes.push(East.function([rowType], nodeAt, ($, row) => {
258
+ const up = $.const(above);
259
+ const rows = $.const(rowsOf);
260
+ const nodeAt = $.const(make);
261
+ return up(row).flatMap((_$, at) => rows(at.node).toArray((_$, node, key) => nodeAt(at.path.concat([key]), some({ path: at.path, group: parentGroup }), node)));
262
+ }));
263
+ continue;
264
+ }
265
+ const deeper = fieldOf(group.type, group.through, DictType(StringType, group.type));
266
+ nodes.push(East.function([rowType], nodeAt, ($, row) => {
267
+ const up = $.const(above);
268
+ const rows = $.const(rowsOf);
269
+ const beneath = $.const(deeper);
270
+ const keysOver = $.const(NESTED_FNS.keysAbove);
271
+ const nodeAt = $.const(make);
272
+ return up(row).flatMap((_$, at) => rows(at.node).flattenTree((_$, node) => beneath(node)).map((_$, entry) => nodeAt(at.path.concat(entry.path),
273
+ // A node's parent: the row above it in this walk, or the parent group's node holding the walk's root.
274
+ some(keysOver(entry.path).match({
275
+ some: (_$, keys) => ({ path: at.path.concat(keys), group: ownGroup }),
276
+ none: () => ({ path: at.path, group: parentGroup }),
277
+ })), entry.node)));
278
+ }));
279
+ }
280
+ return nodes;
281
+ }
282
+ /** A group's nodes from a row, as a function a part is given: `(V) → Array<NodeAt>`. */
283
+ function WalkType(rowType, group) {
284
+ return FunctionType([rowType], ArrayType(NodeAtType(group.type)));
285
+ }
286
+ // ── A program's kit ───────────────────────────────────────────────────────────
287
+ /** `(keys) → Path`: `pathOf`'s type. */
288
+ const PathFnType = FunctionType([KeysType], RecordNestedPathType);
289
+ /** `(tile, start, end, what, startOf, nextOf) → Array<TileFiling>`: `placedFilingsOver`'s type. */
290
+ const FileFnType = FunctionType([RecordLevelType, OptionType(DateTimeType), OptionType(DateTimeType), StringType, TileStepFnType, TileStepFnType], ArrayType(TileFilingType));
291
+ /** `(tile, start, end, what, startOf, nextOf) → Array<TileShare>`: `placedSharesOver`'s type. */
292
+ const ShareFnType = FunctionType([RecordLevelType, OptionType(DateTimeType), OptionType(DateTimeType), StringType, TileStepFnType, TileStepFnType], ArrayType(TileShareType));
293
+ /** `(shares) → Dict<tile, Totals>`: `sharedTotals`' type. */
294
+ const TotalledFnType = FunctionType([ArrayType(TileShareType)], DictType(DateTimeType, RecordNestedTotalsType));
295
+ /** `(instants, level, startOf) → Dict<tile, Totals>`: `instantTotals`' type. */
296
+ const CountedFnType = FunctionType([SetType(DateTimeType), RecordLevelType, TileStepFnType], DictType(DateTimeType, RecordNestedTotalsType));
297
+ /** `(values, level, startOf) → Dict<tile, Totals>`: `valueTotals`' type. */
298
+ const SummedFnType = FunctionType([DictType(DateTimeType, FloatType), RecordLevelType, TileStepFnType], DictType(DateTimeType, RecordNestedTotalsType));
299
+ /** `(span, level, at, startOf) → Boolean`: `inSpan`'s type. */
300
+ const KeptFnType = FunctionType([SpanType, RecordLevelType, DateTimeType, TileStepFnType], BooleanType);
301
+ /** `(tiles, level, nextOf) → Within`: `tilesWithin`'s type. */
302
+ const WithinFnType = FunctionType([SetType(DateTimeType), RecordLevelType, TileStepFnType], WithinType);
303
+ /** `(instants, levels, startOf, nextOf) → SubtotalTiles`: `subtotalTiles`' type. */
304
+ const LevelsWithinFnType = FunctionType([SetType(DateTimeType), ArrayType(RecordLevelType), TileStepFnType, TileStepFnType], SubtotalTilesType);
305
+ /** `(nodes, rollups, levels, tiles, startOf) → Dict<SubtotalKey, Float>`: `subtotalsOf`' type. */
306
+ const SubtotalsFnType = FunctionType([ArrayType(SubtotalNodeType), ArrayType(RecordRollupType), ArrayType(RecordLevelType), SubtotalTilesType, TileStepFnType], DictType(SubtotalKeyType, FloatType));
307
+ /**
308
+ * A program's kit: the functions its parts call, bound once in the program's
309
+ * body and handed to every part ({@link programKit}), so a program holds each
310
+ * once, however many of its parts call it. A function stepping through the
311
+ * tiles is given the kit's `startOf` and `nextOf` by its caller.
312
+ */
313
+ const KitType = StructType({
314
+ /** `tileStart` */
315
+ startOf: TileStepFnType,
316
+ /** `tileNext` */
317
+ nextOf: TileStepFnType,
318
+ /** `pathOf` */
319
+ path: PathFnType,
320
+ /** Where an item is filed: `placedFilingsOver` */
321
+ file: FileFnType,
322
+ /** An item's shares of the tiles it touches: `placedSharesOver` */
323
+ share: ShareFnType,
324
+ /** `sharedTotals` */
325
+ totalled: TotalledFnType,
326
+ /** `instantTotals` */
327
+ counted: CountedFnType,
328
+ /** `valueTotals` */
329
+ summed: SummedFnType,
330
+ /** `inSpan` */
331
+ kept: KeptFnType,
332
+ /** `tilesWithin` */
333
+ within: WithinFnType,
334
+ /** `subtotalTiles` */
335
+ levelsWithin: LevelsWithinFnType,
336
+ /** `subtotalsOf` */
337
+ subtotals: SubtotalsFnType,
338
+ });
339
+ /** Each function of a kit only some parts call, as they call it: each read the first time a kit holds it (#1466). */
340
+ export const KIT_CALLED = lazyBuilds({
341
+ get file() { return TILE_FNS.placedFilingsOver; },
342
+ get share() { return TILE_FNS.placedSharesOver; },
343
+ get totalled() { return NESTED_FNS.sharedTotals; },
344
+ get counted() { return NESTED_FNS.instantTotals; },
345
+ get summed() { return NESTED_FNS.valueTotals; },
346
+ get kept() { return NESTED_FNS.inSpan; },
347
+ get within() { return NESTED_FNS.tilesWithin; },
348
+ get levelsWithin() { return NESTED_FNS.subtotalTiles; },
349
+ get subtotals() { return NESTED_FNS.subtotalsOf; },
350
+ });
351
+ /**
352
+ * Each function of a kit only some parts call, as a kit holds it where none of
353
+ * its program's parts calls it: one of its type making nothing, so a program
354
+ * holds only the functions its parts call. Each built the first time a kit
355
+ * holds it ({@link lazyBuilds}, #1466).
356
+ */
357
+ export const KIT_UNCALLED = lazyBuilds({
358
+ get file() { return East.function(FileFnType.inputs, FileFnType.output, () => []); },
359
+ get share() { return East.function(ShareFnType.inputs, ShareFnType.output, () => []); },
360
+ get totalled() { return East.function(TotalledFnType.inputs, TotalledFnType.output, () => new Map()); },
361
+ get counted() { return East.function(CountedFnType.inputs, CountedFnType.output, () => new Map()); },
362
+ get summed() { return East.function(SummedFnType.inputs, SummedFnType.output, () => new Map()); },
363
+ get kept() { return East.function(KeptFnType.inputs, KeptFnType.output, () => false); },
364
+ get within() { return East.function(WithinFnType.inputs, WithinFnType.output, () => variant('all', null)); },
365
+ get levelsWithin() { return East.function(LevelsWithinFnType.inputs, LevelsWithinFnType.output, () => variant('all', null)); },
366
+ get subtotals() { return East.function(SubtotalsFnType.inputs, SubtotalsFnType.output, () => new Map()); },
367
+ });
368
+ /**
369
+ * A program's kit ({@link KitType}): `() → Kit`, each function its parts call
370
+ * bound once — the tiles' steps and a path's always, each other the parts
371
+ * name, and in place of each they do not, one making nothing.
372
+ *
373
+ * @param calls - What the program's parts call of the kit, beside the tiles' steps and a path's
374
+ * @returns The kit
375
+ */
376
+ function programKit(calls) {
377
+ const kit = {
378
+ startOf: TILE_FNS.tileStart,
379
+ nextOf: TILE_FNS.tileNext,
380
+ path: NESTED_FNS.pathOf,
381
+ file: calls.has('file') ? KIT_CALLED.file : KIT_UNCALLED.file,
382
+ share: calls.has('share') ? KIT_CALLED.share : KIT_UNCALLED.share,
383
+ totalled: calls.has('totalled') ? KIT_CALLED.totalled : KIT_UNCALLED.totalled,
384
+ counted: calls.has('counted') ? KIT_CALLED.counted : KIT_UNCALLED.counted,
385
+ summed: calls.has('summed') ? KIT_CALLED.summed : KIT_UNCALLED.summed,
386
+ kept: calls.has('kept') ? KIT_CALLED.kept : KIT_UNCALLED.kept,
387
+ within: calls.has('within') ? KIT_CALLED.within : KIT_UNCALLED.within,
388
+ levelsWithin: calls.has('levelsWithin') ? KIT_CALLED.levelsWithin : KIT_UNCALLED.levelsWithin,
389
+ subtotals: calls.has('subtotals') ? KIT_CALLED.subtotals : KIT_UNCALLED.subtotals,
390
+ };
391
+ return East.function([], KitType, () => kit);
392
+ }
393
+ // ── What a write's patch touches ──────────────────────────────────────────────
394
+ /**
395
+ * What a write's patch touched of a node: `replaced` — a replace on the way,
396
+ * so the row is compared whole — `unchanged`, or the node before and after,
397
+ * holding of its collections and child rows only what the patch names.
398
+ *
399
+ * @param node - The node's type
400
+ * @returns The variant type
401
+ */
402
+ function TouchedType(node) {
403
+ return VariantType({ replaced: NullType, unchanged: NullType, touched: StructType({ held: node, next: node }) });
404
+ }
405
+ /**
406
+ * A Dict's patch, as East types it: `unchanged`, a `replace`, or an op a key —
407
+ * an `insert` or a `delete` of a value, or an `update` by the value's patch.
408
+ *
409
+ * @param keyType - The Dict's key type
410
+ * @param valueType - Its value type
411
+ * @returns The patch type
412
+ * @throws {Error} When it is not East's own
413
+ */
414
+ function dictPatchType(keyType, valueType) {
415
+ const dictType = DictType(keyType, valueType);
416
+ const patchType = VariantType({
417
+ unchanged: NullType,
418
+ replace: StructType({ before: dictType, after: dictType }),
419
+ patch: DictType(keyType, VariantType({ insert: valueType, delete: valueType, update: patchTypeOf(valueType) })),
420
+ });
421
+ if (!sameEastType(patchType, patchTypeOf(dictType))) {
422
+ throw new Error(`a nested series index's patch of ${printType(dictType)} is not East's ${printType(patchTypeOf(dictType))}`);
423
+ }
424
+ return patchType;
425
+ }
426
+ /**
427
+ * A collection's walk ({@link DictWalk}): the items its patch names, before
428
+ * and after — one inserted after, one deleted before, one updated both.
429
+ *
430
+ * @param keyType - The collection's key type
431
+ * @param itemType - Its items' type
432
+ * @returns The walk
433
+ */
434
+ function touchedItems(keyType, itemType) {
435
+ const dictType = DictType(keyType, itemType);
436
+ const patchType = dictPatchType(keyType, itemType);
437
+ const pairType = StructType({ held: dictType, next: dictType });
438
+ return East.function([dictType, dictType, patchType], OptionType(pairType), ($, held, next, patch) => {
439
+ $.match(patch, {
440
+ unchanged: ($) => {
441
+ $.return(some({ held: new Map(), next: new Map() }));
442
+ },
443
+ replace: ($) => {
444
+ $.return(none);
445
+ },
446
+ patch: ($, ops) => {
447
+ $.return(some({
448
+ held: ops.filterMap((_$, _op, key) => held.tryGet(key)),
449
+ next: ops.filterMap((_$, _op, key) => next.tryGet(key)),
450
+ }));
451
+ },
452
+ });
453
+ return none;
454
+ });
455
+ }
456
+ /**
457
+ * Child rows' walk ({@link DictWalk}): the rows their patch names, before and
458
+ * after — one inserted or deleted whole, with everything beneath it, one
459
+ * updated as its own walk leaves it — and none where one on the way was
460
+ * replaced.
461
+ *
462
+ * @param nodeType - The child rows' type
463
+ * @param walk - Their walk
464
+ * @returns The walk
465
+ */
466
+ function touchedRows(nodeType, walk) {
467
+ const rowsType = DictType(StringType, nodeType);
468
+ const patchType = dictPatchType(StringType, nodeType);
469
+ const pairType = StructType({ held: rowsType, next: rowsType });
470
+ return East.function([rowsType, rowsType, patchType], OptionType(pairType), ($, held, next, patch) => {
471
+ const child = $.const(walk);
472
+ $.match(patch, {
473
+ unchanged: ($) => {
474
+ $.return(some({ held: new Map(), next: new Map() }));
475
+ },
476
+ replace: ($) => {
477
+ $.return(none);
478
+ },
479
+ patch: ($, ops) => {
480
+ const before = $.let(new Map(), rowsType);
481
+ const after = $.let(new Map(), rowsType);
482
+ $.for(ops, ($, op, key) => {
483
+ $.match(op, {
484
+ insert: ($) => {
485
+ $(after.insert(key, next.get(key)));
486
+ },
487
+ delete: ($) => {
488
+ $(before.insert(key, held.get(key)));
489
+ },
490
+ update: ($, rowPatch) => {
491
+ $.match(child(held.get(key), next.get(key), rowPatch), {
492
+ replaced: ($) => {
493
+ $.return(none);
494
+ },
495
+ unchanged: () => { },
496
+ touched: ($, both) => {
497
+ $(before.insert(key, both.held));
498
+ $(after.insert(key, both.next));
499
+ },
500
+ });
501
+ },
502
+ });
503
+ });
504
+ $.return(some({ held: before, next: after }));
505
+ },
506
+ });
507
+ return none;
508
+ });
509
+ }
510
+ /**
511
+ * A recursive node's walk ({@link NodeWalk}): East patches a recursive type
512
+ * only whole, so a change of one is a replace.
513
+ *
514
+ * @param nodeType - The node's type
515
+ * @returns The walk
516
+ * @throws {Error} When its patch is not East's own
517
+ */
518
+ function touchedRecursive(nodeType) {
519
+ const patchType = VariantType({ unchanged: NullType, replace: StructType({ before: nodeType, after: nodeType }) });
520
+ if (!sameEastType(patchType, patchTypeOf(nodeType))) {
521
+ throw new Error(`a nested series index's patch of ${printType(nodeType)} is not East's ${printType(patchTypeOf(nodeType))}`);
522
+ }
523
+ const touchedType = TouchedType(nodeType);
524
+ return East.function([nodeType, nodeType, patchType], touchedType, ($, _held, _next, patch) => {
525
+ $.match(patch, {
526
+ unchanged: ($) => {
527
+ $.return(variant('unchanged', null));
528
+ },
529
+ replace: ($) => {
530
+ $.return(variant('replaced', null));
531
+ },
532
+ });
533
+ return variant('replaced', null);
534
+ });
535
+ }
536
+ /**
537
+ * A struct node's walk ({@link NodeWalk}): each field holding a collection or
538
+ * child rows walked by its patch in turn, and the node rebuilt holding what
539
+ * each walk leaves; every other field as it is.
540
+ *
541
+ * @param nodeType - The node's type, a Struct
542
+ * @param fields - Its fields' walks
543
+ * @returns The walk
544
+ * @throws {Error} When its patch is not East's own
545
+ */
546
+ function touchedStruct(nodeType, fields) {
547
+ if (nodeType.type !== 'Struct')
548
+ throw new Error(`a nested series index's node is a Struct, not ${nodeType.type}`);
549
+ const patchesType = StructType(Object.fromEntries(Object.entries(nodeType.fields).map(([name, type]) => [name, patchTypeOf(type)])));
550
+ const patchType = VariantType({ unchanged: NullType, replace: StructType({ before: nodeType, after: nodeType }), patch: patchesType });
551
+ if (!sameEastType(patchType, patchTypeOf(nodeType))) {
552
+ throw new Error(`a nested series index's patch of ${printType(nodeType)} is not East's ${printType(patchTypeOf(nodeType))}`);
553
+ }
554
+ const pairType = StructType({ held: nodeType, next: nodeType });
555
+ // Each field in turn, the node before and after holding what the walks before it left; none once one was replaced.
556
+ const walked = fields.reduce((before, at) => {
557
+ const read = fieldOf(nodeType, at.field, at.type);
558
+ const patchOf = fieldOf(patchesType, at.field, patchTypeOf(at.type));
559
+ const put = withField(nodeType, at.field, at.type);
560
+ return East.function([pairType, patchesType], OptionType(pairType), ($, pair, patches) => {
561
+ const earlier = $.const(before);
562
+ const readFn = $.const(read);
563
+ const patchFn = $.const(patchOf);
564
+ const walkFn = $.const(at.walk);
565
+ const putFn = $.const(put);
566
+ $.match(earlier(pair, patches), {
567
+ some: ($, so) => {
568
+ $.match(walkFn(readFn(so.held), readFn(so.next), patchFn(patches)), {
569
+ some: ($, both) => {
570
+ $.return(some({ held: putFn(so.held, both.held), next: putFn(so.next, both.next) }));
571
+ },
572
+ none: () => { },
573
+ });
574
+ },
575
+ none: () => { },
576
+ });
577
+ return none;
578
+ });
579
+ }, East.function([pairType, patchesType], OptionType(pairType), (_$, pair) => some(pair)));
580
+ const touchedType = TouchedType(nodeType);
581
+ return East.function([nodeType, nodeType, patchType], touchedType, ($, held, next, patch) => {
582
+ const walk = $.const(walked);
583
+ $.match(patch, {
584
+ unchanged: ($) => {
585
+ $.return(variant('unchanged', null));
586
+ },
587
+ replace: ($) => {
588
+ $.return(variant('replaced', null));
589
+ },
590
+ patch: ($, patches) => {
591
+ $.match(walk({ held, next }, patches), {
592
+ some: ($, both) => {
593
+ $.return(variant('touched', both));
594
+ },
595
+ none: () => { },
596
+ });
597
+ },
598
+ });
599
+ return variant('replaced', null);
600
+ });
601
+ }
602
+ /**
603
+ * The row's walk ({@link NodeWalk}): each group's from its child groups' — a
604
+ * recursive group's, whole.
605
+ *
606
+ * @param decl - The checked declaration
607
+ * @returns The row's walk
608
+ */
609
+ function rowWalk(decl) {
610
+ const walks = [];
611
+ for (const group of [...decl.groups].reverse()) {
612
+ if (group.type.type !== 'Struct') {
613
+ walks[group.index] = touchedRecursive(group.type);
614
+ continue;
615
+ }
616
+ walks[group.index] = touchedStruct(group.type, [
617
+ ...group.collections.map((collection) => {
618
+ const type = collection.kind === 'items' ? DictType(StringType, collection.itemType) : DictType(DateTimeType, collection.valueType);
619
+ return { field: collection.field, type, walk: touchedItems(type.key, type.value) };
620
+ }),
621
+ ...group.rows.map((child) => {
622
+ const childType = decl.groups[child.group].type;
623
+ return { field: child.field, type: DictType(StringType, childType), walk: touchedRows(childType, walks[child.group]) };
624
+ }),
625
+ ]);
626
+ }
627
+ return walks[0];
628
+ }
629
+ // ── A collection's parts ──────────────────────────────────────────────────────
630
+ /** A collection's words in a refusal: the row's key, its place, and the item's key, printed. */
631
+ function whatWords(collection) {
632
+ return collection.place.join(' ');
633
+ }
634
+ /** A node's items' shares of the summary tiles they touch. */
635
+ const NodeSharesType = StructType({ path: KeysType, shares: ArrayType(TileShareType) });
636
+ /** No items or values: a tile's totals before any is counted. */
637
+ const NO_SPAN_TOTALS = { count: 0n, ms: 0n };
638
+ /** The tile a nested series index's span counts by: a Plan's horizon spans whole months. */
639
+ const SPAN_TILE = 'month';
640
+ /** A row's months, by collection: `Dict<{ collection, tile }, Totals>`. */
641
+ const SpanTotalsType = DictType(NestedSpanKeyType, RecordSummaryTotalsType);
642
+ /** `(K, V, Nodes, Kit) → Dict<IK, P>`: parts' entries, one after another, each a function calling the parts before it. */
643
+ function nodesUnion(types, nodesType, parts) {
644
+ const [first, ...rest] = parts;
645
+ if (first === undefined)
646
+ return East.function([types.keyType, types.rowType, nodesType, KitType], types.entries, () => new Map());
647
+ return rest.reduce((before, part) => East.function([types.keyType, types.rowType, nodesType, KitType], types.entries, ($, key, row, nodes, kit) => {
648
+ const all = $.let(before(key, row, nodes, kit));
649
+ $(all.unionInPlace(part(key, row, nodes, kit)));
650
+ return all;
651
+ }), first);
652
+ }
653
+ /** `(K, shares, Kit) → Dict<IK, P>`: two parts' entries from the same shares, one's then the other's. */
654
+ function sharedBoth(types, first, second) {
655
+ return East.function([types.keyType, ArrayType(NodeSharesType), KitType], types.entries, ($, key, shared, kit) => {
656
+ const all = $.let(first(key, shared, kit));
657
+ $(all.unionInPlace(second(key, shared, kit)));
658
+ return all;
659
+ });
660
+ }
661
+ /** `(K, V, V, V, V, Nodes, Kit) → { before, after }`: what parts change, one after another, each a function calling the parts before it. */
662
+ function changedUnion(types, nodesType, parts) {
663
+ const { keyType, rowType, changed } = types;
664
+ const [first, ...rest] = parts;
665
+ if (first === undefined) {
666
+ return East.function([keyType, rowType, rowType, rowType, rowType, nodesType, KitType], changed, () => ({ before: new Map(), after: new Map() }));
667
+ }
668
+ return rest.reduce((before, part) => East.function([keyType, rowType, rowType, rowType, rowType, nodesType, KitType], changed, ($, key, held, next, heldTouched, nextTouched, nodes, kit) => {
669
+ const all = $.let(before(key, held, next, heldTouched, nextTouched, nodes, kit));
670
+ const more = $.let(part(key, held, next, heldTouched, nextTouched, nodes, kit));
671
+ $(all.before.unionInPlace(more.before));
672
+ $(all.after.unionInPlace(more.after));
673
+ return all;
674
+ }), first);
675
+ }
676
+ /** `(K, V, Nodes, Kit) → Dict<{ collection, tile }, Totals>`: parts' months, one after another, each a function calling the parts before it. */
677
+ function spanNodesUnion(types, nodesType, parts) {
678
+ const [first, ...rest] = parts;
679
+ if (first === undefined)
680
+ return East.function([types.keyType, types.rowType, nodesType, KitType], SpanTotalsType, () => new Map());
681
+ return rest.reduce((before, part) => East.function([types.keyType, types.rowType, nodesType, KitType], SpanTotalsType, ($, key, row, nodes, kit) => {
682
+ const all = $.let(before(key, row, nodes, kit));
683
+ $(all.unionInPlace(part(key, row, nodes, kit)));
684
+ return all;
685
+ }), first);
686
+ }
687
+ /**
688
+ * A group's collections' entries of a row ({@link EntriesPart}): the group's
689
+ * walk bound once, and given to each collection's.
690
+ *
691
+ * @param types - The index's types
692
+ * @param nodes - The group's walk
693
+ * @param entries - Its collections' entries, given the walk
694
+ * @returns The part
695
+ */
696
+ function groupEntries(types, nodes, entries) {
697
+ return East.function([types.keyType, types.rowType, KitType], types.entries, ($, key, row, kit) => {
698
+ const walk = $.const(nodes);
699
+ return entries(key, row, walk, kit);
700
+ });
701
+ }
702
+ /**
703
+ * A group's collections' part of a write's entries, by its patch ({@link
704
+ * PatchedPart}): the group's walk bound once, and given to each collection's.
705
+ *
706
+ * @param types - The index's types
707
+ * @param nodes - The group's walk
708
+ * @param changed - Its collections' parts, given the walk
709
+ * @returns The part
710
+ */
711
+ function groupPatched(types, nodes, changed) {
712
+ const { keyType, rowType } = types;
713
+ return East.function([keyType, rowType, rowType, rowType, rowType, KitType], types.changed, ($, key, held, next, heldTouched, nextTouched, kit) => {
714
+ const walk = $.const(nodes);
715
+ return changed(key, held, next, heldTouched, nextTouched, walk, kit);
716
+ });
717
+ }
718
+ /**
719
+ * A group's collections' months of a row, for the index's span ({@link
720
+ * SpanPart}): the group's walk bound once, and given to each collection's.
721
+ *
722
+ * @param types - The index's types
723
+ * @param nodes - The group's walk
724
+ * @param span - Its collections' months, given the walk
725
+ * @returns The part
726
+ */
727
+ function groupSpan(types, nodes, span) {
728
+ return East.function([types.keyType, types.rowType, KitType], SpanTotalsType, ($, key, row, kit) => {
729
+ const walk = $.const(nodes);
730
+ return span(key, row, walk, kit);
731
+ });
732
+ }
733
+ /**
734
+ * What a write changes of a collection's entries, by its patch, given its
735
+ * group's nodes ({@link NodesChanged}): the entries of the items or values it
736
+ * touched, before and after, and, where it touched any, what it moves of the
737
+ * collection's totals and subtotals.
738
+ *
739
+ * @param types - The index's types
740
+ * @param nodesType - The group's walk's type
741
+ * @param filed - The collection's items or values filed, given the walk
742
+ * @param moved - What a write moves of its totals and subtotals; none where it keeps neither
743
+ * @returns The collection's part
744
+ */
745
+ function patchedWith(types, nodesType, filed, moved) {
746
+ const { keyType, rowType, changed } = types;
747
+ if (moved === undefined) {
748
+ return East.function([keyType, rowType, rowType, rowType, rowType, nodesType, KitType], changed, ($, key, _held, _next, heldTouched, nextTouched, nodes, kit) => {
749
+ const filing = $.const(filed);
750
+ return { before: filing(key, heldTouched, nodes, kit), after: filing(key, nextTouched, nodes, kit) };
751
+ });
752
+ }
753
+ return East.function([keyType, rowType, rowType, rowType, rowType, nodesType, KitType], changed, ($, key, held, next, heldTouched, nextTouched, nodes, kit) => {
754
+ const filing = $.const(filed);
755
+ const before = $.let(filing(key, heldTouched, nodes, kit));
756
+ const after = $.let(filing(key, nextTouched, nodes, kit));
757
+ // Nothing of the collection touched: none of its totals or subtotals moves.
758
+ $.if(East.greater(before.size(), 0n).or(() => East.greater(after.size(), 0n)), ($) => {
759
+ const more = $.let(moved(key, held, next, heldTouched, nextTouched, nodes, kit));
760
+ $(before.unionInPlace(more.before));
761
+ $(after.unionInPlace(more.after));
762
+ });
763
+ return { before, after };
764
+ });
765
+ }
766
+ /** Things people drag, filed: `(K, V, Nodes, Kit) → Dict<IK, P>`, each item once (or once a year past a year), at the level its length fits, under its node. */
767
+ function itemEntries(decl, types, collection, nodesType) {
768
+ const group = decl.groups[collection.group];
769
+ const { keyType, rowType, entryKey, entries, tile } = types;
770
+ const holding = fieldOf(group.type, collection.field, DictType(StringType, collection.itemType));
771
+ const readStart = fieldReader(StringType, collection.itemType, { option: collection.start });
772
+ const readEnd = fieldReader(StringType, collection.itemType, { option: collection.end });
773
+ const place = placedItem(decl, collection, collection.itemType, types.entryValue);
774
+ const words = whatWords(collection);
775
+ return East.function([keyType, rowType, nodesType, KitType], entries, ($, key, row, nodes, kit) => {
776
+ const startOf = $.const(kit.startOf);
777
+ const nextOf = $.const(kit.nextOf);
778
+ const file = $.const(kit.file);
779
+ const path = $.const(kit.path);
780
+ const held = $.const(holding);
781
+ const begins = $.const(readStart);
782
+ const ends = $.const(readEnd);
783
+ const into = $.const(place);
784
+ const collectionPath = $.let(path(East.value([...collection.place], KeysType)));
785
+ return nodes(row).flattenToDict(($, node) => {
786
+ const here = $.let(path(node.path));
787
+ return held(node.node).flattenToDict(($, item, id) => {
788
+ const value = $.let(into(item));
789
+ return file(tile, begins(id, item), ends(id, item), East.str `${East.print(key)} ${words} ${East.print(id)}`, startOf, nextOf).toDict((_$, filing) => East.value({
790
+ collection: collectionPath, row: key, path: here, run: variant('items', null), level: filing.level, tile: filing.tile,
791
+ item: variant('id', id),
792
+ }, entryKey), () => value);
793
+ });
794
+ });
795
+ });
796
+ }
797
+ /**
798
+ * Things people drag rolled up, filed under every ancestor too: `(K, V,
799
+ * Nodes, Kit) → Dict<IK, P>`, in the run `subtree` of the row and of each node
800
+ * on the way, at the level and tile of the item's own filing, the keys from
801
+ * the ancestor down naming the item.
802
+ */
803
+ function itemSubtreeEntries(decl, types, collection, nodesType) {
804
+ const group = decl.groups[collection.group];
805
+ const { keyType, rowType, entryKey, entries, tile } = types;
806
+ const holding = fieldOf(group.type, collection.field, DictType(StringType, collection.itemType));
807
+ const readStart = fieldReader(StringType, collection.itemType, { option: collection.start });
808
+ const readEnd = fieldReader(StringType, collection.itemType, { option: collection.end });
809
+ const place = placedItem(decl, collection, collection.itemType, types.entryValue);
810
+ const words = whatWords(collection);
811
+ return East.function([keyType, rowType, nodesType, KitType], entries, ($, key, row, nodes, kit) => {
812
+ const startOf = $.const(kit.startOf);
813
+ const nextOf = $.const(kit.nextOf);
814
+ const file = $.const(kit.file);
815
+ const path = $.const(kit.path);
816
+ const held = $.const(holding);
817
+ const begins = $.const(readStart);
818
+ const ends = $.const(readEnd);
819
+ const into = $.const(place);
820
+ const collectionPath = $.let(path(East.value([...collection.place], KeysType)));
821
+ return nodes(row).flattenToDict(($, node) => held(node.node).flattenToDict(($, item, id) => {
822
+ const value = $.let(into(item));
823
+ const filings = $.let(file(tile, begins(id, item), ends(id, item), East.str `${East.print(key)} ${words} ${East.print(id)}`, startOf, nextOf));
824
+ return East.Array.range(0n, node.path.size()).flattenToDict(($, depth) => {
825
+ const ancestor = $.let(path(node.path.slice(0n, depth)));
826
+ const under = $.let(variant('under', { path: path(node.path.slice(depth, node.path.size())), id }));
827
+ return filings.toDict((_$, filing) => East.value({
828
+ collection: collectionPath, row: key, path: ancestor, run: variant('subtree', null), level: filing.level, tile: filing.tile,
829
+ item: under,
830
+ }, entryKey), () => value);
831
+ });
832
+ }));
833
+ });
834
+ }
835
+ /** Things people drag, filed ({@link itemEntries}), and, rolled up, under every ancestor too ({@link itemSubtreeEntries}). */
836
+ function itemsFiled(decl, types, collection, nodesType) {
837
+ const own = itemEntries(decl, types, collection, nodesType);
838
+ return collection.rollup ? nodesUnion(types, nodesType, [own, itemSubtreeEntries(decl, types, collection, nodesType)]) : own;
839
+ }
840
+ /**
841
+ * Each node's items' shares of the tiles of a level they touch ({@link
842
+ * NodesShares}), of the tiles asked for — an item that cannot touch them not
843
+ * shared out at all — an item with no start touching none.
844
+ */
845
+ function itemShares(decl, types, collection, nodesType, level) {
846
+ const group = decl.groups[collection.group];
847
+ const holding = fieldOf(group.type, collection.field, DictType(StringType, collection.itemType));
848
+ const readStart = fieldReader(StringType, collection.itemType, { option: collection.start });
849
+ const readEnd = fieldReader(StringType, collection.itemType, { option: collection.end });
850
+ const words = whatWords(collection);
851
+ return East.function([types.keyType, types.rowType, WithinType, nodesType, KitType], ArrayType(NodeSharesType), ($, key, row, within, nodes, kit) => {
852
+ const startOf = $.const(kit.startOf);
853
+ const nextOf = $.const(kit.nextOf);
854
+ const share = $.const(kit.share);
855
+ const held = $.const(holding);
856
+ const begins = $.const(readStart);
857
+ const ends = $.const(readEnd);
858
+ const may = $.const(NESTED_FNS.reaches);
859
+ const kept = $.const(NESTED_FNS.sharesWithin);
860
+ return nodes(row).map((_$, node) => ({
861
+ path: node.path,
862
+ shares: held(node.node).flattenToArray(($, item, id) => {
863
+ const start = $.let(begins(id, item));
864
+ const end = $.let(ends(id, item));
865
+ const shares = $.let([], ArrayType(TileShareType));
866
+ $.if(may(within, start, end), ($) => {
867
+ $.assign(shares, kept(share(level, start, end, East.str `${East.print(key)} ${words} ${East.print(id)}`, startOf, nextOf), within));
868
+ });
869
+ return shares;
870
+ }),
871
+ }));
872
+ });
873
+ }
874
+ /** Things people drag, totalled from their shares ({@link SharedEntries}): each node's items' count and milliseconds in each summary tile they touch. */
875
+ function itemTotals(types, collection, summary) {
876
+ const { keyType, entryKey, entryValue, entries } = types;
877
+ return East.function([keyType, ArrayType(NodeSharesType), KitType], entries, ($, key, shared, kit) => {
878
+ const totalled = $.const(kit.totalled);
879
+ const path = $.const(kit.path);
880
+ const collectionPath = $.let(path(East.value([...collection.place], KeysType)));
881
+ return shared.flattenToDict(($, node) => {
882
+ const here = $.let(path(node.path));
883
+ return totalled(node.shares).toDict((_$, _totals, tile) => East.value({
884
+ collection: collectionPath, row: key, path: here, run: variant('totals', null), level: summary, tile, item: variant('none', null),
885
+ }, entryKey), (_$, totals) => East.value(variant('totals', totals), entryValue));
886
+ });
887
+ });
888
+ }
889
+ /**
890
+ * Things people drag rolled up, each ancestor's totals of its subtree's items,
891
+ * from their shares ({@link SharedEntries}): in the run `subtreeTotals`.
892
+ */
893
+ function itemSubtreeTotals(types, collection, summary) {
894
+ const { keyType, entryKey, entryValue, entries } = types;
895
+ return East.function([keyType, ArrayType(NodeSharesType), KitType], entries, ($, key, shared, kit) => {
896
+ const totalled = $.const(kit.totalled);
897
+ const path = $.const(kit.path);
898
+ const collectionPath = $.let(path(East.value([...collection.place], KeysType)));
899
+ // Every node's shares, under each of its ancestors: the row, and each node on the way.
900
+ const beneath = $.let(shared.flatMap((_$, node) => East.Array.range(0n, node.path.size()).flatMap((_$, depth) => node.shares.map((_$, share) => ({ ancestor: path(node.path.slice(0n, depth)), share })))));
901
+ return beneath.groupToArrays((_$, at) => at.ancestor, (_$, at) => at.share).flattenToDict((_$, shares, ancestor) => totalled(shares).toDict((_$, _totals, tile) => East.value({
902
+ collection: collectionPath, row: key, path: ancestor, run: variant('subtreeTotals', null), level: summary, tile,
903
+ item: variant('none', null),
904
+ }, entryKey), (_$, totals) => East.value(variant('totals', totals), entryValue)));
905
+ });
906
+ }
907
+ /** Things people drag's totals from their shares ({@link itemTotals}), and, rolled up, each ancestor's ({@link itemSubtreeTotals}). */
908
+ function itemsTotalled(types, collection, summary) {
909
+ const own = itemTotals(types, collection, summary);
910
+ return collection.rollup ? sharedBoth(types, own, itemSubtreeTotals(types, collection, summary)) : own;
911
+ }
912
+ /** `(K, V, Nodes, Kit) → Dict<IK, P>`: things people drag's totals at every summary tile — their shares, totalled. */
913
+ function itemsTotalledAll(types, nodesType, shares, totals) {
914
+ return East.function([types.keyType, types.rowType, nodesType, KitType], types.entries, (_$, key, row, nodes, kit) => totals(key, shares(key, row, variant('all', null), nodes, kit), kit));
915
+ }
916
+ /**
917
+ * What a write moves of things people drag's totals ({@link NodesChanged}): the
918
+ * totals of the summary tiles the items it touched touch, of the row before
919
+ * and after.
920
+ */
921
+ function itemsMoved(types, nodesType, summary, shares, totals) {
922
+ const { keyType, rowType, changed } = types;
923
+ return East.function([keyType, rowType, rowType, rowType, rowType, nodesType, KitType], changed, ($, key, held, next, heldTouched, nextTouched, nodes, kit) => {
924
+ const shared = $.const(shares);
925
+ const totalled = $.const(totals);
926
+ const within = $.const(kit.within);
927
+ const nextOf = $.const(kit.nextOf);
928
+ // The summary tiles the items the patch names touch, before it and after.
929
+ const touched = $.let(shared(key, heldTouched, variant('all', null), nodes, kit).concat(shared(key, nextTouched, variant('all', null), nodes, kit)));
930
+ const at = $.let(within(touched.flattenToSet((_$, node) => node.shares.toSet((_$, share) => share.tile)), summary, nextOf));
931
+ return { before: totalled(key, shared(key, held, at, nodes, kit), kit), after: totalled(key, shared(key, next, at, nodes, kit), kit) };
932
+ });
933
+ }
934
+ /**
935
+ * The months a row's things people drag touch, each with how many of them
936
+ * touch it and the milliseconds of it they cover ({@link SpanPart}), an item
937
+ * across a month's end counted in each.
938
+ */
939
+ function itemsSpan(types, collection, nodesType, shares) {
940
+ return East.function([types.keyType, types.rowType, nodesType, KitType], SpanTotalsType, ($, key, row, nodes, kit) => {
941
+ const path = $.const(kit.path);
942
+ const at = $.let(path(East.value([...collection.place], KeysType)));
943
+ return shares(key, row, variant('all', null), nodes, kit).flatMap((_$, node) => node.shares).groupReduce((_$, share) => ({ collection: at, tile: share.tile }), ($) => $.const(NO_SPAN_TOTALS, RecordSummaryTotalsType), (_$, totals, share) => ({ count: totals.count.add(1n), ms: totals.ms.add(share.ms) }));
944
+ });
945
+ }
946
+ /** A collection of values, filed: `(K, V, Nodes, Kit) → Dict<IK, P>`, each value at its instant, at the index's tile. */
947
+ function valueEntries(decl, types, collection, nodesType) {
948
+ const group = decl.groups[collection.group];
949
+ const { keyType, rowType, entryKey, entries, tile } = types;
950
+ const holding = fieldOf(group.type, collection.field, DictType(DateTimeType, collection.valueType));
951
+ const place = placedItem(decl, collection, collection.valueType, types.entryValue);
952
+ const words = whatWords(collection);
953
+ return East.function([keyType, rowType, nodesType, KitType], entries, ($, key, row, nodes, kit) => {
954
+ const startOf = $.const(kit.startOf);
955
+ const nextOf = $.const(kit.nextOf);
956
+ const file = $.const(kit.file);
957
+ const path = $.const(kit.path);
958
+ const held = $.const(holding);
959
+ const into = $.const(place);
960
+ const collectionPath = $.let(path(East.value([...collection.place], KeysType)));
961
+ return nodes(row).flattenToDict(($, node) => {
962
+ const here = $.let(path(node.path));
963
+ return held(node.node).flattenToDict(($, value, at) => {
964
+ const instant = $.let(some(at), OptionType(DateTimeType));
965
+ const placed = $.let(into(value));
966
+ return file(tile, instant, instant, East.str `${East.print(key)} ${words} ${East.print(at)}`, startOf, nextOf).toDict((_$, filing) => East.value({
967
+ collection: collectionPath, row: key, path: here, run: variant('items', null), level: filing.level, tile: filing.tile,
968
+ item: variant('at', at),
969
+ }, entryKey), () => placed);
970
+ });
971
+ });
972
+ });
973
+ }
974
+ /**
975
+ * A node's values' totals in each tile of a level: `(values, level, Kit) →
976
+ * Dict<tile, Totals>` — numbers' carry their values (`valueTotals`);
977
+ * any other's count them (`instantTotals`).
978
+ */
979
+ function valuesTotalled(collection) {
980
+ const valuesType = DictType(DateTimeType, collection.valueType);
981
+ const totalsType = DictType(DateTimeType, RecordNestedTotalsType);
982
+ if (collection.numeric === undefined) {
983
+ return East.function([valuesType, RecordLevelType, KitType], totalsType, ($, values, level, kit) => {
984
+ const startOf = $.const(kit.startOf);
985
+ const counted = $.const(kit.counted);
986
+ return counted(values.keys(), level, startOf);
987
+ });
988
+ }
989
+ const asFloats = floatsOf(collection.valueType, collection.numeric);
990
+ return East.function([valuesType, RecordLevelType, KitType], totalsType, ($, values, level, kit) => {
991
+ const startOf = $.const(kit.startOf);
992
+ const floats = $.const(asFloats);
993
+ const summed = $.const(kit.summed);
994
+ return summed(floats(values), level, startOf);
995
+ });
996
+ }
997
+ /**
998
+ * A collection of values, totalled ({@link WithinEntries}): each node's
999
+ * values in each summary tile, of the tiles asked for: how many, and, for
1000
+ * numbers, their sum, the least, the greatest and the latest.
1001
+ */
1002
+ function valueTotalsOf(decl, types, collection, nodesType, summary) {
1003
+ const group = decl.groups[collection.group];
1004
+ const { keyType, rowType, entryKey, entryValue, entries } = types;
1005
+ const holding = fieldOf(group.type, collection.field, DictType(DateTimeType, collection.valueType));
1006
+ const totalsOf = valuesTotalled(collection);
1007
+ return East.function([keyType, rowType, WithinType, nodesType, KitType], entries, ($, key, row, within, nodes, kit) => {
1008
+ const startOf = $.const(kit.startOf);
1009
+ const kept = $.const(kit.kept);
1010
+ const path = $.const(kit.path);
1011
+ const held = $.const(holding);
1012
+ const totalled = $.const(totalsOf);
1013
+ const collectionPath = $.let(path(East.value([...collection.place], KeysType)));
1014
+ return nodes(row).flattenToDict(($, node) => {
1015
+ const here = $.let(path(node.path));
1016
+ const values = $.let(held(node.node));
1017
+ const counted = $.let(within.match({
1018
+ all: () => values,
1019
+ only: (_$, span) => values.filter((_$, _value, at) => kept(span, summary, at, startOf)),
1020
+ }));
1021
+ return totalled(counted, summary, kit).toDict((_$, _totals, tile) => East.value({
1022
+ collection: collectionPath, row: key, path: here, run: variant('totals', null), level: summary, tile, item: variant('none', null),
1023
+ }, entryKey), (_$, totals) => East.value(variant('totals', totals), entryValue));
1024
+ });
1025
+ });
1026
+ }
1027
+ /** `(K, V, Nodes, Kit) → Dict<IK, P>`: a collection of values' totals at every summary tile. */
1028
+ function valuesTotalledAll(types, nodesType, totals) {
1029
+ return East.function([types.keyType, types.rowType, nodesType, KitType], types.entries, (_$, key, row, nodes, kit) => totals(key, row, variant('all', null), nodes, kit));
1030
+ }
1031
+ /**
1032
+ * What a write moves of a collection of values' totals ({@link NodesChanged}): the
1033
+ * totals of the summary tiles the values it touched are in, of the row before
1034
+ * and after.
1035
+ */
1036
+ function valuesMoved(decl, types, collection, nodesType, summary, totals) {
1037
+ const group = decl.groups[collection.group];
1038
+ const { keyType, rowType, changed } = types;
1039
+ const holding = fieldOf(group.type, collection.field, DictType(DateTimeType, collection.valueType));
1040
+ return East.function([keyType, rowType, rowType, rowType, rowType, nodesType, KitType], changed, ($, key, held, next, heldTouched, nextTouched, nodes, kit) => {
1041
+ const startOf = $.const(kit.startOf);
1042
+ const nextOf = $.const(kit.nextOf);
1043
+ const within = $.const(kit.within);
1044
+ const holds = $.const(holding);
1045
+ const totalled = $.const(totals);
1046
+ // The summary tiles the values the patch names are in, before it and after.
1047
+ const touched = $.let(nodes(heldTouched).concat(nodes(nextTouched)).flattenToSet((_$, node) => holds(node.node).toSet((_$, _value, at) => startOf(summary, at))));
1048
+ const at = $.let(within(touched, summary, nextOf));
1049
+ return { before: totalled(key, held, at, nodes, kit), after: totalled(key, next, at, nodes, kit) };
1050
+ });
1051
+ }
1052
+ /**
1053
+ * Every node from the row down to a collection of values' group ({@link
1054
+ * Gathered}): each group's above it, holding none of its values, then its own
1055
+ * group's, holding its values as Floats.
1056
+ */
1057
+ function valuesGathered(decl, types, collection, nodesOf, numeric) {
1058
+ const { rowType } = types;
1059
+ const group = decl.groups[collection.group];
1060
+ // The nodes of each group above the collection's, from the row down.
1061
+ const above = chainTo(decl, collection.group).slice(0, -1).reduce((before, at) => {
1062
+ const nodes = nodesOf[at.index];
1063
+ const atGroup = BigInt(at.index);
1064
+ const none = noValues(at.type);
1065
+ return East.function([rowType], ArrayType(SubtotalNodeType), ($, row) => {
1066
+ const earlier = $.const(before);
1067
+ const these = $.const(nodes);
1068
+ const values = $.const(none);
1069
+ return earlier(row).concat(these(row).map((_$, node) => ({
1070
+ key: { path: node.path, group: atGroup }, parent: node.parent, own: values(node.node),
1071
+ })));
1072
+ });
1073
+ }, East.function([rowType], ArrayType(SubtotalNodeType), () => []));
1074
+ const own = valuesAsFloats(group.type, collection, numeric);
1075
+ const ownGroup = BigInt(group.index);
1076
+ const nodesType = WalkType(rowType, group);
1077
+ return East.function([rowType, nodesType], ArrayType(SubtotalNodeType), ($, row, nodes) => {
1078
+ const earlier = $.const(above);
1079
+ const values = $.const(own);
1080
+ return earlier(row).concat(nodes(row).map((_$, node) => ({ key: { path: node.path, group: ownGroup }, parent: node.parent, own: values(node.node) })));
1081
+ });
1082
+ }
1083
+ /** A collection of values rolled up, every parent's subtotals at the tiles asked for ({@link SubtotalEntries}), composed bottom-up (`subtotalsOf`). */
1084
+ function valueSubtotals(types, collection) {
1085
+ const { keyType, entryKey, entryValue, entries, levels } = types;
1086
+ return East.function([keyType, ArrayType(SubtotalNodeType), SubtotalTilesType, KitType], entries, ($, key, nodes, tiles, kit) => {
1087
+ const startOf = $.const(kit.startOf);
1088
+ const compose = $.const(kit.subtotals);
1089
+ const path = $.const(kit.path);
1090
+ const collectionPath = $.let(path(East.value([...collection.place], KeysType)));
1091
+ const rollups = $.let([...collection.rollups], ArrayType(RecordRollupType));
1092
+ const tiers = $.let([...levels], ArrayType(RecordLevelType));
1093
+ return compose(nodes, rollups, tiers, tiles, startOf).toDict((_$, _value, subtotal) => East.value({
1094
+ collection: collectionPath, row: key, path: subtotal.path, run: variant('subtotals', subtotal.rollup),
1095
+ level: subtotal.level, tile: subtotal.tile, item: variant('none', null),
1096
+ }, entryKey), (_$, value) => East.value(variant('subtotal', value), entryValue));
1097
+ });
1098
+ }
1099
+ /** `(K, V, Nodes, Kit) → Dict<IK, P>`: a collection of values rolled up, every parent's subtotals at every tile. */
1100
+ function valuesSubtotalledAll(types, nodesType, gathered, subtotals) {
1101
+ return East.function([types.keyType, types.rowType, nodesType, KitType], types.entries, (_$, key, row, nodes, kit) => subtotals(key, gathered(row, nodes), variant('all', null), kit));
1102
+ }
1103
+ /**
1104
+ * What a write moves of a collection of values' subtotals ({@link NodesChanged}):
1105
+ * every parent's subtotals of the tiles at each level the values it touched
1106
+ * are at, of the row before and after — where no node holding the
1107
+ * collection's values is a parent of another; in a recursive tree, every
1108
+ * subtotal, for a node given its first value keeps subtotals at no tile, and
1109
+ * one losing its last begins to at every tile.
1110
+ */
1111
+ function valuesSubtotalsMoved(decl, types, collection, nodesType, gathered, subtotals) {
1112
+ const { keyType, rowType, changed, levels } = types;
1113
+ if (decl.groups[collection.group].through !== undefined) {
1114
+ return East.function([keyType, rowType, rowType, rowType, rowType, nodesType, KitType], changed, ($, key, held, next, _heldTouched, _nextTouched, nodes, kit) => {
1115
+ const gather = $.const(gathered);
1116
+ const composed = $.const(subtotals);
1117
+ return { before: composed(key, gather(held, nodes), variant('all', null), kit), after: composed(key, gather(next, nodes), variant('all', null), kit) };
1118
+ });
1119
+ }
1120
+ return East.function([keyType, rowType, rowType, rowType, rowType, nodesType, KitType], changed, ($, key, held, next, heldTouched, nextTouched, nodes, kit) => {
1121
+ const startOf = $.const(kit.startOf);
1122
+ const nextOf = $.const(kit.nextOf);
1123
+ const levelsWithin = $.const(kit.levelsWithin);
1124
+ const gather = $.const(gathered);
1125
+ const composed = $.const(subtotals);
1126
+ const tiers = $.let([...levels], ArrayType(RecordLevelType));
1127
+ // The tiles at each level the values the patch names are at, before it and after.
1128
+ const touched = $.let(gather(heldTouched, nodes).concat(gather(nextTouched, nodes)).flattenToSet((_$, node) => node.own.keys()));
1129
+ const at = $.let(levelsWithin(touched, tiers, startOf, nextOf));
1130
+ return { before: composed(key, gather(held, nodes), at, kit), after: composed(key, gather(next, nodes), at, kit) };
1131
+ });
1132
+ }
1133
+ /** The months a row's values are in, each with how many are in it ({@link SpanPart}), a value covering no milliseconds. */
1134
+ function valuesSpan(decl, types, collection, nodesType) {
1135
+ const group = decl.groups[collection.group];
1136
+ const holding = fieldOf(group.type, collection.field, DictType(DateTimeType, collection.valueType));
1137
+ const month = levelOf(SPAN_TILE);
1138
+ return East.function([types.keyType, types.rowType, nodesType, KitType], SpanTotalsType, ($, _key, row, nodes, kit) => {
1139
+ const startOf = $.const(kit.startOf);
1140
+ const path = $.const(kit.path);
1141
+ const held = $.const(holding);
1142
+ const at = $.let(path(East.value([...collection.place], KeysType)));
1143
+ return nodes(row).flatMap((_$, node) => held(node.node).toArray((_$, _value, instant) => startOf(month, instant))).groupReduce((_$, tile) => ({ collection: at, tile }), ($) => $.const(NO_SPAN_TOTALS, RecordSummaryTotalsType), (_$, totals) => ({ count: totals.count.add(1n), ms: totals.ms }));
1144
+ });
1145
+ }
1146
+ /**
1147
+ * A collection's entries of a row, given its group's nodes ({@link
1148
+ * NodesEntries}): its items or values filed — rolled up, under every ancestor
1149
+ * too — and, where a summary is declared, its totals; where its values roll
1150
+ * up, every parent's subtotals.
1151
+ *
1152
+ * @param decl - The checked declaration
1153
+ * @param types - The index's types
1154
+ * @param collection - The collection
1155
+ * @param nodesOf - Each group's nodes from a row
1156
+ * @returns Its entries
1157
+ */
1158
+ function collectionEntries(decl, types, collection, nodesOf) {
1159
+ const nodesType = WalkType(types.rowType, decl.groups[collection.group]);
1160
+ const { summary } = types;
1161
+ if (collection.kind === 'items') {
1162
+ const filed = itemsFiled(decl, types, collection, nodesType);
1163
+ if (summary === undefined)
1164
+ return filed;
1165
+ return nodesUnion(types, nodesType, [
1166
+ filed, itemsTotalledAll(types, nodesType, itemShares(decl, types, collection, nodesType, summary), itemsTotalled(types, collection, summary)),
1167
+ ]);
1168
+ }
1169
+ const totals = summary === undefined ? [] : [valuesTotalledAll(types, nodesType, valueTotalsOf(decl, types, collection, nodesType, summary))];
1170
+ const subtotals = collection.numeric === undefined || collection.rollups.length === 0 ? [] : [valuesSubtotalledAll(types, nodesType, valuesGathered(decl, types, collection, nodesOf, collection.numeric), valueSubtotals(types, collection))];
1171
+ return nodesUnion(types, nodesType, [valueEntries(decl, types, collection, nodesType), ...totals, ...subtotals]);
1172
+ }
1173
+ /**
1174
+ * A collection's part of a write's entries, by its patch, given its group's
1175
+ * nodes ({@link NodesChanged}): the entries of the items or values it touched,
1176
+ * before and after, and, where it touched any, the totals of the summary tiles
1177
+ * they touch and every parent's subtotals of the tiles at each level they
1178
+ * touch — every subtotal, in a recursive tree — of the row before and after.
1179
+ *
1180
+ * @param decl - The checked declaration
1181
+ * @param types - The index's types
1182
+ * @param collection - The collection
1183
+ * @param nodesOf - Each group's nodes from a row
1184
+ * @returns Its part
1185
+ */
1186
+ function collectionPatched(decl, types, collection, nodesOf) {
1187
+ const nodesType = WalkType(types.rowType, decl.groups[collection.group]);
1188
+ const { summary } = types;
1189
+ if (collection.kind === 'items') {
1190
+ const filed = itemsFiled(decl, types, collection, nodesType);
1191
+ if (summary === undefined)
1192
+ return patchedWith(types, nodesType, filed, undefined);
1193
+ const moved = itemsMoved(types, nodesType, summary, itemShares(decl, types, collection, nodesType, summary), itemsTotalled(types, collection, summary));
1194
+ return patchedWith(types, nodesType, filed, moved);
1195
+ }
1196
+ const moved = [
1197
+ ...(summary === undefined ? [] : [valuesMoved(decl, types, collection, nodesType, summary, valueTotalsOf(decl, types, collection, nodesType, summary))]),
1198
+ ...(collection.numeric === undefined || collection.rollups.length === 0 ? [] : [valuesSubtotalsMoved(decl, types, collection, nodesType, valuesGathered(decl, types, collection, nodesOf, collection.numeric), valueSubtotals(types, collection))]),
1199
+ ];
1200
+ return patchedWith(types, nodesType, valueEntries(decl, types, collection, nodesType), moved.length === 0 ? undefined : changedUnion(types, nodesType, moved));
1201
+ }
1202
+ /** A collection's months of a row, for the index's span, given its group's nodes ({@link NodesSpan}). */
1203
+ function collectionSpan(decl, types, collection) {
1204
+ const nodesType = WalkType(types.rowType, decl.groups[collection.group]);
1205
+ if (collection.kind === 'items')
1206
+ return itemsSpan(types, collection, nodesType, itemShares(decl, types, collection, nodesType, levelOf(SPAN_TILE)));
1207
+ return valuesSpan(decl, types, collection, nodesType);
1208
+ }
1209
+ /** The groups holding a collection: a program's parts are theirs, each binding its group's walk once for its collections. */
1210
+ function groupsHolding(decl) {
1211
+ return decl.groups.filter((group) => group.collections.length > 0);
1212
+ }
1213
+ /**
1214
+ * What a collection's part of a program calls of the kit ({@link KitType})
1215
+ * beside the tiles' steps and a path's: filing, and where a summary is
1216
+ * declared, its totals' — sharing items out, or counting or summing values —
1217
+ * and its parents' subtotals where its values roll up; a write's, too, the
1218
+ * tiles it touches; a span's, sharing items out.
1219
+ *
1220
+ * @param decl - The checked declaration
1221
+ * @param types - The index's types
1222
+ * @param collection - The collection
1223
+ * @param program - The program
1224
+ * @returns What it calls
1225
+ */
1226
+ function kitCalls(decl, types, collection, program) {
1227
+ if (program === 'span')
1228
+ return collection.kind === 'items' ? ['share'] : [];
1229
+ const calls = ['file'];
1230
+ if (types.summary !== undefined) {
1231
+ if (collection.kind === 'items')
1232
+ calls.push('share', 'totalled');
1233
+ else
1234
+ calls.push('kept', collection.numeric === undefined ? 'counted' : 'summed');
1235
+ if (program === 'byPatch')
1236
+ calls.push('within');
1237
+ }
1238
+ if (collection.kind === 'values' && collection.numeric !== undefined && collection.rollups.length > 0) {
1239
+ calls.push('subtotals');
1240
+ if (program === 'byPatch' && decl.groups[collection.group].through === undefined)
1241
+ calls.push('levelsWithin');
1242
+ }
1243
+ return calls;
1244
+ }
1245
+ // ── The programs ──────────────────────────────────────────────────────────────
1246
+ /** `(K, V, Kit) → Dict<IK, P>`: parts' entries, one after another, each a function calling the parts before it. */
1247
+ function entriesUnion(types, parts) {
1248
+ const [first, ...rest] = parts;
1249
+ if (first === undefined)
1250
+ return East.function([types.keyType, types.rowType, KitType], types.entries, () => new Map());
1251
+ return rest.reduce((before, part) => East.function([types.keyType, types.rowType, KitType], types.entries, ($, key, row, kit) => {
1252
+ const all = $.let(before(key, row, kit));
1253
+ $(all.unionInPlace(part(key, row, kit)));
1254
+ return all;
1255
+ }), first);
1256
+ }
1257
+ /** `(K, V, V, V, V, Kit) → { before, after }`: parts of a write's entries, one after another, each a function calling the parts before it. */
1258
+ function patchedUnion(types, parts) {
1259
+ const { keyType, rowType, changed } = types;
1260
+ const [first, ...rest] = parts;
1261
+ if (first === undefined) {
1262
+ return East.function([keyType, rowType, rowType, rowType, rowType, KitType], changed, () => ({ before: new Map(), after: new Map() }));
1263
+ }
1264
+ return rest.reduce((before, part) => East.function([keyType, rowType, rowType, rowType, rowType, KitType], changed, ($, key, held, next, heldTouched, nextTouched, kit) => {
1265
+ const all = $.let(before(key, held, next, heldTouched, nextTouched, kit));
1266
+ const more = $.let(part(key, held, next, heldTouched, nextTouched, kit));
1267
+ $(all.before.unionInPlace(more.before));
1268
+ $(all.after.unionInPlace(more.after));
1269
+ return all;
1270
+ }), first);
1271
+ }
1272
+ /** `(K, V, Kit) → Dict<{ collection, tile }, Totals>`: parts of the span, one after another, each a function calling the parts before it. */
1273
+ function spanUnion(types, parts) {
1274
+ const [first, ...rest] = parts;
1275
+ if (first === undefined)
1276
+ return East.function([types.keyType, types.rowType, KitType], SpanTotalsType, () => new Map());
1277
+ return rest.reduce((before, part) => East.function([types.keyType, types.rowType, KitType], SpanTotalsType, ($, key, row, kit) => {
1278
+ const all = $.let(before(key, row, kit));
1279
+ $(all.unionInPlace(part(key, row, kit)));
1280
+ return all;
1281
+ }), first);
1282
+ }
1283
+ /** The types a nested series index's programs are built over ({@link NestedTypes}). */
1284
+ function nestedTypes(decl, keyType, rowType, tile, summary) {
1285
+ const entryKey = NestedEntryKeyType(keyType);
1286
+ const entryValue = NestedEntryType(decl.places);
1287
+ const entries = DictType(entryKey, entryValue);
1288
+ return {
1289
+ keyType, rowType, entryKey, entryValue, entries,
1290
+ changed: StructType({ before: entries, after: entries }),
1291
+ tile: levelOf(tile),
1292
+ summary: summary === undefined ? undefined : levelOf(summary),
1293
+ levels: RECORD_TILES.slice(RECORD_TILES.indexOf(tile)).map(levelOf),
1294
+ };
1295
+ }
1296
+ /** A program's kit, holding each function its collections' parts call ({@link kitCalls}). */
1297
+ function kitOf(decl, types, program) {
1298
+ return programKit(new Set(decl.collections.flatMap((collection) => kitCalls(decl, types, collection, program))));
1299
+ }
1300
+ /** A row's entries: `(K, V) → Dict<IK, P>`, each group's part's, over a kit binding once each function they call. */
1301
+ function entriesProgram(decl, types, nodesOf) {
1302
+ const kit = kitOf(decl, types, 'entries');
1303
+ const parts = entriesUnion(types, groupsHolding(decl).map((group) => groupEntries(types, nodesOf[group.index], nodesUnion(types, WalkType(types.rowType, group), group.collections.map((collection) => collectionEntries(decl, types, collection, nodesOf))))));
1304
+ return East.function([types.keyType, types.rowType], types.entries, ($, key, row) => {
1305
+ const tools = $.const(kit());
1306
+ return parts(key, row, tools);
1307
+ });
1308
+ }
1309
+ // ── The row's entries, a write's by its patch, and the row's lean form ───────
1310
+ /**
1311
+ * What a write's patch makes of a row's entries: `whole` where it cannot say
1312
+ * — a replace on the way — or the entries it changes, before and after.
1313
+ *
1314
+ * @param entries - The row's entries, `Dict<IK, P>`
1315
+ * @returns The variant type
1316
+ */
1317
+ export function NestedPatchedType(entries) {
1318
+ return VariantType({ whole: NullType, changed: StructType({ before: entries, after: entries }) });
1319
+ }
1320
+ /**
1321
+ * A write's entries of a row, by its patch: `(K, V, V, Patch) → Patched`,
1322
+ * given the row before and after and the patch between them — the row walked
1323
+ * by the patch ({@link rowWalk}), and each collection's entries what it
1324
+ * touched moves, before and after ({@link collectionPatched}), over a kit
1325
+ * binding once each function they call; `whole` where a replace on the way
1326
+ * leaves the row to be compared whole.
1327
+ *
1328
+ * @param decl - The checked declaration
1329
+ * @param types - The index's types
1330
+ * @param nodesOf - Each group's nodes from a row
1331
+ * @returns The function
1332
+ */
1333
+ function nestedByPatch(decl, types, nodesOf) {
1334
+ const { keyType, rowType, entries } = types;
1335
+ const walk = rowWalk(decl);
1336
+ const kit = kitOf(decl, types, 'byPatch');
1337
+ const parts = patchedUnion(types, groupsHolding(decl).map((group) => groupPatched(types, nodesOf[group.index], changedUnion(types, WalkType(rowType, group), group.collections.map((collection) => collectionPatched(decl, types, collection, nodesOf))))));
1338
+ const patchType = patchTypeOf(rowType);
1339
+ const patchedType = NestedPatchedType(entries);
1340
+ return East.function([keyType, rowType, rowType, patchType], patchedType, ($, key, held, next, patch) => {
1341
+ const touched = $.const(walk);
1342
+ $.match(touched(held, next, patch), {
1343
+ replaced: ($) => {
1344
+ $.return(variant('whole', null));
1345
+ },
1346
+ unchanged: ($) => {
1347
+ $.return(variant('changed', { before: new Map(), after: new Map() }));
1348
+ },
1349
+ touched: ($, rows) => {
1350
+ const tools = $.const(kit());
1351
+ $.return(variant('changed', parts(key, held, next, rows.held, rows.next, tools)));
1352
+ },
1353
+ });
1354
+ return variant('whole', null);
1355
+ });
1356
+ }
1357
+ /**
1358
+ * A row's entries: `(K, V) → Dict<IK, P>`, each collection's part's — its
1359
+ * items or values filed, its totals where a summary is declared, its subtree
1360
+ * filing where it rolls items up, and its parents' subtotals where it rolls
1361
+ * values up — one after another, over a kit binding once each function they
1362
+ * call ({@link programKit}). And a write's, by its patch ({@link
1363
+ * nestedByPatch}).
1364
+ *
1365
+ * @param decl - The checked declaration
1366
+ * @param keyType - The record's key type
1367
+ * @param rowType - The record's row type
1368
+ * @param tile - The index's tile
1369
+ * @param summary - Its summary tile; none where no totals are kept
1370
+ * @returns The entries, a write's by its patch, and their key and value types
1371
+ */
1372
+ export function nestedEntries(decl, keyType, rowType, tile, summary) {
1373
+ const types = nestedTypes(decl, keyType, rowType, tile, summary);
1374
+ const nodesOf = groupNodes(decl, rowType);
1375
+ return {
1376
+ entries: entriesProgram(decl, types, nodesOf),
1377
+ byPatch: nestedByPatch(decl, types, nodesOf),
1378
+ entryKey: types.entryKey,
1379
+ entryValue: types.entryValue,
1380
+ };
1381
+ }
1382
+ // ── Its span (#1438) ───────────────────────────────────────────────────────────
1383
+ /**
1384
+ * A nested series index's span of a row (#1438): `(K, V) → Dict<{ collection,
1385
+ * tile }, Totals>`, each collection's months the row's items or values touch,
1386
+ * each with how many of them touch it and the milliseconds of it its items
1387
+ * cover. Summed across the record's rows as a summary index's totals are, and
1388
+ * a month let go once nothing touches it, a collection's first and last month
1389
+ * held are its span: the time a Plan's series reading it cover, whatever rows
1390
+ * they show. Its months' counts are how much there is in each: a Plan's
1391
+ * horizon strip draws them as its bars.
1392
+ *
1393
+ * @param decl - The checked declaration
1394
+ * @param keyType - The record's key type
1395
+ * @param rowType - The record's row type
1396
+ * @param tile - The index's tile
1397
+ * @returns A row's months, by collection
1398
+ */
1399
+ export function nestedSpan(decl, keyType, rowType, tile) {
1400
+ const types = nestedTypes(decl, keyType, rowType, tile, undefined);
1401
+ const nodesOf = groupNodes(decl, rowType);
1402
+ const kit = kitOf(decl, types, 'span');
1403
+ const parts = spanUnion(types, groupsHolding(decl).map((group) => groupSpan(types, nodesOf[group.index], spanNodesUnion(types, WalkType(rowType, group), group.collections.map((collection) => collectionSpan(decl, types, collection))))));
1404
+ return East.function([keyType, rowType], SpanTotalsType, ($, key, row) => {
1405
+ const tools = $.const(kit());
1406
+ return parts(key, row, tools);
1407
+ });
1408
+ }
1409
+ /**
1410
+ * A nested series index's span (#1438), an index of the record's beside it,
1411
+ * named by `nestedSpanName`: its rows' months by collection
1412
+ * ({@link nestedSpan}), summed as a summary index's totals are.
1413
+ *
1414
+ * @param name - The nested series index
1415
+ * @param rec - Its record
1416
+ * @param decl - Its checked declaration
1417
+ * @param keyType - The record's key type
1418
+ * @param rowType - The record's row type
1419
+ * @param tile - Its tile
1420
+ * @param runner - Its runner selection
1421
+ * @returns The span's definition
1422
+ */
1423
+ function nestedSpanDefinition(name, rec, decl, keyType, rowType, tile, runner) {
1424
+ const spanName = nestedSpanName(name);
1425
+ const keyFn = nestedSpan(decl, keyType, rowType, tile);
1426
+ checkPure(`index.nested '${name}' span`, keyFn, INDEX_PURITY);
1427
+ return {
1428
+ kind: 'recordIndex',
1429
+ name: spanName,
1430
+ record: rec,
1431
+ on: Object.freeze([]),
1432
+ span: Object.freeze({ of: name, tile: SPAN_TILE }),
1433
+ keyFn,
1434
+ mergeFn: summaryMerge(spanName, NestedSpanKeyType),
1435
+ // A row touches several months, and a month stands for every row touching it.
1436
+ multi: true,
1437
+ keyType: NestedSpanKeyType,
1438
+ valueType: RecordSummaryTotalsType,
1439
+ runner,
1440
+ };
1441
+ }
1442
+ /** Where a node's items are filed: its collection's place and its path, as an entry's key holds them. */
1443
+ const NodePlaceType = StructType({ collection: RecordNestedPathType, path: RecordNestedPathType });
1444
+ /**
1445
+ * An item out of its entry's value: `(P) → I`, from the outside in — the
1446
+ * `item` case, then each child rows' field from the row down, then the
1447
+ * collection's own (`.item .members .load 0.82` → `0.82`). The inverse of
1448
+ * {@link placedItem}.
1449
+ *
1450
+ * @param decl - The declaration
1451
+ * @param collection - The collection
1452
+ * @param itemType - Its items' type
1453
+ * @param entryValue - The entry value, `P`
1454
+ * @returns The item
1455
+ */
1456
+ function itemOf(decl, collection, itemType, entryValue) {
1457
+ const names = [];
1458
+ for (let group = decl.groups[collection.group], name = collection.field;;) {
1459
+ names.unshift(name);
1460
+ if (group.parent === undefined)
1461
+ break;
1462
+ name = group.parent.field;
1463
+ group = decl.groups[group.parent.group];
1464
+ }
1465
+ // The names are the declaration's, each a case of the variant it unwraps, so the variant's type is the one before.
1466
+ return East.function([entryValue], itemType, (_$, value) => ['item', ...names].reduce((within, name) => within.unwrap(name), value));
1467
+ }
1468
+ /**
1469
+ * A collection of a node, filled: `(keys, byPlace) → Dict<…>`, the items its
1470
+ * entries name at the node's path, under each one's id or instant — an item
1471
+ * filed in several tiles once.
1472
+ *
1473
+ * @param decl - The declaration
1474
+ * @param collection - The collection
1475
+ * @param entry - An entry's type, `{ ik, value }`
1476
+ * @param entryValue - The entry value, `P`
1477
+ * @returns The filling
1478
+ */
1479
+ function collectionFill(decl, collection, entry, entryValue) {
1480
+ const byPlace = DictType(NodePlaceType, ArrayType(entry));
1481
+ const itemType = collection.kind === 'items' ? collection.itemType : collection.valueType;
1482
+ const filled = filledType(collection);
1483
+ const item = itemOf(decl, collection, itemType, entryValue);
1484
+ const keyOf = collection.kind === 'items'
1485
+ ? East.function([entry], StringType, (_$, filed) => East.field(East.field(filed, 'ik'), 'item', RecordNestedItemType).unwrap('id'))
1486
+ : East.function([entry], DateTimeType, (_$, filed) => East.field(East.field(filed, 'ik'), 'item', RecordNestedItemType).unwrap('at'));
1487
+ return East.function([KeysType, byPlace], filled, ($, keys, entries) => {
1488
+ const path = $.const(NESTED_FNS.pathOf);
1489
+ const itemFrom = $.const(item);
1490
+ const key = $.const(keyOf);
1491
+ const here = $.let({ collection: path(East.value([...collection.place], KeysType)), path: path(keys) }, NodePlaceType);
1492
+ return entries.get(here, () => East.value([], ArrayType(entry))).toDict((_$, filed) => key(filed), (_$, filed) => itemFrom(East.field(filed, 'value', entryValue)), (_$, kept) => kept);
1493
+ });
1494
+ }
1495
+ /** A collection's type: its items by their ids, or its values by their instants. */
1496
+ function filledType(collection) {
1497
+ return collection.kind === 'items' ? DictType(StringType, collection.itemType) : DictType(DateTimeType, collection.valueType);
1498
+ }
1499
+ /**
1500
+ * An entry as a fill puts its item back: `(entry) → Option<entry>` — one filed
1501
+ * at its own node as it is; one filed under a parent (`subtree`) at the node
1502
+ * holding it, its path the parent's then the keys down to it, its item its id;
1503
+ * a total or a subtotal none.
1504
+ *
1505
+ * @param entry - An entry's type, `{ ik, value }`
1506
+ * @returns The placing
1507
+ */
1508
+ function fillingEntry(entry) {
1509
+ return East.function([entry], OptionType(entry), ($, filed) => {
1510
+ const keys = $.const(NESTED_FNS.keysOf);
1511
+ const ik = $.let(filed.ik);
1512
+ return East.field(ik, 'run', RecordNestedRunType).match({
1513
+ items: () => some(filed),
1514
+ subtree: ($2) => {
1515
+ const under = $2.let(East.field(ik, 'item', RecordNestedItemType).unwrap('under'));
1516
+ const path = $2.let(keys(East.field(ik, 'path', RecordNestedPathType)).reverse().reduce((_$, rest, key) => variant('step', { key, rest }), under.path));
1517
+ const item = $2.let(variant('id', under.id), RecordNestedItemType);
1518
+ return some({ ik: East.withField(East.withField(ik, 'path', path), 'item', item), value: filed.value });
1519
+ },
1520
+ }, () => none);
1521
+ });
1522
+ }
1523
+ /**
1524
+ * A lean row filled with items read of it: `(K, V, Array<{ ik, value }>) →
1525
+ * V`, each item the entries file — of a node, by its path, and a collection,
1526
+ * by its place — put back in its collection under its id or its instant, an
1527
+ * item filed in several tiles once, and every other field as the lean row
1528
+ * holds it. The inverse of the filing: a row's lean form filled with all its
1529
+ * entries is the row, and filled with the entries of some cells, the row
1530
+ * holding the items read there. An item filed under a parent is put back in
1531
+ * the node holding it, as its own entry puts it — so a parent's items read
1532
+ * whole are its descendants' — and totals and subtotals fill nothing.
1533
+ *
1534
+ * @param decl - The checked declaration
1535
+ * @param keyType - The record's key type
1536
+ * @param rowType - The record's row type
1537
+ * @param entryKey - The entry key, `IK`
1538
+ * @param entryValue - The entry value, `P`
1539
+ * @returns The filling
1540
+ */
1541
+ export function nestedFill(decl, keyType, rowType, entryKey, entryValue) {
1542
+ const entry = StructType({ ik: entryKey, value: entryValue });
1543
+ const byPlace = DictType(NodePlaceType, ArrayType(entry));
1544
+ // Each group's node filled, `(N, keys, byPlace) → N`, and its rows filled under a node at keys, `(Dict<String, N>, keys, byPlace) → Dict`:
1545
+ // its child groups' first.
1546
+ const fillOf = [];
1547
+ const rowsFillOf = [];
1548
+ for (const group of [...decl.groups].reverse()) {
1549
+ const fields = [];
1550
+ for (const collection of group.collections) {
1551
+ const filled = collectionFill(decl, collection, entry, entryValue);
1552
+ const type = filledType(collection);
1553
+ fields.push({ field: collection.field, fill: East.function([group.type, KeysType, byPlace], type, ($, _node, keys, entries) => {
1554
+ const fill = $.const(filled);
1555
+ return fill(keys, entries);
1556
+ }) });
1557
+ }
1558
+ for (const child of group.rows) {
1559
+ const rowsType = DictType(StringType, decl.groups[child.group].type);
1560
+ const rowsOf = fieldOf(group.type, child.field, rowsType);
1561
+ const rowsFill = rowsFillOf[child.group];
1562
+ fields.push({ field: child.field, fill: East.function([group.type, KeysType, byPlace], rowsType, ($, node, keys, entries) => {
1563
+ const rows = $.const(rowsOf);
1564
+ const fill = $.const(rowsFill);
1565
+ return fill(rows(node), keys, entries);
1566
+ }) });
1567
+ }
1568
+ const own = fields.reduce((before, { field, fill }) => East.function([group.type, KeysType, byPlace], group.type, ($, node, keys, entries) => {
1569
+ const earlier = $.const(before);
1570
+ const value = $.const(fill);
1571
+ const held = $.let(earlier(node, keys, entries));
1572
+ return East.withField(held, field, value(node, keys, entries));
1573
+ }), East.function([group.type, KeysType, byPlace], group.type, (_$, node) => node));
1574
+ fillOf[group.index] = own;
1575
+ const rowsType = DictType(StringType, group.type);
1576
+ if (group.through === undefined) {
1577
+ rowsFillOf[group.index] = East.function([rowsType, KeysType, byPlace], rowsType, ($, rows, keys, entries) => {
1578
+ const fill = $.const(own);
1579
+ return rows.map((_$, node, key) => fill(node, keys.concat([key]), entries));
1580
+ });
1581
+ continue;
1582
+ }
1583
+ // Beside recursive(): every row beneath, flattened, each filled at its keys, then rebuilt bottom-up, holding its own rebuilt rows.
1584
+ const keyed = StructType({ key: StringType, node: group.type });
1585
+ const deeper = fieldOf(group.type, group.through, rowsType);
1586
+ const holding = withField(group.type, group.through, rowsType);
1587
+ rowsFillOf[group.index] = East.function([rowsType, KeysType, byPlace], rowsType, ($, rows, keys, entries) => {
1588
+ const beneath = $.const(deeper);
1589
+ const fill = $.const(own);
1590
+ const hold = $.const(holding);
1591
+ const above = $.const(NESTED_FNS.keysAbove);
1592
+ const roots = $.let(rows.flattenTree((_$, node) => beneath(node)).toTree(keyed, (_$, at) => at.path, (_$, at) => above(at.path), (_$, at, _i, children) => ({
1593
+ key: at.path.get(at.path.size().subtract(1n)),
1594
+ node: hold(fill(at.node, keys.concat(at.path), entries), children.toDict((_$, child) => child.key, (_$, child) => child.node)),
1595
+ })));
1596
+ return roots.toDict((_$, root) => root.key, (_$, root) => root.node);
1597
+ });
1598
+ }
1599
+ const rowFill = fillOf[0];
1600
+ const filling = fillingEntry(entry);
1601
+ return East.function([keyType, rowType, ArrayType(entry)], rowType, ($, _key, row, entries) => {
1602
+ const fill = $.const(rowFill);
1603
+ const place = $.const(filling);
1604
+ const own = $.let(entries
1605
+ .filterMap((_$, filed) => place(filed))
1606
+ .groupToArrays(($2, filed) => {
1607
+ const ik = $2.let(East.field(filed, 'ik'));
1608
+ const place = $2.let({ collection: East.field(ik, 'collection', RecordNestedPathType), path: East.field(ik, 'path', RecordNestedPathType) }, NodePlaceType);
1609
+ return place;
1610
+ }));
1611
+ return fill(row, East.value([], KeysType), own);
1612
+ });
1613
+ }
1614
+ /**
1615
+ * A row's lean form: `(K, V) → V`, every listed collection empty, each child
1616
+ * row kept with its own listed collections empty — a recursive group's rows
1617
+ * rebuilt bottom-up by `toTree` over `flattenTree`'s nodes. What the record's
1618
+ * other indexes carry beside a nested series index.
1619
+ *
1620
+ * @param decl - The checked declaration
1621
+ * @param keyType - The record's key type
1622
+ * @param rowType - The record's row type
1623
+ * @returns The lean form
1624
+ */
1625
+ export function nestedLean(decl, keyType, rowType) {
1626
+ // Each group's own lean form, its child groups' first: their collections emptied, their child rows' lean.
1627
+ const leanOf = [];
1628
+ const rowsLeanOf = [];
1629
+ for (const group of [...decl.groups].reverse()) {
1630
+ const fields = {};
1631
+ const struct = group.type.type === 'Recursive' ? group.type.node : group.type;
1632
+ if (struct.type !== 'Struct')
1633
+ throw new Error(`a nested series index's node is a Struct, not ${struct.type}`);
1634
+ for (const collection of group.collections)
1635
+ fields[collection.field] = emptied(group.type, struct.fields[collection.field]);
1636
+ for (const child of group.rows) {
1637
+ const rowsType = DictType(StringType, decl.groups[child.group].type);
1638
+ const rowsOf = fieldOf(group.type, child.field, rowsType);
1639
+ const leanRows = rowsLeanOf[child.group];
1640
+ fields[child.field] = East.function([group.type], rowsType, ($, node) => {
1641
+ const rows = $.const(rowsOf);
1642
+ const lean = $.const(leanRows);
1643
+ return lean(rows(node));
1644
+ });
1645
+ }
1646
+ const own = rebuiltNode(group.type, fields);
1647
+ leanOf[group.index] = own;
1648
+ const rowsType = DictType(StringType, group.type);
1649
+ if (group.through === undefined) {
1650
+ rowsLeanOf[group.index] = East.function([rowsType], rowsType, ($, rows) => {
1651
+ const lean = $.const(own);
1652
+ return rows.map((_$, node) => lean(node));
1653
+ });
1654
+ continue;
1655
+ }
1656
+ // Beside recursive(): every row beneath, flattened, then rebuilt bottom-up, each lean and holding its own rebuilt rows.
1657
+ const keyed = StructType({ key: StringType, node: group.type });
1658
+ const deeper = fieldOf(group.type, group.through, rowsType);
1659
+ const holding = withField(group.type, group.through, rowsType);
1660
+ rowsLeanOf[group.index] = East.function([rowsType], rowsType, ($, rows) => {
1661
+ const beneath = $.const(deeper);
1662
+ const lean = $.const(own);
1663
+ const hold = $.const(holding);
1664
+ const above = $.const(NESTED_FNS.keysAbove);
1665
+ const roots = $.let(rows.flattenTree((_$, node) => beneath(node)).toTree(keyed, (_$, entry) => entry.path, (_$, entry) => above(entry.path), (_$, entry, _i, children) => ({
1666
+ key: entry.path.get(entry.path.size().subtract(1n)),
1667
+ node: hold(lean(entry.node), children.toDict((_$, child) => child.key, (_$, child) => child.node)),
1668
+ })));
1669
+ return roots.toDict((_$, root) => root.key, (_$, root) => root.node);
1670
+ });
1671
+ }
1672
+ const rowLean = leanOf[0];
1673
+ return East.function([keyType, rowType], rowType, ($, _key, row) => {
1674
+ const lean = $.const(rowLean);
1675
+ return lean(row);
1676
+ });
1677
+ }
1678
+ // ── The definition ────────────────────────────────────────────────────────────
1679
+ /**
1680
+ * The nested series index's definition (`index.nested`, #1434): its key function a row's entries, `(K, V) →
1681
+ * Dict<IK, P>` — every declared collection's items filed by #1433's levels,
1682
+ * each node's totals where a summary is declared, each item rolled up filed
1683
+ * under every ancestor too, and every parent's subtotals of each collection of
1684
+ * values rolled up — a write's entries by its patch, which a write maintains
1685
+ * it by where the patch can say what it touched, and, for the record's other
1686
+ * indexes, its lean row.
1687
+ *
1688
+ * @param constructor - The declaration, as a refusal names it
1689
+ * @param name - The index
1690
+ * @param rec - Its record
1691
+ * @param spec - `collections`, `tile` and `summary`, as written
1692
+ * @param config - Its runner selection
1693
+ * @returns The definition: its key e3-types' `NestedEntryKeyType`, its value `NestedEntryType`
1694
+ * @throws {Error} Beside `collections`, the key form's fields, `on` or a `value`; a tile of none of the five; a second
1695
+ * nested series index on the record; or what {@link checkNested} refuses, each in its words
1696
+ */
1697
+ export function nestedDefinition(constructor, name, rec, spec, config) {
1698
+ const { keyType, valueType } = indexedEntry(constructor, name, rec);
1699
+ if ('key' in spec || 'from' in spec || 'to' in spec) {
1700
+ throw new Error(`${constructor} '${name}' takes collections, tile and summary — key, from and to file the record's own events: index.series({ key, from, to, tile })`);
1701
+ }
1702
+ if ('on' in spec) {
1703
+ throw new Error(`${constructor} '${name}' takes no on with collections — a nested collection is read by its row's key, which the rail's indexes page`);
1704
+ }
1705
+ if ('value' in spec)
1706
+ throw new Error(`${constructor} '${name}' takes no value — each entry carries its own item, totals or subtotal`);
1707
+ onlyOptions(constructor, name, spec, ['collections', 'tile', 'summary']);
1708
+ const written = spec;
1709
+ const tile = checkTile(constructor, name, written.tile);
1710
+ const summary = written.summary === undefined ? undefined : checkTile(constructor, name, written.summary);
1711
+ const already = Object.values(rec.indexes).find((index) => index.nested !== undefined);
1712
+ if (already !== undefined) {
1713
+ throw new Error(`${constructor} '${name}': record '${rec.name}' has a nested series index already, '${already.name}' — one declares every collection a record nests`);
1714
+ }
1715
+ const decl = checkNested(constructor, name, valueType, written.collections);
1716
+ const { entries, byPatch, entryKey, entryValue } = nestedEntries(decl, keyType, valueType, tile, summary);
1717
+ const fill = nestedFill(decl, keyType, valueType, entryKey, entryValue);
1718
+ const runner = indexRunner(config);
1719
+ checkPure(`${constructor} '${name}' entries`, entries, INDEX_PURITY);
1720
+ checkPure(`${constructor} '${name}' entries by a patch`, byPatch, INDEX_PURITY);
1721
+ checkEntryParams(constructor, name, 'entries', keyType, valueType, signatureOf(entries).inputs);
1722
+ const def = {
1723
+ kind: 'recordIndex',
1724
+ name,
1725
+ record: rec,
1726
+ // No field leads it: a nested collection is read by its row's key.
1727
+ on: Object.freeze([]),
1728
+ nested: Object.freeze({
1729
+ collections: written.collections, tile, summary, declaration: decl.declaration, lean: nestedLean(decl, keyType, valueType), byPatch, fill,
1730
+ span: nestedSpanDefinition(name, rec, decl, keyType, valueType, tile, runner),
1731
+ }),
1732
+ keyFn: entries,
1733
+ // A row gives many entries, each with its own value.
1734
+ multi: true,
1735
+ keyType: entryKey,
1736
+ valueType: entryValue,
1737
+ runner,
1738
+ };
1739
+ return def;
1740
+ }
1741
+ // ── The functions, each built the first time it is read ──────────────────────
1742
+ /**
1743
+ * A nested series index's shared East functions, each built the first time it
1744
+ * is read, with no location captured ({@link lazyBuilds}, #1466): importing
1745
+ * the SDK builds none of them.
1746
+ */
1747
+ export const NESTED_FNS = lazyBuilds({
1748
+ /** `(keys) → Path`: a node's keys as a key holds them (e3-types' `RecordNestedPathType`), folded from the last. */
1749
+ get pathOf() {
1750
+ return East.function([KeysType], RecordNestedPathType, ($, keys) => {
1751
+ const end = $.const(variant('end', null), RecordNestedPathType);
1752
+ return keys.reverse().reduce((_$, rest, key) => variant('step', { key, rest }), end);
1753
+ });
1754
+ },
1755
+ /** `(path) → keys`: a node's keys out of a key's path, from the row down — the inverse of `pathOf`. */
1756
+ get keysOf() {
1757
+ return East.function([RecordNestedPathType], KeysType, ($, path) => {
1758
+ const keys = $.let([], KeysType);
1759
+ const at = $.let(path);
1760
+ $.while(true, ($2, label) => {
1761
+ $2.match(at.unwrap(), {
1762
+ step: ($3, step) => {
1763
+ $3(keys.pushLast(step.key));
1764
+ $3.assign(at, step.rest);
1765
+ },
1766
+ end: ($3) => {
1767
+ $3.break(label);
1768
+ },
1769
+ });
1770
+ });
1771
+ return keys;
1772
+ });
1773
+ },
1774
+ /** `(shares) → Dict<tile, Totals>`: items' totals in each summary tile they touch — how many, and the milliseconds they cover. */
1775
+ get sharedTotals() {
1776
+ return East.function([ArrayType(TileShareType)], DictType(DateTimeType, RecordNestedTotalsType), (_$, shares) => shares.groupReduce((_$, share) => share.tile, ($) => $.const(NO_TOTALS, RecordNestedTotalsType), (_$, totals, share) => ({ count: totals.count.add(1n), ms: totals.ms.add(share.ms), values: totals.values })));
1777
+ },
1778
+ /**
1779
+ * `(instants, level, startOf) → Dict<tile, Totals>`: values' totals in each
1780
+ * summary tile, an instant covering none of it: how many.
1781
+ */
1782
+ get instantTotals() {
1783
+ return East.function([SetType(DateTimeType), RecordLevelType, TileStepFnType], DictType(DateTimeType, RecordNestedTotalsType), (_$, instants, level, startOf) => instants.groupReduce((_$, at) => startOf(level, at), ($) => $.const(NO_TOTALS, RecordNestedTotalsType), (_$, totals) => ({ count: totals.count.add(1n), ms: totals.ms, values: totals.values })));
1784
+ },
1785
+ /**
1786
+ * `(values, level, startOf) → Dict<tile, Totals>`: Float values' totals in
1787
+ * each summary tile — how many, and their sum, the least, the greatest and the
1788
+ * value at the latest instant, taken in key order, so every runtime adds them
1789
+ * alike.
1790
+ */
1791
+ get valueTotals() {
1792
+ return East.function([DictType(DateTimeType, FloatType), RecordLevelType, TileStepFnType], DictType(DateTimeType, RecordNestedTotalsType), (_$, values, level, startOf) => values.groupReduce((_$, _value, at) => startOf(level, at), ($) => $.const(NO_TOTALS, RecordNestedTotalsType), (_$, totals, value) => ({
1793
+ count: totals.count.add(1n),
1794
+ ms: totals.ms,
1795
+ values: some(totals.values.match({
1796
+ none: () => ({ sum: value, min: value, max: value, last: value }),
1797
+ some: (_$, was) => ({ sum: was.sum.add(value), min: East.min(was.min, value), max: East.max(was.max, value), last: value }),
1798
+ })),
1799
+ })));
1800
+ },
1801
+ /** `(Dict<DateTime, Integer>) → Dict<DateTime, Float>`: Integer values as their totals and subtotals take them. */
1802
+ get integersAsFloats() {
1803
+ return East.function([DictType(DateTimeType, IntegerType)], DictType(DateTimeType, FloatType), (_$, values) => values.map((_$, value) => value.toFloat()));
1804
+ },
1805
+ /** `(Dict<DateTime, Float>) → Dict<DateTime, Float>`: Float values as their totals and subtotals take them. */
1806
+ get floatsAsFloats() {
1807
+ return East.function([DictType(DateTimeType, FloatType)], DictType(DateTimeType, FloatType), (_$, values) => values);
1808
+ },
1809
+ /** `(keys) → Option<keys>`: the keys of the node above, within a walk of a Dict's rows; none for one of its own. */
1810
+ get keysAbove() {
1811
+ return East.function([KeysType], OptionType(KeysType), (_$, keys) => East.greater(keys.size(), 1n).ifElse(() => some(keys.slice(0n, keys.size().subtract(1n))), () => none));
1812
+ },
1813
+ /** `(tiles, level, nextOf) → Within`: a write's tiles of a level, and their span. */
1814
+ get tilesWithin() {
1815
+ return East.function([SetType(DateTimeType), RecordLevelType, TileStepFnType], WithinType, ($, tiles, level, after) => {
1816
+ const starts = $.let(tiles.toArray((_$, start) => start));
1817
+ $.if(East.equal(starts.size(), 0n), ($) => {
1818
+ $.return(variant('only', { tiles, from: EPOCH, to: EPOCH }));
1819
+ });
1820
+ return variant('only', { tiles, from: starts.get(0n), to: after(level, starts.get(starts.size().subtract(1n))) });
1821
+ });
1822
+ },
1823
+ /**
1824
+ * `(within, start, end) → Boolean`: whether an item may touch the tiles — any
1825
+ * item with a start may touch some tile; of a write's tiles, one that starts
1826
+ * before their span ends, and ends, or starts, at or after it begins. An item
1827
+ * with no start touches none.
1828
+ */
1829
+ get reaches() {
1830
+ return East.function([WithinType, OptionType(DateTimeType), OptionType(DateTimeType)], BooleanType, (_$, within, start, end) => start.match({
1831
+ none: () => false,
1832
+ some: (_$, from) => within.match({
1833
+ all: () => true,
1834
+ only: (_$, span) => East.less(from, span.to).and(() => East.greaterEqual(East.max(from, end.unwrap('some', () => from)), span.from)),
1835
+ }),
1836
+ }));
1837
+ },
1838
+ /** `(shares, within) → shares`: an item's shares of the tiles totals are worked out at. */
1839
+ get sharesWithin() {
1840
+ return East.function([ArrayType(TileShareType), WithinType], ArrayType(TileShareType), (_$, shares, within) => within.match({
1841
+ all: () => shares,
1842
+ only: (_$, span) => shares.filter((_$, share) => span.tiles.has(share.tile)),
1843
+ }));
1844
+ },
1845
+ /** `(span, level, at, startOf) → Boolean`: whether a value's instant is in one of a write's tiles. */
1846
+ get inSpan() {
1847
+ return East.function([SpanType, RecordLevelType, DateTimeType, TileStepFnType], BooleanType, (_$, span, level, at, startOf) => East.greaterEqual(at, span.from).and(() => East.less(at, span.to)).and(() => span.tiles.has(startOf(level, at))));
1848
+ },
1849
+ /** `(instants, levels, startOf, nextOf) → SubtotalTiles`: the tiles of each level some values' instants fall in. */
1850
+ get subtotalTiles() {
1851
+ return East.function([SetType(DateTimeType), ArrayType(RecordLevelType), TileStepFnType, TileStepFnType], SubtotalTilesType, ($, instants, levels, startOf, nextOf) => {
1852
+ const within = $.const(NESTED_FNS.tilesWithin);
1853
+ return variant('only', levels.toDict((_$, level) => level, (_$, level) => within(instants.toSet((_$, at) => startOf(level, at)), level, nextOf).unwrap('only')));
1854
+ });
1855
+ },
1856
+ /** `(own, level, tiles, startOf) → own`: a node's own values in the tiles of a level its subtotals are worked out at. */
1857
+ get valuesAt() {
1858
+ return East.function([DictType(DateTimeType, FloatType), RecordLevelType, SubtotalTilesType, TileStepFnType], DictType(DateTimeType, FloatType), ($, own, level, tiles, startOf) => {
1859
+ const kept = $.const(NESTED_FNS.inSpan);
1860
+ return tiles.match({
1861
+ all: () => own,
1862
+ only: (_$, spans) => own.filter((_$, _value, at) => kept(spans.get(level), level, at, startOf)),
1863
+ });
1864
+ });
1865
+ },
1866
+ /** `(own, level, startOf) → Dict<tile, Folded>`: a node's own values a tile of a level at a time, in key order. */
1867
+ get foldedTiles() {
1868
+ return East.function([DictType(DateTimeType, FloatType), RecordLevelType, TileStepFnType], DictType(DateTimeType, FoldedType), (_$, own, level, startOf) => own.groupReduce((_$, _value, at) => startOf(level, at), ($) => $.const({ sum: 0.0, n: 0n, min: 0.0, max: 0.0, last: 0.0 }, FoldedType), (_$, folded, value) => ({
1869
+ sum: folded.sum.add(value),
1870
+ n: folded.n.add(1n),
1871
+ min: East.equal(folded.n, 0n).ifElse(() => value, () => East.min(folded.min, value)),
1872
+ max: East.equal(folded.n, 0n).ifElse(() => value, () => East.max(folded.max, value)),
1873
+ last: value,
1874
+ })));
1875
+ },
1876
+ /** `(folded, rollup) → Float`: a node's own values in a tile, folded by a rollup's fold. */
1877
+ get foldedBy() {
1878
+ return East.function([FoldedType, RecordRollupType], FloatType, (_$, folded, rollup) => rollup.fold.match({
1879
+ sum: () => folded.sum,
1880
+ mean: () => folded.sum.divide(folded.n.toFloat()),
1881
+ min: () => folded.min,
1882
+ max: () => folded.max,
1883
+ last: () => folded.last,
1884
+ count: () => folded.n.toFloat(),
1885
+ }));
1886
+ },
1887
+ /**
1888
+ * `(folded, rollup) → Float`: what a node holding values draws in a tile by a
1889
+ * rollup: its values folded; under a count, one — a leaf row with a value,
1890
+ * whatever the value.
1891
+ */
1892
+ get ownDraw() {
1893
+ return East.function([FoldedType, RecordRollupType], FloatType, ($, folded, rollup) => {
1894
+ const fold = $.const(NESTED_FNS.foldedBy);
1895
+ return rollup.aggregate.match({ count: () => 1.0 }, () => fold(folded, rollup));
1896
+ });
1897
+ },
1898
+ /**
1899
+ * `(own, rollups, levels, tiles, startOf) → Dict<DrawKey, Float>`: what a
1900
+ * node holding values draws, by each rollup, at each level, in each tile its
1901
+ * values touch of those asked for.
1902
+ */
1903
+ get ownDraws() {
1904
+ return East.function([DictType(DateTimeType, FloatType), ArrayType(RecordRollupType), ArrayType(RecordLevelType), SubtotalTilesType, TileStepFnType], DictType(DrawKeyType, FloatType), ($, own, rollups, levels, at, startOf) => {
1905
+ const tiles = $.const(NESTED_FNS.foldedTiles);
1906
+ const within = $.const(NESTED_FNS.valuesAt);
1907
+ const draw = $.const(NESTED_FNS.ownDraw);
1908
+ return levels.flattenToDict((_$, level) => tiles(within(own, level, at, startOf), level, startOf).flattenToDict((_$, folded, tile) => rollups.toDict((_$, rollup) => ({ rollup, level, tile }), (_$, rollup) => draw(folded, rollup))));
1909
+ });
1910
+ },
1911
+ /**
1912
+ * `(children) → Dict<DrawKey, Float>`: what a parent draws, by each rollup, at
1913
+ * each level, in each tile one of its children draws in: what they draw there,
1914
+ * in key order, by the rollup's aggregate — their sum, mean, least or
1915
+ * greatest; under a count, their counts' sum.
1916
+ */
1917
+ get childDraws() {
1918
+ return East.function([ArrayType(ComposedType)], DictType(DrawKeyType, FloatType), ($, children) => {
1919
+ const drawn = $.let(children.flatMap((_$, child) => child.draws.toArray((_$, value, key) => ({ key, value }))));
1920
+ const gathered = $.let(drawn.groupReduce((_$, draw) => draw.key, ($) => $.const({ sum: 0.0, n: 0n, min: 0.0, max: 0.0 }, GatheredType), (_$, all, draw) => ({
1921
+ sum: all.sum.add(draw.value),
1922
+ n: all.n.add(1n),
1923
+ min: East.equal(all.n, 0n).ifElse(() => draw.value, () => East.min(all.min, draw.value)),
1924
+ max: East.equal(all.n, 0n).ifElse(() => draw.value, () => East.max(all.max, draw.value)),
1925
+ })));
1926
+ return gathered.map((_$, all, key) => key.rollup.aggregate.match({
1927
+ sum: () => all.sum,
1928
+ mean: () => all.sum.divide(all.n.toFloat()),
1929
+ min: () => all.min,
1930
+ max: () => all.max,
1931
+ count: () => all.sum,
1932
+ }));
1933
+ });
1934
+ },
1935
+ /**
1936
+ * `(node, children, rollups, levels, tiles, startOf) → Composed`: a node's
1937
+ * result, at the tiles asked for. One holding values of its own draws them,
1938
+ * and keeps no subtotal; one holding none draws its children's, and keeps what
1939
+ * it draws, where it draws, as its subtotals. Either way, it carries every
1940
+ * subtotal beneath it on to its parent.
1941
+ */
1942
+ get composed() {
1943
+ return East.function([SubtotalNodeType, ArrayType(ComposedType), ArrayType(RecordRollupType), ArrayType(RecordLevelType), SubtotalTilesType, TileStepFnType], ComposedType, ($, node, children, rollups, levels, tiles, startOf) => {
1944
+ const own = $.const(NESTED_FNS.ownDraws);
1945
+ const gathered = $.const(NESTED_FNS.childDraws);
1946
+ const path = $.const(NESTED_FNS.pathOf);
1947
+ const beneath = $.let(children.flatMap((_$, child) => child.subtotals.toArray((_$, value, key) => ({ key, value })))
1948
+ .toDict((_$, subtotal) => subtotal.key, (_$, subtotal) => subtotal.value));
1949
+ $.if(East.greater(node.own.size(), 0n), ($) => {
1950
+ $.return({ draws: own(node.own, rollups, levels, tiles, startOf), subtotals: beneath });
1951
+ });
1952
+ const draws = $.let(gathered(children));
1953
+ const here = $.let(path(node.key.path));
1954
+ $(beneath.unionInPlace(draws.toDict((_$, _value, key) => ({ path: here, rollup: key.rollup, level: key.level, tile: key.tile }), (_$, value) => value)));
1955
+ return { draws, subtotals: beneath };
1956
+ });
1957
+ },
1958
+ /**
1959
+ * `(nodes, rollups, levels, tiles, startOf) → Dict<SubtotalKey, Float>`:
1960
+ * every parent's subtotals of a collection of values at the tiles asked for,
1961
+ * composed bottom-up by `toTree` over the nodes from the row down to the
1962
+ * collection, each node's result carried to its parent. A tile no
1963
+ * descendant's value touches has none.
1964
+ */
1965
+ get subtotalsOf() {
1966
+ return East.function([ArrayType(SubtotalNodeType), ArrayType(RecordRollupType), ArrayType(RecordLevelType), SubtotalTilesType, TileStepFnType], DictType(SubtotalKeyType, FloatType), ($, nodes, rollups, levels, tiles, startOf) => {
1967
+ const compose = $.const(NESTED_FNS.composed);
1968
+ const roots = $.let(nodes.toTree(ComposedType, (_$, node) => node.key, (_$, node) => node.parent, (_$, node, _i, children) => compose(node, children, rollups, levels, tiles, startOf)));
1969
+ return roots.flatMap((_$, root) => root.subtotals.toArray((_$, value, key) => ({ key, value })))
1970
+ .toDict((_$, subtotal) => subtotal.key, (_$, subtotal) => subtotal.value);
1971
+ });
1972
+ },
1973
+ });
1974
+ //# sourceMappingURL=record-nested-programs.js.map