@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,1032 @@
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 nested series index, `index.nested` (#1434): what TypeScript checks
7
+ * of a declaration from the record's type alone; the refusals, in their
8
+ * words; a row's entries — its items filed by #1433's levels, its totals, its
9
+ * items rolled up under every ancestor, and every parent's subtotals, checked
10
+ * by hand; the lean rows the record's other indexes carry beside it; and how
11
+ * a write keeps it — by its patch where the patch can say what it touched,
12
+ * whole where it cannot, both one delta, and maintained equals rebuilt, byte
13
+ * for byte. That every runtime files a row alike is e3-core's series spec.
14
+ *
15
+ * Rows and entries are written as East prints them, and read by East's parser.
16
+ */
17
+ import { describe, it } from 'node:test';
18
+ import assert from 'node:assert/strict';
19
+ import { createHash } from 'node:crypto';
20
+ import { ArrayType, DateTimeType, DictType, East, FloatType, IRType, IntegerType, OptionType, RecursiveType, SortedMap, StringType, StructType, VariantType, compareFor, encodeBeast2For, encodeBeast2PagedFor, equalFor, isTypeEqual, parseFor, printFor, printType, variant, walkIR, } from '@elaraai/east';
21
+ import { NestedEntryKeyType, NestedEntryType, RecordNestedDeclType } from '@elaraai/e3-types';
22
+ import { record } from './record.js';
23
+ import { items, recursive, rows, values } from './record-nested.js';
24
+ import { buildMutationProgram, builtIndex, indexBuildProgram } from './record-programs.js';
25
+ import { bundleOf, functionAt } from './record-guards.js';
26
+ import { package_ } from './package.js';
27
+ import { NestedPatchedType } from './record-nested-programs.js';
28
+ import { patchTypeOf } from './record-patches.js';
29
+ import { TILE_FNS } from './record-tiles.js';
30
+ /**
31
+ * The nested series index a record like `rec` — its name and type — declares under `name`, as `e3.record` builds it;
32
+ * and the builders of the collections it files, `index.nested`'s.
33
+ */
34
+ const series = Object.assign((name, rec, spec) => record(rec.name, rec.type, { indexes: (index) => ({ [name]: index.nested(spec) }) }).indexes[name], { items, values, rows, recursive });
35
+ // ── The rows ─────────────────────────────────────────────────────────────────
36
+ const Job = StructType({
37
+ product: StringType, start: OptionType(DateTimeType), end: OptionType(DateTimeType), state: StringType, sheets: FloatType,
38
+ });
39
+ const Stop = StructType({ reason: StringType, start: DateTimeType, end: DateTimeType });
40
+ const Alarm = StructType({ code: StringType, severity: StringType, at: DateTimeType });
41
+ /** A machine: where it stands, when it was in service, and what it nests. */
42
+ const Machine = StructType({
43
+ name: StringType, site: StringType, status: StringType, x: FloatType, y: FloatType,
44
+ installed: OptionType(DateTimeType), retired: OptionType(DateTimeType),
45
+ jobs: DictType(StringType, Job), stops: DictType(StringType, Stop), alarms: DictType(StringType, Alarm),
46
+ load: DictType(DateTimeType, FloatType), output: DictType(DateTimeType, IntegerType),
47
+ });
48
+ const Machines = DictType(StringType, Machine);
49
+ /** The machines' nested series index: every collection a machine nests, filed from a week up and totalled a month at a time. */
50
+ const machinesNested = (index) => index.nested({
51
+ collections: {
52
+ jobs: index.nested.items({ from: 'start', to: 'end' }),
53
+ stops: index.nested.items({ from: 'start', to: 'end' }),
54
+ alarms: index.nested.items({ at: 'at' }),
55
+ load: index.nested.values(),
56
+ output: index.nested.values(),
57
+ },
58
+ tile: 'week',
59
+ summary: 'month',
60
+ });
61
+ /** The machines, declaring their nested series index and their patch. */
62
+ const machines = () => record('machines', Machines, {
63
+ initial: new Map(),
64
+ indexes: (index) => ({ machines_in_time: machinesNested(index) }),
65
+ mutations: (mutation) => ({ patch: mutation.patch() }),
66
+ });
67
+ const machinesInTime = (rec) => rec.indexes.machines_in_time;
68
+ /** A hall's members, each with its own load; the hall's strip is their mean. */
69
+ const Member = StructType({ name: StringType, load: DictType(DateTimeType, FloatType) });
70
+ const Hall = StructType({ name: StringType, site: StringType, members: DictType(StringType, Member) });
71
+ const Halls = DictType(StringType, Hall);
72
+ const halls = () => record('halls', Halls, {
73
+ initial: new Map(),
74
+ indexes: (index) => ({
75
+ halls_in_time: index.nested({
76
+ collections: { members: index.nested.rows({ load: index.nested.values({ rollup: 'mean' }) }) },
77
+ tile: 'day',
78
+ summary: 'month',
79
+ }),
80
+ }),
81
+ mutations: (mutation) => ({ patch: mutation.patch() }),
82
+ });
83
+ const hallsInTime = (rec) => rec.indexes.halls_in_time;
84
+ /** An assembly's parts, each holding its jobs and more parts, to any depth; a part's bands are its subtree's jobs. */
85
+ const Part = RecursiveType((self) => StructType({ name: StringType, jobs: DictType(StringType, Job), parts: DictType(StringType, self) }));
86
+ const Assembly = StructType({ name: StringType, parts: DictType(StringType, Part) });
87
+ const Assemblies = DictType(StringType, Assembly);
88
+ const assemblies = () => record('assemblies', Assemblies, {
89
+ initial: new Map(),
90
+ indexes: (index) => ({
91
+ assemblies_in_time: index.nested({
92
+ collections: {
93
+ parts: index.nested.rows({ jobs: index.nested.items({ from: 'start', to: 'end' }, { rollup: true }), parts: index.nested.recursive() }),
94
+ },
95
+ tile: 'week',
96
+ summary: 'month',
97
+ }),
98
+ }),
99
+ mutations: (mutation) => ({ patch: mutation.patch() }),
100
+ });
101
+ const assembliesInTime = (rec) => rec.indexes.assemblies_in_time;
102
+ /** A ledger's measures, each with more beneath, to any depth. */
103
+ const Measure = RecursiveType((self) => StructType({
104
+ label: StringType, readings: DictType(DateTimeType, FloatType), stock: DictType(DateTimeType, FloatType), children: DictType(StringType, self),
105
+ }));
106
+ const Ledger = StructType({ name: StringType, site: StringType, measures: DictType(StringType, Measure) });
107
+ const Ledgers = DictType(StringType, Ledger);
108
+ const ledgers = () => record('ledgers', Ledgers, {
109
+ initial: new Map(),
110
+ indexes: (index) => ({
111
+ ledgers_in_time: index.nested({
112
+ collections: {
113
+ measures: index.nested.rows({
114
+ readings: index.nested.values({ rollup: ['sum', 'mean', 'count'] }),
115
+ stock: index.nested.values({ rollup: { fold: 'last', aggregate: 'sum' } }),
116
+ children: index.nested.recursive(),
117
+ }),
118
+ },
119
+ tile: 'day',
120
+ }),
121
+ }),
122
+ mutations: (mutation) => ({ patch: mutation.patch() }),
123
+ });
124
+ const ledgersInTime = (rec) => rec.indexes.ledgers_in_time;
125
+ // ── Reading and checking East values ─────────────────────────────────────────
126
+ /** A value written as East prints one, read by East's parser. */
127
+ function parsed(type, text) {
128
+ const read = parseFor(type)(text);
129
+ if (!read.success)
130
+ throw new Error(`not a ${printType(type)}: ${read.error}`);
131
+ return read.value;
132
+ }
133
+ /** Asserts an East value equals the one expected, by its type, printing both as East does when it does not. */
134
+ function assertEast(type, actual, expected, what) {
135
+ if (equalFor(type)(actual, expected))
136
+ return;
137
+ const print = printFor(type);
138
+ assert.fail(`${what}:\n got ${print(actual)}\n expected ${print(expected)}`);
139
+ }
140
+ /** A record's key and row types. */
141
+ function entryOf(rec) {
142
+ const type = rec.type;
143
+ if (type.type !== 'Dict')
144
+ throw new Error(`a nested index's record is a Dict, not ${printType(type)}`);
145
+ return { keyType: type.key, rowType: type.value };
146
+ }
147
+ /** A row's entries, as the index's own function gives them. */
148
+ function entries(def, key, row) {
149
+ const { keyType, rowType } = entryOf(def.record);
150
+ const run = East.compile(functionAt(def.keyFn, [keyType, rowType], DictType(def.keyType, def.valueType)), []);
151
+ return run(key, row);
152
+ }
153
+ /** An entry's value, under the key written as East prints one; undefined where there is none. */
154
+ function entryAt(def, all, key) {
155
+ return all.get(parsed(def.keyType, key));
156
+ }
157
+ /** Asserts the entry under a key holds the value expected, both written as East prints them. */
158
+ function assertEntry(def, all, key, value) {
159
+ const held = entryAt(def, all, key);
160
+ assert.ok(held !== undefined, `no entry under ${key}`);
161
+ assertEast(def.valueType, held, parsed(def.valueType, value), `the entry under ${key}`);
162
+ }
163
+ // ── Rows written as East prints them ─────────────────────────────────────────
164
+ /** A job from `start` to `end`, each written as East prints an instant; no end an instant, no start not yet scheduled. */
165
+ function job(start, end, product = 'Labels') {
166
+ const when = (t) => (t === undefined ? '.none' : `.some ${t}`);
167
+ return `(product="${product}", start=${when(start)}, end=${when(end)}, state="planned", sheets=1200.0)`;
168
+ }
169
+ /** A machine holding the jobs and loads given, as East prints a Dict of them. */
170
+ function machine(jobs, load = {}, status = 'up') {
171
+ const dict = (entries) => (entries.length === 0 ? '{:}' : `{${entries.map(([k, v]) => `${k}:${v}`).join(', ')}}`);
172
+ return `(name="Press", site="North", status="${status}", x=1.0, y=2.0, installed=.none, retired=.none, ` +
173
+ `jobs=${dict(Object.entries(jobs).map(([id, text]) => [`"${id}"`, text]))}, stops={:}, alarms={:}, ` +
174
+ `load=${dict(Object.entries(load).map(([at, value]) => [at, value.toFixed(2)]))}, output={:})`;
175
+ }
176
+ /** A record's state, each row written as East prints it. */
177
+ function state(type, rows) {
178
+ const written = Object.entries(rows).map(([key, row]) => `"${key}":${row}`);
179
+ return parsed(type, written.length === 0 ? '{:}' : `{${written.join(', ')}}`);
180
+ }
181
+ // ── The declaration ──────────────────────────────────────────────────────────
182
+ describe('index.nested — its declaration', () => {
183
+ it('types its entries from the record and the declaration, and carries the declaration, its tile and its summary', () => {
184
+ const def = machinesInTime(machines());
185
+ assert.ok(isTypeEqual(def.keyType, NestedEntryKeyType(StringType)), `its key is ${printType(def.keyType)}`);
186
+ const places = VariantType({ alarms: Alarm, jobs: Job, load: FloatType, output: IntegerType, stops: Stop });
187
+ assert.ok(isTypeEqual(def.valueType, NestedEntryType(places)), `its value is ${printType(def.valueType)}`);
188
+ assert.deepEqual(def.on, []);
189
+ assert.equal(def.multi, true);
190
+ assert.equal(def.nested.tile, 'week');
191
+ assert.equal(def.nested.summary, 'month');
192
+ assertEast(RecordNestedDeclType, def.nested.declaration, parsed(RecordNestedDeclType, '{"alarms":.items (times=.at "at", rollup=false), "jobs":.items (times=.span (from="start", to="end"), rollup=false), ' +
193
+ '"load":.values (rollups=[]), "output":.values (rollups=[]), "stops":.items (times=.span (from="start", to="end"), rollup=false)}'), 'the declaration it carries');
194
+ });
195
+ it('nests the items\' variant as the declaration nests: child rows a variant of their own, a recursive field none', () => {
196
+ const def = assembliesInTime(assemblies());
197
+ assert.ok(isTypeEqual(def.valueType, NestedEntryType(VariantType({ parts: VariantType({ jobs: Job }) }))), printType(def.valueType));
198
+ assertEast(RecordNestedDeclType, def.nested.declaration, parsed(RecordNestedDeclType, '{"parts":.rows {"jobs":.items (times=.span (from="start", to="end"), rollup=true), "parts":.recursive}}'), 'the declaration it carries');
199
+ });
200
+ it('checks each builder against its field from the record\'s type alone, and refuses the same at run time in words', () => {
201
+ const rec = machines();
202
+ // @ts-expect-error — the jobs have no field 'begin'
203
+ const misnamed = () => series('t', rec, { collections: { jobs: series.items({ from: 'begin', to: 'end' }) }, tile: 'week' });
204
+ assert.throws(misnamed, /^Error: e3\.record 'machines': index\.nested 't' collections.jobs times from 'begin', which is no field of the jobs$/);
205
+ // @ts-expect-error — the alarms are keyed by an id: values() fits no such field
206
+ const alarmsAsValues = () => series('t', rec, { collections: { alarms: series.values() }, tile: 'week' });
207
+ assert.throws(alarmsAsValues, /^Error: e3\.record 'machines': index\.nested 't' collections.alarms is values\(\), and 'alarms' is keyed by \.String — values are keyed by their instant: declare it with items\(\{ from, to \}\) or items\(\{ at \}\)$/);
208
+ // @ts-expect-error — the load is keyed by its instant: items(…) fits no such field
209
+ const loadAsItems = () => series('t', rec, { collections: { load: series.items({ at: 'at' }) }, tile: 'week' });
210
+ assert.throws(loadAsItems, /^Error: e3\.record 'machines': index\.nested 't' collections.load is items\(…\), and 'load' is keyed by \.DateTime — a collection keyed by its instant holds values: declare it with values\(\)$/);
211
+ // @ts-expect-error — a machine holds no more machines
212
+ const jobsAsRecursive = () => series('t', rec, { collections: { jobs: series.recursive() }, tile: 'week' });
213
+ assert.throws(jobsAsRecursive, /^Error: e3\.record 'machines': index\.nested 't' collections.jobs is recursive\(\), and holds .+, not .+ — a recursive field holds more rows like the one listing it$/);
214
+ // @ts-expect-error — no rollup is called median
215
+ const median = () => series('t', halls(), { collections: { members: series.rows({ load: series.values({ rollup: 'median' }) }) }, tile: 'day' });
216
+ assert.throws(median, /rolls up by "median", which is no rollup/);
217
+ // @ts-expect-error — a fold names its aggregate too
218
+ const foldAlone = () => series('t', halls(), { collections: { members: series.rows({ load: series.values({ rollup: { fold: 'last' } }) }) }, tile: 'day' });
219
+ assert.throws(foldAlone, /rolls up by \{ fold: "last" \}, which is no rollup/);
220
+ // @ts-expect-error — the row has no field 'job'
221
+ const unknown = () => series('t', rec, { collections: { job: series.items({ from: 'start', to: 'end' }) }, tile: 'week' });
222
+ assert.throws(unknown, /^Error: e3\.record 'machines': index\.nested 't' collections names unknown row field 'job'$/);
223
+ });
224
+ describe('refuses, at definition time, in its words', () => {
225
+ const refused = (spec, words, rec = machines()) => assert.throws(() => series('machines_in_time', rec, spec), (error) => {
226
+ assert.ok(error instanceof Error);
227
+ assert.equal(error.message, `e3.record '${rec.name}': index.nested 'machines_in_time' ${words}`);
228
+ return true;
229
+ });
230
+ const jobs = series.items({ from: 'start', to: 'end' });
231
+ it('collections declaring none, or a field no builder made', () => {
232
+ refused({ collections: {}, tile: 'week' }, 'collections declares no collection');
233
+ refused({ collections: { jobs: { from: 'start' } }, tile: 'week' }, 'collections.jobs is no declaration — declare it with index.nested.items(times), values(), rows(collections) or recursive()');
234
+ });
235
+ it('a field that is not a Dict, or not one of the row\'s', () => {
236
+ refused({ collections: { status: jobs }, tile: 'week' }, 'collections.status is \'status\', of type .String — a collection is a Dict: Dict<String, Item> keyed by an id, or Dict<DateTime, V> keyed by its instant');
237
+ refused({ collections: { job: jobs }, tile: 'week' }, 'collections names unknown row field \'job\'');
238
+ });
239
+ it('child rows that are not structs', () => {
240
+ const Bay = StructType({ name: StringType, loads: DictType(StringType, FloatType) });
241
+ const bays = record('bays', DictType(StringType, Bay), { initial: new Map() });
242
+ assert.throws(() => series('halls_in_time', bays, { collections: { loads: series.rows({}) }, tile: 'day' }), /^Error: e3\.record 'bays': index\.nested 'halls_in_time' collections.loads is rows\(…\), and 'loads' holds \.Float — items and child rows are a Dict<String, Struct>$/);
243
+ });
244
+ it('a time of another type', () => {
245
+ refused({ collections: { jobs: series.items({ from: 'product', to: 'end' }) }, tile: 'week' }, 'collections.jobs times from \'product\', of type .String — a time is a DateTime or an Option<DateTime> field of the item');
246
+ });
247
+ it('a rollup with no parent above it, a count with a fold, and a rollup named twice', () => {
248
+ refused({ collections: { load: series.values({ rollup: 'sum' }) }, tile: 'week' }, 'collections.load rolls up, and no row of the index is a parent of its rows — a rollup is a parent\'s subtotal of its children\'s: ' +
249
+ 'declare it on a collection under rows(…) or beside recursive()');
250
+ const ledgerSpec = (rollup) => ({
251
+ collections: { measures: series.rows({ readings: series.values({ rollup }), children: series.recursive() }) }, tile: 'day',
252
+ });
253
+ assert.throws(() => series('ledgers_in_time', ledgers(), ledgerSpec({ fold: 'sum', aggregate: 'count' })), /^Error: e3\.record 'ledgers': index\.nested 'ledgers_in_time' collections.measures.readings rolls up by \{ fold: 'sum', aggregate: 'count' \} — a count counts the leaf rows with a value, whatever they fold to: write rollup: "count"$/);
254
+ assert.throws(() => series('ledgers_in_time', ledgers(), ledgerSpec(['sum', 'sum'])), /^Error: e3\.record 'ledgers': index\.nested 'ledgers_in_time' collections.measures.readings rolls up by sum twice — name each rollup once$/);
255
+ });
256
+ it('the key form, on or a value beside collections, and a tile of none of the five', () => {
257
+ const collections = { jobs };
258
+ refused({ collections, key: 'site', from: 'installed', to: 'retired', tile: 'week' }, 'takes collections, tile and summary — key, from and to file the record\'s own events: index.series({ key, from, to, tile })');
259
+ refused({ collections, on: ['site'], tile: 'week' }, 'takes no on with collections — a nested collection is read by its row\'s key, which the rail\'s indexes page');
260
+ refused({ collections, value: () => null, tile: 'week' }, 'takes no value — each entry carries its own item, totals or subtotal');
261
+ assert.throws(() => series('machines_in_time', machines(), { collections, tile: 'fortnight' }), /tile/);
262
+ });
263
+ });
264
+ });
265
+ // ── A row's entries ──────────────────────────────────────────────────────────
266
+ describe('index.nested — a row\'s entries', () => {
267
+ it('files a job once under the week its length fits, a value at its instant, and keeps their month totals', () => {
268
+ const def = machinesInTime(machines());
269
+ const row = parsed(Machine, machine({ 'j-0042': job('2026-10-02T06:00:00.000', '2026-10-06T06:00:00.000') }, { '2026-10-05T00:00:00.000': 0.82 }));
270
+ const all = entries(def, 'M-7', row);
271
+ assertEast(DictType(def.keyType, def.valueType), all, parsed(DictType(def.keyType, def.valueType), `{
272
+ (collection=.step (key="jobs", rest=.end), row="M-7", path=.end, run=.items, level=.week, tile=2026-09-28T00:00:00.000, item=.id "j-0042"):
273
+ .item .jobs ${job('2026-10-02T06:00:00.000', '2026-10-06T06:00:00.000')},
274
+ (collection=.step (key="jobs", rest=.end), row="M-7", path=.end, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none):
275
+ .totals (count=1, ms=345600000, values=.none),
276
+ (collection=.step (key="load", rest=.end), row="M-7", path=.end, run=.items, level=.week, tile=2026-10-05T00:00:00.000, item=.at 2026-10-05T00:00:00.000):
277
+ .item .load 0.82,
278
+ (collection=.step (key="load", rest=.end), row="M-7", path=.end, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none):
279
+ .totals (count=1, ms=0, values=.some (sum=0.82, min=0.82, max=0.82, last=0.82))
280
+ }`), 'M-7\'s entries');
281
+ });
282
+ it('files an item with no start nowhere, and counts it in no total', () => {
283
+ const def = machinesInTime(machines());
284
+ const all = entries(def, 'M-7', parsed(Machine, machine({ 'j-1': job(undefined) })));
285
+ assert.equal(all.size, 0, 'no entries');
286
+ });
287
+ it('files values, and items at an instant, at the declared tile alone, an instant covering none of a total', () => {
288
+ const def = machinesInTime(machines());
289
+ const row = parsed(Machine, machine({}, { '2026-10-05T00:00:00.000': 0.5, '2026-10-30T12:00:00.000': 0.75 }));
290
+ row.alarms.set('a-1', parsed(Alarm, '(code="E1", severity="high", at=2026-10-07T09:30:00.000)'));
291
+ const all = entries(def, 'M-7', row);
292
+ for (const [key] of all) {
293
+ const level = key.level.type;
294
+ assert.ok(level === 'week' || level === 'month', `filed at ${level}`);
295
+ }
296
+ assertEntry(def, all, '(collection=.step (key="alarms", rest=.end), row="M-7", path=.end, run=.items, level=.week, tile=2026-10-05T00:00:00.000, item=.id "a-1")', '.item .alarms (code="E1", severity="high", at=2026-10-07T09:30:00.000)');
297
+ assertEntry(def, all, '(collection=.step (key="alarms", rest=.end), row="M-7", path=.end, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none)', '.totals (count=1, ms=0, values=.none)');
298
+ assertEntry(def, all, '(collection=.step (key="load", rest=.end), row="M-7", path=.end, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none)', '.totals (count=2, ms=0, values=.some (sum=1.25, min=0.5, max=0.75, last=0.75))');
299
+ });
300
+ it(`refuses an item touching more than 4096 years, naming its row, its collection and its key`, () => {
301
+ const def = machinesInTime(machines());
302
+ const row = parsed(Machine, machine({ 'j-0042': job('2026-01-01T12:00:00.000', '9999-12-31T00:00:00.000') }));
303
+ assert.throws(() => entries(def, 'M-7', row), /"M-7" jobs "j-0042", from 2026-01-01T12:00:00.000 to 9999-12-31T00:00:00.000, touches more than 4096 year tiles: end it within 4096 years of its start/);
304
+ });
305
+ it('files a member\'s value under its path, and keeps the hall\'s mean of its members\' means', () => {
306
+ const def = hallsInTime(halls());
307
+ const row = parsed(Hall, `(name="Hall 1", site="North", members={
308
+ "m-3":(name="Ada", load={2026-10-05T00:00:00.000:0.82}),
309
+ "m-4":(name="Bo", load={2026-10-05T06:00:00.000:0.5, 2026-10-05T18:00:00.000:0.7})
310
+ })`);
311
+ const all = entries(def, 'H1', row);
312
+ assertEntry(def, all, '(collection=.step (key="members", rest=.step (key="load", rest=.end)), row="H1", path=.step (key="m-3", rest=.end), run=.items, level=.day, ' +
313
+ 'tile=2026-10-05T00:00:00.000, item=.at 2026-10-05T00:00:00.000)', '.item .members .load 0.82');
314
+ // Ada's 0.82 and Bo's mean of 0.5 and 0.7, 0.6, averaged.
315
+ assertEntry(def, all, '(collection=.step (key="members", rest=.step (key="load", rest=.end)), row="H1", path=.end, run=.subtotals (fold=.mean, aggregate=.mean), ' +
316
+ 'level=.week, tile=2026-10-05T00:00:00.000, item=.none)', '.subtotal 0.71');
317
+ });
318
+ it('files a part\'s job at its path five deep, and under each of its five ancestors with the path down to it', () => {
319
+ const def = assembliesInTime(assemblies());
320
+ const deepest = `(name="p5", jobs={"j-9":${job('2026-10-02T00:00:00.000', '2026-10-03T00:00:00.000')}}, parts={:})`;
321
+ const chain = ['p4', 'p3', 'p2', 'p1'].reduce((inner, name, i) => `(name="${name}", jobs={:}, parts={"${['p5', 'p4', 'p3', 'p2'][i]}":${inner}})`, deepest);
322
+ const all = entries(def, 'A-1', parsed(Assembly, `(name="Assembly 1", parts={"p1":${chain}})`));
323
+ const pathOf = (names) => names.reduceRight((rest, key) => `.step (key="${key}", rest=${rest})`, '.end');
324
+ const names = ['p1', 'p2', 'p3', 'p4', 'p5'];
325
+ const value = `.item .parts .jobs ${job('2026-10-02T00:00:00.000', '2026-10-03T00:00:00.000')}`;
326
+ const where = '(collection=.step (key="parts", rest=.step (key="jobs", rest=.end)), row="A-1"';
327
+ assertEntry(def, all, `${where}, path=${pathOf(names)}, run=.items, level=.week, tile=2026-09-28T00:00:00.000, item=.id "j-9")`, value);
328
+ for (let depth = 0; depth < names.length; depth++) {
329
+ assertEntry(def, all, `${where}, path=${pathOf(names.slice(0, depth))}, run=.subtree, level=.week, tile=2026-09-28T00:00:00.000, ` +
330
+ `item=.under (path=${pathOf(names.slice(depth))}, id="j-9"))`, value);
331
+ }
332
+ const subtree = [...all.keys()].filter((key) => key.run.type === 'subtree');
333
+ assert.equal(subtree.length, 5, 'under each of its five ancestors, and no other');
334
+ });
335
+ });
336
+ // ── Its span (#1438) ─────────────────────────────────────────────────────────
337
+ describe('index.nested — its span, beside it (#1438)', () => {
338
+ it('keeps each collection\'s months beside it, `<name>_span`, with how many items or values touch each and the milliseconds its items cover, summed across rows as a summary\'s totals are', () => {
339
+ const rec = machines();
340
+ const span = rec.indexes.machines_in_time.nested.span;
341
+ assert.equal(rec.indexes.machines_in_time_span, span, 'the span beside the nested series index');
342
+ assert.deepEqual(span.span, { of: 'machines_in_time', tile: 'month' });
343
+ assert.ok(span.mergeFn !== undefined && span.multi, 'its rows\' totals summed under each key');
344
+ // A job across a month's end counts in both months, with its milliseconds in each; a month counts every job in it,
345
+ // and every value: 42h of j-1 in September, its other 126h and j-2's 24h in October, two values in November.
346
+ const row = parsed(Machine, machine({ 'j-1': job('2026-09-29T06:00:00.000', '2026-10-06T06:00:00.000'), 'j-2': job('2026-10-12T06:00:00.000', '2026-10-13T06:00:00.000') }, { '2026-11-02T00:00:00.000': 0.5, '2026-11-09T00:00:00.000': 0.7 }));
347
+ const all = entries(span, 'M-7', row);
348
+ assertEast(DictType(span.keyType, span.valueType), all, parsed(DictType(span.keyType, span.valueType), `{
349
+ (collection=.step (key="jobs", rest=.end), tile=2026-09-01T00:00:00.000): (count=1, ms=151200000),
350
+ (collection=.step (key="jobs", rest=.end), tile=2026-10-01T00:00:00.000): (count=2, ms=540000000),
351
+ (collection=.step (key="load", rest=.end), tile=2026-11-01T00:00:00.000): (count=2, ms=0)
352
+ }`), 'M-7\'s months');
353
+ assert.equal(entries(span, 'M-7', parsed(Machine, machine({ 'j-1': job(undefined) }))).size, 0, 'an item with no start touches no month');
354
+ });
355
+ it('counts a part\'s jobs at every depth under their collection, and a member\'s values under theirs', () => {
356
+ const span = assemblies().indexes.assemblies_in_time.nested.span;
357
+ const deep = `(name="p2", jobs={"j-9":${job('2027-03-02T00:00:00.000', '2027-03-03T00:00:00.000')}}, parts={:})`;
358
+ const top = `(name="p1", jobs={"j-1":${job('2026-10-02T00:00:00.000', '2026-10-03T00:00:00.000')}}, parts={"p2":${deep}})`;
359
+ const all = entries(span, 'A-1', parsed(Assembly, `(name="Assembly 1", parts={"p1":${top}})`));
360
+ assertEast(DictType(span.keyType, span.valueType), all, parsed(DictType(span.keyType, span.valueType), `{
361
+ (collection=.step (key="parts", rest=.step (key="jobs", rest=.end)), tile=2026-10-01T00:00:00.000): (count=1, ms=86400000),
362
+ (collection=.step (key="parts", rest=.step (key="jobs", rest=.end)), tile=2027-03-01T00:00:00.000): (count=1, ms=86400000)
363
+ }`), 'the parts\' months');
364
+ const hall = halls().indexes.halls_in_time.nested.span;
365
+ const members = entries(hall, 'H-1', parsed(Hall, '(name="Hall 1", site="North", members={"a":(name="a", load={2026-01-05T00:00:00.000:0.5}), "b":(name="b", load={2026-02-02T00:00:00.000:0.5})})'));
366
+ assertEast(DictType(hall.keyType, hall.valueType), members, parsed(DictType(hall.keyType, hall.valueType), `{
367
+ (collection=.step (key="members", rest=.step (key="load", rest=.end)), tile=2026-01-01T00:00:00.000): (count=1, ms=0),
368
+ (collection=.step (key="members", rest=.step (key="load", rest=.end)), tile=2026-02-01T00:00:00.000): (count=1, ms=0)
369
+ }`), 'the members\' months');
370
+ });
371
+ it('refuses an index named as a nested series index\'s span', () => {
372
+ assert.throws(() => record('machines', Machines, {
373
+ initial: new Map(),
374
+ indexes: (index) => ({ machines_in_time: machinesNested(index), machines_in_time_span: index.on(['name']) }),
375
+ }), /an index named 'machines_in_time_span' — the name is the span the nested series index 'machines_in_time' keeps beside it/);
376
+ });
377
+ });
378
+ // ── Parents' subtotals ───────────────────────────────────────────────────────
379
+ describe('index.nested — every parent\'s subtotals, by hand', () => {
380
+ // m1 holds m11 and m12; m2 holds readings alone; m3 holds readings of its
381
+ // own, and m31, whose stock it derives.
382
+ const ledger = `(name="Ledger 1", site="North", measures={
383
+ "m1":(label="Plant", readings={:}, stock={:}, children={
384
+ "m11":(label="Press", readings={2026-10-05T00:00:00.000:2.0, 2026-10-06T00:00:00.000:4.0},
385
+ stock={2026-10-05T00:00:00.000:10.0, 2026-10-07T00:00:00.000:12.0}, children={:}),
386
+ "m12":(label="Folder", readings={2026-10-05T00:00:00.000:6.0}, stock={2026-10-06T00:00:00.000:5.0}, children={:})
387
+ }),
388
+ "m2":(label="Dock", readings={2026-10-12T00:00:00.000:1.0}, stock={:}, children={:}),
389
+ "m3":(label="Kiln", readings={2026-10-05T00:00:00.000:100.0}, stock={:}, children={
390
+ "m31":(label="Burner", readings={2026-10-05T00:00:00.000:7.0}, stock={2026-10-05T00:00:00.000:3.0}, children={:})
391
+ })
392
+ })`;
393
+ const def = ledgersInTime(ledgers());
394
+ const all = entries(def, 'L1', parsed(Ledger, ledger));
395
+ const pathOf = (names) => names.reduceRight((rest, key) => `.step (key="${key}", rest=${rest})`, '.end');
396
+ const ROLLUPS = {
397
+ sum: '(fold=.sum, aggregate=.sum)', mean: '(fold=.mean, aggregate=.mean)', count: '(fold=.count, aggregate=.count)',
398
+ last: '(fold=.last, aggregate=.sum)',
399
+ };
400
+ /** The subtotal of a collection, by a rollup, at a node, a level and a tile; undefined where there is none. */
401
+ const subtotal = (collection, rollup, path, level, tile) => entryAt(def, all, `(collection=.step (key="measures", rest=.step (key="${collection}", rest=.end)), row="L1", path=${pathOf(path)}, ` +
402
+ `run=.subtotals ${ROLLUPS[rollup]}, level=.${level}, tile=${tile}T00:00:00.000, item=.none)`);
403
+ const assertSubtotal = (got, expected, what) => assertEast(def.valueType, got, parsed(def.valueType, `.subtotal ${expected.toFixed(4)}`), what);
404
+ it('sums: a parent its children\'s sums, the ledger every top measure\'s draw', () => {
405
+ assertSubtotal(subtotal('readings', 'sum', ['m1'], 'day', '2026-10-05'), 8, 'm1 on 5 Oct: 2 + 6');
406
+ assertSubtotal(subtotal('readings', 'sum', [], 'day', '2026-10-05'), 108, 'the ledger on 5 Oct: m1\'s 8 and m3\'s own 100');
407
+ assertSubtotal(subtotal('readings', 'sum', [], 'week', '2026-10-05'), 112, 'the ledger the week of 5 Oct: m1\'s 12 and m3\'s 100');
408
+ });
409
+ it('means as a mean of means', () => {
410
+ assertSubtotal(subtotal('readings', 'mean', ['m1'], 'week', '2026-10-05'), 4.5, 'm1 the week of 5 Oct: m11\'s 3 and m12\'s 6');
411
+ assertSubtotal(subtotal('readings', 'mean', [], 'week', '2026-10-05'), 52.25, 'the ledger: m1\'s 4.5 and m3\'s 100');
412
+ });
413
+ it('counts the leaf rows beneath that draw a value, a parent child adding its own count', () => {
414
+ assertSubtotal(subtotal('readings', 'count', ['m1'], 'day', '2026-10-05'), 2, 'm1: m11 and m12');
415
+ assertSubtotal(subtotal('readings', 'count', [], 'day', '2026-10-05'), 3, 'the ledger: m1\'s two and m3, which holds its own');
416
+ });
417
+ it('sums a last fold: each child\'s latest in the tile', () => {
418
+ assertSubtotal(subtotal('stock', 'last', ['m1'], 'week', '2026-10-05'), 17, 'm1 the week of 5 Oct: m11\'s 12 on the 7th and m12\'s 5');
419
+ assertSubtotal(subtotal('stock', 'last', [], 'day', '2026-10-05'), 13, 'the ledger on 5 Oct: m1\'s 10 and m3\'s 3');
420
+ });
421
+ it('draws a node\'s own values where it holds them, while another collection of the node still derives', () => {
422
+ assert.equal(subtotal('readings', 'sum', ['m3'], 'day', '2026-10-05'), undefined, 'm3 holds its own readings, and keeps no subtotal of them');
423
+ assertSubtotal(subtotal('stock', 'last', ['m3'], 'day', '2026-10-05'), 3, 'm3 holds no stock, and derives m31\'s');
424
+ });
425
+ it('keeps none in a tile no descendant\'s value touches', () => {
426
+ assert.equal(subtotal('readings', 'sum', ['m1'], 'day', '2026-10-08'), undefined, 'm1 on 8 Oct');
427
+ assert.equal(subtotal('readings', 'sum', ['m1'], 'week', '2026-10-12'), undefined, 'm1 the week of 12 Oct');
428
+ });
429
+ it('keeps each level\'s tiles from the index\'s tile to the year', () => {
430
+ for (const [level, tile] of [['day', '2026-10-12'], ['week', '2026-10-12'], ['month', '2026-10-01'], ['quarter', '2026-10-01'], ['year', '2026-01-01']]) {
431
+ assert.ok(subtotal('readings', 'sum', [], level, tile) !== undefined, `the ledger's sum at ${level} ${tile}`);
432
+ }
433
+ assertSubtotal(subtotal('readings', 'sum', [], 'year', '2026-01-01'), 113, 'the ledger\'s year: m1\'s 12, m2\'s 1 and m3\'s own 100, not m31\'s');
434
+ });
435
+ });
436
+ // ── The lean rows ────────────────────────────────────────────────────────────
437
+ describe('index.nested — the record\'s other indexes carry its lean rows', () => {
438
+ const rec = record('machines', Machines, {
439
+ initial: new Map(),
440
+ indexes: (index) => ({
441
+ machines_in_time: machinesNested(index),
442
+ machines_by_site_status: index.on(['site', 'status']),
443
+ machines_in_service: index.interval({ from: 'installed', to: 'retired' }),
444
+ machines_on_floor: index.area({ x: 'x', y: 'y', cell: 1 }),
445
+ machines_by_site_week: index.series({ key: 'site', from: 'installed', to: 'retired', tile: 'week' }),
446
+ machines_by_name: index.on(['name'], { value: East.function([StringType, Machine], StringType, (_$, _key, row) => row.name) }),
447
+ }),
448
+ });
449
+ const { machines_in_time: nested, machines_by_site_status: plain, machines_in_service: interval, machines_on_floor: area, machines_by_site_week: keyed, machines_by_name: named, } = rec.indexes;
450
+ const assembled = package_('machines', '1.0.0', rec).records.machines;
451
+ const row = parsed(Machine, machine({ 'j-1': job('2026-10-02T06:00:00.000') }, { '2026-10-05T00:00:00.000': 0.5 })
452
+ .replace('installed=.none', 'installed=.some 2026-01-05T00:00:00.000'));
453
+ const lean = parsed(Machine, machine({}).replace('installed=.none', 'installed=.some 2026-01-05T00:00:00.000'));
454
+ it('carries the lean machine where an index carries nothing or the row: every listed collection empty', () => {
455
+ for (const declared of [plain, interval, area, keyed]) {
456
+ const built = builtIndex(assembled, assembled.indexes[declared.name]);
457
+ assert.ok(isTypeEqual(built.valueType, Machine), `${declared.name} carries ${printType(built.valueType)}`);
458
+ const carried = new Set();
459
+ const run = indexBuildProgram(Machines, built).compile([]);
460
+ run(parsed(Machines, `{"M-7":${printFor(Machine)(row)}}`), (_entry, value) => { carried.add(value); return null; });
461
+ assert.ok(carried.size > 0, `${declared.name} files the machine`);
462
+ for (const value of carried)
463
+ assertEast(Machine, value, lean, `what ${declared.name} carries`);
464
+ }
465
+ });
466
+ it('leaves an index with a value of its own, and the nested index itself, as declared', () => {
467
+ assert.equal(builtIndex(assembled, assembled.indexes[named.name]), assembled.indexes[named.name]);
468
+ assert.equal(builtIndex(assembled, assembled.indexes[nested.name]), assembled.indexes[nested.name]);
469
+ });
470
+ it('is part of its record from its declaration, whichever index is declared first: a package builds it with the record (#1435)', () => {
471
+ const held = record('machines', Machines, {
472
+ initial: new Map(),
473
+ indexes: (index) => ({ machines_by_site: index.on(['site']), machines_in_time: machinesNested(index) }),
474
+ });
475
+ assert.ok(isTypeEqual(builtIndex(held, held.indexes.machines_by_site).valueType, Machine), 'an index declared before it carries the lean machine');
476
+ const packaged = package_('machines', '1.0.0', held).records.machines;
477
+ assert.deepEqual(Object.keys(packaged.indexes).sort(), ['machines_by_site', 'machines_in_time', 'machines_in_time_span'], 'built with the record, its span beside it');
478
+ assert.ok(isTypeEqual(builtIndex(packaged, packaged.indexes.machines_by_site).valueType, Machine), 'its other index carries the lean machine');
479
+ });
480
+ });
481
+ // ── A lean row filled with entries read of it ────────────────────────────────
482
+ /** A row's lean form, as the record's other indexes carry it. */
483
+ function leanOf(def, key, row) {
484
+ const { keyType, rowType } = entryOf(def.record);
485
+ return East.compile(functionAt(def.nested.lean, [keyType, rowType], rowType), [])(key, row);
486
+ }
487
+ /** A lean row filled with entries, each `{ ik, value }`, as a reader of the index's cells fills it (#1438). */
488
+ function filled(def, key, lean, read) {
489
+ const { keyType, rowType } = entryOf(def.record);
490
+ const entry = StructType({ ik: def.keyType, value: def.valueType });
491
+ const fill = East.compile(functionAt(def.nested.fill, [keyType, rowType, ArrayType(entry)], rowType), []);
492
+ return fill(key, lean, read.map(([ik, value]) => ({ ik, value })));
493
+ }
494
+ describe('index.nested — a lean row filled with the entries read of it (#1438)', () => {
495
+ const [machinesIndex, hallsIndex, assembliesIndex, ledgersIndex] = [machinesInTime(machines()), hallsInTime(halls()), assembliesInTime(assemblies()), ledgersInTime(ledgers())];
496
+ // Past a year long: filed once a year it touches (#1433).
497
+ const PAST_A_YEAR = job('2026-06-01T00:00:00.000', '2027-08-01T00:00:00.000');
498
+ const machineRow = parsed(Machine, machine({
499
+ 'j-1': job('2026-10-02T06:00:00.000', '2026-10-02T14:00:00.000'),
500
+ 'j-2': job('2026-11-03T06:00:00.000', '2026-11-03T14:00:00.000'),
501
+ 'j-3': PAST_A_YEAR,
502
+ }, { '2026-10-05T00:00:00.000': 0.5, '2026-11-09T00:00:00.000': 0.75 }).replace('stops={:}, alarms={:}', 'stops={"s-1":(reason="Clean", start=2026-10-06T08:00:00.000, end=2026-10-06T10:00:00.000)}, ' +
503
+ 'alarms={"a-1":(code="E7", severity="high", at=2026-10-07T09:30:00.000)}').replace('output={:}', 'output={2026-10-05T00:00:00.000:40}'));
504
+ const hallRow = parsed(Hall, '(name="Hall 1", site="North", members={' +
505
+ '"m-3":(name="Ada", load={2026-10-05T00:00:00.000:0.82, 2026-11-09T00:00:00.000:0.5}), "m-4":(name="Bo", load={2026-10-05T00:00:00.000:0.6})})');
506
+ const assemblyRow = parsed(Assembly, '(name="Assembly 1", parts={"p1":(name="p1", jobs={"j-1":' +
507
+ job('2026-10-02T06:00:00.000', '2026-10-02T14:00:00.000') + '}, parts={"p1.2":(name="p1.2", jobs={"j-9":' +
508
+ job('2026-11-03T06:00:00.000', '2026-11-03T14:00:00.000') + '}, parts={:})})})');
509
+ const ledgerRow = parsed(Ledger, '(name="Ledger 1", site="North", measures={"m1":(label="M1", readings={:}, stock={:}, children={' +
510
+ '"m1.1":(label="M1.1", readings={2026-10-05T00:00:00.000:3.0, 2026-10-12T00:00:00.000:4.0}, stock={2026-10-05T00:00:00.000:10.0}, children={:}), ' +
511
+ '"m1.2":(label="M1.2", readings={2026-10-05T00:00:00.000:5.0}, stock={:}, children={:})})})');
512
+ it('is the row, filled with every entry it files: items, values, child rows and a tree, an item filed in two tiles once', () => {
513
+ const cases = [
514
+ [machinesIndex, Machine, machineRow], [hallsIndex, Hall, hallRow], [assembliesIndex, Assembly, assemblyRow], [ledgersIndex, Ledger, ledgerRow],
515
+ ];
516
+ for (const [def, rowType, row] of cases) {
517
+ const all = entries(def, 'R-1', row);
518
+ assertEast(rowType, filled(def, 'R-1', leanOf(def, 'R-1', row), [...all]), row, `${def.name}: the row filled whole`);
519
+ }
520
+ // The job past a year long is filed in 2026's year tile and 2027's, and comes back once.
521
+ const machineEntries = [...entries(machinesIndex, 'R-1', machineRow).keys()]
522
+ .filter((ik) => printFor(machinesIndex.keyType)(ik).includes('item=.id "j-3"'));
523
+ assert.equal(machineEntries.length, 2, 'filed twice');
524
+ });
525
+ it('holds only the items read, filled with some cells\' entries', () => {
526
+ const def = machinesIndex;
527
+ const print = printFor(def.keyType);
528
+ // October's week tiles: j-1, the stop, the alarm, and each value of the week of October 5th.
529
+ const october = [...entries(def, 'R-1', machineRow)].filter(([ik]) => /level=\.week, tile=2026-(09-28|10-)/.test(print(ik)));
530
+ const expected = parsed(Machine, machine({ 'j-1': job('2026-10-02T06:00:00.000', '2026-10-02T14:00:00.000') }, { '2026-10-05T00:00:00.000': 0.5 })
531
+ .replace('stops={:}, alarms={:}', 'stops={"s-1":(reason="Clean", start=2026-10-06T08:00:00.000, end=2026-10-06T10:00:00.000)}, ' +
532
+ 'alarms={"a-1":(code="E7", severity="high", at=2026-10-07T09:30:00.000)}').replace('output={:}', 'output={2026-10-05T00:00:00.000:40}'));
533
+ assertEast(Machine, filled(def, 'R-1', leanOf(def, 'R-1', machineRow), october), expected, 'the October weeks read');
534
+ });
535
+ it('fills nothing from a total or a subtotal', () => {
536
+ for (const [def, row] of [[assembliesIndex, assemblyRow], [hallsIndex, hallRow]]) {
537
+ const print = printFor(def.keyType);
538
+ const others = [...entries(def, 'R-1', row)].filter(([ik]) => !/run=\.(items|subtree),/.test(print(ik)));
539
+ assert.ok(others.length > 0, `${def.name} files totals or subtotals`);
540
+ const lean = leanOf(def, 'R-1', row);
541
+ assertEast(entryOf(def.record).rowType, filled(def, 'R-1', lean, others), lean, `${def.name}: the lean row as it was`);
542
+ }
543
+ });
544
+ it('puts an item filed under a parent back in the node holding it, once beside its own entry', () => {
545
+ const def = assembliesIndex;
546
+ const print = printFor(def.keyType);
547
+ const all = [...entries(def, 'R-1', assemblyRow)];
548
+ const under = all.filter(([ik]) => /run=\.subtree,/.test(print(ik)));
549
+ // Every part's jobs are filed under the row: filled with them alone, every part holds its own.
550
+ assert.ok(under.length > 0, 'the assembly files its parts\' jobs under their parents');
551
+ const lean = leanOf(def, 'R-1', assemblyRow);
552
+ assertEast(Assembly, filled(def, 'R-1', lean, under), assemblyRow, 'every part holding its own jobs');
553
+ // Under p1 alone: p1.2's job in p1.2, and none of p1's own, which is filed under the row.
554
+ const p1 = under.filter(([ik]) => /path=\.step \(key="p1", rest=\.end\), run=/.test(print(ik)));
555
+ assertEast(Assembly, filled(def, 'R-1', lean, p1), parsed(Assembly, '(name="Assembly 1", parts={"p1":(name="p1", jobs={:}, parts={' +
556
+ '"p1.2":(name="p1.2", jobs={"j-9":' + job('2026-11-03T06:00:00.000', '2026-11-03T14:00:00.000') + '}, parts={:})})})'), 'p1\'s descendants\' jobs');
557
+ // Beside each job's own entry, each job once.
558
+ assertEast(Assembly, filled(def, 'R-1', lean, all), assemblyRow, 'the row, each job once');
559
+ });
560
+ });
561
+ // ── Through a write and a rebuild ────────────────────────────────────────────
562
+ /** The `[entry, value]` pairs an index's build program emits for a state. */
563
+ function emitted(def, recordType, rows) {
564
+ const out = [];
565
+ const run = indexBuildProgram(recordType, def).compile([]);
566
+ run(rows, (entry, value) => {
567
+ out.push([entry, value]);
568
+ return null;
569
+ });
570
+ return out;
571
+ }
572
+ /** The delta a patch's program emits for a write of a patch to a state: each entry's target, its key there and its op. */
573
+ function written(rec, mut, before, patch) {
574
+ const changes = [];
575
+ const run = buildMutationProgram(rec, mut).compile([]);
576
+ run(before, patch, (key, op) => {
577
+ changes.push({ target: key.type, key: key.value, op: op.value });
578
+ return null;
579
+ });
580
+ return changes;
581
+ }
582
+ /** The patch from one state to another, as a client's diff makes it: each row it updates by the row's own patch. */
583
+ function diffOf(rec, before, after) {
584
+ return East.compile(East.patchesFor(rec.type).diff, [])(before, after);
585
+ }
586
+ /**
587
+ * The same write with each row it updates replaced whole: the patch's `update`
588
+ * of a row a `replace` of it, before and after, which the index can only
589
+ * compare whole.
590
+ */
591
+ function replacingRows(rec, before, after) {
592
+ const patch = diffOf(rec, before, after);
593
+ if (patch.type !== 'patch')
594
+ return patch;
595
+ const { keyType } = entryOf(rec);
596
+ const held = before;
597
+ const next = after;
598
+ const ops = [...patch.value].map(([key, op]) => [key, op.type === 'update' ? variant('update', variant('replace', { before: held.get(key), after: next.get(key) })) : op]);
599
+ return variant('patch', new SortedMap(ops, compareFor(keyType)));
600
+ }
601
+ /**
602
+ * Asserts a write keeps an index as a rebuild builds it: the write's ops for
603
+ * the index, applied to its entries before, are its entries after, byte for
604
+ * byte as e3 stores them; and the same write with each row it updates
605
+ * replaced whole, which the index compares whole, gives the same ops — and
606
+ * returns the ops.
607
+ */
608
+ function maintainedIsRebuilt(rec, index, before, after, what) {
609
+ const patch = rec.mutations.patch;
610
+ if (patch === undefined)
611
+ throw new Error(`record '${rec.name}' declares no patch for a write to go through`);
612
+ const assembled = package_('nested', '1.0.0', rec).records[rec.name];
613
+ const { keyType } = entryOf(rec);
614
+ const entryKey = StructType({ ik: index.keyType, k: keyType });
615
+ const collection = DictType(entryKey, index.valueType);
616
+ const opsType = patchTypeOf(collection);
617
+ if (opsType.type !== 'Variant')
618
+ throw new Error(`a Dict's patch is a variant, not ${printType(opsType)}`);
619
+ const deltaType = opsType.cases.patch;
620
+ const opsOf = (sent) => new SortedMap(written(assembled, patch, before, sent)
621
+ .filter((change) => change.target === index.name).map((change) => [change.key, change.op]), compareFor(entryKey));
622
+ const held = new SortedMap(emitted(index, rec.type, before), compareFor(entryKey));
623
+ const rebuilt = new SortedMap(emitted(index, rec.type, after), compareFor(entryKey));
624
+ const ops = opsOf(diffOf(rec, before, after));
625
+ const apply = East.compile(East.patchesFor(collection).apply, []);
626
+ const maintained = apply(held, variant('patch', ops));
627
+ assert.deepEqual(encodeBeast2PagedFor(collection)(maintained), encodeBeast2PagedFor(collection)(rebuilt), `${what}: maintained is rebuilt`);
628
+ const print = printFor(deltaType);
629
+ assert.equal(print(opsOf(replacingRows(rec, before, after))), print(ops), `${what}: by the patch, the delta compared whole`);
630
+ return ops;
631
+ }
632
+ /** The ops of a write by their kind, each entry's run and level as East prints them, to compare as a table. */
633
+ function opsTable(ops) {
634
+ const words = [];
635
+ for (const [key, op] of ops) {
636
+ const ik = key.ik;
637
+ words.push(`${op.type} ${ik.run.type} ${ik.level.type}`);
638
+ }
639
+ return words.sort();
640
+ }
641
+ /** The ops of a write as {@link opsTable} gives them, each led by its row's key as East prints it. */
642
+ function rowOpsTable(ops) {
643
+ const words = [];
644
+ for (const [key, op] of ops) {
645
+ const entry = key;
646
+ words.push(`${printFor(StringType)(entry.k)} ${op.type} ${entry.ik.run.type} ${entry.ik.level.type}`);
647
+ }
648
+ return words.sort();
649
+ }
650
+ describe('index.nested — through a write and a rebuild', () => {
651
+ const OCT_2 = '2026-10-02T06:00:00.000';
652
+ const OCT_2_NIGHT = '2026-10-02T14:00:00.000';
653
+ it('a job moved within its tile: an update of its entry, and its month total unchanged', () => {
654
+ const rec = machines();
655
+ const index = machinesInTime(rec);
656
+ const before = state(Machines, { 'M-7': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT) }) });
657
+ const after = state(Machines, { 'M-7': machine({ 'j-1': job('2026-10-03T06:00:00.000', '2026-10-03T14:00:00.000') }) });
658
+ assert.deepEqual(opsTable(maintainedIsRebuilt(rec, index, before, after, 'moved within its week')), ['update items week']);
659
+ });
660
+ it('a job moved to the next week: a delete and an insert, and October\'s total unchanged', () => {
661
+ const rec = machines();
662
+ const index = machinesInTime(rec);
663
+ const before = state(Machines, { 'M-7': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT) }) });
664
+ const after = state(Machines, { 'M-7': machine({ 'j-1': job('2026-10-09T06:00:00.000', '2026-10-09T14:00:00.000') }) });
665
+ assert.deepEqual(opsTable(maintainedIsRebuilt(rec, index, before, after, 'moved a week on')), ['delete items week', 'insert items week']);
666
+ });
667
+ it('a job moved into November: its entries moved, and October\'s total and November\'s changed', () => {
668
+ const rec = machines();
669
+ const index = machinesInTime(rec);
670
+ const before = state(Machines, { 'M-7': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT) }) });
671
+ const after = state(Machines, { 'M-7': machine({ 'j-1': job('2026-11-03T06:00:00.000', '2026-11-03T14:00:00.000') }) });
672
+ assert.deepEqual(opsTable(maintainedIsRebuilt(rec, index, before, after, 'moved into November')), ['delete items week', 'delete totals month', 'insert items week', 'insert totals month']);
673
+ });
674
+ it('a job stretched from 8 hours to 40 days: its week entry deleted, a quarter entry inserted, each month it touches totalled', () => {
675
+ const rec = machines();
676
+ const index = machinesInTime(rec);
677
+ const before = state(Machines, { 'M-7': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT) }) });
678
+ const after = state(Machines, { 'M-7': machine({ 'j-1': job(OCT_2, '2026-11-11T06:00:00.000') }) });
679
+ assert.deepEqual(opsTable(maintainedIsRebuilt(rec, index, before, after, 'stretched to 40 days')), ['delete items week', 'insert items quarter', 'insert totals month', 'update totals month']);
680
+ });
681
+ it('a job moved from M-7 to M-9: M-7\'s entries deleted and its total updated, M-9\'s inserted', () => {
682
+ const rec = machines();
683
+ const index = machinesInTime(rec);
684
+ const other = { 'j-2': job('2026-10-12T06:00:00.000', '2026-10-14T06:00:00.000') };
685
+ const before = state(Machines, { 'M-7': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT), ...other }), 'M-9': machine({}) });
686
+ const after = state(Machines, { 'M-7': machine(other), 'M-9': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT) }) });
687
+ assert.deepEqual(rowOpsTable(maintainedIsRebuilt(rec, index, before, after, 'moved to another machine')), ['"M-7" delete items week', '"M-7" update totals month', '"M-9" insert items week', '"M-9" insert totals month']);
688
+ });
689
+ it('a day\'s load changed: its entry and its month\'s total updated', () => {
690
+ const rec = machines();
691
+ const index = machinesInTime(rec);
692
+ const jobs = { 'j-1': job(OCT_2, OCT_2_NIGHT) };
693
+ const before = state(Machines, { 'M-7': machine(jobs, { '2026-10-05T00:00:00.000': 0.82, '2026-10-06T00:00:00.000': 0.5 }) });
694
+ const after = state(Machines, { 'M-7': machine(jobs, { '2026-10-05T00:00:00.000': 0.9, '2026-10-06T00:00:00.000': 0.5 }) });
695
+ assert.deepEqual(opsTable(maintainedIsRebuilt(rec, index, before, after, 'a load changed')), ['update items week', 'update totals month']);
696
+ });
697
+ it('a machine deleted: every entry of its deleted', () => {
698
+ const rec = machines();
699
+ const index = machinesInTime(rec);
700
+ const kept = machine({ 'j-5': job('2026-09-01T00:00:00.000', '2026-09-30T00:00:00.000') });
701
+ const before = state(Machines, { 'M-7': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT) }, { '2026-10-05T00:00:00.000': 0.82 }), 'M-8': kept });
702
+ const ops = maintainedIsRebuilt(rec, index, before, state(Machines, { 'M-8': kept }), 'a machine deleted');
703
+ assert.deepEqual(rowOpsTable(ops), ['"M-7" delete items week', '"M-7" delete items week', '"M-7" delete totals month', '"M-7" delete totals month']);
704
+ });
705
+ it('a job moved to another machine, one inserted and one deleted, a day\'s load changed, a machine replaced and one deleted', () => {
706
+ const rec = machines();
707
+ const index = machinesInTime(rec);
708
+ const before = state(Machines, {
709
+ 'M-7': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT), 'j-2': job('2026-10-12T06:00:00.000', '2026-10-14T06:00:00.000') }, { '2026-10-05T00:00:00.000': 0.82 }),
710
+ 'M-8': machine({ 'j-5': job('2026-09-01T00:00:00.000', '2026-09-30T00:00:00.000') }),
711
+ 'M-9': machine({}),
712
+ });
713
+ const after = state(Machines, {
714
+ 'M-7': machine({ 'j-3': job('2026-10-20T06:00:00.000') }, { '2026-10-05T00:00:00.000': 0.9 }),
715
+ 'M-9': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT) }, { '2026-12-01T00:00:00.000': 0.4 }, 'down'),
716
+ });
717
+ maintainedIsRebuilt(rec, index, before, after, 'moved, inserted, deleted, changed, replaced');
718
+ });
719
+ it('a machine\'s status changed: nothing here', () => {
720
+ const rec = machines();
721
+ const index = machinesInTime(rec);
722
+ const jobs = { 'j-1': job(OCT_2, OCT_2_NIGHT) };
723
+ const ops = maintainedIsRebuilt(rec, index, state(Machines, { 'M-7': machine(jobs) }), state(Machines, { 'M-7': machine(jobs, {}, 'down') }), 'status');
724
+ assert.equal(ops.size, 0, 'no entry changes');
725
+ });
726
+ it('a member\'s load changed, a member added and one removed: the entries, the totals and the hall\'s means', () => {
727
+ const rec = halls();
728
+ const index = hallsInTime(rec);
729
+ const hall = (members) => `(name="Hall 1", site="North", members={${members}})`;
730
+ const before = state(Halls, { H1: hall('"m-3":(name="Ada", load={2026-10-05T00:00:00.000:0.82}), "m-4":(name="Bo", load={2026-10-05T00:00:00.000:0.6})') });
731
+ const changed = state(Halls, { H1: hall('"m-3":(name="Ada", load={2026-10-05T00:00:00.000:0.7}), "m-4":(name="Bo", load={2026-10-05T00:00:00.000:0.6})') });
732
+ const moved = state(Halls, { H1: hall('"m-3":(name="Ada", load={2026-10-05T00:00:00.000:0.7}), "m-9":(name="Cy", load={2026-11-05T00:00:00.000:0.2})') });
733
+ const ops = maintainedIsRebuilt(rec, index, before, changed, 'a load changed');
734
+ assert.deepEqual(opsTable(ops), ['update items day', 'update subtotals day', 'update subtotals month', 'update subtotals quarter',
735
+ 'update subtotals week', 'update subtotals year', 'update totals month']);
736
+ maintainedIsRebuilt(rec, index, changed, moved, 'a member added and one removed');
737
+ });
738
+ it('a member added to a hall: its load\'s entries inserted under it, and the hall\'s subtotals where its load touches', () => {
739
+ const rec = halls();
740
+ const index = hallsInTime(rec);
741
+ const members = '"m-3":(name="Ada", load={2026-10-05T00:00:00.000:0.7}), "m-4":(name="Bo", load={2026-10-05T00:00:00.000:0.6})';
742
+ const before = state(Halls, { H1: `(name="Hall 1", site="North", members={${members}})` });
743
+ const after = state(Halls, { H1: `(name="Hall 1", site="North", members={${members}, "m-9":(name="Cy", load={2026-11-05T00:00:00.000:0.2})})` });
744
+ assert.deepEqual(opsTable(maintainedIsRebuilt(rec, index, before, after, 'a member added')), ['insert items day', 'insert subtotals day',
745
+ 'insert subtotals month', 'insert subtotals week', 'insert totals month', 'update subtotals quarter', 'update subtotals year']);
746
+ });
747
+ it('a part\'s job moved, rolled up: its entries under it, and under its ancestors in the subtree run, moved; the months it left and joined totalled', () => {
748
+ const rec = assemblies();
749
+ const index = assembliesInTime(rec);
750
+ const assembly = (start, end) => `(name="Assembly 1", parts={"p1":(name="p1", jobs={:}, parts={"p1.2":(name="p1.2", jobs={"j-9":${job(start, end)}}, parts={:})})})`;
751
+ const before = state(Assemblies, { 'A-1': assembly(OCT_2, OCT_2_NIGHT) });
752
+ const after = state(Assemblies, { 'A-1': assembly('2026-11-03T06:00:00.000', '2026-11-03T14:00:00.000') });
753
+ assert.deepEqual(opsTable(maintainedIsRebuilt(rec, index, before, after, 'a part\'s job moved')), [
754
+ 'delete items week', 'delete subtree week', 'delete subtree week', 'delete subtreeTotals month', 'delete subtreeTotals month', 'delete totals month',
755
+ 'insert items week', 'insert subtree week', 'insert subtree week', 'insert subtreeTotals month', 'insert subtreeTotals month', 'insert totals month',
756
+ ]);
757
+ });
758
+ it('a part\'s job moved, rolled up, and a part added and one removed: under every ancestor too', () => {
759
+ const rec = assemblies();
760
+ const index = assembliesInTime(rec);
761
+ const assembly = (jobs, extra = '') => `(name="Assembly 1", parts={"p1":(name="p1", jobs={:}, parts={"p1.2":(name="p1.2", jobs={${jobs}}, parts={:})${extra}})})`;
762
+ const before = state(Assemblies, { 'A-1': assembly(`"j-9":${job(OCT_2, OCT_2_NIGHT)}`) });
763
+ const moved = state(Assemblies, { 'A-1': assembly(`"j-9":${job('2026-11-03T06:00:00.000', '2026-11-03T14:00:00.000')}`) });
764
+ const grown = state(Assemblies, {
765
+ 'A-1': `(name="Assembly 1", parts={"p2":(name="p2", jobs={"j-1":${job(OCT_2)}}, parts={:})})`,
766
+ });
767
+ maintainedIsRebuilt(rec, index, before, moved, 'a part\'s job moved');
768
+ maintainedIsRebuilt(rec, index, moved, grown, 'a part added and one removed');
769
+ });
770
+ it('a leaf measure\'s reading changed, added and removed, and a measure added beneath another', () => {
771
+ const rec = ledgers();
772
+ const index = ledgersInTime(rec);
773
+ const measure = (label, readings, children = '') => `(label="${label}", readings={${readings === '' ? ':' : readings}}, stock={:}, children={${children === '' ? ':' : children}})`;
774
+ const ledger = (m11, more = '') => `(name="Ledger 1", site="North", measures={"m1":${measure('Plant', '', `"m11":${m11}${more}`)}})`;
775
+ const before = state(Ledgers, { L1: ledger(measure('Press', '2026-10-05T00:00:00.000:2.0')) });
776
+ const changed = state(Ledgers, { L1: ledger(measure('Press', '2026-10-05T00:00:00.000:3.0, 2026-10-06T00:00:00.000:1.0')) });
777
+ const removed = state(Ledgers, { L1: ledger(measure('Press', '2026-10-06T00:00:00.000:1.0')) });
778
+ const deeper = state(Ledgers, { L1: ledger(measure('Press', '2026-10-06T00:00:00.000:1.0'), `, "m12":${measure('Folder', '', `"m121":${measure('Belt', '2026-10-07T00:00:00.000:5.0')}`)}`) });
779
+ maintainedIsRebuilt(rec, index, before, changed, 'a reading changed and one added');
780
+ maintainedIsRebuilt(rec, index, changed, removed, 'a reading removed');
781
+ maintainedIsRebuilt(rec, index, removed, deeper, 'a measure added beneath another');
782
+ });
783
+ it('a collection replaced whole, and every row inserted from none and deleted to none', () => {
784
+ const rec = machines();
785
+ const index = machinesInTime(rec);
786
+ const one = state(Machines, { 'M-7': machine({ 'j-1': job(OCT_2, OCT_2_NIGHT), 'j-2': job('2026-10-12T06:00:00.000') }) });
787
+ const other = state(Machines, { 'M-7': machine({ 'j-8': job('2026-12-12T06:00:00.000'), 'j-9': job('2027-01-12T06:00:00.000') }) });
788
+ maintainedIsRebuilt(rec, index, one, other, 'the jobs replaced');
789
+ maintainedIsRebuilt(rec, index, state(Machines, {}), one, 'inserted from none');
790
+ maintainedIsRebuilt(rec, index, one, state(Machines, {}), 'deleted to none');
791
+ });
792
+ });
793
+ // ── A write by its patch ─────────────────────────────────────────────────────
794
+ /**
795
+ * What an index's write by its patch makes of a row: `whole` where it cannot
796
+ * say what the patch touched, or the entries it compares, before and after.
797
+ */
798
+ function byPatch(index, key, held, next, patch) {
799
+ const { keyType, rowType } = entryOf(index.record);
800
+ const nested = index.nested;
801
+ if (nested === undefined)
802
+ throw new Error(`'${index.name}' is no nested series index`);
803
+ const entriesType = DictType(index.keyType, index.valueType);
804
+ const run = East.compile(functionAt(nested.byPatch, [keyType, rowType, rowType, patchTypeOf(rowType)], NestedPatchedType(entriesType)), []);
805
+ const sent = patch ?? East.compile(East.patchesFor(rowType).diff, [])(held, next);
806
+ return run(key, held, next, sent);
807
+ }
808
+ /** Asserts a write by its patch compared the entries expected, before and after, each Dict written as East prints one. */
809
+ function assertCompared(index, compared, before, after) {
810
+ assert.equal(compared.type, 'changed', 'by the patch');
811
+ const both = compared.value;
812
+ const entriesType = DictType(index.keyType, index.valueType);
813
+ assertEast(entriesType, both.before, parsed(entriesType, before), 'the entries before');
814
+ assertEast(entriesType, both.after, parsed(entriesType, after), 'the entries after');
815
+ }
816
+ describe('index.nested — a write by its patch', () => {
817
+ const OCT_2 = '2026-10-02T06:00:00.000';
818
+ const OCT_2_NIGHT = '2026-10-02T14:00:00.000';
819
+ const NOV_3 = '2026-11-03T06:00:00.000';
820
+ const NOV_3_NIGHT = '2026-11-03T14:00:00.000';
821
+ it('compares only the items the patch names, and the totals of the tiles they touch', () => {
822
+ const index = machinesInTime(machines());
823
+ const others = { 'j-2': job('2026-10-12T06:00:00.000'), 'j-3': job('2026-12-01T06:00:00.000') };
824
+ const load = { '2026-10-05T00:00:00.000': 0.82 };
825
+ const held = parsed(Machine, machine({ 'j-1': job(OCT_2, OCT_2_NIGHT), ...others }, load));
826
+ const next = parsed(Machine, machine({ 'j-1': job(NOV_3, NOV_3_NIGHT), ...others }, load));
827
+ assertCompared(index, byPatch(index, 'M-7', held, next), `{
828
+ (collection=.step (key="jobs", rest=.end), row="M-7", path=.end, run=.items, level=.week, tile=2026-09-28T00:00:00.000, item=.id "j-1"):
829
+ .item .jobs ${job(OCT_2, OCT_2_NIGHT)},
830
+ (collection=.step (key="jobs", rest=.end), row="M-7", path=.end, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none):
831
+ .totals (count=2, ms=28800000, values=.none)
832
+ }`, `{
833
+ (collection=.step (key="jobs", rest=.end), row="M-7", path=.end, run=.items, level=.week, tile=2026-11-02T00:00:00.000, item=.id "j-1"):
834
+ .item .jobs ${job(NOV_3, NOV_3_NIGHT)},
835
+ (collection=.step (key="jobs", rest=.end), row="M-7", path=.end, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none):
836
+ .totals (count=1, ms=0, values=.none),
837
+ (collection=.step (key="jobs", rest=.end), row="M-7", path=.end, run=.totals, level=.month, tile=2026-11-01T00:00:00.000, item=.none):
838
+ .totals (count=1, ms=28800000, values=.none)
839
+ }`);
840
+ });
841
+ it('compares a member\'s value, its members\' totals of its month and its hall\'s subtotals, and no other member\'s value', () => {
842
+ const index = hallsInTime(halls());
843
+ const hall = (load) => parsed(Hall, `(name="Hall 1", site="North", members={"m-3":(name="Ada", load={2026-10-05T00:00:00.000:${load}}), "m-4":(name="Bo", load={2026-10-05T00:00:00.000:0.6})})`);
844
+ const member = '(collection=.step (key="members", rest=.step (key="load", rest=.end)), row="H1", path=.step (key="m-3", rest=.end)';
845
+ const other = '(collection=.step (key="members", rest=.step (key="load", rest=.end)), row="H1", path=.step (key="m-4", rest=.end)';
846
+ const parent = '(collection=.step (key="members", rest=.step (key="load", rest=.end)), row="H1", path=.end, run=.subtotals (fold=.mean, aggregate=.mean)';
847
+ const entries = (load) => `{
848
+ ${member}, run=.items, level=.day, tile=2026-10-05T00:00:00.000, item=.at 2026-10-05T00:00:00.000): .item .members .load ${load},
849
+ ${member}, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none):
850
+ .totals (count=1, ms=0, values=.some (sum=${load}, min=${load}, max=${load}, last=${load})),
851
+ ${other}, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none):
852
+ .totals (count=1, ms=0, values=.some (sum=0.6, min=0.6, max=0.6, last=0.6)),
853
+ ${parent}, level=.day, tile=2026-10-05T00:00:00.000, item=.none): .subtotal ${(load + 0.6) / 2},
854
+ ${parent}, level=.week, tile=2026-10-05T00:00:00.000, item=.none): .subtotal ${(load + 0.6) / 2},
855
+ ${parent}, level=.month, tile=2026-10-01T00:00:00.000, item=.none): .subtotal ${(load + 0.6) / 2},
856
+ ${parent}, level=.quarter, tile=2026-10-01T00:00:00.000, item=.none): .subtotal ${(load + 0.6) / 2},
857
+ ${parent}, level=.year, tile=2026-01-01T00:00:00.000, item=.none): .subtotal ${(load + 0.6) / 2}
858
+ }`;
859
+ assertCompared(index, byPatch(index, 'H1', hall('0.82'), hall('0.7')), entries(0.82), entries(0.7));
860
+ });
861
+ it('compares its hall\'s subtotals only at the tiles of each level the member\'s value is in, never another month\'s', () => {
862
+ const index = hallsInTime(halls());
863
+ const OCT_5 = '2026-10-05T00:00:00.000';
864
+ const NOV_9 = '2026-11-09T00:00:00.000';
865
+ const hall = (load) => parsed(Hall, `(name="Hall 1", site="North", members={` +
866
+ `"m-3":(name="Ada", load={${OCT_5}:${load}, ${NOV_9}:0.5}), "m-4":(name="Bo", load={${OCT_5}:0.6, ${NOV_9}:0.4})})`);
867
+ const member = '(collection=.step (key="members", rest=.step (key="load", rest=.end)), row="H1", path=.step (key="m-3", rest=.end)';
868
+ const other = '(collection=.step (key="members", rest=.step (key="load", rest=.end)), row="H1", path=.step (key="m-4", rest=.end)';
869
+ const parent = '(collection=.step (key="members", rest=.step (key="load", rest=.end)), row="H1", path=.end, run=.subtotals (fold=.mean, aggregate=.mean)';
870
+ // October 5's day, week and month hold the two members' values that day; its quarter and its year hold November's too.
871
+ const entries = (load) => `{
872
+ ${member}, run=.items, level=.day, tile=${OCT_5}, item=.at ${OCT_5}): .item .members .load ${load},
873
+ ${member}, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none):
874
+ .totals (count=1, ms=0, values=.some (sum=${load}, min=${load}, max=${load}, last=${load})),
875
+ ${other}, run=.totals, level=.month, tile=2026-10-01T00:00:00.000, item=.none):
876
+ .totals (count=1, ms=0, values=.some (sum=0.6, min=0.6, max=0.6, last=0.6)),
877
+ ${parent}, level=.day, tile=${OCT_5}, item=.none): .subtotal ${(load + 0.6) / 2},
878
+ ${parent}, level=.week, tile=${OCT_5}, item=.none): .subtotal ${(load + 0.6) / 2},
879
+ ${parent}, level=.month, tile=2026-10-01T00:00:00.000, item=.none): .subtotal ${(load + 0.6) / 2},
880
+ ${parent}, level=.quarter, tile=2026-10-01T00:00:00.000, item=.none): .subtotal ${((load + 0.5) / 2 + 0.5) / 2},
881
+ ${parent}, level=.year, tile=2026-01-01T00:00:00.000, item=.none): .subtotal ${((load + 0.5) / 2 + 0.5) / 2}
882
+ }`;
883
+ assertCompared(index, byPatch(index, 'H1', hall('0.82'), hall('0.7')), entries(0.82), entries(0.7));
884
+ });
885
+ it('compares a child row inserted whole, beside what else its patch names', () => {
886
+ const index = assembliesInTime(assemblies());
887
+ const held = parsed(Assembly, `(name="Assembly 1", parts={"p1":(name="p1", jobs={"j-1":${job(OCT_2, OCT_2_NIGHT)}}, parts={:})})`);
888
+ const next = parsed(Assembly, `(name="Assembly 1", parts={"p1":(name="p1", jobs={"j-1":${job(OCT_2, OCT_2_NIGHT)}}, parts={:}), ` +
889
+ `"p2":(name="p2", jobs={:}, parts={"p2.1":(name="p2.1", jobs={"j-7":${job(NOV_3, NOV_3_NIGHT)}}, parts={:})})})`);
890
+ const compared = byPatch(index, 'A-1', held, next);
891
+ assert.equal(compared.type, 'changed', 'by the patch');
892
+ const both = compared.value;
893
+ const jobsOf = (all) => [...all.keys()].flatMap((key) => {
894
+ const item = key.item;
895
+ return item.type === 'none' ? [] : [printFor(index.keyType)(key)];
896
+ });
897
+ assert.deepEqual(jobsOf(both.before), [], 'no item compared before: p1\'s j-1 is not touched');
898
+ const after = jobsOf(both.after);
899
+ assert.equal(after.length, 3, `j-7 under p2.1, and under p2 and the row in the subtree: ${after.join('; ')}`);
900
+ assert.ok(after.every((key) => key.includes('"j-7"')), 'only j-7');
901
+ });
902
+ it('leaves the row to be compared whole where a replace is on the way, as a recursive child row\'s change always is', () => {
903
+ const machinesIndex = machinesInTime(machines());
904
+ const one = parsed(Machine, machine({ 'j-1': job(OCT_2, OCT_2_NIGHT) }));
905
+ const other = parsed(Machine, machine({ 'j-2': job(NOV_3, NOV_3_NIGHT) }));
906
+ assert.equal(byPatch(machinesIndex, 'M-7', one, other, variant('replace', { before: one, after: other })).type, 'whole', 'the row replaced');
907
+ assert.equal(byPatch(machinesIndex, 'M-7', one, other).type, 'whole', 'its jobs replaced, none of their keys kept');
908
+ const assembliesIndex = assembliesInTime(assemblies());
909
+ const assembly = (start, end) => parsed(Assembly, `(name="Assembly 1", parts={"p1":(name="p1", jobs={:}, parts={"p1.2":(name="p1.2", jobs={"j-9":${job(start, end)}}, parts={:})})})`);
910
+ assert.equal(byPatch(assembliesIndex, 'A-1', assembly(OCT_2, OCT_2_NIGHT), assembly(NOV_3, NOV_3_NIGHT)).type, 'whole', 'a part\'s job moved: East patches a part only whole');
911
+ });
912
+ it('compares nothing where the patch names none of what the index files', () => {
913
+ const index = machinesInTime(machines());
914
+ const jobs = { 'j-1': job(OCT_2, OCT_2_NIGHT) };
915
+ assertCompared(index, byPatch(index, 'M-7', parsed(Machine, machine(jobs)), parsed(Machine, machine(jobs, {}, 'down'))), '{:}', '{:}');
916
+ });
917
+ });
918
+ // ── Its programs ─────────────────────────────────────────────────────────────
919
+ const encodeIR = encodeBeast2For(IRType);
920
+ /**
921
+ * A function's IR in a canonical form: every location id zeroed, and every
922
+ * variable and loop label renamed by its first appearance, so one function is
923
+ * alike wherever a program writes it, whatever was built before it.
924
+ */
925
+ function canonicalIR(ir) {
926
+ const names = new Map();
927
+ const labels = new Map();
928
+ const renamed = (seen, prefix, held) => {
929
+ if (held === null || typeof held !== 'object')
930
+ return held;
931
+ const named = held;
932
+ const name = named['name'];
933
+ if (typeof name !== 'string')
934
+ return held;
935
+ if (!seen.has(name))
936
+ seen.set(name, `${prefix}${seen.size}`);
937
+ return { ...named, name: seen.get(name) };
938
+ };
939
+ const walk = (node) => {
940
+ if (Array.isArray(node))
941
+ return node.map(walk);
942
+ if (node === null || typeof node !== 'object')
943
+ return node;
944
+ const proto = Object.getPrototypeOf(node);
945
+ if (proto !== Object.prototype && proto !== null)
946
+ return node;
947
+ const out = {};
948
+ for (const [field, value] of Object.entries(node)) {
949
+ out[field] = field === 'loc_id' ? 0n
950
+ : (field === 'type' && typeof value === 'object') || field === 'type_parameters' ? value
951
+ : field === 'label' ? renamed(labels, 'l', walk(value))
952
+ : walk(value);
953
+ }
954
+ if (out['type'] === 'Variable')
955
+ out['value'] = renamed(names, 'v', out['value']);
956
+ return out;
957
+ };
958
+ return walk(ir);
959
+ }
960
+ /** A function's fingerprint: the SHA-256 of its IR in canonical form, hex. */
961
+ function fingerprint(ir) {
962
+ return createHash('sha256').update(encodeIR(canonicalIR(ir))).digest('hex');
963
+ }
964
+ /** How many nodes an IR holds. */
965
+ function nodesOf(ir) {
966
+ let nodes = 0;
967
+ walkIR(ir, () => { nodes += 1; });
968
+ return nodes;
969
+ }
970
+ /** A nested series index's programs, each's IR: a row's entries, a write's by its patch, the fill, the lean row and the span. */
971
+ function programsOf(index) {
972
+ const nested = index.nested;
973
+ return {
974
+ entries: bundleOf(index.keyFn).ir, byPatch: bundleOf(nested.byPatch).ir, fill: bundleOf(nested.fill).ir, lean: bundleOf(nested.lean).ir,
975
+ span: bundleOf(nested.span.keyFn).ir,
976
+ };
977
+ }
978
+ /** The functions of 50 nodes or more a program writes more than once, in words. */
979
+ function repeated(program) {
980
+ const seen = new Map();
981
+ walkIR(program, (node) => {
982
+ if (node.type !== 'Function')
983
+ return;
984
+ const nodes = nodesOf(node);
985
+ if (nodes < 50)
986
+ return;
987
+ const key = fingerprint(node);
988
+ const at = seen.get(key) ?? { nodes, copies: 0 };
989
+ at.copies += 1;
990
+ seen.set(key, at);
991
+ });
992
+ return [...seen.values()].filter((at) => at.copies > 1).map((at) => `${at.copies} copies of a function of ${at.nodes} nodes`);
993
+ }
994
+ /** How many times a program writes a function. */
995
+ function copiesIn(program, fn) {
996
+ const key = fingerprint(fn.toIR().ir);
997
+ let copies = 0;
998
+ walkIR(program, (node) => {
999
+ if (node.type === 'Function' && fingerprint(node) === key)
1000
+ copies += 1;
1001
+ });
1002
+ return copies;
1003
+ }
1004
+ describe('index.nested — its programs', () => {
1005
+ it('write each function once: none of 50 nodes or more twice in a row\'s entries, a write\'s, the fill, the lean row or the span', () => {
1006
+ const declared = [
1007
+ ['machines', machinesInTime(machines())],
1008
+ ['halls', hallsInTime(halls())],
1009
+ ['assemblies', assembliesInTime(assemblies())],
1010
+ ['ledgers', ledgersInTime(ledgers())],
1011
+ ];
1012
+ for (const [name, index] of declared) {
1013
+ for (const [program, fn] of Object.entries(programsOf(index))) {
1014
+ assert.deepEqual(repeated(fn), [], `the ${name}' ${program}`);
1015
+ }
1016
+ }
1017
+ });
1018
+ it('hold each function their collections call once, and none they do not: no sharing out without a summary or items, no filing in a span', () => {
1019
+ const machinesPrograms = programsOf(machinesInTime(machines()));
1020
+ for (const program of ['entries', 'byPatch']) {
1021
+ assert.equal(copiesIn(machinesPrograms[program], TILE_FNS.placedFilingsOver), 1, `the machines' ${program} file their five collections by one function`);
1022
+ assert.equal(copiesIn(machinesPrograms[program], TILE_FNS.placedSharesOver), 1, `the machines' ${program} share their three of items out by one`);
1023
+ }
1024
+ assert.equal(copiesIn(machinesPrograms.span, TILE_FNS.placedSharesOver), 1, 'the machines\' span shares their items out over the months');
1025
+ assert.equal(copiesIn(machinesPrograms.span, TILE_FNS.placedFilingsOver), 0, 'the machines\' span files nothing');
1026
+ const ledgersPrograms = programsOf(ledgersInTime(ledgers()));
1027
+ for (const program of ['entries', 'byPatch', 'span']) {
1028
+ assert.equal(copiesIn(ledgersPrograms[program], TILE_FNS.placedSharesOver), 0, `the ledgers' ${program}: values, and no summary, so nothing shared out`);
1029
+ }
1030
+ });
1031
+ });
1032
+ //# sourceMappingURL=record-nested.spec.js.map