@elaraai/e3 1.0.107 → 1.0.109

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 (81) hide show
  1. package/dist/src/export.d.ts.map +1 -1
  2. package/dist/src/export.js +13 -6
  3. package/dist/src/export.js.map +1 -1
  4. package/dist/src/export.spec.js +25 -3
  5. package/dist/src/export.spec.js.map +1 -1
  6. package/dist/src/function.d.ts +136 -57
  7. package/dist/src/function.d.ts.map +1 -1
  8. package/dist/src/function.js +47 -12
  9. package/dist/src/function.js.map +1 -1
  10. package/dist/src/function.spec.d.ts +3 -1
  11. package/dist/src/function.spec.d.ts.map +1 -1
  12. package/dist/src/function.spec.js +246 -3
  13. package/dist/src/function.spec.js.map +1 -1
  14. package/dist/src/index-input.d.ts +162 -0
  15. package/dist/src/index-input.d.ts.map +1 -0
  16. package/dist/src/index-input.js +216 -0
  17. package/dist/src/index-input.js.map +1 -0
  18. package/dist/src/index-input.spec.d.ts +6 -0
  19. package/dist/src/index-input.spec.d.ts.map +1 -0
  20. package/dist/src/index-input.spec.js +269 -0
  21. package/dist/src/index-input.spec.js.map +1 -0
  22. package/dist/src/index-read.d.ts +428 -0
  23. package/dist/src/index-read.d.ts.map +1 -0
  24. package/dist/src/index-read.js +747 -0
  25. package/dist/src/index-read.js.map +1 -0
  26. package/dist/src/index-read.spec.d.ts +6 -0
  27. package/dist/src/index-read.spec.d.ts.map +1 -0
  28. package/dist/src/index-read.spec.js +1447 -0
  29. package/dist/src/index-read.spec.js.map +1 -0
  30. package/dist/src/index.d.ts +10 -3
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +4 -1
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/package.d.ts.map +1 -1
  35. package/dist/src/package.js +3 -4
  36. package/dist/src/package.js.map +1 -1
  37. package/dist/src/record-area.d.ts +12 -0
  38. package/dist/src/record-area.d.ts.map +1 -1
  39. package/dist/src/record-area.js +26 -0
  40. package/dist/src/record-area.js.map +1 -1
  41. package/dist/src/record-area.spec.js +4 -14
  42. package/dist/src/record-area.spec.js.map +1 -1
  43. package/dist/src/record-builders.d.ts +39 -14
  44. package/dist/src/record-builders.d.ts.map +1 -1
  45. package/dist/src/record-builders.js.map +1 -1
  46. package/dist/src/record-entries.spec.js +2 -15
  47. package/dist/src/record-entries.spec.js.map +1 -1
  48. package/dist/src/record-index.d.ts +11 -5
  49. package/dist/src/record-index.d.ts.map +1 -1
  50. package/dist/src/record-index.js.map +1 -1
  51. package/dist/src/record-interval.d.ts +7 -0
  52. package/dist/src/record-interval.d.ts.map +1 -1
  53. package/dist/src/record-interval.js +7 -0
  54. package/dist/src/record-interval.js.map +1 -1
  55. package/dist/src/record-nested-programs.d.ts +63 -511
  56. package/dist/src/record-nested-programs.d.ts.map +1 -1
  57. package/dist/src/record-nested-programs.js +403 -222
  58. package/dist/src/record-nested-programs.js.map +1 -1
  59. package/dist/src/record-nested.d.ts +60 -10
  60. package/dist/src/record-nested.d.ts.map +1 -1
  61. package/dist/src/record-nested.js +65 -23
  62. package/dist/src/record-nested.js.map +1 -1
  63. package/dist/src/record-nested.spec.js +113 -34
  64. package/dist/src/record-nested.spec.js.map +1 -1
  65. package/dist/src/record-series.spec.js +6 -31
  66. package/dist/src/record-series.spec.js.map +1 -1
  67. package/dist/src/record.d.ts +9 -0
  68. package/dist/src/record.d.ts.map +1 -1
  69. package/dist/src/record.js +14 -0
  70. package/dist/src/record.js.map +1 -1
  71. package/dist/src/task.d.ts +28 -16
  72. package/dist/src/task.d.ts.map +1 -1
  73. package/dist/src/task.js +33 -5
  74. package/dist/src/task.js.map +1 -1
  75. package/dist/src/test-helpers.d.ts +35 -0
  76. package/dist/src/test-helpers.d.ts.map +1 -0
  77. package/dist/src/test-helpers.js +56 -0
  78. package/dist/src/test-helpers.js.map +1 -0
  79. package/dist/src/types.d.ts +86 -13
  80. package/dist/src/types.d.ts.map +1 -1
  81. package/package.json +3 -3
@@ -0,0 +1,747 @@
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
+ * A reader for each kind of index, inside a task or a function
7
+ * (east-workspace#1618).
8
+ *
9
+ * With `e3.index` a body holds an index's entries, `Dict<{ ik, k }, P>`, and
10
+ * with a range read it reads a run of them. For a plain index that is the
11
+ * whole read: the rows under a key are one run. The indexes a planning board
12
+ * reads are not one run — a series index files each event once, at the level
13
+ * its length fits, so a key's events over a span are a run a level; an
14
+ * interval index answers a window with a run of starts and one a tree node
15
+ * above the window's first instant — and each files more under those runs than
16
+ * a window holds. A reader knows its kind's runs, and tests what they hold.
17
+ *
18
+ * A reader answers a **read** ({@link IndexRead}), which gives the rows its
19
+ * words say and no others, each once, in the index's own order: `each` runs a
20
+ * body for each, a segment in memory at a time, and `collect` gives them as a
21
+ * Dict by the row's key. A read of several runs reads them in the order the
22
+ * index holds them, so its rows come as a walk of the index would meet them.
23
+ *
24
+ * The runs are written as East, over the functions that file each index
25
+ * (`record-tiles.ts`, `record-interval.ts`), so they run on every runner, and
26
+ * are the runs a page's reader of the kind reads (east-ui's
27
+ * `platform/slice/record-interval.ts`, `record-series.ts`).
28
+ *
29
+ * @packageDocumentation
30
+ */
31
+ import { ArrayType, DateTimeType, DictType, East, Expr, FloatType, IntegerType, OptionType, SetType, compareFor, equalFor, isTypeEqual, none, printType, some, variant, } from '@elaraai/east';
32
+ // What a reader's `on` is written as, an object literal, by the rule a key range's bound is (east's `key_range.ts`).
33
+ import { isObjectLiteral } from '@elaraai/east/internal';
34
+ import { RecordLevelType, RecordNestedPathType, RecordNestedTotalsType, RecordRollupType, RecordSummaryTotalsType, nestedPathCases, } from '@elaraai/e3-types';
35
+ import { AREA_FINEST_LEVEL, AREA_FNS, AREA_UNPLACED } from './record-area.js';
36
+ import { INTERVAL_LEAF } from './record-interval.js';
37
+ import { optionField } from './record-keys.js';
38
+ import { checkNested, rollupOf, rollupWords, } from './record-nested.js';
39
+ import { itemOf, nestedPathOf, placePath } from './record-nested-programs.js';
40
+ import { RECORD_TILES, TILE_FNS } from './record-tiles.js';
41
+ /** A read from the walk that gives its rows. */
42
+ function readOf(keyType, carriedType, walk) {
43
+ return {
44
+ each: ($, body) => { walk($, body); },
45
+ collect: ($) => {
46
+ const rows = $.let(new Map(), DictType(keyType, carriedType));
47
+ walk($, ($, carried, key) => { $(rows.insert(key, carried)); });
48
+ return rows;
49
+ },
50
+ };
51
+ }
52
+ /** An entry's row key. */
53
+ const rowKey = (entry) => East.field(entry, 'k');
54
+ /** A part of an entry's index key. */
55
+ const indexKeyPart = (entry, part) => East.field(East.field(entry, 'ik'), part);
56
+ /** The instant a millisecond before one. */
57
+ function msBefore(at) {
58
+ return East.DateTime.fromEpochMilliseconds(at.toEpochMilliseconds().subtract(1n));
59
+ }
60
+ /**
61
+ * The leading values a generated index's reader is given, as the key's `on`:
62
+ * every leading field, exactly.
63
+ *
64
+ * @param entries - The index's entries
65
+ * @param reader - The reader, as the refusal names it
66
+ * @param on - What was written
67
+ * @returns The key's `on`
68
+ * @throws {Error} When a leading field is left out, one is given that leads nothing, or a value is not of its field's
69
+ * type, naming the fields the index is led by
70
+ */
71
+ function leadingOn(entries, reader, on) {
72
+ const onType = entries.ik.fields.on;
73
+ const names = Object.keys(onType.fields);
74
+ const led = names.length === 0
75
+ ? 'the index is led by no field, and takes no `on`'
76
+ : `the index is led by ${names.map((name) => `'${name}'`).join(', ')}, and takes each exactly, as on: { ${names.map((name) => `${name}: …`).join(', ')} }`;
77
+ const given = on === undefined ? {} : on;
78
+ if (!isObjectLiteral(given))
79
+ throw new Error(`${entries.name} ${reader}: \`on\` is written as an object of the leading fields — ${led}`);
80
+ const stranger = Object.keys(given).find((name) => !names.includes(name));
81
+ if (stranger !== undefined)
82
+ throw new Error(`${entries.name} ${reader}: '${stranger}' leads nothing — ${led}`);
83
+ const missing = names.find((name) => given[name] === undefined);
84
+ if (missing !== undefined)
85
+ throw new Error(`${entries.name} ${reader}: '${missing}' is left out — ${led}`);
86
+ try {
87
+ return East.struct(onType, given);
88
+ }
89
+ catch (err) {
90
+ const fields = names.map((name) => `${name}: ${printType(onType.fields[name])}`).join(', ');
91
+ throw new Error(`${entries.name} ${reader}: a leading field is given a value of another type — \`on\` is { ${fields} }: ${err instanceof Error ? err.message : String(err)}`);
92
+ }
93
+ }
94
+ /** A reader's instant, as an expression. */
95
+ function instant(entries, reader, name, at) {
96
+ if (at === undefined)
97
+ throw new Error(`${entries.name} ${reader}: \`${name}\` is left out — a window is [from, to), each a DateTime`);
98
+ return East.value(at, DateTimeType);
99
+ }
100
+ /**
101
+ * Gives a run's rows. A fanned-out index files a row under each of several
102
+ * keys, so a run of more than one key may hold it more than once: the keys of
103
+ * the rows given are then kept, and a row is given the first time it is met.
104
+ */
105
+ function giveRun($, entries, run, once, give) {
106
+ const dict = run;
107
+ if (summedEntries(entries)) {
108
+ // An entry that stands for every row of its key names none: the read gives its index key in a row's key's place.
109
+ $.for(dict, ($, carried, entry) => { give($, carried, East.field(entry, 'ik')); });
110
+ return;
111
+ }
112
+ if (!once) {
113
+ $.for(dict, ($, carried, entry) => { give($, carried, rowKey(entry)); });
114
+ return;
115
+ }
116
+ const given = $.let(new Set(), SetType(entries.k));
117
+ $.for(dict, ($, carried, entry) => {
118
+ $.if(given.tryInsert(rowKey(entry)), ($) => { give($, carried, rowKey(entry)); });
119
+ });
120
+ }
121
+ /** Whether an index's entry stands for every row of its key, and names none: a summary's, a nested series index's span's. */
122
+ const summedEntries = (entries) => entries.def.summary !== undefined || entries.def.span !== undefined;
123
+ function plainReaders(entries) {
124
+ // One whole key's rows are filed under it once each; a key that is a struct may be given by its first fields.
125
+ const fanned = entries.def.multi && !summedEntries(entries);
126
+ // What a read gives beside what the index carries: the row's key, or the index key of an entry that names no row.
127
+ const given = summedEntries(entries) ? entries.ik : entries.k;
128
+ return {
129
+ of: (key) => {
130
+ if (key === undefined)
131
+ throw new Error(`${entries.name} of: the index key is left out — the key the rows are filed under, or its first fields`);
132
+ // The run is made here, where a key that is no leading part of the index's is refused.
133
+ const run = entries.dict.prefix({ ik: key });
134
+ return readOf(given, entries.carried, ($, give) => { giveRun($, entries, run, fanned && entries.ik.type === 'Struct', give); });
135
+ },
136
+ between: (bounds) => {
137
+ const run = entries.dict.range({
138
+ ...(bounds.from !== undefined && { from: { ik: bounds.from } }),
139
+ ...(bounds.to !== undefined && { to: { ik: bounds.to } }),
140
+ });
141
+ return readOf(given, entries.carried, ($, give) => { giveRun($, entries, run, fanned, give); });
142
+ },
143
+ };
144
+ }
145
+ function intervalReaders(entries) {
146
+ const atType = entries.ik.fields.at;
147
+ const optional = isTypeEqual(atType, OptionType(DateTimeType));
148
+ /** An instant as an entry is ordered by it: at the start field's type. */
149
+ const at = (ms) => {
150
+ const time = East.DateTime.fromEpochMilliseconds(ms);
151
+ return optional ? East.value(some(time), OptionType(DateTimeType)) : time;
152
+ };
153
+ return {
154
+ overlapping: (window) => {
155
+ const given = window;
156
+ const written = { on: leadingOn(entries, 'overlapping', given.on), from: instant(entries, 'overlapping', 'from', given.from), to: instant(entries, 'overlapping', 'to', given.to) };
157
+ return readOf(entries.k, entries.carried, ($, give) => {
158
+ const on = $.const(written.on);
159
+ const from = $.const(written.from);
160
+ const to = $.const(written.to);
161
+ $.if(East.less(from, to), ($) => {
162
+ const fromMs = $.const(from.toEpochMilliseconds());
163
+ // The nodes the window reads: node 0, which files the starts, and each node above the window's first
164
+ // instant. Those are found from its leaf up, and a Set holds them all in the index's order: node 0, then the
165
+ // root's child down to the leaf.
166
+ const nodes = $.let(new Set([0n]), SetType(IntegerType));
167
+ const child = $.let(fromMs.add(INTERVAL_LEAF));
168
+ $.while(child.greater(1n), ($) => {
169
+ $(nodes.insert(child));
170
+ $.assign(child, child.divide(2n));
171
+ });
172
+ // One loop, so the body is in the program once: a node's run is chosen by what the node is.
173
+ $.for(nodes, ($, node) => {
174
+ // Node 0's run is the starts inside the window. Any other node's events all cross its centre, so to the
175
+ // left of it they overlap the window when they start before it, and to the right — an odd node — when they
176
+ // end after its first instant.
177
+ const run = $.const(node.equal(0n).ifElse(() => entries.dict.range({ from: { ik: { on, node, at: at(fromMs) } }, to: { ik: { on, node, at: at(to.toEpochMilliseconds()) } } }), () => node.remainder(2n).equal(1n).ifElse(() => entries.dict.range({ from: { ik: { on, node, at: at(fromMs.add(1n)) } }, to: { ik: { on, node: node.add(1n) } } }), () => entries.dict.range({ from: { ik: { on, node } }, to: { ik: { on, node, at: at(fromMs) } } }))));
178
+ $.for(run, ($, carried, entry) => { give($, carried, rowKey(entry)); });
179
+ });
180
+ });
181
+ });
182
+ },
183
+ unset: (...where) => {
184
+ if (!optional) {
185
+ throw new Error(`${entries.name} unset: the index's start, '${entries.def.interval.from}', is a DateTime field, so every row has one — ` +
186
+ `a row with no start is one whose start is an Option<DateTime> left none`);
187
+ }
188
+ const written = leadingOn(entries, 'unset', where[0]?.on);
189
+ return readOf(entries.k, entries.carried, ($, give) => {
190
+ const on = $.const(written);
191
+ const backlog = East.value(none, OptionType(DateTimeType));
192
+ $.for(entries.dict.prefix({ ik: { on, node: 0n, at: backlog } }), ($, carried, entry) => { give($, carried, rowKey(entry)); });
193
+ });
194
+ },
195
+ };
196
+ }
197
+ /** The key a series or a summary reader is given, at the index's key field's type. */
198
+ function eventKey(entries, reader, key) {
199
+ if (key === undefined)
200
+ throw new Error(`${entries.name} ${reader}: \`key\` is left out — the key the events are on`);
201
+ return East.value(key, entries.ik.fields.key);
202
+ }
203
+ /** What a series or a summary reader is given, each part an expression, refused where it is written. */
204
+ function keyWindow(entries, reader, window) {
205
+ const given = (window ?? {});
206
+ return {
207
+ on: leadingOn(entries, reader, given.on),
208
+ key: eventKey(entries, reader, given.key),
209
+ from: instant(entries, reader, 'from', given.from),
210
+ to: instant(entries, reader, 'to', given.to),
211
+ };
212
+ }
213
+ /** A row's field read as an instant: the field itself, or an Option's value, `absent` for none. */
214
+ function timeOf(row, field, absent) {
215
+ return field.optional
216
+ ? East.field(row, field.field, OptionType(DateTimeType)).unwrap('some', () => absent)
217
+ : East.field(row, field.field, DateTimeType);
218
+ }
219
+ /**
220
+ * The levels an index files at from its tile up to the year, in the index's
221
+ * order of them: East's order of the level's cases, which is by their names.
222
+ */
223
+ function levelsFrom(tile) {
224
+ return RECORD_TILES.slice(RECORD_TILES.indexOf(tile))
225
+ .map((level) => variant(level, null))
226
+ .sort(compareFor(RecordLevelType));
227
+ }
228
+ /** The tile arithmetic, held once by a reader's block. */
229
+ function tileFns($) {
230
+ return { startOf: $.const(TILE_FNS.tileStart), nextOf: $.const(TILE_FNS.tileNext) };
231
+ }
232
+ /**
233
+ * The run of a level's tiles a window `[from, to)` reads: the start of the
234
+ * first, and of the tile after the last. The one place the run is worked out,
235
+ * for every reader of tiles.
236
+ *
237
+ * `carried` starts the run a tile sooner, for events with a span: one filed at
238
+ * a level ends within the tile after the one holding its start, so the events
239
+ * of a level that overlap the window start in a tile from the one before the
240
+ * window's first to its last.
241
+ */
242
+ function tilesOver($, tiles, level, from, to, carried) {
243
+ const first = $.const(carried ? tiles.startOf(level, msBefore(tiles.startOf(level, from))) : tiles.startOf(level, from));
244
+ const after = $.const(tiles.nextOf(level, tiles.startOf(level, msBefore(to))));
245
+ return { first, after };
246
+ }
247
+ /**
248
+ * Whether a filed entry's event overlaps a window and is the one to give: the
249
+ * window's edges and the once rule, in one place for every reader of events
250
+ * with a span — a series index's, and a nested series index's items.
251
+ *
252
+ * The edges are the interval index's: an event with no end, or one at or
253
+ * before its start, is an instant, inside from `from` and outside at `to`;
254
+ * any other overlaps where it starts before `to` and ends after `from`. An
255
+ * event past a year is filed under each year it touches, and is given under
256
+ * the first of them the run holds: the run's first tile, or the tile holding
257
+ * its start, which of the tiles it is filed under is the one at or before its
258
+ * start.
259
+ *
260
+ * @param $ - The block the entry is read in
261
+ * @param event - The event: a row, or a nested item
262
+ * @param start - Its start field
263
+ * @param end - Its end field
264
+ * @param entry - The entry's key, whose index key holds the tile it is filed under
265
+ * @param window - The window, and the run's first tile
266
+ * @returns Whether the entry is given
267
+ */
268
+ function spanGiven($, event, start, end, entry, window) {
269
+ // The index files an event with a start alone, and one with no end, or one at or before its start, is an instant.
270
+ const starts = $.const(timeOf(event, start, window.from));
271
+ const startMs = $.const(starts.toEpochMilliseconds());
272
+ const endMs = $.const(timeOf(event, end, starts).toEpochMilliseconds());
273
+ const overlaps = endMs.lessEqual(startMs).ifElse(() => startMs.greaterEqual(window.fromMs).and(() => startMs.less(window.toMs)), () => startMs.less(window.toMs).and(() => endMs.greater(window.fromMs)));
274
+ const tile = $.const(indexKeyPart(entry, 'tile'));
275
+ return overlaps.and(() => East.equal(tile, window.first).or(() => startMs.greaterEqual(tile.toEpochMilliseconds())));
276
+ }
277
+ function seriesReaders(entries) {
278
+ const series = entries.def.series;
279
+ const rowType = entries.carried;
280
+ const start = optionField(rowType, series.from, DateTimeType);
281
+ const end = optionField(rowType, series.to, DateTimeType);
282
+ if (start === undefined || end === undefined) {
283
+ throw new Error(`${entries.name}: a series index carries its rows, and these carry no '${series.from}' and '${series.to}' to test a window by`);
284
+ }
285
+ const levels = levelsFrom(series.tile);
286
+ return {
287
+ events: (window) => {
288
+ const written = keyWindow(entries, 'events', window);
289
+ return readOf(entries.k, entries.carried, ($, give) => {
290
+ const on = $.const(written.on);
291
+ const key = $.const(written.key);
292
+ const from = $.const(written.from);
293
+ const to = $.const(written.to);
294
+ $.if(East.less(from, to), ($) => {
295
+ const tiles = tileFns($);
296
+ const fromMs = $.const(from.toEpochMilliseconds());
297
+ const toMs = $.const(to.toEpochMilliseconds());
298
+ $.for($.const(levels, ArrayType(RecordLevelType)), ($, level) => {
299
+ const { first, after } = tilesOver($, tiles, level, from, to, true);
300
+ const run = entries.dict.range({ from: { ik: { on, key, level, tile: first } }, to: { ik: { on, key, level, tile: after } } });
301
+ $.for(run, ($, row, entry) => {
302
+ $.if(spanGiven($, row, start, end, entry, { from, fromMs, toMs, first }), ($) => { give($, row, rowKey(entry)); });
303
+ });
304
+ });
305
+ });
306
+ });
307
+ },
308
+ };
309
+ }
310
+ function summaryReaders(entries) {
311
+ const level = variant(entries.def.summary.tile, null);
312
+ return {
313
+ totals: (window) => {
314
+ const written = keyWindow(entries, 'totals', window);
315
+ return readOf(DateTimeType, RecordSummaryTotalsType, ($, give) => {
316
+ const on = $.const(written.on);
317
+ const key = $.const(written.key);
318
+ const from = $.const(written.from);
319
+ const to = $.const(written.to);
320
+ $.if(East.less(from, to), ($) => {
321
+ // A total is split by tile, so the tiles that overlap the window hold all of it.
322
+ const { first, after } = tilesOver($, tileFns($), $.const(level, RecordLevelType), from, to, false);
323
+ const run = entries.dict.range({ from: { ik: { on, key, tile: first } }, to: { ik: { on, key, tile: after } } });
324
+ $.for(run, ($, totals, entry) => { give($, totals, indexKeyPart(entry, 'tile')); });
325
+ });
326
+ });
327
+ },
328
+ };
329
+ }
330
+ /** A reader's number, as an expression. */
331
+ function float(entries, reader, name, value) {
332
+ if (value === undefined)
333
+ throw new Error(`${entries.name} ${reader}: \`${name}\` is left out — a window is { x, y, width, height }, each a Float`);
334
+ return East.value(value, FloatType);
335
+ }
336
+ /**
337
+ * A Float with no sign on its zero. East orders `-0.0` below `0.0`, and a
338
+ * window's edge, or a box's, at either is the one edge, as it is to a page's
339
+ * read: a number plus zero is itself, and `0.0` for either zero.
340
+ */
341
+ const unsigned = (value) => value.add(0.0);
342
+ /** The larger of two Floats. */
343
+ const larger = (a, b) => a.greaterEqual(b).ifElse(() => a, () => b);
344
+ /** The smaller of two Floats. */
345
+ const smaller = (a, b) => a.lessEqual(b).ifElse(() => a, () => b);
346
+ function areaReaders(entries) {
347
+ const area = entries.def.area;
348
+ const rowType = entries.carried;
349
+ const xField = optionField(rowType, area.x, FloatType);
350
+ const yField = optionField(rowType, area.y, FloatType);
351
+ if (xField === undefined || yField === undefined) {
352
+ throw new Error(`${entries.name}: an area index carries its rows, and these carry no '${area.x}' and '${area.y}' to test a window by`);
353
+ }
354
+ /** A row's place along an axis: the field itself, or an Option's value — a row a window's runs hold is placed. */
355
+ const placeOf = (row, field) => field.optional ? East.field(row, field.field, OptionType(FloatType)).unwrap('some', () => 0.0) : East.field(row, field.field, FloatType);
356
+ /** A row's size along an axis: its field's, or none for a point. */
357
+ const sizeOf = (row, field) => field === undefined ? East.value(0.0, FloatType) : East.field(row, field, FloatType);
358
+ // The domain is the finest cell's side times 2^27 either side of zero: a power of two, so every edge is exact.
359
+ const half = area.cell * 2 ** (AREA_FINEST_LEVEL - 1);
360
+ const finest = BigInt(AREA_FINEST_LEVEL);
361
+ return {
362
+ within: (window) => {
363
+ const given = (window ?? {});
364
+ const written = {
365
+ on: leadingOn(entries, 'within', given.on),
366
+ x: float(entries, 'within', 'x', given.x), y: float(entries, 'within', 'y', given.y),
367
+ width: float(entries, 'within', 'width', given.width), height: float(entries, 'within', 'height', given.height),
368
+ };
369
+ return readOf(entries.k, entries.carried, ($, give) => {
370
+ const on = $.const(written.on);
371
+ const fromX = $.const(unsigned(written.x));
372
+ const fromY = $.const(unsigned(written.y));
373
+ const width = $.const(unsigned(written.width));
374
+ const height = $.const(unsigned(written.height));
375
+ // A number less itself is zero exactly when it is finite.
376
+ $.if([fromX, fromY, width, height].reduce((finite, value) => finite.and(() => value.subtract(value).equal(0.0)), East.value(true)).not(), ($) => {
377
+ $.error(`${entries.name} within: a window's x, y, width and height are finite numbers`);
378
+ });
379
+ $.if(width.greaterEqual(0.0).and(() => height.greaterEqual(0.0)), ($) => {
380
+ const toX = $.const(fromX.add(width));
381
+ const toY = $.const(fromY.add(height));
382
+ const morton = $.const(AREA_FNS.mortonCode);
383
+ // The deepest level read: the deepest whose cell is at least an eighth of the window's larger side.
384
+ const eighth = $.const(larger(width, height).divide(8.0));
385
+ const deepest = $.let(finest);
386
+ const finestSide = $.let(area.cell);
387
+ $.while(deepest.greater(0n).and(() => finestSide.less(eighth)), ($) => {
388
+ $.assign(finestSide, finestSide.multiply(2.0));
389
+ $.assign(deepest, deepest.subtract(1n));
390
+ });
391
+ // The runs the window reads, each by its first key and the key it ends before. They are found a level at a
392
+ // time, and a Dict holds them in the index's order: a cell before the cells inside it, along the curve.
393
+ const runs = $.let(new Map(), DictType(IntegerType, IntegerType));
394
+ // From the root down: a level's cell side, its cells along an axis, a cell's step at the finest level, and the
395
+ // codes under one cell.
396
+ const level = $.let(0n);
397
+ const side = $.let(half * 2);
398
+ const count = $.let(1n);
399
+ const step = $.let(1n << finest);
400
+ const under = $.let(1n << (2n * finest));
401
+ $.while(level.lessEqual(deepest), ($) => {
402
+ // A row filed in a cell lies within it grown by a quarter of its side: the cells whose grown bounds meet
403
+ // the window, along each axis. The root is read whatever the window: a row outside the domain files under it.
404
+ const reach = $.const(side.divide(4.0));
405
+ const last = $.const(count.subtract(1n).toFloat());
406
+ const cellAt = (at) => East.Float.roundFloor(smaller(larger(at.add(half).divide(side), East.value(0.0, FloatType)), last));
407
+ const meets = (index, from, to) => {
408
+ const start = index.toFloat().multiply(side).subtract(half);
409
+ return level.equal(0n).or(() => start.subtract(reach).lessEqual(to).and(() => start.add(side).add(reach).greaterEqual(from)));
410
+ };
411
+ const firstX = $.const(cellAt(fromX.subtract(side).subtract(reach)));
412
+ const lastX = $.const(cellAt(toX.add(side).add(reach)));
413
+ const firstY = $.const(cellAt(fromY.subtract(side).subtract(reach)));
414
+ const lastY = $.const(cellAt(toY.add(side).add(reach)));
415
+ $.for(East.Array.range(firstX, lastX.add(1n)), ($, ix) => {
416
+ $.if(meets(ix, fromX, toX), ($) => {
417
+ $.for(East.Array.range(firstY, lastY.add(1n)), ($, iy) => {
418
+ $.if(meets(iy, fromY, toY), ($) => {
419
+ // A coarser cell by its own key: the rows filed in it. A cell of the deepest level by the range
420
+ // from its key to its last descendant's: the rows filed in it or in a finer cell inside it.
421
+ const code = $.const(morton(ix.multiply(step), iy.multiply(step)));
422
+ const start = $.const(code.multiply(32n).add(level));
423
+ $(runs.insert(start, level.less(deepest).ifElse(() => start.add(1n), () => code.add(under).multiply(32n))));
424
+ });
425
+ });
426
+ });
427
+ });
428
+ $.assign(level, level.add(1n));
429
+ $.assign(side, side.divide(2.0));
430
+ $.assign(count, count.multiply(2n));
431
+ $.assign(step, step.divide(2n));
432
+ $.assign(under, under.divide(4n));
433
+ });
434
+ $.for(runs, ($, end, start) => {
435
+ const run = entries.dict.range({ from: { ik: { on, area: start } }, to: { ik: { on, area: end } } });
436
+ $.for(run, ($, row, entry) => {
437
+ // The row's box, by its corner or its centre, whichever way its sides run.
438
+ const x = $.const(unsigned(placeOf(row, xField)));
439
+ const y = $.const(unsigned(placeOf(row, yField)));
440
+ const w = $.const(unsigned(sizeOf(row, area.width)));
441
+ const h = $.const(unsigned(sizeOf(row, area.height)));
442
+ const [minX, maxX, minY, maxY] = area.at === 'centre'
443
+ ? [x.subtract(w.abs().divide(2.0)), x.add(w.abs().divide(2.0)), y.subtract(h.abs().divide(2.0)), y.add(h.abs().divide(2.0))]
444
+ : [smaller(x, x.add(w)), larger(x, x.add(w)), smaller(y, y.add(h)), larger(y, y.add(h))];
445
+ $.if(minX.lessEqual(toX).and(() => maxX.greaterEqual(fromX)).and(() => minY.lessEqual(toY)).and(() => maxY.greaterEqual(fromY)), ($) => {
446
+ give($, row, rowKey(entry));
447
+ });
448
+ });
449
+ });
450
+ });
451
+ });
452
+ },
453
+ unplaced: (...where) => {
454
+ if (!xField.optional) {
455
+ throw new Error(`${entries.name} unplaced: the index's place, '${area.x}' and '${area.y}', is Float fields, so every row is placed — ` +
456
+ `a row not yet placed is one whose place is an Option<Float> left none`);
457
+ }
458
+ const written = leadingOn(entries, 'unplaced', where[0]?.on);
459
+ return readOf(entries.k, entries.carried, ($, give) => {
460
+ const on = $.const(written);
461
+ $.for(entries.dict.prefix({ ik: { on, area: AREA_UNPLACED } }), ($, row, entry) => { give($, row, rowKey(entry)); });
462
+ });
463
+ },
464
+ };
465
+ }
466
+ function entriesReaders(entries) {
467
+ return {
468
+ of: (key) => {
469
+ if (key === undefined)
470
+ throw new Error(`${entries.name} of: the key is left out — a key of the rows' '${entries.def.entries.field}'`);
471
+ // The key whole: a row files an entry for each key its field holds, so a part of one would give a row several.
472
+ const written = East.value(key, entries.ik);
473
+ return readOf(entries.k, entries.carried, ($, give) => {
474
+ $.for(entries.dict.prefix({ ik: written }), ($, value, entry) => { give($, value, rowKey(entry)); });
475
+ });
476
+ },
477
+ };
478
+ }
479
+ /**
480
+ * A nested series index's type for an item of a subtree, `{ path, id }`: what
481
+ * its `subtree` reader names each item by, as the index's own key holds it —
482
+ * the type to collect such a read under.
483
+ *
484
+ * @param index - The nested series index, as `record.indexes.<name>` gives it
485
+ * @returns The struct type: the child rows' keys from the node down, and the item's id, each an id of the index's
486
+ * @throws {Error} When the index is no nested series index
487
+ */
488
+ export function NestedUnderType(index) {
489
+ if (index.nested === undefined) {
490
+ throw new Error(`NestedUnderType: '${index.name}' is no nested series index — a subtree's items are an index.nested's, of a collection rolled up`);
491
+ }
492
+ return index.keyType.fields.item.cases.under;
493
+ }
494
+ /** Whether two rollups are one, as an index keeps them. */
495
+ const sameRollup = equalFor(RecordRollupType);
496
+ /** Each nested series index's declaration, as its readers hold it ({@link nestedDeclared}). */
497
+ const NESTED_DECLARED = new WeakMap();
498
+ /**
499
+ * A nested series index's declaration, as its readers hold it: its
500
+ * collections, each with its place and what it holds.
501
+ *
502
+ * The record checked the declaration as it built the index. It is walked here
503
+ * once more for an index, the first time a reader of it is called, and kept:
504
+ * however many functions take the index as an input, and whether or not their
505
+ * bodies read it.
506
+ *
507
+ * @param def - The nested series index
508
+ * @returns Its declaration
509
+ */
510
+ function nestedDeclared(def) {
511
+ let decl = NESTED_DECLARED.get(def);
512
+ if (decl === undefined) {
513
+ const rowType = def.record.type.value;
514
+ decl = checkNested('index.nested', def.name, rowType, def.nested.collections);
515
+ NESTED_DECLARED.set(def, decl);
516
+ }
517
+ return decl;
518
+ }
519
+ function nestedReaders(entries) {
520
+ const nested = entries.def.nested;
521
+ const rowKeyType = entries.ik.fields.row;
522
+ // A node's keys as a reader is given them — each an id of the index's — and as its key holds them (#1540): made of
523
+ // the index's declaration the first time a reader is called.
524
+ let over;
525
+ const keyed = () => (over ??= nestedPathOf(nestedDeclared(entries.def), entries.ik));
526
+ /** The levels the index files at, from its tile up to the year, as a refusal names them. */
527
+ const filedAt = RECORD_TILES.slice(RECORD_TILES.indexOf(nested.tile));
528
+ /** A collection's place, as a refusal names it: `['members', 'load']`. */
529
+ const placeWords = (collection) => `[${collection.place.map((name) => `'${name}'`).join(', ')}]`;
530
+ /**
531
+ * A node's path as a reader is given it: its child rows' keys from the row down, each an id of the index's (#1540).
532
+ * One that is not — a key as it is, where its id is wanted — is refused in words that write the path.
533
+ */
534
+ const pathGiven = (reader, collection, path) => {
535
+ try {
536
+ return East.value((path ?? []), keyed().KeysType);
537
+ }
538
+ catch (cause) {
539
+ const ids = nestedPathCases(collection.place).map((idCase) => `variant('${idCase}', key)`);
540
+ const wanted = ids.length === 0 ? 'a collection of the row itself has no path: leave `path` out' : `path: [${ids.join(', ')}]`;
541
+ throw new Error(`${entries.name} ${reader}: \`path\` names a node by its child rows' keys from the row down, each an id of the index's ` +
542
+ `under its rows' place — ${wanted}`, { cause });
543
+ }
544
+ };
545
+ /** The collection a reader is given by its place, the node it reads, and the window, refused where they do not fit. */
546
+ const written = (reader, window) => {
547
+ const given = (window ?? {});
548
+ const place = given.collection;
549
+ const decl = nestedDeclared(entries.def);
550
+ const collection = Array.isArray(place)
551
+ ? decl.collections.find((at) => at.place.length === place.length && at.place.every((name, i) => name === place[i]))
552
+ : undefined;
553
+ if (collection === undefined) {
554
+ const places = decl.collections.map(placeWords).join(', ');
555
+ throw new Error(`${entries.name} ${reader}: the index files no collection at ${JSON.stringify(place)} — it files ${places}, each by its field names from the row down`);
556
+ }
557
+ if (given.row === undefined)
558
+ throw new Error(`${entries.name} ${reader}: \`row\` is left out — the key of the record's row the node is in`);
559
+ return {
560
+ collection,
561
+ row: East.value(given.row, rowKeyType),
562
+ path: pathGiven(reader, collection, given.path),
563
+ from: instant(entries, reader, 'from', given.from),
564
+ to: instant(entries, reader, 'to', given.to),
565
+ };
566
+ };
567
+ /** What a collection's entry carries, out of its value: the item, or the value. */
568
+ const itemTypeOf = (collection) => collection.kind === 'items' ? collection.itemType : collection.valueType;
569
+ /**
570
+ * A node's items of a run, `items` or `subtree`: a run a level for items
571
+ * with a span, each tested by the window's edges and given once; one run, at
572
+ * the index's tile, for instants and values.
573
+ */
574
+ const itemsOf = ($, run, at, give) => {
575
+ const { collection } = at;
576
+ const spans = collection.kind === 'items' && collection.start.field !== collection.end.field;
577
+ const path = $.const(keyed().pathOf);
578
+ const place = $.const(placePath(collection.place), RecordNestedPathType);
579
+ const row = $.const(at.row);
580
+ const node = $.const(path(at.path));
581
+ const from = $.const(at.from);
582
+ const to = $.const(at.to);
583
+ $.if(East.less(from, to), ($) => {
584
+ const tiles = tileFns($);
585
+ const unwrap = $.const(itemOf(nestedDeclared(entries.def), collection, itemTypeOf(collection), entries.carried));
586
+ const fromMs = $.const(from.toEpochMilliseconds());
587
+ const toMs = $.const(to.toEpochMilliseconds());
588
+ // An item with a span is filed at the level its length fits; an instant, and a value, at the index's tile.
589
+ const levels = spans ? levelsFrom(nested.tile) : [variant(nested.tile, null)];
590
+ $.for($.const(levels, ArrayType(RecordLevelType)), ($, level) => {
591
+ const { first, after } = tilesOver($, tiles, level, from, to, spans);
592
+ const range = entries.dict.range({
593
+ from: { ik: { collection: place, row, path: node, run: variant(run, null), level, tile: first } },
594
+ to: { ik: { collection: place, row, path: node, run: variant(run, null), level, tile: after } },
595
+ });
596
+ $.for(range, ($, value, entry) => {
597
+ const item = $.const(unwrap(value));
598
+ const filed = indexKeyPart(entry, 'item');
599
+ // An item by its id, out of its collection's case of the index's ids; a subtree's as the key holds it.
600
+ const key = run === 'subtree' ? filed.unwrap('under')
601
+ : collection.kind === 'items' ? filed.unwrap('id').unwrap(collection.idCase)
602
+ : filed.unwrap('at');
603
+ if (collection.kind === 'values') {
604
+ // A value is at its instant, which its entry's key holds.
605
+ const instantMs = $.const(filed.unwrap('at').toEpochMilliseconds());
606
+ $.if(instantMs.greaterEqual(fromMs).and(() => instantMs.less(toMs)), ($) => { give($, item, key); });
607
+ return;
608
+ }
609
+ $.if(spanGiven($, item, collection.start, collection.end, entry, { from, fromMs, toMs, first }), ($) => { give($, item, key); });
610
+ });
611
+ });
612
+ });
613
+ };
614
+ /** A node's entries of a run that holds one a tile at a level — `totals`, `subtreeTotals`, a rollup's `subtotals` — for the tiles that overlap the window. */
615
+ const tilesOf = ($, run, tile, held, at, give) => {
616
+ const path = $.const(keyed().pathOf);
617
+ const place = $.const(placePath(at.collection.place), RecordNestedPathType);
618
+ const row = $.const(at.row);
619
+ const node = $.const(path(at.path));
620
+ const from = $.const(at.from);
621
+ const to = $.const(at.to);
622
+ $.if(East.less(from, to), ($) => {
623
+ const level = $.const(variant(tile, null), RecordLevelType);
624
+ const { first, after } = tilesOver($, tileFns($), level, from, to, false);
625
+ const range = entries.dict.range({
626
+ from: { ik: { collection: place, row, path: node, run, level, tile: first } },
627
+ to: { ik: { collection: place, row, path: node, run, level, tile: after } },
628
+ });
629
+ $.for(range, ($, value, entry) => {
630
+ give($, value.unwrap(held), indexKeyPart(entry, 'tile'));
631
+ });
632
+ });
633
+ };
634
+ const summary = (reader) => {
635
+ if (nested.summary === undefined) {
636
+ throw new Error(`${entries.name} ${reader}: the index keeps no totals — declare the tile they are kept by, as index.nested({ …, summary: 'month' })`);
637
+ }
638
+ return nested.summary;
639
+ };
640
+ const rolledUp = (reader, collection) => {
641
+ if (collection.kind !== 'items' || !collection.rollup) {
642
+ throw new Error(`${entries.name} ${reader}: the collection at ${placeWords(collection)} is not rolled up, so no node holds ` +
643
+ `the items beneath it — declare it index.nested.items(times, { rollup: true })`);
644
+ }
645
+ };
646
+ return {
647
+ items: (window) => {
648
+ const at = written('items', window);
649
+ const keyType = at.collection.kind === 'items' ? at.collection.keyType : DateTimeType;
650
+ return readOf(keyType, itemTypeOf(at.collection), ($, give) => { itemsOf($, 'items', at, give); });
651
+ },
652
+ totals: (window) => {
653
+ const at = written('totals', window);
654
+ const tile = summary('totals');
655
+ return readOf(DateTimeType, RecordNestedTotalsType, ($, give) => { tilesOf($, variant('totals', null), tile, 'totals', at, give); });
656
+ },
657
+ subtotals: (window) => {
658
+ const at = written('subtotals', window);
659
+ const given = window;
660
+ const { collection } = at;
661
+ const kept = collection.kind === 'values' ? collection.rollups : [];
662
+ const rollup = rollupOf(`${entries.name} subtotals: the collection at ${placeWords(collection)}`, given.rollup);
663
+ if (!kept.some((declared) => sameRollup(declared, rollup))) {
664
+ const names = kept.length === 0
665
+ ? 'it keeps none: declare index.nested.values({ rollup }) under rows(…) or beside recursive()'
666
+ : `it keeps ${kept.map((declared) => rollupWords(declared)).join(', ')}`;
667
+ throw new Error(`${entries.name} subtotals: the collection at ${placeWords(collection)} keeps no subtotal by ${rollupWords(rollup)} — ${names}`);
668
+ }
669
+ const level = given.level === undefined ? nested.tile : given.level;
670
+ if (typeof level !== 'string' || !filedAt.includes(level)) {
671
+ throw new Error(`${entries.name} subtotals: the index keeps subtotals at ${filedAt.join(', ')}, and none at ${JSON.stringify(given.level)}`);
672
+ }
673
+ return readOf(DateTimeType, FloatType, ($, give) => { tilesOf($, variant('subtotals', rollup), level, 'subtotal', at, give); });
674
+ },
675
+ subtree: (window) => {
676
+ const at = written('subtree', window);
677
+ rolledUp('subtree', at.collection);
678
+ const underType = keyed().ItemType.cases.under;
679
+ return readOf(underType, itemTypeOf(at.collection), ($, give) => { itemsOf($, 'subtree', at, give); });
680
+ },
681
+ subtreeTotals: (window) => {
682
+ const at = written('subtreeTotals', window);
683
+ rolledUp('subtreeTotals', at.collection);
684
+ const tile = summary('subtreeTotals');
685
+ return readOf(DateTimeType, RecordNestedTotalsType, ($, give) => { tilesOf($, variant('subtreeTotals', null), tile, 'totals', at, give); });
686
+ },
687
+ };
688
+ }
689
+ /** The index an expression's readers read, kept on the expression: it carries one index's. */
690
+ const READS = Symbol('e3.indexReads');
691
+ /** An index input, as a refusal names it: `e3.index 'jobs.jobs_by_press'`. */
692
+ const inputWords = (input) => `e3.index '${input.record.name}.${input.index.name}'`;
693
+ /**
694
+ * An expression of an index's entries with the index's readers on it: the
695
+ * expression itself, still the entries.
696
+ *
697
+ * An expression carries one index's readers. One that carries this index's
698
+ * already — a body's parameter for it, or what `read` was given before — is
699
+ * given back as it is, its readers not made again; one that carries another
700
+ * index's is refused, naming it, which is how two indexes whose entries have
701
+ * one type are told apart. An expression that carries none is known by its
702
+ * type alone: the parameter of a task's own function for another index of the
703
+ * same type is read as this one's, and is the author's to keep apart.
704
+ *
705
+ * @param input - The index, as `e3.index` takes it
706
+ * @param entries - Its entries: the body's parameter for it, or any expression of the input's type
707
+ * @returns The expression, with the readers of the index's kind
708
+ * @throws {Error} When the expression is not of the index's entries' type, naming both, or carries another index's
709
+ * readers, naming that index
710
+ */
711
+ export function readersOn(input, entries) {
712
+ const name = inputWords(input);
713
+ if (!(entries instanceof Expr) || !isTypeEqual(Expr.type(entries), input.type)) {
714
+ const given = entries instanceof Expr ? `an expression of ${printType(Expr.type(entries))}` : 'no East expression';
715
+ throw new Error(`${name} reads its own entries, ${printType(input.type)}, and was given ${given} — pass the body's parameter for this index`);
716
+ }
717
+ const read = entries[READS];
718
+ if (read !== undefined) {
719
+ if (read.index === input.index)
720
+ return entries;
721
+ throw new Error(`${name} reads its own entries, and was given those of ${inputWords(read)}, which are of the same type — pass the body's parameter for this index`);
722
+ }
723
+ Object.defineProperty(entries, READS, { value: input });
724
+ return Object.assign(entries, readersOf(name, input, entries));
725
+ }
726
+ /** The readers of an index's kind over an expression of its entries. */
727
+ function readersOf(name, input, entries) {
728
+ const type = input.type;
729
+ const held = {
730
+ name, def: input.index, dict: entries, ik: type.key.fields.ik, k: type.key.fields.k, carried: type.value,
731
+ };
732
+ const def = input.index;
733
+ if (def.series !== undefined)
734
+ return seriesReaders(held);
735
+ if (def.summary !== undefined)
736
+ return summaryReaders(held);
737
+ if (def.interval !== undefined)
738
+ return intervalReaders(held);
739
+ if (def.area !== undefined)
740
+ return areaReaders(held);
741
+ if (def.entries !== undefined)
742
+ return entriesReaders(held);
743
+ if (def.nested !== undefined)
744
+ return nestedReaders(held);
745
+ return plainReaders(held);
746
+ }
747
+ //# sourceMappingURL=index-read.js.map