@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
@@ -9,16 +9,28 @@
9
9
  * migration changes a row; what actually runs is a program built from those
10
10
  * declarations — an ordinary East function assembled at export time from the
11
11
  * author's own expressions, as a stream task's output kind builds its merge
12
- * function. It is linked and
13
- * encoded like any other body, runs on the runner the author chose, and is
14
- * what keeps e3 out of the business of evaluating user East: the engine runs a
15
- * program and applies what it emits.
12
+ * function. It is linked and encoded like any other body, runs on the runner
13
+ * the author chose, and is what keeps e3 out of the business of evaluating
14
+ * user East: the engine runs a program and applies what it emits.
15
+ *
16
+ * Each program is assembled from typed East functions, each built from the
17
+ * declaration's types: the record's key and row, an index's key and
18
+ * projection, a mutation's arguments. Where a declaration chooses — a
19
+ * mutation's form, whether its record has indexes, which kind each index is —
20
+ * the choice is made as the program is built, never inside it. The author's
21
+ * functions are bound as function values and CALLED, never spliced: a spliced
22
+ * expression tree would be re-evaluated per reference and could capture the
23
+ * wrong bindings.
16
24
  *
17
25
  * @packageDocumentation
18
26
  */
19
- import { DictType, East, FunctionType, NullType, OptionType, PatchType, SetType, StructType, VariantType, none, some, variant, withLocationCapture, } from '@elaraai/east';
20
- import { DELTA_CONFLICT, RecordSummaryTotalsType, editTypeOf, indexCollectionType, mutationDeltaType, patchOpsType, } from '@elaraai/e3-types';
21
- import { summaryMerge } from './record-series.js';
27
+ import { ArrayType, BooleanType, DictType, East, FunctionType, IntegerType, NullType, OptionType, PatchType, SetType, StructType, VariantType, none, printType, some, variant, withLocationCapture, } from '@elaraai/east';
28
+ import { DELTA_CONFLICT, RecordSummaryOpType, RecordSummaryTotalsType, editTypeOf, indexCollectionType, mutationDeltaType, patchOpsType, } from '@elaraai/e3-types';
29
+ import { functionAt, sameEastType, signatureOf } from './record-guards.js';
30
+ import { argumentsType, callWithArguments, programOverArguments } from './record-arguments.js';
31
+ import { NestedPatchedType } from './record-nested-programs.js';
32
+ import { patchTypeOf } from './record-patches.js';
33
+ import { lazyBuilds } from './lazy-build.js';
22
34
  /**
23
35
  * Builds a program's IR with no source location captured.
24
36
  *
@@ -52,6 +64,63 @@ function locationFree(build) {
52
64
  export function indexEntryKeyType(keyType, indexKeyType) {
53
65
  return StructType({ ik: indexKeyType, k: keyType });
54
66
  }
67
+ /** A Dict record's key and row types; any other record is refused, naming `what` reads it. */
68
+ function dictEntry(recordType, what) {
69
+ if (recordType.type !== 'Dict')
70
+ throw new Error(`${what} reads a Dict record, not ${printType(recordType)}`);
71
+ return { keyType: recordType.key, valueType: recordType.value };
72
+ }
73
+ /**
74
+ * Whether an index sums its rows' totals under each key, as a summary index
75
+ * does (#1039): a summary's, or a nested series index's span (#1438). Its
76
+ * entry stands for every row of its key, so its `k` is Null, and a write adds
77
+ * to its totals rather than patching them.
78
+ *
79
+ * @param index - The index
80
+ * @returns Whether it is summed
81
+ */
82
+ export function summed(index) {
83
+ return index.summary !== undefined || index.span !== undefined;
84
+ }
85
+ /**
86
+ * A record's index as it is built and bound (#1434): as declared, but, beside
87
+ * a nested series index of the record, one that carries nothing — a plain or
88
+ * an interval index with no `value` — or the row — an area index, a key-form
89
+ * series index — carries the lean row instead: its rows without the listed
90
+ * collections, so a page of them reads no nested item and no segment of the
91
+ * record's own. An index with a `value` of its own carries its own.
92
+ *
93
+ * @param rec - The record, its indexes declared
94
+ * @param index - One of its indexes
95
+ * @returns The index as it is built
96
+ */
97
+ export function builtIndex(rec, index) {
98
+ const nested = Object.values(rec.indexes).find((other) => other.nested !== undefined)?.nested;
99
+ if (nested === undefined || index.nested !== undefined || summed(index))
100
+ return index;
101
+ const carriesTheRow = index.area !== undefined || index.series !== undefined;
102
+ if (index.valueFn !== undefined && !carriesTheRow)
103
+ return index;
104
+ const { valueType } = dictEntry(rec.type, `index '${index.name}'`);
105
+ return { ...index, valueFn: nested.lean, valueType };
106
+ }
107
+ /** An index's keys for a row: `(K, V) → Set<IK>` — its `keys` function, or its `key` function's one key. */
108
+ function indexKeys(index, keyType, valueType) {
109
+ const keysType = SetType(index.keyType);
110
+ if (index.multi)
111
+ return functionAt(index.keyFn, [keyType, valueType], keysType);
112
+ const key = functionAt(index.keyFn, [keyType, valueType], index.keyType);
113
+ return East.function([keyType, valueType], keysType, ($, k, v) => {
114
+ const keyOf = $.const(key);
115
+ return new Set([keyOf(k, v)]);
116
+ });
117
+ }
118
+ /** An index's projection of a row: `(K, V) → P` — its `value` function, or `Null` where it carries none. */
119
+ function indexProjection(index, keyType, valueType) {
120
+ if (index.valueFn !== undefined)
121
+ return functionAt(index.valueFn, [keyType, valueType], index.valueType);
122
+ return East.function([keyType, valueType], NullType, () => null);
123
+ }
55
124
  /**
56
125
  * The build program of an index: `(piece, emit) => Null`.
57
126
  *
@@ -62,50 +131,58 @@ export function indexEntryKeyType(keyType, indexKeyType) {
62
131
  * output through its RunSorter, which sorts what it is given, so the program
63
132
  * holds no more than the row in hand.
64
133
  *
65
- * The author's key and value functions are bound as function values and
66
- * CALLED, never spliced into the loop: a spliced expression tree would be
67
- * re-evaluated per reference and could capture the wrong bindings.
134
+ * A summary's program emits each row's contributions under their keys, `k`
135
+ * Null (#1039). Two rows, in one piece or two, contribute to one key: the
136
+ * build's output names the merge that sums them ({@link summaryMergeProgram}).
137
+ * A nested series index's emits each row's entries, each with its own value
138
+ * (#1434).
68
139
  *
69
140
  * @param recordType - the record's state type, `Dict<K, V>`
70
141
  * @param def - the index declaration
71
142
  * @returns the program's IR bundle
72
143
  */
73
144
  export function indexBuildProgram(recordType, def) {
74
- const dict = recordType;
75
- if (def.summary !== undefined) {
76
- // A summary (#1039): each row's contributions under their keys, `k` Null.
77
- // Two rows, in one piece or two, contribute to one key: the build's
78
- // output names the merge that sums them ({@link summaryMergeProgram}).
79
- const summaryKey = indexEntryKeyType(NullType, def.keyType);
80
- const emitSummary = FunctionType([summaryKey, RecordSummaryTotalsType], NullType);
81
- return locationFree(() => East.function([recordType, emitSummary], NullType, ($, piece, emit) => {
82
- const contribute = $.const(def.keyFn);
145
+ const { keyType, valueType } = dictEntry(recordType, `index '${def.name}'`);
146
+ const pieceType = DictType(keyType, valueType);
147
+ if (summed(def)) {
148
+ const contributions = functionAt(def.keyFn, [keyType, valueType], DictType(def.keyType, RecordSummaryTotalsType));
149
+ const emitType = FunctionType([indexEntryKeyType(NullType, def.keyType), RecordSummaryTotalsType], NullType);
150
+ return locationFree(() => East.function([pieceType, emitType], NullType, ($, piece, emit) => {
151
+ const contribute = $.const(contributions);
83
152
  $.for(piece, ($, row, key) => {
84
153
  $.for(contribute(key, row), ($, totals, ik) => {
85
154
  $(emit({ ik, k: null }, totals));
86
155
  });
87
156
  });
88
- return null;
89
157
  }));
90
158
  }
91
- const entryKey = indexEntryKeyType(dict.key, def.keyType);
92
- const emitType = FunctionType([entryKey, def.valueType], NullType);
93
- return locationFree(() => East.function([recordType, emitType], NullType, ($, piece, emit) => {
94
- const indexKey = $.const(def.keyFn);
95
- const project = def.valueFn === undefined ? undefined : $.const(def.valueFn);
96
- $.for(piece, ($, row, key) => {
97
- const value = project === undefined ? null : $.const(project(key, row));
98
- if (def.multi) {
99
- $.for(indexKey(key, row), ($, ik) => {
159
+ const emitType = FunctionType([indexEntryKeyType(keyType, def.keyType), def.valueType], NullType);
160
+ if (def.nested !== undefined) {
161
+ // A nested series index's row gives its entries with their values (#1434), each under the row's key.
162
+ const entries = functionAt(def.keyFn, [keyType, valueType], DictType(def.keyType, def.valueType));
163
+ return locationFree(() => East.function([pieceType, emitType], NullType, ($, piece, emit) => {
164
+ const entriesOf = $.const(entries);
165
+ $.for(piece, ($, row, key) => {
166
+ $.for(entriesOf(key, row), ($, value, ik) => {
167
+ $(emit({ ik, k: key }, value));
168
+ });
169
+ });
170
+ }));
171
+ }
172
+ return locationFree(() => {
173
+ const keys = indexKeys(def, keyType, valueType);
174
+ const projection = indexProjection(def, keyType, valueType);
175
+ return East.function([pieceType, emitType], NullType, ($, piece, emit) => {
176
+ const keysOf = $.const(keys);
177
+ const project = $.const(projection);
178
+ $.for(piece, ($, row, key) => {
179
+ const value = $.let(project(key, row));
180
+ $.for(keysOf(key, row), ($, ik) => {
100
181
  $(emit({ ik, k: key }, value));
101
182
  });
102
- }
103
- else {
104
- $(emit({ ik: indexKey(key, row), k: key }, value));
105
- }
183
+ });
106
184
  });
107
- return null;
108
- }));
185
+ });
109
186
  }
110
187
  /**
111
188
  * A summary index's build merge (#1039): `({ik, k}, Totals, Totals) =>
@@ -119,9 +196,26 @@ export function indexBuildProgram(recordType, def) {
119
196
  * @throws {Error} When the index is not a summary
120
197
  */
121
198
  export function summaryMergeProgram(def) {
122
- if (def.summary === undefined)
199
+ if (!summed(def) || def.mergeFn === undefined)
123
200
  throw new Error(`index '${def.name}' is not a summary, and its build merges nothing`);
124
- return locationFree(() => summaryMerge(def.name, def.keyType));
201
+ const totals = RecordSummaryTotalsType;
202
+ const merge = functionAt(def.mergeFn, [indexEntryKeyType(NullType, def.keyType), totals, totals], totals);
203
+ return locationFree(() => merge);
204
+ }
205
+ /**
206
+ * A Dict `rekey` step's function as `(K, V) → { key, value }`, whichever order
207
+ * the entry it returns declares its two fields in.
208
+ */
209
+ function rekeyStep(fn, fromKey, fromValue, toKey, toValue) {
210
+ const entryType = StructType({ key: toKey, value: toValue });
211
+ if (sameEastType(signatureOf(fn).output, entryType))
212
+ return functionAt(fn, [fromKey, fromValue], entryType);
213
+ const swapped = functionAt(fn, [fromKey, fromValue], StructType({ value: toValue, key: toKey }));
214
+ return East.function([fromKey, fromValue], entryType, ($, key, row) => {
215
+ const step = $.const(swapped);
216
+ const entry = $.let(step(key, row));
217
+ return { key: entry.key, value: entry.value };
218
+ });
125
219
  }
126
220
  /**
127
221
  * The program a `rows` or `rekey` migration runs over each piece of a record's
@@ -136,42 +230,67 @@ export function summaryMergeProgram(def) {
136
230
  * `array` output in the order emitted, so the program holds no more than the
137
231
  * row in hand.
138
232
  *
139
- * The author's function is bound as a function value and CALLED, never
140
- * spliced: a spliced expression tree would be re-evaluated per reference and
141
- * could capture the wrong bindings.
142
- *
143
233
  * @param def - the migration, a `rows` or `rekey` step
144
234
  * @returns the program's IR bundle
145
235
  * @throws {Error} When the step is a `value` step, whose own function runs.
146
236
  */
147
237
  export function migrationProgram(def) {
148
238
  if (def.form === 'value') {
149
- throw new Error(`e3.migration.value '${def.name}' runs its own function, and has no program`);
239
+ throw new Error(`e3.record '${def.record.name}': migration.value '${def.name}' runs its own function, and has no program`);
150
240
  }
241
+ const from = def.from;
151
242
  const to = def.to;
152
- const emitType = to.type === 'Dict'
153
- ? FunctionType([to.key, to.value], NullType)
154
- : FunctionType([(to.type === 'Array' ? to.value : to.key)], NullType);
155
- return locationFree(() => East.function([def.from, emitType], NullType, ($, piece, emit) => {
156
- const step = $.const(def.fn);
157
- if (to.type !== 'Dict') {
158
- $.for(piece, ($, element) => {
159
- $(emit(step(element)));
160
- });
243
+ if (from.type === 'Dict' && to.type === 'Dict') {
244
+ const fromKey = from.key;
245
+ const fromValue = from.value;
246
+ const toKey = to.key;
247
+ const toValue = to.value;
248
+ const emitType = FunctionType([toKey, toValue], NullType);
249
+ if (def.form === 'rows') {
250
+ // Each row under its own key.
251
+ const step = functionAt(def.fn, [fromKey, fromValue], toValue);
252
+ return locationFree(() => East.function([DictType(fromKey, fromValue), emitType], NullType, ($, piece, emit) => {
253
+ const stepFn = $.const(step);
254
+ $.for(piece, ($, row, key) => {
255
+ $(emit(key, stepFn(key, row)));
256
+ });
257
+ }));
161
258
  }
162
- else if (def.form === 'rows') {
163
- $.for(piece, ($, row, key) => {
164
- $(emit(key, step(key, row)));
259
+ // Each row under the key its step gives it.
260
+ return locationFree(() => {
261
+ const step = rekeyStep(def.fn, fromKey, fromValue, toKey, toValue);
262
+ return East.function([DictType(fromKey, fromValue), emitType], NullType, ($, piece, emit) => {
263
+ const stepFn = $.const(step);
264
+ $.for(piece, ($, row, key) => {
265
+ const entry = $.let(stepFn(key, row));
266
+ $(emit(entry.key, entry.value));
267
+ });
165
268
  });
166
- }
167
- else {
168
- $.for(piece, ($, row, key) => {
169
- const entry = $.let(step(key, row));
170
- $(emit(entry.key, entry.value));
269
+ });
270
+ }
271
+ if (from.type === 'Set' && to.type === 'Set') {
272
+ const fromKey = from.key;
273
+ const toKey = to.key;
274
+ const step = functionAt(def.fn, [fromKey], toKey);
275
+ return locationFree(() => East.function([SetType(fromKey), FunctionType([toKey], NullType)], NullType, ($, piece, emit) => {
276
+ const stepFn = $.const(step);
277
+ $.for(piece, ($, element) => {
278
+ $(emit(stepFn(element)));
171
279
  });
172
- }
173
- return null;
174
- }));
280
+ }));
281
+ }
282
+ if (from.type === 'Array' && to.type === 'Array') {
283
+ const fromValue = from.value;
284
+ const toValue = to.value;
285
+ const step = functionAt(def.fn, [fromValue], toValue);
286
+ return locationFree(() => East.function([ArrayType(fromValue), FunctionType([toValue], NullType)], NullType, ($, piece, emit) => {
287
+ const stepFn = $.const(step);
288
+ $.for(piece, ($, element) => {
289
+ $(emit(stepFn(element)));
290
+ });
291
+ }));
292
+ }
293
+ throw new Error(`e3.record '${def.record.name}': migration.${def.form} '${def.name}' migrates a Dict, a Set or an Array, from ${printType(from)} to ${printType(to)}`);
175
294
  }
176
295
  /**
177
296
  * The delta's targets for a record: its own collection, then each index.
@@ -186,39 +305,72 @@ export function migrationProgram(def) {
186
305
  * @returns the targets, in canonical case order
187
306
  */
188
307
  export function deltaTargets(recordType, indexes) {
189
- const collection = recordType;
308
+ if (recordType.type !== 'Dict' && recordType.type !== 'Set') {
309
+ throw new Error(`a mutation delta addresses a Dict or a Set by key, not ${printType(recordType)}`);
310
+ }
311
+ const keyType = recordType.key;
190
312
  const targets = [
191
- { name: 'primary', keyType: collection.key, collectionType: recordType },
313
+ { name: 'primary', keyType, collectionType: recordType },
192
314
  ];
193
315
  for (const index of indexes) {
194
316
  // A summary's entry stands for every row of its key, so its `k` is Null,
195
317
  // and its arm carries what to add to each total (#1039).
196
- const k = index.summary !== undefined ? NullType : collection.key;
318
+ const k = summed(index) ? NullType : keyType;
197
319
  targets.push({
198
320
  name: index.name,
199
321
  keyType: indexEntryKeyType(k, index.keyType),
200
322
  collectionType: indexCollectionType(k, index.keyType, index.valueType),
201
- ...(index.summary !== undefined && { summary: true }),
323
+ ...(summed(index) && { summary: true }),
202
324
  });
203
325
  }
204
326
  return targets.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
205
327
  }
328
+ /** Whether a record's own collection has a delta at all: one addressed by key,
329
+ * which is what lets a commit rebuild only the segments it touched. An Array
330
+ * record's patch is positional, and a scalar's is a replace. */
331
+ export function hasKeyedDelta(recordType) {
332
+ return recordType.type === 'Dict' || recordType.type === 'Set';
333
+ }
206
334
  /** The foldable op an `edit` body records per key, before the state resolves it
207
335
  * into an insert / delete / update. `set` is deliberately not one of those:
208
336
  * which it becomes depends on whether the record already holds the key, and
209
337
  * the body is not the place that knows. */
210
- function editOpsType(valueType) {
211
- return VariantType({ set: valueType, delete: NullType, update: PatchType(valueType) });
338
+ function editOpsType(valueType, rows) {
339
+ return VariantType({ set: valueType, delete: NullType, update: rows.patchType });
212
340
  }
213
- /** Whether a record's own collection has a delta at all: one addressed by key,
214
- * which is what lets a commit rebuild only the segments it touched. An Array
215
- * record's patch is positional, and a scalar's is a replace. */
216
- export function hasKeyedDelta(recordType) {
217
- const t = recordType.type;
218
- return t === 'Dict' || t === 'Set';
341
+ /** The emit a write's program hands its delta to, entry by entry: `(DeltaKey, DeltaOp) → Null`. */
342
+ function deltaEmitType(recordType, indexes) {
343
+ const delta = mutationDeltaType(deltaTargets(recordType, indexes));
344
+ return FunctionType([delta.key, delta.value], NullType);
345
+ }
346
+ /**
347
+ * The types a Dict record's write is built over: its state; its rows'
348
+ * patches; its patch and its ops, typed to the depth a write reads them — an
349
+ * op's `update` is its row's patch, which the write passes on whole — and
350
+ * checked to be East's own; the rows a write touches; and the emit.
351
+ */
352
+ function dictWrite(keyType, valueType, indexes) {
353
+ const stateType = DictType(keyType, valueType);
354
+ const rows = East.patchesFor(valueType);
355
+ const opsType = DictType(keyType, VariantType({ delete: valueType, insert: valueType, update: rows.patchType }));
356
+ const patchType = VariantType({ unchanged: NullType, replace: StructType({ before: stateType, after: stateType }), patch: opsType });
357
+ if (!sameEastType(patchType, patchTypeOf(stateType))) {
358
+ throw new Error(`a write's patch of ${printType(stateType)} is not East's ${printType(patchTypeOf(stateType))}`);
359
+ }
360
+ return {
361
+ keyType,
362
+ valueType,
363
+ stateType,
364
+ rows,
365
+ patchType,
366
+ opsType,
367
+ /** The rows a write touches: under each key it changes, the row before and after, and the patch that updated it. */
368
+ changesType: DictType(keyType, StructType({ held: OptionType(valueType), next: OptionType(valueType), patch: OptionType(rows.patchType) })),
369
+ emitType: deltaEmitType(stateType, indexes),
370
+ };
219
371
  }
220
372
  /**
221
- * Folds a `PatchType(State)` into the program's per-key op dict.
373
+ * Folds a patch of a Dict record into per-key ops: `(State, Patch, verify, Emit) → Ops`.
222
374
  *
223
375
  * @remarks
224
376
  * A patch has three arms and the delta has one shape, so all three land here.
@@ -227,201 +379,389 @@ export function hasKeyedDelta(recordType) {
227
379
  * ops against the state rather than carried through, which is what keeps the
228
380
  * apply's cost proportional to what actually differs. A client's `replace`
229
381
  * whose `before` the record no longer holds is a stale write, emitted as the
230
- * delta's conflict.
382
+ * delta's conflict; `verify` asks for that check, which a diff of the state
383
+ * needs no more than its own `before`.
231
384
  */
232
- function collectOps($, state, patchExpr, ops, keyed, verifyBefore, emit) {
233
- const patch = $.let(patchExpr);
234
- $.match(patch, {
235
- patch: ($, entries) => {
236
- $.for(entries, ($, op, key) => {
237
- $(ops.insertOrUpdate(key, op));
238
- });
239
- },
240
- replace: ($, whole) => {
241
- if (verifyBefore) {
242
- $.if(East.notEqual(whole.before, state), ($) => {
385
+ export function dictPatchOps(types) {
386
+ const { stateType, rows, patchType, opsType, emitType } = types;
387
+ return East.function([stateType, patchType, BooleanType, emitType], opsType, ($, state, patch, verify, emit) => {
388
+ const diff = $.const(rows.diff);
389
+ const ops = $.let(new Map(), opsType);
390
+ $.match(patch, {
391
+ unchanged: () => { },
392
+ patch: ($, entries) => {
393
+ $.assign(ops, entries);
394
+ },
395
+ replace: ($, whole) => {
396
+ $.if(verify.and(() => East.notEqual(whole.before, state)), ($) => {
243
397
  $(emit(variant(DELTA_CONFLICT, 'the patch replaces a state the record no longer holds'), variant(DELTA_CONFLICT, null)));
244
398
  });
245
- }
246
- if (keyed === 'Set') {
247
- $.for(state, ($, key) => {
399
+ $.for(state, ($, value, key) => {
248
400
  $.if(whole.after.has(key).not(), ($) => {
249
- $(ops.insertOrUpdate(key, variant('delete', null)));
401
+ $(ops.insertOrUpdate(key, variant('delete', value)));
250
402
  });
251
403
  });
252
- $.for(whole.after, ($, key) => {
253
- $.if(state.has(key).not(), ($) => {
254
- $(ops.insertOrUpdate(key, variant('insert', null)));
404
+ $.for(whole.after, ($, value, key) => {
405
+ $.match(state.tryGet(key), {
406
+ none: ($) => {
407
+ $(ops.insertOrUpdate(key, variant('insert', value)));
408
+ },
409
+ some: ($, held) => {
410
+ $.if(East.notEqual(held, value), ($) => {
411
+ $(ops.insertOrUpdate(key, variant('update', diff(held, value))));
412
+ });
413
+ },
255
414
  });
256
415
  });
257
- return;
258
- }
259
- $.for(state, ($, value, key) => {
260
- $.if(whole.after.has(key).not(), ($) => {
261
- $(ops.insertOrUpdate(key, variant('delete', value)));
262
- });
263
- });
264
- $.for(whole.after, ($, value, key) => {
265
- $.match(state.tryGet(key), {
266
- none: ($) => {
267
- $(ops.insertOrUpdate(key, variant('insert', value)));
268
- },
269
- some: ($, held) => {
270
- $.if(East.notEqual(held, value), ($) => {
271
- $(ops.insertOrUpdate(key, variant('update', East.diff(held, value))));
272
- });
273
- },
274
- });
275
- });
276
- },
416
+ },
417
+ });
418
+ return ops;
277
419
  });
278
420
  }
279
421
  /**
280
- * The program every write form runs: `(State, …Args | Patch, Emit) => Null`.
422
+ * The rows a write touches: `(State, Ops, Emit) → Changes`, under each key it
423
+ * changes the row before it and the row after, and, for a row updated by a
424
+ * patch, the patch — none for a row inserted or deleted.
281
425
  *
282
426
  * @remarks
283
- * One program, three forms, one output — the mutation delta, emitted entry by
284
- * entry as it is computed, in any order: the runner writes a `dict` output
285
- * through its RunSorter, which sorts it. e3 stores the delta as segments and
286
- * applies it one target segment at a time; it never evaluates the author's
287
- * East itself, which is what keeps one rule for where user code runs and gives
288
- * the three runtimes something to agree on byte for byte.
289
- *
290
- * The three forms differ only in how the per-key ops are reached — a diff of
291
- * the reducer's result, the folded writes of an `edit` body, or the client's
292
- * own patch — after which the tail is shared: for each touched key, emit its
293
- * op, then resolve the old and new row and ask each index what its entry was
294
- * and what it becomes.
295
- *
296
- * A write the state moved under — a patch whose `before` the record no longer
297
- * holds, an update of a row that no longer matches, a delete or update of a
298
- * key the record does not hold — is emitted as a {@link DELTA_CONFLICT} entry
299
- * naming it, which sorts first, rather than failing the program: a caller
300
- * resubmits a conflict and gives up on a failure.
301
- *
302
- * The author's functions are bound as function values and CALLED, never
303
- * spliced: a spliced tree would be re-evaluated per reference and could
304
- * capture the wrong bindings.
305
- *
306
- * @param rec - the record, carrying its indexes
307
- * @param mut - the mutation declaration
308
- * @returns the program's IR bundle
309
- * @throws {Error} When the record's collection has no keyed delta, or an
310
- * `edit` / `patch` mutation has no body where one is required.
427
+ * Applying a patch verifies the row it was made against, and a row that no
428
+ * longer matches is a stale write — the conflict the engine reports when it
429
+ * applies an unindexed record's patch — emitted as the delta's conflict, its
430
+ * row after then `none`. Named in words every runtime shares: each one's own
431
+ * apply message is different.
311
432
  */
312
- export function buildMutationProgram(rec, mut) {
313
- const collection = rec.type;
314
- if (!hasKeyedDelta(rec.type)) {
315
- throw new Error(`e3.mutation.${mut.form} '${mut.name}' writes a delta, ` +
316
- `which addresses a Dict or a Set by key; record '${rec.name}' holds ${collection.type}.`);
317
- }
318
- const keyed = collection.type;
319
- const indexes = Object.values(rec.indexes)
320
- .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
321
- const delta = mutationDeltaType(deltaTargets(rec.type, indexes));
322
- const emitType = FunctionType([delta.key, delta.value], NullType);
323
- const primaryOps = patchOpsType(rec.type);
324
- const opsType = DictType(collection.key, primaryOps);
325
- const argTypes = mut.form === 'patch' ? [PatchType(rec.type)] : [...mut.argTypes];
326
- if (mut.form !== 'patch' && mut.fn === undefined) {
327
- throw new Error(`e3 mutation '${mut.name}' has no body to build its program from`);
328
- }
329
- return locationFree(() => East.function([rec.type, ...argTypes, emitType], NullType, ($, ...params) => {
330
- const state = params[0];
331
- const emit = params[params.length - 1];
332
- const args = params.slice(1, params.length - 1);
333
- const ops = $.let(new Map(), opsType);
334
- if (mut.form === 'patch') {
335
- collectOps($, state, args[0], ops, keyed, true, emit);
336
- }
337
- else if (mut.form === 'reduce') {
338
- const reduce = $.const(mut.fn);
339
- const next = $.let(reduce(state, ...args));
340
- collectOps($, state, East.diff(state, next), ops, keyed, false, emit);
341
- }
342
- else {
343
- foldEdits($, state, mut, args, ops, rec.type, emit);
344
- }
345
- const keyFns = indexes.map((index) => $.const(index.keyFn));
346
- const valueFns = indexes.map((index) => (index.valueFn === undefined ? undefined : $.const(index.valueFn)));
347
- // Each summary's change, summed over the write's rows by its key (#1039):
348
- // a key two rows share is one entry of the delta, emitted once all are in.
349
- const zero = $.const({ count: 0n, ms: 0n }, RecordSummaryTotalsType);
350
- const sums = new Map(indexes.flatMap((index, i) => (index.summary === undefined ? []
351
- : [[i, $.let(new Map(), DictType(index.keyType, RecordSummaryTotalsType))]])));
433
+ function rowChanges(types) {
434
+ const { valueType, stateType, rows, opsType, changesType, emitType } = types;
435
+ return East.function([stateType, opsType, emitType], changesType, ($, state, ops, emit) => {
436
+ const apply = $.const(rows.apply);
437
+ const changes = $.let(new Map(), changesType);
352
438
  $.for(ops, ($, op, key) => {
353
- $(emit(variant('primary', key), variant('primary', op)));
354
- if (indexes.length === 0)
355
- return;
356
439
  const held = $.let(state.tryGet(key));
357
- const next = $.let(none, OptionType(collection.value));
440
+ const next = $.let(none, OptionType(valueType));
441
+ const patched = $.let(none, OptionType(rows.patchType));
358
442
  $.match(op, {
359
443
  insert: ($, value) => {
360
444
  $.assign(next, some(value));
361
445
  },
362
446
  update: ($, patch) => {
363
- $.matchTag(held, 'some', ($, value) => {
364
- // Applying a patch verifies the row it was made against, and a
365
- // row that no longer matches is a stale write — the conflict the
366
- // engine reports when it applies an unindexed record's patch.
367
- // Named in words every runtime shares: each one's own apply
368
- // message is different.
369
- $.try(($) => {
370
- $.assign(next, some(East.applyPatch(value, patch)));
371
- }).catch(($) => {
372
- $(emit(variant(DELTA_CONFLICT, East.str `update of ${East.print(key)}, whose row no longer matches the patch`), variant(DELTA_CONFLICT, null)));
373
- });
447
+ $.match(held, {
448
+ some: ($, value) => {
449
+ $.try(($) => {
450
+ $.assign(next, some(apply(value, patch)));
451
+ $.assign(patched, some(patch));
452
+ }).catch(($) => {
453
+ $(emit(variant(DELTA_CONFLICT, East.str `update of ${East.print(key)}, whose row no longer matches the patch`), variant(DELTA_CONFLICT, null)));
454
+ });
455
+ },
456
+ none: () => { },
374
457
  });
375
458
  },
459
+ delete: () => { },
376
460
  });
377
- indexes.forEach((index, i) => {
378
- const sum = sums.get(i);
379
- if (sum === undefined)
380
- maintainIndex($, index, key, held, next, keyFns[i], valueFns[i], emit);
381
- else
382
- accumulateSummary($, sum, zero, keyFns[i], key, held, next);
461
+ $(changes.insert(key, { held, next, patch: patched }));
462
+ });
463
+ return changes;
464
+ });
465
+ }
466
+ /**
467
+ * An index's maintenance for one row (#1437): the changes a row going from
468
+ * `held` to `next` makes to the index, `(K, Option<V>, Option<V>,
469
+ * Option<RowPatch>) → Dict<EntryKey, Op>` — the ops a mutation delta's arm for
470
+ * the index holds, by entry.
471
+ *
472
+ * @remarks
473
+ * For an index of entries they are its patch, East's own ops for its
474
+ * collection: a row's entry gone a `delete`, one come an `insert`, and one
475
+ * whose value changed an `update` by the value's own patch. For a summary
476
+ * index they are the row's `add`s: under each key it moves, what it took away
477
+ * and gave, summed, and none where they cancel (#1039). A nested series index
478
+ * is maintained by the row's patch where one is given and says what it touched
479
+ * (#1434), and by the two rows whole otherwise; every other index compares the
480
+ * rows' entries whole.
481
+ *
482
+ * A write's program runs it on each row the write touches, and a binding
483
+ * carries it, so a page previews a drafted row's Save with the function the
484
+ * commit runs.
485
+ *
486
+ * @param rec - The record, a Dict
487
+ * @param index - One of its indexes, as it is built ({@link builtIndex})
488
+ * @returns The function. The patch, where given, is the row's update, so the
489
+ * row is present before and after.
490
+ * @throws {Error} When the record is not a Dict
491
+ */
492
+ export function indexMaintenance(rec, index) {
493
+ const { keyType, valueType } = dictEntry(rec.type, `index '${index.name}' of record '${rec.name}'`);
494
+ const rowPatchType = East.patchesFor(valueType).patchType;
495
+ return summed(index) ? summaryMaintenance(index, keyType, valueType, rowPatchType) : entriesMaintenance(index, keyType, valueType, rowPatchType);
496
+ }
497
+ /** {@link indexMaintenance} for an index of entries — a nested series index or any other but a summary — at a Dict record's types. */
498
+ function entriesMaintenance(index, keyType, valueType, rowPatchType) {
499
+ return index.nested !== undefined ? nestedMaintenance(index, index.nested.byPatch, keyType, valueType, rowPatchType)
500
+ : entryMaintenance(index, keyType, valueType, rowPatchType);
501
+ }
502
+ /** What {@link indexMaintenance} gives for an index, by entry: its collection's patch ops, or a summary's `add`. */
503
+ function maintenanceOpsType(index, keyType) {
504
+ // A summary's entry stands for every row of its key, so its `k` is Null.
505
+ const k = summed(index) ? NullType : keyType;
506
+ const op = summed(index) ? RecordSummaryOpType : patchOpsType(indexCollectionType(k, index.keyType, index.valueType));
507
+ return DictType(indexEntryKeyType(k, index.keyType), op);
508
+ }
509
+ /**
510
+ * The maintenance of an index of entries for one row ({@link indexMaintenance}):
511
+ * its entries before and after, compared.
512
+ *
513
+ * @remarks
514
+ * An entry is `{ik, k}`, so a row moving from one index key to another is a
515
+ * delete at the old entry and an insert at the new one — not an update. Only
516
+ * an entry that keeps its index key and whose projection changed is an update,
517
+ * and an index carrying no projection, whose projection is Null, has none of
518
+ * those at all. The three sets are disjoint, so no entry changes twice.
519
+ */
520
+ function entryMaintenance(index, keyType, valueType, rowPatchType) {
521
+ const opsType = maintenanceOpsType(index, keyType);
522
+ const keys = indexKeys(index, keyType, valueType);
523
+ const projection = indexProjection(index, keyType, valueType);
524
+ const projected = East.patchesFor(index.valueType);
525
+ // A row's entries: its index keys and its projection; none for no row.
526
+ const entriesType = StructType({ keys: SetType(index.keyType), value: OptionType(index.valueType) });
527
+ const entriesOf = East.function([keyType, OptionType(valueType)], entriesType, ($, key, row) => {
528
+ const keysOf = $.const(keys);
529
+ const project = $.const(projection);
530
+ $.match(row, {
531
+ some: ($, value) => {
532
+ $.return({ keys: keysOf(key, value), value: some(project(key, value)) });
533
+ },
534
+ none: () => { },
535
+ });
536
+ return { keys: new Set([]), value: none };
537
+ });
538
+ return East.function([keyType, OptionType(valueType), OptionType(valueType), OptionType(rowPatchType)], opsType, ($, key, held, next, _patch) => {
539
+ const entries = $.const(entriesOf);
540
+ const diff = $.const(projected.diff);
541
+ const ops = $.let(new Map(), opsType);
542
+ const before = $.let(entries(key, held));
543
+ const after = $.let(entries(key, next));
544
+ $.for(before.keys.difference(after.keys), ($, ik) => {
545
+ $(ops.insert({ ik, k: key }, variant('delete', before.value.unwrap())));
546
+ });
547
+ $.for(after.keys.difference(before.keys), ($, ik) => {
548
+ $(ops.insert({ ik, k: key }, variant('insert', after.value.unwrap())));
549
+ });
550
+ $.for(before.keys.intersection(after.keys), ($, ik) => {
551
+ const was = $.let(before.value.unwrap());
552
+ const is = $.let(after.value.unwrap());
553
+ $.if(East.notEqual(was, is), ($) => {
554
+ $(ops.insert({ ik, k: key }, variant('update', diff(was, is))));
383
555
  });
384
556
  });
385
- // Each summary's non-zero changes: what its total under each key gains,
386
- // which the apply adds to the total it holds.
387
- indexes.forEach((index, i) => {
388
- const sum = sums.get(i);
389
- if (sum === undefined)
390
- return;
391
- $.for(sum, ($, change, ik) => {
392
- $.if(change.count.notEqual(0n).or(() => change.ms.notEqual(0n)), ($) => {
393
- $(emit(variant(index.name, { ik, k: null }), variant(index.name, variant('add', change))));
557
+ return ops;
558
+ });
559
+ }
560
+ /**
561
+ * A nested series index's maintenance for one row ({@link indexMaintenance},
562
+ * #1434): its entries before and after compared by key — one gone a delete,
563
+ * one come an insert, one whose value changed an update. By the row's patch
564
+ * where one is given: only the entries of what it touched, before and after,
565
+ * are compared — unless a replace on the way leaves the row to be compared
566
+ * whole, as a row inserted or deleted is. Both give the same ops. The entries'
567
+ * keys hold the row's own key, so no two rows share one.
568
+ */
569
+ function nestedMaintenance(index, byPatchFn, keyType, valueType, rowPatchType) {
570
+ const opsType = maintenanceOpsType(index, keyType);
571
+ const entriesType = DictType(index.keyType, index.valueType);
572
+ const changedType = StructType({ before: entriesType, after: entriesType });
573
+ const entries = functionAt(index.keyFn, [keyType, valueType], entriesType);
574
+ const byPatch = functionAt(byPatchFn, [keyType, valueType, valueType, rowPatchType], NestedPatchedType(entriesType));
575
+ const values = East.patchesFor(index.valueType);
576
+ // A row's entries; none for no row.
577
+ const entriesOf = East.function([keyType, OptionType(valueType)], entriesType, ($, key, row) => {
578
+ const of = $.const(entries);
579
+ $.match(row, {
580
+ some: ($, value) => {
581
+ $.return(of(key, value));
582
+ },
583
+ none: () => { },
584
+ });
585
+ return new Map();
586
+ });
587
+ // A row's entries before and after: by its patch where one is given and can say what it touched; whole otherwise.
588
+ const changedOf = East.function([keyType, OptionType(valueType), OptionType(valueType), OptionType(rowPatchType)], changedType, ($, key, held, next, patch) => {
589
+ const of = $.const(entriesOf);
590
+ const patched = $.const(byPatch);
591
+ $.match(patch, {
592
+ some: ($, rowPatch) => {
593
+ $.match(patched(key, held.unwrap(), next.unwrap(), rowPatch), {
594
+ changed: ($, both) => {
595
+ $.return(both);
596
+ },
597
+ whole: () => { },
394
598
  });
599
+ },
600
+ none: () => { },
601
+ });
602
+ return { before: of(key, held), after: of(key, next) };
603
+ });
604
+ return East.function([keyType, OptionType(valueType), OptionType(valueType), OptionType(rowPatchType)], opsType, ($, key, held, next, patch) => {
605
+ const changedFn = $.const(changedOf);
606
+ const diff = $.const(values.diff);
607
+ const ops = $.let(new Map(), opsType);
608
+ const both = $.let(changedFn(key, held, next, patch));
609
+ const before = $.let(both.before);
610
+ const after = $.let(both.after);
611
+ $.for(before, ($, was, ik) => {
612
+ $.match(after.tryGet(ik), {
613
+ none: ($) => {
614
+ $(ops.insert({ ik, k: key }, variant('delete', was)));
615
+ },
616
+ some: ($, is) => {
617
+ $.if(East.notEqual(was, is), ($) => {
618
+ $(ops.insert({ ik, k: key }, variant('update', diff(was, is))));
619
+ });
620
+ },
395
621
  });
396
622
  });
397
- return null;
398
- }));
623
+ $.for(after, ($, is, ik) => {
624
+ $.if(before.has(ik).not(), ($) => {
625
+ $(ops.insert({ ik, k: key }, variant('insert', is)));
626
+ });
627
+ });
628
+ return ops;
629
+ });
399
630
  }
400
631
  /**
401
- * Sums one touched row's change to a summary (#1039): its old row's
402
- * contributions taken away, its new row's given, under each key.
632
+ * A summary index's maintenance for one row ({@link indexMaintenance},
633
+ * #1039): under each key the row moves, what it took away and what it gives,
634
+ * summed, as an `add` — and none where the two cancel.
403
635
  *
404
636
  * @remarks
405
637
  * A write reads the record, never the summary, so it says what changed rather
406
- * than what a total becomes; the apply adds it to the total held. The change
407
- * of a key two rows share is summed here, so the delta holds it once.
638
+ * than what a total becomes; the apply adds it to the total held.
408
639
  */
409
- function accumulateSummary($, sums, zero, contribute, key, held, next) {
410
- const add = (sign) => ($, row) => {
411
- $.for(contribute(key, row), ($, totals, ik) => {
412
- const was = $.let(sums.get(ik, () => zero));
413
- $(sums.insertOrUpdate(ik, {
414
- count: was.count.add(totals.count.multiply(sign)),
415
- ms: was.ms.add(totals.ms.multiply(sign)),
416
- }));
640
+ function summaryMaintenance(index, keyType, valueType, rowPatchType) {
641
+ // A summary's entry stands for every row of its key, so its `k` is Null.
642
+ const opsType = DictType(indexEntryKeyType(NullType, index.keyType), RecordSummaryOpType);
643
+ const totalsType = DictType(index.keyType, RecordSummaryTotalsType);
644
+ const contributions = functionAt(index.keyFn, [keyType, valueType], totalsType);
645
+ return East.function([keyType, OptionType(valueType), OptionType(valueType), OptionType(rowPatchType)], opsType, ($, key, held, next, _patch) => {
646
+ const contribute = $.const(contributions);
647
+ const signed = $.const(PROGRAM_FNS.signedTotals);
648
+ const add = $.const(PROGRAM_FNS.addedTotals);
649
+ const sums = $.let(new Map(), totalsType);
650
+ $.match(held, {
651
+ some: ($, row) => {
652
+ $(sums.unionInPlace(contribute(key, row).map(($, part) => signed(part, -1n)), ($, was, part) => add(was, part)));
653
+ },
654
+ none: () => { },
417
655
  });
418
- };
419
- $.matchTag(held, 'some', add(-1n));
420
- $.matchTag(next, 'some', add(1n));
656
+ $.match(next, {
657
+ some: ($, row) => {
658
+ $(sums.unionInPlace(contribute(key, row), ($, was, part) => add(was, part)));
659
+ },
660
+ none: () => { },
661
+ });
662
+ const ops = $.let(new Map(), opsType);
663
+ $.for(sums, ($, change, ik) => {
664
+ $.if(change.count.notEqual(0n).or(() => change.ms.notEqual(0n)), ($) => {
665
+ $(ops.insert({ ik, k: null }, variant('add', change)));
666
+ });
667
+ });
668
+ return ops;
669
+ });
670
+ }
671
+ /**
672
+ * One index's changes for a write's touched rows: `(Changes, Emit) → Null`,
673
+ * its maintenance ({@link indexMaintenance}) run on each row, and each op it
674
+ * gives emitted under the index. A summary's `add`s are summed across the rows
675
+ * first, so the delta holds a key once, and never a change of nothing.
676
+ */
677
+ function indexDelta(index, types) {
678
+ const { keyType, valueType, rows, changesType, emitType } = types;
679
+ if (!summed(index)) {
680
+ const maintain = entriesMaintenance(index, keyType, valueType, rows.patchType);
681
+ return East.function([changesType, emitType], NullType, ($, changes, emit) => {
682
+ const maintainFn = $.const(maintain);
683
+ $.for(changes, ($, change, key) => {
684
+ $.for(maintainFn(key, change.held, change.next, change.patch), ($, op, entry) => {
685
+ $(emit(variant(index.name, entry), variant(index.name, op)));
686
+ });
687
+ });
688
+ });
689
+ }
690
+ const maintain = summaryMaintenance(index, keyType, valueType, rows.patchType);
691
+ const sumsType = DictType(indexEntryKeyType(NullType, index.keyType), RecordSummaryTotalsType);
692
+ return East.function([changesType, emitType], NullType, ($, changes, emit) => {
693
+ const maintainFn = $.const(maintain);
694
+ const add = $.const(PROGRAM_FNS.addedTotals);
695
+ const sums = $.let(new Map(), sumsType);
696
+ $.for(changes, ($, change, key) => {
697
+ $.for(maintainFn(key, change.held, change.next, change.patch), ($, op, entry) => {
698
+ $(sums.insertOrUpdate(entry, op.unwrap('add'), ($, was, part) => add(was, part)));
699
+ });
700
+ });
701
+ $.for(sums, ($, change, entry) => {
702
+ $.if(change.count.notEqual(0n).or(() => change.ms.notEqual(0n)), ($) => {
703
+ $(emit(variant(index.name, entry), variant(index.name, variant('add', change))));
704
+ });
705
+ });
706
+ });
707
+ }
708
+ /**
709
+ * Every index's changes for a write's touched rows, each index in turn:
710
+ * `(Changes, Emit) → Null`, a function calling the ones before it and then
711
+ * its own index's.
712
+ */
713
+ function indexesChanges(indexes, types) {
714
+ const { changesType, emitType } = types;
715
+ return indexes.reduce((earlier, index) => {
716
+ const own = indexDelta(index, types);
717
+ return East.function([changesType, emitType], NullType, ($, changes, emit) => {
718
+ const before = $.const(earlier);
719
+ const these = $.const(own);
720
+ $(before(changes, emit));
721
+ $(these(changes, emit));
722
+ });
723
+ }, East.function([changesType, emitType], NullType, () => null));
724
+ }
725
+ /** A write's own ops, each under its key: `(Ops, Emit) → Null`. */
726
+ function primaryOps(opsType, emitType) {
727
+ return East.function([opsType, emitType], NullType, ($, ops, emit) => {
728
+ $.for(ops, ($, op, key) => {
729
+ $(emit(variant('primary', key), variant('primary', op)));
730
+ });
731
+ });
732
+ }
733
+ /** The delta of a write whose record has no indexes, once its ops are known: `(State, Ops, Emit) → Null`, each op under its key. */
734
+ function primaryApply(stateType, opsType, emitType) {
735
+ const primary = primaryOps(opsType, emitType);
736
+ return East.function([stateType, opsType, emitType], NullType, ($, _state, ops, emit) => {
737
+ const own = $.const(primary);
738
+ $(own(ops, emit));
739
+ });
740
+ }
741
+ /**
742
+ * The delta of a Dict record's write, once its ops are known: `(State, Ops,
743
+ * Emit) → Null`, each op under its key and, where the record has indexes, each
744
+ * index's changes for the rows the ops touch.
745
+ */
746
+ function dictApply(indexes, types) {
747
+ const { stateType, opsType, emitType } = types;
748
+ if (indexes.length === 0)
749
+ return primaryApply(stateType, opsType, emitType);
750
+ const primary = primaryOps(opsType, emitType);
751
+ const touched = rowChanges(types);
752
+ const maintain = indexesChanges(indexes, types);
753
+ return East.function([stateType, opsType, emitType], NullType, ($, state, ops, emit) => {
754
+ const own = $.const(primary);
755
+ const rows = $.const(touched);
756
+ const indexed = $.const(maintain);
757
+ $(own(ops, emit));
758
+ const changes = $.let(rows(state, ops, emit));
759
+ $(indexed(changes, emit));
760
+ });
421
761
  }
422
762
  /**
423
763
  * Runs an `edit` body against a capability that folds its writes, then resolves
424
- * the fold into the per-key ops the tail shares.
764
+ * the fold into per-key ops: `(State, Args, Emit) → Ops`.
425
765
  *
426
766
  * @remarks
427
767
  * `set` is the reason the fold has its own op type: whether it becomes an
@@ -431,147 +771,315 @@ function accumulateSummary($, sums, zero, contribute, key, held, next) {
431
771
  * delta's conflict naming the key, as an apply would name it, rather than
432
772
  * reaching the apply as an op that cannot be represented.
433
773
  */
434
- function foldEdits($, state, mut, args, ops, recordType, emit) {
435
- const { key: keyType, value: valueType } = recordType;
436
- const edits = $.let(new Map(), DictType(keyType, editOpsType(valueType)));
437
- const capability = $.const({
438
- set: East.function([keyType, valueType], NullType, ($, key, value) => {
439
- $(edits.insertOrUpdate(key, variant('set', value)));
440
- }),
441
- delete: East.function([keyType], NullType, ($, key) => {
442
- $.if(state.has(key), ($) => {
443
- $(edits.insertOrUpdate(key, variant('delete', null)));
444
- }).else(($) => {
445
- // The record does not hold the key, so a pending `set` of it is this
446
- // body creating it: deleting it again leaves the record as it was, and
447
- // there is nothing to write. Anything else is a delete of a key the
448
- // record does not hold, which resolving refuses.
449
- $.match(edits.tryGet(key), {
450
- some: ($, prior) => {
451
- $.match(prior, {
452
- set: ($) => {
453
- $(edits.delete(key));
454
- },
455
- delete: ($) => {
456
- $(edits.insertOrUpdate(key, variant('delete', null)));
457
- },
458
- update: ($) => {
459
- $(edits.insertOrUpdate(key, variant('delete', null)));
460
- },
461
- });
462
- },
463
- none: ($) => {
464
- $(edits.insertOrUpdate(key, variant('delete', null)));
465
- },
466
- });
467
- });
468
- }),
469
- update: East.function([keyType, PatchType(valueType)], NullType, ($, key, patch) => {
470
- $.match(edits.tryGet(key), {
471
- none: ($) => {
472
- $(edits.insertOrUpdate(key, variant('update', patch)));
774
+ function editOps(fn, argTypes, types) {
775
+ const { keyType, valueType, stateType, rows, opsType, emitType } = types;
776
+ // The capability, typed as the ops are: its `update` takes the row's patch, checked to be East's own.
777
+ const editType = StructType({
778
+ set: FunctionType([keyType, valueType], NullType),
779
+ delete: FunctionType([keyType], NullType),
780
+ update: FunctionType([keyType, rows.patchType], NullType),
781
+ });
782
+ const declared = stateType;
783
+ if (!sameEastType(editType, editTypeOf(declared))) {
784
+ throw new Error(`an edit's capability over ${printType(stateType)} is not ${printType(editTypeOf(declared))}`);
785
+ }
786
+ const editsType = DictType(keyType, editOpsType(valueType, rows));
787
+ const argsType = argumentsType(argTypes);
788
+ const body = callWithArguments(fn, stateType, argTypes, [editType], NullType);
789
+ const resolve = East.function([stateType, editsType, emitType], opsType, ($, state, edits, emit) => {
790
+ const diff = $.const(rows.diff);
791
+ const ops = $.let(new Map(), opsType);
792
+ $.for(edits, ($, edit, key) => {
793
+ const held = $.let(state.tryGet(key));
794
+ $.match(edit, {
795
+ set: ($, value) => {
796
+ $.match(held, {
797
+ some: ($, prior) => {
798
+ // A `set` of what the record already holds changed nothing, and a
799
+ // delta says what changed: an op here would re-cut the segment to
800
+ // the bytes it already has and count itself in the history.
801
+ $.if(East.notEqual(prior, value), ($) => {
802
+ $(ops.insertOrUpdate(key, variant('update', diff(prior, value))));
803
+ });
804
+ },
805
+ none: ($) => {
806
+ $(ops.insertOrUpdate(key, variant('insert', value)));
807
+ },
808
+ });
473
809
  },
474
- some: ($, prior) => {
475
- $.match(prior, {
476
- set: ($, value) => {
477
- $(edits.insertOrUpdate(key, variant('set', East.applyPatch(value, patch))));
810
+ delete: ($) => {
811
+ $.match(held, {
812
+ some: ($, prior) => {
813
+ $(ops.insertOrUpdate(key, variant('delete', prior)));
814
+ },
815
+ none: ($) => {
816
+ $(emit(variant(DELTA_CONFLICT, East.str `delete of ${East.print(key)}, which the record does not hold`), variant(DELTA_CONFLICT, null)));
478
817
  },
479
- update: ($, first) => {
480
- $(edits.insertOrUpdate(key, variant('update', East.composePatch(first, patch, valueType))));
818
+ });
819
+ },
820
+ update: ($, patch) => {
821
+ $.match(held, {
822
+ some: ($) => {
823
+ $(ops.insertOrUpdate(key, variant('update', patch)));
481
824
  },
482
- delete: ($) => {
483
- $.error(East.str `update of ${East.print(key)}, which this mutation already deleted`);
825
+ none: ($) => {
826
+ $(emit(variant(DELTA_CONFLICT, East.str `update of ${East.print(key)}, which the record does not hold`), variant(DELTA_CONFLICT, null)));
484
827
  },
485
828
  });
486
829
  },
487
830
  });
488
- }),
489
- }, editTypeOf(recordType));
490
- const body = $.const(mut.fn);
491
- $(body(state, ...args, capability));
492
- $.for(edits, ($, edit, key) => {
493
- const held = $.let(state.tryGet(key));
494
- $.match(edit, {
495
- set: ($, value) => {
496
- $.match(held, {
497
- some: ($, prior) => {
498
- // A `set` of what the record already holds changed nothing, and a
499
- // delta says what changed: an op here would re-cut the segment to
500
- // the bytes it already has and count itself in the history.
501
- $.if(East.notEqual(prior, value), ($) => {
502
- $(ops.insertOrUpdate(key, variant('update', East.diff(prior, value))));
503
- });
504
- },
831
+ });
832
+ return ops;
833
+ });
834
+ return East.function([stateType, argsType, emitType], opsType, ($, state, args, emit) => {
835
+ const apply = $.const(rows.apply);
836
+ const compose = $.const(rows.compose);
837
+ const edits = $.let(new Map(), editsType);
838
+ const capability = $.const({
839
+ set: East.function([keyType, valueType], NullType, ($, key, value) => {
840
+ $(edits.insertOrUpdate(key, variant('set', value)));
841
+ }),
842
+ delete: East.function([keyType], NullType, ($, key) => {
843
+ $.if(state.has(key), ($) => {
844
+ $(edits.insertOrUpdate(key, variant('delete', null)));
845
+ }).else(($) => {
846
+ // The record does not hold the key, so a pending `set` of it is this
847
+ // body creating it: deleting it again leaves the record as it was, and
848
+ // there is nothing to write. Anything else is a delete of a key the
849
+ // record does not hold, which resolving refuses.
850
+ $.match(edits.tryGet(key), {
851
+ some: ($, prior) => {
852
+ $.match(prior, {
853
+ set: ($) => {
854
+ $(edits.delete(key));
855
+ },
856
+ delete: ($) => {
857
+ $(edits.insertOrUpdate(key, variant('delete', null)));
858
+ },
859
+ update: ($) => {
860
+ $(edits.insertOrUpdate(key, variant('delete', null)));
861
+ },
862
+ });
863
+ },
864
+ none: ($) => {
865
+ $(edits.insertOrUpdate(key, variant('delete', null)));
866
+ },
867
+ });
868
+ });
869
+ }),
870
+ update: East.function([keyType, rows.patchType], NullType, ($, key, patch) => {
871
+ $.match(edits.tryGet(key), {
505
872
  none: ($) => {
506
- $(ops.insertOrUpdate(key, variant('insert', value)));
873
+ $(edits.insertOrUpdate(key, variant('update', patch)));
507
874
  },
508
- });
509
- },
510
- delete: ($) => {
511
- $.match(held, {
512
875
  some: ($, prior) => {
513
- $(ops.insertOrUpdate(key, variant('delete', prior)));
514
- },
515
- none: ($) => {
516
- $(emit(variant(DELTA_CONFLICT, East.str `delete of ${East.print(key)}, which the record does not hold`), variant(DELTA_CONFLICT, null)));
876
+ $.match(prior, {
877
+ set: ($, value) => {
878
+ $(edits.insertOrUpdate(key, variant('set', apply(value, patch))));
879
+ },
880
+ update: ($, first) => {
881
+ $(edits.insertOrUpdate(key, variant('update', compose(first, patch))));
882
+ },
883
+ delete: ($) => {
884
+ $.error(East.str `update of ${East.print(key)}, which this mutation already deleted`);
885
+ },
886
+ });
517
887
  },
518
888
  });
889
+ }),
890
+ }, editType);
891
+ const run = $.const(body);
892
+ const resolveFn = $.const(resolve);
893
+ $(run(state, args, capability));
894
+ return resolveFn(state, edits, emit);
895
+ });
896
+ }
897
+ /**
898
+ * Folds a patch of a Set record into per-key ops: `(State, Patch, verify,
899
+ * Emit) → Ops`, as {@link dictPatchOps} folds a Dict's.
900
+ */
901
+ function setPatchOps(keyType, emitType) {
902
+ const stateType = SetType(keyType);
903
+ const patchType = PatchType(stateType);
904
+ const opsType = patchType.cases.patch;
905
+ return East.function([stateType, patchType, BooleanType, emitType], opsType, ($, state, patch, verify, emit) => {
906
+ const ops = $.let(new Map(), opsType);
907
+ $.match(patch, {
908
+ unchanged: () => { },
909
+ patch: ($, entries) => {
910
+ $.assign(ops, entries);
519
911
  },
520
- update: ($, patch) => {
521
- $.match(held, {
522
- some: ($) => {
523
- $(ops.insertOrUpdate(key, variant('update', patch)));
524
- },
525
- none: ($) => {
526
- $(emit(variant(DELTA_CONFLICT, East.str `update of ${East.print(key)}, which the record does not hold`), variant(DELTA_CONFLICT, null)));
527
- },
912
+ replace: ($, whole) => {
913
+ $.if(verify.and(() => East.notEqual(whole.before, state)), ($) => {
914
+ $(emit(variant(DELTA_CONFLICT, 'the patch replaces a state the record no longer holds'), variant(DELTA_CONFLICT, null)));
915
+ });
916
+ $.for(state, ($, key) => {
917
+ $.if(whole.after.has(key).not(), ($) => {
918
+ $(ops.insertOrUpdate(key, variant('delete', null)));
919
+ });
920
+ });
921
+ $.for(whole.after, ($, key) => {
922
+ $.if(state.has(key).not(), ($) => {
923
+ $(ops.insertOrUpdate(key, variant('insert', null)));
924
+ });
528
925
  });
529
926
  },
530
927
  });
928
+ return ops;
531
929
  });
532
930
  }
931
+ /** A Dict record's write steps. */
932
+ function dictSteps(types, indexes) {
933
+ const { diff } = East.patchesFor(types.stateType);
934
+ return {
935
+ stateType: types.stateType,
936
+ patchType: types.patchType,
937
+ opsType: types.opsType,
938
+ emitType: types.emitType,
939
+ diff,
940
+ patchOps: dictPatchOps(types),
941
+ apply: dictApply(indexes, types),
942
+ };
943
+ }
944
+ /** A Set record's write steps: it is indexed by nothing, so its delta is its own ops. */
945
+ function setSteps(keyType) {
946
+ const stateType = SetType(keyType);
947
+ const patchType = PatchType(stateType);
948
+ const opsType = patchType.cases.patch;
949
+ const emitType = deltaEmitType(stateType, []);
950
+ const { diff } = East.patchesFor(stateType);
951
+ return {
952
+ stateType,
953
+ patchType,
954
+ opsType,
955
+ emitType,
956
+ diff,
957
+ patchOps: setPatchOps(keyType, emitType),
958
+ apply: primaryApply(stateType, opsType, emitType),
959
+ };
960
+ }
961
+ /** A mutation's body; a `patch` mutation has none. */
962
+ function bodyOf(mut) {
963
+ if (mut.fn === undefined)
964
+ throw new Error(`e3 mutation '${mut.name}' has no body to build its program from`);
965
+ return mut.fn;
966
+ }
533
967
  /**
534
- * Emits one index's entry changes for one touched row.
968
+ * A reducer's ops: `(State, Args, Emit) → Ops`, the per-key ops a diff of the
969
+ * whole new state it returns gives — the diff's `before` is the state, so it
970
+ * needs no check.
971
+ */
972
+ function reduceOps(fn, argTypes, steps) {
973
+ const { stateType, opsType, emitType, diff, patchOps } = steps;
974
+ const reduce = callWithArguments(fn, stateType, argTypes, [], stateType);
975
+ const argsType = argumentsType(argTypes);
976
+ return East.function([stateType, argsType, emitType], opsType, ($, state, args, emit) => {
977
+ const reduceFn = $.const(reduce);
978
+ const diffFn = $.const(diff);
979
+ const opsOf = $.const(patchOps);
980
+ const next = $.let(reduceFn(state, args));
981
+ return opsOf(state, diffFn(state, next), false, emit);
982
+ });
983
+ }
984
+ /**
985
+ * The program every write form runs: `(State, …Args | Patch, Emit) => Null`.
535
986
  *
536
987
  * @remarks
537
- * An index entry is `{ik, k}`, so a row moving from one index key to another is
538
- * a delete at the old entry and an insert at the new one — not an update. Only
539
- * an entry that keeps its index key and whose covering projection changed is an
540
- * update, and an index carrying no projection has none of those at all. The
541
- * three sets are disjoint and `k` is this row's, so no entry is emitted twice.
988
+ * One program, three forms, one output — the mutation delta, emitted entry by
989
+ * entry as it is computed, in any order: the runner writes a `dict` output
990
+ * through its RunSorter, which sorts it. e3 stores the delta as segments and
991
+ * applies it one target segment at a time; it never evaluates the author's
992
+ * East itself, which is what keeps one rule for where user code runs and gives
993
+ * the three runtimes something to agree on byte for byte.
994
+ *
995
+ * The three forms differ only in how the per-key ops are reached — a diff of
996
+ * the reducer's result, the folded writes of an `edit` body, or the client's
997
+ * own patch — after which the rest is shared: each op emitted under its key,
998
+ * then each touched key's old and new row, and each index asked what its
999
+ * entries were and what they become.
1000
+ *
1001
+ * A write the state moved under — a patch whose `before` the record no longer
1002
+ * holds, an update of a row that no longer matches, a delete or update of a
1003
+ * key the record does not hold — is emitted as a {@link DELTA_CONFLICT} entry
1004
+ * naming it, which sorts first, rather than failing the program: a caller
1005
+ * resubmits a conflict and gives up on a failure.
1006
+ *
1007
+ * @param rec - the record, carrying its indexes
1008
+ * @param mut - the mutation declaration
1009
+ * @returns the program's IR bundle
1010
+ * @throws {Error} When the record's collection has no keyed delta, an `edit`
1011
+ * mutation writes a Set, or an `edit` / `reduce` mutation has no body.
542
1012
  */
543
- function maintainIndex($, index, key, held, next, indexKey, project, emit) {
544
- const heldKeys = $.let(new Set(), SetType(index.keyType));
545
- const nextKeys = $.let(new Set(), SetType(index.keyType));
546
- const heldValue = $.let(none, OptionType(index.valueType));
547
- const nextValue = $.let(none, OptionType(index.valueType));
548
- const gather = (keys, value) => ($, row) => {
549
- if (index.multi) {
550
- $.for(indexKey(key, row), ($, ik) => {
551
- $(keys.insert(ik));
552
- });
553
- }
554
- else {
555
- $(keys.insert(indexKey(key, row)));
556
- }
557
- $.assign(value, some(project === undefined ? null : project(key, row)));
558
- };
559
- $.matchTag(held, 'some', gather(heldKeys, heldValue));
560
- $.matchTag(next, 'some', gather(nextKeys, nextValue));
561
- $.for(heldKeys.difference(nextKeys), ($, ik) => {
562
- $(emit(variant(index.name, { ik, k: key }), variant(index.name, variant('delete', heldValue.unwrap()))));
563
- });
564
- $.for(nextKeys.difference(heldKeys), ($, ik) => {
565
- $(emit(variant(index.name, { ik, k: key }), variant(index.name, variant('insert', nextValue.unwrap()))));
566
- });
567
- if (project === undefined)
568
- return;
569
- $.for(heldKeys.intersection(nextKeys), ($, ik) => {
570
- const before = $.let(heldValue.unwrap());
571
- const after = $.let(nextValue.unwrap());
572
- $.if(East.notEqual(before, after), ($) => {
573
- $(emit(variant(index.name, { ik, k: key }), variant(index.name, variant('update', East.diff(before, after)))));
1013
+ export function buildMutationProgram(rec, mut) {
1014
+ const recordType = rec.type;
1015
+ if (recordType.type !== 'Dict' && recordType.type !== 'Set') {
1016
+ throw new Error(`e3.record '${rec.name}': mutation.${mut.form} '${mut.name}' writes a delta, ` +
1017
+ `which addresses a Dict or a Set by key, and the record holds ${recordType.type}.`);
1018
+ }
1019
+ // A Set record is indexed by nothing, and written by a patch or a reducer: an edit writes a Dict.
1020
+ if (recordType.type === 'Set' && mut.form === 'edit') {
1021
+ throw new Error(`e3.record '${rec.name}': mutation.edit '${mut.name}' writes a Dict record, and the record holds a Set`);
1022
+ }
1023
+ if (mut.form !== 'patch')
1024
+ bodyOf(mut);
1025
+ return locationFree(() => writeProgram(rec, mut));
1026
+ }
1027
+ /**
1028
+ * A write's program (see {@link buildMutationProgram}): its record's steps,
1029
+ * its form's ops, and the program the runner calls.
1030
+ */
1031
+ function writeProgram(rec, mut) {
1032
+ const recordType = rec.type;
1033
+ let steps;
1034
+ let argumentOps;
1035
+ if (recordType.type === 'Dict') {
1036
+ const indexes = Object.values(rec.indexes).map((index) => builtIndex(rec, index)).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1037
+ const types = dictWrite(recordType.key, recordType.value, indexes);
1038
+ steps = dictSteps(types, indexes);
1039
+ argumentOps = mut.form === 'edit' ? editOps(bodyOf(mut), mut.argTypes, types)
1040
+ : mut.form === 'reduce' ? reduceOps(bodyOf(mut), mut.argTypes, steps)
1041
+ : undefined;
1042
+ }
1043
+ else if (recordType.type === 'Set') {
1044
+ steps = setSteps(recordType.key);
1045
+ argumentOps = mut.form === 'reduce' ? reduceOps(bodyOf(mut), mut.argTypes, steps) : undefined;
1046
+ }
1047
+ else {
1048
+ throw new Error(`a write addresses a Dict or a Set by key, not ${printType(recordType)}`);
1049
+ }
1050
+ const { stateType, patchType, emitType, patchOps, apply } = steps;
1051
+ if (argumentOps === undefined) {
1052
+ // A patch: the client's own, checked against the state it was made from.
1053
+ return East.function([stateType, patchType, emitType], NullType, ($, state, patch, emit) => {
1054
+ const opsOf = $.const(patchOps);
1055
+ const applyFn = $.const(apply);
1056
+ const ops = $.let(opsOf(state, patch, true, emit));
1057
+ $(applyFn(state, ops, emit));
574
1058
  });
575
- });
1059
+ }
1060
+ const opsOfArguments = argumentOps;
1061
+ const argsType = argumentsType(mut.argTypes);
1062
+ return programOverArguments(stateType, mut.argTypes, emitType, East.function([stateType, argsType, emitType], NullType, ($, state, args, emit) => {
1063
+ const opsOf = $.const(opsOfArguments);
1064
+ const applyFn = $.const(apply);
1065
+ const ops = $.let(opsOf(state, args, emit));
1066
+ $(applyFn(state, ops, emit));
1067
+ }));
576
1068
  }
1069
+ // ── The functions, each built the first time it is read ──────────────────────
1070
+ /**
1071
+ * A summary's write's East functions, each built the first time it is read,
1072
+ * with no location captured ({@link lazyBuilds}, #1466): importing the SDK
1073
+ * builds none of them.
1074
+ */
1075
+ export const PROGRAM_FNS = lazyBuilds({
1076
+ /** `(totals, sign) → sign × totals`: a row's contribution given, `1`, or taken away, `−1`. */
1077
+ get signedTotals() {
1078
+ return East.function([RecordSummaryTotalsType, IntegerType], RecordSummaryTotalsType, (_$, totals, sign) => ({ count: totals.count.multiply(sign), ms: totals.ms.multiply(sign) }));
1079
+ },
1080
+ /** `(a, b) → a + b`: two changes to one key's totals. */
1081
+ get addedTotals() {
1082
+ return East.function([RecordSummaryTotalsType, RecordSummaryTotalsType], RecordSummaryTotalsType, (_$, a, b) => ({ count: a.count.add(b.count), ms: a.ms.add(b.ms) }));
1083
+ },
1084
+ });
577
1085
  //# sourceMappingURL=record-programs.js.map