@zonastery/bursar 0.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.
Files changed (70) hide show
  1. package/README.md +375 -0
  2. package/dist/allowance.d.ts +48 -0
  3. package/dist/allowance.d.ts.map +1 -0
  4. package/dist/allowance.js +140 -0
  5. package/dist/allowance.js.map +1 -0
  6. package/dist/breakdown.d.ts +27 -0
  7. package/dist/breakdown.d.ts.map +1 -0
  8. package/dist/breakdown.js +27 -0
  9. package/dist/breakdown.js.map +1 -0
  10. package/dist/config.d.ts +23 -0
  11. package/dist/config.d.ts.map +1 -0
  12. package/dist/config.js +278 -0
  13. package/dist/config.js.map +1 -0
  14. package/dist/engine.d.ts +44 -0
  15. package/dist/engine.d.ts.map +1 -0
  16. package/dist/engine.js +172 -0
  17. package/dist/engine.js.map +1 -0
  18. package/dist/errors.d.ts +55 -0
  19. package/dist/errors.d.ts.map +1 -0
  20. package/dist/errors.js +55 -0
  21. package/dist/errors.js.map +1 -0
  22. package/dist/expr.d.ts +65 -0
  23. package/dist/expr.d.ts.map +1 -0
  24. package/dist/expr.js +681 -0
  25. package/dist/expr.js.map +1 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +14 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/load-pricing-file.d.ts +12 -0
  31. package/dist/load-pricing-file.d.ts.map +1 -0
  32. package/dist/load-pricing-file.js +45 -0
  33. package/dist/load-pricing-file.js.map +1 -0
  34. package/dist/manager.d.ts +421 -0
  35. package/dist/manager.d.ts.map +1 -0
  36. package/dist/manager.js +1112 -0
  37. package/dist/manager.js.map +1 -0
  38. package/dist/metrics.d.ts +19 -0
  39. package/dist/metrics.d.ts.map +1 -0
  40. package/dist/metrics.js +2 -0
  41. package/dist/metrics.js.map +1 -0
  42. package/dist/node.d.ts +15 -0
  43. package/dist/node.d.ts.map +1 -0
  44. package/dist/node.js +15 -0
  45. package/dist/node.js.map +1 -0
  46. package/dist/stores/credit-store.d.ts +171 -0
  47. package/dist/stores/credit-store.d.ts.map +1 -0
  48. package/dist/stores/credit-store.js +52 -0
  49. package/dist/stores/credit-store.js.map +1 -0
  50. package/dist/stores/events.d.ts +63 -0
  51. package/dist/stores/events.d.ts.map +1 -0
  52. package/dist/stores/events.js +68 -0
  53. package/dist/stores/events.js.map +1 -0
  54. package/dist/stores/memory-store.d.ts +178 -0
  55. package/dist/stores/memory-store.d.ts.map +1 -0
  56. package/dist/stores/memory-store.js +1833 -0
  57. package/dist/stores/memory-store.js.map +1 -0
  58. package/dist/stores/postgres-store.d.ts +95 -0
  59. package/dist/stores/postgres-store.d.ts.map +1 -0
  60. package/dist/stores/postgres-store.js +872 -0
  61. package/dist/stores/postgres-store.js.map +1 -0
  62. package/dist/stores/supabase-store.d.ts +76 -0
  63. package/dist/stores/supabase-store.d.ts.map +1 -0
  64. package/dist/stores/supabase-store.js +865 -0
  65. package/dist/stores/supabase-store.js.map +1 -0
  66. package/dist/types.d.ts +462 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +2 -0
  69. package/dist/types.js.map +1 -0
  70. package/package.json +82 -0
package/dist/expr.js ADDED
@@ -0,0 +1,681 @@
1
+ import Decimal from "decimal.js";
2
+ import { ExpressionError } from "./errors.js";
3
+ // Quantization: all credit amounts round to 4 decimal places, ROUND_HALF_UP.
4
+ // This must match the Python SDK's Decimal quantize(0.0001, ROUND_HALF_UP).
5
+ export const MONEY_DP = 4;
6
+ export const MONEY_ROUNDING = Decimal.ROUND_HALF_UP;
7
+ /** Quantize a Decimal credit amount to 4dp, ROUND_HALF_UP. */
8
+ export function quantizeMoney(value) {
9
+ return value.toDecimalPlaces(MONEY_DP, MONEY_ROUNDING);
10
+ }
11
+ const ALLOWED_FUNCTIONS = new Set([
12
+ "ceil",
13
+ "floor",
14
+ "min",
15
+ "max",
16
+ "round",
17
+ "if",
18
+ "tier",
19
+ "clamp",
20
+ "percentile",
21
+ ]);
22
+ function tokenize(src) {
23
+ const tokens = [];
24
+ let i = 0;
25
+ while (i < src.length) {
26
+ if (src[i] === " " || src[i] === "\t" || src[i] === "\n") {
27
+ i++;
28
+ continue;
29
+ }
30
+ if (src[i] === "(") {
31
+ tokens.push({ type: "(", value: "(" });
32
+ i++;
33
+ continue;
34
+ }
35
+ if (src[i] === ")") {
36
+ tokens.push({ type: ")", value: ")" });
37
+ i++;
38
+ continue;
39
+ }
40
+ if (src[i] === ",") {
41
+ tokens.push({ type: ",", value: "," });
42
+ i++;
43
+ continue;
44
+ }
45
+ // Two-char operators
46
+ const two = src.slice(i, i + 2);
47
+ if (two === "**") {
48
+ tokens.push({ type: "**", value: "**" });
49
+ i += 2;
50
+ continue;
51
+ }
52
+ if (two === "//") {
53
+ tokens.push({ type: "//", value: "//" });
54
+ i += 2;
55
+ continue;
56
+ }
57
+ if (two === "==") {
58
+ tokens.push({ type: "==", value: "==" });
59
+ i += 2;
60
+ continue;
61
+ }
62
+ if (two === "!=") {
63
+ tokens.push({ type: "!=", value: "!=" });
64
+ i += 2;
65
+ continue;
66
+ }
67
+ if (two === "<=") {
68
+ tokens.push({ type: "<=", value: "<=" });
69
+ i += 2;
70
+ continue;
71
+ }
72
+ if (two === ">=") {
73
+ tokens.push({ type: ">=", value: ">=" });
74
+ i += 2;
75
+ continue;
76
+ }
77
+ // "not in" needs special handling — we tokenize "not" and then "in" separately
78
+ // The parser will handle "not" + "in" as "not in"
79
+ // One-char operators
80
+ if (src[i] === "+") {
81
+ tokens.push({ type: "+", value: "+" });
82
+ i++;
83
+ continue;
84
+ }
85
+ if (src[i] === "-") {
86
+ tokens.push({ type: "-", value: "-" });
87
+ i++;
88
+ continue;
89
+ }
90
+ if (src[i] === "*") {
91
+ tokens.push({ type: "*", value: "*" });
92
+ i++;
93
+ continue;
94
+ }
95
+ if (src[i] === "/") {
96
+ tokens.push({ type: "/", value: "/" });
97
+ i++;
98
+ continue;
99
+ }
100
+ if (src[i] === "%") {
101
+ tokens.push({ type: "%", value: "%" });
102
+ i++;
103
+ continue;
104
+ }
105
+ if (src[i] === "<") {
106
+ tokens.push({ type: "<", value: "<" });
107
+ i++;
108
+ continue;
109
+ }
110
+ if (src[i] === ">") {
111
+ tokens.push({ type: ">", value: ">" });
112
+ i++;
113
+ continue;
114
+ }
115
+ // Numbers — strict literal: digits with optional '.' and optional 'e'/'E' exponent.
116
+ // Supports scientific notation (1e3, 1e-6, 2.5E+10) so per-token pricing
117
+ // configs like {"_default":"input_tokens * 1e-6"} load in JS (H5 parity fix).
118
+ // Rejects malformed literals like "1.2.3" (H11 parity fix).
119
+ if (/[0-9.]/.test(src[i])) {
120
+ let num = "";
121
+ let dotSeen = false;
122
+ // Mantissa: digits and at most one '.'
123
+ while (i < src.length && /[0-9.]/.test(src[i])) {
124
+ if (src[i] === ".") {
125
+ if (dotSeen) {
126
+ throw new ExpressionError(`invalid number literal: '${num}.'`);
127
+ }
128
+ dotSeen = true;
129
+ }
130
+ num += src[i];
131
+ i++;
132
+ }
133
+ if (num === "." || !/^[0-9]*\.?[0-9]*$/.test(num) || !/[0-9]/.test(num)) {
134
+ throw new ExpressionError(`invalid number literal: '${num}'`);
135
+ }
136
+ // Optional exponent: e/E followed by optional +/- and one or more digits.
137
+ if (i < src.length && (src[i] === "e" || src[i] === "E")) {
138
+ num += src[i];
139
+ i++;
140
+ if (i < src.length && (src[i] === "+" || src[i] === "-")) {
141
+ num += src[i];
142
+ i++;
143
+ }
144
+ if (i >= src.length || !/[0-9]/.test(src[i])) {
145
+ throw new ExpressionError(`invalid number literal: '${num}'`);
146
+ }
147
+ while (i < src.length && /[0-9]/.test(src[i])) {
148
+ num += src[i];
149
+ i++;
150
+ }
151
+ }
152
+ tokens.push({ type: "number", value: num });
153
+ continue;
154
+ }
155
+ // Identifiers and keywords
156
+ if (/[a-zA-Z_]/.test(src[i])) {
157
+ let word = "";
158
+ while (i < src.length && /[a-zA-Z0-9_]/.test(src[i])) {
159
+ word += src[i];
160
+ i++;
161
+ }
162
+ const kw = word === "and"
163
+ ? "and"
164
+ : word === "or"
165
+ ? "or"
166
+ : word === "if"
167
+ ? "if"
168
+ : word === "else"
169
+ ? "else"
170
+ : word === "in"
171
+ ? "in"
172
+ : word === "not"
173
+ ? "not"
174
+ : word === "true"
175
+ ? "number"
176
+ : word === "false"
177
+ ? "number"
178
+ : "identifier";
179
+ tokens.push({
180
+ type: kw,
181
+ value: word === "true" ? "1" : word === "false" ? "0" : word,
182
+ });
183
+ continue;
184
+ }
185
+ throw new ExpressionError(`unexpected character: '${src[i]}'`);
186
+ }
187
+ return tokens;
188
+ }
189
+ // ── Parser ─────────────────────────────────────────────────────────────────
190
+ class Parser {
191
+ tokens;
192
+ pos = 0;
193
+ constructor(tokens) {
194
+ this.tokens = tokens;
195
+ }
196
+ peek() {
197
+ return this.tokens[this.pos];
198
+ }
199
+ previous() {
200
+ return this.tokens[this.pos - 1];
201
+ }
202
+ isAtEnd() {
203
+ return this.pos >= this.tokens.length;
204
+ }
205
+ check(...types) {
206
+ if (this.isAtEnd())
207
+ return false;
208
+ return types.includes(this.tokens[this.pos].type);
209
+ }
210
+ match(...types) {
211
+ for (const t of types) {
212
+ if (this.check(t)) {
213
+ this.pos++;
214
+ return true;
215
+ }
216
+ }
217
+ return false;
218
+ }
219
+ consume(type, msg) {
220
+ if (this.check(type))
221
+ return this.tokens[this.pos++];
222
+ throw new ExpressionError(msg);
223
+ }
224
+ parse() {
225
+ const expr = this.boolExpr();
226
+ // Handle ternary: X if cond else Y (at top level so operators bind correctly)
227
+ if (this.match("if")) {
228
+ const cond = this.boolExpr();
229
+ this.consume("else", "expected 'else' in ternary expression");
230
+ const elseBranch = this.boolExpr();
231
+ return { type: "ternary", cond, then: expr, else: elseBranch };
232
+ }
233
+ return expr;
234
+ }
235
+ comparison() {
236
+ let left = this.addition();
237
+ // Handle "not in" as two tokens
238
+ if (this.match("not") && this.match("in")) {
239
+ const right = this.addition();
240
+ left = { type: "comparison", op: "not in", left, right };
241
+ }
242
+ while (this.match("==", "!=", "<", "<=", ">", ">=", "in")) {
243
+ const op = this.previous().value;
244
+ const right = this.addition();
245
+ left = { type: "comparison", op, left, right };
246
+ }
247
+ return left;
248
+ }
249
+ addition() {
250
+ let left = this.multiplication();
251
+ while (this.match("+", "-")) {
252
+ const op = this.previous().value;
253
+ const right = this.multiplication();
254
+ left = { type: "binary", op, left, right };
255
+ }
256
+ return left;
257
+ }
258
+ multiplication() {
259
+ let left = this.unary();
260
+ // NOTE: "**" is intentionally NOT accepted here. Exponentiation is rejected
261
+ // entirely (sandbox decision C5/C7, matching the Python SDK) — a "**" token
262
+ // surfaces as a leftover token and fails validation/evaluation. We also
263
+ // raise an explicit error if one is seen mid-expression.
264
+ while (this.match("*", "/", "//", "%")) {
265
+ const op = this.previous().value;
266
+ const right = this.unary();
267
+ left = { type: "binary", op, left, right };
268
+ }
269
+ if (this.check("**")) {
270
+ throw new ExpressionError("exponentiation operator '**' is not allowed in pricing expressions");
271
+ }
272
+ return left;
273
+ }
274
+ notExpr() {
275
+ if (this.match("not")) {
276
+ const operand = this.notExpr();
277
+ return { type: "unary", op: "not", operand };
278
+ }
279
+ return this.comparison();
280
+ }
281
+ boolExpr() {
282
+ let left = this.notExpr();
283
+ while (this.match("and", "or")) {
284
+ const op = this.previous().value;
285
+ const right = this.notExpr();
286
+ left = { type: "boolean", op, left, right };
287
+ }
288
+ return left;
289
+ }
290
+ unary() {
291
+ if (this.match("+", "-")) {
292
+ const op = this.previous().value;
293
+ return { type: "unary", op, operand: this.unary() };
294
+ }
295
+ return this.callOrPrimary();
296
+ }
297
+ callOrPrimary() {
298
+ return this.primary();
299
+ }
300
+ primary() {
301
+ if (this.check("**")) {
302
+ throw new ExpressionError("exponentiation operator '**' is not allowed in pricing expressions");
303
+ }
304
+ if (this.match("number")) {
305
+ return { type: "number", value: this.previous().value };
306
+ }
307
+ if (this.match("identifier")) {
308
+ const name = this.previous().value;
309
+ // Check if this is a function call like ceil(...)
310
+ if (this.match("(")) {
311
+ const args = [];
312
+ if (!this.check(")")) {
313
+ do {
314
+ args.push(this.boolExpr());
315
+ } while (this.match(","));
316
+ }
317
+ this.consume(")", "expected ')'");
318
+ if (!ALLOWED_FUNCTIONS.has(name)) {
319
+ throw new ExpressionError(`disallowed function: ${name}`);
320
+ }
321
+ return { type: "call", name, args };
322
+ }
323
+ return { type: "identifier", name };
324
+ }
325
+ // if(cond, then, else) — disambiguate from ternary by checking for '('
326
+ if (this.match("if") && this.match("(")) {
327
+ const args = [];
328
+ if (!this.check(")")) {
329
+ do {
330
+ args.push(this.boolExpr());
331
+ } while (this.match(","));
332
+ }
333
+ this.consume(")", "expected ')'");
334
+ return { type: "call", name: "if", args };
335
+ }
336
+ if (this.match("(")) {
337
+ const expr = this.parse();
338
+ this.consume(")", "expected ')'");
339
+ return expr;
340
+ }
341
+ throw new ExpressionError(`unexpected token: '${this.peek()?.value ?? "EOF"}'`);
342
+ }
343
+ }
344
+ // ── Helper arity / range validation (H6) ─────────────────────────────────────
345
+ // Static checks applied at parse/validate time so config-load (and the parity
346
+ // fixture's expect_error cases) reject malformed helper calls. Semantics must
347
+ // match the Python SDK exactly.
348
+ function checkCallArity(name, argc) {
349
+ switch (name) {
350
+ case "if":
351
+ if (argc !== 3)
352
+ throw new ExpressionError("if() requires exactly 3 arguments: if(condition, then, else)");
353
+ break;
354
+ case "clamp":
355
+ if (argc !== 3)
356
+ throw new ExpressionError("clamp() requires exactly 3 arguments: clamp(x, min, max)");
357
+ break;
358
+ case "tier":
359
+ // tier(value, t1, r1, [t2, r2, ...], default) — the value, then N>=1
360
+ // (threshold, rate) pairs, then a trailing default. Arg count must be
361
+ // EVEN and >= 4 (REFACTOR_CONTRACT.md §1): 4 args = 1 pair + default,
362
+ // 6 args = 2 pairs + default, etc. Odd arg counts (3/5/7) and < 4 are
363
+ // rejected. Semantics: return r_i for the first value < t_i, else default.
364
+ if (argc < 4 || argc % 2 !== 0)
365
+ throw new ExpressionError("tier() requires an even number of arguments >= 4 (value, threshold, rate, ..., default)");
366
+ break;
367
+ case "percentile":
368
+ if (argc < 2)
369
+ throw new ExpressionError("percentile() requires at least 2 arguments (p, v1, [v2, ...])");
370
+ break;
371
+ case "min":
372
+ if (argc < 1)
373
+ throw new ExpressionError("min() requires at least 1 argument");
374
+ break;
375
+ case "max":
376
+ if (argc < 1)
377
+ throw new ExpressionError("max() requires at least 1 argument");
378
+ break;
379
+ case "ceil":
380
+ case "floor":
381
+ if (argc !== 1)
382
+ throw new ExpressionError(`${name}() requires exactly 1 argument`);
383
+ break;
384
+ case "round":
385
+ if (argc !== 1 && argc !== 2)
386
+ throw new ExpressionError("round() requires 1 or 2 arguments: round(x[, ndigits])");
387
+ break;
388
+ default:
389
+ break;
390
+ }
391
+ }
392
+ function validateCalls(node) {
393
+ if (node.type === "call") {
394
+ checkCallArity(node.name, node.args.length);
395
+ }
396
+ for (const child of children(node))
397
+ validateCalls(child);
398
+ }
399
+ // ── Validation ─────────────────────────────────────────────────────────────
400
+ function collectVariables(node) {
401
+ const seen = new Set();
402
+ function walk(n) {
403
+ if (n.type === "identifier" && !ALLOWED_FUNCTIONS.has(n.name)) {
404
+ seen.add(n.name);
405
+ }
406
+ for (const child of children(n))
407
+ walk(child);
408
+ }
409
+ walk(node);
410
+ return seen;
411
+ }
412
+ function children(n) {
413
+ switch (n.type) {
414
+ case "binary":
415
+ return [n.left, n.right];
416
+ case "unary":
417
+ return [n.operand];
418
+ case "call":
419
+ return n.args;
420
+ case "ternary":
421
+ return [n.cond, n.then, n.else];
422
+ case "comparison":
423
+ return [n.left, n.right];
424
+ case "boolean":
425
+ return [n.left, n.right];
426
+ case "number":
427
+ case "identifier":
428
+ return [];
429
+ }
430
+ }
431
+ // ── Public API ─────────────────────────────────────────────────────────────
432
+ /**
433
+ * Validate that an expression string is safe and syntactically valid.
434
+ *
435
+ * @param expr The expression source.
436
+ * @param knownVariables Optional set of metric variable names allowed in the
437
+ * expression. When provided (config-load passes the metric set from
438
+ * `PricingEngine.buildVariables`), any identifier not in this set and not an
439
+ * allowed function is rejected (M5) — typos fail at load, not at runtime.
440
+ */
441
+ export function validateExpression(expr, knownVariables) {
442
+ try {
443
+ const tokens = tokenize(expr);
444
+ const parser = new Parser(tokens);
445
+ const node = parser.parse();
446
+ if (!parser.isAtEnd()) {
447
+ throw new ExpressionError(`unexpected token after expression: '${parser.peek()?.value}'`);
448
+ }
449
+ validateCalls(node);
450
+ const vars = collectVariables(node);
451
+ if (vars.size === 0) {
452
+ throw new ExpressionError("expression references no variables -- must use at least one metric");
453
+ }
454
+ if (knownVariables !== undefined) {
455
+ const known = knownVariables instanceof Set ? knownVariables : new Set(knownVariables);
456
+ for (const name of vars) {
457
+ if (!known.has(name)) {
458
+ throw new ExpressionError(`unknown variable: '${name}'`);
459
+ }
460
+ }
461
+ }
462
+ }
463
+ catch (e) {
464
+ if (e instanceof ExpressionError)
465
+ throw e;
466
+ throw new ExpressionError(`invalid expression: ${e.message}`);
467
+ }
468
+ }
469
+ /**
470
+ * Safely evaluate a validated expression. Returns an exact `Decimal` — never a
471
+ * binary-float `number` — so credit math is precise and parity-stable with the
472
+ * Python `decimal.Decimal` engine.
473
+ */
474
+ export function evaluateExpression(expr, variables) {
475
+ if (!variables || typeof variables !== "object") {
476
+ throw new ExpressionError("variables must be a dict");
477
+ }
478
+ if (Object.keys(variables).length === 0) {
479
+ throw new ExpressionError("cannot evaluate: variables dict is empty");
480
+ }
481
+ let tokens;
482
+ try {
483
+ tokens = tokenize(expr);
484
+ }
485
+ catch (e) {
486
+ if (e instanceof ExpressionError)
487
+ throw e;
488
+ throw new ExpressionError(`syntax error: ${e.message}`);
489
+ }
490
+ const parser = new Parser(tokens);
491
+ const node = parser.parse();
492
+ if (!parser.isAtEnd()) {
493
+ throw new ExpressionError(`unexpected token: '${parser.peek()?.value}'`);
494
+ }
495
+ // Arity/range validation (parity with Python, which validates on every eval).
496
+ validateCalls(node);
497
+ // Validate undefined variables using OWN-property checks only (C6). The `in`
498
+ // operator walks the prototype chain, so identifiers like __proto__,
499
+ // constructor, prototype, toString, hasOwnProperty would otherwise resolve to
500
+ // inherited members. Object.prototype.hasOwnProperty.call rejects all of them.
501
+ function checkVars(n) {
502
+ if (n.type === "identifier" &&
503
+ !ALLOWED_FUNCTIONS.has(n.name) &&
504
+ !Object.prototype.hasOwnProperty.call(variables, n.name)) {
505
+ throw new ExpressionError(`undefined variable: '${n.name}'`);
506
+ }
507
+ for (const child of children(n))
508
+ checkVars(child);
509
+ }
510
+ checkVars(node);
511
+ const result = evaluateNode(node, variables);
512
+ // Guard non-finite results (C7): NaN/Infinity must never become a charge.
513
+ if (!result.isFinite()) {
514
+ throw new ExpressionError(`expression evaluated to a non-finite value: ${result.toString()}`);
515
+ }
516
+ return result;
517
+ }
518
+ const ZERO = new Decimal(0);
519
+ const ONE = new Decimal(1);
520
+ function toDecimal(v) {
521
+ return v instanceof Decimal ? v : new Decimal(v);
522
+ }
523
+ function truthy(d) {
524
+ return !d.isZero();
525
+ }
526
+ function evaluateNode(node, vars) {
527
+ switch (node.type) {
528
+ case "number":
529
+ // Parse from the exact literal string (never via binary float).
530
+ return new Decimal(node.value);
531
+ case "identifier": {
532
+ // Own-property lookup only (C6); undefined identifiers were already
533
+ // rejected by checkVars, but guard defensively here too.
534
+ if (!Object.prototype.hasOwnProperty.call(vars, node.name)) {
535
+ return ZERO;
536
+ }
537
+ return toDecimal(vars[node.name]);
538
+ }
539
+ case "unary": {
540
+ const v = evaluateNode(node.operand, vars);
541
+ if (node.op === "not")
542
+ return truthy(v) ? ZERO : ONE;
543
+ return node.op === "-" ? v.negated() : v;
544
+ }
545
+ case "binary": {
546
+ const l = evaluateNode(node.left, vars);
547
+ const r = evaluateNode(node.right, vars);
548
+ switch (node.op) {
549
+ case "+":
550
+ return l.plus(r);
551
+ case "-":
552
+ return l.minus(r);
553
+ case "*":
554
+ return l.times(r);
555
+ case "/":
556
+ if (r.isZero())
557
+ throw new ExpressionError("division by zero");
558
+ return l.dividedBy(r);
559
+ case "//":
560
+ if (r.isZero())
561
+ throw new ExpressionError("division by zero");
562
+ // Floor division — matches Python's // and JS Math.floor(l / r).
563
+ return l.dividedBy(r).floor();
564
+ case "%":
565
+ if (r.isZero())
566
+ throw new ExpressionError("modulo by zero");
567
+ return l.modulo(r);
568
+ default:
569
+ throw new ExpressionError(`unknown operator: ${node.op}`);
570
+ }
571
+ }
572
+ case "call": {
573
+ const args = node.args.map((a) => evaluateNode(a, vars));
574
+ switch (node.name) {
575
+ case "ceil":
576
+ return args[0].ceil();
577
+ case "floor":
578
+ return args[0].floor();
579
+ case "min":
580
+ if (args.length < 1)
581
+ throw new ExpressionError("min() requires at least 1 argument");
582
+ return Decimal.min(...args);
583
+ case "max":
584
+ if (args.length < 1)
585
+ throw new ExpressionError("max() requires at least 1 argument");
586
+ return Decimal.max(...args);
587
+ case "round": {
588
+ if (args.length !== 1 && args.length !== 2)
589
+ throw new ExpressionError("round() requires 1 or 2 arguments: round(x[, ndigits])");
590
+ const ndigits = args.length === 2 ? args[1].toNumber() : 0;
591
+ return args[0].toDecimalPlaces(ndigits, Decimal.ROUND_HALF_UP);
592
+ }
593
+ case "if":
594
+ if (args.length !== 3)
595
+ throw new ExpressionError("if() requires exactly 3 arguments: if(condition, then, else)");
596
+ return truthy(args[0]) ? args[1] : args[2];
597
+ case "tier": {
598
+ if (args.length < 4 || args.length % 2 !== 0)
599
+ throw new ExpressionError("tier() requires an even number of arguments >= 4 (value, threshold, rate, ..., default)");
600
+ const val = args[0];
601
+ for (let i = 1; i < args.length - 1; i += 2) {
602
+ if (val.lessThan(args[i]))
603
+ return args[i + 1];
604
+ }
605
+ return args[args.length - 1]; // default
606
+ }
607
+ case "clamp":
608
+ if (args.length !== 3)
609
+ throw new ExpressionError("clamp() requires exactly 3 arguments: clamp(x, min, max)");
610
+ return Decimal.max(args[1], Decimal.min(args[0], args[2]));
611
+ case "percentile": {
612
+ if (args.length < 2)
613
+ throw new ExpressionError("percentile() requires at least 2 arguments (p, v1, [v2, ...])");
614
+ const p = args[0];
615
+ if (p.lessThan(0) || p.greaterThan(100))
616
+ throw new ExpressionError("percentile() p must be between 0 and 100");
617
+ const sorted = args.slice(1).sort((a, b) => a.comparedTo(b));
618
+ const n = sorted.length;
619
+ if (n === 1)
620
+ return sorted[0];
621
+ // rank = p/100 * (n - 1); linear interpolation between neighbours.
622
+ const rank = p.dividedBy(100).times(n - 1);
623
+ const lower = rank.floor();
624
+ const lowerIdx = lower.toNumber();
625
+ const upperIdx = Math.min(lowerIdx + 1, n - 1);
626
+ const frac = rank.minus(lower);
627
+ return sorted[lowerIdx].times(ONE.minus(frac)).plus(sorted[upperIdx].times(frac));
628
+ }
629
+ default:
630
+ throw new ExpressionError(`disallowed function: ${node.name}`);
631
+ }
632
+ }
633
+ case "ternary":
634
+ return truthy(evaluateNode(node.cond, vars))
635
+ ? evaluateNode(node.then, vars)
636
+ : evaluateNode(node.else, vars);
637
+ case "comparison": {
638
+ const l = evaluateNode(node.left, vars);
639
+ const r = evaluateNode(node.right, vars);
640
+ switch (node.op) {
641
+ case "==":
642
+ return l.equals(r) ? ONE : ZERO;
643
+ case "!=":
644
+ return l.equals(r) ? ZERO : ONE;
645
+ case "<":
646
+ return l.lessThan(r) ? ONE : ZERO;
647
+ case "<=":
648
+ return l.lessThanOrEqualTo(r) ? ONE : ZERO;
649
+ case ">":
650
+ return l.greaterThan(r) ? ONE : ZERO;
651
+ case ">=":
652
+ return l.greaterThanOrEqualTo(r) ? ONE : ZERO;
653
+ case "in":
654
+ return l.toString().includes(r.toString()) ? ONE : ZERO;
655
+ case "not in":
656
+ return l.toString().includes(r.toString()) ? ZERO : ONE;
657
+ default:
658
+ throw new ExpressionError(`unknown comparison: ${node.op}`);
659
+ }
660
+ }
661
+ case "boolean": {
662
+ const l = evaluateNode(node.left, vars);
663
+ switch (node.op) {
664
+ case "and":
665
+ // H4 fix: return operand (Python short-circuit semantics), not 0/1.
666
+ // (5 and 7) → 7; (0 and 7) → 0; (5 and 0) → 0.
667
+ if (!truthy(l))
668
+ return l;
669
+ return evaluateNode(node.right, vars);
670
+ case "or":
671
+ // (5 or 7) → 5; (0 or 7) → 7; (0 or 0) → 0.
672
+ if (truthy(l))
673
+ return l;
674
+ return evaluateNode(node.right, vars);
675
+ default:
676
+ throw new ExpressionError(`unknown boolean op: ${node.op}`);
677
+ }
678
+ }
679
+ }
680
+ }
681
+ //# sourceMappingURL=expr.js.map