@eidos.space/eidos-file 2.1.0 → 3.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.
@@ -222,7 +222,7 @@ var ConnectionPortEidosFileConnection = class {
222
222
  arity,
223
223
  deterministic: true,
224
224
  directOnly: true
225
- }, (...values) => nativeParameterToSqlValue(operation(...values.map(sqlValueToLegacy))));
225
+ }, (...values) => nativeToSqlValue(operation(...values.map(sqlValueToLegacy))));
226
226
  }
227
227
  transaction(operation) {
228
228
  return this.port.transaction("write", operation);
@@ -402,37 +402,94 @@ const EIDOS_FILE_SYSTEM_COLUMNS = [
402
402
  //#region src/formula.ts
403
403
  /** Eidos File 1.0 has no prop()/props() reference syntax. */
404
404
  const EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES = [];
405
+ const EIDOS_FILE_FORMULA_PROFILE = "sqlite-3.45";
405
406
  const EIDOS_FILE_FORMULA_FUNCTION_NAMES = [
406
407
  "abs",
407
- "coalesce",
408
- "if",
409
- "is_null",
410
- "floor",
411
408
  "ceil",
409
+ "ceiling",
410
+ "char",
411
+ "coalesce",
412
412
  "concat",
413
+ "concat_ws",
414
+ "date",
415
+ "datetime",
416
+ "floor",
417
+ "format",
418
+ "glob",
419
+ "hex",
420
+ "ifnull",
421
+ "iif",
422
+ "instr",
423
+ "julianday",
413
424
  "length",
425
+ "like",
426
+ "lower",
427
+ "ltrim",
414
428
  "max",
415
429
  "min",
430
+ "nullif",
431
+ "octet_length",
432
+ "printf",
433
+ "quote",
434
+ "replace",
435
+ "round",
436
+ "rtrim",
437
+ "sign",
438
+ "strftime",
416
439
  "substr",
417
- "lower_ascii",
418
- "upper_ascii",
419
- "date_add_days",
420
- "date_diff_days",
421
- "datetime_add_milliseconds",
422
- "datetime_diff_milliseconds"
440
+ "substring",
441
+ "time",
442
+ "timediff",
443
+ "trim",
444
+ "typeof",
445
+ "unicode",
446
+ "unixepoch",
447
+ "upper"
423
448
  ];
424
449
  const ALLOWED_FUNCTIONS = new Set(EIDOS_FILE_FORMULA_FUNCTION_NAMES);
425
450
  const ALLOWED_KEYWORDS = new Set([
426
451
  "and",
452
+ "as",
453
+ "case",
454
+ "cast",
455
+ "else",
456
+ "end",
427
457
  "false",
458
+ "integer",
459
+ "is",
428
460
  "not",
429
461
  "null",
430
462
  "or",
431
- "true"
463
+ "real",
464
+ "text",
465
+ "then",
466
+ "true",
467
+ "when"
432
468
  ]);
433
469
  const MAX_FORMULA_BYTES = 4096;
434
470
  const MAX_FORMULA_NODES = 1e4;
435
471
  const MAX_FORMULA_DEPTH = 256;
472
+ /** Fails fast when a Host SQLite build cannot execute the fixed 1.0 profile. */
473
+ function assertEidosFileFormulaProfile(connection) {
474
+ try {
475
+ connection.get(`SELECT
476
+ abs(-1), ceil(1.5), ceiling(1.5), char(65), coalesce(NULL, 1),
477
+ concat(1, NULL, 'x'), concat_ws('-', 1, NULL, 2),
478
+ date('2026-01-01'), datetime('2026-01-01'), floor(1.5),
479
+ format('%d', 1), glob('a*', 'abc'), hex('A'), ifnull(NULL, 1),
480
+ iif(1, 1, 0), instr('abc', 'b'), julianday('2026-01-01'),
481
+ length('abc'), like('a%', 'abc'), lower('A'), ltrim(' x'),
482
+ max(1, 2), min(1, 2), nullif(1, 2), octet_length('😀'),
483
+ printf('%d', 1), quote('x'), replace('abc', 'b', 'x'), round(1.5),
484
+ rtrim('x '), sign(-1), strftime('%Y', '2026-01-01'),
485
+ substr('abc', 1, 2), substring('abc', 1, 2),
486
+ time('2026-01-01T12:00:00Z'),
487
+ timediff('2026-01-02', '2026-01-01'), trim(' x '), typeof(1),
488
+ unicode('A'), unixepoch('2026-01-01'), upper('a')`);
489
+ } catch (error) {
490
+ throw new EidosFileError("unsupported-feature", `SQLite build does not satisfy the Eidos Formula 1.0 function profile: ${error instanceof Error ? error.message : String(error)}`);
491
+ }
492
+ }
436
493
  function nextNonWhitespace(source, index) {
437
494
  while (index < source.length && /\s/u.test(source[index])) index += 1;
438
495
  return source[index];
@@ -504,7 +561,7 @@ function eidosFileFormulaReferences(source) {
504
561
  index += 1;
505
562
  while (index < source.length && /[A-Za-z0-9_]/.test(source[index])) index += 1;
506
563
  const token = source.slice(start, index).toLowerCase();
507
- if (nextNonWhitespace(source, index) === "(") {
564
+ if (nextNonWhitespace(source, index) === "(" && token !== "cast") {
508
565
  if (!ALLOWED_FUNCTIONS.has(token)) throw new EidosFileError("invalid-schema", `Unsupported Eidos File formula function: ${token}`);
509
566
  } else if (!ALLOWED_KEYWORDS.has(token)) throw new EidosFileError("invalid-schema", `Field references must be double-quoted: ${source.slice(start, index)}`);
510
567
  continue;
@@ -518,7 +575,7 @@ function eidosFileFormulaReferences(source) {
518
575
  }
519
576
  continue;
520
577
  }
521
- if ("()+-*/%<>=!&,".includes(character)) {
578
+ if ("()+-*/%<>=!|,".includes(character)) {
522
579
  index += 1;
523
580
  continue;
524
581
  }
@@ -644,7 +701,10 @@ function parseExactFormula(source) {
644
701
  if ([
645
702
  "!=",
646
703
  "<=",
647
- ">="
704
+ ">=",
705
+ "==",
706
+ "<>",
707
+ "||"
648
708
  ].includes(pair)) {
649
709
  tokens.push({
650
710
  kind: "operator",
@@ -653,7 +713,7 @@ function parseExactFormula(source) {
653
713
  index += 2;
654
714
  continue;
655
715
  }
656
- if ("+-*/%<>=&".includes(character)) {
716
+ if ("+-*/%<>=|".includes(character)) {
657
717
  tokens.push({
658
718
  kind: "operator",
659
719
  text: character
@@ -704,6 +764,49 @@ function parseExactFormula(source) {
704
764
  type: "boolean",
705
765
  value: canonical === "TRUE"
706
766
  };
767
+ if (canonical === "CAST") {
768
+ if (take().kind !== "left") throw new EidosFileError("invalid-formula", "CAST requires an opening parenthesis");
769
+ const operand = expression();
770
+ if (!word("AS")) throw new EidosFileError("invalid-formula", "CAST requires AS");
771
+ take();
772
+ const target = take();
773
+ const targetName = target.text.toUpperCase();
774
+ if (target.kind !== "word" || ![
775
+ "TEXT",
776
+ "INTEGER",
777
+ "REAL"
778
+ ].includes(targetName)) throw new EidosFileError("invalid-formula", "CAST target must be TEXT, INTEGER, or REAL");
779
+ if (take().kind !== "right") throw new EidosFileError("invalid-formula", "CAST is missing “)”");
780
+ return {
781
+ type: "cast",
782
+ name: targetName.toLowerCase(),
783
+ operand
784
+ };
785
+ }
786
+ if (canonical === "CASE") {
787
+ const args = [];
788
+ while (word("WHEN")) {
789
+ take();
790
+ args.push(expression());
791
+ if (!word("THEN")) throw new EidosFileError("invalid-formula", "CASE WHEN requires THEN");
792
+ take();
793
+ args.push(expression());
794
+ }
795
+ if (args.length === 0) throw new EidosFileError("invalid-formula", "CASE requires at least one WHEN");
796
+ let hasElse = false;
797
+ if (word("ELSE")) {
798
+ take();
799
+ args.push(expression());
800
+ hasElse = true;
801
+ }
802
+ if (!word("END")) throw new EidosFileError("invalid-formula", "CASE requires END");
803
+ take();
804
+ return {
805
+ type: "case",
806
+ value: hasElse,
807
+ args
808
+ };
809
+ }
707
810
  if (peek().kind !== "left") throw new EidosFileError("invalid-formula", `Field references must be double-quoted: ${token.text}`);
708
811
  if (!ALLOWED_FUNCTIONS.has(token.text.toLowerCase())) throw new EidosFileError("invalid-formula", `Unsupported Formula function: ${token.text}`);
709
812
  take();
@@ -743,10 +846,22 @@ function parseExactFormula(source) {
743
846
  "%"
744
847
  ]);
745
848
  const additive = () => binary(multiplicative, ["+", "-"]);
746
- const concatenation = () => binary(additive, ["&"]);
849
+ const concatenation = () => binary(additive, ["||"]);
747
850
  const comparison = () => {
748
851
  const left = concatenation();
749
- if (!operator("=", "!=", "<", "<=", ">", ">=")) return left;
852
+ if (word("IS")) {
853
+ take();
854
+ const negate = word("NOT");
855
+ if (negate) take();
856
+ if (!word("NULL")) throw new EidosFileError("invalid-formula", "Formula IS only supports IS NULL and IS NOT NULL");
857
+ take();
858
+ return {
859
+ type: "is-null",
860
+ op: negate ? "IS NOT NULL" : "IS NULL",
861
+ operand: left
862
+ };
863
+ }
864
+ if (!operator("=", "==", "!=", "<>", "<", "<=", ">", ">=")) return left;
750
865
  return {
751
866
  type: "binary",
752
867
  op: take().text,
@@ -825,6 +940,35 @@ function exactFormulaType(node, fields, numbers, expected) {
825
940
  node.literal = literal;
826
941
  return setFormulaType(node, literal.type);
827
942
  }
943
+ if (node.type === "cast") {
944
+ if (!node.operand) throw new EidosFileError("invalid-schema", "CAST requires an operand");
945
+ infer(node.operand, "any");
946
+ const result = {
947
+ text: "text",
948
+ integer: "integer",
949
+ real: "number"
950
+ }[String(node.name)];
951
+ if (!result) throw new EidosFileError("invalid-schema", "Invalid CAST target");
952
+ return setFormulaType(node, result);
953
+ }
954
+ if (node.type === "is-null") {
955
+ if (!node.operand) throw new EidosFileError("invalid-schema", "IS NULL requires an operand");
956
+ infer(node.operand, "any");
957
+ return setFormulaType(node, "checkbox");
958
+ }
959
+ if (node.type === "case") {
960
+ const args = node.args ?? [];
961
+ const hasElse = node.value === true;
962
+ const branchNodes = [];
963
+ const pairLength = hasElse ? args.length - 1 : args.length;
964
+ for (let index = 0; index < pairLength; index += 2) {
965
+ requireFormulaType(infer(args[index], "checkbox"), "checkbox", "CASE");
966
+ branchNodes.push(args[index + 1]);
967
+ }
968
+ if (hasElse) branchNodes.push(args[args.length - 1]);
969
+ else branchNodes.push({ type: "null" });
970
+ return setFormulaType(node, inferFormulaSequence(branchNodes, fields, numbers, expected));
971
+ }
828
972
  if (node.type === "unary") {
829
973
  if (!node.operand || ![
830
974
  "+",
@@ -855,9 +999,9 @@ function exactFormulaType(node, fields, numbers, expected) {
855
999
  requireFormulaType(infer(node.right, "checkbox"), "checkbox", op);
856
1000
  return setFormulaType(node, "checkbox");
857
1001
  }
858
- if (op === "&") {
859
- requireFormulaType(infer(node.left, "text"), "text", "&");
860
- requireFormulaType(infer(node.right, "text"), "text", "&");
1002
+ if (op === "||") {
1003
+ infer(node.left, "any");
1004
+ infer(node.right, "any");
861
1005
  return setFormulaType(node, "text");
862
1006
  }
863
1007
  if ([
@@ -875,14 +1019,16 @@ function exactFormulaType(node, fields, numbers, expected) {
875
1019
  }
876
1020
  if ([
877
1021
  "=",
1022
+ "==",
878
1023
  "!=",
1024
+ "<>",
879
1025
  "<",
880
1026
  "<=",
881
1027
  ">",
882
1028
  ">="
883
1029
  ].includes(op)) {
884
1030
  const pair = inferFormulaPair(node.left, node.right, fields, numbers);
885
- if (!pair.left || !pair.right || !formulaTypesComparable(pair.left, pair.right, op)) throw new EidosFileError("invalid-schema", `${op} operands have incompatible types`);
1031
+ if (!pair.left || !pair.right || !formulaTypesComparable(pair.left, pair.right, op === "==" ? "=" : op === "<>" ? "!=" : op)) throw new EidosFileError("invalid-schema", `${op} operands have incompatible types`);
886
1032
  return setFormulaType(node, "checkbox");
887
1033
  }
888
1034
  throw new EidosFileError("invalid-schema", `Unsupported Formula operator: ${op}`);
@@ -893,95 +1039,208 @@ function exactFormulaType(node, fields, numbers, expected) {
893
1039
  const arity = (minimum, maximum = minimum) => {
894
1040
  if (args.length < minimum || args.length > maximum) throw new EidosFileError("invalid-schema", `${name} expects ${minimum === maximum ? minimum : `${minimum}–${maximum}`} arguments`);
895
1041
  };
896
- if (name === "if") {
1042
+ if (name === "iif") {
897
1043
  arity(3);
898
- requireFormulaType(infer(args[0], "checkbox"), "checkbox", "IF");
1044
+ requireFormulaType(infer(args[0], "checkbox"), "checkbox", "IIF");
899
1045
  const pair = inferFormulaPair(args[1], args[2], fields, numbers, expected);
900
- if (!pair.left || !pair.right || pair.left !== pair.right) throw new EidosFileError("invalid-schema", "IF branches require one exact type");
1046
+ if (!pair.left || !pair.right || pair.left !== pair.right) throw new EidosFileError("invalid-schema", "IIF branches require one exact type");
901
1047
  return setFormulaType(node, pair.left);
902
1048
  }
903
- if (name === "coalesce") {
904
- arity(2, 16);
1049
+ if (name === "coalesce" || name === "ifnull") {
1050
+ if (name === "ifnull") arity(2);
1051
+ else arity(2, 16);
905
1052
  return setFormulaType(node, inferFormulaSequence(args, fields, numbers, expected));
906
1053
  }
907
- if (name === "is_null") {
908
- arity(1);
909
- infer(args[0], "any");
910
- return setFormulaType(node, "checkbox");
1054
+ if (name === "nullif") {
1055
+ arity(2);
1056
+ const pair = inferFormulaPair(args[0], args[1], fields, numbers, expected);
1057
+ if (!pair.left || !pair.right || !formulaTypesComparable(pair.left, pair.right, "=")) throw new EidosFileError("invalid-schema", "NULLIF arguments have incompatible types");
1058
+ return setFormulaType(node, pair.left);
911
1059
  }
912
- if (name === "abs") {
1060
+ if ([
1061
+ "abs",
1062
+ "ceil",
1063
+ "ceiling",
1064
+ "floor"
1065
+ ].includes(name)) {
913
1066
  arity(1);
914
1067
  const type = infer(args[0], expected);
915
- if (!isNumericFormulaType(type)) throw new EidosFileError("invalid-schema", "ABS requires numeric input");
1068
+ if (!isNumericFormulaType(type)) throw new EidosFileError("invalid-schema", `${name.toUpperCase()} requires numeric input`);
916
1069
  return setFormulaType(node, type);
917
1070
  }
1071
+ if (name === "round") {
1072
+ arity(1, 2);
1073
+ if (!isNumericFormulaType(infer(args[0], "number"))) throw new EidosFileError("invalid-schema", "ROUND requires numeric input");
1074
+ if (args[1]) requireFormulaType(infer(args[1], "integer"), "integer", "ROUND");
1075
+ return setFormulaType(node, "number");
1076
+ }
1077
+ if (name === "sign") {
1078
+ arity(1);
1079
+ if (!isNumericFormulaType(infer(args[0], "integer"))) throw new EidosFileError("invalid-schema", "SIGN requires numeric input");
1080
+ return setFormulaType(node, "integer");
1081
+ }
918
1082
  if (name === "min" || name === "max") {
919
1083
  arity(2, 16);
920
- const type = inferFormulaSequence(args, fields, numbers, expected, true);
1084
+ const type = inferFormulaSequence(args, fields, numbers, expected);
921
1085
  if (type === "json") throw new EidosFileError("invalid-formula", `${name} requires sortable arguments`);
922
1086
  return setFormulaType(node, type);
923
1087
  }
924
- const signatures = {
925
- floor: {
926
- args: ["number"],
927
- result: "integer"
1088
+ if (name === "concat") {
1089
+ arity(1, 16);
1090
+ for (const argument of args) infer(argument, "any");
1091
+ return setFormulaType(node, "text");
1092
+ }
1093
+ if (name === "concat_ws") {
1094
+ arity(2, 16);
1095
+ requireFormulaType(infer(args[0], "text"), "text", "CONCAT_WS");
1096
+ for (const argument of args.slice(1)) infer(argument, "any");
1097
+ return setFormulaType(node, "text");
1098
+ }
1099
+ if (name === "format" || name === "printf") {
1100
+ arity(1, 16);
1101
+ requireFormulaType(infer(args[0], "text"), "text", name);
1102
+ for (const argument of args.slice(1)) infer(argument, "any");
1103
+ return setFormulaType(node, "text");
1104
+ }
1105
+ if (name === "char") {
1106
+ arity(1, 16);
1107
+ for (const argument of args) requireFormulaType(infer(argument, "integer"), "integer", "CHAR");
1108
+ return setFormulaType(node, "text");
1109
+ }
1110
+ const fixedSignature = {
1111
+ glob: {
1112
+ args: ["text", "text"],
1113
+ result: "checkbox"
928
1114
  },
929
- ceil: {
930
- args: ["number"],
1115
+ instr: {
1116
+ args: ["text", "text"],
931
1117
  result: "integer"
932
1118
  },
933
1119
  length: {
934
1120
  args: ["text"],
935
1121
  result: "integer"
936
1122
  },
937
- substr: {
1123
+ like: {
938
1124
  args: [
939
1125
  "text",
940
- "integer",
941
- "integer"
1126
+ "text",
1127
+ "text"
942
1128
  ],
943
- result: "text",
1129
+ result: "checkbox",
944
1130
  optionalLast: true
945
1131
  },
946
- lower_ascii: {
1132
+ lower: {
947
1133
  args: ["text"],
948
1134
  result: "text"
949
1135
  },
950
- upper_ascii: {
1136
+ ltrim: {
1137
+ args: ["text", "text"],
1138
+ result: "text",
1139
+ optionalLast: true
1140
+ },
1141
+ octet_length: {
951
1142
  args: ["text"],
1143
+ result: "integer"
1144
+ },
1145
+ replace: {
1146
+ args: [
1147
+ "text",
1148
+ "text",
1149
+ "text"
1150
+ ],
952
1151
  result: "text"
953
1152
  },
954
- date_add_days: {
955
- args: ["date", "integer"],
956
- result: "date"
1153
+ rtrim: {
1154
+ args: ["text", "text"],
1155
+ result: "text",
1156
+ optionalLast: true
957
1157
  },
958
- date_diff_days: {
959
- args: ["date", "date"],
960
- result: "integer"
1158
+ substr: {
1159
+ args: [
1160
+ "text",
1161
+ "integer",
1162
+ "integer"
1163
+ ],
1164
+ result: "text",
1165
+ optionalLast: true
961
1166
  },
962
- datetime_add_milliseconds: {
963
- args: ["datetime", "integer"],
964
- result: "datetime"
1167
+ substring: {
1168
+ args: [
1169
+ "text",
1170
+ "integer",
1171
+ "integer"
1172
+ ],
1173
+ result: "text",
1174
+ optionalLast: true
965
1175
  },
966
- datetime_diff_milliseconds: {
967
- args: ["datetime", "datetime"],
1176
+ trim: {
1177
+ args: ["text", "text"],
1178
+ result: "text",
1179
+ optionalLast: true
1180
+ },
1181
+ unicode: {
1182
+ args: ["text"],
968
1183
  result: "integer"
1184
+ },
1185
+ upper: {
1186
+ args: ["text"],
1187
+ result: "text"
969
1188
  }
970
- };
971
- if (name === "concat") {
972
- arity(2, 16);
973
- for (const argument of args) requireFormulaType(infer(argument, "text"), "text", "CONCAT");
1189
+ }[name];
1190
+ if (fixedSignature) {
1191
+ arity(fixedSignature.optionalLast ? fixedSignature.args.length - 1 : fixedSignature.args.length, fixedSignature.args.length);
1192
+ args.forEach((argument, index) => requireFormulaType(infer(argument, fixedSignature.args[index]), fixedSignature.args[index], name));
1193
+ return setFormulaType(node, fixedSignature.result);
1194
+ }
1195
+ if ([
1196
+ "hex",
1197
+ "quote",
1198
+ "typeof"
1199
+ ].includes(name)) {
1200
+ arity(1);
1201
+ infer(args[0], "any");
974
1202
  return setFormulaType(node, "text");
975
1203
  }
976
- const signature = signatures[name];
977
- if (!signature) throw new EidosFileError("invalid-schema", `Unsupported Formula function: ${name}`);
978
- arity(signature.optionalLast ? signature.args.length - 1 : signature.args.length, signature.args.length);
979
- if (name === "substr" && args.length === 3 && args[2]?.type === "unary" && args[2].op === "-" && args[2].operand?.literal) {
980
- const literal = args[2].operand.literal;
981
- if (literal.type === "integer" && BigInt(literal.raw) > 0n) throw new EidosFileError("invalid-formula", "SUBSTR literal length cannot be negative");
1204
+ if ([
1205
+ "date",
1206
+ "datetime",
1207
+ "julianday",
1208
+ "strftime",
1209
+ "time",
1210
+ "timediff",
1211
+ "unixepoch"
1212
+ ].includes(name)) {
1213
+ const timeValue = (argument) => {
1214
+ if (argument.type === "string") {
1215
+ if (String(argument.value).toLowerCase() === "now") throw new EidosFileError("invalid-formula", `${name.toUpperCase()} does not allow the current-time literal`);
1216
+ return;
1217
+ }
1218
+ const type = infer(argument, "date");
1219
+ if (type !== "date" && type !== "datetime") throw new EidosFileError("invalid-schema", `${name.toUpperCase()} requires a date or datetime time value`);
1220
+ };
1221
+ const modifier = (argument) => {
1222
+ if (argument.type !== "string") throw new EidosFileError("invalid-formula", `${name.toUpperCase()} modifiers must be string literals`);
1223
+ const value = String(argument.value).toLowerCase();
1224
+ if ([
1225
+ "localtime",
1226
+ "utc",
1227
+ "auto"
1228
+ ].includes(value) || name === "unixepoch" && ["subsec", "subsecond"].includes(value)) throw new EidosFileError("invalid-formula", `${name.toUpperCase()} modifier is not deterministic`);
1229
+ };
1230
+ if (name === "timediff") {
1231
+ arity(2);
1232
+ timeValue(args[0]);
1233
+ timeValue(args[1]);
1234
+ return setFormulaType(node, "text");
1235
+ }
1236
+ const firstTimeValue = name === "strftime" ? 1 : 0;
1237
+ arity(name === "strftime" ? 2 : 1, 9);
1238
+ if (name === "strftime" && args[0]?.type !== "string") throw new EidosFileError("invalid-formula", "STRFTIME format must be a string literal");
1239
+ timeValue(args[firstTimeValue]);
1240
+ for (const argument of args.slice(firstTimeValue + 1)) modifier(argument);
1241
+ return setFormulaType(node, name === "date" ? "date" : name === "datetime" ? "datetime" : name === "julianday" ? "number" : name === "unixepoch" ? "integer" : "text");
982
1242
  }
983
- args.forEach((argument, index) => requireFormulaType(infer(argument, signature.args[index]), signature.args[index], name));
984
- return setFormulaType(node, signature.result);
1243
+ throw new EidosFileError("invalid-schema", `Unsupported Formula function: ${name}`);
985
1244
  }
986
1245
  throw new EidosFileError("invalid-schema", `Unsupported Formula AST node: ${node.type}`);
987
1246
  }
@@ -1042,6 +1301,17 @@ function compileExactFormulaNode(node, fields, resolve) {
1042
1301
  if (!field) throw new EidosFileError("field-not-found", `Formula Field not found: ${node.name}`);
1043
1302
  return `(${resolve(field)})`;
1044
1303
  }
1304
+ if (node.type === "cast") return `CAST((${compile(node.operand)}) AS ${String(node.name).toUpperCase()})`;
1305
+ if (node.type === "is-null") return `((${compile(node.operand)}) ${String(node.op).toUpperCase()})`;
1306
+ if (node.type === "case") {
1307
+ const args = node.args ?? [];
1308
+ const hasElse = node.value === true;
1309
+ const pairLength = hasElse ? args.length - 1 : args.length;
1310
+ const clauses = [];
1311
+ for (let index = 0; index < pairLength; index += 2) clauses.push(`WHEN (${compile(args[index])}) THEN (${compile(args[index + 1])})`);
1312
+ if (hasElse) clauses.push(`ELSE (${compile(args[args.length - 1])})`);
1313
+ return `(CASE ${clauses.join(" ")} END)`;
1314
+ }
1045
1315
  if (node.type === "unary") {
1046
1316
  const operand = compile(node.operand);
1047
1317
  if (node.op === "NOT") return `(NOT (${operand}))`;
@@ -1053,7 +1323,7 @@ function compileExactFormulaNode(node, fields, resolve) {
1053
1323
  const right = compile(node.right);
1054
1324
  const op = String(node.op).toUpperCase();
1055
1325
  if (op === "AND" || op === "OR") return `((${left}) ${op} (${right}))`;
1056
- if (op === "&") return `((${left}) || (${right}))`;
1326
+ if (op === "||") return `((${left}) || (${right}))`;
1057
1327
  if ([
1058
1328
  "+",
1059
1329
  "-",
@@ -1064,6 +1334,7 @@ function compileExactFormulaNode(node, fields, resolve) {
1064
1334
  }
1065
1335
  if (op === "/") return `eidos_formula_num_div(${left}, ${right})`;
1066
1336
  if (op === "%") return `eidos_formula_int_mod(${left}, ${right})`;
1337
+ const normalizedOp = op === "==" ? "=" : op === "<>" ? "!=" : op;
1067
1338
  const leftType = node.left.inferred;
1068
1339
  const rightType = node.right.inferred;
1069
1340
  if (isNumericFormulaType(leftType) && isNumericFormulaType(rightType) && (leftType !== rightType || leftType === "number")) return `eidos_formula_numeric_${{
@@ -1073,25 +1344,10 @@ function compileExactFormulaNode(node, fields, resolve) {
1073
1344
  "<=": "lte",
1074
1345
  ">": "gt",
1075
1346
  ">=": "gte"
1076
- }[op]}(${left}, ${right})`;
1077
- return `((${left}) COLLATE BINARY ${op} (${right}) COLLATE BINARY)`;
1078
- }
1079
- if (node.type === "call") {
1080
- const name = String(node.function?.name).toLowerCase();
1081
- const args = (node.args ?? []).map(compile);
1082
- if (name === "if") return `(CASE WHEN (${args[0]}) THEN (${args[1]}) ELSE (${args[2]}) END)`;
1083
- if (name === "coalesce") return `coalesce(${args.join(", ")})`;
1084
- if (name === "is_null") return `((${args[0]}) IS NULL)`;
1085
- if (name === "abs") return `eidos_formula_${node.inferred === "integer" ? "int" : "num"}_abs(${args[0]})`;
1086
- if (name === "floor" || name === "ceil") return `eidos_formula_${name}(${args[0]})`;
1087
- if (name === "min" || name === "max") return (node.args ?? []).some((arg) => arg.inferred === "number") && (node.args ?? []).some((arg) => arg.inferred === "integer") ? `eidos_formula_numeric_${name}(${args.join(", ")})` : `${name}(${args.join(", ")})`;
1088
- if (name === "concat") return `(${args.map((arg) => `(${arg})`).join(" || ")})`;
1089
- if (name === "length") return `eidos_formula_length(${args[0]})`;
1090
- if (name === "substr") return `eidos_formula_substr${args.length}(${args.join(", ")})`;
1091
- if (name === "lower_ascii") return `eidos_formula_lower_ascii(${args[0]})`;
1092
- if (name === "upper_ascii") return `eidos_formula_upper_ascii(${args[0]})`;
1093
- return `eidos_formula_${name}(${args.join(", ")})`;
1347
+ }[normalizedOp]}(${left}, ${right})`;
1348
+ return `((${left}) COLLATE BINARY ${normalizedOp} (${right}) COLLATE BINARY)`;
1094
1349
  }
1350
+ if (node.type === "call") return `${String(node.function?.name).toLowerCase()}(${(node.args ?? []).map(compile).join(", ")})`;
1095
1351
  throw new EidosFileError("invalid-schema", `Unsupported Formula AST node: ${node.type}`);
1096
1352
  }
1097
1353
  function exactFormulaLiteral(node, numbers) {
@@ -1106,16 +1362,19 @@ function exactFormulaPrecedence(node) {
1106
1362
  if (op === "AND") return 2;
1107
1363
  if ([
1108
1364
  "=",
1365
+ "==",
1109
1366
  "!=",
1367
+ "<>",
1110
1368
  "<",
1111
1369
  "<=",
1112
1370
  ">",
1113
1371
  ">="
1114
1372
  ].includes(op)) return 4;
1115
- if (op === "&") return 5;
1373
+ if (op === "||") return 5;
1116
1374
  if (op === "+" || op === "-") return 6;
1117
1375
  return 7;
1118
1376
  }
1377
+ if (node.type === "is-null") return 4;
1119
1378
  if (node.type === "unary") return node.op === "NOT" ? 3 : 8;
1120
1379
  return 9;
1121
1380
  }
@@ -1126,6 +1385,22 @@ function serializeExactFormulaNode(node, numbers) {
1126
1385
  if (node.type === "boolean") return node.value === true ? "TRUE" : "FALSE";
1127
1386
  if (node.type === "string") return `'${String(node.value).replace(/'/g, "''")}'`;
1128
1387
  if (node.type === "ref") return quoteIdentifier(String(node.name));
1388
+ if (node.type === "cast") return `CAST(${serializeExactFormulaNode(node.operand, numbers)} AS ${String(node.name).toUpperCase()})`;
1389
+ if (node.type === "is-null") {
1390
+ const operand = node.operand;
1391
+ let serialized = serializeExactFormulaNode(operand, numbers);
1392
+ if (exactFormulaPrecedence(operand) < 5) serialized = `(${serialized})`;
1393
+ return `${serialized} ${String(node.op).toUpperCase()}`;
1394
+ }
1395
+ if (node.type === "case") {
1396
+ const args = node.args ?? [];
1397
+ const hasElse = node.value === true;
1398
+ const pairLength = hasElse ? args.length - 1 : args.length;
1399
+ const clauses = [];
1400
+ for (let index = 0; index < pairLength; index += 2) clauses.push(`WHEN ${serializeExactFormulaNode(args[index], numbers)} THEN ${serializeExactFormulaNode(args[index + 1], numbers)}`);
1401
+ if (hasElse) clauses.push(`ELSE ${serializeExactFormulaNode(args[args.length - 1], numbers)}`);
1402
+ return `CASE ${clauses.join(" ")} END`;
1403
+ }
1129
1404
  if (node.type === "unary") {
1130
1405
  const operand = node.operand;
1131
1406
  if (node.op === "-" && exactFormulaLiteral(operand, numbers)?.raw === "9223372036854775808") return "-9223372036854775808";
@@ -1135,10 +1410,13 @@ function serializeExactFormulaNode(node, numbers) {
1135
1410
  }
1136
1411
  if (node.type === "binary") {
1137
1412
  const op = String(node.op).toUpperCase();
1413
+ const serializedOp = op === "==" ? "=" : op === "<>" ? "!=" : op;
1138
1414
  const precedence = exactFormulaPrecedence(node);
1139
1415
  const comparison = [
1140
1416
  "=",
1417
+ "==",
1141
1418
  "!=",
1419
+ "<>",
1142
1420
  "<",
1143
1421
  "<=",
1144
1422
  ">",
@@ -1150,7 +1428,7 @@ function serializeExactFormulaNode(node, numbers) {
1150
1428
  if (childPrecedence < precedence || right && childPrecedence === precedence || comparison && value.type === "binary" && childPrecedence === 4) serialized = `(${serialized})`;
1151
1429
  return serialized;
1152
1430
  };
1153
- return `${child(node.left, false)} ${op} ${child(node.right, true)}`;
1431
+ return `${child(node.left, false)} ${serializedOp} ${child(node.right, true)}`;
1154
1432
  }
1155
1433
  if (node.type === "call") return `${String(node.function?.name).toUpperCase()}(${(node.args ?? []).map((argument) => serializeExactFormulaNode(argument, numbers)).join(", ")})`;
1156
1434
  throw new EidosFileError("invalid-formula", `Unsupported Formula AST node: ${node.type}`);
@@ -1850,6 +2128,17 @@ const INT64_MIN$1 = -9223372036854775808n;
1850
2128
  const INT64_MAX$1 = 9223372036854775807n;
1851
2129
  function registerEidosFormulaFunctions(connection) {
1852
2130
  const fixed = (name, arity, operation) => connection.registerFunction(name, operation, arity);
2131
+ const fixedWhenMissing = (name, arity, operation) => {
2132
+ try {
2133
+ connection.get(`SELECT ${name}(1.5) AS value`);
2134
+ } catch {
2135
+ fixed(name, arity, operation);
2136
+ }
2137
+ };
2138
+ fixedWhenMissing("floor", 1, (value) => sqliteIntegralBoundary(value, Math.floor));
2139
+ fixedWhenMissing("ceil", 1, (value) => sqliteIntegralBoundary(value, Math.ceil));
2140
+ fixedWhenMissing("ceiling", 1, (value) => sqliteIntegralBoundary(value, Math.ceil));
2141
+ fixedWhenMissing("sign", 1, sqliteSign);
1853
2142
  fixed("eidos_formula_int_add", 2, (a, b) => intBinary(a, b, (x, y) => x + y));
1854
2143
  fixed("eidos_formula_int_sub", 2, (a, b) => intBinary(a, b, (x, y) => x - y));
1855
2144
  fixed("eidos_formula_int_mul", 2, (a, b) => intBinary(a, b, (x, y) => x * y));
@@ -1864,11 +2153,6 @@ function registerEidosFormulaFunctions(connection) {
1864
2153
  const integer = asInteger(value);
1865
2154
  return integer === INT64_MIN$1 ? null : -integer;
1866
2155
  });
1867
- fixed("eidos_formula_int_abs", 1, (value) => {
1868
- if (value === null) return null;
1869
- const integer = asInteger(value);
1870
- return integer === INT64_MIN$1 ? null : integer < 0n ? -integer : integer;
1871
- });
1872
2156
  fixed("eidos_formula_num_add", 2, (a, b) => numberBinary(a, b, (x, y) => x + y));
1873
2157
  fixed("eidos_formula_num_sub", 2, (a, b) => numberBinary(a, b, (x, y) => x - y));
1874
2158
  fixed("eidos_formula_num_mul", 2, (a, b) => numberBinary(a, b, (x, y) => x * y));
@@ -1877,12 +2161,6 @@ function registerEidosFormulaFunctions(connection) {
1877
2161
  if (value === null) return null;
1878
2162
  return finiteNumber$1(-asNumber(value));
1879
2163
  });
1880
- fixed("eidos_formula_num_abs", 1, (value) => {
1881
- if (value === null) return null;
1882
- return finiteNumber$1(Math.abs(asNumber(value)));
1883
- });
1884
- fixed("eidos_formula_floor", 1, (value) => roundedInteger(value, Math.floor));
1885
- fixed("eidos_formula_ceil", 1, (value) => roundedInteger(value, Math.ceil));
1886
2164
  for (const [suffix, predicate] of [
1887
2165
  ["eq", (order) => order === 0],
1888
2166
  ["ne", (order) => order !== 0],
@@ -1894,28 +2172,18 @@ function registerEidosFormulaFunctions(connection) {
1894
2172
  if (a === null || b === null) return null;
1895
2173
  return predicate(compareNumeric(a, b)) ? 1n : 0n;
1896
2174
  });
1897
- for (let arity = 2; arity <= 16; arity += 1) {
1898
- fixed("eidos_formula_numeric_min", arity, (...values) => numericExtreme(values, "min"));
1899
- fixed("eidos_formula_numeric_max", arity, (...values) => numericExtreme(values, "max"));
1900
- }
1901
- fixed("eidos_formula_substr2", 2, (text, start) => scalarSubstring(text, start));
1902
- fixed("eidos_formula_substr3", 3, (text, start, length) => scalarSubstring(text, start, length));
1903
- fixed("eidos_formula_length", 1, (value) => {
1904
- if (value === null) return null;
1905
- if (typeof value !== "string") throw new TypeError("LENGTH expected text");
1906
- return BigInt(Array.from(value).length);
1907
- });
1908
- fixed("eidos_formula_lower_ascii", 1, (value) => asciiCase(value, "lower"));
1909
- fixed("eidos_formula_upper_ascii", 1, (value) => asciiCase(value, "upper"));
1910
- fixed("eidos_formula_date_add_days", 2, dateAddDays);
1911
- fixed("eidos_formula_date_diff_days", 2, dateDiffDays);
1912
- fixed("eidos_formula_datetime_add_milliseconds", 2, datetimeAddMilliseconds);
1913
- fixed("eidos_formula_datetime_diff_milliseconds", 2, datetimeDiffMilliseconds);
1914
- }
1915
- function asciiCase(value, kind) {
2175
+ }
2176
+ function sqliteIntegralBoundary(value, operation) {
2177
+ if (value === null) return null;
2178
+ if (typeof value === "bigint") return value;
2179
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new TypeError("SQLite math function expected numeric input");
2180
+ return operation(value);
2181
+ }
2182
+ function sqliteSign(value) {
1916
2183
  if (value === null) return null;
1917
- if (typeof value !== "string") throw new TypeError("ASCII case expected text");
1918
- return value.replace(kind === "lower" ? /[A-Z]/g : /[a-z]/g, (character) => String.fromCharCode(character.charCodeAt(0) + (kind === "lower" ? 32 : -32)));
2184
+ if (typeof value === "bigint") return value < 0n ? -1n : value > 0n ? 1n : 0n;
2185
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new TypeError("SQLite SIGN expected numeric input");
2186
+ return value < 0 ? -1n : value > 0 ? 1n : 0n;
1919
2187
  }
1920
2188
  function asInteger(value) {
1921
2189
  if (typeof value === "bigint") return value;
@@ -1942,21 +2210,6 @@ function numberBinary(left, right, operation) {
1942
2210
  if (left === null || right === null) return null;
1943
2211
  return finiteNumber$1(operation(asNumber(left), asNumber(right)));
1944
2212
  }
1945
- function roundedInteger(value, operation) {
1946
- if (value === null) return null;
1947
- const rounded = operation(asNumber(value));
1948
- if (!Number.isFinite(rounded) || !Number.isInteger(rounded)) return null;
1949
- return boundedInteger$1(BigInt(rounded));
1950
- }
1951
- function numericExtreme(values, kind) {
1952
- if (values.some((value) => value === null)) return null;
1953
- let selected = values[0];
1954
- for (const value of values.slice(1)) {
1955
- const order = compareNumeric(value, selected);
1956
- if (kind === "min" && order < 0 || kind === "max" && order > 0) selected = value;
1957
- }
1958
- return values.some((value) => typeof value === "number") ? finiteNumber$1(asNumber(selected)) : selected;
1959
- }
1960
2213
  function compareNumeric(left, right) {
1961
2214
  if (typeof left === "bigint" && typeof right === "bigint") return left < right ? -1 : left > right ? 1 : 0;
1962
2215
  if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
@@ -1992,112 +2245,6 @@ function binary64Rational(value) {
1992
2245
  denominator: 1n << BigInt(-exponent)
1993
2246
  };
1994
2247
  }
1995
- function scalarSubstring(text, start, length) {
1996
- if (text === null || start === null || length === null) return null;
1997
- if (typeof text !== "string") throw new TypeError("SUBSTR expected text");
1998
- const scalars = Array.from(text);
1999
- const rawStart = asInteger(start);
2000
- const clampedStart = rawStart < 0n ? BigInt(scalars.length) + rawStart < 0n ? 0n : BigInt(scalars.length) + rawStart : rawStart;
2001
- if (clampedStart > BigInt(Number.MAX_SAFE_INTEGER)) return "";
2002
- if (length === void 0) return scalars.slice(Number(clampedStart)).join("");
2003
- const count = asInteger(length);
2004
- if (count < 0n) return null;
2005
- if (count > BigInt(Number.MAX_SAFE_INTEGER)) return scalars.slice(Number(clampedStart)).join("");
2006
- return scalars.slice(Number(clampedStart), Number(clampedStart + count)).join("");
2007
- }
2008
- function dateAddDays(date, amount) {
2009
- if (date === null || amount === null) return null;
2010
- const parts = parseDate(date);
2011
- const result = civilFromDays(daysFromCivil(parts.year, parts.month, parts.day) + asInteger(amount));
2012
- return result.year < 1n || result.year > 9999n ? null : formatDate(result);
2013
- }
2014
- function dateDiffDays(left, right) {
2015
- if (left === null || right === null) return null;
2016
- const a = parseDate(left);
2017
- const b = parseDate(right);
2018
- return boundedInteger$1(daysFromCivil(a.year, a.month, a.day) - daysFromCivil(b.year, b.month, b.day));
2019
- }
2020
- function datetimeAddMilliseconds(datetime, amount) {
2021
- if (datetime === null || amount === null) return null;
2022
- return formatInstant(parseInstant(datetime) + asInteger(amount));
2023
- }
2024
- function datetimeDiffMilliseconds(left, right) {
2025
- if (left === null || right === null) return null;
2026
- return boundedInteger$1(parseInstant(left) - parseInstant(right));
2027
- }
2028
- function parseDate(value) {
2029
- if (typeof value !== "string") throw new TypeError("Formula expected a date");
2030
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
2031
- if (!match) throw new TypeError("Formula date is not canonical");
2032
- return {
2033
- year: BigInt(match[1]),
2034
- month: BigInt(match[2]),
2035
- day: BigInt(match[3])
2036
- };
2037
- }
2038
- function parseInstant(value) {
2039
- if (typeof value !== "string") throw new TypeError("Formula expected a datetime");
2040
- const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/.exec(value);
2041
- if (!match) throw new TypeError("Formula datetime is not canonical");
2042
- const date = {
2043
- year: BigInt(match[1]),
2044
- month: BigInt(match[2]),
2045
- day: BigInt(match[3])
2046
- };
2047
- return daysFromCivil(date.year, date.month, date.day) * 86400000n + BigInt(match[4]) * 3600000n + BigInt(match[5]) * 60000n + BigInt(match[6]) * 1000n + BigInt(match[7]);
2048
- }
2049
- function formatInstant(milliseconds) {
2050
- let days = milliseconds / 86400000n;
2051
- let remainder = milliseconds % 86400000n;
2052
- if (remainder < 0n) {
2053
- days -= 1n;
2054
- remainder += 86400000n;
2055
- }
2056
- const date = civilFromDays(days);
2057
- if (date.year < 1n || date.year > 9999n) return null;
2058
- const hour = remainder / 3600000n;
2059
- remainder %= 3600000n;
2060
- const minute = remainder / 60000n;
2061
- remainder %= 60000n;
2062
- const second = remainder / 1000n;
2063
- const millisecond = remainder % 1000n;
2064
- return `${formatDate(date)}T${pad(hour, 2)}:${pad(minute, 2)}:${pad(second, 2)}.${pad(millisecond, 3)}Z`;
2065
- }
2066
- function daysFromCivil(year, month, day) {
2067
- const adjustedYear = year - (month <= 2n ? 1n : 0n);
2068
- const era = floorDiv(adjustedYear, 400n);
2069
- const yearOfEra = adjustedYear - era * 400n;
2070
- const dayOfYear = (153n * (month + (month > 2n ? -3n : 9n)) + 2n) / 5n + day - 1n;
2071
- const dayOfEra = yearOfEra * 365n + yearOfEra / 4n - yearOfEra / 100n + dayOfYear;
2072
- return era * 146097n + dayOfEra - 719468n;
2073
- }
2074
- function civilFromDays(days) {
2075
- const shifted = days + 719468n;
2076
- const era = floorDiv(shifted, 146097n);
2077
- const dayOfEra = shifted - era * 146097n;
2078
- const yearOfEra = (dayOfEra - dayOfEra / 1460n + dayOfEra / 36524n - dayOfEra / 146096n) / 365n;
2079
- let year = yearOfEra + era * 400n;
2080
- const dayOfYear = dayOfEra - (365n * yearOfEra + yearOfEra / 4n - yearOfEra / 100n);
2081
- const monthPrime = (5n * dayOfYear + 2n) / 153n;
2082
- const day = dayOfYear - (153n * monthPrime + 2n) / 5n + 1n;
2083
- const month = monthPrime + (monthPrime < 10n ? 3n : -9n);
2084
- year += month <= 2n ? 1n : 0n;
2085
- return {
2086
- year,
2087
- month,
2088
- day
2089
- };
2090
- }
2091
- function floorDiv(value, divisor) {
2092
- const quotient = value / divisor;
2093
- return value < 0n && value % divisor !== 0n ? quotient - 1n : quotient;
2094
- }
2095
- function formatDate(value) {
2096
- return `${pad(value.year, 4)}-${pad(value.month, 2)}-${pad(value.day, 2)}`;
2097
- }
2098
- function pad(value, width) {
2099
- return value.toString().padStart(width, "0");
2100
- }
2101
2248
  //#endregion
2102
2249
  //#region src/lookup-functions.ts
2103
2250
  const INT64_MIN = -9223372036854775808n;
@@ -2737,6 +2884,25 @@ const FILTER_OPERATORS = new Set([
2737
2884
  "is-between",
2738
2885
  "is-relative-to-today"
2739
2886
  ]);
2887
+ const RUNTIME_FILTER_OPERATORS$1 = new Set([
2888
+ "is-null",
2889
+ "is-not-null",
2890
+ "eq",
2891
+ "ne",
2892
+ "lt",
2893
+ "lte",
2894
+ "gt",
2895
+ "gte",
2896
+ "between",
2897
+ "in",
2898
+ "contains",
2899
+ "starts-with",
2900
+ "ends-with",
2901
+ "has-any",
2902
+ "has-all",
2903
+ "relation-has",
2904
+ "relative-date"
2905
+ ]);
2740
2906
  const LEVELS = {
2741
2907
  identity: 0,
2742
2908
  structural: 1,
@@ -3259,17 +3425,128 @@ function validateEidosFile(connection, options = {}) {
3259
3425
  if (!query || Array.isArray(query) || typeof query !== "object") throw new Error("View query_json must be an object");
3260
3426
  if (!layout || Array.isArray(layout) || typeof layout !== "object") throw new Error("View layout_json must be an object");
3261
3427
  let unsupportedQuery = Object.keys(query).some((key) => key !== "filter" && key !== "sort");
3428
+ const hasOnlyKeys = (value, keys) => Object.keys(value).every((key) => keys.includes(key));
3262
3429
  const checkFilter = (value) => {
3263
3430
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("View filter nodes must be objects");
3264
3431
  const node = value;
3265
- if (Array.isArray(node.args)) {
3266
- if (typeof node.op !== "string") throw new Error("View filter group has an invalid op");
3267
- if (node.op !== "and" && node.op !== "or" || Object.keys(node).some((key) => key !== "op" && key !== "args")) unsupportedQuery = true;
3432
+ if (node.op === "and" || node.op === "or") {
3433
+ if (!Array.isArray(node.args)) throw new Error("View filter group must contain args");
3434
+ if (!hasOnlyKeys(node, ["op", "args"])) unsupportedQuery = true;
3268
3435
  node.args.forEach(checkFilter);
3269
3436
  return;
3270
3437
  }
3271
- if (typeof node.field !== "string" || !fieldIds.has(node.field)) throw new Error("View filter references an unknown Field ID");
3438
+ if (node.op === "not") {
3439
+ if (!("arg" in node)) throw new Error("View filter negation must contain an arg");
3440
+ if (!hasOnlyKeys(node, ["op", "arg"])) unsupportedQuery = true;
3441
+ checkFilter(node.arg);
3442
+ return;
3443
+ }
3272
3444
  if (typeof node.op !== "string") throw new Error("View filter rule has an invalid operator");
3445
+ if ("fieldId" in node) {
3446
+ if (typeof node.fieldId !== "string" || !fieldIds.has(node.fieldId)) throw new Error("View filter references an unknown Field ID");
3447
+ if (!RUNTIME_FILTER_OPERATORS$1.has(node.op)) {
3448
+ unsupportedQuery = true;
3449
+ return;
3450
+ }
3451
+ const field = fieldsById.get(node.fieldId);
3452
+ if ((field.storageCodec === "json_array" || field.storageCodec === "relation") && [
3453
+ "lt",
3454
+ "lte",
3455
+ "gt",
3456
+ "gte",
3457
+ "starts-with",
3458
+ "ends-with"
3459
+ ].includes(node.op)) throw new Error("View filter uses a scalar comparison on a list Field");
3460
+ if (node.op === "is-null" || node.op === "is-not-null") {
3461
+ if (!hasOnlyKeys(node, ["op", "fieldId"])) unsupportedQuery = true;
3462
+ return;
3463
+ }
3464
+ if ([
3465
+ "eq",
3466
+ "ne",
3467
+ "lt",
3468
+ "lte",
3469
+ "gt",
3470
+ "gte"
3471
+ ].includes(node.op)) {
3472
+ if (!("value" in node) || node.value === null) throw new Error("View filter operand must be non-null");
3473
+ if (!hasOnlyKeys(node, [
3474
+ "op",
3475
+ "fieldId",
3476
+ "value"
3477
+ ])) unsupportedQuery = true;
3478
+ if (field.type === "relation" && (!Array.isArray(node.value) || !node.value.every(isEidosFileUuid))) throw new Error("View Relation filter values must be canonical Row IDs");
3479
+ return;
3480
+ }
3481
+ if (node.op === "between") {
3482
+ if (!("lower" in node) || !("upper" in node)) throw new Error("View between filter is missing an operand");
3483
+ if (node.lower === null || node.upper === null) throw new Error("View between operands must be non-null");
3484
+ if (!hasOnlyKeys(node, [
3485
+ "op",
3486
+ "fieldId",
3487
+ "lower",
3488
+ "upper"
3489
+ ])) unsupportedQuery = true;
3490
+ return;
3491
+ }
3492
+ if ([
3493
+ "in",
3494
+ "has-any",
3495
+ "has-all"
3496
+ ].includes(node.op)) {
3497
+ if (!Array.isArray(node.values) || node.values.some((entry) => entry === null)) throw new Error("View membership filter values must be a non-null array");
3498
+ if (!hasOnlyKeys(node, [
3499
+ "op",
3500
+ "fieldId",
3501
+ "values"
3502
+ ])) unsupportedQuery = true;
3503
+ if (field.type === "relation" && !(node.op === "in" ? node.values.every((value) => Array.isArray(value) && value.every(isEidosFileUuid)) : node.values.every(isEidosFileUuid))) throw new Error("View Relation filter values must be canonical Row IDs");
3504
+ return;
3505
+ }
3506
+ if ([
3507
+ "contains",
3508
+ "starts-with",
3509
+ "ends-with"
3510
+ ].includes(node.op)) {
3511
+ if (typeof node.value !== "string") throw new Error("View text filter value must be a string");
3512
+ if (!hasOnlyKeys(node, [
3513
+ "op",
3514
+ "fieldId",
3515
+ "value"
3516
+ ])) unsupportedQuery = true;
3517
+ return;
3518
+ }
3519
+ if (node.op === "relation-has") {
3520
+ if (field.type !== "relation" || !isEidosFileUuid(node.rowId)) throw new Error("View Relation filter must reference a canonical Row ID");
3521
+ if (!hasOnlyKeys(node, [
3522
+ "op",
3523
+ "fieldId",
3524
+ "rowId"
3525
+ ])) unsupportedQuery = true;
3526
+ return;
3527
+ }
3528
+ if (node.op === "relative-date") {
3529
+ if (field.type !== "date" && field.type !== "datetime" && field.type !== "created-time" && field.type !== "last-edited-time") throw new Error("View relative filter requires a Date or Datetime Field");
3530
+ if (![
3531
+ "past",
3532
+ "next",
3533
+ "this"
3534
+ ].includes(String(node.direction)) || ![
3535
+ "day",
3536
+ "week",
3537
+ "month",
3538
+ "year"
3539
+ ].includes(String(node.unit))) throw new Error("View relative filter value is invalid");
3540
+ if (!hasOnlyKeys(node, [
3541
+ "op",
3542
+ "fieldId",
3543
+ "direction",
3544
+ "unit"
3545
+ ])) unsupportedQuery = true;
3546
+ return;
3547
+ }
3548
+ }
3549
+ if (typeof node.field !== "string" || !fieldIds.has(node.field)) throw new Error("View filter references an unknown Field ID");
3273
3550
  if (!FILTER_OPERATORS.has(node.op)) {
3274
3551
  unsupportedQuery = true;
3275
3552
  return;
@@ -3312,8 +3589,9 @@ function validateEidosFile(connection, options = {}) {
3312
3589
  if ("sort" in query) {
3313
3590
  if (!Array.isArray(query.sort)) throw new Error("View sort must be an array");
3314
3591
  for (const item of query.sort) {
3315
- if (!item || Array.isArray(item) || typeof item !== "object" || typeof item.field !== "string" || !fieldIds.has(item.field)) throw new Error("View sort contains an invalid Field reference or direction");
3316
- if (item.direction !== "asc" && item.direction !== "desc" || item.nulls !== void 0 && item.nulls !== "first" && item.nulls !== "last" || Object.keys(item).some((key) => key !== "field" && key !== "direction" && key !== "nulls")) unsupportedQuery = true;
3592
+ const fieldId = item && !Array.isArray(item) && typeof item === "object" ? typeof item.fieldId === "string" ? item.fieldId : item.field : void 0;
3593
+ if (!item || Array.isArray(item) || typeof item !== "object" || typeof fieldId !== "string" || !fieldIds.has(fieldId)) throw new Error("View sort contains an invalid Field reference or direction");
3594
+ if (item.direction !== "asc" && item.direction !== "desc" || item.nulls !== void 0 && item.nulls !== "first" && item.nulls !== "last" || Object.keys(item).some((key) => key !== "field" && key !== "fieldId" && key !== "direction" && key !== "nulls")) unsupportedQuery = true;
3317
3595
  }
3318
3596
  }
3319
3597
  if (unsupportedQuery) add(warnings, "view-query-unsupported", `View ${view.id} uses query semantics from a newer Eidos version`);
@@ -3529,13 +3807,14 @@ function presentationSettingsObject(source) {
3529
3807
  ]) delete property[key];
3530
3808
  return property;
3531
3809
  }
3810
+ function assertedRawSelectOptions(property) {
3811
+ assertEidosFileSelectOptions(property);
3812
+ return Array.isArray(property?.options) ? property.options.map((option) => ({ ...option })) : [];
3813
+ }
3532
3814
  function presentationSettings(input) {
3533
3815
  const property = presentationSettingsObject("property" in input ? input.property : void 0);
3534
3816
  if (input.type === "select" || input.type === "multi-select") {
3535
- property.options = assertEidosFileSelectOptions("property" in input ? input.property : void 0).map((option) => ({
3536
- color: option.color,
3537
- name: option.name
3538
- }));
3817
+ property.options = assertedRawSelectOptions("property" in input ? input.property : void 0);
3539
3818
  if (input.type === "select") {
3540
3819
  const defaultOption = assertEidosFileSelectDefaultOption(property);
3541
3820
  if (defaultOption === null) delete property.defaultOption;
@@ -3548,8 +3827,9 @@ function transformOptionValue(value, fieldId, changes) {
3548
3827
  if (Array.isArray(value)) return value.map((entry) => transformOptionValue(entry, fieldId, changes));
3549
3828
  if (!value || typeof value !== "object") return value;
3550
3829
  const object = value;
3830
+ const referencesField = object.fieldId === fieldId || object.field === fieldId;
3551
3831
  const next = {};
3552
- for (const [key, entry] of Object.entries(object)) if (object.field === fieldId && key === "value") next[key] = Array.isArray(entry) ? entry.map((item) => typeof item === "string" ? changes.get(item) ?? item : item) : typeof entry === "string" ? changes.get(entry) ?? entry : entry;
3832
+ for (const [key, entry] of Object.entries(object)) if (referencesField && (key === "value" || key === "values" || key === "lower" || key === "upper")) next[key] = Array.isArray(entry) ? entry.map((item) => typeof item === "string" ? changes.get(item) ?? item : item) : typeof entry === "string" ? changes.get(entry) ?? entry : entry;
3553
3833
  else next[key] = transformOptionValue(entry, fieldId, changes);
3554
3834
  return next;
3555
3835
  }
@@ -3695,27 +3975,165 @@ function filterToStorage(filter, fields) {
3695
3975
  if (!normalized) return null;
3696
3976
  const byKey = /* @__PURE__ */ new Map();
3697
3977
  for (const field of fields) if (field.id) {
3698
- byKey.set(field.id, field.id);
3699
- byKey.set(field.tableColumnName, field.id);
3700
- byKey.set(field.name, field.id);
3978
+ byKey.set(field.id, field);
3979
+ byKey.set(field.tableColumnName, field);
3980
+ byKey.set(field.name, field);
3701
3981
  }
3702
- const convert = (group) => {
3703
- const args = [];
3704
- for (const child of group.children) if (child.type === "group") args.push(convert(child));
3705
- else {
3706
- const field = byKey.get(child.field);
3707
- if (field) args.push({
3708
- field,
3709
- op: child.operator,
3710
- ..."value" in child ? { value: child.value } : {}
3711
- });
3982
+ const convertRule = (rule) => {
3983
+ const field = byKey.get(rule.field);
3984
+ if (!field?.id) return null;
3985
+ const fieldId = field.id;
3986
+ const list = field.storageCodec === "json_array" || field.storageCodec === "relation";
3987
+ const values = Array.isArray(rule.value) ? rule.value : [rule.value ?? null];
3988
+ const scalar = values[0] ?? null;
3989
+ const equalityValue = list && Array.isArray(rule.value) ? rule.value : scalar;
3990
+ const requireValue = () => {
3991
+ if (scalar === null) throw new EidosFileError("invalid-query", `Saved View filter ${rule.operator} requires an operand`);
3992
+ return scalar;
3993
+ };
3994
+ const requireValues = () => {
3995
+ if (values.some((value) => value === null)) throw new EidosFileError("invalid-query", `Saved View filter ${rule.operator} requires non-null operands`);
3996
+ return values;
3997
+ };
3998
+ const membership = () => list ? {
3999
+ fieldId,
4000
+ op: "has-any",
4001
+ values: requireValues()
4002
+ } : {
4003
+ fieldId,
4004
+ op: "in",
4005
+ values: requireValues()
4006
+ };
4007
+ if (rule.operator === "is-relative-to-today") {
4008
+ const relative = rule.value;
4009
+ if (!relative || typeof relative !== "object" || Array.isArray(relative) || !("direction" in relative) || !("unit" in relative) || ![
4010
+ "past",
4011
+ "next",
4012
+ "this"
4013
+ ].includes(String(relative.direction)) || ![
4014
+ "day",
4015
+ "week",
4016
+ "month",
4017
+ "year"
4018
+ ].includes(String(relative.unit))) throw new EidosFileError("invalid-query", "Saved View relative date filter is invalid");
4019
+ return {
4020
+ direction: relative.direction,
4021
+ fieldId,
4022
+ op: "relative-date",
4023
+ unit: relative.unit
4024
+ };
3712
4025
  }
3713
- return {
3714
- args,
4026
+ if (rule.operator === "is-between") {
4027
+ if (!Array.isArray(rule.value) || rule.value.length !== 2 || rule.value.some((value) => value === null)) throw new EidosFileError("invalid-query", "Saved View between filter is invalid");
4028
+ return {
4029
+ fieldId,
4030
+ lower: rule.value[0],
4031
+ op: "between",
4032
+ upper: rule.value[1]
4033
+ };
4034
+ }
4035
+ switch (rule.operator) {
4036
+ case "is-empty": return list ? {
4037
+ fieldId,
4038
+ op: "eq",
4039
+ value: []
4040
+ } : {
4041
+ fieldId,
4042
+ op: "is-null"
4043
+ };
4044
+ case "is-not-empty": return list ? {
4045
+ fieldId,
4046
+ op: "ne",
4047
+ value: []
4048
+ } : {
4049
+ fieldId,
4050
+ op: "is-not-null"
4051
+ };
4052
+ case "equals": return equalityValue === null ? {
4053
+ fieldId,
4054
+ op: "is-null"
4055
+ } : {
4056
+ fieldId,
4057
+ op: "eq",
4058
+ value: equalityValue
4059
+ };
4060
+ case "not-equals": return equalityValue === null ? {
4061
+ fieldId,
4062
+ op: "is-not-null"
4063
+ } : {
4064
+ fieldId,
4065
+ op: "ne",
4066
+ value: equalityValue
4067
+ };
4068
+ case "less-than": return {
4069
+ fieldId,
4070
+ op: "lt",
4071
+ value: requireValue()
4072
+ };
4073
+ case "less-than-or-equal": return {
4074
+ fieldId,
4075
+ op: "lte",
4076
+ value: requireValue()
4077
+ };
4078
+ case "greater-than": return {
4079
+ fieldId,
4080
+ op: "gt",
4081
+ value: requireValue()
4082
+ };
4083
+ case "greater-than-or-equal": return {
4084
+ fieldId,
4085
+ op: "gte",
4086
+ value: requireValue()
4087
+ };
4088
+ case "contains": return list ? membership() : {
4089
+ fieldId,
4090
+ op: "contains",
4091
+ value: String(requireValue())
4092
+ };
4093
+ case "not-contains": return {
4094
+ arg: list ? membership() : {
4095
+ fieldId,
4096
+ op: "contains",
4097
+ value: String(requireValue())
4098
+ },
4099
+ op: "not"
4100
+ };
4101
+ case "starts-with": return {
4102
+ fieldId,
4103
+ op: "starts-with",
4104
+ value: String(requireValue())
4105
+ };
4106
+ case "ends-with": return {
4107
+ fieldId,
4108
+ op: "ends-with",
4109
+ value: String(requireValue())
4110
+ };
4111
+ case "is-any-of": return membership();
4112
+ case "is-all-of": return {
4113
+ fieldId,
4114
+ op: "has-all",
4115
+ values: requireValues()
4116
+ };
4117
+ case "is-none-of": return {
4118
+ arg: membership(),
4119
+ op: "not"
4120
+ };
4121
+ }
4122
+ };
4123
+ const convertGroup = (group) => {
4124
+ const node = {
4125
+ args: group.children.flatMap((child) => {
4126
+ const converted = child.type === "group" ? convertGroup(child) : convertRule(child);
4127
+ return converted ? [converted] : [];
4128
+ }),
3715
4129
  op: group.conjunction
3716
4130
  };
4131
+ return group.negated ? {
4132
+ arg: node,
4133
+ op: "not"
4134
+ } : node;
3717
4135
  };
3718
- return convert(normalized);
4136
+ return convertGroup(normalized);
3719
4137
  }
3720
4138
  function filterFromStorage(value, fields) {
3721
4139
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
@@ -3746,7 +4164,133 @@ function filterFromStorage(value, fields) {
3746
4164
  children
3747
4165
  };
3748
4166
  };
3749
- return normalizeEidosFileFilter(convert(value));
4167
+ const runtimeGroup = (conjunction, children) => ({
4168
+ type: "group",
4169
+ conjunction,
4170
+ children
4171
+ });
4172
+ const convertRuntime = (input) => {
4173
+ if (!input || typeof input !== "object" || Array.isArray(input)) return null;
4174
+ const node = input;
4175
+ if ((node.op === "and" || node.op === "or") && Array.isArray(node.args)) return runtimeGroup(node.op, node.args.flatMap((child) => {
4176
+ const converted = convertRuntime(child);
4177
+ return converted ? [converted] : [];
4178
+ }));
4179
+ if (node.op === "not" && node.arg !== void 0) {
4180
+ const child = convertRuntime(node.arg);
4181
+ if (!child) return null;
4182
+ const nested = child.type === "group" ? child : runtimeGroup("and", [child]);
4183
+ return {
4184
+ ...nested,
4185
+ negated: nested.negated !== true
4186
+ };
4187
+ }
4188
+ if (typeof node.fieldId !== "string" || !ids.has(node.fieldId) || typeof node.op !== "string") return null;
4189
+ const field = node.fieldId;
4190
+ if (node.op === "between") return {
4191
+ type: "rule",
4192
+ field,
4193
+ operator: "is-between",
4194
+ value: [node.lower, node.upper]
4195
+ };
4196
+ if (node.op === "relative-date") return {
4197
+ type: "rule",
4198
+ field,
4199
+ operator: "is-relative-to-today",
4200
+ value: {
4201
+ direction: node.direction,
4202
+ unit: node.unit
4203
+ }
4204
+ };
4205
+ if (node.op === "has-all") return {
4206
+ type: "rule",
4207
+ field,
4208
+ operator: "is-all-of",
4209
+ value: node.values
4210
+ };
4211
+ if (node.op === "in") return runtimeGroup("or", node.values.map((entry) => ({
4212
+ type: "rule",
4213
+ field,
4214
+ operator: "equals",
4215
+ value: entry
4216
+ })));
4217
+ if (node.op === "is-null" || node.op === "is-not-null") return {
4218
+ type: "rule",
4219
+ field,
4220
+ operator: node.op === "is-null" ? "equals" : "not-equals",
4221
+ value: null
4222
+ };
4223
+ const operator = RUNTIME_TO_COMPATIBILITY_OPERATOR[node.op];
4224
+ if (!operator) return null;
4225
+ return {
4226
+ type: "rule",
4227
+ field,
4228
+ operator,
4229
+ ...node.op === "has-any" ? { value: node.values } : node.op === "relation-has" ? { value: [node.rowId] } : "value" in node ? { value: node.value } : {}
4230
+ };
4231
+ };
4232
+ const containsRuntimeField = (input) => {
4233
+ if (!input || typeof input !== "object") return false;
4234
+ if (Array.isArray(input)) return input.some(containsRuntimeField);
4235
+ const node = input;
4236
+ return typeof node.fieldId === "string" || Object.values(node).some(containsRuntimeField);
4237
+ };
4238
+ if (!containsRuntimeField(value)) return normalizeEidosFileFilter(convert(value));
4239
+ const converted = convertRuntime(value);
4240
+ return normalizeEidosFileFilter(converted?.type === "group" ? converted : converted ? runtimeGroup("and", [converted]) : null);
4241
+ }
4242
+ const RUNTIME_TO_COMPATIBILITY_OPERATOR = {
4243
+ eq: "equals",
4244
+ ne: "not-equals",
4245
+ lt: "less-than",
4246
+ lte: "less-than-or-equal",
4247
+ gt: "greater-than",
4248
+ gte: "greater-than-or-equal",
4249
+ contains: "contains",
4250
+ "starts-with": "starts-with",
4251
+ "ends-with": "ends-with",
4252
+ "has-any": "is-any-of",
4253
+ "relation-has": "is-any-of"
4254
+ };
4255
+ const RUNTIME_FILTER_OPERATORS = new Set([
4256
+ "is-null",
4257
+ "is-not-null",
4258
+ "eq",
4259
+ "ne",
4260
+ "lt",
4261
+ "lte",
4262
+ "gt",
4263
+ "gte",
4264
+ "between",
4265
+ "in",
4266
+ "contains",
4267
+ "starts-with",
4268
+ "ends-with",
4269
+ "has-any",
4270
+ "has-all",
4271
+ "relation-has",
4272
+ "relative-date"
4273
+ ]);
4274
+ function sortsFromStorage(value) {
4275
+ if (!Array.isArray(value)) return [];
4276
+ return value.flatMap((entry) => {
4277
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
4278
+ const sort = entry;
4279
+ const field = typeof sort.fieldId === "string" ? sort.fieldId : typeof sort.field === "string" ? sort.field : null;
4280
+ if (!field) return [];
4281
+ return [{
4282
+ field,
4283
+ direction: sort.direction === "desc" ? "desc" : "asc",
4284
+ nulls: sort.nulls === "first" ? "first" : "last"
4285
+ }];
4286
+ });
4287
+ }
4288
+ function sortsToStorage(sorts) {
4289
+ return sorts.map((sort) => ({
4290
+ direction: sort.direction,
4291
+ fieldId: sort.field,
4292
+ ...sort.nulls === "first" ? { nulls: "first" } : {}
4293
+ }));
3750
4294
  }
3751
4295
  function storedViewQueryStatus(query, fields) {
3752
4296
  const fieldIds = new Set(fields.flatMap((field) => field.id ? [field.id] : []));
@@ -3773,7 +4317,54 @@ function storedViewQueryStatus(query, fields) {
3773
4317
  const filterSupported = (value) => {
3774
4318
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
3775
4319
  const node = value;
3776
- if (Array.isArray(node.args)) return (node.op === "and" || node.op === "or") && Object.keys(node).every((key) => key === "op" || key === "args") && node.args.every(filterSupported);
4320
+ if ((node.op === "and" || node.op === "or") && Array.isArray(node.args)) return Object.keys(node).every((key) => key === "op" || key === "args") && node.args.every(filterSupported);
4321
+ if (node.op === "not") return Object.keys(node).every((key) => key === "op" || key === "arg") && filterSupported(node.arg);
4322
+ if (typeof node.fieldId === "string") {
4323
+ if (!fieldIds.has(node.fieldId) || typeof node.op !== "string" || !RUNTIME_FILTER_OPERATORS.has(node.op)) return false;
4324
+ const allowed = new Set(["fieldId", "op"]);
4325
+ if ([
4326
+ "eq",
4327
+ "ne",
4328
+ "lt",
4329
+ "lte",
4330
+ "gt",
4331
+ "gte",
4332
+ "contains",
4333
+ "starts-with",
4334
+ "ends-with"
4335
+ ].includes(node.op)) {
4336
+ allowed.add("value");
4337
+ if (!("value" in node) || node.value === null) return false;
4338
+ } else if ([
4339
+ "in",
4340
+ "has-any",
4341
+ "has-all"
4342
+ ].includes(node.op)) {
4343
+ allowed.add("values");
4344
+ if (!Array.isArray(node.values)) return false;
4345
+ } else if (node.op === "between") {
4346
+ allowed.add("lower");
4347
+ allowed.add("upper");
4348
+ if (!("lower" in node) || !("upper" in node) || node.lower === null || node.upper === null) return false;
4349
+ } else if (node.op === "relation-has") {
4350
+ allowed.add("rowId");
4351
+ if (typeof node.rowId !== "string") return false;
4352
+ } else if (node.op === "relative-date") {
4353
+ allowed.add("direction");
4354
+ allowed.add("unit");
4355
+ if (![
4356
+ "past",
4357
+ "next",
4358
+ "this"
4359
+ ].includes(String(node.direction)) || ![
4360
+ "day",
4361
+ "week",
4362
+ "month",
4363
+ "year"
4364
+ ].includes(String(node.unit))) return false;
4365
+ }
4366
+ return Object.keys(node).every((key) => allowed.has(key));
4367
+ }
3777
4368
  if (typeof node.field !== "string" || !fieldIds.has(node.field) || !isEidosFileFilterOperator(node.op) || Object.keys(node).some((key) => key !== "field" && key !== "op" && key !== "value")) return false;
3778
4369
  return supportedRuleValue(node.op, node.value);
3779
4370
  };
@@ -3783,7 +4374,9 @@ function storedViewQueryStatus(query, fields) {
3783
4374
  for (const value of query.sort) {
3784
4375
  if (!value || typeof value !== "object" || Array.isArray(value)) return "unsupported";
3785
4376
  const sort = value;
3786
- if (typeof sort.field !== "string" || !fieldIds.has(sort.field) || sort.direction !== "asc" && sort.direction !== "desc" || sort.nulls !== void 0 && sort.nulls !== "first" && sort.nulls !== "last" || Object.keys(sort).some((key) => key !== "field" && key !== "direction" && key !== "nulls")) return "unsupported";
4377
+ const field = typeof sort.fieldId === "string" ? sort.fieldId : typeof sort.field === "string" ? sort.field : null;
4378
+ const fieldKey = typeof sort.fieldId === "string" ? "fieldId" : "field";
4379
+ if (!field || !fieldIds.has(field) || sort.direction !== "asc" && sort.direction !== "desc" || sort.nulls !== void 0 && sort.nulls !== "first" && sort.nulls !== "last" || Object.keys(sort).some((key) => key !== fieldKey && key !== "direction" && key !== "nulls")) return "unsupported";
3787
4380
  }
3788
4381
  }
3789
4382
  return "supported";
@@ -3805,6 +4398,7 @@ var EidosFileRuntime = class {
3805
4398
  connection.exec("PRAGMA foreign_keys = ON; PRAGMA trusted_schema = OFF;");
3806
4399
  connection.registerFunction("eidos_casefold", (value) => value === null ? null : String(value).toUpperCase().toLowerCase());
3807
4400
  registerEidosFormulaFunctions(connection);
4401
+ assertEidosFileFormulaProfile(connection);
3808
4402
  registerEidosLookupFunctions(connection);
3809
4403
  }
3810
4404
  close() {
@@ -4460,7 +5054,7 @@ var EidosFileRuntime = class {
4460
5054
  if (changes.optionValueChanges && changes.optionValueChanges.length > 0) {
4461
5055
  if (field.type !== "select" && field.type !== "multi-select") throw new EidosFileError("invalid-schema", "Only Select Fields have option values");
4462
5056
  const replacements = new Map(changes.optionValueChanges.map((change) => [change.from, change.to]));
4463
- const options = assertEidosFileSelectOptions(settings);
5057
+ const options = assertedRawSelectOptions(settings);
4464
5058
  const existingNames = new Set(options.map((option) => option.name));
4465
5059
  settings.options = options.flatMap((option) => {
4466
5060
  const replacement = replacements.get(option.name);
@@ -4474,10 +5068,7 @@ var EidosFileRuntime = class {
4474
5068
  if (field.type === "select" && typeof settings.defaultOption === "string") settings.defaultOption = replacements.get(settings.defaultOption) ?? settings.defaultOption;
4475
5069
  }
4476
5070
  if (field.type === "select" || field.type === "multi-select") {
4477
- settings.options = assertEidosFileSelectOptions(settings).map((option) => ({
4478
- color: option.color,
4479
- name: option.name
4480
- }));
5071
+ settings.options = assertedRawSelectOptions(settings);
4481
5072
  if (field.type === "select") {
4482
5073
  const defaultOption = assertEidosFileSelectDefaultOption(settings);
4483
5074
  if (defaultOption === null) delete settings.defaultOption;
@@ -4827,7 +5418,7 @@ var EidosFileRuntime = class {
4827
5418
  const query = jsonObject(row.query_json);
4828
5419
  const layout = jsonObject(row.layout_json);
4829
5420
  const queryStatus = storedViewQueryStatus(query, fields);
4830
- const storedSorts = normalizeEidosFileSorts(query.sort);
5421
+ const storedSorts = sortsFromStorage(query.sort);
4831
5422
  const fieldIds = new Set(fields.flatMap((field) => field.id ? [field.id] : []));
4832
5423
  const fieldOrder = Array.isArray(layout.fieldOrder) ? layout.fieldOrder.flatMap((value) => typeof value === "string" && fieldIds.has(value) ? [value] : []) : [];
4833
5424
  const properties = { ...layout };
@@ -4901,7 +5492,7 @@ var EidosFileRuntime = class {
4901
5492
  input.type,
4902
5493
  canonicalizeEidosFileJson({
4903
5494
  ...filterToStorage(input.filter, fields) ? { filter: filterToStorage(input.filter, fields) } : {},
4904
- ...sorts.length > 0 ? { sort: sorts } : {}
5495
+ ...sorts.length > 0 ? { sort: sortsToStorage(sorts) } : {}
4905
5496
  }),
4906
5497
  canonicalizeEidosFileJson({
4907
5498
  ...properties,
@@ -4970,7 +5561,7 @@ var EidosFileRuntime = class {
4970
5561
  next.type,
4971
5562
  queryChanged ? canonicalizeEidosFileJson({
4972
5563
  ...filterToStorage(next.filter, fields) ? { filter: filterToStorage(next.filter, fields) } : {},
4973
- ...sorts.length ? { sort: sorts } : {}
5564
+ ...sorts.length ? { sort: sortsToStorage(sorts) } : {}
4974
5565
  }) : currentRow.query_json,
4975
5566
  layoutChanged ? canonicalizeEidosFileJson(layout) : currentRow.layout_json,
4976
5567
  stablePosition(next.position, current.position ?? 0),
@@ -6216,6 +6807,6 @@ function fieldValueTypeForScan(field) {
6216
6807
  return field.type;
6217
6808
  }
6218
6809
  //#endregion
6219
- export { EIDOS_FILE_REQUIRED_TABLES as $, eidosFileLookupElementType as A, eidosFileFormulaReferences as B, normalizeEidosFileFilter as C, eidosFileFieldStoresJsonArray as D, removeEidosFileFilterField as E, EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES as F, EIDOS_FILE_FIELDS_TABLE as G, EIDOS_FILE_APPLICATION_ID as H, EIDOS_FILE_FORMULA_FUNCTION_NAMES as I, EIDOS_FILE_FORMULA_FIELDS_TABLE as J, EIDOS_FILE_FORMAT as K, compileEidosFileFormula as L, eidosFileLookupTargetDisplayType as M, eidosFileLookupTargetValueType as N, eidosFileLookupAggregateSupportsTarget as O, eidosFileLookupValueType as P, EIDOS_FILE_RELATION_FIELDS_TABLE as Q, compileEidosFileFormulaFields as R, isEidosFileFilterOperator as S, normalizeEidosFileSorts as T, EIDOS_FILE_EXTENSION as U, rewriteEidosFileFormulaFieldReferences as V, EIDOS_FILE_FEATURES_TABLE as W, EIDOS_FILE_META_TABLE as X, EIDOS_FILE_LOOKUP_FIELDS_TABLE as Y, EIDOS_FILE_MIME_TYPE as Z, assertEidosFileRowQuery as _, EIDOS_FILE_FORMAT_VERSION_TEXT as a, hasEidosFileSqliteHeader as at, eidosFileRowQueryPredicateColumns as b, incrementEidosFileRevision as c, ConnectionPortEidosFileConnection as ct, decodeEidosFileRelationDisplay as d, assertInt64Decimal as dt, EIDOS_FILE_SCHEMA_VERSION as et, decodeEidosFileRelationIds as f, assertUnicodeString as ft, parseNonNegativeInt64 as g, cancellationPortFromSignal as h, sqlValueToNative as ht, scanStableRowPages as i, SQLITE_HEADER as it, eidosFileLookupStorageCodec as j, eidosFileLookupDisplayType as k, initializeEidosFileSchema as l, EidosAdapterError as lt, MemoryByteSource as m, nativeToSqlValue as mt, validateEidosFile as n, EIDOS_FILE_TABLES_TABLE as nt, EIDOS_FILE_SCHEMA_SQL as o, eidosFileColumnStatLabel as ot, encodeEidosFileRelationIds as p, exactConnectionBindingCount as pt, EIDOS_FILE_FORMAT_VERSION as q, smallestDependencyCycle as r, EIDOS_FILE_VIEWS_TABLE as rt, configureEidosFileConnection as s, eidosFileColumnStatTypesForField as st, EidosFileRuntime as t, EIDOS_FILE_SYSTEM_COLUMNS as tt, setEidosFileMetadata as u, assertExactConnectionBindings as ut, compileEidosFileRowQuery as v, normalizeEidosFileRowQuery as w, eidosFileSortExpression as x, eidosFileRowQueryAffectedByFieldChanges as y, compileEidosFileFormulaSource as z };
6810
+ export { EIDOS_FILE_MIME_TYPE as $, eidosFileLookupElementType as A, compileEidosFileFormulaFields as B, normalizeEidosFileFilter as C, eidosFileFieldStoresJsonArray as D, removeEidosFileFilterField as E, EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES as F, EIDOS_FILE_EXTENSION as G, eidosFileFormulaReferences as H, EIDOS_FILE_FORMULA_FUNCTION_NAMES as I, EIDOS_FILE_FORMAT as J, EIDOS_FILE_FEATURES_TABLE as K, EIDOS_FILE_FORMULA_PROFILE as L, eidosFileLookupTargetDisplayType as M, eidosFileLookupTargetValueType as N, eidosFileLookupAggregateSupportsTarget as O, eidosFileLookupValueType as P, EIDOS_FILE_META_TABLE as Q, assertEidosFileFormulaProfile as R, isEidosFileFilterOperator as S, normalizeEidosFileSorts as T, rewriteEidosFileFormulaFieldReferences as U, compileEidosFileFormulaSource as V, EIDOS_FILE_APPLICATION_ID as W, EIDOS_FILE_FORMULA_FIELDS_TABLE as X, EIDOS_FILE_FORMAT_VERSION as Y, EIDOS_FILE_LOOKUP_FIELDS_TABLE as Z, assertEidosFileRowQuery as _, sqlValueToNative as _t, EIDOS_FILE_FORMAT_VERSION_TEXT as a, EIDOS_FILE_VIEWS_TABLE as at, eidosFileRowQueryPredicateColumns as b, incrementEidosFileRevision as c, eidosFileColumnStatLabel as ct, decodeEidosFileRelationDisplay as d, EidosAdapterError as dt, EIDOS_FILE_RELATION_FIELDS_TABLE as et, decodeEidosFileRelationIds as f, assertExactConnectionBindings as ft, parseNonNegativeInt64 as g, nativeToSqlValue as gt, cancellationPortFromSignal as h, exactConnectionBindingCount as ht, scanStableRowPages as i, EIDOS_FILE_TABLES_TABLE as it, eidosFileLookupStorageCodec as j, eidosFileLookupDisplayType as k, initializeEidosFileSchema as l, eidosFileColumnStatTypesForField as lt, MemoryByteSource as m, assertUnicodeString as mt, validateEidosFile as n, EIDOS_FILE_SCHEMA_VERSION as nt, EIDOS_FILE_SCHEMA_SQL as o, SQLITE_HEADER as ot, encodeEidosFileRelationIds as p, assertInt64Decimal as pt, EIDOS_FILE_FIELDS_TABLE as q, smallestDependencyCycle as r, EIDOS_FILE_SYSTEM_COLUMNS as rt, configureEidosFileConnection as s, hasEidosFileSqliteHeader as st, EidosFileRuntime as t, EIDOS_FILE_REQUIRED_TABLES as tt, setEidosFileMetadata as u, ConnectionPortEidosFileConnection as ut, compileEidosFileRowQuery as v, normalizeEidosFileRowQuery as w, eidosFileSortExpression as x, eidosFileRowQueryAffectedByFieldChanges as y, compileEidosFileFormula as z };
6220
6811
 
6221
- //# sourceMappingURL=runtime-Dt0bwaa5.mjs.map
6812
+ //# sourceMappingURL=runtime-BLZqiCnB.mjs.map