@eidos.space/eidos-file 0.1.0 → 1.0.0

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 (43) hide show
  1. package/DEVELOPER_PLATFORM.md +49 -53
  2. package/README.md +66 -99
  3. package/dist/adapter-contract-B3p-48Yb.d.mts +1149 -0
  4. package/dist/adapter-contract-B3p-48Yb.d.mts.map +1 -0
  5. package/dist/better-sqlite3.d.mts +64 -3
  6. package/dist/better-sqlite3.d.mts.map +1 -1
  7. package/dist/better-sqlite3.mjs +387 -14
  8. package/dist/better-sqlite3.mjs.map +1 -1
  9. package/dist/browser.d.mts +4 -3
  10. package/dist/browser.d.mts.map +1 -1
  11. package/dist/browser.mjs +30 -11
  12. package/dist/browser.mjs.map +1 -1
  13. package/dist/csv-WEud-i_H.mjs +376 -0
  14. package/dist/csv-WEud-i_H.mjs.map +1 -0
  15. package/dist/csv.d.mts +1 -1
  16. package/dist/csv.d.mts.map +1 -1
  17. package/dist/csv.mjs +1 -248
  18. package/dist/index.d.mts +312 -18
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +3237 -4
  21. package/dist/index.mjs.map +1 -0
  22. package/dist/runtime-CMdfE7Gx.mjs +5476 -0
  23. package/dist/runtime-CMdfE7Gx.mjs.map +1 -0
  24. package/dist/runtime-DCo5E0Kr.d.mts +668 -0
  25. package/dist/runtime-DCo5E0Kr.d.mts.map +1 -0
  26. package/dist/select-options-DihMTuoa.mjs +518 -0
  27. package/dist/select-options-DihMTuoa.mjs.map +1 -0
  28. package/dist/sqlite-wasm-B86yaLG6.mjs +2000 -0
  29. package/dist/sqlite-wasm-B86yaLG6.mjs.map +1 -0
  30. package/dist/temporal-CVzLU63l.d.mts +517 -0
  31. package/dist/temporal-CVzLU63l.d.mts.map +1 -0
  32. package/package.json +2 -3
  33. package/dist/csv.mjs.map +0 -1
  34. package/dist/host-CqP1MeMK.d.mts +0 -213
  35. package/dist/host-CqP1MeMK.d.mts.map +0 -1
  36. package/dist/host-D5kZAhga.mjs +0 -478
  37. package/dist/host-D5kZAhga.mjs.map +0 -1
  38. package/dist/relation-values-B0JhHBjZ.mjs +0 -232
  39. package/dist/relation-values-B0JhHBjZ.mjs.map +0 -1
  40. package/dist/runtime-C3bstvB8.d.mts +0 -465
  41. package/dist/runtime-C3bstvB8.d.mts.map +0 -1
  42. package/dist/runtime-CWC5y95G.mjs +0 -2907
  43. package/dist/runtime-CWC5y95G.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,4 +1,3237 @@
1
- import { a as EidosFileRuntimeDataSource, i as eidosFileTypeHandler, n as EidosFileHostError, o as eidosFileSnapshot, r as EidosFileSession, t as EidosFileHandlerRegistry } from "./host-D5kZAhga.mjs";
2
- import { _ as encodeEidosFileJsonArray, a as decodeEidosFileMultiSelectValues, c as isMutableEidosFileFieldType, d as parseEidosFileSelectOptions, f as decodeEidosFileAttachmentPaths, g as decodeEidosFileStringArray, h as decodeEidosFileJsonArray, i as MUTABLE_BASE_FIELD_TYPES, l as planEidosFileFieldConversion, m as normalizeEidosFileAttachmentPath, n as decodeEidosFileRelationIds, o as eidosFileFieldDisplayValues, p as encodeEidosFileAttachmentPaths, r as encodeEidosFileRelationIds, s as encodeEidosFileMultiSelectValues, t as decodeEidosFileRelationDisplay, u as assertEidosFileSelectOptions, v as EidosFileError } from "./relation-values-B0JhHBjZ.mjs";
3
- import { A as EIDOS_FILE_REQUIRED_TABLES, B as createEidosFileUuid, C as EIDOS_FILE_EXTENSION, D as EIDOS_FILE_MIME_TYPE, E as EIDOS_FILE_META_TABLE, F as eidosFileColumnStatLabel, H as rawTableNameForId, I as eidosFileColumnStatTypesForField, L as assertEidosFileColumnName, M as EIDOS_FILE_TABLES_TABLE, N as EIDOS_FILE_VIEWS_TABLE, O as EIDOS_FILE_REFERENCES_TABLE, P as SQLITE_HEADER, R as assertEidosFileTableId, S as EIDOS_FILE_COLUMNS_TABLE, T as EIDOS_FILE_FORMAT_VERSION, V as quoteIdentifier, _ as eidosFileLookupDisplayType, a as eidosFileRowQueryPredicateColumns, b as compileEidosFileFormula, c as normalizeEidosFileSorts, d as migrateEidosFileSchema, f as EIDOS_FILE_SCHEMA_SQL, g as eidosFileLookupAggregateSupportsTarget, h as eidosFileFieldStoresJsonArray, i as eidosFileRowQueryAffectedByFieldChanges, j as EIDOS_FILE_SCHEMA_VERSION, k as EIDOS_FILE_REQUIRED_META_KEYS, l as removeEidosFileFilterField, m as setEidosFileMetadata, n as validateEidosFile, o as normalizeEidosFileFilter, p as initializeEidosFileSchema, r as compileEidosFileRowQuery, s as normalizeEidosFileRowQuery, t as EidosFileRuntime, u as getEidosFileSchemaVersion, v as eidosFileLookupStorageCodec, w as EIDOS_FILE_FORMAT, x as compileEidosFileFormulaFields, y as eidosFileLookupTargetDisplayType, z as createEidosFileIdentifier } from "./runtime-CWC5y95G.mjs";
4
- export { EIDOS_FILE_COLUMNS_TABLE, EIDOS_FILE_EXTENSION, EIDOS_FILE_FORMAT, EIDOS_FILE_FORMAT_VERSION, EIDOS_FILE_META_TABLE, EIDOS_FILE_MIME_TYPE, EIDOS_FILE_REFERENCES_TABLE, EIDOS_FILE_REQUIRED_META_KEYS, EIDOS_FILE_REQUIRED_TABLES, EIDOS_FILE_SCHEMA_SQL, EIDOS_FILE_SCHEMA_VERSION, EIDOS_FILE_TABLES_TABLE, EIDOS_FILE_VIEWS_TABLE, EidosFileError, EidosFileHandlerRegistry, EidosFileHostError, EidosFileRuntime, EidosFileRuntimeDataSource, EidosFileSession, MUTABLE_BASE_FIELD_TYPES, SQLITE_HEADER, assertEidosFileColumnName, assertEidosFileSelectOptions, assertEidosFileTableId, compileEidosFileFormula, compileEidosFileFormulaFields, compileEidosFileRowQuery, createEidosFileIdentifier, createEidosFileUuid, decodeEidosFileAttachmentPaths, decodeEidosFileJsonArray, decodeEidosFileMultiSelectValues, decodeEidosFileRelationDisplay, decodeEidosFileRelationIds, decodeEidosFileStringArray, eidosFileColumnStatLabel, eidosFileColumnStatTypesForField, eidosFileFieldDisplayValues, eidosFileFieldStoresJsonArray, eidosFileLookupAggregateSupportsTarget, eidosFileLookupDisplayType, eidosFileLookupStorageCodec, eidosFileLookupTargetDisplayType, eidosFileRowQueryAffectedByFieldChanges, eidosFileRowQueryPredicateColumns, eidosFileSnapshot, eidosFileTypeHandler, encodeEidosFileAttachmentPaths, encodeEidosFileJsonArray, encodeEidosFileMultiSelectValues, encodeEidosFileRelationIds, getEidosFileSchemaVersion, initializeEidosFileSchema, isMutableEidosFileFieldType, migrateEidosFileSchema, normalizeEidosFileAttachmentPath, normalizeEidosFileFilter, normalizeEidosFileRowQuery, normalizeEidosFileSorts, parseEidosFileSelectOptions, planEidosFileFieldConversion, quoteIdentifier, rawTableNameForId, removeEidosFileFilterField, setEidosFileMetadata, validateEidosFile };
1
+ import { A as parseEidosFileJson, C as createEidosFileUuid, D as rawTableNameForId, E as quoteIdentifier, O as canonicalizeEidosFileJson, S as createEidosFileIdentifier, T as isEidosFileUuid, _ as EidosUuidV7Generator, b as assertEidosFileTableId, c as normalizeEidosFileDate, d as decodeEidosFileAttachmentPaths, f as decodeEidosFileValues, g as normalizeEidosFileAttachmentPath, h as isSafeEidosFileUri, j as EidosFileError, k as isCanonicalEidosFileJson, l as normalizeEidosFileInstant, m as encodeEidosFileValues, n as parseEidosFileSelectOptions, o as isCanonicalEidosFileDate, p as encodeEidosFileAttachmentPaths, r as currentEidosFileInstant, s as isCanonicalEidosFileInstant, t as assertEidosFileSelectOptions, u as assertEidosFileValues, v as assertEidosFileColumnName, w as eidosFilePhysicalName, x as assertEidosFileUuid, y as assertEidosFileDisplayName } from "./select-options-DihMTuoa.mjs";
2
+ import { a as eidosFileTypeHandler, c as AdapterTransportRuntimeClient, d as transportFitsHostLimit, f as validateAdapterCarrier, i as EidosFileSession, l as AdapterTransportServer, n as EidosFileHandlerRegistry, o as EidosFileRuntimeDataSource, p as validateAdapterEnvelope, r as EidosFileHostError, s as eidosFileSnapshot, t as SQLiteWasmConnectionPort, u as EIDOS_ADAPTER_TRANSPORT_LIMITS } from "./sqlite-wasm-B86yaLG6.mjs";
3
+ import { $ as EIDOS_FILE_SYSTEM_COLUMNS, A as eidosFileLookupTargetDisplayType, B as EIDOS_FILE_APPLICATION_ID, C as normalizeEidosFileSorts, D as eidosFileLookupDisplayType, E as eidosFileLookupAggregateSupportsTarget, F as compileEidosFileFormula, G as EIDOS_FILE_FORMAT_VERSION, H as EIDOS_FILE_FEATURES_TABLE, I as compileEidosFileFormulaFields, J as EIDOS_FILE_META_TABLE, K as EIDOS_FILE_FORMULA_FIELDS_TABLE, L as compileEidosFileFormulaSource, M as eidosFileLookupValueType, N as EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES, O as eidosFileLookupElementType, P as EIDOS_FILE_FORMULA_FUNCTION_NAMES, Q as EIDOS_FILE_SCHEMA_VERSION, R as eidosFileFormulaReferences, S as normalizeEidosFileRowQuery, T as eidosFileFieldStoresJsonArray, U as EIDOS_FILE_FIELDS_TABLE, V as EIDOS_FILE_EXTENSION, W as EIDOS_FILE_FORMAT, X as EIDOS_FILE_RELATION_FIELDS_TABLE, Y as EIDOS_FILE_MIME_TYPE, Z as EIDOS_FILE_REQUIRED_TABLES, _ as compileEidosFileRowQuery, a as EIDOS_FILE_SCHEMA_SQL, at as eidosFileColumnStatTypesForField, b as eidosFileSortExpression, c as initializeEidosFileSchema, d as decodeEidosFileRelationIds, et as EIDOS_FILE_TABLES_TABLE, f as encodeEidosFileRelationIds, ft as nativeToSqlValue, g as assertEidosFileRowQuery, h as parseNonNegativeInt64, i as EIDOS_FILE_FORMAT_VERSION_TEXT, it as eidosFileColumnStatLabel, j as eidosFileLookupTargetValueType, k as eidosFileLookupStorageCodec, l as setEidosFileMetadata, lt as assertInt64Decimal, m as cancellationPortFromSignal, n as validateEidosFile, nt as SQLITE_HEADER, o as configureEidosFileConnection, ot as ConnectionPortEidosFileConnection, p as MemoryByteSource, pt as sqlValueToNative, q as EIDOS_FILE_LOOKUP_FIELDS_TABLE, r as smallestDependencyCycle, rt as hasEidosFileSqliteHeader, s as incrementEidosFileRevision, st as EidosAdapterError, t as EidosFileRuntime, tt as EIDOS_FILE_VIEWS_TABLE, u as decodeEidosFileRelationDisplay, ut as assertUnicodeString, v as eidosFileRowQueryAffectedByFieldChanges, w as removeEidosFileFilterField, x as normalizeEidosFileFilter, y as eidosFileRowQueryPredicateColumns, z as rewriteEidosFileFormulaFieldReferences } from "./runtime-CMdfE7Gx.mjs";
4
+ import { _ as planEidosFileFieldConversion, a as eidosFileCsvExportHeader, b as encodeEidosFileJsonArray, c as importEidosFileCsv, d as prepareEidosFileCsvImport, f as MUTABLE_BASE_FIELD_TYPES, g as isMutableEidosFileFieldType, h as encodeEidosFileMultiSelectValues, i as createEidosFileCsvRowEncoder, l as parseEidosFileCsvRows, m as eidosFileFieldDisplayValues, n as EIDOS_FILE_CSV_PREVIEW_ROW_COUNT, o as eidosFileCsvRowToEidosFileRow, p as decodeEidosFileMultiSelectValues, r as createEidosFileCsvImportPlan, s as encodeEidosFileCsvRecord, t as EIDOS_FILE_CSV_INFERENCE_ROW_COUNT, u as planEidosFileCsvImport, v as decodeEidosFileJsonArray, y as decodeEidosFileStringArray } from "./csv-WEud-i_H.mjs";
5
+ //#region src/canonical-conversion.ts
6
+ const INT64_MIN = -9223372036854775808n;
7
+ const INT64_MAX = 9223372036854775807n;
8
+ const INT64 = /^(?:0|-[1-9][0-9]*|[1-9][0-9]*)$/u;
9
+ const LIST_TYPES = new Set([
10
+ "multi-select",
11
+ "file",
12
+ "relation"
13
+ ]);
14
+ const TEXT_TYPES = new Set([
15
+ "text",
16
+ "date",
17
+ "datetime",
18
+ "url",
19
+ "select"
20
+ ]);
21
+ function planCanonicalFieldConversion(input) {
22
+ const policies = new Set(input.policies ?? []);
23
+ const sourceHasSqlNull = input.rows.some((row) => row.value === null);
24
+ const sourceHasJsonNull = input.rows.some((row) => input.from === "json" && row.value === "null");
25
+ const sourceHasEmptyList = input.rows.some((row) => {
26
+ if (row.value === null || typeof row.value !== "string") return false;
27
+ return row.value === "[]";
28
+ });
29
+ const changes = /* @__PURE__ */ new Map();
30
+ const rows = [];
31
+ let severity = 0;
32
+ let error;
33
+ for (const row of input.rows) try {
34
+ let converted;
35
+ if (row.value === null) converted = convertNull(input, policies, sourceHasJsonNull, sourceHasEmptyList);
36
+ else converted = convertNonNull(input, row.value, policies, {
37
+ sourceHasSqlNull,
38
+ sourceHasJsonNull
39
+ });
40
+ if (converted.value === null && !input.toNullable && !LIST_TYPES.has(input.to)) throw new Error("Destination non-nullability rejects SQL NULL");
41
+ validateDestination(input, converted.value);
42
+ const changed = storageClass(input.from) !== storageClass(input.to) || !sameStorageValue(row.value, converted.value);
43
+ rows.push({
44
+ id: row.id,
45
+ value: converted.value,
46
+ changed
47
+ });
48
+ if (changed) {
49
+ severity = Math.max(severity, converted.class);
50
+ changes.set("value-reencoded", (changes.get("value-reencoded") ?? 0) + 1);
51
+ if (converted.code) changes.set(converted.code, (changes.get(converted.code) ?? 0) + 1);
52
+ }
53
+ } catch (cause) {
54
+ severity = 3;
55
+ error = cause instanceof Error ? cause.message : "Conversion is forbidden";
56
+ break;
57
+ }
58
+ if (severity === 3) return {
59
+ classification: "forbidden",
60
+ rows: [],
61
+ affectedRows: "0",
62
+ valueChanges: [],
63
+ error
64
+ };
65
+ const affectedRows = rows.filter((row) => row.changed).length;
66
+ return {
67
+ classification: severity === 2 ? "explicit-lossy" : severity === 1 ? "lossless-rewrite" : "metadata-only",
68
+ rows,
69
+ affectedRows: String(affectedRows),
70
+ valueChanges: Array.from(changes, ([code, count]) => ({
71
+ code,
72
+ rows: String(count)
73
+ }))
74
+ };
75
+ }
76
+ function convertNull(input, policies, sourceHasJsonNull, sourceHasEmptyList) {
77
+ if (LIST_TYPES.has(input.to)) {
78
+ if (!policies.has("null-to-empty-list")) throw new Error("SQL NULL requires null-to-empty-list for a list destination");
79
+ return {
80
+ value: "[]",
81
+ class: sourceHasEmptyList ? 2 : 1,
82
+ code: "null-to-empty-list"
83
+ };
84
+ }
85
+ if (!input.toNullable) throw new Error("Destination non-nullability rejects SQL NULL");
86
+ return {
87
+ value: null,
88
+ class: sourceHasJsonNull && policies.has("json-null-to-sql-null") ? 2 : 0
89
+ };
90
+ }
91
+ function convertNonNull(input, value, policies, domain) {
92
+ const { from, to } = input;
93
+ if (from === to) return {
94
+ value,
95
+ class: 0
96
+ };
97
+ if (TEXT_TYPES.has(from) && TEXT_TYPES.has(to)) {
98
+ if (to === "datetime" && from === "date") return {
99
+ value: `${asText(value)}T00:00:00.000Z`,
100
+ class: 1
101
+ };
102
+ if (to === "date" && from === "datetime") {
103
+ const text = asText(value);
104
+ if (text.endsWith("T00:00:00.000Z")) return {
105
+ value: text.slice(0, 10),
106
+ class: 1
107
+ };
108
+ if (!policies.has("utc-date")) throw new Error("Datetime with a time component requires utc-date");
109
+ return {
110
+ value: text.slice(0, 10),
111
+ class: 2,
112
+ code: "datetime-to-date"
113
+ };
114
+ }
115
+ return {
116
+ value: asText(value),
117
+ class: 0
118
+ };
119
+ }
120
+ if (to === "text") {
121
+ if (from === "number") return {
122
+ value: canonicalNumber(asNumber(value)),
123
+ class: 1
124
+ };
125
+ if (from === "integer") return {
126
+ value: String(asInteger(value)),
127
+ class: 1
128
+ };
129
+ if (from === "checkbox") return {
130
+ value: asCheckbox(value) ? "true" : "false",
131
+ class: 1
132
+ };
133
+ if (from === "json" || LIST_TYPES.has(from)) return {
134
+ value: asText(value),
135
+ class: 0
136
+ };
137
+ }
138
+ if (to === "select") {
139
+ if (from === "number") return {
140
+ value: canonicalNumber(asNumber(value)),
141
+ class: 1
142
+ };
143
+ if (from === "integer") return {
144
+ value: String(asInteger(value)),
145
+ class: 1
146
+ };
147
+ if (from === "checkbox") return {
148
+ value: asCheckbox(value) ? "true" : "false",
149
+ class: 1
150
+ };
151
+ if (from === "multi-select") {
152
+ const list = parseStringList(value);
153
+ if (list.length === 1) return {
154
+ value: list[0],
155
+ class: 1
156
+ };
157
+ if (!policies.has("first")) throw new Error("Multi-select to Select requires a singleton or first");
158
+ if (list.length === 0) {
159
+ if (!input.toNullable) throw new Error("Empty list requires nullable Select");
160
+ return {
161
+ value: null,
162
+ class: 1,
163
+ code: "list-empty-to-null"
164
+ };
165
+ }
166
+ return {
167
+ value: list[0],
168
+ class: 2,
169
+ code: "list-tail-dropped"
170
+ };
171
+ }
172
+ if (from === "json") return unwrapJsonScalar(value, "select", policies, domain);
173
+ }
174
+ if (to === "number") {
175
+ if (from === "integer") {
176
+ const integer = asInteger(value);
177
+ const number = Number(integer);
178
+ if (Number.isInteger(number) && BigInt(number) === integer) return {
179
+ value: number,
180
+ class: 1
181
+ };
182
+ if (!policies.has("round-binary64") || !Number.isFinite(number)) throw new Error("Integer is not exactly representable as binary64");
183
+ return {
184
+ value: number,
185
+ class: 2,
186
+ code: "binary64-rounded"
187
+ };
188
+ }
189
+ if (from === "checkbox") return {
190
+ value: asCheckbox(value) ? 1 : 0,
191
+ class: 1
192
+ };
193
+ if (from === "text" || from === "select") {
194
+ const text = asText(value);
195
+ const number = Number(text);
196
+ if (!Number.isFinite(number) || canonicalNumber(number) !== text) throw new Error("Text is not the exact inverse binary64 spelling");
197
+ return {
198
+ value: number,
199
+ class: 1
200
+ };
201
+ }
202
+ if (from === "json") return unwrapJsonScalar(value, "number", policies, domain);
203
+ }
204
+ if (to === "integer") {
205
+ if (from === "checkbox") return {
206
+ value: asCheckbox(value) ? 1n : 0n,
207
+ class: 0
208
+ };
209
+ if (from === "text" || from === "select") return {
210
+ value: parseInt64(asText(value)),
211
+ class: 1
212
+ };
213
+ if (from === "number") return numberToInteger(asNumber(value), policies);
214
+ if (from === "json") return unwrapJsonScalar(value, "integer", policies, domain);
215
+ }
216
+ if (to === "checkbox") {
217
+ if (from === "text" || from === "select") {
218
+ const text = asText(value);
219
+ if (text === "true") return {
220
+ value: 1n,
221
+ class: 1
222
+ };
223
+ if (text === "false") return {
224
+ value: 0n,
225
+ class: 1
226
+ };
227
+ throw new Error("Text is not lowercase true or false");
228
+ }
229
+ if (from === "integer") {
230
+ const integer = asInteger(value);
231
+ if (integer === 0n || integer === 1n) return {
232
+ value: integer,
233
+ class: 0
234
+ };
235
+ if (!policies.has("zero-false-nonzero-true")) throw new Error("Integer Checkbox conversion requires exact 0/1");
236
+ return {
237
+ value: integer === 0n ? 0n : 1n,
238
+ class: 2,
239
+ code: "numeric-to-checkbox"
240
+ };
241
+ }
242
+ if (from === "number") {
243
+ const number = asNumber(value);
244
+ if (number === 0 || number === 1) return {
245
+ value: BigInt(number),
246
+ class: 1
247
+ };
248
+ if (!policies.has("zero-false-nonzero-true")) throw new Error("Number Checkbox conversion requires exact 0.0/1.0");
249
+ return {
250
+ value: number === 0 ? 0n : 1n,
251
+ class: 2,
252
+ code: "numeric-to-checkbox"
253
+ };
254
+ }
255
+ if (from === "json") return unwrapJsonScalar(value, "checkbox", policies, domain);
256
+ }
257
+ if (to === "date" || to === "datetime" || to === "url") {
258
+ if (from === "json") return unwrapJsonScalar(value, to, policies, domain);
259
+ }
260
+ if (to === "json") {
261
+ if (from === "json" || LIST_TYPES.has(from)) return {
262
+ value: asText(value),
263
+ class: 0
264
+ };
265
+ if (TEXT_TYPES.has(from)) return {
266
+ value: canonicalizeEidosFileJson(asText(value)),
267
+ class: 1
268
+ };
269
+ if (from === "number") return {
270
+ value: canonicalizeEidosFileJson(asNumber(value)),
271
+ class: 1
272
+ };
273
+ if (from === "integer") {
274
+ const integer = asInteger(value);
275
+ const number = Number(integer);
276
+ if (Number.isInteger(number) && BigInt(number) === integer) return {
277
+ value: canonicalizeEidosFileJson(number),
278
+ class: 1
279
+ };
280
+ if (!policies.has("round-binary64") || !Number.isFinite(number)) throw new Error("Integer JSON conversion requires round-binary64");
281
+ return {
282
+ value: canonicalizeEidosFileJson(number),
283
+ class: 2,
284
+ code: "binary64-rounded"
285
+ };
286
+ }
287
+ if (from === "checkbox") return {
288
+ value: asCheckbox(value) ? "true" : "false",
289
+ class: 1
290
+ };
291
+ }
292
+ if (LIST_TYPES.has(to)) {
293
+ if (from === "select" && to === "multi-select") return {
294
+ value: canonicalizeEidosFileJson([asText(value)]),
295
+ class: 1
296
+ };
297
+ if (from === "text" || from === "json" || from === "multi-select" && to === "relation" || from === "relation" && to === "multi-select" || from === to) return {
298
+ value: asText(value),
299
+ class: 0
300
+ };
301
+ }
302
+ throw new Error(`Conversion from ${from} to ${to} is forbidden`);
303
+ }
304
+ function unwrapJsonScalar(value, to, policies, domain) {
305
+ const parsed = parseEidosFileJson(asText(value));
306
+ if (parsed === null) {
307
+ if (!policies.has("json-null-to-sql-null")) throw new Error("JSON literal null requires json-null-to-sql-null");
308
+ return {
309
+ value: null,
310
+ class: domain.sourceHasSqlNull && domain.sourceHasJsonNull ? 2 : 1,
311
+ code: "json-null-to-sql-null"
312
+ };
313
+ }
314
+ if (to === "number" && typeof parsed === "number") return {
315
+ value: parsed,
316
+ class: 1
317
+ };
318
+ if (to === "integer" && typeof parsed === "number") return numberToInteger(parsed, policies);
319
+ if (to === "checkbox" && typeof parsed === "boolean") return {
320
+ value: parsed ? 1n : 0n,
321
+ class: 1
322
+ };
323
+ if ([
324
+ "text",
325
+ "date",
326
+ "datetime",
327
+ "url",
328
+ "select"
329
+ ].includes(to) && typeof parsed === "string") return {
330
+ value: parsed,
331
+ class: 1
332
+ };
333
+ throw new Error(`JSON root is incompatible with ${to}`);
334
+ }
335
+ function numberToInteger(number, policies) {
336
+ let result = number;
337
+ let code;
338
+ let classification = 1;
339
+ if (!Number.isInteger(result)) {
340
+ if (policies.has("truncate-toward-zero")) {
341
+ result = Math.trunc(result);
342
+ code = "fraction-truncated";
343
+ } else if (policies.has("round-ties-even")) {
344
+ result = roundTiesEven(result);
345
+ code = "integer-rounded";
346
+ } else throw new Error("Fractional Number requires an Integer rounding policy");
347
+ classification = 2;
348
+ }
349
+ if (!Number.isInteger(result)) throw new Error("Integer result is not integral");
350
+ const integer = BigInt(result);
351
+ if (integer < INT64_MIN || integer > INT64_MAX) throw new Error("Integer result is outside signed int64");
352
+ return {
353
+ value: integer,
354
+ class: classification,
355
+ ...code ? { code } : {}
356
+ };
357
+ }
358
+ function validateDestination(input, value) {
359
+ if (value === null) return;
360
+ switch (input.to) {
361
+ case "number":
362
+ asNumber(value);
363
+ return;
364
+ case "integer":
365
+ asInteger(value);
366
+ return;
367
+ case "checkbox":
368
+ asCheckbox(value);
369
+ return;
370
+ case "date":
371
+ if (!isCanonicalEidosFileDate(value)) throw new Error("Invalid Date value");
372
+ return;
373
+ case "datetime":
374
+ if (!isCanonicalEidosFileInstant(value)) throw new Error("Invalid Datetime value");
375
+ return;
376
+ case "url":
377
+ if (!isUriReference(asText(value))) throw new Error("Invalid URI-reference");
378
+ return;
379
+ case "json":
380
+ if (!isCanonicalEidosFileJson(asText(value))) throw new Error("Invalid canonical JSON");
381
+ return;
382
+ case "multi-select":
383
+ parseStringList(value);
384
+ return;
385
+ case "file":
386
+ assertEidosFileValues(parseEidosFileJson(asText(value)));
387
+ return;
388
+ case "relation": {
389
+ const ids = parseStringList(value);
390
+ if (!ids.every(isEidosFileUuid)) throw new Error("Invalid Relation Row ID");
391
+ if (input.relationCardinality === "one" && ids.length > 1) throw new Error("One-cardinality Relation contains more than one Row ID");
392
+ if (input.relationIdValid && !ids.every(input.relationIdValid)) throw new Error("Relation Row ID does not resolve in the target Table");
393
+ return;
394
+ }
395
+ case "text":
396
+ case "select":
397
+ asText(value);
398
+ return;
399
+ }
400
+ }
401
+ function parseStringList(value) {
402
+ const text = asText(value);
403
+ if (!isCanonicalEidosFileJson(text)) throw new Error("List is not canonical JSON");
404
+ const parsed = parseEidosFileJson(text);
405
+ if (!Array.isArray(parsed) || !parsed.every((entry) => typeof entry === "string")) throw new Error("List must contain only strings");
406
+ if (new Set(parsed).size !== parsed.length) throw new Error("List values must be unique");
407
+ return parsed;
408
+ }
409
+ function asText(value) {
410
+ if (typeof value !== "string") throw new Error("Expected TEXT storage");
411
+ return value;
412
+ }
413
+ function asNumber(value) {
414
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error("Expected finite REAL storage");
415
+ return Object.is(value, -0) ? 0 : value;
416
+ }
417
+ function asInteger(value) {
418
+ if (typeof value === "bigint") {
419
+ if (value < INT64_MIN || value > INT64_MAX) throw new Error("INTEGER outside int64");
420
+ return value;
421
+ }
422
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new Error("Expected exact INTEGER storage");
423
+ return BigInt(value);
424
+ }
425
+ function asCheckbox(value) {
426
+ const integer = asInteger(value);
427
+ if (integer !== 0n && integer !== 1n) throw new Error("Checkbox must be 0 or 1");
428
+ return integer === 1n;
429
+ }
430
+ function parseInt64(value) {
431
+ if (!INT64.test(value) || value === "-0") throw new Error("Invalid int64 spelling");
432
+ const integer = BigInt(value);
433
+ if (integer < INT64_MIN || integer > INT64_MAX) throw new Error("INTEGER outside int64");
434
+ return integer;
435
+ }
436
+ function canonicalNumber(value) {
437
+ return canonicalizeEidosFileJson(value);
438
+ }
439
+ function roundTiesEven(value) {
440
+ const floor = Math.floor(value);
441
+ const fraction = value - floor;
442
+ if (fraction < .5) return floor;
443
+ if (fraction > .5) return floor + 1;
444
+ return floor % 2 === 0 ? floor : floor + 1;
445
+ }
446
+ function isUriReference(value) {
447
+ return !/[\u0000-\u0020<>"{}|\\^`]/u.test(value) && !/%(?![0-9A-Fa-f]{2})/u.test(value);
448
+ }
449
+ function sameStorageValue(left, right) {
450
+ if (left instanceof Uint8Array || right instanceof Uint8Array) return left instanceof Uint8Array && right instanceof Uint8Array && left.byteLength === right.byteLength && left.every((byte, index) => byte === right[index]);
451
+ if ((typeof left === "bigint" || typeof left === "number" && Number.isSafeInteger(left)) && (typeof right === "bigint" || typeof right === "number" && Number.isSafeInteger(right))) return BigInt(left) === BigInt(right);
452
+ return typeof left === typeof right && Object.is(left, right);
453
+ }
454
+ function storageClass(type) {
455
+ if (type === "integer" || type === "checkbox") return "integer";
456
+ if (type === "number") return "real";
457
+ return "text";
458
+ }
459
+ //#endregion
460
+ //#region src/runtime-service.ts
461
+ const EIDOS_RUNTIME_LIMITS = Object.freeze({
462
+ requestBytesMax: 8 * 1024 * 1024,
463
+ responseBytesMax: 16 * 1024 * 1024,
464
+ schemaPageSizeMax: 1e3,
465
+ pageSizeMax: 1e3,
466
+ projectionFieldsMax: 256,
467
+ rowsByIdMax: 1e3,
468
+ mutationRowsMax: 500,
469
+ mutationCellsMax: 25e3,
470
+ mutationBytesMax: 8 * 1024 * 1024,
471
+ aggregateItemsMax: 128,
472
+ groupPageSizeMax: 256,
473
+ formulaPreviewRowsMax: 100,
474
+ filterDepthMax: 8,
475
+ filterNodesMax: 100,
476
+ sortFieldsMax: 32,
477
+ groupFieldsMax: 8,
478
+ searchBytesMax: 4096,
479
+ listElementsMax: 1e4,
480
+ logicalValueBytesMax: 1048576,
481
+ jsonCellBytesMax: 1048576,
482
+ formulaBytesMax: 4096,
483
+ formulaNodesMax: 1e4,
484
+ formulaDepthMax: 256,
485
+ diagnosticsMax: 1e3,
486
+ foregroundTimeMsMax: 3e4,
487
+ csvBytesMax: 16 * 1024 * 1024,
488
+ schemaPlanEntriesMax: 64,
489
+ schemaPlanBytesMax: 8 * 1024 * 1024,
490
+ undoEntriesMax: 1,
491
+ undoBytesMax: 1
492
+ });
493
+ const READONLY_CAPABILITIES = Object.freeze({
494
+ readRows: true,
495
+ schemaPaging: true,
496
+ cursorPaging: true,
497
+ aggregate: true,
498
+ groupRows: true,
499
+ formulaPreview: true,
500
+ mutateRows: false,
501
+ mutationUndo: false,
502
+ mutateView: false,
503
+ schemaPreflight: false,
504
+ mutateSchema: false,
505
+ validate: true,
506
+ events: false,
507
+ csvExport: false,
508
+ csvImport: false
509
+ });
510
+ function runtimeCapabilities(writable) {
511
+ return {
512
+ ...READONLY_CAPABILITIES,
513
+ mutateRows: writable,
514
+ mutateView: writable,
515
+ schemaPreflight: writable,
516
+ mutateSchema: writable
517
+ };
518
+ }
519
+ var Runtime = class {
520
+ static async open(connection, environment, mode, context) {
521
+ assertFactoryContext(context, environment);
522
+ assertConnectionCapabilities(connection);
523
+ if (mode === "readwrite" && !connection.capabilities().snapshot) throw runtimeError("adapter-error", "Adapter snapshot capability is required");
524
+ const bridge = new ConnectionPortEidosFileConnection(connection);
525
+ const validation = connection.transaction("read", () => validateEidosFile(bridge, { level: mode === "readwrite" ? "structural" : "identity" }));
526
+ if (!validation.valid) throw runtimeError("corrupt-file", validation.errors.map((issue) => issue.message).join("; ") || "Eidos File validation failed");
527
+ return createRuntimeBinding(connection, environment, mode);
528
+ }
529
+ static async create(connection, environment, createInput, context) {
530
+ assertFactoryContext(context, environment);
531
+ assertConnectionCapabilities(connection);
532
+ assertEidosFileDisplayName(createInput.title, "File title");
533
+ if (createInput.createdAt !== void 0 && !isCanonicalEidosFileInstant(createInput.createdAt)) throw runtimeError("invalid-request", "createdAt must be a canonical millisecond UTC instant", { path: "/createdAt" });
534
+ if (createInput.fileId !== void 0) try {
535
+ assertEidosFileUuid(createInput.fileId, "File ID");
536
+ } catch {
537
+ throw runtimeError("invalid-request", "fileId must be UUIDv7", { path: "/fileId" });
538
+ }
539
+ const generator = uuidGenerator(environment);
540
+ const createdAt = createInput.createdAt ?? checkedNowInstant(environment);
541
+ const fileId = createInput.fileId ?? generator.next();
542
+ const bridge = new ConnectionPortEidosFileConnection(connection);
543
+ connection.transaction("write", () => {
544
+ if (connection.query("SELECT name FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'").rows.length !== 0) throw runtimeError("invalid-request", "Runtime.create requires an empty database");
545
+ initializeEidosFileSchema(bridge, {
546
+ fileId,
547
+ title: createInput.title,
548
+ createdAt
549
+ }, false);
550
+ const validation = validateEidosFile(bridge, { level: "structural" });
551
+ if (!validation.valid) throw runtimeError("corrupt-file", validation.errors.map((issue) => issue.message).join("; "));
552
+ });
553
+ return createRuntimeBinding(connection, environment, "readwrite", generator);
554
+ }
555
+ };
556
+ function createRuntimeBinding(connection, environment, mode, generator = uuidGenerator(environment)) {
557
+ const service = new EidosRuntimeService(connection, new EidosFileRuntime(new ConnectionPortEidosFileConnection(connection), false, {
558
+ nowInstant: () => checkedNowInstant(environment),
559
+ allocateId: () => generator.next()
560
+ }), environment, mode === "readwrite", generator);
561
+ return {
562
+ service,
563
+ hostBridge: service.hostBridge
564
+ };
565
+ }
566
+ var EidosRuntimeService = class {
567
+ hostBridge;
568
+ capabilitiesValue;
569
+ epoch;
570
+ cursorSecret;
571
+ requestControls = /* @__PURE__ */ new Map();
572
+ schemaPlans = /* @__PURE__ */ new Map();
573
+ schemaPlanSequence = 0;
574
+ queue = Promise.resolve();
575
+ state = "open";
576
+ constructor(connection, core, environment, writable, generator) {
577
+ this.connection = connection;
578
+ this.core = core;
579
+ this.environment = environment;
580
+ this.writable = writable;
581
+ this.generator = generator;
582
+ this.capabilitiesValue = runtimeCapabilities(writable);
583
+ this.epoch = generator.next();
584
+ this.cursorSecret = environment.entropy.randomBytes(16).slice();
585
+ if (this.cursorSecret.byteLength !== 16) throw runtimeError("adapter-error", "EntropyPort returned an invalid cursor authentication key");
586
+ this.hostBridge = {
587
+ allocateFileEntry: (request, context) => this.invoke(context, () => this.allocateFileEntry(request), false, request),
588
+ createPublicationSnapshot: (request, context) => this.invoke(context, async () => {
589
+ if (parseRevision(request.maxBytes, "maxBytes") < 0n) throw runtimeError("invalid-request", "maxBytes must be non-negative");
590
+ return this.connection.transaction("read", async () => {
591
+ const identity = this.connection.get("SELECT file_id, revision FROM eidos__meta WHERE singleton=1");
592
+ if (!identity.row) throw runtimeError("corrupt-file", "Missing Eidos File identity");
593
+ const fileId = taggedText(identity.row[0]);
594
+ const revision = taggedInteger(identity.row[1]);
595
+ const snapshot = await this.connection.snapshot({
596
+ cancellation: cancellationPortFromSignal(context.signal),
597
+ ...context.deadlineMilliseconds === void 0 ? {} : { deadlineMilliseconds: context.deadlineMilliseconds },
598
+ maxBytes: request.maxBytes
599
+ });
600
+ return {
601
+ fileId,
602
+ revision,
603
+ bytes: snapshot.bytes,
604
+ release: snapshot.release
605
+ };
606
+ });
607
+ }, false, request, false)
608
+ };
609
+ }
610
+ negotiate(request, context) {
611
+ return this.invoke(context, () => {
612
+ if (request.protocol !== "eidos-runtime" || !Array.isArray(request.versions) || request.versions.length !== 1 || request.versions[0] !== "1.0") throw runtimeError("unsupported", "Eidos Runtime 1.0 is required");
613
+ return {
614
+ version: "1.0",
615
+ capabilities: { ...this.capabilitiesValue },
616
+ limits: { ...EIDOS_RUNTIME_LIMITS }
617
+ };
618
+ }, false, request);
619
+ }
620
+ getSnapshot(request, context) {
621
+ return this.invoke(context, () => this.snapshotAtMinimumRevision(request.minimumRevision, context), false, request);
622
+ }
623
+ async snapshotAtMinimumRevision(minimumRevision, context) {
624
+ const target = minimumRevision === void 0 ? null : parseRevision(minimumRevision, "minimumRevision");
625
+ const startedAt = this.environment.clock.nowMilliseconds();
626
+ const budget = Math.min(context.deadlineMilliseconds ?? EIDOS_RUNTIME_LIMITS.foregroundTimeMsMax, EIDOS_RUNTIME_LIMITS.foregroundTimeMsMax);
627
+ let current = this.read(() => this.snapshot());
628
+ while (target !== null && BigInt(current.revision) < target) {
629
+ if (this.requestControls.get(context.requestId)?.cancelled || context.signal?.aborted) throw runtimeError("cancelled", "Snapshot wait was cancelled", {
630
+ retryable: true,
631
+ currentRevision: current.revision
632
+ });
633
+ if (this.state !== "open") throw runtimeError("closed", "Runtime closed during snapshot wait");
634
+ const elapsed = this.environment.clock.nowMilliseconds() - startedAt;
635
+ if (!Number.isFinite(elapsed) || elapsed < 0) throw runtimeError("fatal", "Monotonic clock moved backward");
636
+ if (elapsed >= budget) throw runtimeError("deadline-exceeded", "minimumRevision was not reached before the deadline", {
637
+ retryable: true,
638
+ currentRevision: current.revision
639
+ });
640
+ await new Promise((resolve) => setTimeout(resolve, 10));
641
+ this.connection.dataVersion();
642
+ current = this.read(() => this.snapshot());
643
+ }
644
+ return current;
645
+ }
646
+ getSchemaPage(request, context) {
647
+ return this.invoke(context, async () => this.read(async () => {
648
+ assertLimit(request.limit, EIDOS_RUNTIME_LIMITS.schemaPageSizeMax, "limit");
649
+ const snapshot = this.snapshot();
650
+ assertCurrentRevision(request.revision, snapshot.revision);
651
+ let offset = 0;
652
+ if (request.cursor !== void 0) {
653
+ const payload = this.decodeCursor(request.cursor, "schema");
654
+ if (payload.fileId !== snapshot.fileId || payload.revision !== request.revision || typeof payload.offset !== "number" || !Number.isSafeInteger(payload.offset) || payload.offset < 0) throw runtimeError("invalid-query", "Invalid schema cursor");
655
+ offset = payload.offset;
656
+ }
657
+ const objects = this.schemaDescriptors();
658
+ const page = objects.slice(offset, offset + request.limit);
659
+ if (offset > objects.length) throw runtimeError("invalid-query", "Schema cursor is past the end");
660
+ const responseFor = (prefix) => {
661
+ const nextOffset = offset + prefix.length;
662
+ return {
663
+ fileId: snapshot.fileId,
664
+ revision: snapshot.revision,
665
+ objects: prefix,
666
+ nextCursor: nextOffset < objects.length ? this.encodeCursor("schema", {
667
+ fileId: snapshot.fileId,
668
+ revision: snapshot.revision,
669
+ offset: nextOffset
670
+ }) : null
671
+ };
672
+ };
673
+ while (page.length > 0 && jcsByteLength(responseFor(page)) > EIDOS_RUNTIME_LIMITS.responseBytesMax) page.pop();
674
+ if (jcsByteLength(responseFor(page)) > EIDOS_RUNTIME_LIMITS.responseBytesMax || offset < objects.length && page.length === 0) throw runtimeError("resource-limit", "Schema descriptor cannot fit responseBytesMax");
675
+ return responseFor(page);
676
+ }), false, request);
677
+ }
678
+ queryRows(request, context) {
679
+ return this.invoke(context, async () => this.read(async () => {
680
+ assertLimit(request.limit, EIDOS_RUNTIME_LIMITS.pageSizeMax, "limit");
681
+ assertProjection(request.projection);
682
+ const query = this.compatibilityQuery(request.tableId, request.query);
683
+ const direction = request.direction ?? "forward";
684
+ const metadata = this.core.info();
685
+ const projectionDigest = await projectionHash(request.projection);
686
+ const queryDigest = await hashJson(normalizedRuntimeQuery(request.query));
687
+ const backwardQuery = reverseRuntimeQuery(request.query, this.core.listFields(request.tableId));
688
+ const traversalQuery = direction === "forward" ? request.query : backwardQuery;
689
+ const traversal = this.compatibilityQuery(request.tableId, traversalQuery);
690
+ let coreCursor;
691
+ if (request.cursor !== void 0) {
692
+ const cursor = this.decodeCursor(request.cursor, "rows");
693
+ if (cursor.fileId !== metadata.fileId || cursor.tableId !== request.tableId || cursor.queryHash !== queryDigest || cursor.projectionHash !== projectionDigest) throw runtimeError("invalid-query", "Row cursor binding mismatch");
694
+ if (cursor.revision !== String(metadata.revision)) throw runtimeError("stale-revision", "Row cursor revision is stale", { currentRevision: String(metadata.revision) });
695
+ const selected = direction === "forward" ? cursor.forward : cursor.backward;
696
+ if (typeof selected !== "string") throw runtimeError("invalid-query", "Row cursor boundary is invalid");
697
+ coreCursor = selected;
698
+ }
699
+ const extraFields = (request.query.sort ?? []).map((sort) => sort.fieldId);
700
+ const fields = Array.from(new Set([...request.projection.fields, ...extraFields]));
701
+ const result = this.core.queryRows(request.tableId, {
702
+ fields,
703
+ query: traversal,
704
+ limit: request.limit + 1,
705
+ cursor: coreCursor,
706
+ resolveRelations: request.projection.resolveRelations.length > 0
707
+ });
708
+ const hasMoreInTraversal = result.rows.length > request.limit;
709
+ const traversalRows = result.rows.slice(0, request.limit);
710
+ const logicalRows = direction === "forward" ? traversalRows : traversalRows.reverse();
711
+ const columns = this.columns(request.tableId, request.projection);
712
+ const rows = this.projectRows(request.tableId, request.projection, logicalRows, columns);
713
+ const boundaryCursor = (row) => {
714
+ if (!row) return null;
715
+ return this.encodeCursor("rows", {
716
+ fileId: metadata.fileId,
717
+ tableId: request.tableId,
718
+ revision: String(metadata.revision),
719
+ queryHash: queryDigest,
720
+ projectionHash: projectionDigest,
721
+ forward: this.core.createRowCursor(request.tableId, query, row),
722
+ backward: this.core.createRowCursor(request.tableId, this.compatibilityQuery(request.tableId, backwardQuery), row)
723
+ });
724
+ };
725
+ const hasEarlier = direction === "backward" ? hasMoreInTraversal : request.cursor !== void 0;
726
+ const hasLater = direction === "forward" ? hasMoreInTraversal : request.cursor !== void 0;
727
+ return {
728
+ fileId: metadata.fileId,
729
+ tableId: request.tableId,
730
+ revision: String(metadata.revision),
731
+ projectionHash: projectionDigest,
732
+ columns,
733
+ rows,
734
+ nextCursor: hasLater ? boundaryCursor(logicalRows.at(-1)) : null,
735
+ previousCursor: hasEarlier ? boundaryCursor(logicalRows[0]) : null
736
+ };
737
+ }), false, request);
738
+ }
739
+ getRowsById(request, context) {
740
+ return this.invoke(context, async () => this.read(async () => {
741
+ if (request.rowIds.length > EIDOS_RUNTIME_LIMITS.rowsByIdMax || new Set(request.rowIds).size !== request.rowIds.length) throw runtimeError("invalid-request", "rowIds must be unique and within rowsByIdMax");
742
+ request.rowIds.forEach((id) => assertEidosFileUuid(id, "Row ID"));
743
+ assertProjection(request.projection);
744
+ return this.getRowsByIdDirect(request.tableId, request.rowIds, request.projection);
745
+ }), false, request);
746
+ }
747
+ aggregate(request, context) {
748
+ return this.invoke(context, () => this.read(() => this.aggregateNow(request)), false, request);
749
+ }
750
+ groupRows(request, context) {
751
+ return this.invoke(context, async () => this.read(async () => this.groupRowsNow(request)), false, request);
752
+ }
753
+ queryGroupRows(request, context) {
754
+ return this.invoke(context, async () => this.read(async () => {
755
+ assertLimit(request.limit, EIDOS_RUNTIME_LIMITS.pageSizeMax, "limit");
756
+ const cursor = this.decodeCursor(request.cursor, "group-rows");
757
+ const source = cursor.request;
758
+ if (!source || typeof source !== "object" || Array.isArray(source)) throw runtimeError("invalid-query", "Invalid group row cursor");
759
+ assertProjection(source.projection);
760
+ const metadata = this.core.info();
761
+ const projectionDigest = await projectionHash(source.projection);
762
+ const bindingDigest = await groupBindingHash(source);
763
+ if (cursor.fileId !== metadata.fileId || cursor.tableId !== source.tableId || cursor.projectionHash !== projectionDigest || cursor.bindingHash !== bindingDigest || !Array.isArray(cursor.groupKey) || typeof cursor.forward !== "string" || typeof cursor.backward !== "string") throw runtimeError("invalid-query", "Group row cursor binding mismatch");
764
+ if (cursor.revision !== String(metadata.revision)) throw runtimeError("stale-revision", "Group row cursor revision is stale", { currentRevision: String(metadata.revision) });
765
+ const groupKey = cursor.groupKey;
766
+ if (groupKey.length !== source.groupBy.length) throw runtimeError("invalid-query", "Group row cursor key is invalid");
767
+ const groupQuery = queryForGroup(source.query, source.groupBy, groupKey);
768
+ const direction = request.direction ?? "forward";
769
+ const backwardQuery = reverseRuntimeQuery(groupQuery, this.core.listFields(source.tableId));
770
+ const traversalQuery = direction === "forward" ? groupQuery : backwardQuery;
771
+ const fields = Array.from(new Set([...source.projection.fields, ...(groupQuery.sort ?? []).map((sort) => sort.fieldId)]));
772
+ const result = this.core.queryRows(source.tableId, {
773
+ fields,
774
+ query: this.compatibilityQuery(source.tableId, traversalQuery),
775
+ limit: request.limit + 1,
776
+ cursor: direction === "forward" ? cursor.forward : cursor.backward,
777
+ resolveRelations: source.projection.resolveRelations.length > 0
778
+ });
779
+ const hasMore = result.rows.length > request.limit;
780
+ const traversalRows = result.rows.slice(0, request.limit);
781
+ const logicalRows = direction === "forward" ? traversalRows : traversalRows.reverse();
782
+ const columns = this.columns(source.tableId, source.projection);
783
+ const rowCursor = (row) => {
784
+ if (!row) return null;
785
+ return this.encodeCursor("group-rows", {
786
+ fileId: metadata.fileId,
787
+ tableId: source.tableId,
788
+ revision: String(metadata.revision),
789
+ projectionHash: projectionDigest,
790
+ bindingHash: bindingDigest,
791
+ request: groupCursorSource(source),
792
+ groupKey,
793
+ forward: this.core.createRowCursor(source.tableId, this.compatibilityQuery(source.tableId, groupQuery), row),
794
+ backward: this.core.createRowCursor(source.tableId, this.compatibilityQuery(source.tableId, backwardQuery), row)
795
+ });
796
+ };
797
+ const hasEarlier = direction === "backward" ? hasMore : request.cursor !== void 0;
798
+ const hasLater = direction === "forward" ? hasMore : request.cursor !== void 0;
799
+ return {
800
+ fileId: metadata.fileId,
801
+ tableId: source.tableId,
802
+ revision: String(metadata.revision),
803
+ projectionHash: projectionDigest,
804
+ columns,
805
+ groupKey,
806
+ rows: this.projectRows(source.tableId, source.projection, logicalRows, columns),
807
+ nextCursor: hasLater ? rowCursor(logicalRows.at(-1)) : null,
808
+ previousCursor: hasEarlier ? rowCursor(logicalRows[0]) : null
809
+ };
810
+ }), false, request);
811
+ }
812
+ previewFormula(request, context) {
813
+ return this.invoke(context, () => {
814
+ if (!this.capabilitiesValue.formulaPreview) throw runtimeError("unsupported", "formulaPreview is unavailable");
815
+ return this.read(() => {
816
+ const name = request.fieldId === void 0 ? request.candidateName : this.core.listFields(request.tableId).find((field) => field.id === request.fieldId)?.name;
817
+ if (!name) throw runtimeError("invalid-request", "Formula candidate name is required");
818
+ try {
819
+ const result = this.core.previewFormula(request.tableId, {
820
+ name,
821
+ columnName: name,
822
+ formula: request.sourceText,
823
+ displayType: request.declaredResultType
824
+ });
825
+ const metadata = this.core.info();
826
+ return {
827
+ fileId: metadata.fileId,
828
+ revision: String(metadata.revision),
829
+ valid: true,
830
+ inferredType: request.declaredResultType,
831
+ dependencies: result.dependencies.flatMap((dependency) => {
832
+ const field = this.core.listFields(request.tableId).find((entry) => entry.name === dependency.name || entry.tableColumnName === dependency.columnName);
833
+ return field?.id ? [field.id] : [];
834
+ }),
835
+ rows: result.samples.map((sample) => ({
836
+ rowId: sample.rowId,
837
+ value: compatibilityLogicalValue(sample.value, request.declaredResultType)
838
+ })),
839
+ diagnostics: [],
840
+ diagnosticsTruncated: false
841
+ };
842
+ } catch (error) {
843
+ const mapped = mapRuntimeFailure(error);
844
+ return {
845
+ fileId: this.core.info().fileId,
846
+ revision: String(this.core.info().revision),
847
+ valid: false,
848
+ diagnostics: [{
849
+ code: "formula-parse-invalid",
850
+ severity: "error",
851
+ message: mapped.message
852
+ }],
853
+ diagnosticsTruncated: false
854
+ };
855
+ }
856
+ });
857
+ }, false, request);
858
+ }
859
+ mutateRows(request, context) {
860
+ return this.invoke(context, async () => {
861
+ this.assertWritable("mutateRows");
862
+ if (request.changes.length < 1 || request.changes.length > EIDOS_RUNTIME_LIMITS.mutationRowsMax) throw runtimeError("invalid-request", "changes must be within mutationRowsMax");
863
+ if (request.changes.reduce((total, change) => total + ("values" in change ? Object.keys(change.values).length : 0), 0) > EIDOS_RUNTIME_LIMITS.mutationCellsMax) throw runtimeError("resource-limit", "Mutation exceeds mutationCellsMax");
864
+ assertJcsBytes(request, EIDOS_RUNTIME_LIMITS.mutationBytesMax, "Row mutation");
865
+ const current = this.core.info();
866
+ assertCurrentRevision(request.expectedRevision, String(current.revision));
867
+ const clientKeys = /* @__PURE__ */ new Set();
868
+ const rowIds = /* @__PURE__ */ new Set();
869
+ for (const change of request.changes) if (change.kind === "create") {
870
+ if (!change.clientKey || clientKeys.has(change.clientKey)) throw runtimeError("invalid-request", "Create clientKey values must be non-empty and unique");
871
+ clientKeys.add(change.clientKey);
872
+ } else {
873
+ assertEidosFileUuid(change.rowId, "Row ID");
874
+ if (rowIds.has(change.rowId)) throw runtimeError("invalid-request", "A Row ID may occur only once per mutation");
875
+ rowIds.add(change.rowId);
876
+ }
877
+ if (rowIds.size > 0) {
878
+ const rowIdField = this.core.listFields(request.tableId).find((field) => field.systemRole === "row-id" || field.type === "row-id");
879
+ if (!rowIdField?.id) throw runtimeError("corrupt-file", "Table is missing Row-ID Field");
880
+ const existing = new Set(this.fetchRowsByIds(request.tableId, Array.from(rowIds), {
881
+ fields: [rowIdField.id],
882
+ resolveRelations: []
883
+ }).map((row) => row.id));
884
+ for (const rowId of rowIds) if (!existing.has(rowId)) throw runtimeError("not-found", "Row not found", {
885
+ tableId: request.tableId,
886
+ rowId
887
+ });
888
+ }
889
+ const inserts = request.changes.filter((change) => change.kind === "create").map((change) => ({ fields: this.mutationValues(request.tableId, change.values) }));
890
+ const updates = request.changes.filter((change) => change.kind === "update").map((change) => ({
891
+ id: change.rowId,
892
+ fields: this.mutationValues(request.tableId, change.values)
893
+ }));
894
+ const deletes = request.changes.filter((change) => change.kind === "delete").map((change) => change.rowId);
895
+ const beforeRevision = String(this.core.info().revision);
896
+ return this.withCommitBarrier("mutateRows", beforeRevision, context, async () => {
897
+ const result = this.core.mutateRows({
898
+ tableId: request.tableId,
899
+ insert: inserts,
900
+ update: updates,
901
+ delete: deletes,
902
+ expectedRevision: parseRevision(request.expectedRevision)
903
+ });
904
+ const after = this.core.info();
905
+ const created = request.changes.filter((change) => change.kind === "create").map((change, index) => ({
906
+ clientKey: change.clientKey,
907
+ rowId: result.rows[index].id
908
+ }));
909
+ const affectedRows = result.affected ?? [];
910
+ const response = {
911
+ fileId: after.fileId,
912
+ revision: String(after.revision),
913
+ changed: String(after.revision) !== beforeRevision,
914
+ created,
915
+ affectedRows
916
+ };
917
+ if (request.returning) response.returnedRows = await this.getRowsByIdDirect(request.tableId, request.changes.flatMap((change) => {
918
+ if (change.kind === "create") {
919
+ const allocated = created.find((entry) => entry.clientKey === change.clientKey);
920
+ return allocated ? [allocated.rowId] : [];
921
+ }
922
+ if (change.kind === "update") return [change.rowId];
923
+ return [];
924
+ }), request.returning);
925
+ return response;
926
+ }, (result) => ({
927
+ operation: "mutateRows",
928
+ result: {
929
+ fileId: result.fileId,
930
+ revision: result.revision,
931
+ changed: true,
932
+ created: result.created,
933
+ affectedRows: result.affectedRows
934
+ }
935
+ }));
936
+ }, false, request);
937
+ }
938
+ mutationValues(tableId, values) {
939
+ const fields = new Map(this.core.listFields(tableId).map((field) => [field.id, field]));
940
+ const normalized = {};
941
+ for (const [fieldId, value] of Object.entries(values)) {
942
+ const field = fields.get(fieldId);
943
+ if (!field) throw runtimeError("not-found", "Mutation Field not found", { fieldId });
944
+ if (!fieldWritable(field)) throw runtimeError("forbidden", "Mutation Field is read-only", { fieldId });
945
+ const type = fieldValueType(field);
946
+ assertJcsBytes(value, EIDOS_RUNTIME_LIMITS.logicalValueBytesMax, "Logical value");
947
+ if (value === null) {
948
+ if (!field.nullable) throw runtimeError("constraint", "Field is not nullable", { fieldId });
949
+ normalized[fieldId] = null;
950
+ continue;
951
+ }
952
+ if (!logicalValueMatchesType(value, type)) throw runtimeError("invalid-value", "Mutation value type is invalid", { fieldId });
953
+ if (Array.isArray(value) && value.length > EIDOS_RUNTIME_LIMITS.listElementsMax) throw runtimeError("resource-limit", "List exceeds listElementsMax", { fieldId });
954
+ if (type === "date" && !isCanonicalEidosFileDate(value)) throw runtimeError("invalid-value", "Date is not canonical", { fieldId });
955
+ if (type === "datetime" && !isCanonicalEidosFileInstant(value)) throw runtimeError("invalid-value", "Datetime is not canonical", { fieldId });
956
+ if (type === "json") {
957
+ const text = value;
958
+ if (new TextEncoder().encode(text).byteLength > EIDOS_RUNTIME_LIMITS.jsonCellBytesMax) throw runtimeError("resource-limit", "JSON cell exceeds jsonCellBytesMax", { fieldId });
959
+ try {
960
+ if (canonicalizeEidosFileJson(JSON.parse(text)) !== text) throw new Error("non-canonical");
961
+ } catch {
962
+ throw runtimeError("invalid-value", "JSON Field value must be canonical JCS text", { fieldId });
963
+ }
964
+ }
965
+ if (type === "integer") normalized[fieldId] = parseSignedInt64(value, "Integer value");
966
+ else normalized[fieldId] = value;
967
+ }
968
+ return normalized;
969
+ }
970
+ async mutateView(request, context) {
971
+ return this.invoke(context, () => {
972
+ this.assertWritable("mutateView");
973
+ if (request.changes.length < 1) throw runtimeError("invalid-request", "View mutation changes are required");
974
+ const before = this.core.info();
975
+ assertCurrentRevision(request.expectedRevision, String(before.revision));
976
+ const clientKeys = /* @__PURE__ */ new Set();
977
+ const viewIds = /* @__PURE__ */ new Set();
978
+ const createdViews = [];
979
+ const affected = /* @__PURE__ */ new Set();
980
+ for (const change of request.changes) if (change.kind === "create-view") {
981
+ if (!change.clientKey || clientKeys.has(change.clientKey)) throw runtimeError("invalid-request", "View clientKey values must be non-empty and unique");
982
+ clientKeys.add(change.clientKey);
983
+ } else {
984
+ if (viewIds.has(change.viewId)) throw runtimeError("invalid-request", "A View ID may occur only once per request");
985
+ viewIds.add(change.viewId);
986
+ }
987
+ return this.withCommitBarrier("mutateView", String(before.revision), context, () => {
988
+ this.core.applyCanonicalMutation(() => {
989
+ for (const change of request.changes) {
990
+ if (change.kind === "create-view") {
991
+ const view = this.core.createView(change.tableId, {
992
+ name: assertEidosFileDisplayName(change.name, "View name"),
993
+ type: change.type,
994
+ position: int64ToSafeNumber(change.position, "position"),
995
+ properties: objectValue(change.layout),
996
+ filter: change.query.filter ? runtimeFilterToCompatibility(change.query.filter) : null,
997
+ sorts: (change.query.sort ?? []).map((sort) => ({
998
+ field: sort.fieldId,
999
+ direction: sort.direction,
1000
+ nulls: sort.nulls ?? "last"
1001
+ }))
1002
+ });
1003
+ createdViews.push({
1004
+ clientKey: change.clientKey,
1005
+ viewId: view.id
1006
+ });
1007
+ affected.add(view.id);
1008
+ continue;
1009
+ }
1010
+ if (!this.allViews().find((view) => view.id === change.viewId)) throw runtimeError("not-found", "View not found");
1011
+ if (change.kind === "delete-view") {
1012
+ this.core.deleteView(change.viewId);
1013
+ affected.add(change.viewId);
1014
+ continue;
1015
+ }
1016
+ const layout = change.patch.layout === void 0 ? void 0 : objectValue(change.patch.layout);
1017
+ const fieldOrder = Array.isArray(layout?.fieldOrder) ? layout.fieldOrder.filter((fieldId) => typeof fieldId === "string") : null;
1018
+ const hiddenFields = Array.isArray(layout?.hiddenFields) ? layout.hiddenFields.filter((fieldId) => typeof fieldId === "string") : [];
1019
+ this.core.updateView(change.viewId, {
1020
+ ...change.patch.name === void 0 ? {} : { name: change.patch.name },
1021
+ ...change.patch.type === void 0 ? {} : { type: change.patch.type },
1022
+ ...change.patch.position === void 0 ? {} : { position: int64ToSafeNumber(change.patch.position, "position") },
1023
+ ...layout === void 0 ? {} : {
1024
+ properties: layout,
1025
+ orderMap: fieldOrder ? Object.fromEntries(fieldOrder.map((fieldId, index) => [fieldId, index])) : null,
1026
+ hiddenFields
1027
+ },
1028
+ ...change.patch.query === void 0 ? {} : {
1029
+ filter: change.patch.query.filter ? runtimeFilterToCompatibility(change.patch.query.filter) : null,
1030
+ sorts: (change.patch.query.sort ?? []).map((sort) => ({
1031
+ field: sort.fieldId,
1032
+ direction: sort.direction,
1033
+ nulls: sort.nulls ?? "last"
1034
+ }))
1035
+ }
1036
+ });
1037
+ affected.add(change.viewId);
1038
+ }
1039
+ }, parseRevision(request.expectedRevision));
1040
+ const after = this.core.info();
1041
+ return {
1042
+ fileId: after.fileId,
1043
+ revision: String(after.revision),
1044
+ changed: String(after.revision) !== String(before.revision),
1045
+ createdViews,
1046
+ affectedViewIds: Array.from(affected).sort(binaryCompare)
1047
+ };
1048
+ }, (result) => ({
1049
+ operation: "mutateView",
1050
+ result: {
1051
+ fileId: result.fileId,
1052
+ revision: result.revision,
1053
+ changed: true,
1054
+ createdViews: result.createdViews,
1055
+ affectedViewIds: result.affectedViewIds
1056
+ }
1057
+ }));
1058
+ }, false, request);
1059
+ }
1060
+ async preflightSchema(request, context) {
1061
+ return this.invoke(context, async () => {
1062
+ this.assertWritable("preflightSchema");
1063
+ const metadata = this.core.info();
1064
+ assertCurrentRevision(request.expectedRevision, String(metadata.revision));
1065
+ const analysis = this.analyzeSchemaChange(request.change);
1066
+ const actionsHash = await hashJson(request.change);
1067
+ const token = this.generator.next();
1068
+ const expiresInMilliseconds = 6e5;
1069
+ const wall = checkedNowInstant(this.environment);
1070
+ const expiresAt = new Date(Date.parse(wall) + expiresInMilliseconds).toISOString();
1071
+ const plan = {
1072
+ token,
1073
+ change: request.change,
1074
+ actionsHash,
1075
+ baseRevision: request.expectedRevision,
1076
+ classification: analysis.classification,
1077
+ dependencies: analysis.dependencies,
1078
+ warnings: analysis.warnings,
1079
+ affectedRows: analysis.affectedRows,
1080
+ valueChanges: analysis.valueChanges,
1081
+ createdAtSequence: ++this.schemaPlanSequence,
1082
+ expiresAtMonotonic: this.environment.clock.nowMilliseconds() + expiresInMilliseconds,
1083
+ expiresAt
1084
+ };
1085
+ const retainedBytes = jcsByteLength(plan);
1086
+ if (retainedBytes > EIDOS_RUNTIME_LIMITS.schemaPlanBytesMax) throw runtimeError("resource-limit", "Schema plan exceeds schemaPlanBytesMax");
1087
+ const dependencies = plan.dependencies.slice(0, EIDOS_RUNTIME_LIMITS.schemaPageSizeMax);
1088
+ const responseBase = {
1089
+ fileId: metadata.fileId,
1090
+ planToken: token,
1091
+ baseRevision: request.expectedRevision,
1092
+ actionsHash,
1093
+ classification: plan.classification,
1094
+ affectedRows: plan.affectedRows,
1095
+ dependencyCount: String(plan.dependencies.length),
1096
+ warnings: plan.warnings.slice(0, EIDOS_RUNTIME_LIMITS.diagnosticsMax),
1097
+ warningsTruncated: plan.warnings.length > EIDOS_RUNTIME_LIMITS.diagnosticsMax,
1098
+ valueChanges: plan.valueChanges.slice(0, EIDOS_RUNTIME_LIMITS.diagnosticsMax),
1099
+ valueChangesTruncated: plan.valueChanges.length > EIDOS_RUNTIME_LIMITS.diagnosticsMax,
1100
+ expiresInMilliseconds,
1101
+ expiresAt
1102
+ };
1103
+ const responseFor = (prefix) => ({
1104
+ ...responseBase,
1105
+ dependencies: prefix,
1106
+ ...prefix.length < plan.dependencies.length ? { dependencyCursor: this.encodeCursor("schema-dependencies", {
1107
+ planToken: token,
1108
+ offset: prefix.length
1109
+ }) } : {}
1110
+ });
1111
+ while (dependencies.length > 0 && jcsByteLength(responseFor(dependencies)) > EIDOS_RUNTIME_LIMITS.responseBytesMax) dependencies.pop();
1112
+ if (jcsByteLength(responseFor(dependencies)) > EIDOS_RUNTIME_LIMITS.responseBytesMax || plan.dependencies.length > 0 && dependencies.length === 0) throw runtimeError("resource-limit", "Schema preflight result cannot fit responseBytesMax");
1113
+ this.evictSchemaPlans(retainedBytes);
1114
+ this.schemaPlans.set(token, plan);
1115
+ return responseFor(dependencies);
1116
+ }, false, request);
1117
+ }
1118
+ async getSchemaPlanDependencies(request, context) {
1119
+ return this.invoke(context, () => {
1120
+ assertLimit(request.limit, EIDOS_RUNTIME_LIMITS.schemaPageSizeMax, "limit");
1121
+ const plan = this.retainedSchemaPlan(request.planToken);
1122
+ let offset = 0;
1123
+ if (request.cursor !== void 0) {
1124
+ const cursor = this.decodeCursor(request.cursor, "schema-dependencies");
1125
+ if (cursor.planToken !== request.planToken || typeof cursor.offset !== "number" || !Number.isSafeInteger(cursor.offset) || cursor.offset < 0) throw runtimeError("invalid-plan", "Invalid dependency cursor");
1126
+ offset = cursor.offset;
1127
+ }
1128
+ const dependencies = plan.dependencies.slice(offset, offset + request.limit);
1129
+ if (offset > plan.dependencies.length) throw runtimeError("invalid-plan", "Dependency cursor is past the end");
1130
+ const responseFor = (prefix) => {
1131
+ const nextOffset = offset + prefix.length;
1132
+ return {
1133
+ fileId: this.core.info().fileId,
1134
+ revision: plan.baseRevision,
1135
+ dependencyCount: String(plan.dependencies.length),
1136
+ dependencies: prefix,
1137
+ nextCursor: nextOffset < plan.dependencies.length ? this.encodeCursor("schema-dependencies", {
1138
+ planToken: plan.token,
1139
+ offset: nextOffset
1140
+ }) : null
1141
+ };
1142
+ };
1143
+ while (dependencies.length > 0 && jcsByteLength(responseFor(dependencies)) > EIDOS_RUNTIME_LIMITS.responseBytesMax) dependencies.pop();
1144
+ if (jcsByteLength(responseFor(dependencies)) > EIDOS_RUNTIME_LIMITS.responseBytesMax || offset < plan.dependencies.length && dependencies.length === 0) throw runtimeError("resource-limit", "Schema dependency cannot fit responseBytesMax");
1145
+ return responseFor(dependencies);
1146
+ }, false, request);
1147
+ }
1148
+ async mutateSchema(request, context) {
1149
+ return this.invoke(context, () => {
1150
+ this.assertWritable("mutateSchema");
1151
+ if (!request.planToken || !/^[0-9a-f-]{36}$/.test(request.planToken)) throw runtimeError("invalid-plan", "Invalid schema plan token");
1152
+ const plan = this.retainedSchemaPlan(request.planToken);
1153
+ if (request.actionsHash !== plan.actionsHash || request.expectedRevision !== plan.baseRevision) throw runtimeError("invalid-plan", "Schema plan binding mismatch");
1154
+ const before = this.core.info();
1155
+ assertCurrentRevision(plan.baseRevision, String(before.revision));
1156
+ if (plan.classification === "forbidden") throw runtimeError("forbidden", "Schema plan is forbidden");
1157
+ if (plan.classification === "explicit-lossy" && request.confirmLossy !== true) throw runtimeError("lossy-confirmation-required", "Schema plan requires confirmLossy:true");
1158
+ this.schemaPlans.delete(plan.token);
1159
+ const createdObjects = [];
1160
+ const affectedTableIds = /* @__PURE__ */ new Set();
1161
+ const affectedFieldIds = /* @__PURE__ */ new Set();
1162
+ return this.withCommitBarrier("mutateSchema", String(before.revision), context, () => {
1163
+ this.core.applyCanonicalMutation(() => {
1164
+ this.applySchemaChange(plan.change, createdObjects, affectedTableIds, affectedFieldIds);
1165
+ }, parseRevision(request.expectedRevision));
1166
+ const after = this.core.info();
1167
+ return {
1168
+ fileId: after.fileId,
1169
+ revision: String(after.revision),
1170
+ changed: String(after.revision) !== String(before.revision),
1171
+ createdObjects,
1172
+ affectedTableIds: Array.from(affectedTableIds).sort(binaryCompare),
1173
+ affectedFieldIds: Array.from(affectedFieldIds).sort(binaryCompare)
1174
+ };
1175
+ }, (result) => ({
1176
+ operation: "mutateSchema",
1177
+ result: {
1178
+ fileId: result.fileId,
1179
+ revision: result.revision,
1180
+ changed: true,
1181
+ createdObjects: result.createdObjects,
1182
+ affectedTableIds: result.affectedTableIds,
1183
+ affectedFieldIds: result.affectedFieldIds
1184
+ }
1185
+ }));
1186
+ }, false, request);
1187
+ }
1188
+ validate(request, context) {
1189
+ return this.invoke(context, () => this.read(() => {
1190
+ assertLimit(request.diagnosticsLimit, EIDOS_RUNTIME_LIMITS.diagnosticsMax, "diagnosticsLimit");
1191
+ const result = this.core.validate({ level: request.level });
1192
+ const metadata = result.metadata;
1193
+ const diagnostics = [...result.errors.map((issue) => validationDiagnostic(issue, "error")), ...result.warnings.map((issue) => validationDiagnostic(issue, "warning"))];
1194
+ const retained = diagnostics.slice(0, request.diagnosticsLimit);
1195
+ return {
1196
+ ...metadata ? {
1197
+ fileId: metadata.fileId,
1198
+ revision: String(metadata.revision)
1199
+ } : {},
1200
+ level: request.level,
1201
+ valid: result.valid,
1202
+ diagnostics: retained,
1203
+ truncated: retained.length < diagnostics.length
1204
+ };
1205
+ }), false, request);
1206
+ }
1207
+ async cancel(request) {
1208
+ const control = this.requestControls.get(request.requestId);
1209
+ if (!control) return;
1210
+ control.cancelled = true;
1211
+ if (this.connection.capabilities().interrupt) try {
1212
+ this.connection.interrupt();
1213
+ } catch {}
1214
+ }
1215
+ close(context) {
1216
+ if (this.state === "closed") return Promise.resolve();
1217
+ try {
1218
+ assertRequestContext(context);
1219
+ } catch (error) {
1220
+ return Promise.reject(mapRuntimeFailure(error));
1221
+ }
1222
+ if (context.signal?.aborted) return Promise.reject(runtimeError("cancelled", "Close was cancelled"));
1223
+ if (this.state === "open") this.state = "closing";
1224
+ return this.invoke(context, () => {
1225
+ this.schemaPlans.clear();
1226
+ this.state = "closed";
1227
+ }, true);
1228
+ }
1229
+ snapshot() {
1230
+ const metadata = this.core.info();
1231
+ const tables = this.core.listTables();
1232
+ const fields = tables.flatMap((table) => this.core.listFields(table.id));
1233
+ const views = tables.flatMap((table) => this.core.listViews(table.id));
1234
+ return {
1235
+ fileId: metadata.fileId,
1236
+ format: {
1237
+ major: 1,
1238
+ minor: 0
1239
+ },
1240
+ revision: String(metadata.revision),
1241
+ title: metadata.title ?? "Untitled",
1242
+ defaultTableId: metadata.defaultTableId ?? null,
1243
+ schemaCounts: {
1244
+ tables: String(tables.length),
1245
+ fields: String(fields.length),
1246
+ views: String(views.length),
1247
+ features: "0"
1248
+ }
1249
+ };
1250
+ }
1251
+ schemaDescriptors() {
1252
+ const tables = this.core.listTables();
1253
+ const tableDescriptors = tables.map((table) => {
1254
+ const label = this.core.listFields(table.id).find((field) => field.isRecordLabel);
1255
+ if (!label?.id) throw runtimeError("corrupt-file", "Table has no Record Label Field", { tableId: table.id });
1256
+ return {
1257
+ object: "table",
1258
+ id: table.id,
1259
+ name: table.name,
1260
+ labelFieldId: label.id,
1261
+ position: String(table.position ?? 0),
1262
+ settings: objectValue({
1263
+ ...table.icon === null ? {} : { icon: table.icon },
1264
+ ...table.description === null ? {} : { description: table.description }
1265
+ })
1266
+ };
1267
+ });
1268
+ const fieldDescriptors = tables.flatMap((table) => this.core.listFields(table.id).map((field) => fieldDescriptor(field)));
1269
+ const views = tables.flatMap((table) => this.core.listViews(table.id).map((view) => ({
1270
+ object: "view",
1271
+ id: view.id,
1272
+ tableId: view.tableId,
1273
+ name: view.name,
1274
+ type: view.type,
1275
+ query: {
1276
+ ...view.filter ? { filter: compatibilityFilterToRuntime(view.filter) } : {},
1277
+ ...view.sorts.length > 0 ? { sort: view.sorts.map((sort) => ({
1278
+ fieldId: sort.field,
1279
+ direction: sort.direction,
1280
+ ...sort.nulls ? { nulls: sort.nulls } : {}
1281
+ })) } : {}
1282
+ },
1283
+ layout: objectValue(view.properties ?? {}),
1284
+ position: String(view.position ?? 0)
1285
+ })));
1286
+ return [
1287
+ ...tableDescriptors,
1288
+ ...fieldDescriptors,
1289
+ ...views
1290
+ ];
1291
+ }
1292
+ columns(tableId, projection) {
1293
+ const fields = this.core.listFields(tableId);
1294
+ return projection.fields.map((fieldId) => {
1295
+ const field = fields.find((entry) => entry.id === fieldId);
1296
+ if (!field) throw runtimeError("not-found", "Projection Field not found", {
1297
+ tableId,
1298
+ fieldId
1299
+ });
1300
+ const relation = relationDefinition(field);
1301
+ return {
1302
+ fieldId,
1303
+ name: field.name,
1304
+ valueType: fieldValueType(field),
1305
+ source: field.type === "formula" ? "formula" : field.type === "lookup" ? "lookup" : field.type === "relation" && relation?.direction === "inverse" ? "inverse-relation" : "stored",
1306
+ writable: fieldWritable(field)
1307
+ };
1308
+ });
1309
+ }
1310
+ projectRows(tableId, projection, rows, columns) {
1311
+ const fields = this.core.listFields(tableId);
1312
+ return rows.map((row) => {
1313
+ const projected = {
1314
+ id: row.id,
1315
+ values: projection.fields.map((fieldId, index) => compatibilityLogicalValue(row.fields[fieldId] ?? null, columns[index].valueType))
1316
+ };
1317
+ const resolvedRelations = projection.resolveRelations.flatMap((fieldId) => {
1318
+ const column = projection.fields.indexOf(fieldId);
1319
+ if (column < 0) return [];
1320
+ const field = fields.find((entry) => entry.id === fieldId);
1321
+ const definition = field ? relationDefinition(field) : void 0;
1322
+ if (!field || !definition) return [];
1323
+ const labelField = this.core.listFields(definition.targetTableId).find((entry) => entry.isRecordLabel);
1324
+ if (!labelField?.id) return [];
1325
+ return [{
1326
+ column,
1327
+ items: (row.resolved?.[fieldId] ?? []).map((item) => ({
1328
+ id: item.id,
1329
+ state: "resolved",
1330
+ labelFieldId: labelField.id,
1331
+ labelType: fieldValueType(labelField),
1332
+ label: item.label
1333
+ }))
1334
+ }];
1335
+ });
1336
+ if (resolvedRelations.length > 0) projected.resolvedRelations = resolvedRelations;
1337
+ if (projected.values.length !== columns.length) throw runtimeError("fatal", "Columnar projection length mismatch");
1338
+ return projected;
1339
+ });
1340
+ }
1341
+ aggregateNow(request) {
1342
+ if (request.items.length < 1 || request.items.length > EIDOS_RUNTIME_LIMITS.aggregateItemsMax) throw runtimeError("invalid-request", "Aggregate items exceed aggregateItemsMax");
1343
+ const keys = /* @__PURE__ */ new Set();
1344
+ const fields = this.core.listFields(request.tableId);
1345
+ const fieldsById = new Map(fields.map((field) => [field.id, field]));
1346
+ const fieldIds = Array.from(new Set([...request.items.flatMap((item) => item.op === "count-all" ? [] : [item.fieldId]), ...runtimeQueryFieldIds(request.query)]));
1347
+ for (const fieldId of fieldIds) if (!fieldsById.has(fieldId)) throw runtimeError("not-found", "Aggregate Field not found", { fieldId });
1348
+ const rows = this.core.runtimeScanLogicalRows(request.tableId, fieldIds, this.compatibilityQuery(request.tableId, request.query ?? {})).sort((left, right) => binaryCompare(left.id, right.id));
1349
+ const results = request.items.map((item) => {
1350
+ if (!item.key || keys.has(item.key)) throw runtimeError("invalid-request", "Aggregate keys must be non-empty and unique");
1351
+ keys.add(item.key);
1352
+ if (item.op === "count-all") return {
1353
+ key: item.key,
1354
+ value: String(rows.length)
1355
+ };
1356
+ return aggregateItemResult(item, fieldValueType(fieldsById.get(item.fieldId)), rows.map((row) => row.fields[item.fieldId] ?? null));
1357
+ });
1358
+ const metadata = this.core.info();
1359
+ return {
1360
+ fileId: metadata.fileId,
1361
+ tableId: request.tableId,
1362
+ revision: String(metadata.revision),
1363
+ results
1364
+ };
1365
+ }
1366
+ compatibilityQuery(tableId, query) {
1367
+ assertRuntimeRowQuery(this.core.listFields(tableId), query);
1368
+ return runtimeQueryToCompatibility(query);
1369
+ }
1370
+ async groupRowsNow(request) {
1371
+ assertLimit(request.groupLimit, EIDOS_RUNTIME_LIMITS.groupPageSizeMax, "groupLimit");
1372
+ assertLimit(request.rowsPerGroup, EIDOS_RUNTIME_LIMITS.pageSizeMax, "rowsPerGroup");
1373
+ if (request.groupBy.length < 1 || request.groupBy.length > EIDOS_RUNTIME_LIMITS.groupFieldsMax || new Set(request.groupBy).size !== request.groupBy.length) throw runtimeError("invalid-query", "groupBy is invalid");
1374
+ assertProjection(request.projection);
1375
+ if (request.aggregates.length > EIDOS_RUNTIME_LIMITS.aggregateItemsMax) throw runtimeError("invalid-request", "Group aggregates exceed aggregateItemsMax");
1376
+ const fields = this.core.listFields(request.tableId);
1377
+ const fieldsById = new Map(fields.map((field) => [field.id, field]));
1378
+ const groupTypes = request.groupBy.map((fieldId) => {
1379
+ const field = fieldsById.get(fieldId);
1380
+ const type = field ? fieldValueType(field) : void 0;
1381
+ if (!field || typeof type !== "string" || !isSortableType(type)) throw runtimeError("invalid-query", "Group Field is not groupable", { fieldId });
1382
+ return type;
1383
+ });
1384
+ assertAggregateItems(request.aggregates, fieldsById);
1385
+ const required = Array.from(new Set([
1386
+ ...request.projection.fields,
1387
+ ...request.groupBy,
1388
+ ...request.aggregates.flatMap((item) => item.op === "count-all" ? [] : [item.fieldId]),
1389
+ ...runtimeQueryFieldIds(request.query)
1390
+ ]));
1391
+ const sourceRows = this.core.runtimeScanLogicalRows(request.tableId, required, this.compatibilityQuery(request.tableId, request.query));
1392
+ const grouped = /* @__PURE__ */ new Map();
1393
+ for (const row of sourceRows) {
1394
+ const rawKey = request.groupBy.map((fieldId) => row.fields[fieldId] ?? null);
1395
+ const identity = groupIdentity(rawKey, groupTypes);
1396
+ const existing = grouped.get(identity);
1397
+ if (existing) existing.rows.push(row);
1398
+ else grouped.set(identity, {
1399
+ identity,
1400
+ rawKey,
1401
+ key: rawKey.map((value, index) => value === null ? null : publicAggregateValue(value, groupTypes[index])),
1402
+ rows: [row]
1403
+ });
1404
+ }
1405
+ const ordered = Array.from(grouped.values()).sort((left, right) => compareGroupKeys(left.rawKey, right.rawKey, groupTypes));
1406
+ const metadata = this.core.info();
1407
+ const projectionDigest = await projectionHash(request.projection);
1408
+ const bindingDigest = await groupBindingHash(request);
1409
+ const direction = request.direction ?? "forward";
1410
+ let boundary = direction === "forward" ? -1 : ordered.length;
1411
+ if (request.cursor !== void 0) {
1412
+ const cursor = this.decodeCursor(request.cursor, "groups");
1413
+ if (cursor.fileId !== metadata.fileId || cursor.tableId !== request.tableId || cursor.bindingHash !== bindingDigest || cursor.projectionHash !== projectionDigest || typeof cursor.groupIdentity !== "string") throw runtimeError("invalid-query", "Group cursor binding mismatch");
1414
+ if (cursor.revision !== String(metadata.revision)) throw runtimeError("stale-revision", "Group cursor revision is stale", { currentRevision: String(metadata.revision) });
1415
+ boundary = ordered.findIndex((entry) => entry.identity === cursor.groupIdentity);
1416
+ if (boundary < 0) throw runtimeError("invalid-query", "Group cursor boundary is invalid");
1417
+ }
1418
+ const start = direction === "forward" ? boundary + 1 : Math.max(0, boundary - request.groupLimit);
1419
+ const end = direction === "forward" ? Math.min(ordered.length, start + request.groupLimit) : boundary;
1420
+ const selected = ordered.slice(start, end);
1421
+ const visibleRowIds = selected.flatMap((group) => group.rows.slice(0, request.rowsPerGroup).map((row) => row.id));
1422
+ let projectionRows = new Map(sourceRows.map((row) => [row.id, row]));
1423
+ if (request.projection.resolveRelations.length > 0) projectionRows = new Map(this.fetchRowsByIds(request.tableId, visibleRowIds, request.projection).map((row) => [row.id, row]));
1424
+ const columns = this.columns(request.tableId, request.projection);
1425
+ const cursorForGroup = (group) => group ? this.encodeCursor("groups", {
1426
+ fileId: metadata.fileId,
1427
+ tableId: request.tableId,
1428
+ revision: String(metadata.revision),
1429
+ projectionHash: projectionDigest,
1430
+ bindingHash: bindingDigest,
1431
+ groupIdentity: group.identity
1432
+ }) : null;
1433
+ return {
1434
+ fileId: metadata.fileId,
1435
+ tableId: request.tableId,
1436
+ revision: String(metadata.revision),
1437
+ projectionHash: projectionDigest,
1438
+ columns,
1439
+ groups: selected.map((group) => {
1440
+ const visible = group.rows.slice(0, request.rowsPerGroup);
1441
+ const projected = visible.map((row) => projectionRows.get(row.id) ?? row);
1442
+ const groupedQuery = queryForGroup(request.query, request.groupBy, group.key);
1443
+ const backwardGroupedQuery = reverseRuntimeQuery(groupedQuery, this.core.listFields(request.tableId));
1444
+ const rowCursor = (row) => this.encodeCursor("group-rows", {
1445
+ fileId: metadata.fileId,
1446
+ tableId: request.tableId,
1447
+ revision: String(metadata.revision),
1448
+ projectionHash: projectionDigest,
1449
+ bindingHash: bindingDigest,
1450
+ request: groupCursorSource(request),
1451
+ groupKey: group.key,
1452
+ forward: this.core.createRowCursor(request.tableId, this.compatibilityQuery(request.tableId, groupedQuery), row),
1453
+ backward: this.core.createRowCursor(request.tableId, this.compatibilityQuery(request.tableId, backwardGroupedQuery), row)
1454
+ });
1455
+ return {
1456
+ key: group.key,
1457
+ count: String(group.rows.length),
1458
+ aggregates: aggregateResultsForRows(request.aggregates, fieldsById, group.rows),
1459
+ rows: this.projectRows(request.tableId, request.projection, projected, columns),
1460
+ nextRowCursor: visible.length < group.rows.length && visible.length > 0 ? rowCursor(visible.at(-1)) : null
1461
+ };
1462
+ }),
1463
+ nextCursor: end < ordered.length ? cursorForGroup(selected.at(-1)) : null,
1464
+ previousCursor: start > 0 ? cursorForGroup(selected[0]) : null
1465
+ };
1466
+ }
1467
+ async getRowsByIdDirect(tableId, rowIds, projection) {
1468
+ const rows = this.fetchRowsByIds(tableId, rowIds, projection);
1469
+ const found = new Set(rows.map((row) => row.id));
1470
+ const metadata = this.core.info();
1471
+ const columns = this.columns(tableId, projection);
1472
+ return {
1473
+ fileId: metadata.fileId,
1474
+ tableId,
1475
+ revision: String(metadata.revision),
1476
+ projectionHash: await projectionHash(projection),
1477
+ columns,
1478
+ rows: this.projectRows(tableId, projection, rows, columns),
1479
+ missingRowIds: rowIds.filter((id) => !found.has(id))
1480
+ };
1481
+ }
1482
+ fetchRowsByIds(tableId, rowIds, projection) {
1483
+ if (rowIds.length === 0) return [];
1484
+ const rowIdField = this.core.listFields(tableId).find((field) => field.systemRole === "row-id" || field.type === "row-id");
1485
+ if (!rowIdField?.id) throw runtimeError("corrupt-file", "Table is missing its Row-ID Field");
1486
+ const found = /* @__PURE__ */ new Map();
1487
+ for (let offset = 0; offset < rowIds.length; offset += EIDOS_RUNTIME_LIMITS.rowsByIdMax) {
1488
+ const ids = rowIds.slice(offset, offset + EIDOS_RUNTIME_LIMITS.rowsByIdMax);
1489
+ const rows = this.core.queryRows(tableId, {
1490
+ fields: projection.fields,
1491
+ query: this.compatibilityQuery(tableId, { filter: {
1492
+ op: "in",
1493
+ fieldId: rowIdField.id,
1494
+ values: ids
1495
+ } }),
1496
+ limit: ids.length,
1497
+ resolveRelations: projection.resolveRelations.length > 0
1498
+ }).rows;
1499
+ for (const row of rows) found.set(row.id, row);
1500
+ }
1501
+ return rowIds.flatMap((rowId) => {
1502
+ const row = found.get(rowId);
1503
+ return row ? [row] : [];
1504
+ });
1505
+ }
1506
+ allViews() {
1507
+ return this.core.listTables().flatMap((table) => this.core.listViews(table.id));
1508
+ }
1509
+ analyzeSchemaChange(change) {
1510
+ const leaves = change.kind === "batch" ? change.changes : [change];
1511
+ if (leaves.length === 0) throw runtimeError("invalid-request", "Schema batch must be non-empty");
1512
+ const dependencies = /* @__PURE__ */ new Map();
1513
+ const warnings = [];
1514
+ let classification = "metadata-only";
1515
+ let affectedRows = 0n;
1516
+ const valueChanges = [];
1517
+ const forbid = (code, message, members = {}) => {
1518
+ classification = "forbidden";
1519
+ warnings.push({
1520
+ code,
1521
+ severity: "error",
1522
+ message,
1523
+ ...members
1524
+ });
1525
+ };
1526
+ const lossy = (message, members = {}) => {
1527
+ if (classification !== "forbidden") classification = "explicit-lossy";
1528
+ warnings.push({
1529
+ code: "object-delete-loss",
1530
+ severity: "warning",
1531
+ message,
1532
+ ...members
1533
+ });
1534
+ };
1535
+ const tableIds = new Set(this.core.listTables().map((table) => table.id));
1536
+ const fields = this.core.listTables().flatMap((table) => this.core.listFields(table.id));
1537
+ const fieldsById = new Map(fields.map((field) => [field.id, field]));
1538
+ const proposedFields = new Map(fields.map((field) => [field.id, {
1539
+ ...field,
1540
+ settings: { ...field.settings ?? {} },
1541
+ property: field.property ? { ...field.property } : null
1542
+ }]));
1543
+ const tableNames = new Map(this.core.listTables().map((table) => [table.id, table.name]));
1544
+ let syntheticField = 0;
1545
+ let rewrittenFormulaSources = 0;
1546
+ for (const leaf of leaves) switch (leaf.kind) {
1547
+ case "create-table": {
1548
+ const tableId = `new-table:${leaf.clientKey}`;
1549
+ tableNames.set(tableId, leaf.name);
1550
+ for (const system of simulatedSystemFields(tableId, leaf.name)) proposedFields.set(system.id, system);
1551
+ for (const field of leaf.fields) {
1552
+ const candidate = simulatedNewField(tableId, leaf.name, field, ++syntheticField);
1553
+ proposedFields.set(candidate.id, candidate);
1554
+ }
1555
+ break;
1556
+ }
1557
+ case "delete-table":
1558
+ for (const [id, field] of proposedFields) if (field.tableId === leaf.tableId) proposedFields.delete(id);
1559
+ tableNames.delete(leaf.tableId);
1560
+ break;
1561
+ case "create-field": {
1562
+ const candidate = simulatedNewField(leaf.tableId, tableNames.get(leaf.tableId) ?? leaf.tableId, leaf.field, ++syntheticField);
1563
+ proposedFields.set(candidate.id, candidate);
1564
+ break;
1565
+ }
1566
+ case "delete-field":
1567
+ proposedFields.delete(leaf.fieldId);
1568
+ break;
1569
+ case "rename-field": {
1570
+ const candidate = proposedFields.get(leaf.fieldId);
1571
+ if (!candidate) break;
1572
+ const oldName = candidate.name;
1573
+ for (const formula of proposedFields.values()) {
1574
+ if (formula.tableId !== candidate.tableId || formula.type !== "formula") continue;
1575
+ const source = String(formula.property?.formula ?? "");
1576
+ const rewritten = rewriteEidosFileFormulaFieldReferences(source, oldName, leaf.name);
1577
+ if (rewritten !== source) {
1578
+ formula.property = {
1579
+ ...formula.property ?? {},
1580
+ formula: rewritten
1581
+ };
1582
+ rewrittenFormulaSources += 1;
1583
+ }
1584
+ }
1585
+ candidate.name = leaf.name;
1586
+ break;
1587
+ }
1588
+ case "set-formula": {
1589
+ const candidate = proposedFields.get(leaf.fieldId);
1590
+ if (candidate?.type === "formula") candidate.property = {
1591
+ ...candidate.property ?? {},
1592
+ formula: leaf.definition.sourceText,
1593
+ displayType: leaf.definition.resultType
1594
+ };
1595
+ break;
1596
+ }
1597
+ case "set-lookup": {
1598
+ const candidate = proposedFields.get(leaf.fieldId);
1599
+ if (candidate?.type === "lookup") candidate.property = {
1600
+ ...candidate.property ?? {},
1601
+ relationField: leaf.definition.relationFieldId,
1602
+ targetField: leaf.definition.targetFieldId,
1603
+ aggregate: leaf.definition.aggregate,
1604
+ distinct: leaf.definition.distinctValues
1605
+ };
1606
+ break;
1607
+ }
1608
+ case "set-relation": {
1609
+ const candidate = proposedFields.get(leaf.fieldId);
1610
+ if (candidate?.type === "relation") {
1611
+ candidate.property = simulatedRelationProperty(leaf.definition);
1612
+ candidate.physicalName = leaf.definition.direction === "forward" ? candidate.physicalName ?? candidate.tableColumnName : null;
1613
+ }
1614
+ break;
1615
+ }
1616
+ case "convert-field": {
1617
+ const candidate = proposedFields.get(leaf.fieldId);
1618
+ if (candidate) {
1619
+ candidate.type = leaf.to;
1620
+ candidate.property = leaf.to === "relation" ? simulatedRelationProperty(leaf.definition) : null;
1621
+ candidate.storageCodec = leaf.to === "relation" ? "relation" : leaf.to === "file" || leaf.to === "multi-select" ? "json_array" : "scalar";
1622
+ candidate.valueKind = leaf.to === "relation" ? "relation" : "source";
1623
+ }
1624
+ break;
1625
+ }
1626
+ }
1627
+ for (let pass = 0; pass < proposedFields.size; pass += 1) {
1628
+ let changed = false;
1629
+ for (const field of proposedFields.values()) {
1630
+ if (field.type !== "lookup" || !field.property) continue;
1631
+ const target = proposedFields.get(String(field.property.targetField));
1632
+ if (!target) continue;
1633
+ const displayType = eidosFileLookupDisplayType(String(field.property.aggregate), target);
1634
+ const valueType = eidosFileLookupValueType(String(field.property.aggregate), target);
1635
+ if (field.property.displayType !== displayType || JSON.stringify(field.property.valueType) !== JSON.stringify(valueType)) {
1636
+ field.property.displayType = displayType;
1637
+ field.property.valueType = valueType;
1638
+ changed = true;
1639
+ }
1640
+ }
1641
+ if (!changed) break;
1642
+ }
1643
+ const proposedByTable = /* @__PURE__ */ new Map();
1644
+ for (const field of proposedFields.values()) {
1645
+ const owner = proposedByTable.get(field.tableId) ?? [];
1646
+ owner.push(field);
1647
+ proposedByTable.set(field.tableId, owner);
1648
+ }
1649
+ const dependencyGraph = /* @__PURE__ */ new Map();
1650
+ for (const field of proposedFields.values()) dependencyGraph.set(field.id, /* @__PURE__ */ new Set());
1651
+ for (const [tableId, tableFields] of proposedByTable) {
1652
+ const names = /* @__PURE__ */ new Map();
1653
+ for (const field of tableFields) {
1654
+ const folded = asciiNoCase(field.name);
1655
+ const duplicate = names.get(folded);
1656
+ if (duplicate && duplicate !== field.id) forbid("semantic-field-invalid", "Field names are not unique", {
1657
+ tableId,
1658
+ fieldId: field.id
1659
+ });
1660
+ else names.set(folded, field.id);
1661
+ }
1662
+ try {
1663
+ for (const compiled of compileEidosFileFormulaFields(tableFields)) for (const dependency of compiled.dependencyFieldIds) dependencyGraph.get(dependency)?.add(compiled.field.id);
1664
+ } catch (error) {
1665
+ forbid("formula-type-invalid", error instanceof Error ? error.message : "Invalid Formula", { tableId });
1666
+ }
1667
+ }
1668
+ for (const field of proposedFields.values()) if (field.type === "lookup") {
1669
+ const relationId = String(field.property?.relationField ?? "");
1670
+ const targetId = String(field.property?.targetField ?? "");
1671
+ const aggregate = String(field.property?.aggregate ?? "");
1672
+ const relation = proposedFields.get(relationId);
1673
+ const target = proposedFields.get(targetId);
1674
+ const targetTableId = String(relation?.property?.targetTableId ?? "");
1675
+ if (relation?.type !== "relation" || relation.tableId !== field.tableId || !target || target.tableId !== targetTableId || ![
1676
+ "values",
1677
+ "first",
1678
+ "count",
1679
+ "sum",
1680
+ "average",
1681
+ "min",
1682
+ "max"
1683
+ ].includes(aggregate) || !eidosFileLookupAggregateSupportsTarget(aggregate, target)) forbid("lookup-invalid", `Lookup ${field.name} is invalid`, {
1684
+ tableId: field.tableId,
1685
+ fieldId: field.id
1686
+ });
1687
+ dependencyGraph.get(relationId)?.add(field.id);
1688
+ dependencyGraph.get(targetId)?.add(field.id);
1689
+ } else if (field.type === "relation" && field.property?.direction === "inverse") {
1690
+ const sourceId = String(field.property.sourceFieldId ?? "");
1691
+ dependencyGraph.get(sourceId)?.add(field.id);
1692
+ }
1693
+ const cycle = smallestDependencyCycle(dependencyGraph);
1694
+ if (cycle) forbid("semantic-cycle", "Derived Field dependency cycle", { relatedFieldIds: cycle });
1695
+ if (rewrittenFormulaSources > 0) classification = "lossless-rewrite";
1696
+ for (const leaf of leaves) {
1697
+ if ("position" in leaf) parseSignedInt64(leaf.position, "position");
1698
+ switch (leaf.kind) {
1699
+ case "create-table":
1700
+ if (leaf.fields.some((field) => field.kind === "relation" || field.kind === "lookup")) forbid("relation-definition-invalid", "Relation and Lookup Fields cannot be created inside create-table");
1701
+ break;
1702
+ case "set-file-title":
1703
+ assertEidosFileDisplayName(leaf.title, "File title");
1704
+ break;
1705
+ case "set-default-table":
1706
+ if (leaf.tableId !== null && !tableIds.has(leaf.tableId)) forbid("dependency-blocked", "Default Table does not exist");
1707
+ break;
1708
+ case "delete-table":
1709
+ if (!tableIds.has(leaf.tableId)) {
1710
+ forbid("dependency-blocked", "Table does not exist", { tableId: leaf.tableId });
1711
+ break;
1712
+ }
1713
+ if (this.core.info().defaultTableId === leaf.tableId) forbid("dependency-blocked", "Clear or retarget the default Table before deletion", { tableId: leaf.tableId });
1714
+ lossy("Deleting a Table removes its rows and Fields", { tableId: leaf.tableId });
1715
+ affectedRows += BigInt(this.core.countRows(leaf.tableId));
1716
+ dependencies.set("table:" + leaf.tableId, {
1717
+ object: "table",
1718
+ id: leaf.tableId
1719
+ });
1720
+ for (const field of this.core.listFields(leaf.tableId)) dependencies.set("field:" + field.id, {
1721
+ object: "field",
1722
+ id: field.id
1723
+ });
1724
+ for (const view of this.core.listViews(leaf.tableId)) dependencies.set("view:" + view.id, {
1725
+ object: "view",
1726
+ id: view.id
1727
+ });
1728
+ break;
1729
+ case "rename-table":
1730
+ case "set-table-settings":
1731
+ case "set-table-position":
1732
+ if (!tableIds.has(leaf.tableId)) forbid("dependency-blocked", "Table does not exist", { tableId: leaf.tableId });
1733
+ break;
1734
+ case "create-field":
1735
+ if (!tableIds.has(leaf.tableId)) forbid("dependency-blocked", "Owning Table does not exist", { tableId: leaf.tableId });
1736
+ if (leaf.field.kind !== "formula" && leaf.field.kind !== "lookup" && leaf.field.kind !== "relation" && leaf.field.nullable === false && this.core.countRows(leaf.tableId) > 0) forbid("non-nullability-blocked", "A populated Table cannot add a non-null scalar Field", { tableId: leaf.tableId });
1737
+ break;
1738
+ case "delete-field": {
1739
+ const field = fieldsById.get(leaf.fieldId);
1740
+ if (!field) {
1741
+ forbid("dependency-blocked", "Field does not exist", { fieldId: leaf.fieldId });
1742
+ break;
1743
+ }
1744
+ if (field.systemRole) forbid("dependency-blocked", "System Fields cannot be deleted", { fieldId: leaf.fieldId });
1745
+ else {
1746
+ lossy("Deleting a Field removes its values", {
1747
+ tableId: field.tableId,
1748
+ fieldId: leaf.fieldId
1749
+ });
1750
+ affectedRows += BigInt(this.core.countRows(field.tableId));
1751
+ }
1752
+ dependencies.set("field:" + leaf.fieldId, {
1753
+ object: "field",
1754
+ id: leaf.fieldId
1755
+ });
1756
+ break;
1757
+ }
1758
+ case "rename-field":
1759
+ case "set-field-settings":
1760
+ case "set-field-position":
1761
+ case "set-formula":
1762
+ case "set-lookup":
1763
+ case "set-relation":
1764
+ case "rename-option":
1765
+ if (!fieldsById.has(leaf.fieldId)) forbid("dependency-blocked", "Field does not exist", { fieldId: leaf.fieldId });
1766
+ if (leaf.kind === "rename-option" && leaf.collision === "merge" && !warnings.some((warning) => warning.severity === "error")) {
1767
+ classification = "explicit-lossy";
1768
+ warnings.push({
1769
+ code: "option-merge-loss",
1770
+ severity: "warning",
1771
+ fieldId: leaf.fieldId,
1772
+ message: "Option values may merge"
1773
+ });
1774
+ }
1775
+ break;
1776
+ case "set-record-label":
1777
+ if (!tableIds.has(leaf.tableId) || fieldsById.get(leaf.fieldId)?.tableId !== leaf.tableId) forbid("record-label-blocked", "Record Label Field is invalid", {
1778
+ tableId: leaf.tableId,
1779
+ fieldId: leaf.fieldId
1780
+ });
1781
+ break;
1782
+ case "set-field-nullable": {
1783
+ const field = fieldsById.get(leaf.fieldId);
1784
+ if (!field || field.systemRole || !field.physicalName) forbid("non-nullability-blocked", "Only stored scalar/JSON Fields support nullable changes", { fieldId: leaf.fieldId });
1785
+ else if (leaf.nullable === false) {
1786
+ const table = this.core.getTable(field.tableId);
1787
+ const nulls = this.core.connection.get("SELECT count(*) AS count FROM " + quoteSqlIdentifier(table.physicalName ?? table.rawTableName) + " WHERE " + quoteSqlIdentifier(field.physicalName) + " IS NULL")?.count;
1788
+ if (BigInt(nulls ?? 0) > 0n) forbid("non-nullability-blocked", "Existing SQL NULL values block non-nullability", {
1789
+ tableId: field.tableId,
1790
+ fieldId: leaf.fieldId
1791
+ });
1792
+ }
1793
+ break;
1794
+ }
1795
+ case "convert-field": {
1796
+ const field = fieldsById.get(leaf.fieldId);
1797
+ if (!field || field.systemRole || !field.physicalName || ["formula", "lookup"].includes(field.type)) {
1798
+ forbid("conversion-domain-invalid", "Only stored user Fields support convert-field", { fieldId: leaf.fieldId });
1799
+ break;
1800
+ }
1801
+ const conversion = this.conversionPlan(leaf);
1802
+ if (conversion.classification === "forbidden") {
1803
+ forbid("conversion-domain-invalid", conversion.error ?? "Stored values cannot be converted", {
1804
+ tableId: field.tableId,
1805
+ fieldId: leaf.fieldId
1806
+ });
1807
+ break;
1808
+ }
1809
+ classification = highestSchemaClassification(classification, conversion.classification);
1810
+ affectedRows += BigInt(conversion.affectedRows);
1811
+ valueChanges.push(...conversion.valueChanges.map((change) => ({
1812
+ ...change,
1813
+ tableId: field.tableId,
1814
+ fieldId: leaf.fieldId
1815
+ })));
1816
+ break;
1817
+ }
1818
+ }
1819
+ }
1820
+ const orderedDependencies = Array.from(dependencies.values()).sort((left, right) => {
1821
+ const order = {
1822
+ table: 0,
1823
+ field: 1,
1824
+ view: 2
1825
+ };
1826
+ return order[left.object] - order[right.object] || binaryCompare(left.id, right.id);
1827
+ });
1828
+ return {
1829
+ classification,
1830
+ dependencies: orderedDependencies,
1831
+ warnings,
1832
+ affectedRows: String(affectedRows),
1833
+ valueChanges
1834
+ };
1835
+ }
1836
+ conversionPlan(change) {
1837
+ const field = this.field(change.fieldId);
1838
+ if (!field.physicalName) return {
1839
+ classification: "forbidden",
1840
+ rows: [],
1841
+ affectedRows: "0",
1842
+ valueChanges: [],
1843
+ error: "Virtual and inverse Fields cannot be converted"
1844
+ };
1845
+ const table = this.core.getTable(field.tableId);
1846
+ const rows = this.core.connection.query(`SELECT "_id" AS id, ${quoteSqlIdentifier(field.physicalName)} AS value
1847
+ FROM ${quoteSqlIdentifier(table.physicalName ?? table.rawTableName)}
1848
+ ORDER BY "_id" COLLATE BINARY`);
1849
+ let relationIds;
1850
+ if (change.to === "relation") {
1851
+ const target = this.core.getTable(change.definition.targetTableId);
1852
+ relationIds = new Set(this.core.connection.query(`SELECT "_id" AS id FROM ${quoteSqlIdentifier(target.physicalName ?? target.rawTableName)}`).map((row) => row.id));
1853
+ }
1854
+ return planCanonicalFieldConversion({
1855
+ from: field.type,
1856
+ to: change.to,
1857
+ toNullable: "toNullable" in change ? change.toNullable : false,
1858
+ policies: change.policies,
1859
+ rows,
1860
+ ...relationIds ? { relationIdValid: (id) => relationIds.has(id) } : {},
1861
+ ...change.to === "relation" ? { relationCardinality: change.definition.cardinality } : {}
1862
+ });
1863
+ }
1864
+ applySchemaChange(change, createdObjects, affectedTableIds, affectedFieldIds) {
1865
+ const leaves = change.kind === "batch" ? change.changes : [change];
1866
+ for (const leaf of leaves) switch (leaf.kind) {
1867
+ case "create-table": {
1868
+ const table = this.core.createTable({
1869
+ name: leaf.name,
1870
+ createDefaultView: false,
1871
+ fields: leaf.fields.map(newFieldInput)
1872
+ });
1873
+ affectedTableIds.add(table.id);
1874
+ const fields = this.core.listFields(table.id);
1875
+ createdObjects.push({
1876
+ id: table.id,
1877
+ object: "table",
1878
+ clientKey: leaf.clientKey
1879
+ });
1880
+ for (const field of fields) {
1881
+ if (field.systemRole) createdObjects.push({
1882
+ id: field.id,
1883
+ object: "field",
1884
+ systemRole: field.systemRole
1885
+ });
1886
+ else {
1887
+ const source = leaf.fields.find((candidate) => candidate.name === field.name);
1888
+ if (source) createdObjects.push({
1889
+ id: field.id,
1890
+ object: "field",
1891
+ clientKey: source.clientKey
1892
+ });
1893
+ }
1894
+ affectedFieldIds.add(field.id);
1895
+ }
1896
+ this.core.connection.run("UPDATE eidos__tables SET position=?, settings_json=? WHERE id=?", [
1897
+ parseSignedInt64(leaf.position, "position"),
1898
+ canonicalizeEidosFileJson(leaf.settings ?? {}),
1899
+ table.id
1900
+ ]);
1901
+ for (const source of leaf.fields) {
1902
+ const field = fields.find((entry) => entry.name === source.name);
1903
+ if (!field) continue;
1904
+ this.core.connection.run("UPDATE eidos__fields SET position=?, settings_json=? WHERE id=?", [
1905
+ parseSignedInt64(source.position, "position"),
1906
+ canonicalizeEidosFileJson(source.settings ?? {}),
1907
+ field.id
1908
+ ]);
1909
+ }
1910
+ if (leaf.labelFieldClientKey) {
1911
+ const source = leaf.fields.find((field) => field.clientKey === leaf.labelFieldClientKey);
1912
+ const label = source ? fields.find((field) => field.name === source.name) : void 0;
1913
+ if (!label?.id) throw runtimeError("invalid-request", "labelFieldClientKey does not identify a supplied Field");
1914
+ this.core.updateField(table.id, label.id, { isRecordLabel: true });
1915
+ }
1916
+ break;
1917
+ }
1918
+ case "set-file-title":
1919
+ this.core.connection.run("UPDATE eidos__meta SET title=? WHERE singleton=1", [assertEidosFileDisplayName(leaf.title, "File title")]);
1920
+ break;
1921
+ case "set-default-table":
1922
+ this.core.connection.run("UPDATE eidos__meta SET default_table_id=? WHERE singleton=1", [leaf.tableId]);
1923
+ break;
1924
+ case "delete-table":
1925
+ this.core.deleteTable(leaf.tableId);
1926
+ affectedTableIds.add(leaf.tableId);
1927
+ break;
1928
+ case "rename-table":
1929
+ this.core.updateTable(leaf.tableId, { name: leaf.name });
1930
+ affectedTableIds.add(leaf.tableId);
1931
+ break;
1932
+ case "set-table-settings":
1933
+ this.core.connection.run("UPDATE eidos__tables SET settings_json=? WHERE id=?", [canonicalizeEidosFileJson(leaf.settings), leaf.tableId]);
1934
+ affectedTableIds.add(leaf.tableId);
1935
+ break;
1936
+ case "set-table-position":
1937
+ this.core.connection.run("UPDATE eidos__tables SET position=? WHERE id=?", [parseSignedInt64(leaf.position, "position"), leaf.tableId]);
1938
+ affectedTableIds.add(leaf.tableId);
1939
+ break;
1940
+ case "create-field": {
1941
+ const field = this.core.addField(leaf.tableId, newFieldInput(leaf.field));
1942
+ this.core.connection.run("UPDATE eidos__fields SET position=?, settings_json=? WHERE id=?", [
1943
+ parseSignedInt64(leaf.field.position, "position"),
1944
+ canonicalizeEidosFileJson(leaf.field.settings ?? {}),
1945
+ field.id
1946
+ ]);
1947
+ createdObjects.push({
1948
+ id: field.id,
1949
+ object: "field",
1950
+ clientKey: leaf.field.clientKey
1951
+ });
1952
+ affectedTableIds.add(leaf.tableId);
1953
+ affectedFieldIds.add(field.id);
1954
+ break;
1955
+ }
1956
+ case "delete-field": {
1957
+ const field = this.field(leaf.fieldId);
1958
+ if (field.isRecordLabel && leaf.replacementLabelFieldId) this.core.updateField(field.tableId, leaf.replacementLabelFieldId, { isRecordLabel: true });
1959
+ this.core.deleteField(field.tableId, leaf.fieldId);
1960
+ affectedTableIds.add(field.tableId);
1961
+ affectedFieldIds.add(leaf.fieldId);
1962
+ break;
1963
+ }
1964
+ case "rename-field": {
1965
+ const field = this.field(leaf.fieldId);
1966
+ this.core.updateField(field.tableId, leaf.fieldId, { name: leaf.name });
1967
+ affectedTableIds.add(field.tableId);
1968
+ affectedFieldIds.add(leaf.fieldId);
1969
+ break;
1970
+ }
1971
+ case "set-field-settings": {
1972
+ const field = this.field(leaf.fieldId);
1973
+ this.core.connection.run("UPDATE eidos__fields SET settings_json=? WHERE id=?", [canonicalizeEidosFileJson(leaf.settings), leaf.fieldId]);
1974
+ affectedTableIds.add(field.tableId);
1975
+ affectedFieldIds.add(leaf.fieldId);
1976
+ break;
1977
+ }
1978
+ case "set-field-position": {
1979
+ const field = this.field(leaf.fieldId);
1980
+ this.core.connection.run("UPDATE eidos__fields SET position=? WHERE id=?", [parseSignedInt64(leaf.position, "position"), leaf.fieldId]);
1981
+ affectedTableIds.add(field.tableId);
1982
+ affectedFieldIds.add(leaf.fieldId);
1983
+ break;
1984
+ }
1985
+ case "set-record-label":
1986
+ this.core.updateField(leaf.tableId, leaf.fieldId, { isRecordLabel: true });
1987
+ affectedTableIds.add(leaf.tableId);
1988
+ affectedFieldIds.add(leaf.fieldId);
1989
+ break;
1990
+ case "set-formula": {
1991
+ const field = this.field(leaf.fieldId);
1992
+ this.core.updateField(field.tableId, leaf.fieldId, { property: {
1993
+ ...field.settings ?? {},
1994
+ formula: leaf.definition.sourceText,
1995
+ displayType: leaf.definition.resultType
1996
+ } });
1997
+ affectedTableIds.add(field.tableId);
1998
+ affectedFieldIds.add(leaf.fieldId);
1999
+ break;
2000
+ }
2001
+ case "set-lookup": {
2002
+ const field = this.field(leaf.fieldId);
2003
+ this.core.updateField(field.tableId, leaf.fieldId, { property: {
2004
+ ...field.settings ?? {},
2005
+ relationField: leaf.definition.relationFieldId,
2006
+ targetField: leaf.definition.targetFieldId,
2007
+ aggregate: leaf.definition.aggregate,
2008
+ distinct: leaf.definition.distinctValues
2009
+ } });
2010
+ affectedTableIds.add(field.tableId);
2011
+ affectedFieldIds.add(leaf.fieldId);
2012
+ break;
2013
+ }
2014
+ case "set-relation": {
2015
+ const field = this.field(leaf.fieldId);
2016
+ this.core.updateField(field.tableId, leaf.fieldId, { property: leaf.definition.direction === "forward" ? {
2017
+ ...field.settings ?? {},
2018
+ direction: "forward",
2019
+ targetTableId: leaf.definition.targetTableId,
2020
+ cardinality: leaf.definition.cardinality,
2021
+ onDelete: leaf.definition.onDelete
2022
+ } : {
2023
+ ...field.settings ?? {},
2024
+ direction: "inverse",
2025
+ targetTableId: leaf.definition.targetTableId,
2026
+ sourceFieldId: leaf.definition.inverseOfFieldId,
2027
+ cardinality: "many"
2028
+ } });
2029
+ affectedTableIds.add(field.tableId);
2030
+ affectedFieldIds.add(leaf.fieldId);
2031
+ break;
2032
+ }
2033
+ case "rename-option": {
2034
+ const field = this.field(leaf.fieldId);
2035
+ this.core.updateField(field.tableId, leaf.fieldId, { optionValueChanges: [{
2036
+ from: leaf.from,
2037
+ to: leaf.to
2038
+ }] });
2039
+ affectedTableIds.add(field.tableId);
2040
+ affectedFieldIds.add(leaf.fieldId);
2041
+ break;
2042
+ }
2043
+ case "set-field-nullable": {
2044
+ const field = this.field(leaf.fieldId);
2045
+ this.core.setFieldNullable(leaf.fieldId, leaf.nullable);
2046
+ affectedTableIds.add(field.tableId);
2047
+ affectedFieldIds.add(leaf.fieldId);
2048
+ break;
2049
+ }
2050
+ case "convert-field": {
2051
+ const field = this.field(leaf.fieldId);
2052
+ const conversion = this.conversionPlan(leaf);
2053
+ if (conversion.classification === "forbidden") throw runtimeError("forbidden", conversion.error ?? "Conversion predicates no longer hold");
2054
+ this.core.convertStoredField(leaf.fieldId, leaf.to, "toNullable" in leaf ? leaf.toNullable : false, conversion.rows, leaf.to === "relation" ? {
2055
+ targetTableId: leaf.definition.targetTableId,
2056
+ cardinality: leaf.definition.cardinality,
2057
+ onDelete: leaf.definition.onDelete
2058
+ } : void 0);
2059
+ affectedTableIds.add(field.tableId);
2060
+ affectedFieldIds.add(leaf.fieldId);
2061
+ break;
2062
+ }
2063
+ }
2064
+ }
2065
+ field(fieldId) {
2066
+ for (const table of this.core.listTables()) {
2067
+ const field = this.core.listFields(table.id).find((candidate) => candidate.id === fieldId);
2068
+ if (field) return field;
2069
+ }
2070
+ throw runtimeError("not-found", "Field not found", { fieldId });
2071
+ }
2072
+ retainedSchemaPlan(token) {
2073
+ const plan = this.schemaPlans.get(token);
2074
+ if (!plan) throw runtimeError("plan-expired", "Schema plan is not retained");
2075
+ if (this.environment.clock.nowMilliseconds() > plan.expiresAtMonotonic) {
2076
+ this.schemaPlans.delete(token);
2077
+ throw runtimeError("plan-expired", "Schema plan expired");
2078
+ }
2079
+ return plan;
2080
+ }
2081
+ evictSchemaPlans(incomingBytes = 0) {
2082
+ const now = this.environment.clock.nowMilliseconds();
2083
+ for (const [token, plan] of this.schemaPlans) if (now > plan.expiresAtMonotonic) this.schemaPlans.delete(token);
2084
+ const retainedBytes = () => Array.from(this.schemaPlans.values()).reduce((total, plan) => total + jcsByteLength(plan), 0);
2085
+ while (this.schemaPlans.size >= EIDOS_RUNTIME_LIMITS.schemaPlanEntriesMax || retainedBytes() + incomingBytes > EIDOS_RUNTIME_LIMITS.schemaPlanBytesMax) {
2086
+ const oldest = Array.from(this.schemaPlans.values()).sort((left, right) => left.createdAtSequence - right.createdAtSequence)[0];
2087
+ if (!oldest) break;
2088
+ this.schemaPlans.delete(oldest.token);
2089
+ }
2090
+ }
2091
+ allocateFileEntry(request) {
2092
+ const extensions = request.extensions ?? {};
2093
+ for (const key of [
2094
+ "id",
2095
+ "name",
2096
+ "mediaType",
2097
+ "size",
2098
+ "uri"
2099
+ ]) if (Object.prototype.hasOwnProperty.call(extensions, key)) throw runtimeError("invalid-request", "File entry extension collides with required member", { path: "/extensions/" + key });
2100
+ const candidate = {
2101
+ ...extensions,
2102
+ id: this.generator.next(),
2103
+ name: request.name,
2104
+ mediaType: request.mediaType,
2105
+ size: request.size,
2106
+ uri: request.uri
2107
+ };
2108
+ try {
2109
+ return assertEidosFileValues([candidate])[0];
2110
+ } catch (error) {
2111
+ throw runtimeError("invalid-value", error instanceof Error ? error.message : "Invalid File entry");
2112
+ }
2113
+ }
2114
+ read(operation) {
2115
+ return this.connection.transaction("read", operation);
2116
+ }
2117
+ async withCommitBarrier(operation, baseRevision, context, execute, reconciliation) {
2118
+ const barrier = this.environment.transportCommitBarrier;
2119
+ if (!barrier) return execute();
2120
+ return this.connection.transaction("write", async () => {
2121
+ const result = await execute();
2122
+ if (result.changed) {
2123
+ const record = reconciliation(result);
2124
+ if (record.operation !== operation) throw runtimeError("fatal", "Commit reconciliation operation mismatch");
2125
+ assertJcsBytes(record, EIDOS_RUNTIME_LIMITS.responseBytesMax, "Commit reconciliation");
2126
+ await barrier.prepare({
2127
+ fileID: result.fileId,
2128
+ baseRevision,
2129
+ commitRevision: result.revision,
2130
+ reconciliation: record
2131
+ }, context);
2132
+ }
2133
+ return result;
2134
+ });
2135
+ }
2136
+ assertWritable(operation) {
2137
+ if (!this.writable) throw runtimeError("unsupported", operation + " is unavailable read-only");
2138
+ }
2139
+ invoke(context, operation, allowClosing = false, requestPayload, accountResponse = true) {
2140
+ try {
2141
+ assertRequestContext(context);
2142
+ if (requestPayload !== void 0) assertJcsBytes(requestPayload, EIDOS_RUNTIME_LIMITS.requestBytesMax, "Runtime request");
2143
+ } catch (error) {
2144
+ return Promise.reject(mapRuntimeFailure(error));
2145
+ }
2146
+ if (this.state === "closed" || this.state === "fatal" || !allowClosing && this.state !== "open") return Promise.reject(runtimeError(this.state === "fatal" ? "fatal" : "closed", "Runtime is closed"));
2147
+ if (this.requestControls.has(context.requestId)) return Promise.reject(runtimeError("invalid-request", "requestId is already unresolved", { path: "/requestId" }));
2148
+ const acceptedAt = this.environment.clock.nowMilliseconds();
2149
+ const control = {
2150
+ cancelled: context.signal?.aborted === true,
2151
+ unsubscribe: () => void 0
2152
+ };
2153
+ control.unsubscribe = context.signal?.onAbort(() => {
2154
+ control.cancelled = true;
2155
+ }) ?? (() => void 0);
2156
+ this.requestControls.set(context.requestId, control);
2157
+ const execute = async () => {
2158
+ try {
2159
+ if (!allowClosing) this.checkControl(context, control, acceptedAt);
2160
+ const result = await operation();
2161
+ if (result !== void 0 && accountResponse) assertJcsBytes(result, EIDOS_RUNTIME_LIMITS.responseBytesMax, "Runtime response");
2162
+ return result;
2163
+ } catch (error) {
2164
+ const failure = mapRuntimeFailure(error);
2165
+ if (failure.code === "fatal" || failure.code === "unknown-commit") this.state = "fatal";
2166
+ throw failure;
2167
+ } finally {
2168
+ control.unsubscribe();
2169
+ this.requestControls.delete(context.requestId);
2170
+ }
2171
+ };
2172
+ const result = this.queue.then(execute, execute);
2173
+ this.queue = result.then(() => void 0, () => void 0);
2174
+ return result;
2175
+ }
2176
+ checkControl(context, control, acceptedAt) {
2177
+ if (control.cancelled) throw runtimeError("cancelled", "Request was cancelled", { retryable: true });
2178
+ const elapsed = this.environment.clock.nowMilliseconds() - acceptedAt;
2179
+ const budget = Math.min(context.deadlineMilliseconds ?? EIDOS_RUNTIME_LIMITS.foregroundTimeMsMax, EIDOS_RUNTIME_LIMITS.foregroundTimeMsMax);
2180
+ if (!Number.isFinite(elapsed) || elapsed < 0) {
2181
+ this.state = "fatal";
2182
+ throw runtimeError("fatal", "Monotonic clock moved backward");
2183
+ }
2184
+ if (elapsed > budget) throw runtimeError("deadline-exceeded", "Request deadline exceeded", { retryable: true });
2185
+ }
2186
+ encodeCursor(kind, value) {
2187
+ const payload = canonicalizeEidosFileJson({
2188
+ version: 1,
2189
+ epoch: this.epoch,
2190
+ kind,
2191
+ ...value
2192
+ });
2193
+ return encodeURIComponent(payload + "." + cursorMac(this.cursorSecret, payload));
2194
+ }
2195
+ decodeCursor(cursor, kind) {
2196
+ try {
2197
+ const envelope = decodeURIComponent(cursor);
2198
+ const separator = envelope.lastIndexOf(".");
2199
+ if (separator < 1) throw new Error("cursor authentication missing");
2200
+ const payload = envelope.slice(0, separator);
2201
+ if (!constantTimeTextEqual(envelope.slice(separator + 1), cursorMac(this.cursorSecret, payload))) throw new Error("cursor authentication failed");
2202
+ const parsed = JSON.parse(payload);
2203
+ if (parsed.version !== 1 || parsed.epoch !== this.epoch || parsed.kind !== kind) throw new Error("cursor binding mismatch");
2204
+ return parsed;
2205
+ } catch {
2206
+ throw runtimeError("invalid-query", "Invalid or foreign cursor");
2207
+ }
2208
+ }
2209
+ };
2210
+ function fieldDescriptor(field) {
2211
+ const definition = field.type === "relation" ? relationDefinition(field) : field.type === "formula" ? {
2212
+ sourceText: String(field.property?.formula ?? ""),
2213
+ resultType: String(field.property?.displayType ?? "text")
2214
+ } : field.type === "lookup" ? {
2215
+ relationFieldId: String(field.property?.relationField ?? ""),
2216
+ targetFieldId: String(field.property?.targetField ?? ""),
2217
+ aggregate: String(field.property?.aggregate ?? "values"),
2218
+ distinctValues: field.property?.distinct === true
2219
+ } : void 0;
2220
+ return {
2221
+ object: "field",
2222
+ id: field.id,
2223
+ tableId: field.tableId,
2224
+ name: field.name,
2225
+ kind: field.type === "created-time" || field.type === "last-edited-time" ? "datetime" : field.type === "row-id" ? "text" : field.type,
2226
+ valueType: fieldValueType(field),
2227
+ systemRole: field.systemRole ?? null,
2228
+ nullable: field.nullable ?? false,
2229
+ position: String(field.position ?? 0),
2230
+ settings: objectValue(field.settings ?? {}),
2231
+ writable: fieldWritable(field),
2232
+ ...definition ? { definition } : {}
2233
+ };
2234
+ }
2235
+ function fieldValueType(field) {
2236
+ if (field.systemRole === "row-id" || field.type === "row-id") return "row-id";
2237
+ if (field.systemRole === "created-time" || field.systemRole === "updated-time" || field.type === "created-time" || field.type === "last-edited-time") return "datetime";
2238
+ if (field.type === "formula") return String(field.property?.displayType ?? "text");
2239
+ if (field.type === "lookup") {
2240
+ const generated = field.property?.valueType;
2241
+ const generatedObject = generated && typeof generated === "object" ? generated : void 0;
2242
+ if (typeof generated === "string" || generatedObject?.kind === "list" && typeof generatedObject.element === "string") return generated;
2243
+ const display = String(field.property?.displayType ?? "text");
2244
+ if (field.property?.aggregate === "values") return {
2245
+ kind: "list",
2246
+ element: display === "file" ? "file-entry" : display === "relation" ? "row-id" : display === "multi-select" ? "select" : display
2247
+ };
2248
+ return display;
2249
+ }
2250
+ return field.type;
2251
+ }
2252
+ function fieldWritable(field) {
2253
+ const relation = field.type === "relation" ? relationDefinition(field) : void 0;
2254
+ return !field.systemRole && field.type !== "formula" && field.type !== "lookup" && !(field.type === "relation" && relation?.direction === "inverse");
2255
+ }
2256
+ function relationDefinition(field) {
2257
+ if (field.type !== "relation" || !field.property) return void 0;
2258
+ const direction = field.property.direction === "inverse" ? "inverse" : "forward";
2259
+ if (direction === "inverse") return {
2260
+ direction,
2261
+ targetTableId: String(field.property.targetTableId),
2262
+ cardinality: "many",
2263
+ inverseOfFieldId: String(field.property.sourceFieldId)
2264
+ };
2265
+ return {
2266
+ direction,
2267
+ targetTableId: String(field.property.targetTableId),
2268
+ cardinality: field.property.cardinality === "one" ? "one" : "many",
2269
+ onDelete: [
2270
+ "restrict",
2271
+ "detach",
2272
+ "preserve"
2273
+ ].includes(String(field.property.onDelete)) ? field.property.onDelete : "restrict"
2274
+ };
2275
+ }
2276
+ function normalizedRuntimeQuery(query) {
2277
+ return objectValue({
2278
+ ...query.filter === void 0 ? {} : { filter: query.filter },
2279
+ ...query.search === void 0 ? {} : { search: query.search },
2280
+ sort: (query.sort ?? []).map((sort) => ({
2281
+ fieldId: sort.fieldId,
2282
+ direction: sort.direction,
2283
+ nulls: sort.nulls ?? "last"
2284
+ }))
2285
+ });
2286
+ }
2287
+ function runtimeQueryFieldIds(query) {
2288
+ if (!query) return [];
2289
+ const ids = new Set([...query.search?.fields ?? [], ...(query.sort ?? []).map((sort) => sort.fieldId)]);
2290
+ const visit = (node) => {
2291
+ if (node.op === "and" || node.op === "or") {
2292
+ node.args.forEach(visit);
2293
+ return;
2294
+ }
2295
+ if (node.op === "not") {
2296
+ visit(node.arg);
2297
+ return;
2298
+ }
2299
+ if ("fieldId" in node) ids.add(node.fieldId);
2300
+ };
2301
+ if (query.filter) visit(query.filter);
2302
+ return [...ids];
2303
+ }
2304
+ function reverseRuntimeQuery(query, fields) {
2305
+ const sorts = (query.sort ?? []).map((sort) => ({
2306
+ ...sort,
2307
+ direction: sort.direction === "asc" ? "desc" : "asc"
2308
+ }));
2309
+ const rowId = fields.find((field) => field.systemRole === "row-id" || field.type === "row-id");
2310
+ if (rowId && !sorts.some((sort) => sort.fieldId === rowId.id)) sorts.push({
2311
+ fieldId: rowId.id,
2312
+ direction: "desc",
2313
+ nulls: "last"
2314
+ });
2315
+ return {
2316
+ ...query.filter === void 0 ? {} : { filter: query.filter },
2317
+ ...query.search === void 0 ? {} : { search: query.search },
2318
+ sort: sorts
2319
+ };
2320
+ }
2321
+ function runtimeQueryToCompatibility(query) {
2322
+ return {
2323
+ ...query.search ? { search: query.search.text } : {},
2324
+ ...query.search ? { searchFields: [...query.search.fields] } : {},
2325
+ ...query.filter ? { filter: runtimeFilterToCompatibility(query.filter) } : {},
2326
+ sorts: (query.sort ?? []).map((sort) => ({
2327
+ field: sort.fieldId,
2328
+ direction: sort.direction,
2329
+ nulls: sort.nulls ?? "last"
2330
+ }))
2331
+ };
2332
+ }
2333
+ function assertRuntimeRowQuery(fields, query) {
2334
+ if (!query || typeof query !== "object" || Array.isArray(query)) throw runtimeError("invalid-query", "RowQuery must be an object");
2335
+ const byId = new Map(fields.map((field) => [field.id, field]));
2336
+ if (query.search !== void 0) {
2337
+ if (typeof query.search.text !== "string" || new TextEncoder().encode(query.search.text).byteLength > EIDOS_RUNTIME_LIMITS.searchBytesMax || !Array.isArray(query.search.fields) || query.search.fields.length < 1 || query.search.fields.length > EIDOS_RUNTIME_LIMITS.projectionFieldsMax || new Set(query.search.fields).size !== query.search.fields.length) throw runtimeError("invalid-query", "Search request is invalid");
2338
+ for (const fieldId of query.search.fields) {
2339
+ const field = byId.get(fieldId);
2340
+ const type = field ? fieldValueType(field) : void 0;
2341
+ if (!field || typeof type !== "string" || ![
2342
+ "text",
2343
+ "url",
2344
+ "select",
2345
+ "row-id"
2346
+ ].includes(type)) throw runtimeError("invalid-query", "Search Field is not searchable", { fieldId });
2347
+ }
2348
+ }
2349
+ if (query.sort !== void 0) {
2350
+ if (!Array.isArray(query.sort) || query.sort.length > EIDOS_RUNTIME_LIMITS.sortFieldsMax || new Set(query.sort.map((sort) => sort.fieldId)).size !== query.sort.length) throw runtimeError("invalid-query", "Sort list is invalid");
2351
+ query.sort.forEach((sort, index) => {
2352
+ const field = byId.get(sort.fieldId);
2353
+ const type = field ? fieldValueType(field) : void 0;
2354
+ if (!field || typeof type !== "string" || ![
2355
+ "text",
2356
+ "number",
2357
+ "integer",
2358
+ "checkbox",
2359
+ "date",
2360
+ "datetime",
2361
+ "url",
2362
+ "select",
2363
+ "row-id"
2364
+ ].includes(type) || !["asc", "desc"].includes(sort.direction) || sort.nulls !== void 0 && !["first", "last"].includes(sort.nulls) || type === "row-id" && index !== query.sort.length - 1) throw runtimeError("invalid-query", "Sort Field is invalid", { fieldId: sort.fieldId });
2365
+ });
2366
+ }
2367
+ let nodes = 0;
2368
+ const visit = (node, depth) => {
2369
+ nodes += 1;
2370
+ if (depth > EIDOS_RUNTIME_LIMITS.filterDepthMax || nodes > EIDOS_RUNTIME_LIMITS.filterNodesMax) throw runtimeError("resource-limit", "Filter complexity exceeds limits");
2371
+ if (!node || typeof node !== "object" || typeof node.op !== "string") throw runtimeError("invalid-query", "Filter node is invalid");
2372
+ if (node.op === "and" || node.op === "or") {
2373
+ if (!Array.isArray(node.args)) throw runtimeError("invalid-query", "Logical Filter args are invalid");
2374
+ node.args.forEach((child) => visit(child, depth + 1));
2375
+ return;
2376
+ }
2377
+ if (node.op === "not") {
2378
+ visit(node.arg, depth + 1);
2379
+ return;
2380
+ }
2381
+ if (!("fieldId" in node)) throw runtimeError("invalid-query", "Filter Field is required");
2382
+ const field = byId.get(node.fieldId);
2383
+ if (!field) throw runtimeError("invalid-query", "Filter Field does not exist", { fieldId: node.fieldId });
2384
+ const type = fieldValueType(field);
2385
+ if (node.op === "is-null" || node.op === "is-not-null") return;
2386
+ if (node.op === "contains" || node.op === "starts-with" || node.op === "ends-with") {
2387
+ if (typeof type !== "string" || ![
2388
+ "text",
2389
+ "url",
2390
+ "select",
2391
+ "row-id"
2392
+ ].includes(type) || typeof node.value !== "string") throw runtimeError("invalid-query", "String Filter operand is invalid");
2393
+ return;
2394
+ }
2395
+ if (node.op === "has-any" || node.op === "has-all") {
2396
+ if (typeof type === "string" || !Array.isArray(node.values) || !node.values.every((value) => value !== null && logicalValueMatchesType(value, type.element))) throw runtimeError("invalid-query", "List Filter operand is invalid");
2397
+ return;
2398
+ }
2399
+ if (node.op === "relation-has") {
2400
+ if (field.type !== "relation") throw runtimeError("invalid-query", "relation-has requires Relation");
2401
+ try {
2402
+ assertEidosFileUuid(node.rowId, "Row ID");
2403
+ } catch {
2404
+ throw runtimeError("invalid-query", "relation-has Row ID is invalid");
2405
+ }
2406
+ return;
2407
+ }
2408
+ if (node.op === "in") {
2409
+ if (!Array.isArray(node.values) || !node.values.every((value) => value !== null && logicalValueMatchesType(value, type))) throw runtimeError("invalid-query", "in operands are invalid");
2410
+ return;
2411
+ }
2412
+ if (node.op === "between") {
2413
+ if (typeof type !== "string" || !isSortableType(type) || node.lower === null || node.upper === null || !logicalValueMatchesType(node.lower, type) || !logicalValueMatchesType(node.upper, type)) throw runtimeError("invalid-query", "between operands are invalid");
2414
+ return;
2415
+ }
2416
+ if (!("value" in node) || node.value === null || !logicalValueMatchesType(node.value, type) || [
2417
+ "lt",
2418
+ "lte",
2419
+ "gt",
2420
+ "gte"
2421
+ ].includes(node.op) && (typeof type !== "string" || !isSortableType(type))) throw runtimeError("invalid-query", "Filter operand type is invalid");
2422
+ };
2423
+ if (query.filter) visit(query.filter, 1);
2424
+ }
2425
+ function isSortableType(type) {
2426
+ return [
2427
+ "text",
2428
+ "number",
2429
+ "integer",
2430
+ "checkbox",
2431
+ "date",
2432
+ "datetime",
2433
+ "url",
2434
+ "select",
2435
+ "row-id"
2436
+ ].includes(type);
2437
+ }
2438
+ function logicalValueMatchesType(value, type) {
2439
+ if (typeof type === "object") return Array.isArray(value) && value.every((entry) => entry !== null && logicalValueMatchesType(entry, type.element));
2440
+ switch (type) {
2441
+ case "number": return typeof value === "number" && Number.isFinite(value);
2442
+ case "integer": return typeof value === "string" && /^(?:0|-[1-9][0-9]*|[1-9][0-9]*)$/.test(value);
2443
+ case "checkbox": return typeof value === "boolean";
2444
+ case "row-id":
2445
+ if (typeof value !== "string") return false;
2446
+ try {
2447
+ assertEidosFileUuid(value, "Row ID");
2448
+ return true;
2449
+ } catch {
2450
+ return false;
2451
+ }
2452
+ case "text":
2453
+ case "url":
2454
+ case "select":
2455
+ case "date":
2456
+ case "datetime": return typeof value === "string";
2457
+ case "multi-select": return Array.isArray(value) && value.every((entry) => typeof entry === "string");
2458
+ case "relation": return Array.isArray(value) && value.every((entry) => typeof entry === "string");
2459
+ case "file": return Array.isArray(value) && value.every((entry) => isFileEntry(entry));
2460
+ case "file-entry": return isFileEntry(value);
2461
+ case "json":
2462
+ if (typeof value !== "string") return false;
2463
+ try {
2464
+ return canonicalizeEidosFileJson(JSON.parse(value)) === value;
2465
+ } catch {
2466
+ return false;
2467
+ }
2468
+ }
2469
+ }
2470
+ function isFileEntry(value) {
2471
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2472
+ const entry = value;
2473
+ return typeof entry.id === "string" && typeof entry.name === "string" && typeof entry.mediaType === "string" && typeof entry.size === "string" && typeof entry.uri === "string";
2474
+ }
2475
+ function runtimeFilterToCompatibility(node) {
2476
+ const group = (conjunction, children) => ({
2477
+ type: "group",
2478
+ conjunction,
2479
+ children
2480
+ });
2481
+ if (node.op === "and" || node.op === "or") return group(node.op, node.args.map(runtimeFilterToCompatibility));
2482
+ if (node.op === "not") {
2483
+ const nested = runtimeFilterToCompatibility(node.arg);
2484
+ return {
2485
+ ...nested,
2486
+ negated: nested.negated !== true
2487
+ };
2488
+ }
2489
+ if (node.op === "between") return group("and", [{
2490
+ type: "rule",
2491
+ field: node.fieldId,
2492
+ operator: "greater-than-or-equal",
2493
+ value: node.lower
2494
+ }, {
2495
+ type: "rule",
2496
+ field: node.fieldId,
2497
+ operator: "less-than-or-equal",
2498
+ value: node.upper
2499
+ }]);
2500
+ if (node.op === "has-all") return group("and", [{
2501
+ type: "rule",
2502
+ field: node.fieldId,
2503
+ operator: "is-all-of",
2504
+ value: node.values
2505
+ }]);
2506
+ const leaf = node;
2507
+ const operator = {
2508
+ "is-null": "is-empty",
2509
+ "is-not-null": "is-not-empty",
2510
+ eq: "equals",
2511
+ ne: "not-equals",
2512
+ lt: "less-than",
2513
+ lte: "less-than-or-equal",
2514
+ gt: "greater-than",
2515
+ gte: "greater-than-or-equal",
2516
+ in: "is-any-of",
2517
+ contains: "contains",
2518
+ "starts-with": "starts-with",
2519
+ "ends-with": "ends-with",
2520
+ "has-any": "is-any-of",
2521
+ "relation-has": "is-any-of"
2522
+ }[leaf.op];
2523
+ if (!operator) throw runtimeError("invalid-query", "Filter operation is unsupported");
2524
+ const value = leaf.op === "in" || leaf.op === "has-any" ? leaf.values : leaf.op === "relation-has" ? [leaf.rowId] : "value" in leaf ? leaf.value : void 0;
2525
+ return group("and", [{
2526
+ type: "rule",
2527
+ field: leaf.fieldId,
2528
+ operator,
2529
+ ...value === void 0 ? {} : { value }
2530
+ }]);
2531
+ }
2532
+ function compatibilityFilterToRuntime(group) {
2533
+ return {
2534
+ op: group.conjunction,
2535
+ args: group.children.map((child) => {
2536
+ if (child.type === "group") return compatibilityFilterToRuntime(child);
2537
+ const operator = compatibilityOperator(child.operator);
2538
+ if (operator === "is-null" || operator === "is-not-null") return {
2539
+ op: operator,
2540
+ fieldId: child.field
2541
+ };
2542
+ if (operator === "in") return {
2543
+ op: "in",
2544
+ fieldId: child.field,
2545
+ values: Array.isArray(child.value) ? child.value : [child.value ?? null]
2546
+ };
2547
+ return {
2548
+ op: operator ?? "eq",
2549
+ fieldId: child.field,
2550
+ value: Array.isArray(child.value) ? child.value[0] : child.value ?? null
2551
+ };
2552
+ })
2553
+ };
2554
+ }
2555
+ function compatibilityOperator(operator) {
2556
+ switch (operator) {
2557
+ case "is-empty": return "is-null";
2558
+ case "is-not-empty": return "is-not-null";
2559
+ case "equals": return "eq";
2560
+ case "not-equals": return "ne";
2561
+ case "less-than": return "lt";
2562
+ case "less-than-or-equal": return "lte";
2563
+ case "greater-than": return "gt";
2564
+ case "greater-than-or-equal": return "gte";
2565
+ case "contains": return "contains";
2566
+ case "starts-with": return "starts-with";
2567
+ case "ends-with": return "ends-with";
2568
+ case "is-any-of": return "in";
2569
+ case "not-contains":
2570
+ case "is-none-of": return;
2571
+ }
2572
+ }
2573
+ function compatibilityLogicalValue(value, type) {
2574
+ if (type === "integer" && (typeof value === "number" || typeof value === "bigint")) return String(value);
2575
+ if (typeof value === "string" && typeof type === "object") {
2576
+ const parsed = JSON.parse(value);
2577
+ if (!Array.isArray(parsed)) return null;
2578
+ return parsed.map((entry) => compatibilityLogicalValue(entry, type.element));
2579
+ }
2580
+ if (typeof value === "string" && typeof type === "string" && [
2581
+ "file",
2582
+ "multi-select",
2583
+ "relation"
2584
+ ].includes(type)) return JSON.parse(value);
2585
+ if (typeof value === "string" && type === "file-entry") return JSON.parse(value);
2586
+ if (type === "checkbox" && typeof value === "number") return value === 1;
2587
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || Array.isArray(value) || typeof value === "object" && value !== null) return value;
2588
+ return null;
2589
+ }
2590
+ function validationDiagnostic(issue, severity) {
2591
+ return {
2592
+ code: validationCode(issue.code),
2593
+ severity,
2594
+ message: issue.message,
2595
+ ...issue.table ? { tableId: issue.table } : {}
2596
+ };
2597
+ }
2598
+ function validationCode(code) {
2599
+ return new Set([
2600
+ "file-not-sqlite",
2601
+ "file-identity-invalid",
2602
+ "file-format-unsupported",
2603
+ "file-feature-unsupported",
2604
+ "file-core-object-invalid",
2605
+ "file-metadata-invalid",
2606
+ "file-foreign-key-invalid",
2607
+ "file-physical-schema-invalid",
2608
+ "file-definition-invalid",
2609
+ "file-trigger-invalid",
2610
+ "file-index-invalid",
2611
+ "file-extension-invalid",
2612
+ "file-cell-invalid",
2613
+ "file-json-invalid",
2614
+ "file-reference-invalid",
2615
+ "file-unresolved-relation",
2616
+ "file-integrity-invalid"
2617
+ ]).has(code) ? code : "file-core-object-invalid";
2618
+ }
2619
+ function objectValue(value) {
2620
+ return JSON.parse(canonicalizeEidosFileJson(value));
2621
+ }
2622
+ function simulatedSystemFields(tableId, tableName) {
2623
+ return [
2624
+ [
2625
+ "row-id",
2626
+ "row-id",
2627
+ "_id",
2628
+ -3
2629
+ ],
2630
+ [
2631
+ "created-time",
2632
+ "created-time",
2633
+ "_created_at",
2634
+ -2
2635
+ ],
2636
+ [
2637
+ "updated-time",
2638
+ "last-edited-time",
2639
+ "_updated_at",
2640
+ -1
2641
+ ]
2642
+ ].map(([role, type, name, position]) => ({
2643
+ id: `${tableId}:system:${role}`,
2644
+ tableId,
2645
+ name: String(name),
2646
+ type,
2647
+ tableName,
2648
+ tableColumnName: String(name),
2649
+ physicalName: String(name),
2650
+ systemRole: role,
2651
+ nullable: false,
2652
+ isRecordLabel: false,
2653
+ position: Number(position),
2654
+ settings: {},
2655
+ property: {},
2656
+ storageCodec: "scalar",
2657
+ valueKind: "system",
2658
+ isHidden: true,
2659
+ isDerived: false,
2660
+ sourceTableColumnName: null,
2661
+ dependsOn: null
2662
+ }));
2663
+ }
2664
+ function simulatedNewField(tableId, tableName, field, sequence) {
2665
+ const id = `${tableId}:new-field:${sequence}:${field.clientKey}`;
2666
+ let property = field.settings ? { ...field.settings } : {};
2667
+ if (field.kind === "formula") {
2668
+ const definition = field.definition;
2669
+ if (!definition || !("sourceText" in definition) || !("resultType" in definition)) throw runtimeError("invalid-request", "Formula Field requires definition");
2670
+ property = {
2671
+ ...property,
2672
+ formula: definition.sourceText,
2673
+ displayType: definition.resultType
2674
+ };
2675
+ } else if (field.kind === "lookup") {
2676
+ const definition = field.definition;
2677
+ if (!definition || !("relationFieldId" in definition) || !("targetFieldId" in definition) || !("aggregate" in definition)) throw runtimeError("invalid-request", "Lookup Field requires definition");
2678
+ property = {
2679
+ ...property,
2680
+ relationField: definition.relationFieldId,
2681
+ targetField: definition.targetFieldId,
2682
+ aggregate: definition.aggregate,
2683
+ distinct: definition.distinctValues,
2684
+ displayType: "text"
2685
+ };
2686
+ } else if (field.kind === "relation") {
2687
+ const definition = field.definition;
2688
+ if (!definition || !("direction" in definition)) throw runtimeError("invalid-request", "Relation Field requires definition");
2689
+ property = simulatedRelationProperty(definition);
2690
+ }
2691
+ const virtual = field.kind === "formula" || field.kind === "lookup" || field.kind === "relation" && property.direction === "inverse";
2692
+ const list = ["multi-select", "file"].includes(field.kind);
2693
+ return {
2694
+ id,
2695
+ tableId,
2696
+ name: field.name,
2697
+ type: field.kind,
2698
+ tableName,
2699
+ tableColumnName: virtual ? id : field.name,
2700
+ physicalName: virtual ? null : field.name,
2701
+ systemRole: null,
2702
+ nullable: field.kind === "formula" || field.kind === "lookup" ? true : list || field.kind === "relation" ? false : field.nullable !== false,
2703
+ isRecordLabel: false,
2704
+ position: Number(field.position),
2705
+ settings: field.settings ?? {},
2706
+ property,
2707
+ storageCodec: field.kind === "relation" ? "relation" : list || field.kind === "lookup" && property.aggregate === "values" ? "json_array" : "scalar",
2708
+ valueKind: virtual ? "derived" : field.kind === "relation" ? "relation" : "source",
2709
+ isHidden: false,
2710
+ isDerived: virtual,
2711
+ sourceTableColumnName: field.kind === "relation" && property.direction === "inverse" ? String(property.sourceFieldId ?? "") : null,
2712
+ dependsOn: null
2713
+ };
2714
+ }
2715
+ function simulatedRelationProperty(definition) {
2716
+ return definition.direction === "forward" ? {
2717
+ direction: "forward",
2718
+ targetTableId: definition.targetTableId,
2719
+ cardinality: definition.cardinality,
2720
+ onDelete: definition.onDelete
2721
+ } : {
2722
+ direction: "inverse",
2723
+ targetTableId: definition.targetTableId,
2724
+ sourceFieldId: definition.inverseOfFieldId,
2725
+ cardinality: "many"
2726
+ };
2727
+ }
2728
+ function asciiNoCase(value) {
2729
+ return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
2730
+ }
2731
+ function highestSchemaClassification(left, right) {
2732
+ const rank = {
2733
+ "metadata-only": 0,
2734
+ "lossless-rewrite": 1,
2735
+ "explicit-lossy": 2,
2736
+ forbidden: 3
2737
+ };
2738
+ return rank[left] >= rank[right] ? left : right;
2739
+ }
2740
+ function assertConnectionCapabilities(connection) {
2741
+ const capabilities = connection.capabilities();
2742
+ if (capabilities.adapterVersion !== "1.0" || !capabilities.json1 || !capabilities.returning || !capabilities.strict || !capabilities.int64 || !capabilities.scalarFunctions || !capabilities.snapshot) throw runtimeError("adapter-error", "ConnectionPort does not satisfy EA-Connection-1.0");
2743
+ }
2744
+ function assertFactoryContext(context, environment) {
2745
+ if (context.cancellation.cancelled()) throw runtimeError("cancelled", "Runtime factory was cancelled", { retryable: true });
2746
+ if (context.deadlineMilliseconds !== void 0) assertPositiveSafeInteger(context.deadlineMilliseconds, "deadlineMilliseconds");
2747
+ checkedNowInstant(environment);
2748
+ const monotonic = environment.clock.nowMilliseconds();
2749
+ if (!Number.isFinite(monotonic) || monotonic < 0) throw runtimeError("adapter-error", "ClockPort.nowMilliseconds must be non-negative and finite");
2750
+ }
2751
+ function checkedNowInstant(environment) {
2752
+ const instant = environment.clock.nowInstant();
2753
+ if (!isCanonicalEidosFileInstant(instant)) throw runtimeError("adapter-error", "ClockPort.nowInstant returned a non-canonical instant");
2754
+ return instant;
2755
+ }
2756
+ function uuidGenerator(environment) {
2757
+ return new EidosUuidV7Generator(() => checkedNowInstant(environment), (length) => environment.entropy.randomBytes(length).slice());
2758
+ }
2759
+ function assertRequestContext(context) {
2760
+ if (typeof context.requestId !== "string" || context.requestId.length === 0 || context.requestId.includes("\0") || new TextEncoder().encode(context.requestId).byteLength > 128) throw runtimeError("invalid-request", "Invalid requestId", { path: "/requestId" });
2761
+ if (context.deadlineMilliseconds !== void 0) assertPositiveSafeInteger(context.deadlineMilliseconds, "deadlineMilliseconds");
2762
+ }
2763
+ function assertPositiveSafeInteger(value, label) {
2764
+ if (!Number.isSafeInteger(value) || value < 1) throw runtimeError("invalid-request", label + " must be a positive JSON safe integer");
2765
+ }
2766
+ function assertLimit(value, maximum, label) {
2767
+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) throw runtimeError("invalid-request", label + " must be between 1 and " + maximum);
2768
+ }
2769
+ function assertProjection(projection) {
2770
+ if (projection.fields.length > EIDOS_RUNTIME_LIMITS.projectionFieldsMax || new Set(projection.fields).size !== projection.fields.length || new Set(projection.resolveRelations).size !== projection.resolveRelations.length || projection.resolveRelations.some((fieldId) => !projection.fields.includes(fieldId))) throw runtimeError("invalid-request", "Invalid ProjectionSpec");
2771
+ }
2772
+ function assertCurrentRevision(expected, current) {
2773
+ parseRevision(expected, "revision");
2774
+ if (expected !== current) throw runtimeError("stale-revision", "File revision has changed", {
2775
+ retryable: true,
2776
+ currentRevision: current
2777
+ });
2778
+ }
2779
+ function parseRevision(value, label = "revision") {
2780
+ if (!/^(?:0|[1-9][0-9]*)$/.test(value)) throw runtimeError("invalid-request", label + " must be canonical non-negative int64 decimal");
2781
+ const parsed = BigInt(value);
2782
+ if (parsed > 9223372036854775807n) throw runtimeError("invalid-request", label + " exceeds int64");
2783
+ return parsed;
2784
+ }
2785
+ function taggedText(value) {
2786
+ if (value?.tag !== "text") throw runtimeError("corrupt-file", "Expected SQLite TEXT storage class");
2787
+ return value.value;
2788
+ }
2789
+ function taggedInteger(value) {
2790
+ if (value?.tag !== "integer") throw runtimeError("corrupt-file", "Expected SQLite INTEGER storage class");
2791
+ return value.value;
2792
+ }
2793
+ async function projectionHash(projection) {
2794
+ return hashJson(projection);
2795
+ }
2796
+ async function hashJson(value) {
2797
+ const bytes = new TextEncoder().encode(canonicalizeEidosFileJson(value));
2798
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
2799
+ return Array.from(new Uint8Array(digest), (value) => value.toString(16).padStart(2, "0")).join("");
2800
+ }
2801
+ const UINT64_MASK = (1n << 64n) - 1n;
2802
+ function cursorMac(key, payload) {
2803
+ const message = new TextEncoder().encode(payload);
2804
+ const read64 = (bytes, offset) => {
2805
+ let value = 0n;
2806
+ for (let index = 0; index < 8; index += 1) value |= BigInt(bytes[offset + index] ?? 0) << BigInt(index * 8);
2807
+ return value;
2808
+ };
2809
+ const rotate = (value, bits) => (value << bits | value >> 64n - bits) & UINT64_MASK;
2810
+ let v0 = 8317987319222330741n ^ read64(key, 0);
2811
+ let v1 = 7237128888997146477n ^ read64(key, 8);
2812
+ let v2 = 7816392313619706465n ^ read64(key, 0);
2813
+ let v3 = 8387220255154660723n ^ read64(key, 8);
2814
+ const round = () => {
2815
+ v0 = v0 + v1 & UINT64_MASK;
2816
+ v1 = rotate(v1, 13n) ^ v0;
2817
+ v0 = rotate(v0, 32n);
2818
+ v2 = v2 + v3 & UINT64_MASK;
2819
+ v3 = rotate(v3, 16n) ^ v2;
2820
+ v0 = v0 + v3 & UINT64_MASK;
2821
+ v3 = rotate(v3, 21n) ^ v0;
2822
+ v2 = v2 + v1 & UINT64_MASK;
2823
+ v1 = rotate(v1, 17n) ^ v2;
2824
+ v2 = rotate(v2, 32n);
2825
+ };
2826
+ let offset = 0;
2827
+ while (offset + 8 <= message.byteLength) {
2828
+ const block = read64(message, offset);
2829
+ v3 ^= block;
2830
+ round();
2831
+ round();
2832
+ v0 ^= block;
2833
+ offset += 8;
2834
+ }
2835
+ let finalBlock = BigInt(message.byteLength) << 56n;
2836
+ for (let index = 0; offset + index < message.byteLength; index += 1) finalBlock |= BigInt(message[offset + index]) << BigInt(index * 8);
2837
+ v3 ^= finalBlock;
2838
+ round();
2839
+ round();
2840
+ v0 ^= finalBlock;
2841
+ v2 ^= 255n;
2842
+ round();
2843
+ round();
2844
+ round();
2845
+ round();
2846
+ return ((v0 ^ v1 ^ v2 ^ v3) & UINT64_MASK).toString(16).padStart(16, "0");
2847
+ }
2848
+ function constantTimeTextEqual(left, right) {
2849
+ let difference = left.length ^ right.length;
2850
+ const length = Math.max(left.length, right.length);
2851
+ for (let index = 0; index < length; index += 1) difference |= (left.charCodeAt(index) || 0) ^ (right.charCodeAt(index) || 0);
2852
+ return difference === 0;
2853
+ }
2854
+ function parseSignedInt64(value, label) {
2855
+ if (!/^(?:0|-[1-9][0-9]*|[1-9][0-9]*)$/.test(value) || value === "-0") throw runtimeError("invalid-request", label + " must be canonical signed int64 decimal");
2856
+ const parsed = BigInt(value);
2857
+ if (parsed < -9223372036854775808n || parsed > 9223372036854775807n) throw runtimeError("invalid-request", label + " exceeds signed int64");
2858
+ return parsed;
2859
+ }
2860
+ function int64ToSafeNumber(value, label) {
2861
+ const parsed = parseSignedInt64(value, label);
2862
+ if (parsed < BigInt(Number.MIN_SAFE_INTEGER) || parsed > BigInt(Number.MAX_SAFE_INTEGER)) throw runtimeError("resource-limit", label + " cannot be represented by this compatibility engine");
2863
+ return Number(parsed);
2864
+ }
2865
+ function quoteSqlIdentifier(value) {
2866
+ return "\"" + value.replace(/"/g, "\"\"") + "\"";
2867
+ }
2868
+ function newFieldInput(field) {
2869
+ const base = {
2870
+ name: field.name,
2871
+ nullable: field.nullable
2872
+ };
2873
+ if (field.kind === "formula") {
2874
+ const definition = field.definition;
2875
+ return {
2876
+ name: field.name,
2877
+ type: "formula",
2878
+ property: {
2879
+ ...field.settings ?? {},
2880
+ formula: definition.sourceText,
2881
+ displayType: definition.resultType
2882
+ }
2883
+ };
2884
+ }
2885
+ if (field.kind === "lookup") {
2886
+ const definition = field.definition;
2887
+ return {
2888
+ name: field.name,
2889
+ type: "lookup",
2890
+ property: {
2891
+ ...field.settings ?? {},
2892
+ relationField: definition.relationFieldId,
2893
+ targetField: definition.targetFieldId,
2894
+ aggregate: definition.aggregate,
2895
+ displayType: "text",
2896
+ distinct: definition.distinctValues
2897
+ }
2898
+ };
2899
+ }
2900
+ if (field.kind === "relation") {
2901
+ const definition = field.definition;
2902
+ return {
2903
+ name: field.name,
2904
+ type: "relation",
2905
+ property: definition.direction === "forward" ? {
2906
+ ...field.settings ?? {},
2907
+ direction: "forward",
2908
+ targetTableId: definition.targetTableId,
2909
+ cardinality: definition.cardinality,
2910
+ onDelete: definition.onDelete
2911
+ } : {
2912
+ ...field.settings ?? {},
2913
+ direction: "inverse",
2914
+ targetTableId: definition.targetTableId,
2915
+ sourceFieldId: definition.inverseOfFieldId,
2916
+ cardinality: "many"
2917
+ }
2918
+ };
2919
+ }
2920
+ return {
2921
+ ...base,
2922
+ type: field.kind,
2923
+ property: field.settings
2924
+ };
2925
+ }
2926
+ function runtimeError(code, message, members = {}) {
2927
+ return {
2928
+ code,
2929
+ message: message.slice(0, 4096),
2930
+ retryable: false,
2931
+ ...members
2932
+ };
2933
+ }
2934
+ function mapRuntimeFailure(error) {
2935
+ if (isRuntimeError(error)) return error;
2936
+ if (error instanceof EidosFileError) {
2937
+ const code = {
2938
+ "invalid-sqlite": "corrupt-file",
2939
+ "not-eidos-file": "corrupt-file",
2940
+ "unsupported-version": "unsupported",
2941
+ "unsupported-feature": "unsupported",
2942
+ "invalid-schema": "corrupt-file",
2943
+ "invalid-formula": "invalid-formula",
2944
+ "invalid-value": "invalid-value",
2945
+ "constraint-conflict": "constraint",
2946
+ "dependency-cycle": "cycle",
2947
+ "stale-revision": "stale-revision",
2948
+ "file-conflict": "conflict",
2949
+ "permission-denied": "forbidden",
2950
+ "query-limit": "resource-limit",
2951
+ "resource-limit": "resource-limit",
2952
+ "unsupported-format": "unsupported",
2953
+ "invalid-identifier": "invalid-request",
2954
+ "invalid-query": "invalid-query",
2955
+ "invalid-range": "invalid-request",
2956
+ "invalid-csv": "invalid-value",
2957
+ "protected-field": "forbidden",
2958
+ "protected-view": "forbidden",
2959
+ "relation-in-use": "constraint",
2960
+ "formula-in-use": "constraint",
2961
+ "lookup-in-use": "constraint",
2962
+ "table-not-found": "not-found",
2963
+ "row-not-found": "not-found",
2964
+ "field-not-found": "not-found",
2965
+ "view-not-found": "not-found",
2966
+ "file-exists": "already-exists",
2967
+ "file-not-found": "not-found"
2968
+ }[error.code];
2969
+ return runtimeError(code, error.message, { retryable: code === "stale-revision" || code === "conflict" });
2970
+ }
2971
+ if (typeof error === "object" && error !== null && "code" in error && "fatal" in error) {
2972
+ const adapter = error;
2973
+ return runtimeError(adapter.code === "commit-outcome-unknown" ? "unknown-commit" : adapter.fatal ? "fatal" : adapter.code === "busy" ? "busy" : adapter.code === "cancelled" ? "cancelled" : adapter.code === "deadline-exceeded" ? "deadline-exceeded" : adapter.code === "resource-limit" ? "resource-limit" : adapter.code === "corrupt" || adapter.code === "not-a-database" ? "corrupt-file" : adapter.code === "adapter-closed" ? "closed" : "adapter-error", adapter.message ?? "Adapter failure", adapter.code === "commit-outcome-unknown" ? {
2974
+ retryable: false,
2975
+ details: { reconciliationRequired: true }
2976
+ } : { retryable: adapter.retryable === true });
2977
+ }
2978
+ return runtimeError("fatal", error instanceof Error ? error.message : "Unknown Runtime failure");
2979
+ }
2980
+ function isRuntimeError(value) {
2981
+ return typeof value === "object" && value !== null && typeof value.code === "string" && typeof value.message === "string" && typeof value.retryable === "boolean";
2982
+ }
2983
+ function binaryCompare(left, right) {
2984
+ const a = new TextEncoder().encode(left);
2985
+ const b = new TextEncoder().encode(right);
2986
+ for (let index = 0; index < Math.min(a.length, b.length); index += 1) if (a[index] !== b[index]) return a[index] - b[index];
2987
+ return a.length - b.length;
2988
+ }
2989
+ function assertAggregateItems(items, fieldsById) {
2990
+ const keys = /* @__PURE__ */ new Set();
2991
+ for (const item of items) {
2992
+ if (!item.key || keys.has(item.key)) throw runtimeError("invalid-request", "Aggregate keys must be non-empty and unique");
2993
+ keys.add(item.key);
2994
+ if (item.op !== "count-all" && !fieldsById.has(item.fieldId)) throw runtimeError("not-found", "Aggregate Field not found", { fieldId: item.fieldId });
2995
+ }
2996
+ }
2997
+ function aggregateResultsForRows(items, fieldsById, rows) {
2998
+ const rowIdOrder = [...rows].sort((left, right) => binaryCompare(left.id, right.id));
2999
+ return items.map((item) => {
3000
+ if (item.op === "count-all") return {
3001
+ key: item.key,
3002
+ value: String(rows.length)
3003
+ };
3004
+ return aggregateItemResult(item, fieldValueType(fieldsById.get(item.fieldId)), rowIdOrder.map((row) => row.fields[item.fieldId] ?? null));
3005
+ });
3006
+ }
3007
+ function groupIdentity(values, types) {
3008
+ return canonicalizeEidosFileJson(values.map((value, index) => value === null ? "null" : typedAggregateKey(value, types[index])));
3009
+ }
3010
+ function compareGroupKeys(left, right, types) {
3011
+ for (let index = 0; index < types.length; index += 1) {
3012
+ const a = left[index] ?? null;
3013
+ const b = right[index] ?? null;
3014
+ if (a === null || b === null) {
3015
+ if (a === b) continue;
3016
+ return a === null ? -1 : 1;
3017
+ }
3018
+ const comparison = compareAggregateValues(a, b, types[index]);
3019
+ if (comparison !== 0) return comparison;
3020
+ }
3021
+ return 0;
3022
+ }
3023
+ function groupCursorSource(request) {
3024
+ return objectValue({
3025
+ tableId: request.tableId,
3026
+ query: normalizedRuntimeQuery(request.query),
3027
+ groupBy: request.groupBy,
3028
+ aggregates: request.aggregates,
3029
+ projection: request.projection,
3030
+ groupLimit: 1,
3031
+ rowsPerGroup: 1
3032
+ });
3033
+ }
3034
+ function queryForGroup(query, groupBy, key) {
3035
+ const rules = groupBy.map((fieldId, index) => key[index] === null ? {
3036
+ op: "is-null",
3037
+ fieldId
3038
+ } : {
3039
+ op: "eq",
3040
+ fieldId,
3041
+ value: key[index]
3042
+ });
3043
+ return {
3044
+ ...query,
3045
+ filter: query.filter === void 0 ? {
3046
+ op: "and",
3047
+ args: rules
3048
+ } : {
3049
+ op: "and",
3050
+ args: [query.filter, ...rules]
3051
+ }
3052
+ };
3053
+ }
3054
+ function groupBindingHash(request) {
3055
+ return hashJson({
3056
+ tableId: request.tableId,
3057
+ query: normalizedRuntimeQuery(request.query),
3058
+ groupBy: request.groupBy,
3059
+ aggregates: request.aggregates,
3060
+ projection: request.projection
3061
+ });
3062
+ }
3063
+ function aggregateItemResult(item, valueType, values) {
3064
+ const nonNull = values.filter((value) => value !== null);
3065
+ const distinct = /* @__PURE__ */ new Map();
3066
+ for (const value of nonNull) {
3067
+ const key = typedAggregateKey(value, valueType);
3068
+ if (!distinct.has(key)) distinct.set(key, value);
3069
+ }
3070
+ if (item.op === "count") return {
3071
+ key: item.key,
3072
+ value: String(nonNull.length)
3073
+ };
3074
+ if (item.op === "distinct-count") return {
3075
+ key: item.key,
3076
+ value: String(distinct.size)
3077
+ };
3078
+ const sortable = typeof valueType === "string" && isSortableType(valueType);
3079
+ const numeric = valueType === "integer" || valueType === "number";
3080
+ if ((item.op === "sum" || item.op === "average") && !numeric) throw runtimeError("invalid-request", `${item.op} requires an Integer or Number Field`, { fieldId: item.fieldId });
3081
+ if ((item.op === "min" || item.op === "max") && !sortable) throw runtimeError("invalid-request", `${item.op} requires a sortable scalar Field`, { fieldId: item.fieldId });
3082
+ const sum = () => {
3083
+ if (nonNull.length === 0) return null;
3084
+ if (valueType === "integer") {
3085
+ const total = nonNull.reduce((accumulator, value) => accumulator + BigInt(value), 0n);
3086
+ if (total < -9223372036854775808n || total > 9223372036854775807n) throw runtimeError("constraint", "Integer aggregate sum exceeds int64", { fieldId: item.fieldId });
3087
+ return String(total);
3088
+ }
3089
+ const result = pairwiseBinary64(nonNull.map(Number));
3090
+ if (!Number.isFinite(result)) throw runtimeError("constraint", "Number aggregate is non-finite", { fieldId: item.fieldId });
3091
+ return Object.is(result, -0) ? 0 : result;
3092
+ };
3093
+ const average = () => {
3094
+ if (nonNull.length === 0) return null;
3095
+ const result = valueType === "integer" ? rationalToBinary64(nonNull.reduce((accumulator, value) => accumulator + BigInt(value), 0n), BigInt(nonNull.length)) : pairwiseBinary64(nonNull.map(Number)) / nonNull.length;
3096
+ if (!Number.isFinite(result)) throw runtimeError("constraint", "Average aggregate is non-finite", { fieldId: item.fieldId });
3097
+ return Object.is(result, -0) ? 0 : result;
3098
+ };
3099
+ const extreme = (kind) => {
3100
+ if (nonNull.length === 0) return null;
3101
+ let selected = nonNull[0];
3102
+ for (const candidate of nonNull.slice(1)) {
3103
+ const compared = compareAggregateValues(candidate, selected, valueType);
3104
+ if (kind === "min" && compared < 0 || kind === "max" && compared > 0) selected = candidate;
3105
+ }
3106
+ return publicAggregateValue(selected, valueType);
3107
+ };
3108
+ if (item.op === "sum") return {
3109
+ key: item.key,
3110
+ value: sum()
3111
+ };
3112
+ if (item.op === "average") return {
3113
+ key: item.key,
3114
+ value: average()
3115
+ };
3116
+ if (item.op === "min" || item.op === "max") return {
3117
+ key: item.key,
3118
+ value: extreme(item.op)
3119
+ };
3120
+ const statistics = {
3121
+ rows: String(values.length),
3122
+ nulls: String(values.length - nonNull.length),
3123
+ distinct: String(distinct.size)
3124
+ };
3125
+ if (sortable) {
3126
+ statistics.min = extreme("min");
3127
+ statistics.max = extreme("max");
3128
+ }
3129
+ if (numeric) {
3130
+ statistics.sum = sum();
3131
+ statistics.average = average();
3132
+ }
3133
+ return {
3134
+ key: item.key,
3135
+ statistics
3136
+ };
3137
+ }
3138
+ function publicAggregateValue(value, type) {
3139
+ if (value === null) return null;
3140
+ if (type === "integer") return String(value);
3141
+ if (type === "checkbox") return value === true || value === 1 || value === 1n;
3142
+ if (typeof value === "number") return Object.is(value, -0) ? 0 : value;
3143
+ if (typeof value === "string" || typeof value === "boolean" || Array.isArray(value)) return value;
3144
+ throw runtimeError("fatal", "Aggregate produced an invalid logical value");
3145
+ }
3146
+ function typedAggregateKey(value, type) {
3147
+ if (type === "integer") return `integer:${String(value)}`;
3148
+ if (type === "number") return `number:${Object.is(value, -0) ? 0 : Number(value)}`;
3149
+ if (type === "checkbox") return `checkbox:${value === true || value === 1 ? 1 : 0}`;
3150
+ if (typeof type === "object" || [
3151
+ "file",
3152
+ "multi-select",
3153
+ "relation",
3154
+ "file-entry"
3155
+ ].includes(String(type))) try {
3156
+ return `structured:${canonicalizeEidosFileJson(value)}`;
3157
+ } catch {
3158
+ throw runtimeError("fatal", "Aggregate encountered an invalid structured value");
3159
+ }
3160
+ return `${String(type)}:${String(value)}`;
3161
+ }
3162
+ function compareAggregateValues(left, right, type) {
3163
+ if (type === "integer") {
3164
+ const a = BigInt(left);
3165
+ const b = BigInt(right);
3166
+ return a < b ? -1 : a > b ? 1 : 0;
3167
+ }
3168
+ if (type === "number") {
3169
+ const a = Number(left);
3170
+ const b = Number(right);
3171
+ return a < b ? -1 : a > b ? 1 : 0;
3172
+ }
3173
+ if (type === "checkbox") {
3174
+ const a = left === true || left === 1 || left === 1n;
3175
+ return a === (right === true || right === 1 || right === 1n) ? 0 : a ? 1 : -1;
3176
+ }
3177
+ return binaryCompare(String(left), String(right));
3178
+ }
3179
+ function pairwiseBinary64(values) {
3180
+ let level = values.map((value) => Object.is(value, -0) ? 0 : value);
3181
+ while (level.length > 1) {
3182
+ const next = [];
3183
+ for (let index = 0; index < level.length; index += 2) next.push(index + 1 < level.length ? level[index] + level[index + 1] : level[index]);
3184
+ level = next;
3185
+ }
3186
+ return level[0] ?? 0;
3187
+ }
3188
+ function rationalToBinary64(numerator, denominator) {
3189
+ if (denominator <= 0n) throw runtimeError("fatal", "Invalid rational denominator");
3190
+ if (numerator === 0n) return 0;
3191
+ const negative = numerator < 0n;
3192
+ const absolute = negative ? -numerator : numerator;
3193
+ let exponent = bitLength(absolute) - bitLength(denominator);
3194
+ if (exponent >= 0) {
3195
+ if (absolute < denominator << BigInt(exponent)) exponent -= 1;
3196
+ } else if (absolute << BigInt(-exponent) < denominator) exponent -= 1;
3197
+ if (exponent > 1023) return negative ? -Infinity : Infinity;
3198
+ let result;
3199
+ if (exponent >= -1022) {
3200
+ const shift = 52 - exponent;
3201
+ let significand = divideRoundTiesEven(shift >= 0 ? absolute << BigInt(shift) : absolute, shift >= 0 ? denominator : denominator << BigInt(-shift));
3202
+ if (significand === 9007199254740992n) {
3203
+ significand >>= 1n;
3204
+ exponent += 1;
3205
+ if (exponent > 1023) return negative ? -Infinity : Infinity;
3206
+ }
3207
+ result = Number(significand) * 2 ** (exponent - 52);
3208
+ } else {
3209
+ const significand = divideRoundTiesEven(absolute << 1074n, denominator);
3210
+ result = Number(significand) * 2 ** -1074;
3211
+ }
3212
+ return negative ? -result : result;
3213
+ }
3214
+ function divideRoundTiesEven(numerator, denominator) {
3215
+ const quotient = numerator / denominator;
3216
+ const doubled = numerator % denominator * 2n;
3217
+ return doubled > denominator || doubled === denominator && quotient % 2n !== 0n ? quotient + 1n : quotient;
3218
+ }
3219
+ function bitLength(value) {
3220
+ return value.toString(2).length;
3221
+ }
3222
+ function assertJcsBytes(value, maximum, label) {
3223
+ let bytes;
3224
+ try {
3225
+ bytes = jcsByteLength(value);
3226
+ } catch {
3227
+ throw runtimeError("invalid-request", `${label} is not canonical JSON data`);
3228
+ }
3229
+ if (bytes > maximum) throw runtimeError("resource-limit", `${label} exceeds its byte limit`);
3230
+ }
3231
+ function jcsByteLength(value) {
3232
+ return new TextEncoder().encode(canonicalizeEidosFileJson(value)).byteLength;
3233
+ }
3234
+ //#endregion
3235
+ export { AdapterTransportRuntimeClient, AdapterTransportServer, ConnectionPortEidosFileConnection, EIDOS_ADAPTER_TRANSPORT_LIMITS, EIDOS_FILE_APPLICATION_ID, EIDOS_FILE_CSV_INFERENCE_ROW_COUNT, EIDOS_FILE_CSV_PREVIEW_ROW_COUNT, EIDOS_FILE_EXTENSION, EIDOS_FILE_FEATURES_TABLE, EIDOS_FILE_FIELDS_TABLE, EIDOS_FILE_FORMAT, EIDOS_FILE_FORMAT_VERSION, EIDOS_FILE_FORMAT_VERSION_TEXT, EIDOS_FILE_FORMULA_FIELDS_TABLE, EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES, EIDOS_FILE_FORMULA_FUNCTION_NAMES, EIDOS_FILE_LOOKUP_FIELDS_TABLE, EIDOS_FILE_META_TABLE, EIDOS_FILE_MIME_TYPE, EIDOS_FILE_RELATION_FIELDS_TABLE, EIDOS_FILE_REQUIRED_TABLES, EIDOS_FILE_SCHEMA_SQL, EIDOS_FILE_SCHEMA_VERSION, EIDOS_FILE_SYSTEM_COLUMNS, EIDOS_FILE_TABLES_TABLE, EIDOS_FILE_VIEWS_TABLE, EIDOS_RUNTIME_LIMITS, EidosAdapterError, EidosFileError, EidosFileHandlerRegistry, EidosFileHostError, EidosFileRuntime, EidosFileRuntimeDataSource, EidosFileSession, EidosRuntimeService, EidosUuidV7Generator, MUTABLE_BASE_FIELD_TYPES, MemoryByteSource, Runtime, SQLITE_HEADER, SQLiteWasmConnectionPort, assertEidosFileColumnName, assertEidosFileDisplayName, assertEidosFileRowQuery, assertEidosFileSelectOptions, assertEidosFileTableId, assertEidosFileUuid, assertEidosFileValues, assertInt64Decimal, assertUnicodeString, cancellationPortFromSignal, canonicalizeEidosFileJson, compileEidosFileFormula, compileEidosFileFormulaFields, compileEidosFileFormulaSource, compileEidosFileRowQuery, configureEidosFileConnection, createEidosFileCsvImportPlan, createEidosFileCsvRowEncoder, createEidosFileIdentifier, createEidosFileUuid, currentEidosFileInstant, decodeEidosFileAttachmentPaths, decodeEidosFileJsonArray, decodeEidosFileMultiSelectValues, decodeEidosFileRelationDisplay, decodeEidosFileRelationIds, decodeEidosFileStringArray, decodeEidosFileValues, eidosFileColumnStatLabel, eidosFileColumnStatTypesForField, eidosFileCsvExportHeader, eidosFileCsvRowToEidosFileRow, eidosFileFieldDisplayValues, eidosFileFieldStoresJsonArray, eidosFileFormulaReferences, eidosFileLookupAggregateSupportsTarget, eidosFileLookupDisplayType, eidosFileLookupElementType, eidosFileLookupStorageCodec, eidosFileLookupTargetDisplayType, eidosFileLookupTargetValueType, eidosFileLookupValueType, eidosFilePhysicalName, eidosFileRowQueryAffectedByFieldChanges, eidosFileRowQueryPredicateColumns, eidosFileSnapshot, eidosFileSortExpression, eidosFileTypeHandler, encodeEidosFileAttachmentPaths, encodeEidosFileCsvRecord, encodeEidosFileJsonArray, encodeEidosFileMultiSelectValues, encodeEidosFileRelationIds, encodeEidosFileValues, hasEidosFileSqliteHeader, importEidosFileCsv, incrementEidosFileRevision, initializeEidosFileSchema, isCanonicalEidosFileDate, isCanonicalEidosFileInstant, isCanonicalEidosFileJson, isEidosFileUuid, isMutableEidosFileFieldType, isSafeEidosFileUri, nativeToSqlValue, normalizeEidosFileAttachmentPath, normalizeEidosFileDate, normalizeEidosFileFilter, normalizeEidosFileInstant, normalizeEidosFileRowQuery, normalizeEidosFileSorts, parseEidosFileCsvRows, parseEidosFileJson, parseEidosFileSelectOptions, parseNonNegativeInt64, planCanonicalFieldConversion, planEidosFileCsvImport, planEidosFileFieldConversion, prepareEidosFileCsvImport, quoteIdentifier, rawTableNameForId, removeEidosFileFilterField, rewriteEidosFileFormulaFieldReferences, setEidosFileMetadata, sqlValueToNative, transportFitsHostLimit, validateAdapterCarrier, validateAdapterEnvelope, validateEidosFile };
3236
+
3237
+ //# sourceMappingURL=index.mjs.map