@devmm/puredocs-excel-formula 1.0.0 → 1.0.1

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.
package/dist/index.cjs CHANGED
@@ -31,15 +31,21 @@ var FormulaError = /* @__PURE__ */ ((FormulaError2) => {
31
31
  FormulaError2[FormulaError2["Spill"] = 9] = "Spill";
32
32
  return FormulaError2;
33
33
  })(FormulaError || {});
34
+ var TailCall = class {
35
+ constructor(lambda, args) {
36
+ this.lambda = lambda;
37
+ this.args = args;
38
+ }
39
+ };
34
40
  var _num, _obj;
35
41
  var _FormulaValue = class _FormulaValue {
36
- constructor(kind, num4 = 0, obj, errorCode = 0 /* None */) {
42
+ constructor(kind, num5 = 0, obj, errorCode = 0 /* None */) {
37
43
  /** Numeric payload (also used for boolean: 1=true, 0=false). */
38
44
  __privateAdd(this, _num);
39
- /** String or ArrayValue payload. */
45
+ /** String, ArrayValue, or LambdaLike payload. */
40
46
  __privateAdd(this, _obj);
41
47
  this.kind = kind;
42
- __privateSet(this, _num, num4);
48
+ __privateSet(this, _num, num5);
43
49
  __privateSet(this, _obj, obj);
44
50
  this.errorCode = errorCode;
45
51
  }
@@ -79,6 +85,9 @@ var _FormulaValue = class _FormulaValue {
79
85
  static array(a) {
80
86
  return new _FormulaValue("array", 0, a);
81
87
  }
88
+ static lambda(fn) {
89
+ return new _FormulaValue("lambda", 0, fn);
90
+ }
82
91
  // ── Type checks ──────────────────────────────────────────────────────────
83
92
  get isBlank() {
84
93
  return this.kind === "blank";
@@ -98,6 +107,9 @@ var _FormulaValue = class _FormulaValue {
98
107
  get isArray() {
99
108
  return this.kind === "array";
100
109
  }
110
+ get isLambda() {
111
+ return this.kind === "lambda";
112
+ }
101
113
  get isNumeric() {
102
114
  return this.kind === "number" || this.kind === "boolean" || this.kind === "blank";
103
115
  }
@@ -114,6 +126,9 @@ var _FormulaValue = class _FormulaValue {
114
126
  get arrayVal() {
115
127
  return __privateGet(this, _obj) ?? ArrayValue.empty;
116
128
  }
129
+ get lambdaVal() {
130
+ return __privateGet(this, _obj);
131
+ }
117
132
  // ── Coercion (Excel semantics, no exceptions) ─────────────────────────────
118
133
  coerceToNumber() {
119
134
  switch (this.kind) {
@@ -181,6 +196,8 @@ var _FormulaValue = class _FormulaValue {
181
196
  return "";
182
197
  case "error":
183
198
  return _FormulaValue.errorToString(this.errorCode);
199
+ case "lambda":
200
+ return _FormulaValue.errorToString(8 /* Calc */);
184
201
  default:
185
202
  return "";
186
203
  }
@@ -278,6 +295,8 @@ var _FormulaValue = class _FormulaValue {
278
295
  return _FormulaValue.errorToString(this.errorCode);
279
296
  case "array":
280
297
  return this.arrayVal.toObjectArray();
298
+ case "lambda":
299
+ return _FormulaValue.errorToString(8 /* Calc */);
281
300
  default:
282
301
  return null;
283
302
  }
@@ -426,10 +445,11 @@ var TokenType = /* @__PURE__ */ ((TokenType2) => {
426
445
  TokenType2[TokenType2["GreaterThanOrEqual"] = 21] = "GreaterThanOrEqual";
427
446
  TokenType2[TokenType2["SheetReference"] = 22] = "SheetReference";
428
447
  TokenType2[TokenType2["NamedRange"] = 23] = "NamedRange";
429
- TokenType2[TokenType2["Exclamation"] = 24] = "Exclamation";
430
- TokenType2[TokenType2["AtSign"] = 25] = "AtSign";
431
- TokenType2[TokenType2["ErrorLiteral"] = 26] = "ErrorLiteral";
432
- TokenType2[TokenType2["EOF"] = 27] = "EOF";
448
+ TokenType2[TokenType2["SpillReference"] = 24] = "SpillReference";
449
+ TokenType2[TokenType2["Exclamation"] = 25] = "Exclamation";
450
+ TokenType2[TokenType2["AtSign"] = 26] = "AtSign";
451
+ TokenType2[TokenType2["ErrorLiteral"] = 27] = "ErrorLiteral";
452
+ TokenType2[TokenType2["EOF"] = 28] = "EOF";
433
453
  return TokenType2;
434
454
  })(TokenType || {});
435
455
  function makeToken(type, value2, position) {
@@ -472,7 +492,7 @@ var FormulaLexer = class {
472
492
  const token = __privateMethod(this, _FormulaLexer_instances, readNextToken_fn).call(this);
473
493
  if (token) tokens.push(token);
474
494
  }
475
- tokens.push(makeToken(27 /* EOF */, "", __privateGet(this, _pos)));
495
+ tokens.push(makeToken(28 /* EOF */, "", __privateGet(this, _pos)));
476
496
  return tokens;
477
497
  }
478
498
  };
@@ -526,7 +546,7 @@ readErrorLiteral_fn = function() {
526
546
  if (!KNOWN_ERRORS.has(upper2)) {
527
547
  throw new FormulaException(`Unknown error literal "${raw}" at position ${start}.`);
528
548
  }
529
- return makeToken(26 /* ErrorLiteral */, upper2, start);
549
+ return makeToken(27 /* ErrorLiteral */, upper2, start);
530
550
  };
531
551
  readQuotedSheetRef_fn = function() {
532
552
  const start = __privateWrapper(this, _pos)._++;
@@ -605,7 +625,13 @@ readIdentifier_fn = function() {
605
625
  return makeToken(5 /* Function */, upper2, start);
606
626
  }
607
627
  const stripped = raw.replace(/\$/g, "");
608
- if (isCellRef(stripped)) return makeToken(3 /* CellReference */, stripped, start);
628
+ if (isCellRef(stripped)) {
629
+ if (__privateGet(this, _formula)[__privateGet(this, _pos)] === "#") {
630
+ __privateWrapper(this, _pos)._++;
631
+ return makeToken(24 /* SpillReference */, stripped, start);
632
+ }
633
+ return makeToken(3 /* CellReference */, stripped, start);
634
+ }
609
635
  return makeToken(23 /* NamedRange */, raw, start);
610
636
  };
611
637
  readCellRefChars_fn = function() {
@@ -648,9 +674,9 @@ readOperator_fn = function() {
648
674
  case "=":
649
675
  return makeToken(16 /* Equal */, "=", start);
650
676
  case "@":
651
- return makeToken(25 /* AtSign */, "@", start);
677
+ return makeToken(26 /* AtSign */, "@", start);
652
678
  case "!":
653
- return makeToken(24 /* Exclamation */, "!", start);
679
+ return makeToken(25 /* Exclamation */, "!", start);
654
680
  case "<":
655
681
  if (__privateGet(this, _formula)[__privateGet(this, _pos)] === ">") {
656
682
  __privateWrapper(this, _pos)._++;
@@ -687,6 +713,15 @@ function isCellRef(s) {
687
713
 
688
714
  // src/formula-node.ts
689
715
  var FormulaNode = class {
716
+ /**
717
+ * Evaluates this node in tail position. Returns a TailCall when the node's
718
+ * value is a call to a lambda in tail position (so the caller's trampoline can
719
+ * iterate without growing the stack); otherwise the final value. The default
720
+ * is a plain evaluate — only control-flow and call nodes override it.
721
+ */
722
+ evaluateTail(ctx) {
723
+ return this.evaluate(ctx);
724
+ }
690
725
  };
691
726
  var NumberNode = class extends FormulaNode {
692
727
  constructor(value2) {
@@ -778,6 +813,15 @@ var NamedRangeNode = class extends FormulaNode {
778
813
  return ctx.resolveNamedRange(this.name);
779
814
  }
780
815
  };
816
+ var SpillReferenceNode = class extends FormulaNode {
817
+ constructor(anchorRef) {
818
+ super();
819
+ this.anchorRef = anchorRef;
820
+ }
821
+ evaluate(ctx) {
822
+ return ctx.resolveSpillRange(this.anchorRef);
823
+ }
824
+ };
781
825
  var BinaryOperator = /* @__PURE__ */ ((BinaryOperator2) => {
782
826
  BinaryOperator2[BinaryOperator2["Add"] = 0] = "Add";
783
827
  BinaryOperator2[BinaryOperator2["Subtract"] = 1] = "Subtract";
@@ -901,10 +945,85 @@ var FunctionCallNode = class extends FormulaNode {
901
945
  evaluate(ctx) {
902
946
  return ctx.evaluateFunction(this.functionName, this.args);
903
947
  }
948
+ evaluateTail(ctx) {
949
+ const name = this.functionName;
950
+ const a = this.args;
951
+ switch (name) {
952
+ case "IF": {
953
+ const cond = a[0].evaluate(ctx);
954
+ if (cond.isError) return cond;
955
+ const b = cond.coerceToBool();
956
+ if (b.isError) return b;
957
+ if (b.booleanValue) return a[1].evaluateTail(ctx);
958
+ return a.length > 2 ? a[2].evaluateTail(ctx) : FormulaValue.false_;
959
+ }
960
+ case "IFS": {
961
+ for (let i = 0; i + 1 < a.length; i += 2) {
962
+ const cond = a[i].evaluate(ctx);
963
+ if (cond.isError) return cond;
964
+ const b = cond.coerceToBool();
965
+ if (b.isError) return b;
966
+ if (b.booleanValue) return a[i + 1].evaluateTail(ctx);
967
+ }
968
+ return FormulaValue.errorNA;
969
+ }
970
+ case "IFERROR": {
971
+ const v = a[0].evaluate(ctx);
972
+ return v.isError ? a[1].evaluateTail(ctx) : v;
973
+ }
974
+ case "IFNA": {
975
+ const v = a[0].evaluate(ctx);
976
+ return v.isError && v.errorCode === 7 /* NA */ ? a[1].evaluateTail(ctx) : v;
977
+ }
978
+ case "LET": {
979
+ if (a.length < 3 || a.length % 2 === 0) break;
980
+ const bindings = /* @__PURE__ */ new Map();
981
+ ctx.pushScope(bindings);
982
+ try {
983
+ for (let i = 0; i < a.length - 1; i += 2) {
984
+ const nn = a[i];
985
+ if (!(nn instanceof NamedRangeNode)) return FormulaValue.errorValue;
986
+ const val = a[i + 1].evaluate(ctx);
987
+ if (val.isError) return val;
988
+ bindings.set(nn.name.toUpperCase(), val);
989
+ }
990
+ return a[a.length - 1].evaluateTail(ctx);
991
+ } finally {
992
+ ctx.popScope();
993
+ }
994
+ }
995
+ }
996
+ if (!ctx.hasFunction(name)) {
997
+ const named = ctx.resolveNamedRange(name);
998
+ if (named.isLambda) {
999
+ return new TailCall(named.lambdaVal, a.map((arg2) => arg2.evaluate(ctx)));
1000
+ }
1001
+ }
1002
+ return this.evaluate(ctx);
1003
+ }
1004
+ };
1005
+ var CallNode = class extends FormulaNode {
1006
+ constructor(callee, args) {
1007
+ super();
1008
+ this.callee = callee;
1009
+ this.args = args;
1010
+ }
1011
+ evaluate(ctx) {
1012
+ const fn = this.callee.evaluate(ctx);
1013
+ if (fn.isError) return fn;
1014
+ if (!fn.isLambda) return FormulaValue.errorValue;
1015
+ return fn.lambdaVal.call(this.args.map((a) => a.evaluate(ctx)));
1016
+ }
1017
+ evaluateTail(ctx) {
1018
+ const fn = this.callee.evaluate(ctx);
1019
+ if (fn.isError) return fn;
1020
+ if (!fn.isLambda) return FormulaValue.errorValue;
1021
+ return new TailCall(fn.lambdaVal, this.args.map((a) => a.evaluate(ctx)));
1022
+ }
904
1023
  };
905
1024
 
906
1025
  // src/formula-parser.ts
907
- var _tokens, _pos2, _FormulaParser_instances, current_get, advance_fn, expect_fn, parseComparison_fn, parseConcatenation_fn, parseAddSub_fn, parseMulDiv_fn, parseUnary_fn, parsePower_fn, parsePercent_fn, parsePrimary_fn, parseFunction_fn;
1026
+ var _tokens, _pos2, _FormulaParser_instances, current_get, advance_fn, expect_fn, parseComparison_fn, parseConcatenation_fn, parseAddSub_fn, parseMulDiv_fn, parseUnary_fn, parsePower_fn, parsePercent_fn, parsePostfix_fn, parsePrimary_fn, parseFunction_fn, parseArgList_fn;
908
1027
  var FormulaParser = class {
909
1028
  constructor(tokens) {
910
1029
  __privateAdd(this, _FormulaParser_instances);
@@ -915,7 +1034,7 @@ var FormulaParser = class {
915
1034
  parse() {
916
1035
  __privateSet(this, _pos2, 0);
917
1036
  const node = __privateMethod(this, _FormulaParser_instances, parseComparison_fn).call(this);
918
- if (__privateGet(this, _FormulaParser_instances, current_get).type !== 27 /* EOF */) {
1037
+ if (__privateGet(this, _FormulaParser_instances, current_get).type !== 28 /* EOF */) {
919
1038
  throw new FormulaException(
920
1039
  `Unexpected token '${__privateGet(this, _FormulaParser_instances, current_get).value}' at position ${__privateGet(this, _FormulaParser_instances, current_get).position}.`
921
1040
  );
@@ -927,7 +1046,7 @@ _tokens = new WeakMap();
927
1046
  _pos2 = new WeakMap();
928
1047
  _FormulaParser_instances = new WeakSet();
929
1048
  current_get = function() {
930
- return __privateGet(this, _tokens)[__privateGet(this, _pos2)] ?? { type: 27 /* EOF */, value: "", position: -1 };
1049
+ return __privateGet(this, _tokens)[__privateGet(this, _pos2)] ?? { type: 28 /* EOF */, value: "", position: -1 };
931
1050
  };
932
1051
  advance_fn = function() {
933
1052
  const t = __privateGet(this, _FormulaParser_instances, current_get);
@@ -992,7 +1111,7 @@ parseUnary_fn = function() {
992
1111
  __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
993
1112
  return new UnaryOpNode(1 /* Plus */, __privateMethod(this, _FormulaParser_instances, parsePower_fn).call(this));
994
1113
  }
995
- if (__privateGet(this, _FormulaParser_instances, current_get).type === 25 /* AtSign */) {
1114
+ if (__privateGet(this, _FormulaParser_instances, current_get).type === 26 /* AtSign */) {
996
1115
  __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
997
1116
  return new ImplicitIntersectionNode(__privateMethod(this, _FormulaParser_instances, parsePower_fn).call(this));
998
1117
  }
@@ -1007,13 +1126,22 @@ parsePower_fn = function() {
1007
1126
  return left2;
1008
1127
  };
1009
1128
  parsePercent_fn = function() {
1010
- let node = __privateMethod(this, _FormulaParser_instances, parsePrimary_fn).call(this);
1129
+ let node = __privateMethod(this, _FormulaParser_instances, parsePostfix_fn).call(this);
1011
1130
  while (__privateGet(this, _FormulaParser_instances, current_get).type === 14 /* Percent */) {
1012
1131
  __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
1013
1132
  node = new UnaryOpNode(2 /* Percent */, node);
1014
1133
  }
1015
1134
  return node;
1016
1135
  };
1136
+ /** Handles postfix call syntax on an expression, e.g. LAMBDA(x,x+1)(5). */
1137
+ parsePostfix_fn = function() {
1138
+ let node = __privateMethod(this, _FormulaParser_instances, parsePrimary_fn).call(this);
1139
+ while (__privateGet(this, _FormulaParser_instances, current_get).type === 6 /* LeftParen */) {
1140
+ __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
1141
+ node = new CallNode(node, __privateMethod(this, _FormulaParser_instances, parseArgList_fn).call(this));
1142
+ }
1143
+ return node;
1144
+ };
1017
1145
  parsePrimary_fn = function() {
1018
1146
  const token = __privateGet(this, _FormulaParser_instances, current_get);
1019
1147
  switch (token.type) {
@@ -1029,7 +1157,7 @@ parsePrimary_fn = function() {
1029
1157
  case 2 /* Boolean */:
1030
1158
  __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
1031
1159
  return new BooleanNode(token.value === "TRUE");
1032
- case 26 /* ErrorLiteral */:
1160
+ case 27 /* ErrorLiteral */:
1033
1161
  __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
1034
1162
  return new ErrorNode(FormulaValue.error(FormulaValue.errorFromString(token.value)));
1035
1163
  case 3 /* CellReference */: {
@@ -1056,6 +1184,9 @@ parsePrimary_fn = function() {
1056
1184
  case 23 /* NamedRange */:
1057
1185
  __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
1058
1186
  return new NamedRangeNode(token.value);
1187
+ case 24 /* SpillReference */:
1188
+ __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
1189
+ return new SpillReferenceNode(token.value);
1059
1190
  case 5 /* Function */:
1060
1191
  return __privateMethod(this, _FormulaParser_instances, parseFunction_fn).call(this);
1061
1192
  case 6 /* LeftParen */: {
@@ -1073,6 +1204,10 @@ parsePrimary_fn = function() {
1073
1204
  parseFunction_fn = function() {
1074
1205
  const nameToken = __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
1075
1206
  __privateMethod(this, _FormulaParser_instances, expect_fn).call(this, 6 /* LeftParen */);
1207
+ return new FunctionCallNode(nameToken.value.toUpperCase(), __privateMethod(this, _FormulaParser_instances, parseArgList_fn).call(this));
1208
+ };
1209
+ /** Parses a comma-separated argument list up to and including the ')'. */
1210
+ parseArgList_fn = function() {
1076
1211
  const args = [];
1077
1212
  if (__privateGet(this, _FormulaParser_instances, current_get).type !== 7 /* RightParen */) {
1078
1213
  if (__privateGet(this, _FormulaParser_instances, current_get).type === 8 /* Comma */) {
@@ -1090,7 +1225,7 @@ parseFunction_fn = function() {
1090
1225
  }
1091
1226
  }
1092
1227
  __privateMethod(this, _FormulaParser_instances, expect_fn).call(this, 7 /* RightParen */);
1093
- return new FunctionCallNode(nameToken.value.toUpperCase(), args);
1228
+ return args;
1094
1229
  };
1095
1230
  function comparisonOp(type) {
1096
1231
  switch (type) {
@@ -1121,10 +1256,14 @@ function registerMath(r) {
1121
1256
  r.register("COUNTA", countA, 1);
1122
1257
  r.register("COUNTBLANK", countBlank, 1, 1);
1123
1258
  r.register("COUNTIF", countIf, 2, 2);
1259
+ r.register("COUNTIFS", countIfs, 2);
1124
1260
  r.register("SUMIF", sumIf, 2, 3);
1261
+ r.register("SUMIFS", sumIfs, 3);
1125
1262
  r.register("AVERAGEIF", averageIf, 2, 3);
1263
+ r.register("AVERAGEIFS", averageIfs, 3);
1126
1264
  r.register("PRODUCT", product, 1);
1127
1265
  r.register("SUMPRODUCT", sumProduct, 1);
1266
+ r.register("SUMSQ", sumSq, 1);
1128
1267
  r.register("ABS", abs, 1, 1);
1129
1268
  r.register("ROUND", round, 2, 2);
1130
1269
  r.register("ROUNDUP", roundUp, 2, 2);
@@ -1149,6 +1288,114 @@ function registerMath(r) {
1149
1288
  r.register("EXP", exp, 1, 1);
1150
1289
  r.register("FACT", fact, 1, 1);
1151
1290
  r.register("COMBIN", combin, 2, 2);
1291
+ r.register("SIN", unary(Math.sin), 1, 1);
1292
+ r.register("COS", unary(Math.cos), 1, 1);
1293
+ r.register("TAN", unary(Math.tan), 1, 1);
1294
+ r.register("ASIN", asin, 1, 1);
1295
+ r.register("ACOS", acos, 1, 1);
1296
+ r.register("ATAN", unary(Math.atan), 1, 1);
1297
+ r.register("ATAN2", atan2, 2, 2);
1298
+ r.register("SINH", unary(Math.sinh), 1, 1);
1299
+ r.register("COSH", unary(Math.cosh), 1, 1);
1300
+ r.register("TANH", unary(Math.tanh), 1, 1);
1301
+ r.register("DEGREES", unary((r2d) => r2d * 180 / Math.PI), 1, 1);
1302
+ r.register("RADIANS", unary((d) => d * Math.PI / 180), 1, 1);
1303
+ }
1304
+ function valueAt(v, i) {
1305
+ return v.isArray ? v.arrayVal.getFlat(i) : v;
1306
+ }
1307
+ function lengthOf(v) {
1308
+ return v.isArray ? v.arrayVal.length : 1;
1309
+ }
1310
+ function computeIfsMask(a, c, startIdx, len2) {
1311
+ const mask = new Uint8Array(len2).fill(1);
1312
+ for (let p = startIdx; p + 1 < a.length; p += 2) {
1313
+ const cr = a[p].evaluate(c);
1314
+ if (cr.isError) return { ok: false, error: cr };
1315
+ const crit = a[p + 1].evaluate(c);
1316
+ if (crit.isError) return { ok: false, error: crit };
1317
+ const critText = crit.asText();
1318
+ for (let i = 0; i < len2; i++) {
1319
+ if (!mask[i]) continue;
1320
+ if (!exports.FormulaHelper.matchesCriteria(valueAt(cr, i), critText)) mask[i] = 0;
1321
+ }
1322
+ }
1323
+ return { ok: true, mask };
1324
+ }
1325
+ function sumIfs(a, c) {
1326
+ if (a.length < 3 || a.length % 2 === 0) return FormulaValue.errorValue;
1327
+ const sumRange = a[0].evaluate(c);
1328
+ if (sumRange.isError) return sumRange;
1329
+ const len2 = lengthOf(sumRange);
1330
+ const m = computeIfsMask(a, c, 1, len2);
1331
+ if (!m.ok) return m.error;
1332
+ let total = 0;
1333
+ for (let i = 0; i < len2; i++) {
1334
+ if (!m.mask[i]) continue;
1335
+ const r = valueAt(sumRange, i).tryAsDouble();
1336
+ if (r.ok) total += r.value;
1337
+ }
1338
+ return FormulaValue.number(total);
1339
+ }
1340
+ function countIfs(a, c) {
1341
+ if (a.length < 2 || a.length % 2 !== 0) return FormulaValue.errorValue;
1342
+ const first = a[0].evaluate(c);
1343
+ if (first.isError) return first;
1344
+ const len2 = lengthOf(first);
1345
+ const m = computeIfsMask(a, c, 0, len2);
1346
+ if (!m.ok) return m.error;
1347
+ let n = 0;
1348
+ for (let i = 0; i < len2; i++) if (m.mask[i]) n++;
1349
+ return FormulaValue.number(n);
1350
+ }
1351
+ function averageIfs(a, c) {
1352
+ if (a.length < 3 || a.length % 2 === 0) return FormulaValue.errorValue;
1353
+ const avgRange = a[0].evaluate(c);
1354
+ if (avgRange.isError) return avgRange;
1355
+ const len2 = lengthOf(avgRange);
1356
+ const m = computeIfsMask(a, c, 1, len2);
1357
+ if (!m.ok) return m.error;
1358
+ let total = 0, cnt = 0;
1359
+ for (let i = 0; i < len2; i++) {
1360
+ if (!m.mask[i]) continue;
1361
+ const r = valueAt(avgRange, i).tryAsDouble();
1362
+ if (r.ok) {
1363
+ total += r.value;
1364
+ cnt++;
1365
+ }
1366
+ }
1367
+ return cnt === 0 ? FormulaValue.errorDiv0 : FormulaValue.number(total / cnt);
1368
+ }
1369
+ function sumSq(a, c) {
1370
+ const r = exports.FormulaHelper.collectNumbers(a, c);
1371
+ if (!r.ok) return r.error;
1372
+ return FormulaValue.number(r.values.reduce((s, n) => s + n * n, 0));
1373
+ }
1374
+ function unary(fn) {
1375
+ return (a, c) => {
1376
+ const r = exports.FormulaHelper.evalDouble(a[0], c);
1377
+ return r.ok ? FormulaValue.number(fn(r.value)) : r.error;
1378
+ };
1379
+ }
1380
+ function asin(a, c) {
1381
+ const r = exports.FormulaHelper.evalDouble(a[0], c);
1382
+ if (!r.ok) return r.error;
1383
+ if (r.value < -1 || r.value > 1) return FormulaValue.errorNum;
1384
+ return FormulaValue.number(Math.asin(r.value));
1385
+ }
1386
+ function acos(a, c) {
1387
+ const r = exports.FormulaHelper.evalDouble(a[0], c);
1388
+ if (!r.ok) return r.error;
1389
+ if (r.value < -1 || r.value > 1) return FormulaValue.errorNum;
1390
+ return FormulaValue.number(Math.acos(r.value));
1391
+ }
1392
+ function atan2(a, c) {
1393
+ const x = exports.FormulaHelper.evalDouble(a[0], c);
1394
+ if (!x.ok) return x.error;
1395
+ const y = exports.FormulaHelper.evalDouble(a[1], c);
1396
+ if (!y.ok) return y.error;
1397
+ if (x.value === 0 && y.value === 0) return FormulaValue.errorDiv0;
1398
+ return FormulaValue.number(Math.atan2(y.value, x.value));
1152
1399
  }
1153
1400
  function sum(a, c) {
1154
1401
  const r = exports.FormulaHelper.collectNumbers(a, c);
@@ -1267,7 +1514,7 @@ function product(a, c) {
1267
1514
  return FormulaValue.number(r.values.reduce((p, n) => p * n, 1));
1268
1515
  }
1269
1516
  function sumProduct(a, c) {
1270
- const arrays = a.map((arg) => arg.evaluate(c));
1517
+ const arrays = a.map((arg2) => arg2.evaluate(c));
1271
1518
  for (const v of arrays) if (v.isError) return v;
1272
1519
  const first = arrays[0];
1273
1520
  const len2 = first.isArray ? first.arrayVal.length : 1;
@@ -1468,6 +1715,8 @@ function registerText(r) {
1468
1715
  r.register("CHAR", char_, 1, 1);
1469
1716
  r.register("CODE", code, 1, 1);
1470
1717
  r.register("T", t_, 1, 1);
1718
+ r.register("TEXTBEFORE", textBefore, 2, 3);
1719
+ r.register("TEXTAFTER", textAfter, 2, 3);
1471
1720
  }
1472
1721
  function str(a, c, idx) {
1473
1722
  const r = exports.FormulaHelper.evalString(a[idx], c);
@@ -1596,8 +1845,8 @@ function replace(a, c) {
1596
1845
  }
1597
1846
  function concatenate(a, c) {
1598
1847
  let result = "";
1599
- for (const arg of a) {
1600
- const v = arg.evaluate(c);
1848
+ for (const arg2 of a) {
1849
+ const v = arg2.evaluate(c);
1601
1850
  if (v.isError) return v;
1602
1851
  result += v.asText();
1603
1852
  }
@@ -1724,6 +1973,45 @@ function t_(a, c) {
1724
1973
  const v = a[0].evaluate(c);
1725
1974
  return v.isText ? v : FormulaValue.emptyString;
1726
1975
  }
1976
+ function textBefore(a, c) {
1977
+ return textSplitAt(a, c, "before");
1978
+ }
1979
+ function textAfter(a, c) {
1980
+ return textSplitAt(a, c, "after");
1981
+ }
1982
+ function textSplitAt(a, c, mode2) {
1983
+ const s = str(a, c, 0);
1984
+ if (!s.ok) return s.e;
1985
+ const d = str(a, c, 1);
1986
+ if (!d.ok) return d.e;
1987
+ let instance = 1;
1988
+ if (a.length > 2) {
1989
+ const r = num(a, c, 2);
1990
+ if (!r.ok) return r.e;
1991
+ instance = Math.trunc(r.n);
1992
+ }
1993
+ if (instance === 0) return FormulaValue.errorValue;
1994
+ const text = s.s;
1995
+ const delim = d.s;
1996
+ if (delim === "") {
1997
+ return FormulaValue.text(mode2 === "before" ? "" : text);
1998
+ }
1999
+ const positions = [];
2000
+ let from = 0;
2001
+ for (; ; ) {
2002
+ const idx = text.indexOf(delim, from);
2003
+ if (idx === -1) break;
2004
+ positions.push(idx);
2005
+ from = idx + delim.length;
2006
+ }
2007
+ if (positions.length === 0) return FormulaValue.errorNA;
2008
+ const nth = instance > 0 ? instance - 1 : positions.length + instance;
2009
+ if (nth < 0 || nth >= positions.length) return FormulaValue.errorNA;
2010
+ const pos = positions[nth];
2011
+ return FormulaValue.text(
2012
+ mode2 === "before" ? text.slice(0, pos) : text.slice(pos + delim.length)
2013
+ );
2014
+ }
1727
2015
 
1728
2016
  // src/functions/logical-functions.ts
1729
2017
  function registerLogical(r) {
@@ -1748,8 +2036,8 @@ function if_(a, c) {
1748
2036
  }
1749
2037
  function and(a, c) {
1750
2038
  let hasValue = false;
1751
- for (const arg of a) {
1752
- const v = arg.evaluate(c);
2039
+ for (const arg2 of a) {
2040
+ const v = arg2.evaluate(c);
1753
2041
  if (v.isError) return v;
1754
2042
  if (v.isArray) {
1755
2043
  for (const item of v.arrayVal.values()) {
@@ -1775,8 +2063,8 @@ function and(a, c) {
1775
2063
  }
1776
2064
  function or(a, c) {
1777
2065
  let hasValue = false;
1778
- for (const arg of a) {
1779
- const v = arg.evaluate(c);
2066
+ for (const arg2 of a) {
2067
+ const v = arg2.evaluate(c);
1780
2068
  if (v.isError) return v;
1781
2069
  if (v.isArray) {
1782
2070
  for (const item of v.arrayVal.values()) {
@@ -1809,8 +2097,8 @@ function not(a, c) {
1809
2097
  }
1810
2098
  function xor(a, c) {
1811
2099
  let trueCount = 0;
1812
- for (const arg of a) {
1813
- const v = arg.evaluate(c);
2100
+ for (const arg2 of a) {
2101
+ const v = arg2.evaluate(c);
1814
2102
  if (v.isError) return v;
1815
2103
  const bv = v.coerceToBool();
1816
2104
  if (bv.isError) return bv;
@@ -2070,14 +2358,17 @@ function datedif(a, c) {
2070
2358
  function registerLookup(r) {
2071
2359
  r.register("VLOOKUP", vlookup, 3, 4);
2072
2360
  r.register("HLOOKUP", hlookup, 3, 4);
2361
+ r.register("LOOKUP", lookup, 2, 3);
2073
2362
  r.register("INDEX", index_, 2, 3);
2074
2363
  r.register("MATCH", match, 2, 3);
2075
2364
  r.register("CHOOSE", choose, 2);
2365
+ r.register("ADDRESS", address, 2, 5);
2076
2366
  r.register("ROW", row, 0, 1);
2077
2367
  r.register("COLUMN", column, 0, 1);
2078
2368
  r.register("ROWS", rows, 1, 1);
2079
2369
  r.register("COLUMNS", columns, 1, 1);
2080
2370
  r.register("OFFSET", offset, 3, 5, true);
2371
+ r.register("INDIRECT", indirect, 1, 2, true);
2081
2372
  }
2082
2373
  function num2(a, c, i) {
2083
2374
  const r = exports.FormulaHelper.evalDouble(a[i], c);
@@ -2206,6 +2497,86 @@ function choose(a, c) {
2206
2497
  if (idx < 1 || idx >= a.length) return FormulaValue.errorValue;
2207
2498
  return a[idx].evaluate(c);
2208
2499
  }
2500
+ function approxMatchFlat(arr, lookupVal) {
2501
+ let best = -1;
2502
+ for (let i = 0; i < arr.length; i++) {
2503
+ if (FormulaValue.compare(arr.getFlat(i), lookupVal) <= 0) best = i;
2504
+ else break;
2505
+ }
2506
+ return best;
2507
+ }
2508
+ function lookup(a, c) {
2509
+ const lookupVal = a[0].evaluate(c);
2510
+ if (lookupVal.isError) return lookupVal;
2511
+ const vecVal = a[1].evaluate(c);
2512
+ if (vecVal.isError) return vecVal;
2513
+ if (a.length > 2) {
2514
+ const resVal = a[2].evaluate(c);
2515
+ if (resVal.isError) return resVal;
2516
+ const vecArr = vecVal.isArray ? vecVal.arrayVal : ArrayValue.fromScalar(vecVal);
2517
+ const idx = approxMatchFlat(vecArr, lookupVal);
2518
+ if (idx < 0) return FormulaValue.errorNA;
2519
+ if (resVal.isArray) return resVal.arrayVal.getFlat(idx);
2520
+ return idx === 0 ? resVal : FormulaValue.errorNA;
2521
+ }
2522
+ if (!vecVal.isArray) {
2523
+ return FormulaValue.areEqual(vecVal, lookupVal) ? vecVal : FormulaValue.errorNA;
2524
+ }
2525
+ const arr = vecVal.arrayVal;
2526
+ if (arr.columns >= arr.rows) {
2527
+ let best2 = -1;
2528
+ for (let col = 0; col < arr.columns; col++) {
2529
+ if (FormulaValue.compare(arr.get(0, col), lookupVal) <= 0) best2 = col;
2530
+ else break;
2531
+ }
2532
+ return best2 >= 0 ? arr.get(arr.rows - 1, best2) : FormulaValue.errorNA;
2533
+ }
2534
+ let best = -1;
2535
+ for (let r = 0; r < arr.rows; r++) {
2536
+ if (FormulaValue.compare(arr.get(r, 0), lookupVal) <= 0) best = r;
2537
+ else break;
2538
+ }
2539
+ return best >= 0 ? arr.get(best, arr.columns - 1) : FormulaValue.errorNA;
2540
+ }
2541
+ function address(a, c) {
2542
+ const rn = num2(a, c, 0);
2543
+ if (!rn.ok) return rn.e;
2544
+ const cn = num2(a, c, 1);
2545
+ if (!cn.ok) return cn.e;
2546
+ const row2 = Math.round(rn.n);
2547
+ const col = Math.round(cn.n);
2548
+ if (row2 < 1 || col < 1) return FormulaValue.errorValue;
2549
+ let absNum = 1;
2550
+ if (a.length > 2) {
2551
+ const r = num2(a, c, 2);
2552
+ if (!r.ok) return r.e;
2553
+ absNum = Math.round(r.n);
2554
+ }
2555
+ if (absNum < 1 || absNum > 4) return FormulaValue.errorValue;
2556
+ let a1 = true;
2557
+ if (a.length > 3) {
2558
+ const v = a[3].evaluate(c);
2559
+ if (v.isError) return v;
2560
+ a1 = v.isBlank ? true : v.coerceToBool().booleanValue;
2561
+ }
2562
+ let sheetPrefix = "";
2563
+ if (a.length > 4) {
2564
+ const s = exports.FormulaHelper.evalString(a[4], c);
2565
+ if (!s.ok) return s.error;
2566
+ if (s.value !== "") sheetPrefix = `${s.value}!`;
2567
+ }
2568
+ const rowAbs = absNum === 1 || absNum === 2;
2569
+ const colAbs = absNum === 1 || absNum === 3;
2570
+ let ref;
2571
+ if (a1) {
2572
+ ref = `${colAbs ? "$" : ""}${puredocsExcel.columnLetter(col)}${rowAbs ? "$" : ""}${row2}`;
2573
+ } else {
2574
+ const rPart = rowAbs ? `R${row2}` : `R[${row2}]`;
2575
+ const cPart = colAbs ? `C${col}` : `C[${col}]`;
2576
+ ref = `${rPart}${cPart}`;
2577
+ }
2578
+ return FormulaValue.text(`${sheetPrefix}${ref}`);
2579
+ }
2209
2580
  function row(a, c) {
2210
2581
  if (a.length === 0) return FormulaValue.number(c.formulaRow || 1);
2211
2582
  const node = a[0];
@@ -2244,6 +2615,61 @@ function columns(a, c) {
2244
2615
  const v = a[0].evaluate(c);
2245
2616
  return v.isArray ? FormulaValue.number(v.arrayVal.columns) : FormulaValue.one;
2246
2617
  }
2618
+ function indirect(a, c) {
2619
+ const s = exports.FormulaHelper.evalString(a[0], c);
2620
+ if (!s.ok) return s.error;
2621
+ let a1 = true;
2622
+ if (a.length > 1) {
2623
+ const v = a[1].evaluate(c);
2624
+ if (v.isError) return v;
2625
+ a1 = v.isBlank ? true : v.coerceToBool().booleanValue;
2626
+ }
2627
+ const text = s.value.trim();
2628
+ if (text === "") return FormulaValue.errorRef;
2629
+ let sheet;
2630
+ let body = text;
2631
+ const bang = text.lastIndexOf("!");
2632
+ if (bang >= 0) {
2633
+ sheet = text.slice(0, bang).replace(/^'|'$/g, "");
2634
+ body = text.slice(bang + 1);
2635
+ }
2636
+ const colon = body.indexOf(":");
2637
+ try {
2638
+ if (colon >= 0) {
2639
+ const start = toA1(body.slice(0, colon), a1, c);
2640
+ const end = toA1(body.slice(colon + 1), a1, c);
2641
+ if (start === null || end === null) return FormulaValue.errorRef;
2642
+ return sheet !== void 0 ? c.getSheetRangeValues(sheet, start, end) : c.getRangeValues(start, end);
2643
+ }
2644
+ const cell = toA1(body, a1, c);
2645
+ if (cell === null) return FormulaValue.errorRef;
2646
+ return sheet !== void 0 ? c.getSheetCellValue(sheet, cell) : c.getCellValue(cell);
2647
+ } catch {
2648
+ return FormulaValue.errorRef;
2649
+ }
2650
+ }
2651
+ function toA1(ref, a1, c) {
2652
+ const r = ref.trim();
2653
+ if (a1) {
2654
+ try {
2655
+ const { row: row3, column: column2 } = puredocsExcel.parseCellRef(r);
2656
+ return puredocsExcel.cellRefFromRowCol(row3, column2);
2657
+ } catch {
2658
+ return null;
2659
+ }
2660
+ }
2661
+ const m = /^R(\[-?\d+\]|\d+)?C(\[-?\d+\]|\d+)?$/i.exec(r);
2662
+ if (!m) return null;
2663
+ const axis = (part, base) => {
2664
+ if (part === void 0) return base;
2665
+ if (part.startsWith("[")) return base + parseInt(part.slice(1, -1), 10);
2666
+ return parseInt(part, 10);
2667
+ };
2668
+ const row2 = axis(m[1], c.formulaRow || 1);
2669
+ const col = axis(m[2], c.formulaCol || 1);
2670
+ if (row2 === null || col === null || row2 < 1 || col < 1) return null;
2671
+ return puredocsExcel.cellRefFromRowCol(row2, col);
2672
+ }
2247
2673
  function offset(a, c) {
2248
2674
  const baseNode = a[0];
2249
2675
  let baseRef;
@@ -2300,8 +2726,8 @@ function registerStatistical(r) {
2300
2726
  }
2301
2727
  function variance(nums, population) {
2302
2728
  const mean = nums.reduce((s, n) => s + n, 0) / nums.length;
2303
- const sumSq = nums.reduce((s, n) => s + (n - mean) ** 2, 0);
2304
- return sumSq / (population ? nums.length : nums.length - 1);
2729
+ const sumSq2 = nums.reduce((s, n) => s + (n - mean) ** 2, 0);
2730
+ return sumSq2 / (population ? nums.length : nums.length - 1);
2305
2731
  }
2306
2732
  function numsFromArray(v) {
2307
2733
  if (v.isArray) {
@@ -2534,6 +2960,627 @@ function errorType(a, c) {
2534
2960
  return FormulaValue.number(map[v.errorCode] ?? 7);
2535
2961
  }
2536
2962
 
2963
+ // src/functions/finance-functions.ts
2964
+ function registerFinance(r) {
2965
+ r.register("PMT", pmt, 3, 5);
2966
+ r.register("FV", fv, 3, 5);
2967
+ r.register("PV", pv, 3, 5);
2968
+ r.register("NPV", npv, 2);
2969
+ r.register("IRR", irr, 1, 2);
2970
+ }
2971
+ function arg(a, c, idx, dflt) {
2972
+ if (idx >= a.length) return { ok: true, n: dflt };
2973
+ const r = exports.FormulaHelper.evalDouble(a[idx], c);
2974
+ return r.ok ? { ok: true, n: r.value } : { ok: false, e: r.error };
2975
+ }
2976
+ function pmt(a, c) {
2977
+ const rate = arg(a, c, 0, 0);
2978
+ if (!rate.ok) return rate.e;
2979
+ const nper = arg(a, c, 1, 0);
2980
+ if (!nper.ok) return nper.e;
2981
+ const pvv = arg(a, c, 2, 0);
2982
+ if (!pvv.ok) return pvv.e;
2983
+ const fvv = arg(a, c, 3, 0);
2984
+ if (!fvv.ok) return fvv.e;
2985
+ const type = arg(a, c, 4, 0);
2986
+ if (!type.ok) return type.e;
2987
+ const r = rate.n, n = nper.n, present = pvv.n, future = fvv.n, t = type.n;
2988
+ if (n === 0) return FormulaValue.errorNum;
2989
+ if (r === 0) return FormulaValue.number(-(present + future) / n);
2990
+ const pow = Math.pow(1 + r, n);
2991
+ let payment = (-future - present * pow) * r / (pow - 1);
2992
+ if (t === 1) payment /= 1 + r;
2993
+ return FormulaValue.number(payment);
2994
+ }
2995
+ function fv(a, c) {
2996
+ const rate = arg(a, c, 0, 0);
2997
+ if (!rate.ok) return rate.e;
2998
+ const nper = arg(a, c, 1, 0);
2999
+ if (!nper.ok) return nper.e;
3000
+ const pmtv = arg(a, c, 2, 0);
3001
+ if (!pmtv.ok) return pmtv.e;
3002
+ const pvv = arg(a, c, 3, 0);
3003
+ if (!pvv.ok) return pvv.e;
3004
+ const type = arg(a, c, 4, 0);
3005
+ if (!type.ok) return type.e;
3006
+ const r = rate.n, n = nper.n, payment = pmtv.n, present = pvv.n, t = type.n;
3007
+ if (r === 0) return FormulaValue.number(-(present + payment * n));
3008
+ const pow = Math.pow(1 + r, n);
3009
+ return FormulaValue.number(-(present * pow + payment * (1 + r * t) * (pow - 1) / r));
3010
+ }
3011
+ function pv(a, c) {
3012
+ const rate = arg(a, c, 0, 0);
3013
+ if (!rate.ok) return rate.e;
3014
+ const nper = arg(a, c, 1, 0);
3015
+ if (!nper.ok) return nper.e;
3016
+ const pmtv = arg(a, c, 2, 0);
3017
+ if (!pmtv.ok) return pmtv.e;
3018
+ const fvv = arg(a, c, 3, 0);
3019
+ if (!fvv.ok) return fvv.e;
3020
+ const type = arg(a, c, 4, 0);
3021
+ if (!type.ok) return type.e;
3022
+ const r = rate.n, n = nper.n, payment = pmtv.n, future = fvv.n, t = type.n;
3023
+ if (r === 0) return FormulaValue.number(-(future + payment * n));
3024
+ const pow = Math.pow(1 + r, n);
3025
+ return FormulaValue.number(-(future + payment * (1 + r * t) * (pow - 1) / r) / pow);
3026
+ }
3027
+ function npv(a, c) {
3028
+ const rate = exports.FormulaHelper.evalDouble(a[0], c);
3029
+ if (!rate.ok) return rate.error;
3030
+ if (rate.value === -1) return FormulaValue.errorDiv0;
3031
+ const flows = exports.FormulaHelper.collectNumbers(a.slice(1), c);
3032
+ if (!flows.ok) return flows.error;
3033
+ let total = 0;
3034
+ for (let i = 0; i < flows.values.length; i++) {
3035
+ total += flows.values[i] / Math.pow(1 + rate.value, i + 1);
3036
+ }
3037
+ return FormulaValue.number(total);
3038
+ }
3039
+ function irr(a, c) {
3040
+ const flowsRes = exports.FormulaHelper.collectNumbers([a[0]], c);
3041
+ if (!flowsRes.ok) return flowsRes.error;
3042
+ const flows = flowsRes.values;
3043
+ if (flows.length < 2) return FormulaValue.errorNum;
3044
+ let guess = 0.1;
3045
+ if (a.length > 1) {
3046
+ const g = exports.FormulaHelper.evalDouble(a[1], c);
3047
+ if (!g.ok) return g.error;
3048
+ guess = g.value;
3049
+ }
3050
+ const npvAt = (rate2) => {
3051
+ let sum2 = 0;
3052
+ for (let i = 0; i < flows.length; i++) sum2 += flows[i] / Math.pow(1 + rate2, i);
3053
+ return sum2;
3054
+ };
3055
+ let rate = guess;
3056
+ for (let iter = 0; iter < 100; iter++) {
3057
+ const f = npvAt(rate);
3058
+ if (Math.abs(f) < 1e-7) return FormulaValue.number(rate);
3059
+ const h = 1e-6;
3060
+ const deriv = (npvAt(rate + h) - f) / h;
3061
+ if (deriv === 0) break;
3062
+ const next = rate - f / deriv;
3063
+ if (!isFinite(next) || next <= -1) break;
3064
+ if (Math.abs(next - rate) < 1e-9) {
3065
+ rate = next;
3066
+ break;
3067
+ }
3068
+ rate = next;
3069
+ }
3070
+ if (Math.abs(npvAt(rate)) < 1e-6) return FormulaValue.number(rate);
3071
+ return FormulaValue.errorNum;
3072
+ }
3073
+
3074
+ // src/functions/meta-functions.ts
3075
+ var MAX_TAIL_ITERATIONS = 1e7;
3076
+ function registerMeta(r) {
3077
+ r.register("LET", let_, 3);
3078
+ r.register("LAMBDA", lambda_, 1);
3079
+ r.register("MAP", map_, 2);
3080
+ r.register("REDUCE", reduce_, 3, 3);
3081
+ r.register("SCAN", scan_, 3, 3);
3082
+ r.register("BYROW", byRow, 2, 2);
3083
+ r.register("BYCOL", byCol, 2, 2);
3084
+ }
3085
+ var asArray = (v) => v.isArray ? v.arrayVal : ArrayValue.fromScalar(v);
3086
+ function let_(a, c) {
3087
+ if (a.length < 3 || a.length % 2 === 0) return FormulaValue.errorValue;
3088
+ const bindings = /* @__PURE__ */ new Map();
3089
+ c.pushScope(bindings);
3090
+ try {
3091
+ for (let i = 0; i < a.length - 1; i += 2) {
3092
+ const nameNode = a[i];
3093
+ if (!(nameNode instanceof NamedRangeNode)) return FormulaValue.errorValue;
3094
+ const value2 = a[i + 1].evaluate(c);
3095
+ if (value2.isError) return value2;
3096
+ bindings.set(nameNode.name.toUpperCase(), value2);
3097
+ }
3098
+ return a[a.length - 1].evaluate(c);
3099
+ } finally {
3100
+ c.popScope();
3101
+ }
3102
+ }
3103
+ function lambda_(a, c) {
3104
+ const paramNodes = a.slice(0, -1);
3105
+ const body = a[a.length - 1];
3106
+ const params = [];
3107
+ for (const p of paramNodes) {
3108
+ if (!(p instanceof NamedRangeNode)) return FormulaValue.errorValue;
3109
+ params.push(p.name.toUpperCase());
3110
+ }
3111
+ const ctx = c;
3112
+ const lambda = {
3113
+ arity: params.length,
3114
+ // One tail-aware evaluation of the body: binds params, then evaluates in
3115
+ // tail mode so a self/other tail call surfaces as a TailCall.
3116
+ step(args) {
3117
+ const bindings = /* @__PURE__ */ new Map();
3118
+ params.forEach((p, i) => bindings.set(p, args[i] ?? FormulaValue.blank));
3119
+ ctx.pushScope(bindings);
3120
+ try {
3121
+ return body.evaluateTail(ctx);
3122
+ } finally {
3123
+ ctx.popScope();
3124
+ }
3125
+ },
3126
+ // Run to completion. Tail calls iterate here (O(1) stack); only non-tail
3127
+ // recursion re-enters call() and is bounded by the recursion guard.
3128
+ call(args) {
3129
+ const guard = ctx.recursionGuard;
3130
+ if (guard) {
3131
+ if (guard.depth >= guard.max) return FormulaValue.errorNum;
3132
+ guard.depth++;
3133
+ }
3134
+ try {
3135
+ let current = lambda;
3136
+ let currentArgs = args;
3137
+ for (let iter = 0; ; iter++) {
3138
+ if (iter > MAX_TAIL_ITERATIONS) return FormulaValue.errorNum;
3139
+ const r = current.step ? current.step(currentArgs) : current.call(currentArgs);
3140
+ if (r instanceof TailCall) {
3141
+ current = r.lambda;
3142
+ currentArgs = r.args;
3143
+ continue;
3144
+ }
3145
+ return r;
3146
+ }
3147
+ } finally {
3148
+ if (guard) guard.depth--;
3149
+ }
3150
+ }
3151
+ };
3152
+ return FormulaValue.lambda(lambda);
3153
+ }
3154
+ function lambdaArg(node, c) {
3155
+ const v = node.evaluate(c);
3156
+ if (v.isError) return { ok: false, e: v };
3157
+ if (!v.isLambda) return { ok: false, e: FormulaValue.errorValue };
3158
+ return { ok: true, fn: v.lambdaVal };
3159
+ }
3160
+ function map_(a, c) {
3161
+ const fn = lambdaArg(a[a.length - 1], c);
3162
+ if (!fn.ok) return fn.e;
3163
+ const arrays = a.slice(0, -1).map((n) => asArray(n.evaluate(c)));
3164
+ if (arrays.length === 0) return FormulaValue.errorValue;
3165
+ const rows2 = arrays[0].rows, cols = arrays[0].columns;
3166
+ const out = new ArrayValue(rows2, cols);
3167
+ for (let r = 0; r < rows2; r++) {
3168
+ for (let col = 0; col < cols; col++) {
3169
+ out.set(r, col, fn.fn.call(arrays.map((ar) => ar.get(r, col))));
3170
+ }
3171
+ }
3172
+ return FormulaValue.array(out);
3173
+ }
3174
+ function reduce_(a, c) {
3175
+ let acc = a[0].evaluate(c);
3176
+ if (acc.isError) return acc;
3177
+ const arr = asArray(a[1].evaluate(c));
3178
+ const fn = lambdaArg(a[2], c);
3179
+ if (!fn.ok) return fn.e;
3180
+ for (const v of arr.values()) {
3181
+ acc = fn.fn.call([acc, v]);
3182
+ if (acc.isError) return acc;
3183
+ }
3184
+ return acc;
3185
+ }
3186
+ function scan_(a, c) {
3187
+ let acc = a[0].evaluate(c);
3188
+ if (acc.isError) return acc;
3189
+ const arr = asArray(a[1].evaluate(c));
3190
+ const fn = lambdaArg(a[2], c);
3191
+ if (!fn.ok) return fn.e;
3192
+ const out = new ArrayValue(arr.rows, arr.columns);
3193
+ for (let r = 0; r < arr.rows; r++) {
3194
+ for (let col = 0; col < arr.columns; col++) {
3195
+ acc = fn.fn.call([acc, arr.get(r, col)]);
3196
+ out.set(r, col, acc);
3197
+ }
3198
+ }
3199
+ return FormulaValue.array(out);
3200
+ }
3201
+ function byRow(a, c) {
3202
+ const arr = asArray(a[0].evaluate(c));
3203
+ const fn = lambdaArg(a[1], c);
3204
+ if (!fn.ok) return fn.e;
3205
+ const out = new ArrayValue(arr.rows, 1);
3206
+ for (let r = 0; r < arr.rows; r++) {
3207
+ const row2 = new ArrayValue(1, arr.columns);
3208
+ for (let col = 0; col < arr.columns; col++) row2.set(0, col, arr.get(r, col));
3209
+ out.set(r, 0, fn.fn.call([FormulaValue.array(row2)]));
3210
+ }
3211
+ return FormulaValue.array(out);
3212
+ }
3213
+ function byCol(a, c) {
3214
+ const arr = asArray(a[0].evaluate(c));
3215
+ const fn = lambdaArg(a[1], c);
3216
+ if (!fn.ok) return fn.e;
3217
+ const out = new ArrayValue(1, arr.columns);
3218
+ for (let col = 0; col < arr.columns; col++) {
3219
+ const column2 = new ArrayValue(arr.rows, 1);
3220
+ for (let r = 0; r < arr.rows; r++) column2.set(r, 0, arr.get(r, col));
3221
+ out.set(0, col, fn.fn.call([FormulaValue.array(column2)]));
3222
+ }
3223
+ return FormulaValue.array(out);
3224
+ }
3225
+ function registerAggregate(r) {
3226
+ r.register("SUBTOTAL", subtotal, 2);
3227
+ r.register("AGGREGATE", aggregate, 3);
3228
+ }
3229
+ function collectValues(a, c, startIdx, opts) {
3230
+ const out = [];
3231
+ const ws = c.worksheet;
3232
+ for (let i = startIdx; i < a.length; i++) {
3233
+ const node = a[i];
3234
+ if (node instanceof RangeReferenceNode) {
3235
+ const b = c.getRangeBounds(node.startRef, node.endRef);
3236
+ for (let row2 = b.startRow; row2 <= b.endRow; row2++) {
3237
+ if (opts.excludeHidden && ws.isRowHidden?.(row2)) continue;
3238
+ for (let col = b.startCol; col <= b.endCol; col++) {
3239
+ const ref = puredocsExcel.cellRefFromRowCol(row2, col);
3240
+ if (opts.nestedPattern) {
3241
+ const f = ws.getCellFormula?.(ref);
3242
+ if (f && opts.nestedPattern.test(f)) continue;
3243
+ }
3244
+ const v = c.getCellValue(ref);
3245
+ if (v.isError) {
3246
+ if (opts.ignoreErrors) continue;
3247
+ return { ok: false, error: v };
3248
+ }
3249
+ out.push(v);
3250
+ }
3251
+ }
3252
+ } else {
3253
+ const v = node.evaluate(c);
3254
+ if (v.isError) {
3255
+ if (opts.ignoreErrors) continue;
3256
+ return { ok: false, error: v };
3257
+ }
3258
+ if (v.isArray) {
3259
+ for (const item of v.arrayVal.values()) {
3260
+ if (item.isError) {
3261
+ if (opts.ignoreErrors) continue;
3262
+ return { ok: false, error: item };
3263
+ }
3264
+ out.push(item);
3265
+ }
3266
+ } else {
3267
+ out.push(v);
3268
+ }
3269
+ }
3270
+ }
3271
+ return { ok: true, values: out };
3272
+ }
3273
+ function applyAggregate(fn, values, extra) {
3274
+ const nums = [];
3275
+ let countA2 = 0;
3276
+ for (const v of values) {
3277
+ if (!v.isBlank) countA2++;
3278
+ const r = v.tryAsDouble();
3279
+ if (r.ok && !v.isText && !v.isBlank) nums.push(r.value);
3280
+ }
3281
+ const sum2 = () => nums.reduce((s, n) => s + n, 0);
3282
+ const avg = () => nums.length ? sum2() / nums.length : NaN;
3283
+ const variance2 = (sample) => {
3284
+ const n = nums.length;
3285
+ if (sample ? n < 2 : n < 1) return NaN;
3286
+ const m = avg();
3287
+ const ss = nums.reduce((s, x) => s + (x - m) ** 2, 0);
3288
+ return ss / (sample ? n - 1 : n);
3289
+ };
3290
+ const sorted = () => [...nums].sort((x, y) => x - y);
3291
+ switch (fn) {
3292
+ case 1:
3293
+ return isNaN(avg()) ? FormulaValue.errorDiv0 : FormulaValue.number(avg());
3294
+ case 2:
3295
+ return FormulaValue.number(nums.length);
3296
+ // COUNT
3297
+ case 3:
3298
+ return FormulaValue.number(countA2);
3299
+ // COUNTA
3300
+ case 4:
3301
+ return nums.length ? FormulaValue.number(Math.max(...nums)) : FormulaValue.zero;
3302
+ case 5:
3303
+ return nums.length ? FormulaValue.number(Math.min(...nums)) : FormulaValue.zero;
3304
+ case 6:
3305
+ return FormulaValue.number(nums.reduce((p, n) => p * n, 1));
3306
+ // PRODUCT
3307
+ case 7: {
3308
+ const v = variance2(true);
3309
+ return isNaN(v) ? FormulaValue.errorDiv0 : FormulaValue.number(Math.sqrt(v));
3310
+ }
3311
+ // STDEV.S
3312
+ case 8: {
3313
+ const v = variance2(false);
3314
+ return isNaN(v) ? FormulaValue.errorDiv0 : FormulaValue.number(Math.sqrt(v));
3315
+ }
3316
+ // STDEV.P
3317
+ case 9:
3318
+ return FormulaValue.number(sum2());
3319
+ // SUM
3320
+ case 10: {
3321
+ const v = variance2(true);
3322
+ return isNaN(v) ? FormulaValue.errorDiv0 : FormulaValue.number(v);
3323
+ }
3324
+ // VAR.S
3325
+ case 11: {
3326
+ const v = variance2(false);
3327
+ return isNaN(v) ? FormulaValue.errorDiv0 : FormulaValue.number(v);
3328
+ }
3329
+ // VAR.P
3330
+ // AGGREGATE-only selectors:
3331
+ case 12: {
3332
+ const s = sorted();
3333
+ const m = s.length;
3334
+ if (!m) return FormulaValue.errorNum;
3335
+ const mid2 = Math.floor(m / 2);
3336
+ return FormulaValue.number(m % 2 ? s[mid2] : (s[mid2 - 1] + s[mid2]) / 2);
3337
+ }
3338
+ // MEDIAN
3339
+ case 14: {
3340
+ const s = sorted();
3341
+ const k = Math.round(extra ?? 0);
3342
+ return k >= 1 && k <= s.length ? FormulaValue.number(s[s.length - k]) : FormulaValue.errorNum;
3343
+ }
3344
+ case 15: {
3345
+ const s = sorted();
3346
+ const k = Math.round(extra ?? 0);
3347
+ return k >= 1 && k <= s.length ? FormulaValue.number(s[k - 1]) : FormulaValue.errorNum;
3348
+ }
3349
+ default:
3350
+ return FormulaValue.errorValue;
3351
+ }
3352
+ }
3353
+ function subtotal(a, c) {
3354
+ const fnVal = a[0].evaluate(c);
3355
+ if (fnVal.isError) return fnVal;
3356
+ const raw = fnVal.tryAsDouble();
3357
+ if (!raw.ok) return FormulaValue.errorValue;
3358
+ const code2 = Math.round(raw.value);
3359
+ const excludeHidden = code2 >= 101 && code2 <= 111;
3360
+ const fn = excludeHidden ? code2 - 100 : code2;
3361
+ if (fn < 1 || fn > 11) return FormulaValue.errorValue;
3362
+ const collected = collectValues(a, c, 1, {
3363
+ excludeHidden,
3364
+ nestedPattern: /^\s*SUBTOTAL\s*\(/i,
3365
+ ignoreErrors: false
3366
+ });
3367
+ if (!collected.ok) return collected.error;
3368
+ return applyAggregate(fn, collected.values);
3369
+ }
3370
+ function aggregate(a, c) {
3371
+ const fnVal = a[0].evaluate(c);
3372
+ if (fnVal.isError) return fnVal;
3373
+ const optVal = a[1].evaluate(c);
3374
+ if (optVal.isError) return optVal;
3375
+ const fnR = fnVal.tryAsDouble();
3376
+ const optR = optVal.tryAsDouble();
3377
+ if (!fnR.ok || !optR.ok) return FormulaValue.errorValue;
3378
+ const fn = Math.round(fnR.value);
3379
+ const option = Math.round(optR.value);
3380
+ if (fn < 1 || fn > 19) return FormulaValue.errorValue;
3381
+ const excludeHidden = option === 1 || option === 3 || option === 5 || option === 7;
3382
+ const ignoreErrors = option === 2 || option === 3 || option === 6 || option === 7;
3383
+ const ignoreNested = option <= 3 || option === 5 || option === 7;
3384
+ let extra;
3385
+ let endIdx = a.length;
3386
+ if (fn === 14 || fn === 15) {
3387
+ const kVal = a[a.length - 1].evaluate(c);
3388
+ const kR = kVal.tryAsDouble();
3389
+ if (!kR.ok) return FormulaValue.errorValue;
3390
+ extra = kR.value;
3391
+ endIdx = a.length - 1;
3392
+ }
3393
+ const collected = collectValues(a.slice(0, endIdx), c, 2, {
3394
+ excludeHidden,
3395
+ nestedPattern: ignoreNested ? /^\s*(SUBTOTAL|AGGREGATE)\s*\(/i : null,
3396
+ ignoreErrors
3397
+ });
3398
+ if (!collected.ok) return collected.error;
3399
+ return applyAggregate(fn, collected.values, extra);
3400
+ }
3401
+
3402
+ // src/functions/array-functions.ts
3403
+ function registerArray(r) {
3404
+ r.register("TRANSPOSE", transpose, 1, 1);
3405
+ r.register("SEQUENCE", sequence, 1, 4);
3406
+ r.register("UNIQUE", unique, 1, 3);
3407
+ r.register("SORT", sort, 1, 4);
3408
+ r.register("FILTER", filter, 2, 3);
3409
+ r.register("MMULT", mmult, 2, 2);
3410
+ r.register("TEXTSPLIT", textSplit, 2, 6);
3411
+ }
3412
+ var asArray2 = (v) => v.isArray ? v.arrayVal : ArrayValue.fromScalar(v);
3413
+ function fromRows(rows2) {
3414
+ const nr = rows2.length;
3415
+ const nc = nr > 0 ? rows2[0].length : 0;
3416
+ const arr = new ArrayValue(nr, nc);
3417
+ for (let r = 0; r < nr; r++) for (let c = 0; c < nc; c++) arr.set(r, c, rows2[r][c]);
3418
+ return FormulaValue.array(arr);
3419
+ }
3420
+ function toRows(arr) {
3421
+ const rows2 = [];
3422
+ for (let r = 0; r < arr.rows; r++) {
3423
+ const row2 = [];
3424
+ for (let c = 0; c < arr.columns; c++) row2.push(arr.get(r, c));
3425
+ rows2.push(row2);
3426
+ }
3427
+ return rows2;
3428
+ }
3429
+ var num4 = (a, c, i, dflt) => {
3430
+ if (i >= a.length) return { ok: true, n: dflt };
3431
+ const r = exports.FormulaHelper.evalDouble(a[i], c);
3432
+ return r.ok ? { ok: true, n: r.value } : { ok: false, e: r.error };
3433
+ };
3434
+ function transpose(a, c) {
3435
+ const v = a[0].evaluate(c);
3436
+ if (v.isError) return v;
3437
+ return FormulaValue.array(asArray2(v).transpose());
3438
+ }
3439
+ function sequence(a, c) {
3440
+ const rows2 = num4(a, c, 0, 1);
3441
+ if (!rows2.ok) return rows2.e;
3442
+ const cols = num4(a, c, 1, 1);
3443
+ if (!cols.ok) return cols.e;
3444
+ const start = num4(a, c, 2, 1);
3445
+ if (!start.ok) return start.e;
3446
+ const step = num4(a, c, 3, 1);
3447
+ if (!step.ok) return step.e;
3448
+ const R = Math.trunc(rows2.n), C = Math.trunc(cols.n);
3449
+ if (R < 1 || C < 1) return FormulaValue.errorValue;
3450
+ const arr = new ArrayValue(R, C);
3451
+ for (let r = 0; r < R; r++) {
3452
+ for (let col = 0; col < C; col++) {
3453
+ arr.set(r, col, FormulaValue.number(start.n + (r * C + col) * step.n));
3454
+ }
3455
+ }
3456
+ return FormulaValue.array(arr);
3457
+ }
3458
+ function rowsEqual(x, y) {
3459
+ if (x.length !== y.length) return false;
3460
+ for (let i = 0; i < x.length; i++) if (!FormulaValue.areEqual(x[i], y[i])) return false;
3461
+ return true;
3462
+ }
3463
+ function unique(a, c) {
3464
+ const v = a[0].evaluate(c);
3465
+ if (v.isError) return v;
3466
+ const byCol2 = a.length > 1 ? a[1].evaluate(c).coerceToBool().booleanValue : false;
3467
+ const exactlyOnce = a.length > 2 ? a[2].evaluate(c).coerceToBool().booleanValue : false;
3468
+ let rows2 = toRows(byCol2 ? asArray2(v).transpose() : asArray2(v));
3469
+ const counts = rows2.map((r) => rows2.filter((o) => rowsEqual(o, r)).length);
3470
+ const seen = [];
3471
+ const result = [];
3472
+ rows2.forEach((r, i) => {
3473
+ if (seen.some((o) => rowsEqual(o, r))) return;
3474
+ seen.push(r);
3475
+ if (exactlyOnce && counts[i] > 1) return;
3476
+ result.push(r);
3477
+ });
3478
+ if (result.length === 0) return FormulaValue.error(8 /* Calc */);
3479
+ const out = fromRows(result);
3480
+ return byCol2 ? FormulaValue.array(out.arrayVal.transpose()) : out;
3481
+ }
3482
+ function sort(a, c) {
3483
+ const v = a[0].evaluate(c);
3484
+ if (v.isError) return v;
3485
+ const sortIndex = num4(a, c, 1, 1);
3486
+ if (!sortIndex.ok) return sortIndex.e;
3487
+ const sortOrder = num4(a, c, 2, 1);
3488
+ if (!sortOrder.ok) return sortOrder.e;
3489
+ const byCol2 = a.length > 3 ? a[3].evaluate(c).coerceToBool().booleanValue : false;
3490
+ const base = byCol2 ? asArray2(v).transpose() : asArray2(v);
3491
+ const rows2 = toRows(base);
3492
+ const idx = Math.trunc(sortIndex.n) - 1;
3493
+ const dir = sortOrder.n < 0 ? -1 : 1;
3494
+ if (rows2.length > 0 && (idx < 0 || idx >= rows2[0].length)) return FormulaValue.errorValue;
3495
+ const sorted = rows2.map((r, i) => ({ r, i })).sort((x, y) => {
3496
+ const cmp = FormulaValue.compare(x.r[idx], y.r[idx]) * dir;
3497
+ return cmp !== 0 ? cmp : x.i - y.i;
3498
+ }).map((o) => o.r);
3499
+ const out = fromRows(sorted);
3500
+ return byCol2 ? FormulaValue.array(out.arrayVal.transpose()) : out;
3501
+ }
3502
+ function filter(a, c) {
3503
+ const v = a[0].evaluate(c);
3504
+ if (v.isError) return v;
3505
+ const inc = a[1].evaluate(c);
3506
+ if (inc.isError) return inc;
3507
+ const arr = asArray2(v);
3508
+ const incArr = asArray2(inc);
3509
+ const perRow = incArr.rows === arr.rows && incArr.columns === 1;
3510
+ const perCol = incArr.columns === arr.columns && incArr.rows === 1;
3511
+ if (!perRow && !perCol) return FormulaValue.errorValue;
3512
+ const keptRows = [];
3513
+ if (perRow) {
3514
+ for (let r = 0; r < arr.rows; r++) {
3515
+ if (!incArr.get(r, 0).coerceToBool().booleanValue) continue;
3516
+ const row2 = [];
3517
+ for (let col = 0; col < arr.columns; col++) row2.push(arr.get(r, col));
3518
+ keptRows.push(row2);
3519
+ }
3520
+ } else {
3521
+ const keepCols = [];
3522
+ for (let col = 0; col < arr.columns; col++) {
3523
+ if (incArr.get(0, col).coerceToBool().booleanValue) keepCols.push(col);
3524
+ }
3525
+ for (let r = 0; r < arr.rows; r++) {
3526
+ keptRows.push(keepCols.map((col) => arr.get(r, col)));
3527
+ }
3528
+ if (keepCols.length === 0) keptRows.length = 0;
3529
+ }
3530
+ if (keptRows.length === 0 || keptRows[0] && keptRows[0].length === 0) {
3531
+ return a.length > 2 ? a[2].evaluate(c) : FormulaValue.error(8 /* Calc */);
3532
+ }
3533
+ return fromRows(keptRows);
3534
+ }
3535
+ function mmult(a, c) {
3536
+ const av = a[0].evaluate(c);
3537
+ if (av.isError) return av;
3538
+ const bv = a[1].evaluate(c);
3539
+ if (bv.isError) return bv;
3540
+ const A = asArray2(av), B = asArray2(bv);
3541
+ if (A.columns !== B.rows) return FormulaValue.errorValue;
3542
+ const out = new ArrayValue(A.rows, B.columns);
3543
+ for (let i = 0; i < A.rows; i++) {
3544
+ for (let j = 0; j < B.columns; j++) {
3545
+ let sum2 = 0;
3546
+ for (let k = 0; k < A.columns; k++) {
3547
+ const x = A.get(i, k).tryAsDouble();
3548
+ const y = B.get(k, j).tryAsDouble();
3549
+ if (!x.ok || !y.ok) return FormulaValue.errorValue;
3550
+ sum2 += x.value * y.value;
3551
+ }
3552
+ out.set(i, j, FormulaValue.number(sum2));
3553
+ }
3554
+ }
3555
+ return FormulaValue.array(out);
3556
+ }
3557
+ function textSplit(a, c) {
3558
+ const t = exports.FormulaHelper.evalString(a[0], c);
3559
+ if (!t.ok) return t.error;
3560
+ const colD = exports.FormulaHelper.evalString(a[1], c);
3561
+ if (!colD.ok) return colD.error;
3562
+ let rowD = "";
3563
+ if (a.length > 2) {
3564
+ const rd = a[2].evaluate(c);
3565
+ if (rd.isError) return rd;
3566
+ if (!rd.isBlank) {
3567
+ const r = exports.FormulaHelper.evalString(a[2], c);
3568
+ if (!r.ok) return r.error;
3569
+ rowD = r.value;
3570
+ }
3571
+ }
3572
+ const split = (s, d) => d === "" ? [s] : s.split(d);
3573
+ const lines = rowD ? split(t.value, rowD) : [t.value];
3574
+ const grid = lines.map((line) => split(line, colD.value));
3575
+ const width = grid.reduce((m, r) => Math.max(m, r.length), 0);
3576
+ const rows2 = grid.map((r) => {
3577
+ const row2 = [];
3578
+ for (let i = 0; i < width; i++) row2.push(FormulaValue.text(r[i] ?? ""));
3579
+ return row2;
3580
+ });
3581
+ return fromRows(rows2);
3582
+ }
3583
+
2537
3584
  // src/function-registry.ts
2538
3585
  var _default, _functions, _FunctionRegistry_instances, registerBuiltIns_fn;
2539
3586
  var _FunctionRegistry = class _FunctionRegistry {
@@ -2592,6 +3639,10 @@ registerBuiltIns_fn = function() {
2592
3639
  registerLookup(this);
2593
3640
  registerStatistical(this);
2594
3641
  registerInfo(this);
3642
+ registerFinance(this);
3643
+ registerMeta(this);
3644
+ registerAggregate(this);
3645
+ registerArray(this);
2595
3646
  };
2596
3647
  __privateAdd(_FunctionRegistry, _default);
2597
3648
  var FunctionRegistry = _FunctionRegistry;
@@ -2613,8 +3664,8 @@ exports.FormulaHelper = void 0;
2613
3664
  FormulaHelper2.evalString = evalString;
2614
3665
  function collectNumbers(args, ctx) {
2615
3666
  const nums = [];
2616
- for (const arg of args) {
2617
- const v = arg.evaluate(ctx);
3667
+ for (const arg2 of args) {
3668
+ const v = arg2.evaluate(ctx);
2618
3669
  if (v.isError) return { ok: false, error: v };
2619
3670
  if (v.isArray) {
2620
3671
  for (const item of v.arrayVal.values()) {
@@ -2634,8 +3685,8 @@ exports.FormulaHelper = void 0;
2634
3685
  FormulaHelper2.collectNumbers = collectNumbers;
2635
3686
  function flattenArgs(args, ctx) {
2636
3687
  const result = [];
2637
- for (const arg of args) {
2638
- const v = arg.evaluate(ctx);
3688
+ for (const arg2 of args) {
3689
+ const v = arg2.evaluate(ctx);
2639
3690
  if (v.isArray) {
2640
3691
  for (const item of v.arrayVal.values()) result.push(item);
2641
3692
  } else {
@@ -2673,9 +3724,9 @@ exports.FormulaHelper = void 0;
2673
3724
  const pattern = wildcardToRegex(criteria);
2674
3725
  return pattern.test(value2.asText());
2675
3726
  }
2676
- const num4 = parseFloat(criteria);
2677
- if (!isNaN(num4)) {
2678
- return FormulaValue.areEqual(value2, FormulaValue.number(num4));
3727
+ const num5 = parseFloat(criteria);
3728
+ if (!isNaN(num5)) {
3729
+ return FormulaValue.areEqual(value2, FormulaValue.number(num5));
2679
3730
  }
2680
3731
  return value2.asText().toUpperCase() === criteria.toUpperCase();
2681
3732
  }
@@ -2687,18 +3738,33 @@ exports.FormulaHelper = void 0;
2687
3738
  })(exports.FormulaHelper || (exports.FormulaHelper = {}));
2688
3739
 
2689
3740
  // src/formula-context.ts
2690
- var _sheet, _functions2, _evaluating;
3741
+ var _sheet, _functions2, _evaluating, _scopes, _FormulaContext_instances, lookupScope_fn;
2691
3742
  var _FormulaContext = class _FormulaContext {
2692
3743
  constructor(sheet, formulaRow = 0, formulaCol = 0, evaluating, registry) {
3744
+ __privateAdd(this, _FormulaContext_instances);
2693
3745
  __privateAdd(this, _sheet);
2694
3746
  __privateAdd(this, _functions2);
2695
3747
  __privateAdd(this, _evaluating);
3748
+ /**
3749
+ * Lexical scope stack for LET/LAMBDA local names. Each frame maps an
3750
+ * upper-cased local name to its value. Names resolve innermost-first and take
3751
+ * precedence over workbook defined names.
3752
+ */
3753
+ __privateAdd(this, _scopes, []);
2696
3754
  __privateSet(this, _sheet, sheet);
2697
3755
  this.formulaRow = formulaRow;
2698
3756
  this.formulaCol = formulaCol;
2699
3757
  __privateSet(this, _evaluating, evaluating ?? /* @__PURE__ */ new Set());
2700
3758
  __privateSet(this, _functions2, registry ?? FunctionRegistry.default);
2701
3759
  }
3760
+ /** Pushes a new binding frame (used by LET/LAMBDA). */
3761
+ pushScope(bindings) {
3762
+ __privateGet(this, _scopes).push(bindings);
3763
+ }
3764
+ /** Pops the innermost binding frame. */
3765
+ popScope() {
3766
+ __privateGet(this, _scopes).pop();
3767
+ }
2702
3768
  get worksheet() {
2703
3769
  return __privateGet(this, _sheet);
2704
3770
  }
@@ -2750,8 +3816,21 @@ var _FormulaContext = class _FormulaContext {
2750
3816
  return FormulaValue.errorRef;
2751
3817
  }
2752
3818
  }
2753
- resolveNamedRange(_name) {
2754
- return FormulaValue.errorName;
3819
+ resolveNamedRange(name) {
3820
+ const scoped = __privateMethod(this, _FormulaContext_instances, lookupScope_fn).call(this, name);
3821
+ if (scoped !== void 0) return scoped;
3822
+ return this.nameResolver ? this.nameResolver(name) : FormulaValue.errorName;
3823
+ }
3824
+ /**
3825
+ * Resolves a spill-range reference (A1#) to the array spilling from the anchor
3826
+ * cell. Requires the worksheet to expose getSpillRange; otherwise #REF!.
3827
+ */
3828
+ resolveSpillRange(anchorRef) {
3829
+ const spillRef = __privateGet(this, _sheet).getSpillRange?.(anchorRef);
3830
+ if (!spillRef) return FormulaValue.errorRef;
3831
+ const colon = spillRef.indexOf(":");
3832
+ if (colon < 0) return this.getCellValue(spillRef);
3833
+ return this.getRangeValues(spillRef.slice(0, colon), spillRef.slice(colon + 1));
2755
3834
  }
2756
3835
  getRangeBounds(startRef, endRef) {
2757
3836
  const s = puredocsExcel.parseCellRef(startRef);
@@ -2759,13 +3838,34 @@ var _FormulaContext = class _FormulaContext {
2759
3838
  return { startRow: s.row, startCol: s.column, endRow: e.row, endCol: e.column };
2760
3839
  }
2761
3840
  // ── Function dispatch ─────────────────────────────────────────────────────
3841
+ /** True if a built-in function with this name is registered. */
3842
+ hasFunction(name) {
3843
+ return __privateGet(this, _functions2).has(name);
3844
+ }
2762
3845
  evaluateFunction(name, args) {
3846
+ if (!__privateGet(this, _functions2).has(name)) {
3847
+ const named = this.resolveNamedRange(name);
3848
+ if (named.isLambda) {
3849
+ return named.lambdaVal.call(args.map((a) => a.evaluate(this)));
3850
+ }
3851
+ }
2763
3852
  return __privateGet(this, _functions2).execute(name, args, this);
2764
3853
  }
2765
3854
  };
2766
3855
  _sheet = new WeakMap();
2767
3856
  _functions2 = new WeakMap();
2768
3857
  _evaluating = new WeakMap();
3858
+ _scopes = new WeakMap();
3859
+ _FormulaContext_instances = new WeakSet();
3860
+ lookupScope_fn = function(name) {
3861
+ if (__privateGet(this, _scopes).length === 0) return void 0;
3862
+ const key = name.toUpperCase();
3863
+ for (let i = __privateGet(this, _scopes).length - 1; i >= 0; i--) {
3864
+ const v = __privateGet(this, _scopes)[i].get(key);
3865
+ if (v !== void 0) return v;
3866
+ }
3867
+ return void 0;
3868
+ };
2769
3869
  var FormulaContext = _FormulaContext;
2770
3870
 
2771
3871
  // src/lru-cache.ts
@@ -2872,16 +3972,63 @@ function parseFormula(formula) {
2872
3972
  astCache.set(stripped, ast);
2873
3973
  return ast;
2874
3974
  }
3975
+ var DEFAULT_LAMBDA_DEPTH = 1024;
3976
+ function buildContext(sheet, opts) {
3977
+ const evaluating = opts.evaluating ?? /* @__PURE__ */ new Set();
3978
+ const ctx = new FormulaContext(
3979
+ sheet,
3980
+ opts.formulaRow ?? 0,
3981
+ opts.formulaCol ?? 0,
3982
+ evaluating
3983
+ );
3984
+ ctx.recursionGuard = opts.recursionGuard ?? { depth: 0, max: DEFAULT_LAMBDA_DEPTH };
3985
+ const wb = opts.workbook;
3986
+ if (wb) {
3987
+ ctx.workbook = wb;
3988
+ if (typeof wb.getDefinedName === "function") {
3989
+ const resolving = opts.resolvingNames ?? /* @__PURE__ */ new Set();
3990
+ const resolved = opts.resolvedNames ?? /* @__PURE__ */ new Map();
3991
+ const guard = ctx.recursionGuard;
3992
+ ctx.nameResolver = (name) => resolveName(name, sheet, wb, evaluating, resolving, resolved, guard);
3993
+ }
3994
+ }
3995
+ return ctx;
3996
+ }
3997
+ function resolveName(name, sheet, workbook, evaluating, resolving, resolved, recursionGuard) {
3998
+ const key = `${sheet.name}\0${name.toUpperCase()}`;
3999
+ const cached = resolved.get(key);
4000
+ if (cached !== void 0) return cached;
4001
+ if (resolving.has(key)) return FormulaValue.errorRef;
4002
+ const refersTo = workbook.getDefinedName(name, sheet.name);
4003
+ if (refersTo == null || refersTo === "") return FormulaValue.errorName;
4004
+ resolving.add(key);
4005
+ try {
4006
+ const ast = parseFormula(refersTo);
4007
+ const ctx = buildContext(sheet, {
4008
+ workbook,
4009
+ evaluating,
4010
+ resolvingNames: resolving,
4011
+ resolvedNames: resolved,
4012
+ recursionGuard
4013
+ });
4014
+ const value2 = ast.evaluate(ctx);
4015
+ if (value2.isLambda) resolved.set(key, value2);
4016
+ return value2;
4017
+ } catch {
4018
+ return FormulaValue.errorName;
4019
+ } finally {
4020
+ resolving.delete(key);
4021
+ }
4022
+ }
2875
4023
  function evaluateFormula(formula, sheet, options) {
2876
4024
  if (!formula) return FormulaValue.blank;
2877
4025
  try {
2878
4026
  const ast = parseFormula(formula);
2879
- const ctx = new FormulaContext(
2880
- sheet,
2881
- options?.formulaRow ?? 0,
2882
- options?.formulaCol ?? 0
2883
- );
2884
- if (options?.workbook) ctx.workbook = options.workbook;
4027
+ const ctx = buildContext(sheet, {
4028
+ workbook: options?.workbook,
4029
+ formulaRow: options?.formulaRow,
4030
+ formulaCol: options?.formulaCol
4031
+ });
2885
4032
  return ast.evaluate(ctx);
2886
4033
  } catch {
2887
4034
  return FormulaValue.errorValue;
@@ -2901,12 +4048,445 @@ function getAstCacheStats() {
2901
4048
  function setAstCacheCapacity(capacity) {
2902
4049
  astCache.resize(capacity);
2903
4050
  }
4051
+ function extractReferences(ast, formulaSheet, registry = FunctionRegistry.default, resolveName2) {
4052
+ const refs = [];
4053
+ let volatile = false;
4054
+ const seenNames = /* @__PURE__ */ new Set();
4055
+ const cell = (sheet, ref) => {
4056
+ const { row: row2, column: column2 } = puredocsExcel.parseCellRef(ref);
4057
+ return { sheet: sheet.toUpperCase(), startRow: row2, startCol: column2, endRow: row2, endCol: column2 };
4058
+ };
4059
+ const range = (sheet, startRef, endRef) => {
4060
+ const s = puredocsExcel.parseCellRef(startRef);
4061
+ const e = puredocsExcel.parseCellRef(endRef);
4062
+ return {
4063
+ sheet: sheet.toUpperCase(),
4064
+ startRow: Math.min(s.row, e.row),
4065
+ startCol: Math.min(s.column, e.column),
4066
+ endRow: Math.max(s.row, e.row),
4067
+ endCol: Math.max(s.column, e.column)
4068
+ };
4069
+ };
4070
+ const walk = (node) => {
4071
+ if (node instanceof CellReferenceNode) {
4072
+ refs.push(cell(formulaSheet, node.reference));
4073
+ } else if (node instanceof RangeReferenceNode) {
4074
+ refs.push(range(formulaSheet, node.startRef, node.endRef));
4075
+ } else if (node instanceof SheetCellReferenceNode) {
4076
+ refs.push(cell(node.sheetName, node.cellReference));
4077
+ } else if (node instanceof SheetRangeReferenceNode) {
4078
+ refs.push(range(node.sheetName, node.startRef, node.endRef));
4079
+ } else if (node instanceof NamedRangeNode) {
4080
+ expandName(node.name);
4081
+ } else if (node instanceof SpillReferenceNode) {
4082
+ refs.push(cell(formulaSheet, node.anchorRef));
4083
+ } else if (node instanceof FunctionCallNode) {
4084
+ if (registry.isVolatile(node.functionName)) volatile = true;
4085
+ for (const arg2 of node.args) walk(arg2);
4086
+ } else if (node instanceof BinaryOpNode) {
4087
+ walk(node.left);
4088
+ walk(node.right);
4089
+ } else if (node instanceof UnaryOpNode) {
4090
+ walk(node.operand);
4091
+ } else if (node instanceof ImplicitIntersectionNode) {
4092
+ walk(node.inner);
4093
+ }
4094
+ };
4095
+ const expandName = (name) => {
4096
+ if (!resolveName2) return;
4097
+ const key = name.toUpperCase();
4098
+ if (seenNames.has(key)) return;
4099
+ seenNames.add(key);
4100
+ const refersTo = resolveName2(name, formulaSheet);
4101
+ if (!refersTo) return;
4102
+ try {
4103
+ walk(parseFormula(refersTo));
4104
+ } catch {
4105
+ }
4106
+ };
4107
+ walk(ast);
4108
+ return { refs, volatile };
4109
+ }
4110
+ function refContains(ref, sheet, row2, col) {
4111
+ return ref.sheet === sheet && row2 >= ref.startRow && row2 <= ref.endRow && col >= ref.startCol && col <= ref.endCol;
4112
+ }
4113
+
4114
+ // src/recalc-engine.ts
4115
+ function createWorkbookRecalcModel(workbook) {
4116
+ return {
4117
+ getCellValue: (sheet, ref) => workbook.getWorksheet(sheet).getCellValue(ref),
4118
+ setCellValue: (sheet, ref, value2) => {
4119
+ workbook.getWorksheet(sheet).getCell(ref).setComputedValue(value2);
4120
+ },
4121
+ setCellFormula: (sheet, ref, formula) => {
4122
+ workbook.getWorksheet(sheet).getCell(ref).setFormula(formula);
4123
+ },
4124
+ clearCell: (sheet, ref) => {
4125
+ workbook.getWorksheet(sheet).getCell(ref).clear();
4126
+ },
4127
+ setCellArrayRef: (sheet, ref, spillRef) => {
4128
+ workbook.getWorksheet(sheet).getCell(ref).setArrayRef(spillRef);
4129
+ },
4130
+ getCellFormula: (sheet, ref) => workbook.getWorksheet(sheet).getCellFormula?.(ref) ?? null,
4131
+ getSpillRange: (sheet, ref) => workbook.getWorksheet(sheet).getSpillRange?.(ref) ?? null,
4132
+ isRowHidden: (sheet, row2) => workbook.getWorksheet(sheet).isRowHidden?.(row2) ?? false,
4133
+ getDefinedName: (name, sheet) => workbook.getDefinedName(name, sheet)
4134
+ };
4135
+ }
4136
+ var normSheet = (s) => s.toUpperCase();
4137
+ var normRef = (r) => r.replace(/\$/g, "").toUpperCase();
4138
+ var keyOf = (sheet, ref) => `${normSheet(sheet)}!${normRef(ref)}`;
4139
+ function parseKey(key) {
4140
+ const bang = key.indexOf("!");
4141
+ const sheet = key.slice(0, bang);
4142
+ const ref = key.slice(bang + 1);
4143
+ const { row: row2, column: column2 } = puredocsExcel.parseCellRef(ref);
4144
+ return { sheet, ref, row: row2, col: column2 };
4145
+ }
4146
+ var _model, _registry, _formulas, _sheetNames, _spills, _spillOwner, _RecalcEngine_instances, rememberSheet_fn, recalcFrom_fn, dependentClosure_fn, directDependents_fn, evaluatePass_fn, writeResult_fn, isOccupied_fn, clearSpill_fn, evaluateFormulaValue_fn, sheetLike_fn, buildWorkbookLike_fn;
4147
+ var RecalcEngine = class {
4148
+ constructor(model, registry = FunctionRegistry.default) {
4149
+ __privateAdd(this, _RecalcEngine_instances);
4150
+ __privateAdd(this, _model);
4151
+ __privateAdd(this, _registry);
4152
+ __privateAdd(this, _formulas, /* @__PURE__ */ new Map());
4153
+ /** upper-cased sheet key → original casing, for case-correct model I/O. */
4154
+ __privateAdd(this, _sheetNames, /* @__PURE__ */ new Map());
4155
+ /** anchor cellKey → set of spilled (non-anchor) cellKeys it currently owns. */
4156
+ __privateAdd(this, _spills, /* @__PURE__ */ new Map());
4157
+ /** spilled cellKey → the anchor cellKey that owns it. */
4158
+ __privateAdd(this, _spillOwner, /* @__PURE__ */ new Map());
4159
+ __privateSet(this, _model, model);
4160
+ __privateSet(this, _registry, registry);
4161
+ }
4162
+ // ── Registration ─────────────────────────────────────────────────────────────
4163
+ /**
4164
+ * Registers (or replaces) a formula for a cell and recalculates that cell and
4165
+ * everything downstream of it. Returns the recomputed cells in the order they
4166
+ * were evaluated. The leading '=' of the formula is optional.
4167
+ */
4168
+ setCellFormula(sheet, ref, formula) {
4169
+ if (!formula) throw new Error("Formula cannot be empty.");
4170
+ const text = formula.startsWith("=") ? formula.slice(1) : formula;
4171
+ const s = normSheet(sheet);
4172
+ const r = normRef(ref);
4173
+ const { row: row2, column: column2 } = puredocsExcel.parseCellRef(r);
4174
+ const ast = parseFormula(text);
4175
+ const { refs, volatile } = extractReferences(
4176
+ ast,
4177
+ s,
4178
+ __privateGet(this, _registry),
4179
+ __privateGet(this, _model).getDefinedName ? (n, sh) => __privateGet(this, _model).getDefinedName(n, sh) : void 0
4180
+ );
4181
+ __privateMethod(this, _RecalcEngine_instances, rememberSheet_fn).call(this, sheet);
4182
+ __privateGet(this, _formulas).set(keyOf(s, r), {
4183
+ sheet: s,
4184
+ sheetName: sheet,
4185
+ ref: r,
4186
+ row: row2,
4187
+ col: column2,
4188
+ formula: text,
4189
+ refs,
4190
+ volatile
4191
+ });
4192
+ __privateGet(this, _model).setCellFormula?.(sheet, r, text);
4193
+ return __privateMethod(this, _RecalcEngine_instances, recalcFrom_fn).call(this, [{ sheet: s, row: row2, col: column2 }], keyOf(s, r));
4194
+ }
4195
+ /**
4196
+ * Removes a formula from a cell and recalculates its dependents (which may now
4197
+ * read a plain input value instead). Returns the recomputed dependent cells.
4198
+ */
4199
+ clearCellFormula(sheet, ref) {
4200
+ const s = normSheet(sheet);
4201
+ const r = normRef(ref);
4202
+ const existed = __privateGet(this, _formulas).delete(keyOf(s, r));
4203
+ if (!existed) return [];
4204
+ __privateGet(this, _model).clearCell?.(sheet, r);
4205
+ const { row: row2, column: column2 } = puredocsExcel.parseCellRef(r);
4206
+ return __privateMethod(this, _RecalcEngine_instances, recalcFrom_fn).call(this, [{ sheet: s, row: row2, col: column2 }]);
4207
+ }
4208
+ /**
4209
+ * Writes a raw input value to a cell and recalculates every formula that
4210
+ * depends on it. Use this for non-formula edits so dependents stay current.
4211
+ */
4212
+ setCellValue(sheet, ref, value2) {
4213
+ __privateMethod(this, _RecalcEngine_instances, rememberSheet_fn).call(this, sheet);
4214
+ const s = normSheet(sheet);
4215
+ const r = normRef(ref);
4216
+ __privateGet(this, _model).setCellValue(sheet, r, value2);
4217
+ const { row: row2, column: column2 } = puredocsExcel.parseCellRef(r);
4218
+ return __privateMethod(this, _RecalcEngine_instances, recalcFrom_fn).call(this, [{ sheet: s, row: row2, col: column2 }]);
4219
+ }
4220
+ /**
4221
+ * Signals that a cell changed by some external means (the model was already
4222
+ * updated) and recalculates its dependents.
4223
+ */
4224
+ onCellChanged(sheet, ref) {
4225
+ __privateMethod(this, _RecalcEngine_instances, rememberSheet_fn).call(this, sheet);
4226
+ const s = normSheet(sheet);
4227
+ const r = normRef(ref);
4228
+ const { row: row2, column: column2 } = puredocsExcel.parseCellRef(r);
4229
+ return __privateMethod(this, _RecalcEngine_instances, recalcFrom_fn).call(this, [{ sheet: s, row: row2, col: column2 }]);
4230
+ }
4231
+ /** Recalculates every registered formula in dependency order. */
4232
+ recalcAll() {
4233
+ return __privateMethod(this, _RecalcEngine_instances, evaluatePass_fn).call(this, [...__privateGet(this, _formulas).values()]).results;
4234
+ }
4235
+ /** The precedents recorded for a formula cell (mainly for tests/inspection). */
4236
+ getPrecedents(sheet, ref) {
4237
+ return __privateGet(this, _formulas).get(keyOf(sheet, ref))?.refs ?? [];
4238
+ }
4239
+ };
4240
+ _model = new WeakMap();
4241
+ _registry = new WeakMap();
4242
+ _formulas = new WeakMap();
4243
+ _sheetNames = new WeakMap();
4244
+ _spills = new WeakMap();
4245
+ _spillOwner = new WeakMap();
4246
+ _RecalcEngine_instances = new WeakSet();
4247
+ rememberSheet_fn = function(name) {
4248
+ __privateGet(this, _sheetNames).set(normSheet(name), name);
4249
+ };
4250
+ // ── Internals ────────────────────────────────────────────────────────────────
4251
+ /**
4252
+ * Recomputes formulas affected by the given changed cells, to a fixpoint.
4253
+ *
4254
+ * A single topological pass is not enough once dynamic arrays exist: a
4255
+ * formula that spills changes cells the graph could not know about until the
4256
+ * array was computed, and those cells may have their own dependents. So we
4257
+ * evaluate a pass, collect every cell whose value actually changed (formula
4258
+ * outputs plus spilled/cleared cells), then recompute the dependents of those
4259
+ * cells, repeating until nothing new is affected (bounded for safety).
4260
+ */
4261
+ recalcFrom_fn = function(seeds, includeKey) {
4262
+ const results = [];
4263
+ const evaluated = /* @__PURE__ */ new Set();
4264
+ let pending = __privateMethod(this, _RecalcEngine_instances, dependentClosure_fn).call(this, seeds, evaluated);
4265
+ for (const e of __privateGet(this, _formulas).values()) {
4266
+ if (e.volatile) pending.set(keyOf(e.sheet, e.ref), e);
4267
+ }
4268
+ if (includeKey) {
4269
+ const self = __privateGet(this, _formulas).get(includeKey);
4270
+ if (self) pending.set(includeKey, self);
4271
+ }
4272
+ let guard = 0;
4273
+ const maxIterations = __privateGet(this, _formulas).size + 8;
4274
+ while (pending.size > 0 && guard++ <= maxIterations) {
4275
+ const { results: passResults, changed } = __privateMethod(this, _RecalcEngine_instances, evaluatePass_fn).call(this, [...pending.values()]);
4276
+ results.push(...passResults);
4277
+ for (const k of pending.keys()) evaluated.add(k);
4278
+ pending = __privateMethod(this, _RecalcEngine_instances, dependentClosure_fn).call(this, changed, evaluated);
4279
+ }
4280
+ return results;
4281
+ };
4282
+ /** Formula entries (not yet evaluated) whose precedents include one of the cells. */
4283
+ dependentClosure_fn = function(cells, evaluated) {
4284
+ const out = /* @__PURE__ */ new Map();
4285
+ const queue = [...cells];
4286
+ while (queue.length > 0) {
4287
+ const cell = queue.shift();
4288
+ for (const dep of __privateMethod(this, _RecalcEngine_instances, directDependents_fn).call(this, cell)) {
4289
+ const k = keyOf(dep.sheet, dep.ref);
4290
+ if (out.has(k) || evaluated.has(k)) continue;
4291
+ out.set(k, dep);
4292
+ queue.push({ sheet: dep.sheet, row: dep.row, col: dep.col });
4293
+ }
4294
+ }
4295
+ return out;
4296
+ };
4297
+ /** Formula entries whose precedents include the given cell. */
4298
+ directDependents_fn = function(cell) {
4299
+ const out = [];
4300
+ for (const e of __privateGet(this, _formulas).values()) {
4301
+ if (e.refs.some((ref) => refContains(ref, cell.sheet, cell.row, cell.col))) out.push(e);
4302
+ }
4303
+ return out;
4304
+ };
4305
+ /**
4306
+ * Topologically sorts the given entries and evaluates them, writing results
4307
+ * (scalars or spilled arrays) back to the model. Returns the results and the
4308
+ * flat list of cells whose value changed. Entries left in a cycle are #REF!.
4309
+ */
4310
+ evaluatePass_fn = function(entries) {
4311
+ const inSet = /* @__PURE__ */ new Map();
4312
+ for (const e of entries) inSet.set(keyOf(e.sheet, e.ref), e);
4313
+ const indegree = /* @__PURE__ */ new Map();
4314
+ const dependents = /* @__PURE__ */ new Map();
4315
+ for (const k of inSet.keys()) {
4316
+ indegree.set(k, 0);
4317
+ dependents.set(k, []);
4318
+ }
4319
+ for (const e of entries) {
4320
+ const depKey = keyOf(e.sheet, e.ref);
4321
+ for (const [pk, pe] of inSet) {
4322
+ if (pk === depKey) continue;
4323
+ if (e.refs.some((ref) => refContains(ref, pe.sheet, pe.row, pe.col))) {
4324
+ dependents.get(pk).push(depKey);
4325
+ indegree.set(depKey, indegree.get(depKey) + 1);
4326
+ }
4327
+ }
4328
+ }
4329
+ const ready = [];
4330
+ for (const [k, d] of indegree) if (d === 0) ready.push(k);
4331
+ const order = [];
4332
+ while (ready.length > 0) {
4333
+ const k = ready.shift();
4334
+ order.push(k);
4335
+ for (const d of dependents.get(k)) {
4336
+ indegree.set(d, indegree.get(d) - 1);
4337
+ if (indegree.get(d) === 0) ready.push(d);
4338
+ }
4339
+ }
4340
+ const results = [];
4341
+ const changed = [];
4342
+ const emitted = new Set(order);
4343
+ for (const k of order) {
4344
+ const e = inSet.get(k);
4345
+ const { result, changed: c } = __privateMethod(this, _RecalcEngine_instances, writeResult_fn).call(this, e);
4346
+ results.push(result);
4347
+ changed.push(...c);
4348
+ }
4349
+ for (const [k, e] of inSet) {
4350
+ if (emitted.has(k)) continue;
4351
+ __privateMethod(this, _RecalcEngine_instances, clearSpill_fn).call(this, keyOf(e.sheet, e.ref), changed);
4352
+ const value2 = FormulaValue.errorRef.toObject();
4353
+ __privateGet(this, _model).setCellValue(e.sheetName, e.ref, value2);
4354
+ changed.push({ sheet: e.sheet, row: e.row, col: e.col });
4355
+ results.push({ sheet: e.sheetName, ref: e.ref, value: value2, circular: true });
4356
+ }
4357
+ return { results, changed };
4358
+ };
4359
+ /**
4360
+ * Evaluates one formula and writes its result. Scalars go to the anchor cell.
4361
+ * Arrays spill across a block anchored at the formula cell: on a collision
4362
+ * with existing content the anchor becomes #SPILL! and nothing spills; when
4363
+ * an array shrinks, previously-spilled cells it no longer covers are cleared.
4364
+ */
4365
+ writeResult_fn = function(e) {
4366
+ const anchorKey = keyOf(e.sheet, e.ref);
4367
+ const fv2 = __privateMethod(this, _RecalcEngine_instances, evaluateFormulaValue_fn).call(this, e);
4368
+ const changed = [];
4369
+ const prevSpill = __privateGet(this, _spills).get(anchorKey) ?? /* @__PURE__ */ new Set();
4370
+ if (!fv2.isArray) {
4371
+ __privateMethod(this, _RecalcEngine_instances, clearSpill_fn).call(this, anchorKey, changed);
4372
+ __privateGet(this, _model).setCellArrayRef?.(e.sheetName, e.ref, null);
4373
+ const value2 = fv2.toObject();
4374
+ __privateGet(this, _model).setCellValue(e.sheetName, e.ref, value2);
4375
+ changed.push({ sheet: e.sheet, row: e.row, col: e.col });
4376
+ return { result: { sheet: e.sheetName, ref: e.ref, value: value2 }, changed };
4377
+ }
4378
+ const arr = fv2.arrayVal;
4379
+ const rows2 = arr.rows, cols = arr.columns;
4380
+ let collides = false;
4381
+ for (let dr = 0; dr < rows2 && !collides; dr++) {
4382
+ for (let dc = 0; dc < cols && !collides; dc++) {
4383
+ if (dr === 0 && dc === 0) continue;
4384
+ const r = e.row + dr, c = e.col + dc;
4385
+ const cellKey = keyOf(e.sheet, puredocsExcel.cellRefFromRowCol(r, c));
4386
+ if (__privateMethod(this, _RecalcEngine_instances, isOccupied_fn).call(this, cellKey, e.sheetName, puredocsExcel.cellRefFromRowCol(r, c), anchorKey, prevSpill)) {
4387
+ collides = true;
4388
+ }
4389
+ }
4390
+ }
4391
+ if (collides) {
4392
+ __privateMethod(this, _RecalcEngine_instances, clearSpill_fn).call(this, anchorKey, changed);
4393
+ __privateGet(this, _model).setCellArrayRef?.(e.sheetName, e.ref, null);
4394
+ const value2 = FormulaValue.error(9 /* Spill */).toObject();
4395
+ __privateGet(this, _model).setCellValue(e.sheetName, e.ref, value2);
4396
+ changed.push({ sheet: e.sheet, row: e.row, col: e.col });
4397
+ return { result: { sheet: e.sheetName, ref: e.ref, value: value2 }, changed };
4398
+ }
4399
+ const newSpill = /* @__PURE__ */ new Set();
4400
+ for (let dr = 0; dr < rows2; dr++) {
4401
+ for (let dc = 0; dc < cols; dc++) {
4402
+ const r = e.row + dr, c = e.col + dc;
4403
+ const ref = puredocsExcel.cellRefFromRowCol(r, c);
4404
+ __privateGet(this, _model).setCellValue(e.sheetName, ref, arr.get(dr, dc).toObject());
4405
+ changed.push({ sheet: e.sheet, row: r, col: c });
4406
+ if (dr !== 0 || dc !== 0) {
4407
+ const cellKey = keyOf(e.sheet, ref);
4408
+ newSpill.add(cellKey);
4409
+ __privateGet(this, _spillOwner).set(cellKey, anchorKey);
4410
+ }
4411
+ }
4412
+ }
4413
+ for (const oldKey of prevSpill) {
4414
+ if (newSpill.has(oldKey)) continue;
4415
+ const cell = parseKey(oldKey);
4416
+ __privateGet(this, _model).setCellValue(__privateGet(this, _sheetNames).get(cell.sheet) ?? cell.sheet, cell.ref, null);
4417
+ __privateGet(this, _spillOwner).delete(oldKey);
4418
+ changed.push({ sheet: cell.sheet, row: cell.row, col: cell.col });
4419
+ }
4420
+ __privateGet(this, _spills).set(anchorKey, newSpill);
4421
+ const spillRef = `${e.ref}:${puredocsExcel.cellRefFromRowCol(e.row + rows2 - 1, e.col + cols - 1)}`;
4422
+ __privateGet(this, _model).setCellArrayRef?.(e.sheetName, e.ref, spillRef);
4423
+ return {
4424
+ result: { sheet: e.sheetName, ref: e.ref, value: arr.get(0, 0).toObject(), spill: { rows: rows2, cols } },
4425
+ changed
4426
+ };
4427
+ };
4428
+ /** Whether a target cell already holds content that blocks a spill. */
4429
+ isOccupied_fn = function(cellKey, sheetName, ref, anchorKey, prevSpill) {
4430
+ if (__privateGet(this, _formulas).has(cellKey) && cellKey !== anchorKey) return true;
4431
+ const owner = __privateGet(this, _spillOwner).get(cellKey);
4432
+ if (owner && owner !== anchorKey) return true;
4433
+ if (prevSpill.has(cellKey)) return false;
4434
+ const v = __privateGet(this, _model).getCellValue(sheetName, ref);
4435
+ return v !== null && v !== void 0 && v !== "";
4436
+ };
4437
+ /** Clears an anchor's spilled cells (not the anchor itself) and forgets them. */
4438
+ clearSpill_fn = function(anchorKey, changed) {
4439
+ const spill = __privateGet(this, _spills).get(anchorKey);
4440
+ if (!spill) return;
4441
+ for (const cellKey of spill) {
4442
+ const cell = parseKey(cellKey);
4443
+ __privateGet(this, _model).setCellValue(__privateGet(this, _sheetNames).get(cell.sheet) ?? cell.sheet, cell.ref, null);
4444
+ __privateGet(this, _spillOwner).delete(cellKey);
4445
+ changed.push({ sheet: cell.sheet, row: cell.row, col: cell.col });
4446
+ }
4447
+ __privateGet(this, _spills).delete(anchorKey);
4448
+ };
4449
+ evaluateFormulaValue_fn = function(e) {
4450
+ const wb = __privateMethod(this, _RecalcEngine_instances, buildWorkbookLike_fn).call(this);
4451
+ const ws = __privateMethod(this, _RecalcEngine_instances, sheetLike_fn).call(this, e.sheetName);
4452
+ return evaluateFormula(e.formula, ws, {
4453
+ workbook: wb,
4454
+ formulaRow: e.row,
4455
+ formulaCol: e.col
4456
+ });
4457
+ };
4458
+ sheetLike_fn = function(sheetName) {
4459
+ return {
4460
+ name: sheetName,
4461
+ getCellValue: (ref) => __privateGet(this, _model).getCellValue(sheetName, ref),
4462
+ isRowHidden: __privateGet(this, _model).isRowHidden ? (row2) => __privateGet(this, _model).isRowHidden(sheetName, row2) : void 0,
4463
+ getCellFormula: __privateGet(this, _model).getCellFormula ? (ref) => __privateGet(this, _model).getCellFormula(sheetName, ref) : void 0,
4464
+ getSpillRange: __privateGet(this, _model).getSpillRange ? (ref) => __privateGet(this, _model).getSpillRange(sheetName, ref) : void 0
4465
+ };
4466
+ };
4467
+ buildWorkbookLike_fn = function() {
4468
+ const self = this;
4469
+ return {
4470
+ get worksheets() {
4471
+ return [...__privateGet(self, _sheetNames).values()].map((n) => {
4472
+ var _a;
4473
+ return __privateMethod(_a = self, _RecalcEngine_instances, sheetLike_fn).call(_a, n);
4474
+ });
4475
+ },
4476
+ getWorksheet: (name) => {
4477
+ var _a;
4478
+ return __privateMethod(_a = self, _RecalcEngine_instances, sheetLike_fn).call(_a, name);
4479
+ },
4480
+ getDefinedName: __privateGet(this, _model).getDefinedName ? (name, sheet) => __privateGet(this, _model).getDefinedName(name, sheet) : void 0
4481
+ };
4482
+ };
2904
4483
 
2905
4484
  exports.ArrayValue = ArrayValue;
2906
4485
  exports.BinaryOpNode = BinaryOpNode;
2907
4486
  exports.BinaryOperator = BinaryOperator;
2908
4487
  exports.BlankNode = BlankNode;
2909
4488
  exports.BooleanNode = BooleanNode;
4489
+ exports.CallNode = CallNode;
2910
4490
  exports.CellReferenceNode = CellReferenceNode;
2911
4491
  exports.ErrorNode = ErrorNode;
2912
4492
  exports.FormulaContext = FormulaContext;
@@ -2923,21 +4503,30 @@ exports.LruCache = LruCache;
2923
4503
  exports.NamedRangeNode = NamedRangeNode;
2924
4504
  exports.NumberNode = NumberNode;
2925
4505
  exports.RangeReferenceNode = RangeReferenceNode;
4506
+ exports.RecalcEngine = RecalcEngine;
2926
4507
  exports.SheetCellReferenceNode = SheetCellReferenceNode;
2927
4508
  exports.SheetRangeReferenceNode = SheetRangeReferenceNode;
4509
+ exports.SpillReferenceNode = SpillReferenceNode;
2928
4510
  exports.StringNode = StringNode;
2929
4511
  exports.TokenType = TokenType;
2930
4512
  exports.UnaryOpNode = UnaryOpNode;
2931
4513
  exports.UnaryOperator = UnaryOperator;
2932
4514
  exports.clearAstCache = clearAstCache;
4515
+ exports.createWorkbookRecalcModel = createWorkbookRecalcModel;
2933
4516
  exports.evaluateFormula = evaluateFormula;
4517
+ exports.extractReferences = extractReferences;
2934
4518
  exports.getAstCacheStats = getAstCacheStats;
2935
4519
  exports.parseFormula = parseFormula;
4520
+ exports.refContains = refContains;
4521
+ exports.registerAggregate = registerAggregate;
4522
+ exports.registerArray = registerArray;
2936
4523
  exports.registerDate = registerDate;
4524
+ exports.registerFinance = registerFinance;
2937
4525
  exports.registerInfo = registerInfo;
2938
4526
  exports.registerLogical = registerLogical;
2939
4527
  exports.registerLookup = registerLookup;
2940
4528
  exports.registerMath = registerMath;
4529
+ exports.registerMeta = registerMeta;
2941
4530
  exports.registerStatistical = registerStatistical;
2942
4531
  exports.registerText = registerText;
2943
4532
  exports.setAstCacheCapacity = setAstCacheCapacity;