@eidos.space/eidos-file 2.0.0 → 2.0.2

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 (40) hide show
  1. package/README.md +1 -1
  2. package/dist/{adapter-contract-BRKKEulb.d.mts → adapter-contract-CPhqAl4b.d.mts} +23 -3
  3. package/dist/{adapter-contract-BRKKEulb.d.mts.map → adapter-contract-CPhqAl4b.d.mts.map} +1 -1
  4. package/dist/better-sqlite3.d.mts +2 -2
  5. package/dist/better-sqlite3.mjs +2 -2
  6. package/dist/browser.d.mts +4 -4
  7. package/dist/browser.mjs +3 -3
  8. package/dist/{csv-BQPkzC5Y.mjs → csv-CvzHNNGW.mjs} +32 -5
  9. package/dist/{csv-BQPkzC5Y.mjs.map → csv-CvzHNNGW.mjs.map} +1 -1
  10. package/dist/csv.d.mts +1 -1
  11. package/dist/csv.d.mts.map +1 -1
  12. package/dist/csv.mjs +1 -1
  13. package/dist/index.d.mts +15 -4
  14. package/dist/index.d.mts.map +1 -1
  15. package/dist/index.mjs +90 -30
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/node-sqlite.d.mts +16 -3
  18. package/dist/node-sqlite.d.mts.map +1 -1
  19. package/dist/node-sqlite.mjs +27 -3
  20. package/dist/node-sqlite.mjs.map +1 -1
  21. package/dist/{runtime-C9IcEeTi.d.mts → runtime-CkL1OOJT.d.mts} +64 -2
  22. package/dist/runtime-CkL1OOJT.d.mts.map +1 -0
  23. package/dist/{runtime-9_adwQ0y.mjs → runtime-qbuZMbV4.mjs} +396 -81
  24. package/dist/runtime-qbuZMbV4.mjs.map +1 -0
  25. package/dist/{select-options-CfNwfc_a.mjs → select-options-Dr8XCYOS.mjs} +28 -6
  26. package/dist/select-options-Dr8XCYOS.mjs.map +1 -0
  27. package/dist/{sqlite-wasm-BM6hsxH8.mjs → sqlite-wasm-fT8Z-5Ww.mjs} +23 -9
  28. package/dist/sqlite-wasm-fT8Z-5Ww.mjs.map +1 -0
  29. package/dist/system-metadata-merge-BaX38cp-.d.mts +77 -0
  30. package/dist/system-metadata-merge-BaX38cp-.d.mts.map +1 -0
  31. package/dist/system-metadata-merge-CjTqAwCi.mjs +819 -0
  32. package/dist/system-metadata-merge-CjTqAwCi.mjs.map +1 -0
  33. package/dist/{temporal-fyRCzJjy.d.mts → temporal-ysCLNSub.d.mts} +8 -3
  34. package/dist/temporal-ysCLNSub.d.mts.map +1 -0
  35. package/package.json +1 -1
  36. package/dist/runtime-9_adwQ0y.mjs.map +0 -1
  37. package/dist/runtime-C9IcEeTi.d.mts.map +0 -1
  38. package/dist/select-options-CfNwfc_a.mjs.map +0 -1
  39. package/dist/sqlite-wasm-BM6hsxH8.mjs.map +0 -1
  40. package/dist/temporal-fyRCzJjy.d.mts.map +0 -1
@@ -1,4 +1,4 @@
1
- import { A as isCanonicalEidosFileJson, C as assertEidosFileUuid, D as isEidosFileUuid, E as isEidosFileReservedTableName, M as EidosFileError, O as quoteIdentifier, S as assertEidosFileTableName, T as createEidosFileUuid, a as eidosFileInstantSqlCheck, b as assertEidosFileDisplayName, c as normalizeEidosFileDate, f as decodeEidosFileValues, i as eidosFileDateSqlCheck, j as parseEidosFileJson, k as canonicalizeEidosFileJson, l as normalizeEidosFileInstant, o as isCanonicalEidosFileDate, r as currentEidosFileInstant, s as isCanonicalEidosFileInstant, t as assertEidosFileSelectOptions, u as assertEidosFileValues } from "./select-options-CfNwfc_a.mjs";
1
+ import { A as isCanonicalEidosFileJson, C as assertEidosFileUuid, D as isEidosFileUuid, E as isEidosFileReservedTableName, M as EidosFileError, O as quoteIdentifier, S as assertEidosFileTableName, T as createEidosFileUuid, a as eidosFileInstantSqlCheck, b as assertEidosFileDisplayName, c as normalizeEidosFileDate, f as decodeEidosFileValues, i as eidosFileDateSqlCheck, j as parseEidosFileJson, k as canonicalizeEidosFileJson, l as normalizeEidosFileInstant, o as isCanonicalEidosFileDate, r as currentEidosFileInstant, s as isCanonicalEidosFileInstant, t as assertEidosFileSelectOptions, u as assertEidosFileValues } from "./select-options-Dr8XCYOS.mjs";
2
2
  //#region src/connection-port.ts
3
3
  const INT64_MIN$2 = -9223372036854775808n;
4
4
  const INT64_MAX$2 = 9223372036854775807n;
@@ -3268,6 +3268,8 @@ function validateEidosFile(connection, options = {}) {
3268
3268
  }
3269
3269
  //#endregion
3270
3270
  //#region src/runtime.ts
3271
+ const ROW_MUTATION_UNDO_ENTRIES_MAX = 50;
3272
+ const ROW_MUTATION_UNDO_BYTES_MAX = 64 * 1024 * 1024;
3271
3273
  function sameSqlValue(left, right) {
3272
3274
  if (left instanceof Uint8Array && right instanceof Uint8Array) return left.byteLength === right.byteLength && left.every((value, index) => value === right[index]);
3273
3275
  if ((typeof left === "number" || typeof left === "bigint") && (typeof right === "number" || typeof right === "bigint") && (typeof left === "bigint" || Number.isInteger(left)) && (typeof right === "bigint" || Number.isInteger(right))) return BigInt(left) === BigInt(right);
@@ -3490,6 +3492,53 @@ function compileKeysetAfter(sorts, values, lastId) {
3490
3492
  params
3491
3493
  };
3492
3494
  }
3495
+ function compileKeysetBefore(sorts, values, firstId) {
3496
+ if (values.length !== sorts.length) throw new EidosFileError("invalid-query", "Sort boundary is invalid");
3497
+ const params = [];
3498
+ const branches = [];
3499
+ sorts.forEach(({ field, sort }, index) => {
3500
+ const expression = eidosFileSortExpression(field);
3501
+ const value = values[index] ?? null;
3502
+ let before;
3503
+ if (value === null) before = sort.nulls === "last" ? `${expression} IS NOT NULL` : "0";
3504
+ else {
3505
+ const comparison = sort.direction === "desc" ? ">" : "<";
3506
+ before = sort.nulls === "first" ? `(${expression} ${comparison} ? OR ${expression} IS NULL)` : `${expression} ${comparison} ?`;
3507
+ }
3508
+ if (before !== "0") {
3509
+ const parts = [];
3510
+ for (let prefixIndex = 0; prefixIndex < index; prefixIndex += 1) {
3511
+ const prefixExpression = eidosFileSortExpression(sorts[prefixIndex].field);
3512
+ const prefixValue = values[prefixIndex] ?? null;
3513
+ if (prefixValue === null) parts.push(`${prefixExpression} IS NULL`);
3514
+ else {
3515
+ parts.push(`${prefixExpression} IS ?`);
3516
+ params.push(prefixValue);
3517
+ }
3518
+ }
3519
+ parts.push(before);
3520
+ if (value !== null) params.push(value);
3521
+ branches.push(`(${parts.join(" AND ")})`);
3522
+ }
3523
+ });
3524
+ const finalParts = [];
3525
+ sorts.forEach(({ field }, index) => {
3526
+ const expression = eidosFileSortExpression(field);
3527
+ const value = values[index] ?? null;
3528
+ if (value === null) finalParts.push(`${expression} IS NULL`);
3529
+ else {
3530
+ finalParts.push(`${expression} IS ?`);
3531
+ params.push(value);
3532
+ }
3533
+ });
3534
+ finalParts.push("\"__base_rowid\" < ?");
3535
+ params.push(assertEidosFileUuid(firstId, "Row ID"));
3536
+ branches.push(`(${finalParts.join(" AND ")})`);
3537
+ return {
3538
+ sql: `(${branches.join(" OR ")})`,
3539
+ params
3540
+ };
3541
+ }
3493
3542
  function filterToStorage(filter, fields) {
3494
3543
  const normalized = normalizeEidosFileFilter(filter);
3495
3544
  if (!normalized) return null;
@@ -3551,6 +3600,9 @@ function filterFromStorage(value, fields) {
3551
3600
  var EidosFileRuntime = class {
3552
3601
  mutationDepth = 0;
3553
3602
  mutationInstant = null;
3603
+ rowMutationUndoEntries = /* @__PURE__ */ new Map();
3604
+ rowMutationUndoBytes = 0;
3605
+ nestedMutationInvalidatesRowUndo = false;
3554
3606
  schemaCache;
3555
3607
  nowInstant;
3556
3608
  allocateId;
@@ -3565,6 +3617,7 @@ var EidosFileRuntime = class {
3565
3617
  registerEidosLookupFunctions(connection);
3566
3618
  }
3567
3619
  close() {
3620
+ this.clearRowMutationUndoEntries();
3568
3621
  if (this.ownsConnection) this.connection.close?.();
3569
3622
  }
3570
3623
  inspect() {
@@ -3752,29 +3805,46 @@ var EidosFileRuntime = class {
3752
3805
  applyCanonicalMutation(operation, expectedRevision) {
3753
3806
  return this.mutate(() => operation(this.operationInstant()), expectedRevision);
3754
3807
  }
3755
- mutate(operation, expectedRevision) {
3756
- if (this.mutationDepth > 0) return operation();
3757
- return this.connection.transaction(() => {
3758
- this.schemaCache = void 0;
3759
- const revision = this.info().revision ?? 0;
3760
- if (expectedRevision !== void 0 && BigInt(revision) !== BigInt(expectedRevision)) throw new EidosFileError("stale-revision", `Expected revision ${expectedRevision}, found ${revision}`);
3761
- const totalChangesBefore = this.connection.get("SELECT total_changes() AS total")?.total ?? 0;
3762
- this.mutationInstant = this.nowInstant();
3763
- this.mutationDepth += 1;
3764
- try {
3765
- const result = operation();
3766
- const totalChangesAfter = this.connection.get("SELECT total_changes() AS total")?.total ?? totalChangesBefore;
3767
- if (BigInt(totalChangesAfter) === BigInt(totalChangesBefore)) return result;
3768
- const validation = validateEidosFile(this.connection, { level: "semantic" });
3769
- if (!validation.valid) throw new EidosFileError("invalid-schema", validation.errors.map((issue) => issue.message).join("; "));
3770
- incrementEidosFileRevision(this.connection, this.operationInstant());
3771
- return result;
3772
- } finally {
3773
- this.mutationDepth -= 1;
3774
- this.mutationInstant = null;
3808
+ mutate(operation, expectedRevision, invalidatesRowUndo = false) {
3809
+ if (this.mutationDepth > 0) {
3810
+ const result = operation();
3811
+ if (invalidatesRowUndo) this.nestedMutationInvalidatesRowUndo = true;
3812
+ return result;
3813
+ }
3814
+ const previousInvalidation = this.nestedMutationInvalidatesRowUndo;
3815
+ this.nestedMutationInvalidatesRowUndo = false;
3816
+ let clearRowUndoAfterCommit = false;
3817
+ try {
3818
+ const result = this.connection.transaction(() => {
3775
3819
  this.schemaCache = void 0;
3776
- }
3777
- });
3820
+ const revision = this.info().revision ?? 0;
3821
+ if (expectedRevision !== void 0 && BigInt(revision) !== BigInt(expectedRevision)) throw new EidosFileError("stale-revision", `Expected revision ${expectedRevision}, found ${revision}`);
3822
+ const totalChangesBefore = this.connection.get("SELECT total_changes() AS total")?.total ?? 0;
3823
+ this.mutationInstant = this.nowInstant();
3824
+ this.mutationDepth += 1;
3825
+ try {
3826
+ const operationResult = operation();
3827
+ const totalChangesAfter = this.connection.get("SELECT total_changes() AS total")?.total ?? totalChangesBefore;
3828
+ if (BigInt(totalChangesAfter) === BigInt(totalChangesBefore)) return operationResult;
3829
+ const validation = validateEidosFile(this.connection, { level: "semantic" });
3830
+ if (!validation.valid) throw new EidosFileError("invalid-schema", validation.errors.map((issue) => issue.message).join("; "));
3831
+ incrementEidosFileRevision(this.connection, this.operationInstant());
3832
+ clearRowUndoAfterCommit = invalidatesRowUndo || this.nestedMutationInvalidatesRowUndo;
3833
+ return operationResult;
3834
+ } finally {
3835
+ this.mutationDepth -= 1;
3836
+ this.mutationInstant = null;
3837
+ this.schemaCache = void 0;
3838
+ }
3839
+ });
3840
+ if (clearRowUndoAfterCommit) this.clearRowMutationUndoEntries();
3841
+ return result;
3842
+ } finally {
3843
+ this.nestedMutationInvalidatesRowUndo = previousInvalidation;
3844
+ }
3845
+ }
3846
+ mutateSchemaState(operation) {
3847
+ return this.mutate(operation, void 0, true);
3778
3848
  }
3779
3849
  operationInstant() {
3780
3850
  return this.mutationInstant ?? this.nowInstant();
@@ -3842,7 +3912,7 @@ var EidosFileRuntime = class {
3842
3912
  assertEidosFileUuid(tableId, "Table ID");
3843
3913
  const fields = this.prepareFields(input);
3844
3914
  const position = this.listTables().length;
3845
- return this.mutate(() => {
3915
+ return this.mutateSchemaState(() => {
3846
3916
  const now = this.operationInstant();
3847
3917
  const definitions = fields.flatMap((field) => {
3848
3918
  const definition = fieldColumnSql(field);
@@ -4057,7 +4127,7 @@ var EidosFileRuntime = class {
4057
4127
  }
4058
4128
  updateTable(tableId, changes) {
4059
4129
  const table = this.getTable(tableId);
4060
- return this.mutate(() => {
4130
+ return this.mutateSchemaState(() => {
4061
4131
  let name = table.name;
4062
4132
  let physicalName = table.physicalName ?? table.rawTableName;
4063
4133
  if (changes.name !== void 0 && changes.name !== table.name) {
@@ -4099,7 +4169,7 @@ var EidosFileRuntime = class {
4099
4169
  }
4100
4170
  deleteTable(tableId) {
4101
4171
  const table = this.getTable(tableId);
4102
- return this.mutate(() => {
4172
+ return this.mutateSchemaState(() => {
4103
4173
  this.connection.exec(`DROP TABLE ${quoteIdentifier(table.physicalName ?? table.rawTableName)}`);
4104
4174
  return this.connection.run(`DELETE FROM ${EIDOS_FILE_TABLES_TABLE} WHERE id = ?`, [tableId]).changes > 0;
4105
4175
  });
@@ -4132,7 +4202,7 @@ var EidosFileRuntime = class {
4132
4202
  "multi-select",
4133
4203
  "relation"
4134
4204
  ].includes(prepared.type) && this.countRows(tableId) > 0) throw new EidosFileError("constraint-conflict", "A populated Table cannot add a non-null scalar Field without a default");
4135
- return this.mutate(() => {
4205
+ return this.mutateSchemaState(() => {
4136
4206
  if (prepared.isRecordLabel && prepared.type === "lookup") throw new EidosFileError("invalid-schema", "A Lookup cannot be the Record Label Field in Eidos File 1.0");
4137
4207
  const definition = fieldColumnSql(prepared);
4138
4208
  if (definition) this.connection.exec(`ALTER TABLE ${quoteIdentifier(table.physicalName ?? table.rawTableName)} ADD COLUMN ${definition}`);
@@ -4175,7 +4245,7 @@ var EidosFileRuntime = class {
4175
4245
  const field = this.fieldByKey(tableId, fieldKey);
4176
4246
  const fieldId = field.id;
4177
4247
  if (changes.type !== void 0 && canonicalFieldType({ type: changes.type }) !== field.type) throw new EidosFileError("invalid-schema", "Field type conversion requires an explicit canonical conversion operation");
4178
- return this.mutate(() => {
4248
+ return this.mutateSchemaState(() => {
4179
4249
  let name = field.name;
4180
4250
  let physicalName = field.physicalName ?? null;
4181
4251
  if (changes.name !== void 0 && changes.name !== field.name) {
@@ -4348,7 +4418,7 @@ var EidosFileRuntime = class {
4348
4418
  "lookup"
4349
4419
  ].includes(field.type)) throw new EidosFileError("protected-field", "Only stored scalar and JSON Fields have configurable nullability");
4350
4420
  if ((field.nullable ?? true) === nullable) return field;
4351
- return this.mutate(() => {
4421
+ return this.mutateSchemaState(() => {
4352
4422
  const table = this.getTable(field.tableId);
4353
4423
  if (!nullable) {
4354
4424
  const nulls = this.connection.get("SELECT count(*) AS count FROM " + quoteIdentifier(table.physicalName ?? table.rawTableName) + " WHERE " + quoteIdentifier(field.physicalName) + " IS NULL")?.count ?? 0;
@@ -4367,7 +4437,7 @@ var EidosFileRuntime = class {
4367
4437
  "select",
4368
4438
  "url"
4369
4439
  ].includes(field.type) || (field.nullable ?? false) !== nullable) throw new EidosFileError("invalid-schema", "Metadata-only conversion requires an unchanged Text, Select, or URL storage shape");
4370
- return this.mutate(() => {
4440
+ return this.mutateSchemaState(() => {
4371
4441
  this.connection.run(`UPDATE ${EIDOS_FILE_FIELDS_TABLE} SET type = ? WHERE id = ?`, [targetType, fieldId]);
4372
4442
  this.connection.run(`UPDATE ${EIDOS_FILE_TABLES_TABLE} SET updated_at = ? WHERE id = ?`, [this.operationInstant(), field.tableId]);
4373
4443
  this.schemaCache = void 0;
@@ -4387,7 +4457,7 @@ var EidosFileRuntime = class {
4387
4457
  if (targetType === "relation" && !relation) throw new EidosFileError("invalid-schema", "Relation conversion requires a forward Relation definition");
4388
4458
  const expectedRows = this.countRows(field.tableId);
4389
4459
  if (rows.length !== expectedRows || new Set(rows.map((row) => row.id)).size !== rows.length) throw new EidosFileError("stale-revision", "Conversion rows no longer match the Table");
4390
- return this.mutate(() => {
4460
+ return this.mutateSchemaState(() => {
4391
4461
  const relationFieldIdsBefore = Array.from(this.allSchema().relations.keys());
4392
4462
  for (const relationFieldId of relationFieldIdsBefore) this.dropRelationTriggers(relationFieldId);
4393
4463
  this.connection.run(`DELETE FROM ${EIDOS_FILE_RELATION_FIELDS_TABLE} WHERE field_id = ?`, [fieldId]);
@@ -4510,7 +4580,7 @@ var EidosFileRuntime = class {
4510
4580
  if (field.isRecordLabel && !replacementRecordLabelFieldId) throw new EidosFileError("constraint-conflict", "Deleting the Record Label Field requires a replacement Field ID");
4511
4581
  const replacement = replacementRecordLabelFieldId ? this.fieldByKey(tableId, replacementRecordLabelFieldId) : void 0;
4512
4582
  if (replacement?.id === field.id) throw new EidosFileError("constraint-conflict", "The replacement Record Label Field must be a different Field");
4513
- return this.mutate(() => {
4583
+ return this.mutateSchemaState(() => {
4514
4584
  if (field.isRecordLabel && replacement?.id) this.connection.run(`UPDATE ${EIDOS_FILE_TABLES_TABLE}
4515
4585
  SET label_field_id = ?, updated_at = ? WHERE id = ?`, [
4516
4586
  replacement.id,
@@ -4974,6 +5044,24 @@ var EidosFileRuntime = class {
4974
5044
  ...nextCursor ? { nextCursor } : {}
4975
5045
  };
4976
5046
  }
5047
+ /** Returns the zero-based position of a Row ID in a filtered/sorted query. */
5048
+ getRowIndex(tableId, rowId, query = {}) {
5049
+ const id = assertEidosFileUuid(rowId, "Row ID");
5050
+ const compatibleQuery = this.compatibilityQuery(tableId, query);
5051
+ const fields = this.listFields(tableId);
5052
+ const source = this.logicalSource(tableId, this.requiredQueryFieldKeys(fields, compatibleQuery), false, false);
5053
+ const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery);
5054
+ const sorts = uniqueSortFields(source.fields, compatibleQuery.sorts);
5055
+ const targetWhere = compiled.whereSql ? `${compiled.whereSql} AND "__base_rowid" = ?` : "WHERE \"__base_rowid\" = ?";
5056
+ const target = this.connection.get(`WITH logical AS (${source.sql})
5057
+ SELECT * FROM logical ${targetWhere} LIMIT 1`, [...compiled.params, id]);
5058
+ if (!target) return null;
5059
+ const before = compileKeysetBefore(sorts, sorts.map(({ field }) => cursorSortValue(target, field)), id);
5060
+ const beforeWhere = compiled.whereSql ? `${compiled.whereSql} AND ${before.sql}` : `WHERE ${before.sql}`;
5061
+ const result = this.connection.get(`WITH logical AS (${source.sql})
5062
+ SELECT COUNT(*) AS count FROM logical ${beforeWhere}`, [...compiled.params, ...before.params]);
5063
+ return Number(result?.count ?? 0);
5064
+ }
4977
5065
  getRow(tableId, rowId) {
4978
5066
  const source = this.logicalSource(tableId);
4979
5067
  const row = this.connection.get(`WITH logical AS (${source.sql}) SELECT * FROM logical WHERE "__base_rowid" = ?`, [assertEidosFileUuid(rowId, "Row ID")]);
@@ -4992,40 +5080,62 @@ var EidosFileRuntime = class {
4992
5080
  includeRelationDisplays: options.resolveRelations === true
4993
5081
  });
4994
5082
  return {
4995
- rows: page.rows.map((row) => {
4996
- const logicalFields = Object.fromEntries(requested.map((field) => {
4997
- const raw = row[field.tableColumnName];
4998
- let value = raw ?? null;
4999
- const resultType = field.type === "formula" || field.type === "lookup" ? String(field.property?.displayType ?? field.type) : field.type;
5000
- if (typeof raw === "string" && (field.type === "file" || field.type === "multi-select" || field.type === "relation" || field.type === "lookup" && field.property?.aggregate === "values")) if (field.type === "file") try {
5001
- value = decodeEidosFileValues(raw);
5002
- } catch {
5003
- throw new EidosFileError("invalid-sqlite", `${field.name} contains an invalid stored File value`);
5004
- }
5005
- else value = parseEidosFileJson(raw);
5006
- else if (resultType === "checkbox" && typeof raw === "number") value = raw === 1;
5007
- return [field.id, value];
5008
- }));
5009
- const resolved = options.resolveRelations ? Object.fromEntries(requested.flatMap((field) => {
5010
- if (field.type !== "relation") return [];
5011
- const display = row[`${field.tableColumnName}__display`];
5012
- if (typeof display !== "string") return [[field.id, []]];
5013
- const parsed = parseEidosFileJson(display);
5014
- if (!Array.isArray(parsed)) return [[field.id, []]];
5015
- return [[field.id, parsed.flatMap((entry) => entry && !Array.isArray(entry) && typeof entry === "object" && typeof entry.id === "string" ? [{
5016
- id: entry.id,
5017
- label: entry.title ?? null
5018
- }] : [])]];
5019
- })) : void 0;
5020
- return {
5021
- id: String(row[rowIdField.tableColumnName]),
5022
- fields: logicalFields,
5023
- ...resolved && Object.keys(resolved).length > 0 ? { resolved } : {}
5024
- };
5025
- }),
5083
+ rows: this.logicalRows(rowIdField, requested, page.rows, options.resolveRelations === true),
5026
5084
  ...page.nextCursor ? { nextCursor: page.nextCursor } : {}
5027
5085
  };
5028
5086
  }
5087
+ /** @internal Exact primary-key lookup without page totals or cursor work. */
5088
+ getLogicalRowsByIds(tableId, rowIds, options = {}) {
5089
+ if (rowIds.length === 0) return [];
5090
+ if (rowIds.length > 500) throw new EidosFileError("resource-limit", "getLogicalRowsByIds accepts at most 500 Row IDs");
5091
+ const ids = rowIds.map((rowId) => assertEidosFileUuid(rowId, "Row ID"));
5092
+ const fields = this.listFields(tableId);
5093
+ const requested = options.fields ? options.fields.map((id) => this.fieldByKey(tableId, id)) : fields;
5094
+ const rowIdField = fields.find((field) => field.type === "row-id");
5095
+ const source = this.logicalSource(tableId, requested.map((field) => field.id), false, options.resolveRelations === true);
5096
+ const rawRows = this.connection.query(`WITH logical AS (${source.sql})
5097
+ SELECT * FROM logical
5098
+ WHERE "__base_rowid" IN (${ids.map(() => "?").join(", ")})`, ids);
5099
+ const logicalRows = this.logicalRows(rowIdField, requested, rawRows.map((row) => Object.fromEntries(Object.entries(row).flatMap(([key, value]) => key === "__base_rowid" ? [] : [[key, rowValue(value)]]))), options.resolveRelations === true);
5100
+ const byId = new Map(logicalRows.map((row) => [row.id, row]));
5101
+ return ids.flatMap((rowId) => {
5102
+ const row = byId.get(rowId);
5103
+ return row ? [row] : [];
5104
+ });
5105
+ }
5106
+ logicalRows(rowIdField, requested, rows, resolveRelations) {
5107
+ return rows.map((row) => {
5108
+ const logicalFields = Object.fromEntries(requested.map((field) => {
5109
+ const raw = row[field.tableColumnName];
5110
+ let value = raw ?? null;
5111
+ const resultType = field.type === "formula" || field.type === "lookup" ? String(field.property?.displayType ?? field.type) : field.type;
5112
+ if (typeof raw === "string" && (field.type === "file" || field.type === "multi-select" || field.type === "relation" || field.type === "lookup" && field.property?.aggregate === "values")) if (field.type === "file") try {
5113
+ value = decodeEidosFileValues(raw);
5114
+ } catch {
5115
+ throw new EidosFileError("invalid-sqlite", `${field.name} contains an invalid stored File value`);
5116
+ }
5117
+ else value = parseEidosFileJson(raw);
5118
+ else if (resultType === "checkbox" && typeof raw === "number") value = raw === 1;
5119
+ return [field.id, value];
5120
+ }));
5121
+ const resolved = resolveRelations ? Object.fromEntries(requested.flatMap((field) => {
5122
+ if (field.type !== "relation") return [];
5123
+ const display = row[`${field.tableColumnName}__display`];
5124
+ if (typeof display !== "string") return [[field.id, []]];
5125
+ const parsed = parseEidosFileJson(display);
5126
+ if (!Array.isArray(parsed)) return [[field.id, []]];
5127
+ return [[field.id, parsed.flatMap((entry) => entry && !Array.isArray(entry) && typeof entry === "object" && typeof entry.id === "string" ? [{
5128
+ id: entry.id,
5129
+ label: entry.title ?? null
5130
+ }] : [])]];
5131
+ })) : void 0;
5132
+ return {
5133
+ id: String(row[rowIdField.tableColumnName]),
5134
+ fields: logicalFields,
5135
+ ...resolved && Object.keys(resolved).length > 0 ? { resolved } : {}
5136
+ };
5137
+ });
5138
+ }
5029
5139
  /**
5030
5140
  * @internal Exact Runtime aggregate/group scan. One set-based SQL statement
5031
5141
  * returns typed logical inputs in effective query order; the public Runtime
@@ -5371,6 +5481,217 @@ var EidosFileRuntime = class {
5371
5481
  return updates.map((update) => update.rowId);
5372
5482
  }).map((id) => this.getRow(tableId, id));
5373
5483
  }
5484
+ rowMutationUndoEntryBytes(entry) {
5485
+ const json = JSON.stringify(entry, (_key, value) => {
5486
+ if (typeof value === "bigint") return { $int64: value.toString() };
5487
+ if (value instanceof Uint8Array) return { $blob: Array.from(value) };
5488
+ return value;
5489
+ });
5490
+ return new TextEncoder().encode(json).byteLength;
5491
+ }
5492
+ prepareRowMutationUndo(entry) {
5493
+ const bytes = this.rowMutationUndoEntryBytes(entry);
5494
+ if (bytes > ROW_MUTATION_UNDO_BYTES_MAX) throw new EidosFileError("resource-limit", "This deletion is too large to retain for undo");
5495
+ const base = `row-undo:${this.allocateId()}`;
5496
+ let token = base;
5497
+ let suffix = 1;
5498
+ while (this.rowMutationUndoEntries.has(token)) {
5499
+ token = `${base}:${suffix}`;
5500
+ suffix += 1;
5501
+ }
5502
+ return {
5503
+ token,
5504
+ retained: {
5505
+ entry,
5506
+ bytes
5507
+ }
5508
+ };
5509
+ }
5510
+ deleteRowMutationUndoEntry(token) {
5511
+ const retained = this.rowMutationUndoEntries.get(token);
5512
+ if (!retained) return false;
5513
+ this.rowMutationUndoEntries.delete(token);
5514
+ this.rowMutationUndoBytes = Math.max(0, this.rowMutationUndoBytes - retained.bytes);
5515
+ return true;
5516
+ }
5517
+ clearRowMutationUndoEntries() {
5518
+ this.rowMutationUndoEntries.clear();
5519
+ this.rowMutationUndoBytes = 0;
5520
+ }
5521
+ commitRowMutationUndo(prepared, consumedToken) {
5522
+ if (consumedToken) this.deleteRowMutationUndoEntry(consumedToken);
5523
+ this.rowMutationUndoEntries.set(prepared.token, prepared.retained);
5524
+ this.rowMutationUndoBytes += prepared.retained.bytes;
5525
+ while (this.rowMutationUndoEntries.size > ROW_MUTATION_UNDO_ENTRIES_MAX || this.rowMutationUndoBytes > ROW_MUTATION_UNDO_BYTES_MAX) {
5526
+ const redoToken = Array.from(this.rowMutationUndoEntries).find(([token, retained]) => token !== prepared.token && retained.entry.kind === "repeat-delete")?.[0];
5527
+ const oldestToken = this.rowMutationUndoEntries.keys().next().value;
5528
+ const token = redoToken ?? oldestToken;
5529
+ if (typeof token !== "string" || token === prepared.token) break;
5530
+ this.deleteRowMutationUndoEntry(token);
5531
+ }
5532
+ return prepared.token;
5533
+ }
5534
+ captureRowDeletionUndoState(tableId, rowIds) {
5535
+ const ids = Array.from(new Set(rowIds.map((id) => assertEidosFileUuid(id, "Row ID"))));
5536
+ const table = this.getTable(tableId);
5537
+ const physicalTable = table.physicalName ?? table.rawTableName;
5538
+ const rawRows = ids.length === 0 ? [] : this.connection.query(`SELECT * FROM ${quoteIdentifier(physicalTable)} WHERE "_id" IN (${ids.map(() => "?").join(", ")})`, ids);
5539
+ const rawById = new Map(rawRows.flatMap((row) => typeof row._id === "string" ? [[row._id, row]] : []));
5540
+ for (const rowId of ids) if (!rawById.has(rowId)) throw new EidosFileError("row-not-found", `Row not found: ${rowId}`);
5541
+ const deleteSet = new Set(ids);
5542
+ const detachedRelations = [];
5543
+ const schema = this.allSchema();
5544
+ for (const [fieldId, relation] of schema.relations) {
5545
+ if (relation.direction !== "forward" || relation.on_delete !== "detach" || uuid(relation.target_table_id) !== tableId) continue;
5546
+ const field = Array.from(schema.fieldsByTable.values()).flat().find((candidate) => candidate.id === fieldId);
5547
+ if (!field?.tableId || !field.physicalName) continue;
5548
+ const sourceTable = schema.tables.get(field.tableId);
5549
+ if (!sourceTable) continue;
5550
+ const sourceRows = this.connection.query(`SELECT "_id", ${quoteIdentifier(field.physicalName)} AS relation_value FROM ${quoteIdentifier(sourceTable.physical_name)} ORDER BY "_id" COLLATE BINARY`);
5551
+ for (const sourceRow of sourceRows) {
5552
+ if (field.tableId === tableId && deleteSet.has(sourceRow._id)) continue;
5553
+ if (typeof sourceRow.relation_value !== "string") throw new EidosFileError("invalid-value", `Relation ${fieldId} has a non-text stored value`);
5554
+ const parsed = parseEidosFileJson(sourceRow.relation_value);
5555
+ if (!Array.isArray(parsed)) throw new EidosFileError("invalid-value", `Relation ${fieldId} has a non-array stored value`);
5556
+ if (!parsed.some((entry) => typeof entry === "string" && deleteSet.has(entry))) continue;
5557
+ const survivors = parsed.filter((entry) => typeof entry !== "string" || !deleteSet.has(entry));
5558
+ detachedRelations.push({
5559
+ tableId: field.tableId,
5560
+ physicalTable: sourceTable.physical_name,
5561
+ physicalColumn: field.physicalName,
5562
+ rowId: sourceRow._id,
5563
+ value: sourceRow.relation_value,
5564
+ detachedValue: canonicalizeEidosFileJson(survivors)
5565
+ });
5566
+ }
5567
+ }
5568
+ return {
5569
+ tableId,
5570
+ rowIds: ids,
5571
+ rows: ids.map((rowId) => ({
5572
+ tableId,
5573
+ physicalTable,
5574
+ row: rawById.get(rowId)
5575
+ })),
5576
+ detachedRelations
5577
+ };
5578
+ }
5579
+ sameUndoPhysicalRow(left, right) {
5580
+ const leftKeys = Object.keys(left).filter((key) => key !== "_updated_at").sort();
5581
+ const rightKeys = Object.keys(right).filter((key) => key !== "_updated_at").sort();
5582
+ return leftKeys.length === rightKeys.length && leftKeys.every((key, index) => key === rightKeys[index] && sameSqlValue(left[key], right[key]));
5583
+ }
5584
+ assertRepeatRowDeletionApplicable(state) {
5585
+ const current = this.captureRowDeletionUndoState(state.tableId, state.rowIds);
5586
+ if (current.rows.length !== state.rows.length || current.rows.some((entry, index) => {
5587
+ const expected = state.rows[index];
5588
+ return !expected || entry.physicalTable !== expected.physicalTable || !this.sameUndoPhysicalRow(entry.row, expected.row);
5589
+ })) throw new EidosFileError("file-conflict", "The restored records changed and cannot be redone");
5590
+ const relationKey = (entry) => `${entry.tableId}\u0000${entry.rowId}\u0000${entry.physicalColumn}`;
5591
+ const expectedRelations = new Map(state.detachedRelations.map((entry) => [relationKey(entry), entry]));
5592
+ if (current.detachedRelations.length !== expectedRelations.size || current.detachedRelations.some((entry) => {
5593
+ const expected = expectedRelations.get(relationKey(entry));
5594
+ return !expected || !sameSqlValue(entry.value, expected.value);
5595
+ })) throw new EidosFileError("file-conflict", "Related records changed and this deletion cannot be redone");
5596
+ }
5597
+ restoreRowDeletionUndoState(state) {
5598
+ return this.mutate(() => {
5599
+ const table = this.getTable(state.tableId);
5600
+ const physicalTable = table.physicalName ?? table.rawTableName;
5601
+ if (state.rows.some((entry) => entry.physicalTable !== physicalTable)) throw new EidosFileError("stale-revision", "The table changed after these rows were deleted");
5602
+ if (state.rowIds.length > 0) {
5603
+ const existing = this.connection.get(`SELECT count(*) AS count FROM ${quoteIdentifier(physicalTable)} WHERE "_id" IN (${state.rowIds.map(() => "?").join(", ")})`, state.rowIds)?.count;
5604
+ if (Number(existing ?? 0) !== 0) throw new EidosFileError("file-conflict", "A deleted Row ID is already in use");
5605
+ }
5606
+ for (const relation of state.detachedRelations) {
5607
+ const current = this.connection.get(`SELECT ${quoteIdentifier(relation.physicalColumn)} AS value FROM ${quoteIdentifier(relation.physicalTable)} WHERE "_id" = ?`, [relation.rowId]);
5608
+ if (!current || !sameSqlValue(current.value, relation.detachedValue)) throw new EidosFileError("file-conflict", `Related Row ${relation.rowId} changed after the deletion`);
5609
+ }
5610
+ const schema = this.allSchema();
5611
+ const outgoingRelationColumns = new Set((schema.fieldsByTable.get(state.tableId) ?? []).flatMap((field) => {
5612
+ return (field.id ? schema.relations.get(field.id) : void 0)?.direction === "forward" && field.physicalName ? [field.physicalName] : [];
5613
+ }));
5614
+ for (const entry of state.rows) {
5615
+ const keys = Object.keys(entry.row);
5616
+ const values = keys.map((key) => outgoingRelationColumns.has(key) ? "[]" : entry.row[key]);
5617
+ this.connection.run(`INSERT INTO ${quoteIdentifier(physicalTable)} (${keys.map(quoteIdentifier).join(", ")}) VALUES (${keys.map(() => "?").join(", ")})`, values);
5618
+ }
5619
+ for (const entry of state.rows) {
5620
+ const rowId = entry.row._id;
5621
+ if (typeof rowId !== "string") throw new EidosFileError("invalid-schema", "Deleted row state is missing its Row ID");
5622
+ const keys = Object.keys(entry.row).filter((key) => key !== "_id");
5623
+ if (keys.length > 0) {
5624
+ if (this.connection.run(`UPDATE ${quoteIdentifier(physicalTable)} SET ${keys.map((key) => `${quoteIdentifier(key)} = ?`).join(", ")} WHERE "_id" = ?`, [...keys.map((key) => key === "_updated_at" ? this.operationInstant() : entry.row[key]), rowId]).changes === 0) throw new EidosFileError("stale-revision", `Could not restore Row ${rowId}`);
5625
+ }
5626
+ }
5627
+ for (const relation of state.detachedRelations) if (this.connection.run(`UPDATE ${quoteIdentifier(relation.physicalTable)} SET ${quoteIdentifier(relation.physicalColumn)} = ?, "_updated_at" = ? WHERE "_id" = ?`, [
5628
+ relation.value,
5629
+ this.operationInstant(),
5630
+ relation.rowId
5631
+ ]).changes === 0) throw new EidosFileError("stale-revision", `Could not restore Relation on Row ${relation.rowId}`);
5632
+ return [...state.rows.map((entry) => ({
5633
+ tableId: entry.tableId,
5634
+ rowId: String(entry.row._id)
5635
+ })), ...state.detachedRelations.map((entry) => ({
5636
+ tableId: entry.tableId,
5637
+ rowId: entry.rowId
5638
+ }))];
5639
+ });
5640
+ }
5641
+ deleteRowsReversible(tableId, rowIds, expectedRevision, consumedUndoToken) {
5642
+ if (rowIds.length === 0) return {
5643
+ revision: this.info().revision ?? 0,
5644
+ deleted: [],
5645
+ affected: [],
5646
+ rowCount: this.countRows(tableId)
5647
+ };
5648
+ const rowCountBefore = this.countRows(tableId);
5649
+ const state = this.captureRowDeletionUndoState(tableId, rowIds);
5650
+ const preparedUndo = this.prepareRowMutationUndo({
5651
+ kind: "restore-delete",
5652
+ state
5653
+ });
5654
+ const result = this.mutateRows({
5655
+ tableId,
5656
+ delete: state.rowIds,
5657
+ expectedRevision
5658
+ });
5659
+ const undoToken = this.commitRowMutationUndo(preparedUndo, consumedUndoToken);
5660
+ return {
5661
+ revision: result.revision,
5662
+ deleted: result.deleted,
5663
+ affected: result.affected ?? [],
5664
+ rowCount: rowCountBefore - result.deleted.length,
5665
+ undoToken
5666
+ };
5667
+ }
5668
+ revertRowMutation(undoToken) {
5669
+ const retained = this.rowMutationUndoEntries.get(undoToken);
5670
+ if (!retained) throw new EidosFileError("stale-revision", "This row change can no longer be undone");
5671
+ const entry = retained.entry;
5672
+ if (entry.kind === "restore-delete") {
5673
+ const rowCount = this.countRows(entry.state.tableId) + entry.state.rowIds.length;
5674
+ const preparedUndo = this.prepareRowMutationUndo({
5675
+ kind: "repeat-delete",
5676
+ state: entry.state
5677
+ });
5678
+ const affected = this.restoreRowDeletionUndoState(entry.state);
5679
+ return {
5680
+ revision: this.info().revision ?? 0,
5681
+ affected,
5682
+ rowCount,
5683
+ undoToken: this.commitRowMutationUndo(preparedUndo, undoToken)
5684
+ };
5685
+ }
5686
+ this.assertRepeatRowDeletionApplicable(entry.state);
5687
+ const result = this.deleteRowsReversible(entry.state.tableId, entry.state.rowIds, void 0, undoToken);
5688
+ return {
5689
+ revision: result.revision,
5690
+ affected: result.affected,
5691
+ rowCount: result.rowCount,
5692
+ undoToken: result.undoToken
5693
+ };
5694
+ }
5374
5695
  deleteRow(tableId, rowId) {
5375
5696
  return this.deleteRows(tableId, [rowId]).length === 1;
5376
5697
  }
@@ -5383,18 +5704,25 @@ var EidosFileRuntime = class {
5383
5704
  delete: ids
5384
5705
  }).deleted;
5385
5706
  }
5386
- deleteRowRanges(tableId, ranges, query = {}) {
5707
+ rowIdsForRanges(tableId, ranges, query) {
5387
5708
  const rowIdField = this.listFields(tableId).find((field) => field.type === "row-id");
5388
- const ids = ranges.flatMap((range) => {
5709
+ return ranges.flatMap((range) => {
5389
5710
  const start = Math.max(0, Math.trunc(range.startIndex));
5390
5711
  const end = Math.max(start, Math.trunc(range.endIndex));
5391
- return this.getRowPage(tableId, start, end - start + 1, query).rows.flatMap((row) => {
5712
+ if (end === start) return [];
5713
+ return this.getRowPage(tableId, start, end - start, query).rows.flatMap((row) => {
5392
5714
  const id = row[rowIdField.tableColumnName];
5393
5715
  return typeof id === "string" ? [id] : [];
5394
5716
  });
5395
5717
  });
5718
+ }
5719
+ deleteRowRanges(tableId, ranges, query = {}) {
5720
+ const ids = this.rowIdsForRanges(tableId, ranges, query);
5396
5721
  return this.deleteRows(tableId, ids).length;
5397
5722
  }
5723
+ deleteRowRangesReversible(tableId, ranges, query = {}) {
5724
+ return this.deleteRowsReversible(tableId, this.rowIdsForRanges(tableId, ranges, query));
5725
+ }
5398
5726
  previewFormula(tableId, input) {
5399
5727
  const fields = this.listFields(tableId);
5400
5728
  const compiled = compileEidosFileFormula({
@@ -5589,20 +5917,7 @@ var EidosFileRuntime = class {
5589
5917
  };
5590
5918
  }, input.expectedRevision);
5591
5919
  const requestedIds = [...new Set([...result.inserted, ...result.updated])];
5592
- const rowIdField = this.listFields(input.tableId).find((field) => field.type === "row-id");
5593
- const queried = requestedIds.length === 0 ? [] : this.queryRows(input.tableId, {
5594
- query: { filter: {
5595
- type: "group",
5596
- conjunction: "and",
5597
- children: [{
5598
- type: "rule",
5599
- field: rowIdField.id,
5600
- operator: "is-any-of",
5601
- value: requestedIds
5602
- }]
5603
- } },
5604
- limit: requestedIds.length
5605
- }).rows;
5920
+ const queried = this.getLogicalRowsByIds(input.tableId, requestedIds);
5606
5921
  const rowsById = new Map(queried.map((row) => [row.id, row]));
5607
5922
  return {
5608
5923
  revision: this.info().revision ?? 0,
@@ -5634,4 +5949,4 @@ function fieldValueTypeForScan(field) {
5634
5949
  //#endregion
5635
5950
  export { EIDOS_FILE_SCHEMA_VERSION as $, eidosFileLookupStorageCodec as A, rewriteEidosFileFormulaFieldReferences as B, normalizeEidosFileRowQuery as C, eidosFileLookupAggregateSupportsTarget as D, eidosFileFieldStoresJsonArray as E, EIDOS_FILE_FORMULA_FUNCTION_NAMES as F, EIDOS_FILE_FORMAT as G, EIDOS_FILE_EXTENSION as H, compileEidosFileFormula as I, EIDOS_FILE_LOOKUP_FIELDS_TABLE as J, EIDOS_FILE_FORMAT_VERSION as K, compileEidosFileFormulaFields as L, eidosFileLookupTargetValueType as M, eidosFileLookupValueType as N, eidosFileLookupDisplayType as O, EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES as P, EIDOS_FILE_REQUIRED_TABLES as Q, compileEidosFileFormulaSource as R, normalizeEidosFileFilter as S, removeEidosFileFilterField as T, EIDOS_FILE_FEATURES_TABLE as U, EIDOS_FILE_APPLICATION_ID as V, EIDOS_FILE_FIELDS_TABLE as W, EIDOS_FILE_MIME_TYPE as X, EIDOS_FILE_META_TABLE as Y, EIDOS_FILE_RELATION_FIELDS_TABLE as Z, assertEidosFileRowQuery as _, EIDOS_FILE_FORMAT_VERSION_TEXT as a, eidosFileColumnStatLabel as at, eidosFileRowQueryPredicateColumns as b, incrementEidosFileRevision as c, EidosAdapterError as ct, decodeEidosFileRelationDisplay as d, assertUnicodeString as dt, EIDOS_FILE_SYSTEM_COLUMNS as et, decodeEidosFileRelationIds as f, exactConnectionBindingCount as ft, parseNonNegativeInt64 as g, cancellationPortFromSignal as h, scanStableRowPages as i, hasEidosFileSqliteHeader as it, eidosFileLookupTargetDisplayType as j, eidosFileLookupElementType as k, initializeEidosFileSchema as l, assertExactConnectionBindings as lt, MemoryByteSource as m, sqlValueToNative as mt, validateEidosFile as n, EIDOS_FILE_VIEWS_TABLE as nt, EIDOS_FILE_SCHEMA_SQL as o, eidosFileColumnStatTypesForField as ot, encodeEidosFileRelationIds as p, nativeToSqlValue as pt, EIDOS_FILE_FORMULA_FIELDS_TABLE as q, smallestDependencyCycle as r, SQLITE_HEADER as rt, configureEidosFileConnection as s, ConnectionPortEidosFileConnection as st, EidosFileRuntime as t, EIDOS_FILE_TABLES_TABLE as tt, setEidosFileMetadata as u, assertInt64Decimal as ut, compileEidosFileRowQuery as v, normalizeEidosFileSorts as w, eidosFileSortExpression as x, eidosFileRowQueryAffectedByFieldChanges as y, eidosFileFormulaReferences as z };
5636
5951
 
5637
- //# sourceMappingURL=runtime-9_adwQ0y.mjs.map
5952
+ //# sourceMappingURL=runtime-qbuZMbV4.mjs.map