solve-engine 2.20.0 → 2.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/chunk-3LUEJHAC.js +3 -0
  2. package/dist/chunk-3LUEJHAC.js.map +1 -0
  3. package/dist/chunk-4CNYGIND.js +2 -0
  4. package/dist/chunk-4CNYGIND.js.map +1 -0
  5. package/dist/{chunk-DLXG73JZ.js → chunk-4DJJIUQF.js} +2 -2
  6. package/dist/{chunk-DLXG73JZ.js.map → chunk-4DJJIUQF.js.map} +1 -1
  7. package/dist/chunk-4UHAGMER.cjs +3 -0
  8. package/dist/chunk-4UHAGMER.cjs.map +1 -0
  9. package/dist/chunk-A5M4QZIK.js +2 -0
  10. package/dist/chunk-A5M4QZIK.js.map +1 -0
  11. package/dist/{chunk-BB5RRSGS.js → chunk-AF7HQN6I.js} +2 -2
  12. package/dist/{chunk-BB5RRSGS.js.map → chunk-AF7HQN6I.js.map} +1 -1
  13. package/dist/{chunk-TLNKERM6.js → chunk-AHPBZTW6.js} +2 -2
  14. package/dist/{chunk-TLNKERM6.js.map → chunk-AHPBZTW6.js.map} +1 -1
  15. package/dist/chunk-ALY4ZMYO.js +2 -0
  16. package/dist/{chunk-YBKMCGJ3.js.map → chunk-ALY4ZMYO.js.map} +1 -1
  17. package/dist/{chunk-6NXOKM2O.js → chunk-CHVGFTO3.js} +2 -2
  18. package/dist/{chunk-6NXOKM2O.js.map → chunk-CHVGFTO3.js.map} +1 -1
  19. package/dist/{chunk-Y6QP576X.js → chunk-DCNGKGOZ.js} +3 -3
  20. package/dist/{chunk-Y6QP576X.js.map → chunk-DCNGKGOZ.js.map} +1 -1
  21. package/dist/{chunk-XB3TWS7J.cjs → chunk-EZKR44MA.cjs} +2 -2
  22. package/dist/chunk-EZKR44MA.cjs.map +1 -0
  23. package/dist/{chunk-6EPJNHSQ.js → chunk-FP6Z6PYR.js} +2 -2
  24. package/dist/{chunk-6EPJNHSQ.js.map → chunk-FP6Z6PYR.js.map} +1 -1
  25. package/dist/{chunk-WOGCCIKZ.js → chunk-GF3Z6DDF.js} +3 -3
  26. package/dist/{chunk-WOGCCIKZ.js.map → chunk-GF3Z6DDF.js.map} +1 -1
  27. package/dist/{chunk-CDIHV3ZS.js → chunk-HMC7FJO7.js} +2 -2
  28. package/dist/{chunk-CDIHV3ZS.js.map → chunk-HMC7FJO7.js.map} +1 -1
  29. package/dist/{chunk-KQQWHGCN.cjs → chunk-IFGF26F4.cjs} +2 -2
  30. package/dist/{chunk-KQQWHGCN.cjs.map → chunk-IFGF26F4.cjs.map} +1 -1
  31. package/dist/{chunk-IXOE2BQG.cjs → chunk-J4LSAHCY.cjs} +2 -2
  32. package/dist/{chunk-IXOE2BQG.cjs.map → chunk-J4LSAHCY.cjs.map} +1 -1
  33. package/dist/{chunk-TM752D4J.cjs → chunk-KRXO3MOW.cjs} +2 -2
  34. package/dist/{chunk-TM752D4J.cjs.map → chunk-KRXO3MOW.cjs.map} +1 -1
  35. package/dist/{chunk-DGAFTYOC.cjs → chunk-LZAW6QB3.cjs} +4 -4
  36. package/dist/{chunk-DGAFTYOC.cjs.map → chunk-LZAW6QB3.cjs.map} +1 -1
  37. package/dist/{chunk-53JLDRXA.cjs → chunk-N37PUZJR.cjs} +2 -2
  38. package/dist/{chunk-53JLDRXA.cjs.map → chunk-N37PUZJR.cjs.map} +1 -1
  39. package/dist/{chunk-6CFYMI6C.cjs → chunk-ORZLXBDK.cjs} +3 -3
  40. package/dist/{chunk-6CFYMI6C.cjs.map → chunk-ORZLXBDK.cjs.map} +1 -1
  41. package/dist/{chunk-MDLR2PWN.js → chunk-PRSXXDTA.js} +2 -2
  42. package/dist/chunk-PRSXXDTA.js.map +1 -0
  43. package/dist/{chunk-KLPKLTJZ.cjs → chunk-SGIDBZ4T.cjs} +2 -2
  44. package/dist/{chunk-KLPKLTJZ.cjs.map → chunk-SGIDBZ4T.cjs.map} +1 -1
  45. package/dist/{chunk-QD2Z5TDD.cjs → chunk-UNKSCVIL.cjs} +2 -2
  46. package/dist/{chunk-QD2Z5TDD.cjs.map → chunk-UNKSCVIL.cjs.map} +1 -1
  47. package/dist/{chunk-EAB6SSAV.cjs → chunk-USQ4KL6S.cjs} +2 -2
  48. package/dist/{chunk-EAB6SSAV.cjs.map → chunk-USQ4KL6S.cjs.map} +1 -1
  49. package/dist/chunk-XDXIPVZB.cjs +2 -0
  50. package/dist/chunk-XDXIPVZB.cjs.map +1 -0
  51. package/dist/chunk-ZKFCKAIX.cjs +2 -0
  52. package/dist/chunk-ZKFCKAIX.cjs.map +1 -0
  53. package/dist/constants.cjs +1 -1
  54. package/dist/constants.js +1 -1
  55. package/dist/engine.cjs +1 -1
  56. package/dist/engine.js +1 -1
  57. package/dist/index.cjs +1 -1
  58. package/dist/index.js +1 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/language.cjs +1 -1
  61. package/dist/language.js +1 -1
  62. package/dist/lexer.cjs +1 -1
  63. package/dist/lexer.js +1 -1
  64. package/dist/normalizer.cjs +1 -1
  65. package/dist/normalizer.js +1 -1
  66. package/dist/packages.cjs +1 -1
  67. package/dist/packages.d.cts +47 -1
  68. package/dist/packages.d.ts +47 -1
  69. package/dist/packages.js +1 -1
  70. package/dist/testing.cjs +2 -2
  71. package/dist/testing.js +1 -1
  72. package/dist/uom.cjs +1 -1
  73. package/dist/uom.js +1 -1
  74. package/dist/vm.cjs +1 -1
  75. package/dist/vm.js +1 -1
  76. package/dist/worker.cjs +2 -2
  77. package/dist/worker.js +1 -1
  78. package/dist/worker.js.map +1 -1
  79. package/package.json +1 -1
  80. package/dist/chunk-3AES5ZGS.cjs +0 -3
  81. package/dist/chunk-3AES5ZGS.cjs.map +0 -1
  82. package/dist/chunk-6YGRMAQR.js +0 -2
  83. package/dist/chunk-6YGRMAQR.js.map +0 -1
  84. package/dist/chunk-7WX33WM2.js +0 -3
  85. package/dist/chunk-7WX33WM2.js.map +0 -1
  86. package/dist/chunk-BVSATTRX.cjs +0 -2
  87. package/dist/chunk-BVSATTRX.cjs.map +0 -1
  88. package/dist/chunk-HCPZRSHR.cjs +0 -2
  89. package/dist/chunk-HCPZRSHR.cjs.map +0 -1
  90. package/dist/chunk-JMYBZ6JF.js +0 -2
  91. package/dist/chunk-JMYBZ6JF.js.map +0 -1
  92. package/dist/chunk-MDLR2PWN.js.map +0 -1
  93. package/dist/chunk-XB3TWS7J.cjs.map +0 -1
  94. package/dist/chunk-YBKMCGJ3.js +0 -2
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkEZKR44MA_cjs=require('./chunk-EZKR44MA.cjs');var y=new Map(Object.entries(chunkEZKR44MA_cjs.a)),I=new Map(Object.entries(chunkEZKR44MA_cjs.b));function c(n){return y.get(n)}function b(n,e,t){let r=y.get(e);if(r===void 0)throw new RangeError(`${e} is not a valid unit`);let i=y.get(t);if(i===void 0)throw new RangeError(`${t} is not a valid unit`);return M(n,e,t,r,i)}function M(n,e,t,r,i){let s=r,o=i;if(s[0]!==o[0])throw new RangeError(`Cannot convert between different measures: ${e} and ${t}`);let u=s[1],a=o[1],l=I.get(e),g=I.get(t);return l!==void 0?g!==void 0?(n+l)*(u/a)-g:(n+l)*(u/a):g!==void 0?n*(u/a)-g:n*(u/a)}function O(n,e){let t=y.get(e);if(t===void 0)throw new RangeError(`${e} is not a valid unit`);let r=chunkEZKR44MA_cjs.c[t[0]],i=r[0][0],s=i,o=b(n,e,i),u=o<0?-o:o;for(let a=0;a<r.length;a++){let l=r[a];if(u>=l[1])s=l[0];else break}return {quantity:b(n,e,s),unit:s}}var k=new Set(["workday","workdays"]),S=7/5;function m(n){return typeof n=="string"&&k.has(n)}function P(n){return n}function f(n){if(m(n))return f("day");let e=chunkEZKR44MA_cjs.f[n];if(e)return e.measure;let t=c(n);if(t!==void 0)return chunkEZKR44MA_cjs.e[t[0]]}function Y(n,e){if(n===e)return true;if(m(n)||m(e)){let o=f(n),u=f(e);return !!o&&o===u}let t=c(n),r=c(e);if(t!==void 0&&r!==void 0)return t[0]===r[0];let i=chunkEZKR44MA_cjs.f[n],s=chunkEZKR44MA_cjs.f[e];return i!==void 0&&s!==void 0?i.measure===s.measure:U(n,e)||U(e,n)}function U(n,e){let t=chunkEZKR44MA_cjs.f[n];if(t===void 0)return false;let r=c(e);return r===void 0?false:chunkEZKR44MA_cjs.e[r[0]]===t.measure}function p(n,e,t){if(e===t)return n;let r=c(e),i=c(t);if(r!==void 0&&i!==void 0)return M(n,e,t,r,i);if(m(e)&&m(t))return n;if(m(e)){let u=n*S;return t==="day"?u:p(u,"day",t)}if(m(t))return (e==="day"?n:p(n,e,"day"))/S;let s=chunkEZKR44MA_cjs.f[e],o=chunkEZKR44MA_cjs.f[t];return s!==void 0&&o!==void 0?n*(s.toBase/o.toBase):s!==void 0&&U(e,t)?b(n*s.toBase,A(t),t):o!==void 0&&U(t,e)?b(n,e,A(e))/o.toBase:b(n,e,t)}function A(n){let e=c(n);if(e===void 0)return n;for(let t of Object.keys(chunkEZKR44MA_cjs.a)){let r=chunkEZKR44MA_cjs.a[t];if(r[0]===e[0]&&r[1]===1)return t}return n}function j(n){let e=n,t=c(e);if(t===void 0)return [];let r=chunkEZKR44MA_cjs.d[t[0]];return r?r.filter(i=>i!==e):[]}function W(n){return m(n)||chunkEZKR44MA_cjs.f[n]?true:c(n)!==void 0}function Q(n,e){let t=e;try{let r=O(n,t);return {value:r.quantity,unit:r.unit}}catch{return {value:n,unit:t}}}var D={mpg:{numerator:"km",denominator:"l",factor:1.609344/3.785411784},kmpl:{numerator:"km",denominator:"l",factor:1},l100km:{numerator:"l",denominator:"km",factor:.01}};function N(n,e){let t=D[e];if(t!==void 0)return {value:n*t.factor,numerator:t.numerator,denominator:t.denominator};let r=e.indexOf("/");if(r>=0)return {value:n,numerator:e.slice(0,r),denominator:e.slice(r+1)};let i=chunkEZKR44MA_cjs.f[e];return i!==void 0&&i.measure==="speed"?{value:n*i.toBase,numerator:"m",denominator:"s"}:i!==void 0&&i.measure==="dataRate"?{value:n*i.toBase,numerator:"b",denominator:"s"}:null}function q(n){if(n===void 0)return false;let e=N(1,n);if(e===null||f(e.denominator)!=="time")return false;let t=f(e.numerator);return t==="length"||t==="data"}function X(n,e,t,r){let i=N(t,r);if(i===null||f(i.denominator)!=="time"||f(e)!==f(i.numerator))return null;let o=p(n,e,i.numerator)/i.value;return p(o,i.denominator,"s")}function R(n,e){if(n===e)return 1;if(n===""||e==="")return null;let t=f(n),r=f(e);return t===void 0||r===void 0||t!==r?null:p(1,n,e)}function z(n,e,t){let r=N(n,e);if(r===null)return null;let i,s,o,u=D[t],a=t.indexOf("/");if(u!==void 0)i=u.numerator,s=u.denominator,o=u.factor;else if(a>=0)i=t.slice(0,a),s=t.slice(a+1),o=1;else {let x=chunkEZKR44MA_cjs.f[t];if(x===void 0||x.measure!=="speed")return null;i="m",s="s",o=x.toBase;}let l=R(r.numerator,i),g=R(r.denominator,s);if(l!==null&&g!==null)return r.value*l/g/o;let _=R(r.denominator,i),v=R(r.numerator,s);return _!==null&&v!==null&&r.value!==0?_/v/r.value/o:null}exports.a=m;exports.b=P;exports.c=f;exports.d=Y;exports.e=p;exports.f=j;exports.g=W;exports.h=Q;exports.i=q;exports.j=X;exports.k=z;//# sourceMappingURL=chunk-ZKFCKAIX.cjs.map
2
+ //# sourceMappingURL=chunk-ZKFCKAIX.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/uom/UnitConversion.ts","../src/uom/UomConverter.ts"],"names":["UNIT_LOOKUP","UNIT_TABLE","DIFFERENCE_LOOKUP","UNIT_DIFFERENCES","lookupUnit","unit","convertRaw","quantity","from","to","parsedFrom","parsedTo","convertResolved","fromEntry","toEntry","fromRatio","toRatio","fromDifference","toDifference","convertToBestMetric","best","BEST_UNITS_METRIC","smallestUnit","bestUnit","baseQuantity","absQuantity","i","bestEntry","WORKDAY_UNIT_NAMES","WORKDAY_TO_DAY_FACTOR","isWorkdayUnit","resolveUnit","getMeasure","extended","EXTENDED_UNITS","entry","MEASURE_KIND_NAMES","canConvert","fromMeasure","toMeasure","fromExtended","toExtended","bridgesToBaseMeasure","extendedUnit","baseUnit","base","convertUnit","value","days","fExt","tExt","baseUnitFor","symbol","candidate","getConvertiblePossibilities","resolved","symbols","MEASURE_SYMBOLS","s","isConvertibleUnit","getBestUnit","u","result","FUEL_RATE_UNITS","expandUnitToRate","fuel","slash","ext","isPhysicalTimeRate","rate","numeratorMeasure","quantityAtRateSeconds","quantityUnit","rateValue","rateUnit","timeInDenominator","rateAxisFactor","convertRate","source","targetNumerator","targetDenominator","targetScale","fuelTarget","numeratorFactor","denominatorFactor","crossNumerator","crossDenominator"],"mappings":"mEAmCA,IAAMA,CAAAA,CAA8C,IAAI,GAAA,CAAI,MAAA,CAAO,OAAA,CAAQC,mBAAU,CAAC,CAAA,CAShFC,CAAAA,CAAiD,IAAI,GAAA,CAAI,MAAA,CAAO,OAAA,CAAQC,mBAAgB,CAAC,CAAA,CAgBxF,SAASC,CAAAA,CAAWC,CAAAA,CAAqC,CAC9D,OAAOL,CAAAA,CAAY,GAAA,CAAIK,CAAI,CAC7B,CAWO,SAASC,CAAAA,CAAWC,CAAAA,CAAkBC,CAAAA,CAAcC,CAAAA,CAAoB,CAC7E,IAAMC,CAAAA,CAAaV,CAAAA,CAAY,GAAA,CAAIQ,CAAI,CAAA,CACvC,GAAIE,CAAAA,GAAe,MAAA,CACjB,MAAM,IAAI,UAAA,CAAW,CAAA,EAAGF,CAAI,CAAA,oBAAA,CAAsB,CAAA,CAGpD,IAAMG,CAAAA,CAAWX,CAAAA,CAAY,GAAA,CAAIS,CAAE,CAAA,CACnC,GAAIE,CAAAA,GAAa,MAAA,CACf,MAAM,IAAI,UAAA,CAAW,GAAGF,CAAE,CAAA,oBAAA,CAAsB,CAAA,CAGlD,OAAOG,CAAAA,CAAgBL,CAAAA,CAAUC,CAAAA,CAAMC,CAAAA,CAAIC,CAAAA,CAAYC,CAAQ,CACjE,CAWO,SAASC,CAAAA,CACdL,CA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A,CAAiBC,CAAAA,CAAmBR,CAAAA,CAAO,KAAA,CAASG,EAGvD,IACT","file":"chunk-ZKFCKAIX.cjs","sourcesContent":["/**\n * The unit conversion algorithm, ported from the `convert` npm package v7.0.2\n * alongside its tables (see `generated/UnitTable.generated.ts` and\n * THIRD-PARTY-NOTICES.md).\n *\n * Transliterated expression for expression rather than rewritten. Floating\n * point is not associative, so `(q + d) * (a / b) - d2` and any algebraically\n * equal rearrangement disagree in the last bits. Those bits are observable:\n * `0.5 l` best-converts to `500.00000000000006 mL` today, and the test suite\n * pins several conversions to ten decimal places.\n *\n * This module is deliberately unaware of the engine's own additions. Workdays,\n * extended units, currency and the caches all live in `UomConverter.ts`, which\n * layers them on top of these three functions.\n */\n\nimport {\n UNIT_TABLE,\n UNIT_DIFFERENCES,\n BEST_UNITS_METRIC,\n type UnitEntry,\n} from \"./generated/UnitTable.generated\";\n\n/**\n * The generated tables re-keyed into Maps once at module load.\n *\n * Not a micro-optimization. A 1456-key object literal lands in V8's dictionary\n * mode, and guarding a read on it against inherited names (`constructor`,\n * `toString`) costs about 123ns per call with either `hasOwnProperty.call` or\n * `Object.hasOwn`, measured. `Map.get` is about 6ns and needs no guard at all,\n * because a Map has no prototype chain to fall through to. That is a 20x\n * difference on the single hottest operation in the unit system: `convertRaw`\n * performs two of these per call, and `LanguageService` sweeps all 1456 keys\n * to build completions.\n */\nconst UNIT_LOOKUP: ReadonlyMap<string, UnitEntry> = new Map(Object.entries(UNIT_TABLE));\n\n/**\n * Temperature offsets, as a Map for the same reason.\n *\n * Also removes a latent hazard: the upstream code tests membership with `in`,\n * and `\"toString\" in UNIT_DIFFERENCES` is true, so an inherited name reaching\n * that branch would add a function to a number.\n */\nconst DIFFERENCE_LOOKUP: ReadonlyMap<string, number> = new Map(Object.entries(UNIT_DIFFERENCES));\n\n/**\n * Looks up a unit spelling.\n *\n * @returns its `[kind, ratio]` entry, or `undefined` if the spelling is not a\n * unit. Case-sensitive: no normalization or aliasing happens anywhere in this\n * module.\n *\n * The one deliberate deviation from upstream. `convert` tests membership with\n * `in` and reads the property directly, so inherited names like \"constructor\"\n * and \"toString\" reach its measure comparison and fail there with \"Cannot\n * convert between different measures\" instead of \"is not a valid unit\". Both\n * throw a RangeError and both report no measure, so nothing downstream can\n * tell the difference, and naming the real problem is the better message.\n */\nexport function lookupUnit(unit: string): UnitEntry | undefined {\n return UNIT_LOOKUP.get(unit);\n}\n\n/**\n * Converts `quantity` from one unit to another.\n *\n * THROWS a `RangeError` for an unknown unit or a pair in different measures.\n * Callers depend on that: `VM.ts`'s `extractDurationMs()` calls this with an\n * arbitrary unit inside a bare try/catch and treats the throw as \"not a\n * duration, contribute zero\". Returning NaN or the input unchanged instead\n * would turn `<date> + 5 kg` into an Invalid Date rather than a no-op.\n */\nexport function convertRaw(quantity: number, from: string, to: string): number {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const parsedTo = UNIT_LOOKUP.get(to);\n if (parsedTo === undefined) {\n throw new RangeError(`${to} is not a valid unit`);\n }\n\n return convertResolved(quantity, from, to, parsedFrom, parsedTo);\n}\n\n/**\n * The conversion arithmetic, for callers that have already looked both units\n * up and want to skip doing it twice.\n *\n * Split out for `UomConverter.convertUnit()`, which has to check whether\n * either side is a workday or an extended unit before it can dispatch, and\n * would otherwise resolve each unit once to decide and again to convert. The\n * entries MUST be the ones this module returned for these exact spellings.\n */\nexport function convertResolved(\n quantity: number,\n from: string,\n to: string,\n fromEntry: UnitEntry,\n toEntry: UnitEntry\n): number {\n const parsedFrom = fromEntry;\n const parsedTo = toEntry;\n\n if (parsedFrom[0] !== parsedTo[0]) {\n // DELIBERATE DEVIATION from the ported original, which silently reinterpreted\n // \"m\" as minutes whenever the other side was a time unit. That is a guess,\n // and this project's stated position is that refusing to guess is the safer\n // default for a tool doing arithmetic on someone's real numbers (see\n // docs/architecture/design-decisions.md). The guess was not harmless: it\n // reached `<date> + <duration>` through VM.ts's extractDurationMs(), where\n // `today + 5 m` silently added five MINUTES for someone who wrote metres.\n //\n // Minutes are spelled \"min\", \"minute\" or \"minutes\", all of which the table\n // has always accepted.\n throw new RangeError(`Cannot convert between different measures: ${from} and ${to}`);\n }\n\n const fromRatio = parsedFrom[1];\n const toRatio = parsedTo[1];\n\n // Only six units in the whole table carry an offset, so the common path is\n // both misses. Reading the Map once per side and reusing the value beats\n // testing membership and then reading it again.\n const fromDifference = DIFFERENCE_LOOKUP.get(from);\n const toDifference = DIFFERENCE_LOOKUP.get(to);\n\n // Scales that do not share an origin (temperature) need the offset applied\n // around the ratio. Do not refactor the four branches into one expression:\n // the grouping is what makes the result bit-identical to the original.\n if (fromDifference !== undefined) {\n if (toDifference !== undefined) {\n return (quantity + fromDifference) * (fromRatio / toRatio) - toDifference;\n }\n return (quantity + fromDifference) * (fromRatio / toRatio);\n }\n\n if (toDifference !== undefined) {\n return quantity * (fromRatio / toRatio) - toDifference;\n }\n\n return quantity * (fromRatio / toRatio);\n}\n\n/**\n * Picks the most readable metric unit for a magnitude and converts to it.\n *\n * Only the metric lists are ported; nothing has ever requested the imperial\n * ones. Note the final conversion goes from the ORIGINAL unit to the chosen\n * one directly rather than via the smallest unit, which is what keeps the\n * result exact.\n */\nexport function convertToBestMetric(\n quantity: number,\n from: string\n): { quantity: number; unit: string } {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const best = BEST_UNITS_METRIC[parsedFrom[0]];\n const smallestUnit = best[0][0];\n let bestUnit = smallestUnit;\n\n const baseQuantity = convertRaw(quantity, from, smallestUnit);\n const absQuantity = baseQuantity < 0 ? -baseQuantity : baseQuantity;\n\n // Thresholds are expressed in the smallest unit and ascend, so the last one\n // the magnitude reaches wins. Breaking early rather than scanning the whole\n // list matters for zero and for negatives, which stay on the smallest unit.\n for (let i = 0; i < best.length; i++) {\n const bestEntry = best[i];\n if (absQuantity >= bestEntry[1]) {\n bestUnit = bestEntry[0];\n } else {\n break;\n }\n }\n\n return { quantity: convertRaw(quantity, from, bestUnit), unit: bestUnit };\n}\n","/**\n * UoM Converter, built on the in-house unit tables in `UnitConversion.ts` and\n * `generated/UnitTable.generated.ts` (ported from the `convert` npm package\n * v7.0.2 so the engine ships with no runtime dependencies).\n *\n * Units are strictly case-sensitive and are looked up without aliasing. No unit\n * remapping, what you type is what you get.\n * e.g. 'C' = Celsius, 'c' = cup; 'MB' = megabytes, 'mb' = millibits.\n *\n * This file owns everything the base tables do not: the workday shim, the\n * extended (custom-measure) units, and the two caches.\n */\n\nimport { lookupUnit, convertRaw, convertResolved, convertToBestMetric } from \"@solve-js/uom/UnitConversion\";\nimport { MEASURE_KIND_NAMES, MEASURE_SYMBOLS, UNIT_TABLE } from \"@solve-js/uom/generated/UnitTable.generated\";\nimport { EXTENDED_UNITS } from \"@solve-js/uom/ExtendedUnits\";\n\n// ── \"workday\", a synthetic unit with no entry in the base table ───────────\n//\n// A business day (Mon-Fri) backing the datetime package's `<date> + N\n// workdays` arithmetic and `$X/workday` Rate literals\n// (packages/datetime/). NOT a real physical unit, a business day has no\n// fixed duration, since it depends on which calendar dates are weekends\n// so the ported base table has no concept of it and can't be\n// taught one without monkey-patching its internal unit table.\n//\n// For RATE-MATH purposes only (e.g. \"$500/workday x 4 weeks\" needs a\n// workday count to multiply by), a workday is treated as a FIXED 7/5 of a\n// calendar day: 5 workdays span exactly 7 calendar days in a whole week,\n// so this ratio is exact for whole-week spans and a reasonable linear\n// approximation otherwise. This is deliberately NOT the same\n// calendar-aware, weekend-skipping logic real \"<date> + N workdays\" date\n// arithmetic needs (see vm/VM.ts's addBusinessDays()), that can't be\n// reduced to a fixed ratio, since the exact skip pattern depends on which\n// day of the week the calculation actually starts from.\n//\n// Handled here as a thin pre/post layer in front of the normal\n// base-table path (rather than inside the tables themselves) so every\n// caller of getMeasure()/convertUnit()/canConvert() automatically gets\n// workday support for free.\nconst WORKDAY_UNIT_NAMES = new Set([\"workday\", \"workdays\"]);\nconst WORKDAY_TO_DAY_FACTOR = 7 / 5; // 1 workday == 1.4 calendar days\n\n/** Whether `unit` is the synthetic \"workday\" unit (see module note above). */\nexport function isWorkdayUnit(unit: string | undefined): unit is string {\n return typeof unit === \"string\" && WORKDAY_UNIT_NAMES.has(unit);\n}\n\n/**\n * Validate `unit` against the known unit table.\n *\n * @returns `unit` unchanged in all cases. This does NOT normalize casing\n * or aliasing (units are strictly case-sensitive, see the module note\n * above). A unit the table doesn't recognize is still\n * returned as-is (not thrown), so callers must not assume a returned\n * string is actually convertible, check with {@link isConvertibleUnit}\n * or {@link canConvert} first if that matters.\n *\n * Kept as an identity function purely for API compatibility. It used to guard\n * a validity cache, which existed because validating a unit meant a\n * throw/catch round trip through the old dependency. Validation is now a Map\n * lookup, so the cache cost more than it saved: worse, it was capped at 1000\n * entries against a 1456-unit table, so any sweep over the full vocabulary\n * (which is exactly what LanguageService does to build completions) evicted\n * on almost every call. That one change took the full-table sweep from 7.7ms\n * to under 20us.\n */\nexport function resolveUnit(unit: string): string {\n return unit;\n}\n\n// MEASURE_KIND_NAMES now comes from the generated table (it is derived data,\n// so the generator emits it rather than it being retyped here). The reason it\n// is a module-level constant has not changed: getMeasure() runs at least twice\n// per conversion, and this used to be reallocated on every call.\n\n/**\n * Get the measure/dimension kind for `unit` (e.g. `\"length\"`, `\"mass\"`,\n * `\"temperature\"`), used to check whether two units are even in the same\n * dimension before attempting a conversion.\n *\n * @returns `undefined` if `unit` isn't recognized, rather than throwing.\n */\nexport function getMeasure(unit: string): string | undefined {\n // Workday is a Time-measure unit by convention (see isWorkdayUnit's doc\n // comment) and is not in the base table, so resolve its measure via \"day\"\n // instead of attempting the real lookup below.\n if (isWorkdayUnit(unit)) return getMeasure(\"day\");\n\n // Extended (custom) categories the base table has no measure kind for,\n // see ExtendedUnits.ts.\n const extended = EXTENDED_UNITS[unit];\n if (extended) return extended.measure;\n\n const entry = lookupUnit(unit);\n if (entry === undefined) return undefined;\n\n return MEASURE_KIND_NAMES[entry[0]];\n}\n\n/**\n * Check whether `from` can be converted to `to`. Same unit, or same\n * measure kind (length, mass, ...) and the underlying tables accept the pair.\n * Never throws; returns `false` on any failure.\n */\nexport function canConvert(from: string, to: string): boolean {\n if (from === to) return true;\n if (isWorkdayUnit(from) || isWorkdayUnit(to)) {\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n return !!fromMeasure && fromMeasure === toMeasure;\n }\n // One table read per side, comparing numeric kind ids. The old shape called\n // getMeasure() on each side (two more reads) purely to compare the resulting\n // STRINGS, then did a throwaway conversion to confirm what the kind check had\n // already established.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return fromEntry[0] === toEntry[0];\n }\n\n // Extended (custom) categories aren't in the base table at all, so they are\n // compared on their own measure names instead.\n const fromExtended = EXTENDED_UNITS[from];\n const toExtended = EXTENDED_UNITS[to];\n if (fromExtended !== undefined && toExtended !== undefined) {\n return fromExtended.measure === toExtended.measure;\n }\n\n // Mixed: one side is in the base table and the other is extended. That used\n // to be refused outright, on the grounds that the two measure spaces are\n // disjoint. They are not, once an extended unit names a measure the base\n // table also has: `furlong` is a length and so is `m`, and the ratio between\n // them is exactly what both tables already record.\n return bridgesToBaseMeasure(from, to) || bridgesToBaseMeasure(to, from);\n}\n\n/**\n * Whether `extendedUnit` extends a measure the base table also knows, so a\n * value in it can reach `baseUnit`.\n *\n * The bridge works because both tables express a unit as a ratio to the same\n * physical base: the generated table's length ratios are metres and its mass\n * ratios are grams, and an extended unit declaring `measure: \"length\"` states\n * its `toBase` in the same metres. Composing the two ratios is then ordinary\n * arithmetic rather than a second conversion system.\n *\n * A measure the base table has no concept of, such as pace, still fails here,\n * which is the behaviour this replaced and the reason the check is by measure\n * name rather than by presence in the extended table.\n */\nfunction bridgesToBaseMeasure(extendedUnit: string, baseUnit: string): boolean {\n const extended = EXTENDED_UNITS[extendedUnit];\n if (extended === undefined) return false;\n\n const base = lookupUnit(resolveUnit(baseUnit));\n if (base === undefined) return false;\n\n return MEASURE_KIND_NAMES[base[0]] === extended.measure;\n}\n\n/**\n * Convert `value` from unit `from` to unit `to`.\n *\n * Does not validate that the conversion is possible, callers should check\n * with {@link canConvert} first if `from`/`to` aren't already known-good.\n *\n * THROWS a RangeError for an unknown unit or a cross-measure pair. `VM.ts`'s\n * `extractDurationMs()` depends on that, see {@link convertRaw}.\n *\n * This used to memoize a per-pair conversion factor in an LFU cache. The cache\n * is gone: computing the factor is now two Map reads, while the cache cost a\n * template-string key allocation on every call plus the LFU's own frequency\n * bookkeeping, so it was slower than the work it avoided. Removing it is\n * bit-exact, not merely close: the cache stored `convertRaw(1, f, t)`, which is\n * exactly `fromRatio / toRatio`, and then multiplied, which is the identical\n * expression `convertRaw(value, f, t)` evaluates. It also deleted the special\n * case that existed only to keep offset-based temperature pairs out of a\n * factor cache.\n */\nexport function convertUnit(value: number, from: string, to: string): number {\n if (from === to) return value;\n\n // Fast path first: two ordinary units, which is nearly every call. Resolving\n // both here and handing the entries to convertResolved() avoids looking them\n // up again inside convertRaw(). Neither workdays nor extended units appear in\n // the base table, so they always fall through to the branches below and this\n // ordering cannot steal a case from them. UnitVocabulary.spec.ts pins that\n // the two vocabularies stay disjoint.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return convertResolved(value, from, to, fromEntry, toEntry);\n }\n\n // Workday <-> any other Time-measure unit: pivot through \"day\" using the\n // fixed 7/5 ratio (see isWorkdayUnit's doc comment above).\n if (isWorkdayUnit(from) && isWorkdayUnit(to)) return value; // \"workday\" <-> \"workdays\" alias\n if (isWorkdayUnit(from)) {\n const days = value * WORKDAY_TO_DAY_FACTOR;\n return to === \"day\" ? days : convertUnit(days, \"day\", to);\n }\n if (isWorkdayUnit(to)) {\n const days = from === \"day\" ? value : convertUnit(value, from, \"day\");\n return days / WORKDAY_TO_DAY_FACTOR;\n }\n\n // Extended (custom) categories the base table has no measure kind for\n // (see ExtendedUnits.ts), compute the ratio directly from each unit's\n // factor-to-base value instead of calling convertRaw(), which would throw\n // on an unrecognized unit string. Every extended category is a pure linear\n // ratio scale (no Temperature-style offset), so this is always safe.\n const fExt = EXTENDED_UNITS[from];\n const tExt = EXTENDED_UNITS[to];\n if (fExt !== undefined && tExt !== undefined) {\n return value * (fExt.toBase / tExt.toBase);\n }\n\n // One side extended, the other in the base table, sharing a measure. Convert\n // through the measure's base unit, which both tables state their ratios\n // against: an extended length declares its `toBase` in metres, and the\n // generated table's length ratios are metres too.\n if (fExt !== undefined && bridgesToBaseMeasure(from, to)) {\n return convertRaw(value * fExt.toBase, baseUnitFor(to), to);\n }\n if (tExt !== undefined && bridgesToBaseMeasure(to, from)) {\n return convertRaw(value, from, baseUnitFor(from)) / tExt.toBase;\n }\n\n // Offsets, cross-measure rejection and the unknown-unit throw all live in\n // convertRaw. Nothing is layered on top here any more.\n return convertRaw(value, from, to);\n}\n\n/**\n * The unit a measure states its ratios against, found from any unit in it.\n *\n * Read out of the table rather than hard-coded, so it cannot drift from the\n * ratios it has to agree with: the base is whichever unit of that measure has\n * a ratio of exactly one.\n */\nfunction baseUnitFor(unit: string): string {\n const entry = lookupUnit(resolveUnit(unit));\n if (entry === undefined) return unit;\n\n for (const symbol of Object.keys(UNIT_TABLE)) {\n const candidate = UNIT_TABLE[symbol];\n if (candidate[0] === entry[0] && candidate[1] === 1) return symbol;\n }\n return unit;\n}\n\n/**\n * List every unit symbol in the same measure/dimension as `unit` (wiki:\n * Units-Of-Measurement, \"Conversion Possibilities\", `sourceUnit to ?`\n * e.g. `cm to ?\"` → every Length unit). Excludes `unit` itself.\n *\n * Reads MEASURE_SYMBOLS, which is a curated symbols-only vocabulary and\n * deliberately NOT the keys of the unit table filtered by kind. The two\n * differ: Volume's symbols include `c` and `pt` but not `cup`/`cups`, and\n * Time's include `wk` and `mo` but not `week`/`month`. Deriving this list\n * from the unit table instead would roughly quadruple every answer.\n *\n * @returns `[]` if `unit` isn't recognized, rather than throwing.\n */\nexport function getConvertiblePossibilities(unit: string): string[] {\n const resolved = resolveUnit(unit);\n const entry = lookupUnit(resolved);\n if (entry === undefined) return [];\n const symbols = MEASURE_SYMBOLS[entry[0]];\n if (!symbols) return [];\n return symbols.filter((s) => s !== resolved);\n}\n\n/** Check whether `unit` is a unit the conversion tables recognize. Never throws. */\nexport function isConvertibleUnit(unit: string): boolean {\n if (isWorkdayUnit(unit)) return true;\n if (EXTENDED_UNITS[unit]) return true;\n return lookupUnit(resolveUnit(unit)) !== undefined;\n}\n\n/**\n * Convert `value` (in `unit`) to whichever unit of the same measure gives\n * the most human-readable magnitude, e.g. 1500 metres becomes 1.5 km. Falls\n * back to returning `value`/`unit` unchanged if `unit` isn't recognized,\n * which is what every extended unit and workday does.\n *\n * Note the chosen unit is drawn from the best-unit lists, which are not\n * restricted to spellings the lexer accepts: 0.5 l reports \"mL\".\n */\nexport function getBestUnit(value: number, unit: string): { value: number; unit: string } {\n const u = resolveUnit(unit);\n try {\n const result = convertToBestMetric(value, u);\n return { value: result.quantity, unit: result.unit };\n } catch {\n return { value, unit: u };\n }\n}\n\n// ── Rate and derived-unit conversion ───────────────────────────────────────\n//\n// A rate value carries a compound unit spelled \"numerator/denominator\" (e.g.\n// \"km/h\", \"m/s\"), see vm/Value.ts's rateValue(). Plain convertUnit() cannot\n// touch one, because neither half is the whole unit and getMeasure(\"km/h\") is\n// undefined. This section converts a rate to another rate, and bridges a rate\n// to the single-token speed spellings (mph, kph, mps, ...) that ExtendedUnits.ts\n// already carries, so \"100 km/h in mph\" and \"60 mph in km/h\" resolve instead of\n// reporting incompatible units.\n\n/** A rate reduced to a numerator unit over a denominator unit. */\ninterface RateForm {\n /** Magnitude, scaled so `value numerator/denominator` is the physical quantity. */\n value: number;\n /** Numerator unit spelling, or `\"\"` for a countless rate such as `30/week`. */\n numerator: string;\n /** Denominator unit spelling. */\n denominator: string;\n}\n\n/**\n * Express `value unit` as a numerator/denominator rate, or `null` when `unit`\n * is neither a compound rate spelling nor a single-token speed alias.\n *\n * A speed alias (mph, kph, ...) is one unit standing for a length/time rate, so\n * it expands to the base pair `m`/`s` with its value scaled by the alias's\n * metres-per-second factor. That collapses both inputs to one shape, so a\n * single routine handles rate/rate and rate/alias without a second code path.\n */\n/**\n * The single-token fuel-economy units, each as the `numerator/denominator` rate\n * it stands for and the factor that turns one of it into that rate's base. `mpg`\n * is `km/l` scaled, `l/100km` is `l/km` scaled by a hundredth (issue #190).\n */\nconst FUEL_RATE_UNITS: Record<string, { numerator: string; denominator: string; factor: number }> = {\n mpg: { numerator: \"km\", denominator: \"l\", factor: 1.609344 / 3.785411784 },\n kmpl: { numerator: \"km\", denominator: \"l\", factor: 1 },\n l100km: { numerator: \"l\", denominator: \"km\", factor: 0.01 },\n};\n\nfunction expandUnitToRate(value: number, unit: string): RateForm | null {\n const fuel = FUEL_RATE_UNITS[unit];\n if (fuel !== undefined) {\n return { value: value * fuel.factor, numerator: fuel.numerator, denominator: fuel.denominator };\n }\n const slash = unit.indexOf(\"/\");\n if (slash >= 0) {\n return { value, numerator: unit.slice(0, slash), denominator: unit.slice(slash + 1) };\n }\n const ext = EXTENDED_UNITS[unit];\n if (ext !== undefined && ext.measure === \"speed\") {\n // 1 alias == ext.toBase m/s, so `value alias` is `value * toBase` m/s.\n return { value: value * ext.toBase, numerator: \"m\", denominator: \"s\" };\n }\n if (ext !== undefined && ext.measure === \"dataRate\") {\n // 1 alias == ext.toBase bits/s, so `value alias` is `value * toBase` b/s.\n return { value: value * ext.toBase, numerator: \"b\", denominator: \"s\" };\n }\n return null;\n}\n\n/**\n * Whether `unit` is a *physical* rate over time, one whose numerator is a length\n * or a data size, so `<quantity> at <unit>` means dividing that quantity by the\n * rate to get a duration: `250 miles at 60 mph`, `4 GB at 50 Mbps`.\n *\n * Deliberately NOT true for a price rate like `$/hour`: those are handled by the\n * existing at-rate builtin, which multiplies or divides against the currency,\n * and must keep their own answer (`$500 at $20/hour` is `25 hours`, formatted\n * that way). The numerator-measure check is what tells the two apart.\n */\nexport function isPhysicalTimeRate(unit: string | undefined): boolean {\n if (unit === undefined) return false;\n const rate = expandUnitToRate(1, unit);\n if (rate === null || getMeasure(rate.denominator) !== \"time\") return false;\n const numeratorMeasure = getMeasure(rate.numerator);\n return numeratorMeasure === \"length\" || numeratorMeasure === \"data\";\n}\n\n/**\n * `<quantity> at <rate>` where `rate` is a {@link isPhysicalTimeRate}, in\n * seconds. The quantity's measure must match the rate's numerator (a distance at\n * a speed, a data size at a bandwidth); otherwise the pair does not line up and\n * this returns null for the caller to report.\n */\nexport function quantityAtRateSeconds(\n quantity: number,\n quantityUnit: string,\n rateValue: number,\n rateUnit: string,\n): number | null {\n const rate = expandUnitToRate(rateValue, rateUnit);\n if (rate === null || getMeasure(rate.denominator) !== \"time\") return null;\n if (getMeasure(quantityUnit) !== getMeasure(rate.numerator)) return null;\n const quantityInNumerator = convertUnit(quantity, quantityUnit, rate.numerator);\n const timeInDenominator = quantityInNumerator / rate.value;\n return convertUnit(timeInDenominator, rate.denominator, \"s\");\n}\n\n/**\n * The factor that turns one `from` into `to` along a single rate axis, or\n * `null` when the two cannot line up.\n *\n * Same spelling needs no conversion. A countless axis (`\"\"`) only lines up with\n * another countless one, never with a real unit. Otherwise both sides must name\n * the same measure, which is what keeps a length numerator from pairing with a\n * mass one.\n */\nfunction rateAxisFactor(from: string, to: string): number | null {\n if (from === to) return 1;\n if (from === \"\" || to === \"\") return null;\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n if (fromMeasure === undefined || toMeasure === undefined || fromMeasure !== toMeasure) {\n return null;\n }\n return convertUnit(1, from, to);\n}\n\n/**\n * Convert `value` from a rate/speed unit `from` to a rate/speed unit `to`,\n * returning the converted magnitude, or `null` when the pair is not\n * rate-convertible (so the caller falls back to its own incompatible-units\n * handling).\n *\n * Handles rate to rate (`10 m/s in km/h`), rate to speed alias\n * (`100 km/h in mph`) and speed alias to rate (`60 mph in km/h`). Plain\n * same-measure pairs (`kph in mph`, `km in miles`) never reach here, they are\n * resolved by {@link convertUnit} first.\n *\n * The rule is the ordinary one for a quotient of quantities: convert the\n * numerator and the denominator each on their own, so `A/B -> C/D` scales by\n * `(A->C) / (B->D)`.\n */\nexport function convertRate(value: number, from: string, to: string): number | null {\n const source = expandUnitToRate(value, from);\n if (source === null) return null;\n\n // The target is either a rate spelling or a single-token speed alias. An\n // alias expands to the base m/s pair, and `targetScale` is what the base-form\n // magnitude is divided by to read out in the alias itself.\n let targetNumerator: string;\n let targetDenominator: string;\n let targetScale: number;\n const fuelTarget = FUEL_RATE_UNITS[to];\n const slash = to.indexOf(\"/\");\n if (fuelTarget !== undefined) {\n // The base-pair magnitude divided by the fuel unit's own factor reads out in\n // that unit (so a l/km magnitude becomes a l/100km figure).\n targetNumerator = fuelTarget.numerator;\n targetDenominator = fuelTarget.denominator;\n targetScale = fuelTarget.factor;\n } else if (slash >= 0) {\n targetNumerator = to.slice(0, slash);\n targetDenominator = to.slice(slash + 1);\n targetScale = 1;\n } else {\n const ext = EXTENDED_UNITS[to];\n if (ext === undefined || ext.measure !== \"speed\") return null;\n targetNumerator = \"m\";\n targetDenominator = \"s\";\n targetScale = ext.toBase;\n }\n\n const numeratorFactor = rateAxisFactor(source.numerator, targetNumerator);\n const denominatorFactor = rateAxisFactor(source.denominator, targetDenominator);\n if (numeratorFactor !== null && denominatorFactor !== null) {\n return (source.value * numeratorFactor) / denominatorFactor / targetScale;\n }\n\n // A reciprocal pairing: distance-per-volume against volume-per-distance, the\n // fuel-economy case (miles per gallon to litres per kilometre). The two rates\n // measure the same thing upside down, so the source's numerator lines up with\n // the target's denominator and its denominator with the target's numerator,\n // and the magnitude is inverted. `40 miles/gallon` becomes `0.0588 l/km`:\n // one over forty, scaled gallon-to-litre over mile-to-kilometre. See issue\n // #190; this is why fuel economy needs its own route and is not a rescale of\n // each axis like `mph` to `km/h`.\n const crossNumerator = rateAxisFactor(source.denominator, targetNumerator);\n const crossDenominator = rateAxisFactor(source.numerator, targetDenominator);\n if (crossNumerator !== null && crossDenominator !== null && source.value !== 0) {\n return (crossNumerator / crossDenominator / source.value) / targetScale;\n }\n\n return null;\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkKQQWHGCN_cjs=require('./chunk-KQQWHGCN.cjs');require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"ConfigManager",{enumerable:true,get:function(){return chunkKQQWHGCN_cjs.d}});Object.defineProperty(exports,"DEFAULT_CONFIG",{enumerable:true,get:function(){return chunkKQQWHGCN_cjs.b}});Object.defineProperty(exports,"ENGINE_VERSION",{enumerable:true,get:function(){return chunkKQQWHGCN_cjs.a}});//# sourceMappingURL=constants.cjs.map
1
+ 'use strict';var chunkIFGF26F4_cjs=require('./chunk-IFGF26F4.cjs');require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"ConfigManager",{enumerable:true,get:function(){return chunkIFGF26F4_cjs.d}});Object.defineProperty(exports,"DEFAULT_CONFIG",{enumerable:true,get:function(){return chunkIFGF26F4_cjs.b}});Object.defineProperty(exports,"ENGINE_VERSION",{enumerable:true,get:function(){return chunkIFGF26F4_cjs.a}});//# sourceMappingURL=constants.cjs.map
2
2
  //# sourceMappingURL=constants.cjs.map
package/dist/constants.js CHANGED
@@ -1,2 +1,2 @@
1
- export{d as ConfigManager,b as DEFAULT_CONFIG,a as ENGINE_VERSION}from'./chunk-TLNKERM6.js';import'./chunk-PIZQIQVM.js';//# sourceMappingURL=constants.js.map
1
+ export{d as ConfigManager,b as DEFAULT_CONFIG,a as ENGINE_VERSION}from'./chunk-AHPBZTW6.js';import'./chunk-PIZQIQVM.js';//# sourceMappingURL=constants.js.map
2
2
  //# sourceMappingURL=constants.js.map
package/dist/engine.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk6CFYMI6C_cjs=require('./chunk-6CFYMI6C.cjs');require('./chunk-EFJCC6FJ.cjs');var chunkDGAFTYOC_cjs=require('./chunk-DGAFTYOC.cjs');require('./chunk-JYLNQOPU.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-LNZNJSRW.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-QD2Z5TDD.cjs'),require('./chunk-HG4NPDN5.cjs'),require('./chunk-H3JXNH7X.cjs'),require('./chunk-R2SZFJTT.cjs'),require('./chunk-53JLDRXA.cjs'),require('./chunk-EN3CDYOS.cjs'),require('./chunk-KLPKLTJZ.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-HCPZRSHR.cjs'),require('./chunk-6YM67DWH.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-J7ABVGZH.cjs'),require('./chunk-75JLWK4L.cjs'),require('./chunk-BVSATTRX.cjs'),require('./chunk-KQQWHGCN.cjs'),require('./chunk-TM752D4J.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-EAB6SSAV.cjs'),require('./chunk-5IJD5L3O.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-IXOE2BQG.cjs'),require('./chunk-XB3TWS7J.cjs'),require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"DocumentModel",{enumerable:true,get:function(){return chunk6CFYMI6C_cjs.a}});Object.defineProperty(exports,"EvalTier",{enumerable:true,get:function(){return chunk6CFYMI6C_cjs.b}});Object.defineProperty(exports,"ThreeTierEvaluator",{enumerable:true,get:function(){return chunk6CFYMI6C_cjs.c}});Object.defineProperty(exports,"evaluateDocument",{enumerable:true,get:function(){return chunk6CFYMI6C_cjs.d}});Object.defineProperty(exports,"AsyncResolutionBatcher",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.h}});Object.defineProperty(exports,"ExpressionEngine",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.n}});Object.defineProperty(exports,"SNAPSHOT_FORMAT",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.d}});Object.defineProperty(exports,"SNAPSHOT_VERSION",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.e}});Object.defineProperty(exports,"SnapshotErrorCodes",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.f}});Object.defineProperty(exports,"checkExpressionComplexity",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.j}});Object.defineProperty(exports,"checkExpressionLength",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.i}});Object.defineProperty(exports,"extractReadsAndWrites",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.k}});Object.defineProperty(exports,"findInlineSolvesInLine",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.m}});Object.defineProperty(exports,"isEmptyLine",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.l}});//# sourceMappingURL=engine.cjs.map
1
+ 'use strict';var chunkORZLXBDK_cjs=require('./chunk-ORZLXBDK.cjs');require('./chunk-EFJCC6FJ.cjs');var chunkLZAW6QB3_cjs=require('./chunk-LZAW6QB3.cjs');require('./chunk-JYLNQOPU.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-LNZNJSRW.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-UNKSCVIL.cjs'),require('./chunk-HG4NPDN5.cjs'),require('./chunk-H3JXNH7X.cjs'),require('./chunk-R2SZFJTT.cjs'),require('./chunk-N37PUZJR.cjs'),require('./chunk-EN3CDYOS.cjs'),require('./chunk-SGIDBZ4T.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-XDXIPVZB.cjs'),require('./chunk-6YM67DWH.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-J7ABVGZH.cjs'),require('./chunk-75JLWK4L.cjs'),require('./chunk-ZKFCKAIX.cjs'),require('./chunk-IFGF26F4.cjs'),require('./chunk-KRXO3MOW.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-USQ4KL6S.cjs'),require('./chunk-5IJD5L3O.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs'),require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"DocumentModel",{enumerable:true,get:function(){return chunkORZLXBDK_cjs.a}});Object.defineProperty(exports,"EvalTier",{enumerable:true,get:function(){return chunkORZLXBDK_cjs.b}});Object.defineProperty(exports,"ThreeTierEvaluator",{enumerable:true,get:function(){return chunkORZLXBDK_cjs.c}});Object.defineProperty(exports,"evaluateDocument",{enumerable:true,get:function(){return chunkORZLXBDK_cjs.d}});Object.defineProperty(exports,"AsyncResolutionBatcher",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.h}});Object.defineProperty(exports,"ExpressionEngine",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.n}});Object.defineProperty(exports,"SNAPSHOT_FORMAT",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.d}});Object.defineProperty(exports,"SNAPSHOT_VERSION",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.e}});Object.defineProperty(exports,"SnapshotErrorCodes",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.f}});Object.defineProperty(exports,"checkExpressionComplexity",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.j}});Object.defineProperty(exports,"checkExpressionLength",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.i}});Object.defineProperty(exports,"extractReadsAndWrites",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.k}});Object.defineProperty(exports,"findInlineSolvesInLine",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.m}});Object.defineProperty(exports,"isEmptyLine",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.l}});//# sourceMappingURL=engine.cjs.map
2
2
  //# sourceMappingURL=engine.cjs.map
package/dist/engine.js CHANGED
@@ -1,2 +1,2 @@
1
- export{a as DocumentModel,b as EvalTier,c as ThreeTierEvaluator,d as evaluateDocument}from'./chunk-Y6QP576X.js';import'./chunk-RAF57WYO.js';export{h as AsyncResolutionBatcher,n as ExpressionEngine,d as SNAPSHOT_FORMAT,e as SNAPSHOT_VERSION,f as SnapshotErrorCodes,j as checkExpressionComplexity,i as checkExpressionLength,k as extractReadsAndWrites,m as findInlineSolvesInLine,l as isEmptyLine}from'./chunk-WOGCCIKZ.js';import'./chunk-JVMINMAB.js';import'./chunk-2RWAXT6O.js';import'./chunk-7E7NXKQ5.js';import'./chunk-MIQBJGGR.js';import'./chunk-YBKMCGJ3.js';import'./chunk-JP4JMQOG.js';import'./chunk-QTSDIDAS.js';import'./chunk-XEIDV5JP.js';import'./chunk-CDIHV3ZS.js';import'./chunk-O3BDXOQJ.js';import'./chunk-DLXG73JZ.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-JMYBZ6JF.js';import'./chunk-EQDT42JG.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-KEA5HRL3.js';import'./chunk-3GR46UOX.js';import'./chunk-6YGRMAQR.js';import'./chunk-TLNKERM6.js';import'./chunk-6EPJNHSQ.js';import'./chunk-JPFCXLJV.js';import'./chunk-BB5RRSGS.js';import'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';import'./chunk-6NXOKM2O.js';import'./chunk-MDLR2PWN.js';import'./chunk-PIZQIQVM.js';//# sourceMappingURL=engine.js.map
1
+ export{a as DocumentModel,b as EvalTier,c as ThreeTierEvaluator,d as evaluateDocument}from'./chunk-DCNGKGOZ.js';import'./chunk-RAF57WYO.js';export{h as AsyncResolutionBatcher,n as ExpressionEngine,d as SNAPSHOT_FORMAT,e as SNAPSHOT_VERSION,f as SnapshotErrorCodes,j as checkExpressionComplexity,i as checkExpressionLength,k as extractReadsAndWrites,m as findInlineSolvesInLine,l as isEmptyLine}from'./chunk-GF3Z6DDF.js';import'./chunk-JVMINMAB.js';import'./chunk-2RWAXT6O.js';import'./chunk-7E7NXKQ5.js';import'./chunk-MIQBJGGR.js';import'./chunk-ALY4ZMYO.js';import'./chunk-JP4JMQOG.js';import'./chunk-QTSDIDAS.js';import'./chunk-XEIDV5JP.js';import'./chunk-HMC7FJO7.js';import'./chunk-O3BDXOQJ.js';import'./chunk-4DJJIUQF.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-A5M4QZIK.js';import'./chunk-EQDT42JG.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-KEA5HRL3.js';import'./chunk-3GR46UOX.js';import'./chunk-4CNYGIND.js';import'./chunk-AHPBZTW6.js';import'./chunk-FP6Z6PYR.js';import'./chunk-JPFCXLJV.js';import'./chunk-AF7HQN6I.js';import'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import'./chunk-PIZQIQVM.js';//# sourceMappingURL=engine.js.map
2
2
  //# sourceMappingURL=engine.js.map
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';require('./chunk-6CFYMI6C.cjs'),require('./chunk-EFJCC6FJ.cjs');var chunkDGAFTYOC_cjs=require('./chunk-DGAFTYOC.cjs');require('./chunk-JYLNQOPU.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-LNZNJSRW.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-QD2Z5TDD.cjs'),require('./chunk-HG4NPDN5.cjs'),require('./chunk-H3JXNH7X.cjs'),require('./chunk-R2SZFJTT.cjs');var chunk3AES5ZGS_cjs=require('./chunk-3AES5ZGS.cjs');require('./chunk-TL545PXW.cjs'),require('./chunk-53JLDRXA.cjs');var chunkEN3CDYOS_cjs=require('./chunk-EN3CDYOS.cjs');require('./chunk-KLPKLTJZ.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-HCPZRSHR.cjs'),require('./chunk-6YM67DWH.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-J7ABVGZH.cjs');var chunk75JLWK4L_cjs=require('./chunk-75JLWK4L.cjs');require('./chunk-BVSATTRX.cjs');var chunkKQQWHGCN_cjs=require('./chunk-KQQWHGCN.cjs');require('./chunk-TM752D4J.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-EAB6SSAV.cjs'),require('./chunk-5IJD5L3O.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-IXOE2BQG.cjs'),require('./chunk-XB3TWS7J.cjs');var chunkCO2BI6WL_cjs=require('./chunk-CO2BI6WL.cjs');var r={DEFINE_FUNCTION_INVALID_NAME:"DEFINE_FUNCTION_INVALID_NAME",DEFINE_FUNCTION_INVALID_SPEC:"DEFINE_FUNCTION_INVALID_SPEC",DEFINE_FUNCTION_ARITY_MISMATCH:"DEFINE_FUNCTION_ARITY_MISMATCH",DEFINE_FUNCTION_ARGUMENT_TYPE:"DEFINE_FUNCTION_ARGUMENT_TYPE",DEFINE_FUNCTION_RETURN_TYPE:"DEFINE_FUNCTION_RETURN_TYPE"},b=/^[a-z_][a-z0-9_]*$/i,y=new Set(["number","string","boolean"]);function u(e){return e===1?"1 argument":`${e} arguments`}function f(e){switch(e.type){case 0:case 1:return "a number";case 3:return "a string";case 10:return "a boolean";case 2:return "a big integer";case 5:return "a percentage";case 6:return "a value with a unit";case 4:return "a date";case 7:return "a matrix";case 8:return "a range";case 9:return "a symbolic expression";default:return "an unsupported value"}}function A(e,n,t){switch(n.type){case "number":if(e.type===0||e.type===1)return e.toNumber();break;case "string":if(e.type===3)return e.value;break;case "boolean":if(e.type===10)return e.value;break}throw chunkCO2BI6WL_cjs.c.execution({code:r.DEFINE_FUNCTION_ARGUMENT_TYPE,message:`${t}() expects "${n.name}" to be a ${n.type}, but was given ${f(e)}`,expected:`a ${n.type}`,found:f(e),context:{functionName:t,argName:n.name,expectedType:n.type}})}function S(e,n,t){switch(n){case "number":if(typeof e=="number")return chunk75JLWK4L_cjs.n(e);break;case "string":if(typeof e=="string")return chunk75JLWK4L_cjs.t(e);break;case "boolean":if(typeof e=="boolean")return chunk75JLWK4L_cjs.L(e);break}throw chunkCO2BI6WL_cjs.c.internal({code:r.DEFINE_FUNCTION_RETURN_TYPE,message:`${t}() is declared to return a ${n}, but its implementation returned ${typeof e}`,expected:`a ${n}`,found:typeof e,context:{functionName:t,expectedType:n}})}var p=class{constructor(n){this.fnName=n;this.category="Function";}parse(n,t,i){n.consume("LPAREN");let a=0;if(n.peek()?.type!=="RPAREN")for(n.parseExpression(chunkEN3CDYOS_cjs.a.Lowest,i),a++;n.match("COMMA");)n.parseExpression(chunkEN3CDYOS_cjs.a.Lowest,i),a++;n.consume("RPAREN"),i.emitPluginCall(this.fnName,a);}};function P(e){let n=e.args.length;return t=>{if(t.length!==n)throw chunkCO2BI6WL_cjs.c.execution({code:r.DEFINE_FUNCTION_ARITY_MISMATCH,message:`${e.name}() takes ${u(n)}, but was given ${t.length===0?"none":u(t.length)}`,expected:u(n),found:t.length===0?"none":u(t.length),context:{functionName:e.name,expected:n,actual:t.length}});let i=new Array(n);for(let s=0;s<n;s++)i[s]=A(t[s],e.args[s],e.name);let a=e.call(...i);return S(a,e.returns,e.name)}}function V(e){if(typeof e?.name!="string"||!b.test(e.name))throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_NAME,message:`defineFunction: name must be a single identifier, got ${JSON.stringify(e?.name)}`,suggestion:'e.g. "vat" or "net_price"',context:{name:e?.name}});if(!Array.isArray(e.args))throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" args must be an array`,context:{name:e.name}});for(let n of e.args){if(typeof n?.name!="string"||n.name.length===0)throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has an argument with no name`,context:{name:e.name}});if(!y.has(n.type))throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" argument "${n.name}" has unsupported type ${JSON.stringify(n.type)}`,suggestion:"supported argument types are number, string, boolean",context:{name:e.name,argName:n.name,type:n.type}})}if(!y.has(e.returns))throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has unsupported return type ${JSON.stringify(e.returns)}`,suggestion:"supported return types are number, string, boolean",context:{name:e.name,returns:e.returns}});if(typeof e.call!="function")throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" is missing a call implementation`,context:{name:e.name}})}function O(e){V(e);let n=e.name,t=`DEFINE_FN_${n.toUpperCase()}`;return {name:`solve-fn-${n}`,lexerVocabulary:{keywords:{[n.toLowerCase()]:t}},prefixParselets:{[t]:new p(n)},pluginFunctions:{[n]:P(e)}}}function h(e={}){let{extraPackages:n=[],...t}=e;return new chunkDGAFTYOC_cjs.n({...t,packages:n.length>0?[...chunk3AES5ZGS_cjs.y,...n]:chunk3AES5ZGS_cjs.y})}Object.defineProperty(exports,"ExpressionEngine",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.n}});Object.defineProperty(exports,"SNAPSHOT_FORMAT",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.d}});Object.defineProperty(exports,"SNAPSHOT_VERSION",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.e}});Object.defineProperty(exports,"SnapshotErrorCodes",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.f}});Object.defineProperty(exports,"assertEngineVersionCompatible",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.c}});Object.defineProperty(exports,"checkEngineVersionCompatibility",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.b}});Object.defineProperty(exports,"checkPackageCompatibility",{enumerable:true,get:function(){return chunkDGAFTYOC_cjs.a}});Object.defineProperty(exports,"ENGINE_VERSION",{enumerable:true,get:function(){return chunkKQQWHGCN_cjs.a}});exports.DefineFunctionErrorCodes=r;exports.createEngine=h;exports.defineFunction=O;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';require('./chunk-ORZLXBDK.cjs'),require('./chunk-EFJCC6FJ.cjs');var chunkLZAW6QB3_cjs=require('./chunk-LZAW6QB3.cjs');require('./chunk-JYLNQOPU.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-LNZNJSRW.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-UNKSCVIL.cjs'),require('./chunk-HG4NPDN5.cjs'),require('./chunk-H3JXNH7X.cjs'),require('./chunk-R2SZFJTT.cjs');var chunk4UHAGMER_cjs=require('./chunk-4UHAGMER.cjs');require('./chunk-TL545PXW.cjs'),require('./chunk-N37PUZJR.cjs');var chunkEN3CDYOS_cjs=require('./chunk-EN3CDYOS.cjs');require('./chunk-SGIDBZ4T.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-XDXIPVZB.cjs'),require('./chunk-6YM67DWH.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-J7ABVGZH.cjs');var chunk75JLWK4L_cjs=require('./chunk-75JLWK4L.cjs');require('./chunk-ZKFCKAIX.cjs');var chunkIFGF26F4_cjs=require('./chunk-IFGF26F4.cjs');require('./chunk-KRXO3MOW.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-USQ4KL6S.cjs'),require('./chunk-5IJD5L3O.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs');var chunkCO2BI6WL_cjs=require('./chunk-CO2BI6WL.cjs');var r={DEFINE_FUNCTION_INVALID_NAME:"DEFINE_FUNCTION_INVALID_NAME",DEFINE_FUNCTION_INVALID_SPEC:"DEFINE_FUNCTION_INVALID_SPEC",DEFINE_FUNCTION_ARITY_MISMATCH:"DEFINE_FUNCTION_ARITY_MISMATCH",DEFINE_FUNCTION_ARGUMENT_TYPE:"DEFINE_FUNCTION_ARGUMENT_TYPE",DEFINE_FUNCTION_RETURN_TYPE:"DEFINE_FUNCTION_RETURN_TYPE"},b=/^[a-z_][a-z0-9_]*$/i,y=new Set(["number","string","boolean"]);function u(e){return e===1?"1 argument":`${e} arguments`}function f(e){switch(e.type){case 0:case 1:return "a number";case 3:return "a string";case 10:return "a boolean";case 2:return "a big integer";case 5:return "a percentage";case 6:return "a value with a unit";case 4:return "a date";case 7:return "a matrix";case 8:return "a range";case 9:return "a symbolic expression";default:return "an unsupported value"}}function A(e,n,t){switch(n.type){case "number":if(e.type===0||e.type===1)return e.toNumber();break;case "string":if(e.type===3)return e.value;break;case "boolean":if(e.type===10)return e.value;break}throw chunkCO2BI6WL_cjs.c.execution({code:r.DEFINE_FUNCTION_ARGUMENT_TYPE,message:`${t}() expects "${n.name}" to be a ${n.type}, but was given ${f(e)}`,expected:`a ${n.type}`,found:f(e),context:{functionName:t,argName:n.name,expectedType:n.type}})}function S(e,n,t){switch(n){case "number":if(typeof e=="number")return chunk75JLWK4L_cjs.n(e);break;case "string":if(typeof e=="string")return chunk75JLWK4L_cjs.t(e);break;case "boolean":if(typeof e=="boolean")return chunk75JLWK4L_cjs.L(e);break}throw chunkCO2BI6WL_cjs.c.internal({code:r.DEFINE_FUNCTION_RETURN_TYPE,message:`${t}() is declared to return a ${n}, but its implementation returned ${typeof e}`,expected:`a ${n}`,found:typeof e,context:{functionName:t,expectedType:n}})}var p=class{constructor(n){this.fnName=n;this.category="Function";}parse(n,t,i){n.consume("LPAREN");let a=0;if(n.peek()?.type!=="RPAREN")for(n.parseExpression(chunkEN3CDYOS_cjs.a.Lowest,i),a++;n.match("COMMA");)n.parseExpression(chunkEN3CDYOS_cjs.a.Lowest,i),a++;n.consume("RPAREN"),i.emitPluginCall(this.fnName,a);}};function P(e){let n=e.args.length;return t=>{if(t.length!==n)throw chunkCO2BI6WL_cjs.c.execution({code:r.DEFINE_FUNCTION_ARITY_MISMATCH,message:`${e.name}() takes ${u(n)}, but was given ${t.length===0?"none":u(t.length)}`,expected:u(n),found:t.length===0?"none":u(t.length),context:{functionName:e.name,expected:n,actual:t.length}});let i=new Array(n);for(let s=0;s<n;s++)i[s]=A(t[s],e.args[s],e.name);let a=e.call(...i);return S(a,e.returns,e.name)}}function V(e){if(typeof e?.name!="string"||!b.test(e.name))throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_NAME,message:`defineFunction: name must be a single identifier, got ${JSON.stringify(e?.name)}`,suggestion:'e.g. "vat" or "net_price"',context:{name:e?.name}});if(!Array.isArray(e.args))throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" args must be an array`,context:{name:e.name}});for(let n of e.args){if(typeof n?.name!="string"||n.name.length===0)throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has an argument with no name`,context:{name:e.name}});if(!y.has(n.type))throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" argument "${n.name}" has unsupported type ${JSON.stringify(n.type)}`,suggestion:"supported argument types are number, string, boolean",context:{name:e.name,argName:n.name,type:n.type}})}if(!y.has(e.returns))throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has unsupported return type ${JSON.stringify(e.returns)}`,suggestion:"supported return types are number, string, boolean",context:{name:e.name,returns:e.returns}});if(typeof e.call!="function")throw chunkCO2BI6WL_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" is missing a call implementation`,context:{name:e.name}})}function O(e){V(e);let n=e.name,t=`DEFINE_FN_${n.toUpperCase()}`;return {name:`solve-fn-${n}`,lexerVocabulary:{keywords:{[n.toLowerCase()]:t}},prefixParselets:{[t]:new p(n)},pluginFunctions:{[n]:P(e)}}}function h(e={}){let{extraPackages:n=[],...t}=e;return new chunkLZAW6QB3_cjs.n({...t,packages:n.length>0?[...chunk4UHAGMER_cjs.z,...n]:chunk4UHAGMER_cjs.z})}Object.defineProperty(exports,"ExpressionEngine",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.n}});Object.defineProperty(exports,"SNAPSHOT_FORMAT",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.d}});Object.defineProperty(exports,"SNAPSHOT_VERSION",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.e}});Object.defineProperty(exports,"SnapshotErrorCodes",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.f}});Object.defineProperty(exports,"assertEngineVersionCompatible",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.c}});Object.defineProperty(exports,"checkEngineVersionCompatibility",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.b}});Object.defineProperty(exports,"checkPackageCompatibility",{enumerable:true,get:function(){return chunkLZAW6QB3_cjs.a}});Object.defineProperty(exports,"ENGINE_VERSION",{enumerable:true,get:function(){return chunkIFGF26F4_cjs.a}});exports.DefineFunctionErrorCodes=r;exports.createEngine=h;exports.defineFunction=O;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import'./chunk-Y6QP576X.js';import'./chunk-RAF57WYO.js';import {n}from'./chunk-WOGCCIKZ.js';export{n as ExpressionEngine,d as SNAPSHOT_FORMAT,e as SNAPSHOT_VERSION,f as SnapshotErrorCodes,c as assertEngineVersionCompatible,b as checkEngineVersionCompatibility,a as checkPackageCompatibility}from'./chunk-WOGCCIKZ.js';import'./chunk-JVMINMAB.js';import'./chunk-2RWAXT6O.js';import'./chunk-7E7NXKQ5.js';import'./chunk-MIQBJGGR.js';import'./chunk-YBKMCGJ3.js';import'./chunk-JP4JMQOG.js';import'./chunk-QTSDIDAS.js';import'./chunk-XEIDV5JP.js';import {y as y$1}from'./chunk-7WX33WM2.js';import'./chunk-MRRMIBHE.js';import'./chunk-CDIHV3ZS.js';import {a}from'./chunk-O3BDXOQJ.js';import'./chunk-DLXG73JZ.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-JMYBZ6JF.js';import'./chunk-EQDT42JG.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-KEA5HRL3.js';import {L,t,n as n$1}from'./chunk-3GR46UOX.js';import'./chunk-6YGRMAQR.js';export{a as ENGINE_VERSION}from'./chunk-TLNKERM6.js';import'./chunk-6EPJNHSQ.js';import'./chunk-JPFCXLJV.js';import'./chunk-BB5RRSGS.js';import'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';import'./chunk-6NXOKM2O.js';import'./chunk-MDLR2PWN.js';import {c}from'./chunk-PIZQIQVM.js';var r={DEFINE_FUNCTION_INVALID_NAME:"DEFINE_FUNCTION_INVALID_NAME",DEFINE_FUNCTION_INVALID_SPEC:"DEFINE_FUNCTION_INVALID_SPEC",DEFINE_FUNCTION_ARITY_MISMATCH:"DEFINE_FUNCTION_ARITY_MISMATCH",DEFINE_FUNCTION_ARGUMENT_TYPE:"DEFINE_FUNCTION_ARGUMENT_TYPE",DEFINE_FUNCTION_RETURN_TYPE:"DEFINE_FUNCTION_RETURN_TYPE"},b=/^[a-z_][a-z0-9_]*$/i,y=new Set(["number","string","boolean"]);function u(e){return e===1?"1 argument":`${e} arguments`}function f(e){switch(e.type){case 0:case 1:return "a number";case 3:return "a string";case 10:return "a boolean";case 2:return "a big integer";case 5:return "a percentage";case 6:return "a value with a unit";case 4:return "a date";case 7:return "a matrix";case 8:return "a range";case 9:return "a symbolic expression";default:return "an unsupported value"}}function A(e,n,t){switch(n.type){case "number":if(e.type===0||e.type===1)return e.toNumber();break;case "string":if(e.type===3)return e.value;break;case "boolean":if(e.type===10)return e.value;break}throw c.execution({code:r.DEFINE_FUNCTION_ARGUMENT_TYPE,message:`${t}() expects "${n.name}" to be a ${n.type}, but was given ${f(e)}`,expected:`a ${n.type}`,found:f(e),context:{functionName:t,argName:n.name,expectedType:n.type}})}function S(e,n,t$1){switch(n){case "number":if(typeof e=="number")return n$1(e);break;case "string":if(typeof e=="string")return t(e);break;case "boolean":if(typeof e=="boolean")return L(e);break}throw c.internal({code:r.DEFINE_FUNCTION_RETURN_TYPE,message:`${t$1}() is declared to return a ${n}, but its implementation returned ${typeof e}`,expected:`a ${n}`,found:typeof e,context:{functionName:t$1,expectedType:n}})}var p=class{constructor(n){this.fnName=n;this.category="Function";}parse(n,t,i){n.consume("LPAREN");let a$1=0;if(n.peek()?.type!=="RPAREN")for(n.parseExpression(a.Lowest,i),a$1++;n.match("COMMA");)n.parseExpression(a.Lowest,i),a$1++;n.consume("RPAREN"),i.emitPluginCall(this.fnName,a$1);}};function P(e){let n=e.args.length;return t=>{if(t.length!==n)throw c.execution({code:r.DEFINE_FUNCTION_ARITY_MISMATCH,message:`${e.name}() takes ${u(n)}, but was given ${t.length===0?"none":u(t.length)}`,expected:u(n),found:t.length===0?"none":u(t.length),context:{functionName:e.name,expected:n,actual:t.length}});let i=new Array(n);for(let s=0;s<n;s++)i[s]=A(t[s],e.args[s],e.name);let a=e.call(...i);return S(a,e.returns,e.name)}}function V(e){if(typeof e?.name!="string"||!b.test(e.name))throw c.config({code:r.DEFINE_FUNCTION_INVALID_NAME,message:`defineFunction: name must be a single identifier, got ${JSON.stringify(e?.name)}`,suggestion:'e.g. "vat" or "net_price"',context:{name:e?.name}});if(!Array.isArray(e.args))throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" args must be an array`,context:{name:e.name}});for(let n of e.args){if(typeof n?.name!="string"||n.name.length===0)throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has an argument with no name`,context:{name:e.name}});if(!y.has(n.type))throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" argument "${n.name}" has unsupported type ${JSON.stringify(n.type)}`,suggestion:"supported argument types are number, string, boolean",context:{name:e.name,argName:n.name,type:n.type}})}if(!y.has(e.returns))throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has unsupported return type ${JSON.stringify(e.returns)}`,suggestion:"supported return types are number, string, boolean",context:{name:e.name,returns:e.returns}});if(typeof e.call!="function")throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" is missing a call implementation`,context:{name:e.name}})}function O(e){V(e);let n=e.name,t=`DEFINE_FN_${n.toUpperCase()}`;return {name:`solve-fn-${n}`,lexerVocabulary:{keywords:{[n.toLowerCase()]:t}},prefixParselets:{[t]:new p(n)},pluginFunctions:{[n]:P(e)}}}function h(e={}){let{extraPackages:n$1=[],...t}=e;return new n({...t,packages:n$1.length>0?[...y$1,...n$1]:y$1})}export{r as DefineFunctionErrorCodes,h as createEngine,O as defineFunction};//# sourceMappingURL=index.js.map
1
+ import'./chunk-DCNGKGOZ.js';import'./chunk-RAF57WYO.js';import {n}from'./chunk-GF3Z6DDF.js';export{n as ExpressionEngine,d as SNAPSHOT_FORMAT,e as SNAPSHOT_VERSION,f as SnapshotErrorCodes,c as assertEngineVersionCompatible,b as checkEngineVersionCompatibility,a as checkPackageCompatibility}from'./chunk-GF3Z6DDF.js';import'./chunk-JVMINMAB.js';import'./chunk-2RWAXT6O.js';import'./chunk-7E7NXKQ5.js';import'./chunk-MIQBJGGR.js';import'./chunk-ALY4ZMYO.js';import'./chunk-JP4JMQOG.js';import'./chunk-QTSDIDAS.js';import'./chunk-XEIDV5JP.js';import {z}from'./chunk-3LUEJHAC.js';import'./chunk-MRRMIBHE.js';import'./chunk-HMC7FJO7.js';import {a}from'./chunk-O3BDXOQJ.js';import'./chunk-4DJJIUQF.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-A5M4QZIK.js';import'./chunk-EQDT42JG.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-KEA5HRL3.js';import {L,t,n as n$1}from'./chunk-3GR46UOX.js';import'./chunk-4CNYGIND.js';export{a as ENGINE_VERSION}from'./chunk-AHPBZTW6.js';import'./chunk-FP6Z6PYR.js';import'./chunk-JPFCXLJV.js';import'./chunk-AF7HQN6I.js';import'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import {c}from'./chunk-PIZQIQVM.js';var r={DEFINE_FUNCTION_INVALID_NAME:"DEFINE_FUNCTION_INVALID_NAME",DEFINE_FUNCTION_INVALID_SPEC:"DEFINE_FUNCTION_INVALID_SPEC",DEFINE_FUNCTION_ARITY_MISMATCH:"DEFINE_FUNCTION_ARITY_MISMATCH",DEFINE_FUNCTION_ARGUMENT_TYPE:"DEFINE_FUNCTION_ARGUMENT_TYPE",DEFINE_FUNCTION_RETURN_TYPE:"DEFINE_FUNCTION_RETURN_TYPE"},b=/^[a-z_][a-z0-9_]*$/i,y=new Set(["number","string","boolean"]);function u(e){return e===1?"1 argument":`${e} arguments`}function f(e){switch(e.type){case 0:case 1:return "a number";case 3:return "a string";case 10:return "a boolean";case 2:return "a big integer";case 5:return "a percentage";case 6:return "a value with a unit";case 4:return "a date";case 7:return "a matrix";case 8:return "a range";case 9:return "a symbolic expression";default:return "an unsupported value"}}function A(e,n,t){switch(n.type){case "number":if(e.type===0||e.type===1)return e.toNumber();break;case "string":if(e.type===3)return e.value;break;case "boolean":if(e.type===10)return e.value;break}throw c.execution({code:r.DEFINE_FUNCTION_ARGUMENT_TYPE,message:`${t}() expects "${n.name}" to be a ${n.type}, but was given ${f(e)}`,expected:`a ${n.type}`,found:f(e),context:{functionName:t,argName:n.name,expectedType:n.type}})}function S(e,n,t$1){switch(n){case "number":if(typeof e=="number")return n$1(e);break;case "string":if(typeof e=="string")return t(e);break;case "boolean":if(typeof e=="boolean")return L(e);break}throw c.internal({code:r.DEFINE_FUNCTION_RETURN_TYPE,message:`${t$1}() is declared to return a ${n}, but its implementation returned ${typeof e}`,expected:`a ${n}`,found:typeof e,context:{functionName:t$1,expectedType:n}})}var p=class{constructor(n){this.fnName=n;this.category="Function";}parse(n,t,i){n.consume("LPAREN");let a$1=0;if(n.peek()?.type!=="RPAREN")for(n.parseExpression(a.Lowest,i),a$1++;n.match("COMMA");)n.parseExpression(a.Lowest,i),a$1++;n.consume("RPAREN"),i.emitPluginCall(this.fnName,a$1);}};function P(e){let n=e.args.length;return t=>{if(t.length!==n)throw c.execution({code:r.DEFINE_FUNCTION_ARITY_MISMATCH,message:`${e.name}() takes ${u(n)}, but was given ${t.length===0?"none":u(t.length)}`,expected:u(n),found:t.length===0?"none":u(t.length),context:{functionName:e.name,expected:n,actual:t.length}});let i=new Array(n);for(let s=0;s<n;s++)i[s]=A(t[s],e.args[s],e.name);let a=e.call(...i);return S(a,e.returns,e.name)}}function V(e){if(typeof e?.name!="string"||!b.test(e.name))throw c.config({code:r.DEFINE_FUNCTION_INVALID_NAME,message:`defineFunction: name must be a single identifier, got ${JSON.stringify(e?.name)}`,suggestion:'e.g. "vat" or "net_price"',context:{name:e?.name}});if(!Array.isArray(e.args))throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" args must be an array`,context:{name:e.name}});for(let n of e.args){if(typeof n?.name!="string"||n.name.length===0)throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has an argument with no name`,context:{name:e.name}});if(!y.has(n.type))throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" argument "${n.name}" has unsupported type ${JSON.stringify(n.type)}`,suggestion:"supported argument types are number, string, boolean",context:{name:e.name,argName:n.name,type:n.type}})}if(!y.has(e.returns))throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has unsupported return type ${JSON.stringify(e.returns)}`,suggestion:"supported return types are number, string, boolean",context:{name:e.name,returns:e.returns}});if(typeof e.call!="function")throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" is missing a call implementation`,context:{name:e.name}})}function O(e){V(e);let n=e.name,t=`DEFINE_FN_${n.toUpperCase()}`;return {name:`solve-fn-${n}`,lexerVocabulary:{keywords:{[n.toLowerCase()]:t}},prefixParselets:{[t]:new p(n)},pluginFunctions:{[n]:P(e)}}}function h(e={}){let{extraPackages:n$1=[],...t}=e;return new n({...t,packages:n$1.length>0?[...z,...n$1]:z})}export{r as DefineFunctionErrorCodes,h as createEngine,O as defineFunction};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/defineFunction.ts","../src/api/createEngine.ts"],"names":["DefineFunctionErrorCodes","NAME_PATTERN","SUPPORTED_TYPES","plural","count","describeValueType","v","coerceArgument","value","arg","fnName","ErrorFactory","wrapReturn","result","returns","numberValue","stringValue","boolValue","DefinedFunctionParselet","parser","_token","builder","argCount","BindingPower","makeHandler","spec","arity","args","jsArgs","i","validateSpec","defineFunction","name","tokenType","createEngine","options","extraPackages","engineOptions","ExpressionEngine","BUILTIN_PACKAGES"],"mappings":"wwCAkFO,IAAMA,EAA2B,CAEtC,4BAAA,CAA8B,+BAE9B,4BAAA,CAA8B,8BAAA,CAE9B,+BAAgC,gCAAA,CAEhC,6BAAA,CAA+B,+BAAA,CAE/B,2BAAA,CAA6B,6BAC/B,CAAA,CAGMC,CAAAA,CAAe,sBAEfC,CAAAA,CAAuC,IAAI,IAAI,CAA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,OAAO,CACL,IAAA,CAAM,YAAYA,CAAI,CAAA,CAAA,CACtB,eAAA,CAAiB,CAGf,SAAU,CAAE,CAACA,EAAK,WAAA,EAAa,EAAGC,CAAU,CAC9C,EACA,eAAA,CAAiB,CACf,CAACA,CAAS,EAAG,IAAIf,CAAAA,CAAwBc,CAAI,CAC/C,CAAA,CACA,eAAA,CAAiB,CACf,CAACA,CAAI,EAAGR,CAAAA,CAAYC,CAAoB,CAC1C,CACF,CACF,CCrWO,SAASS,EAAaC,CAAAA,CAA+B,GAAsB,CACjF,GAAM,CAAE,aAAA,CAAAC,GAAAA,CAAgB,EAAC,CAAG,GAAGC,CAAc,CAAA,CAAIF,EACjD,OAAO,IAAIG,EAAiB,CAC3B,GAAGD,EACH,QAAA,CAAUD,GAAAA,CAAc,OAAS,CAAA,CAAI,CAAC,GAAGG,GAAAA,CAAkB,GAAGH,GAAa,CAAA,CAAIG,GAChF,CAAC,CACF","file":"index.js","sourcesContent":["import type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport type { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport type { Parser } from \"@solve-js/parser/Parser\";\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport {\n Value,\n ValueType,\n numberValue,\n stringValue,\n boolValue,\n} from \"@solve-js/vm/Value\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A higher-level, declarative way to contribute a single `name(args)`\n * function, sitting ON TOP OF the package contract rather than replacing it.\n *\n * The low-level contract (allocate a plugin function index, write a parselet,\n * emit `CALL_PLUGIN`) stays exactly as it was and remains the way to add\n * anything that needs custom parsing. This module derives that same wiring\n * from a declaration for the common case, a function called with parenthesised\n * arguments, so adding `vat(x)` costs a spec object rather than an\n * understanding of the parser and the VM. See `defineFunction`.\n */\n\n/** The value types a declared argument or return may take. */\nexport type FunctionValueType = \"number\" | \"string\" | \"boolean\";\n\n/** The JavaScript type a {@link FunctionValueType} maps to at the `call` boundary. */\ntype JsValue<T extends FunctionValueType> = T extends \"number\"\n ? number\n : T extends \"string\"\n ? string\n : boolean;\n\n/** One declared parameter: a name (for error messages) and a value type. */\nexport interface FunctionArg {\n /** Parameter name, used only in the generated type-mismatch messages. */\n name: string;\n /** The value type this parameter accepts. */\n type: FunctionValueType;\n}\n\n/** Map a tuple of {@link FunctionArg} specs to the tuple of JS values `call` receives. */\ntype CallArgs<A extends readonly FunctionArg[]> = {\n [K in keyof A]: JsValue<A[K][\"type\"]>;\n};\n\n/**\n * A declarative function definition.\n *\n * `A` and `R` are inferred from the literal `args`/`returns` (via\n * `defineFunction`'s `const` type parameter), so `call`'s parameters and\n * return are typed from the declaration with no annotations: an\n * `{ type: \"number\" }` argument arrives as a `number`, and a `returns:\n * \"string\"` demands a `string` back.\n */\nexport interface FunctionSpec<\n A extends readonly FunctionArg[] = readonly FunctionArg[],\n R extends FunctionValueType = FunctionValueType,\n> {\n /**\n * The call name, a single identifier (`/^[a-z_][a-z0-9_]*$/i`). Registered\n * as a lexer keyword, so it is matched case-insensitively and cannot collide\n * with a built-in keyword (that collision throws at registration time).\n */\n name: string;\n /** The parameters, in order. A fixed-length list: variadic and optional args are out of scope (see {@link defineFunction}). */\n args: A;\n /** The value type the function returns. */\n returns: R;\n /** The implementation, receiving plain JS values and returning one. Must be synchronous (see {@link defineFunction}). */\n call: (...args: CallArgs<A>) => JsValue<R>;\n}\n\n/**\n * Error codes the declarative function API raises. Kept as a co-located const\n * (the convention `errors/ErrorCode.ts` documents for a domain's own codes) so\n * the strings have one source of truth.\n */\nexport const DefineFunctionErrorCodes = {\n /** The spec's `name` is not a single identifier. Thrown by `defineFunction`, before any engine sees it. */\n DEFINE_FUNCTION_INVALID_NAME: \"DEFINE_FUNCTION_INVALID_NAME\",\n /** The spec is otherwise malformed (bad `args`, unsupported type, missing `call`). Thrown by `defineFunction`. */\n DEFINE_FUNCTION_INVALID_SPEC: \"DEFINE_FUNCTION_INVALID_SPEC\",\n /** The call site passed the wrong number of arguments. Raised at evaluation time. */\n DEFINE_FUNCTION_ARITY_MISMATCH: \"DEFINE_FUNCTION_ARITY_MISMATCH\",\n /** An argument was the wrong value type. Raised at evaluation time. */\n DEFINE_FUNCTION_ARGUMENT_TYPE: \"DEFINE_FUNCTION_ARGUMENT_TYPE\",\n /** The `call` implementation returned a value that did not match `returns`. Raised at evaluation time, an authoring bug rather than a user one. */\n DEFINE_FUNCTION_RETURN_TYPE: \"DEFINE_FUNCTION_RETURN_TYPE\",\n} as const;\n\n/** A single identifier: a letter or underscore, then letters, digits, or underscores. */\nconst NAME_PATTERN = /^[a-z_][a-z0-9_]*$/i;\n\nconst SUPPORTED_TYPES: ReadonlySet<string> = new Set([\"number\", \"string\", \"boolean\"]);\n\n/** \"1 argument\" / \"2 arguments\", so a count reads as English either way. Mirrors `VMBuiltinArity.ts`. */\nfunction plural(count: number): string {\n return count === 1 ? \"1 argument\" : `${count} arguments`;\n}\n\n/**\n * A human noun for the type a Value actually carries, for the \"was given ...\"\n * half of a mismatch message. Covers the three declarable types by their own\n * names and everything else by a readable category, so the message never reads\n * \"given a 6\".\n */\nfunction describeValueType(v: Value): string {\n switch (v.type) {\n case ValueType.Number:\n case ValueType.Hex:\n return \"a number\";\n case ValueType.String:\n return \"a string\";\n case ValueType.Boolean:\n return \"a boolean\";\n case ValueType.BigInt:\n return \"a big integer\";\n case ValueType.Percentage:\n return \"a percentage\";\n case ValueType.Uom:\n return \"a value with a unit\";\n case ValueType.Datetime:\n return \"a date\";\n case ValueType.Matrix:\n return \"a matrix\";\n case ValueType.Range:\n return \"a range\";\n case ValueType.Symbolic:\n return \"a symbolic expression\";\n default:\n return \"an unsupported value\";\n }\n}\n\n/**\n * Read one runtime Value as the JS primitive its declared type promises, or\n * raise the engine's structured type error.\n *\n * A \"number\" accepts a plain number or a based literal (`0xFF`), both of which\n * ARE numbers written differently, and reads it with `toNumber()`. Nothing\n * else is coerced: a percentage, a unit-bearing value or a string is a\n * genuinely different kind of value, and silently reinterpreting it is the\n * class of wrong-answer this API exists to avoid.\n */\nfunction coerceArgument(\n value: Value,\n arg: FunctionArg,\n fnName: string,\n): number | string | boolean {\n switch (arg.type) {\n case \"number\":\n // Hex is a number in another base (see `hexValue`), so it reads as one here.\n if (value.type === ValueType.Number || value.type === ValueType.Hex) {\n return value.toNumber();\n }\n break;\n case \"string\":\n if (value.type === ValueType.String) return value.value as string;\n break;\n case \"boolean\":\n if (value.type === ValueType.Boolean) return value.value as boolean;\n break;\n }\n throw ErrorFactory.execution({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_ARGUMENT_TYPE,\n message: `${fnName}() expects \"${arg.name}\" to be a ${arg.type}, but was given ${describeValueType(value)}`,\n expected: `a ${arg.type}`,\n found: describeValueType(value),\n context: { functionName: fnName, argName: arg.name, expectedType: arg.type },\n });\n}\n\n/**\n * Wrap the `call` result back into a Value of the declared return type, or\n * raise a structured error if the implementation handed back something else.\n *\n * The type check here catches an authoring mistake (a function declared to\n * return a number that returns `undefined`, or a Promise from an accidental\n * `async`), turning it into a named error rather than a Value that lies about\n * its own type downstream.\n */\nfunction wrapReturn(result: unknown, returns: FunctionValueType, fnName: string): Value {\n switch (returns) {\n case \"number\":\n if (typeof result === \"number\") return numberValue(result);\n break;\n case \"string\":\n if (typeof result === \"string\") return stringValue(result);\n break;\n case \"boolean\":\n if (typeof result === \"boolean\") return boolValue(result);\n break;\n }\n throw ErrorFactory.internal({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_RETURN_TYPE,\n message: `${fnName}() is declared to return a ${returns}, but its implementation returned ${typeof result}`,\n expected: `a ${returns}`,\n found: typeof result,\n context: { functionName: fnName, expectedType: returns },\n });\n}\n\n/**\n * The call-syntax parselet generated for one declared function.\n *\n * Identical in shape to the built-in `FunctionCallParselet`: consume the open\n * paren, parse a comma-separated argument list, then emit `CALL_PLUGIN` with\n * the function's index and the argument count. The count is whatever was\n * written, arity is checked at the dispatch point (see {@link makeHandler}),\n * the same place the built-in arity check lives.\n */\nclass DefinedFunctionParselet implements PrefixParselet {\n readonly category = \"Function\";\n\n constructor(\n private readonly fnName: string,\n ) {}\n\n parse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n parser.consume(\"LPAREN\");\n\n let argCount = 0;\n if (parser.peek()?.type !== \"RPAREN\") {\n parser.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (parser.match(\"COMMA\")) {\n parser.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n\n parser.consume(\"RPAREN\");\n\n builder.emitPluginCall(this.fnName, argCount);\n }\n}\n\n/**\n * Build the plugin function that checks arity and argument types, calls the\n * host implementation, and wraps the result.\n *\n * The VM has already screened out faulted arguments (an errored or still\n * pending operand short-circuits before the handler runs, see\n * `VM.ts`'s `CALL_PLUGIN` case), so every Value reaching here carries a real\n * result. Arity is checked first, before any argument is read, so a wrong\n * count is reported as a wrong count rather than as a type error on a missing\n * argument.\n */\nfunction makeHandler(spec: FunctionSpec): (args: Value[]) => Value {\n const arity = spec.args.length;\n return (args: Value[]): Value => {\n if (args.length !== arity) {\n throw ErrorFactory.execution({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_ARITY_MISMATCH,\n message: `${spec.name}() takes ${plural(arity)}, but was given ${args.length === 0 ? \"none\" : plural(args.length)}`,\n expected: plural(arity),\n found: args.length === 0 ? \"none\" : plural(args.length),\n context: { functionName: spec.name, expected: arity, actual: args.length },\n });\n }\n\n const jsArgs: (number | string | boolean)[] = new Array(arity);\n for (let i = 0; i < arity; i++) {\n jsArgs[i] = coerceArgument(args[i], spec.args[i], spec.name);\n }\n\n const result = (spec.call as (...a: (number | string | boolean)[]) => unknown)(...jsArgs);\n return wrapReturn(result, spec.returns, spec.name);\n };\n}\n\n/** Reject a spec that could not produce a working function, before any engine sees it. */\nfunction validateSpec(spec: FunctionSpec): void {\n if (typeof spec?.name !== \"string\" || !NAME_PATTERN.test(spec.name)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_NAME,\n message: `defineFunction: name must be a single identifier, got ${JSON.stringify(spec?.name)}`,\n suggestion: 'e.g. \"vat\" or \"net_price\"',\n context: { name: spec?.name },\n });\n }\n if (!Array.isArray(spec.args)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" args must be an array`,\n context: { name: spec.name },\n });\n }\n for (const arg of spec.args) {\n if (typeof arg?.name !== \"string\" || arg.name.length === 0) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" has an argument with no name`,\n context: { name: spec.name },\n });\n }\n if (!SUPPORTED_TYPES.has(arg.type)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" argument \"${arg.name}\" has unsupported type ${JSON.stringify(arg.type)}`,\n suggestion: \"supported argument types are number, string, boolean\",\n context: { name: spec.name, argName: arg.name, type: arg.type },\n });\n }\n }\n if (!SUPPORTED_TYPES.has(spec.returns)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" has unsupported return type ${JSON.stringify(spec.returns)}`,\n suggestion: \"supported return types are number, string, boolean\",\n context: { name: spec.name, returns: spec.returns },\n });\n }\n if (typeof spec.call !== \"function\") {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" is missing a call implementation`,\n context: { name: spec.name },\n });\n }\n}\n\n/**\n * Turn a declarative {@link FunctionSpec} into a ready-to-register\n * {@link IEnginePackage}.\n *\n * This is the higher-level API from issue #102. It derives, from the\n * declaration alone, everything the low-level contract asks an author to write\n * by hand: a named plugin function (the engine assigns its `CALL_PLUGIN`\n * index), a lexer keyword so the name tokenises, a call-syntax parselet emitting\n * that call by name, and a handler that checks arity and argument types (yielding\n * the engine's own structured errors) before invoking `call` and wrapping its\n * result. Anything needing custom parsing keeps writing a raw parselet exactly\n * as before, this sits on top of that contract and does not change it.\n *\n * @example\n * ```ts\n * const engine = new ExpressionEngine({ packages: [\n * ...BUILTIN_PACKAGES,\n * defineFunction({\n * name: \"vat\",\n * args: [{ name: \"amount\", type: \"number\" }],\n * returns: \"number\",\n * call: (amount) => amount * 1.2,\n * }),\n * ] });\n * engine.evaluateExpression(\"vat(100)\"); // 120\n * ```\n *\n * The returned package is self-contained and composes with any others through\n * the engine's `packages` array; register several functions by passing several\n * packages. Its name is `solve-fn-<name>`.\n *\n * Scope: arguments are a fixed-length list of `number`/`string`/`boolean`, and\n * `call` is synchronous. Variadic and optional arguments, other value types\n * (units, percentages, dates, matrices), and async work are deliberately out\n * of scope, a function needing any of those keeps using the low-level\n * contract, whose parselets and async resolvers are unchanged.\n *\n * @throws {EngineError} (category CONFIG) if the spec is malformed, at the\n * point `defineFunction` is called, before the package reaches an engine.\n */\nexport function defineFunction<\n const A extends readonly FunctionArg[],\n R extends FunctionValueType,\n>(spec: FunctionSpec<A, R>): IEnginePackage {\n validateSpec(spec as FunctionSpec);\n\n const name = spec.name;\n // Uppercased so the generated type is a valid, collision-resistant token\n // type; the name pattern guarantees it forms one. Distinct from the\n // built-in FUNC type, so this never routes through the builtin name map.\n const tokenType = `DEFINE_FN_${name.toUpperCase()}`;\n\n return {\n name: `solve-fn-${name}`,\n lexerVocabulary: {\n // Lowercased because the lexer lowercases input before lookup, so the\n // call is matched case-insensitively.\n keywords: { [name.toLowerCase()]: tokenType },\n },\n prefixParselets: {\n [tokenType]: new DefinedFunctionParselet(name),\n },\n pluginFunctions: {\n [name]: makeHandler(spec as FunctionSpec),\n },\n };\n}\n","import { ExpressionEngine, type EngineOptions } from \"@solve-js/engine/ExpressionEngine\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\n\n/** Options for {@link createEngine}: the engine options, minus `packages` (the\n * built-in set is always registered), plus `extraPackages` to add your own. */\nexport interface CreateEngineOptions extends Omit<EngineOptions, \"packages\"> {\n\t/** Packages to register ON TOP of the built-in set (e.g. an OSRS or stocks package). */\n\textraPackages?: IEnginePackage[];\n}\n\n/**\n * A batteries-included {@link ExpressionEngine} with every built-in package\n * registered.\n *\n * The constructor registers only the packages it is given, so a consumer's\n * bundler can tree-shake away the built-ins they never use: an engine built\n * with `new ExpressionEngine({ packages: [ARITHMETIC_PACKAGE] })` carries no\n * finance, colour or weather code. This convenience is the opposite trade: it\n * pulls the FULL built-in set (`BUILTIN_PACKAGES`) for the common \"I want\n * everything\" case, so importing it defeats that tree-shaking. Reach for the\n * constructor with an explicit package list when bundle size matters, and for\n * `createEngine` when it does not.\n *\n * @param options - Engine options ({@link EngineOptions}) minus `packages`, plus\n * an optional `extraPackages` to register alongside the built-in set.\n * @returns An engine with the built-in packages (and any extras) registered.\n *\n * @example\n * ```typescript\n * import { createEngine } from \"solve-engine\";\n * const engine = createEngine();\n * const value = engine.evaluateExpression(\"2 + 2 * 10\");\n * console.log(value.toNumber()); // 22\n * ```\n */\nexport function createEngine(options: CreateEngineOptions = {}): ExpressionEngine {\n\tconst { extraPackages = [], ...engineOptions } = options;\n\treturn new ExpressionEngine({\n\t\t...engineOptions,\n\t\tpackages: extraPackages.length > 0 ? [...BUILTIN_PACKAGES, ...extraPackages] : BUILTIN_PACKAGES,\n\t});\n}\n"]}
1
+ {"version":3,"sources":["../src/api/defineFunction.ts","../src/api/createEngine.ts"],"names":["DefineFunctionErrorCodes","NAME_PATTERN","SUPPORTED_TYPES","plural","count","describeValueType","v","coerceArgument","value","arg","fnName","ErrorFactory","wrapReturn","result","returns","numberValue","stringValue","boolValue","DefinedFunctionParselet","parser","_token","builder","argCount","BindingPower","makeHandler","spec","arity","args","jsArgs","i","validateSpec","defineFunction","name","tokenType","createEngine","options","extraPackages","engineOptions","ExpressionEngine","BUILTIN_PACKAGES"],"mappings":"iwCAkFO,IAAMA,EAA2B,CAEtC,4BAAA,CAA8B,+BAE9B,4BAAA,CAA8B,8BAAA,CAE9B,+BAAgC,gCAAA,CAEhC,6BAAA,CAA+B,+BAAA,CAE/B,2BAAA,CAA6B,6BAC/B,CAAA,CAGMC,CAAAA,CAAe,sBAEfC,CAAAA,CAAuC,IAAI,IAAI,CAAC,QAAA,CAAU,QAAA,CAAU,SAAS,CAAC,EAGpF,SAASC,EAAOC,CAAAA,CAAuB,CACrC,OAAOA,CAAAA,GAAU,CAAA,CAAI,aAAe,CAAA,EAAGA,CAAK,YAC9C,CAQA,SAASC,EAAkBC,CAAAA,CAAkB,CAC3C,OAAQA,CAAAA,CAAE,IAAA,EACR,KAAA,CAAA,CACA,OACE,OAAO,UAAA,CACT,OACE,OAAO,UAAA,CACT,QACE,OAAO,WAAA,CACT,KAAA,CAAA,CACE,OAAO,gBACT,KAAA,CAAA,CACE,OAAO,eACT,KAAA,CAAA,CACE,OAAO,sBACT,KAAA,CAAA,CACE,OAAO,QAAA,CACT,KAAA,CAAA,CACE,OAAO,UAAA,CACT,KAAA,CAAA,CACE,OAAO,SAAA,CACT,KAAA,CAAA,CACE,OAAO,uBAAA,CACT,QACE,OAAO,sBACX,CACF,CAYA,SAASC,CAAAA,CACPC,EACAC,CAAAA,CACAC,CAAAA,CAC2B,CAC3B,OAAQD,CAAAA,CAAI,IAAA,EACV,KAAK,QAAA,CAEH,GAAID,EAAM,IAAA,GAAS,CAAA,EAAoBA,EAAM,IAAA,GAAS,CAAA,CACpD,OAAOA,CAAAA,CAAM,UAAS,CAExB,MACF,KAAK,QAAA,CACH,GAAIA,EAAM,IAAA,GAAS,CAAA,CAAkB,OAAOA,CAAAA,CAAM,MAClD,MACF,KAAK,UACH,GAAIA,CAAAA,CAAM,OA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4BAAA,CAC/B,QAAS,CAAA,iBAAA,EAAoByB,CAAAA,CAAK,IAAI,CAAA,kCAAA,CAAA,CACtC,OAAA,CAAS,CAAE,IAAA,CAAMA,CAAAA,CAAK,IAAK,CAC7B,CAAC,CAEL,CA0CO,SAASM,CAAAA,CAGdN,CAAAA,CAA0C,CAC1CK,CAAAA,CAAaL,CAAoB,EAEjC,IAAMO,CAAAA,CAAOP,EAAK,IAAA,CAIZQ,CAAAA,CAAY,CAAA,UAAA,EAAaD,CAAAA,CAAK,aAAa,CAAA,CAAA,CAEjD,OAAO,CACL,IAAA,CAAM,YAAYA,CAAI,CAAA,CAAA,CACtB,eAAA,CAAiB,CAGf,SAAU,CAAE,CAACA,EAAK,WAAA,EAAa,EAAGC,CAAU,CAC9C,EACA,eAAA,CAAiB,CACf,CAACA,CAAS,EAAG,IAAIf,CAAAA,CAAwBc,CAAI,CAC/C,CAAA,CACA,eAAA,CAAiB,CACf,CAACA,CAAI,EAAGR,CAAAA,CAAYC,CAAoB,CAC1C,CACF,CACF,CCrWO,SAASS,EAAaC,CAAAA,CAA+B,GAAsB,CACjF,GAAM,CAAE,aAAA,CAAAC,GAAAA,CAAgB,EAAC,CAAG,GAAGC,CAAc,CAAA,CAAIF,EACjD,OAAO,IAAIG,EAAiB,CAC3B,GAAGD,EACH,QAAA,CAAUD,GAAAA,CAAc,OAAS,CAAA,CAAI,CAAC,GAAGG,CAAAA,CAAkB,GAAGH,GAAa,CAAA,CAAIG,CAChF,CAAC,CACF","file":"index.js","sourcesContent":["import type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport type { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport type { Parser } from \"@solve-js/parser/Parser\";\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport {\n Value,\n ValueType,\n numberValue,\n stringValue,\n boolValue,\n} from \"@solve-js/vm/Value\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A higher-level, declarative way to contribute a single `name(args)`\n * function, sitting ON TOP OF the package contract rather than replacing it.\n *\n * The low-level contract (allocate a plugin function index, write a parselet,\n * emit `CALL_PLUGIN`) stays exactly as it was and remains the way to add\n * anything that needs custom parsing. This module derives that same wiring\n * from a declaration for the common case, a function called with parenthesised\n * arguments, so adding `vat(x)` costs a spec object rather than an\n * understanding of the parser and the VM. See `defineFunction`.\n */\n\n/** The value types a declared argument or return may take. */\nexport type FunctionValueType = \"number\" | \"string\" | \"boolean\";\n\n/** The JavaScript type a {@link FunctionValueType} maps to at the `call` boundary. */\ntype JsValue<T extends FunctionValueType> = T extends \"number\"\n ? number\n : T extends \"string\"\n ? string\n : boolean;\n\n/** One declared parameter: a name (for error messages) and a value type. */\nexport interface FunctionArg {\n /** Parameter name, used only in the generated type-mismatch messages. */\n name: string;\n /** The value type this parameter accepts. */\n type: FunctionValueType;\n}\n\n/** Map a tuple of {@link FunctionArg} specs to the tuple of JS values `call` receives. */\ntype CallArgs<A extends readonly FunctionArg[]> = {\n [K in keyof A]: JsValue<A[K][\"type\"]>;\n};\n\n/**\n * A declarative function definition.\n *\n * `A` and `R` are inferred from the literal `args`/`returns` (via\n * `defineFunction`'s `const` type parameter), so `call`'s parameters and\n * return are typed from the declaration with no annotations: an\n * `{ type: \"number\" }` argument arrives as a `number`, and a `returns:\n * \"string\"` demands a `string` back.\n */\nexport interface FunctionSpec<\n A extends readonly FunctionArg[] = readonly FunctionArg[],\n R extends FunctionValueType = FunctionValueType,\n> {\n /**\n * The call name, a single identifier (`/^[a-z_][a-z0-9_]*$/i`). Registered\n * as a lexer keyword, so it is matched case-insensitively and cannot collide\n * with a built-in keyword (that collision throws at registration time).\n */\n name: string;\n /** The parameters, in order. A fixed-length list: variadic and optional args are out of scope (see {@link defineFunction}). */\n args: A;\n /** The value type the function returns. */\n returns: R;\n /** The implementation, receiving plain JS values and returning one. Must be synchronous (see {@link defineFunction}). */\n call: (...args: CallArgs<A>) => JsValue<R>;\n}\n\n/**\n * Error codes the declarative function API raises. Kept as a co-located const\n * (the convention `errors/ErrorCode.ts` documents for a domain's own codes) so\n * the strings have one source of truth.\n */\nexport const DefineFunctionErrorCodes = {\n /** The spec's `name` is not a single identifier. Thrown by `defineFunction`, before any engine sees it. */\n DEFINE_FUNCTION_INVALID_NAME: \"DEFINE_FUNCTION_INVALID_NAME\",\n /** The spec is otherwise malformed (bad `args`, unsupported type, missing `call`). Thrown by `defineFunction`. */\n DEFINE_FUNCTION_INVALID_SPEC: \"DEFINE_FUNCTION_INVALID_SPEC\",\n /** The call site passed the wrong number of arguments. Raised at evaluation time. */\n DEFINE_FUNCTION_ARITY_MISMATCH: \"DEFINE_FUNCTION_ARITY_MISMATCH\",\n /** An argument was the wrong value type. Raised at evaluation time. */\n DEFINE_FUNCTION_ARGUMENT_TYPE: \"DEFINE_FUNCTION_ARGUMENT_TYPE\",\n /** The `call` implementation returned a value that did not match `returns`. Raised at evaluation time, an authoring bug rather than a user one. */\n DEFINE_FUNCTION_RETURN_TYPE: \"DEFINE_FUNCTION_RETURN_TYPE\",\n} as const;\n\n/** A single identifier: a letter or underscore, then letters, digits, or underscores. */\nconst NAME_PATTERN = /^[a-z_][a-z0-9_]*$/i;\n\nconst SUPPORTED_TYPES: ReadonlySet<string> = new Set([\"number\", \"string\", \"boolean\"]);\n\n/** \"1 argument\" / \"2 arguments\", so a count reads as English either way. Mirrors `VMBuiltinArity.ts`. */\nfunction plural(count: number): string {\n return count === 1 ? \"1 argument\" : `${count} arguments`;\n}\n\n/**\n * A human noun for the type a Value actually carries, for the \"was given ...\"\n * half of a mismatch message. Covers the three declarable types by their own\n * names and everything else by a readable category, so the message never reads\n * \"given a 6\".\n */\nfunction describeValueType(v: Value): string {\n switch (v.type) {\n case ValueType.Number:\n case ValueType.Hex:\n return \"a number\";\n case ValueType.String:\n return \"a string\";\n case ValueType.Boolean:\n return \"a boolean\";\n case ValueType.BigInt:\n return \"a big integer\";\n case ValueType.Percentage:\n return \"a percentage\";\n case ValueType.Uom:\n return \"a value with a unit\";\n case ValueType.Datetime:\n return \"a date\";\n case ValueType.Matrix:\n return \"a matrix\";\n case ValueType.Range:\n return \"a range\";\n case ValueType.Symbolic:\n return \"a symbolic expression\";\n default:\n return \"an unsupported value\";\n }\n}\n\n/**\n * Read one runtime Value as the JS primitive its declared type promises, or\n * raise the engine's structured type error.\n *\n * A \"number\" accepts a plain number or a based literal (`0xFF`), both of which\n * ARE numbers written differently, and reads it with `toNumber()`. Nothing\n * else is coerced: a percentage, a unit-bearing value or a string is a\n * genuinely different kind of value, and silently reinterpreting it is the\n * class of wrong-answer this API exists to avoid.\n */\nfunction coerceArgument(\n value: Value,\n arg: FunctionArg,\n fnName: string,\n): number | string | boolean {\n switch (arg.type) {\n case \"number\":\n // Hex is a number in another base (see `hexValue`), so it reads as one here.\n if (value.type === ValueType.Number || value.type === ValueType.Hex) {\n return value.toNumber();\n }\n break;\n case \"string\":\n if (value.type === ValueType.String) return value.value as string;\n break;\n case \"boolean\":\n if (value.type === ValueType.Boolean) return value.value as boolean;\n break;\n }\n throw ErrorFactory.execution({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_ARGUMENT_TYPE,\n message: `${fnName}() expects \"${arg.name}\" to be a ${arg.type}, but was given ${describeValueType(value)}`,\n expected: `a ${arg.type}`,\n found: describeValueType(value),\n context: { functionName: fnName, argName: arg.name, expectedType: arg.type },\n });\n}\n\n/**\n * Wrap the `call` result back into a Value of the declared return type, or\n * raise a structured error if the implementation handed back something else.\n *\n * The type check here catches an authoring mistake (a function declared to\n * return a number that returns `undefined`, or a Promise from an accidental\n * `async`), turning it into a named error rather than a Value that lies about\n * its own type downstream.\n */\nfunction wrapReturn(result: unknown, returns: FunctionValueType, fnName: string): Value {\n switch (returns) {\n case \"number\":\n if (typeof result === \"number\") return numberValue(result);\n break;\n case \"string\":\n if (typeof result === \"string\") return stringValue(result);\n break;\n case \"boolean\":\n if (typeof result === \"boolean\") return boolValue(result);\n break;\n }\n throw ErrorFactory.internal({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_RETURN_TYPE,\n message: `${fnName}() is declared to return a ${returns}, but its implementation returned ${typeof result}`,\n expected: `a ${returns}`,\n found: typeof result,\n context: { functionName: fnName, expectedType: returns },\n });\n}\n\n/**\n * The call-syntax parselet generated for one declared function.\n *\n * Identical in shape to the built-in `FunctionCallParselet`: consume the open\n * paren, parse a comma-separated argument list, then emit `CALL_PLUGIN` with\n * the function's index and the argument count. The count is whatever was\n * written, arity is checked at the dispatch point (see {@link makeHandler}),\n * the same place the built-in arity check lives.\n */\nclass DefinedFunctionParselet implements PrefixParselet {\n readonly category = \"Function\";\n\n constructor(\n private readonly fnName: string,\n ) {}\n\n parse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n parser.consume(\"LPAREN\");\n\n let argCount = 0;\n if (parser.peek()?.type !== \"RPAREN\") {\n parser.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (parser.match(\"COMMA\")) {\n parser.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n\n parser.consume(\"RPAREN\");\n\n builder.emitPluginCall(this.fnName, argCount);\n }\n}\n\n/**\n * Build the plugin function that checks arity and argument types, calls the\n * host implementation, and wraps the result.\n *\n * The VM has already screened out faulted arguments (an errored or still\n * pending operand short-circuits before the handler runs, see\n * `VM.ts`'s `CALL_PLUGIN` case), so every Value reaching here carries a real\n * result. Arity is checked first, before any argument is read, so a wrong\n * count is reported as a wrong count rather than as a type error on a missing\n * argument.\n */\nfunction makeHandler(spec: FunctionSpec): (args: Value[]) => Value {\n const arity = spec.args.length;\n return (args: Value[]): Value => {\n if (args.length !== arity) {\n throw ErrorFactory.execution({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_ARITY_MISMATCH,\n message: `${spec.name}() takes ${plural(arity)}, but was given ${args.length === 0 ? \"none\" : plural(args.length)}`,\n expected: plural(arity),\n found: args.length === 0 ? \"none\" : plural(args.length),\n context: { functionName: spec.name, expected: arity, actual: args.length },\n });\n }\n\n const jsArgs: (number | string | boolean)[] = new Array(arity);\n for (let i = 0; i < arity; i++) {\n jsArgs[i] = coerceArgument(args[i], spec.args[i], spec.name);\n }\n\n const result = (spec.call as (...a: (number | string | boolean)[]) => unknown)(...jsArgs);\n return wrapReturn(result, spec.returns, spec.name);\n };\n}\n\n/** Reject a spec that could not produce a working function, before any engine sees it. */\nfunction validateSpec(spec: FunctionSpec): void {\n if (typeof spec?.name !== \"string\" || !NAME_PATTERN.test(spec.name)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_NAME,\n message: `defineFunction: name must be a single identifier, got ${JSON.stringify(spec?.name)}`,\n suggestion: 'e.g. \"vat\" or \"net_price\"',\n context: { name: spec?.name },\n });\n }\n if (!Array.isArray(spec.args)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" args must be an array`,\n context: { name: spec.name },\n });\n }\n for (const arg of spec.args) {\n if (typeof arg?.name !== \"string\" || arg.name.length === 0) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" has an argument with no name`,\n context: { name: spec.name },\n });\n }\n if (!SUPPORTED_TYPES.has(arg.type)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" argument \"${arg.name}\" has unsupported type ${JSON.stringify(arg.type)}`,\n suggestion: \"supported argument types are number, string, boolean\",\n context: { name: spec.name, argName: arg.name, type: arg.type },\n });\n }\n }\n if (!SUPPORTED_TYPES.has(spec.returns)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" has unsupported return type ${JSON.stringify(spec.returns)}`,\n suggestion: \"supported return types are number, string, boolean\",\n context: { name: spec.name, returns: spec.returns },\n });\n }\n if (typeof spec.call !== \"function\") {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" is missing a call implementation`,\n context: { name: spec.name },\n });\n }\n}\n\n/**\n * Turn a declarative {@link FunctionSpec} into a ready-to-register\n * {@link IEnginePackage}.\n *\n * This is the higher-level API from issue #102. It derives, from the\n * declaration alone, everything the low-level contract asks an author to write\n * by hand: a named plugin function (the engine assigns its `CALL_PLUGIN`\n * index), a lexer keyword so the name tokenises, a call-syntax parselet emitting\n * that call by name, and a handler that checks arity and argument types (yielding\n * the engine's own structured errors) before invoking `call` and wrapping its\n * result. Anything needing custom parsing keeps writing a raw parselet exactly\n * as before, this sits on top of that contract and does not change it.\n *\n * @example\n * ```ts\n * const engine = new ExpressionEngine({ packages: [\n * ...BUILTIN_PACKAGES,\n * defineFunction({\n * name: \"vat\",\n * args: [{ name: \"amount\", type: \"number\" }],\n * returns: \"number\",\n * call: (amount) => amount * 1.2,\n * }),\n * ] });\n * engine.evaluateExpression(\"vat(100)\"); // 120\n * ```\n *\n * The returned package is self-contained and composes with any others through\n * the engine's `packages` array; register several functions by passing several\n * packages. Its name is `solve-fn-<name>`.\n *\n * Scope: arguments are a fixed-length list of `number`/`string`/`boolean`, and\n * `call` is synchronous. Variadic and optional arguments, other value types\n * (units, percentages, dates, matrices), and async work are deliberately out\n * of scope, a function needing any of those keeps using the low-level\n * contract, whose parselets and async resolvers are unchanged.\n *\n * @throws {EngineError} (category CONFIG) if the spec is malformed, at the\n * point `defineFunction` is called, before the package reaches an engine.\n */\nexport function defineFunction<\n const A extends readonly FunctionArg[],\n R extends FunctionValueType,\n>(spec: FunctionSpec<A, R>): IEnginePackage {\n validateSpec(spec as FunctionSpec);\n\n const name = spec.name;\n // Uppercased so the generated type is a valid, collision-resistant token\n // type; the name pattern guarantees it forms one. Distinct from the\n // built-in FUNC type, so this never routes through the builtin name map.\n const tokenType = `DEFINE_FN_${name.toUpperCase()}`;\n\n return {\n name: `solve-fn-${name}`,\n lexerVocabulary: {\n // Lowercased because the lexer lowercases input before lookup, so the\n // call is matched case-insensitively.\n keywords: { [name.toLowerCase()]: tokenType },\n },\n prefixParselets: {\n [tokenType]: new DefinedFunctionParselet(name),\n },\n pluginFunctions: {\n [name]: makeHandler(spec as FunctionSpec),\n },\n };\n}\n","import { ExpressionEngine, type EngineOptions } from \"@solve-js/engine/ExpressionEngine\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\n\n/** Options for {@link createEngine}: the engine options, minus `packages` (the\n * built-in set is always registered), plus `extraPackages` to add your own. */\nexport interface CreateEngineOptions extends Omit<EngineOptions, \"packages\"> {\n\t/** Packages to register ON TOP of the built-in set (e.g. an OSRS or stocks package). */\n\textraPackages?: IEnginePackage[];\n}\n\n/**\n * A batteries-included {@link ExpressionEngine} with every built-in package\n * registered.\n *\n * The constructor registers only the packages it is given, so a consumer's\n * bundler can tree-shake away the built-ins they never use: an engine built\n * with `new ExpressionEngine({ packages: [ARITHMETIC_PACKAGE] })` carries no\n * finance, colour or weather code. This convenience is the opposite trade: it\n * pulls the FULL built-in set (`BUILTIN_PACKAGES`) for the common \"I want\n * everything\" case, so importing it defeats that tree-shaking. Reach for the\n * constructor with an explicit package list when bundle size matters, and for\n * `createEngine` when it does not.\n *\n * @param options - Engine options ({@link EngineOptions}) minus `packages`, plus\n * an optional `extraPackages` to register alongside the built-in set.\n * @returns An engine with the built-in packages (and any extras) registered.\n *\n * @example\n * ```typescript\n * import { createEngine } from \"solve-engine\";\n * const engine = createEngine();\n * const value = engine.evaluateExpression(\"2 + 2 * 10\");\n * console.log(value.toNumber()); // 22\n * ```\n */\nexport function createEngine(options: CreateEngineOptions = {}): ExpressionEngine {\n\tconst { extraPackages = [], ...engineOptions } = options;\n\treturn new ExpressionEngine({\n\t\t...engineOptions,\n\t\tpackages: extraPackages.length > 0 ? [...BUILTIN_PACKAGES, ...extraPackages] : BUILTIN_PACKAGES,\n\t});\n}\n"]}
package/dist/language.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkBVSATTRX_cjs=require('./chunk-BVSATTRX.cjs'),chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),chunkIXOE2BQG_cjs=require('./chunk-IXOE2BQG.cjs');require('./chunk-XB3TWS7J.cjs');var I=50,C={variable:0,function:1,keyword:1,operator:1,comparison:1,bitwise:1,datetime:1,vector:1,unit:2},T=2e3,p=class{constructor(e,o){this.cache=new Map;this.staticCompletionCandidates=null;this.staticCompletionIndex=null;this.engine=e??null,this.variableNameSource=o?.variableNameSource??(()=>this.defaultVariableNames()),this.normalizeForHighlighting=o?.normalizeForHighlighting??false;}defaultVariableNames(){if(!this.engine)return [];let e=this.engine.getDag().getSnapshot(),o=new Set(Object.keys(e.consumers));for(let n of Object.values(e.writes))for(let i of n)o.add(i);return o}classifyNormalized(e){let o=this.engine.getLexer(),n=o.getHighlightTokenObjects(e);if(n.length===0)return [];let i=e.startsWith("> ")&&o.classifyLine(e).skip?e.slice(2):e,r;try{r=this.engine.getNormalizer().normalize(n);}catch{r=n;}let l=[];for(let t of r){let s;if(t.sourceEnd!==void 0)s=t.sourceEnd;else if(i.startsWith(t.text,t.offset))s=t.offset+t.text.length;else continue;l.push({type:t.type,value:t.value,offset:t.offset,col:t.col,length:s-t.offset,category:chunkY7O4D3BJ_cjs.d(t.type)});}return l}getSemanticTokens(e,o){let n=this.cache.get(o);if(n&&n.text===e)return n.bareWordCandidate!==void 0?this.isKnownVariable(n.bareWordCandidate)?n.tokens:[]:n.tokens;if(!this.engine)return [];let i=this.engine.getLexer(),r=this.normalizeForHighlighting?this.classifyNormalized(e):i.getHighlightTokens(e);if(r.length===0)return this.putCache(o,e,[]),[];let l=i.classifyLine(e),t=[];if(l.hasInlineSolve){let s=i.findInlineSolves(e).filter(a=>this.parsesAsExpression(a.expression)).map(a=>({from:a.start,to:a.end}));for(let a of r){if(!a.category)continue;let m=a.offset,f=a.offset+a.length;s.some(u=>m>=u.from&&f<=u.to)&&t.push({from:m,to:f,category:a.category});}}else {let s=e.startsWith("> ")&&l.skip?e.slice(2):e;if(this.parsesAsExpression(s))for(let a of r)a.category&&t.push({from:a.offset,to:a.offset+a.length,category:a.category});}if(t.length===1&&t[0].category==="variable"){let s=e.slice(t[0].from,t[0].to);return this.putCache(o,e,t,s),this.isKnownVariable(s)?t:[]}return this.putCache(o,e,t),t}getCompletions(e,o){let n=/[A-Za-z0-9_]+$/.exec(e.slice(0,o));if(!n)return [];let i=n[0].toLowerCase();if(!this.engine)return [];let r=[];for(let t of this.variableNameSource())t.toLowerCase().startsWith(i)&&r.push({label:t,category:"variable"});let l=this.getStaticCompletionIndex().get(i[0]);if(l)for(let t of l)t.lowerLabel.startsWith(i)&&r.push(t.item);return r.sort((t,s)=>{let a=(C[t.category]??3)-(C[s.category]??3);return a!==0?a:t.label.localeCompare(s.label)}),r.slice(0,I)}getStaticCompletionCandidates(){if(this.staticCompletionCandidates)return this.staticCompletionCandidates;let e=[];for(let[o,n]of Object.entries(this.engine.getLexer().getKeywords())){let i=chunkY7O4D3BJ_cjs.d(n);i&&e.push({label:o,category:i});}for(let o of chunkIXOE2BQG_cjs.a)e.push({label:o,category:"unit",detail:chunkBVSATTRX_cjs.c(o)});return e.push(...this.engine.getPackageCompletionItems()),this.staticCompletionCandidates=e,e}getStaticCompletionIndex(){if(this.staticCompletionIndex)return this.staticCompletionIndex;let e=new Map;for(let o of this.getStaticCompletionCandidates()){let n=o.label.toLowerCase(),i=n[0];if(i===void 0)continue;let r=e.get(i);r===void 0&&(r=[],e.set(i,r)),r.push({item:o,lowerLabel:n});}return this.staticCompletionIndex=e,e}isKnownVariable(e){for(let o of this.variableNameSource())if(o===e)return true;return false}parsesAsExpression(e){return this.engine.tryCompileExpression(e)}putCache(e,o,n,i){if(!this.cache.has(e)&&this.cache.size>=T){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r);}this.cache.set(e,{text:o,tokens:n,bareWordCandidate:i});}invalidateLines(e){for(let o of e)this.cache.delete(o);}invalidateCache(){this.cache.clear(),this.staticCompletionCandidates=null,this.staticCompletionIndex=null;}};var y="solve-";function x(c,e=y){return `${e}${c}`}function E(c){return e=>`${c}${e}`}var S={keyword:"keyword",operator:"keyword",comparison:"keyword",bitwise:"keyword",function:"function",variable:"variable",unit:"type",datetime:"keyword",vector:"type"};function w(c){return {label:c.label,type:S[c.category]??"text",detail:c.detail}}Object.defineProperty(exports,"UNCATEGORIZED_TOKEN_TYPES",{enumerable:true,get:function(){return chunkY7O4D3BJ_cjs.a}});Object.defineProperty(exports,"getTokenCategory",{enumerable:true,get:function(){return chunkY7O4D3BJ_cjs.d}});Object.defineProperty(exports,"registerTokenCategory",{enumerable:true,get:function(){return chunkY7O4D3BJ_cjs.b}});Object.defineProperty(exports,"unregisterTokenCategory",{enumerable:true,get:function(){return chunkY7O4D3BJ_cjs.c}});exports.DEFAULT_TOKEN_CLASS_PREFIX=y;exports.LanguageService=p;exports.completionItemToOption=w;exports.createTokenClassName=E;exports.tokenClassName=x;//# sourceMappingURL=language.cjs.map
1
+ 'use strict';var chunkZKFCKAIX_cjs=require('./chunk-ZKFCKAIX.cjs'),chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),chunkJ4LSAHCY_cjs=require('./chunk-J4LSAHCY.cjs');require('./chunk-EZKR44MA.cjs');var I=50,C={variable:0,function:1,keyword:1,operator:1,comparison:1,bitwise:1,datetime:1,vector:1,unit:2},T=2e3,p=class{constructor(e,o){this.cache=new Map;this.staticCompletionCandidates=null;this.staticCompletionIndex=null;this.engine=e??null,this.variableNameSource=o?.variableNameSource??(()=>this.defaultVariableNames()),this.normalizeForHighlighting=o?.normalizeForHighlighting??false;}defaultVariableNames(){if(!this.engine)return [];let e=this.engine.getDag().getSnapshot(),o=new Set(Object.keys(e.consumers));for(let n of Object.values(e.writes))for(let i of n)o.add(i);return o}classifyNormalized(e){let o=this.engine.getLexer(),n=o.getHighlightTokenObjects(e);if(n.length===0)return [];let i=e.startsWith("> ")&&o.classifyLine(e).skip?e.slice(2):e,r;try{r=this.engine.getNormalizer().normalize(n);}catch{r=n;}let l=[];for(let t of r){let s;if(t.sourceEnd!==void 0)s=t.sourceEnd;else if(i.startsWith(t.text,t.offset))s=t.offset+t.text.length;else continue;l.push({type:t.type,value:t.value,offset:t.offset,col:t.col,length:s-t.offset,category:chunkY7O4D3BJ_cjs.d(t.type)});}return l}getSemanticTokens(e,o){let n=this.cache.get(o);if(n&&n.text===e)return n.bareWordCandidate!==void 0?this.isKnownVariable(n.bareWordCandidate)?n.tokens:[]:n.tokens;if(!this.engine)return [];let i=this.engine.getLexer(),r=this.normalizeForHighlighting?this.classifyNormalized(e):i.getHighlightTokens(e);if(r.length===0)return this.putCache(o,e,[]),[];let l=i.classifyLine(e),t=[];if(l.hasInlineSolve){let s=i.findInlineSolves(e).filter(a=>this.parsesAsExpression(a.expression)).map(a=>({from:a.start,to:a.end}));for(let a of r){if(!a.category)continue;let m=a.offset,f=a.offset+a.length;s.some(u=>m>=u.from&&f<=u.to)&&t.push({from:m,to:f,category:a.category});}}else {let s=e.startsWith("> ")&&l.skip?e.slice(2):e;if(this.parsesAsExpression(s))for(let a of r)a.category&&t.push({from:a.offset,to:a.offset+a.length,category:a.category});}if(t.length===1&&t[0].category==="variable"){let s=e.slice(t[0].from,t[0].to);return this.putCache(o,e,t,s),this.isKnownVariable(s)?t:[]}return this.putCache(o,e,t),t}getCompletions(e,o){let n=/[A-Za-z0-9_]+$/.exec(e.slice(0,o));if(!n)return [];let i=n[0].toLowerCase();if(!this.engine)return [];let r=[];for(let t of this.variableNameSource())t.toLowerCase().startsWith(i)&&r.push({label:t,category:"variable"});let l=this.getStaticCompletionIndex().get(i[0]);if(l)for(let t of l)t.lowerLabel.startsWith(i)&&r.push(t.item);return r.sort((t,s)=>{let a=(C[t.category]??3)-(C[s.category]??3);return a!==0?a:t.label.localeCompare(s.label)}),r.slice(0,I)}getStaticCompletionCandidates(){if(this.staticCompletionCandidates)return this.staticCompletionCandidates;let e=[];for(let[o,n]of Object.entries(this.engine.getLexer().getKeywords())){let i=chunkY7O4D3BJ_cjs.d(n);i&&e.push({label:o,category:i});}for(let o of chunkJ4LSAHCY_cjs.a)e.push({label:o,category:"unit",detail:chunkZKFCKAIX_cjs.c(o)});return e.push(...this.engine.getPackageCompletionItems()),this.staticCompletionCandidates=e,e}getStaticCompletionIndex(){if(this.staticCompletionIndex)return this.staticCompletionIndex;let e=new Map;for(let o of this.getStaticCompletionCandidates()){let n=o.label.toLowerCase(),i=n[0];if(i===void 0)continue;let r=e.get(i);r===void 0&&(r=[],e.set(i,r)),r.push({item:o,lowerLabel:n});}return this.staticCompletionIndex=e,e}isKnownVariable(e){for(let o of this.variableNameSource())if(o===e)return true;return false}parsesAsExpression(e){return this.engine.tryCompileExpression(e)}putCache(e,o,n,i){if(!this.cache.has(e)&&this.cache.size>=T){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r);}this.cache.set(e,{text:o,tokens:n,bareWordCandidate:i});}invalidateLines(e){for(let o of e)this.cache.delete(o);}invalidateCache(){this.cache.clear(),this.staticCompletionCandidates=null,this.staticCompletionIndex=null;}};var y="solve-";function x(c,e=y){return `${e}${c}`}function E(c){return e=>`${c}${e}`}var S={keyword:"keyword",operator:"keyword",comparison:"keyword",bitwise:"keyword",function:"function",variable:"variable",unit:"type",datetime:"keyword",vector:"type"};function w(c){return {label:c.label,type:S[c.category]??"text",detail:c.detail}}Object.defineProperty(exports,"UNCATEGORIZED_TOKEN_TYPES",{enumerable:true,get:function(){return chunkY7O4D3BJ_cjs.a}});Object.defineProperty(exports,"getTokenCategory",{enumerable:true,get:function(){return chunkY7O4D3BJ_cjs.d}});Object.defineProperty(exports,"registerTokenCategory",{enumerable:true,get:function(){return chunkY7O4D3BJ_cjs.b}});Object.defineProperty(exports,"unregisterTokenCategory",{enumerable:true,get:function(){return chunkY7O4D3BJ_cjs.c}});exports.DEFAULT_TOKEN_CLASS_PREFIX=y;exports.LanguageService=p;exports.completionItemToOption=w;exports.createTokenClassName=E;exports.tokenClassName=x;//# sourceMappingURL=language.cjs.map
2
2
  //# sourceMappingURL=language.cjs.map
package/dist/language.js CHANGED
@@ -1,2 +1,2 @@
1
- import {c}from'./chunk-6YGRMAQR.js';import {d}from'./chunk-JPFCXLJV.js';export{a as UNCATEGORIZED_TOKEN_TYPES,d as getTokenCategory,b as registerTokenCategory,c as unregisterTokenCategory}from'./chunk-JPFCXLJV.js';import {a}from'./chunk-6NXOKM2O.js';import'./chunk-MDLR2PWN.js';var I=50,C={variable:0,function:1,keyword:1,operator:1,comparison:1,bitwise:1,datetime:1,vector:1,unit:2},T=2e3,p=class{constructor(e,o){this.cache=new Map;this.staticCompletionCandidates=null;this.staticCompletionIndex=null;this.engine=e??null,this.variableNameSource=o?.variableNameSource??(()=>this.defaultVariableNames()),this.normalizeForHighlighting=o?.normalizeForHighlighting??false;}defaultVariableNames(){if(!this.engine)return [];let e=this.engine.getDag().getSnapshot(),o=new Set(Object.keys(e.consumers));for(let n of Object.values(e.writes))for(let i of n)o.add(i);return o}classifyNormalized(e){let o=this.engine.getLexer(),n=o.getHighlightTokenObjects(e);if(n.length===0)return [];let i=e.startsWith("> ")&&o.classifyLine(e).skip?e.slice(2):e,r;try{r=this.engine.getNormalizer().normalize(n);}catch{r=n;}let l=[];for(let t of r){let s;if(t.sourceEnd!==void 0)s=t.sourceEnd;else if(i.startsWith(t.text,t.offset))s=t.offset+t.text.length;else continue;l.push({type:t.type,value:t.value,offset:t.offset,col:t.col,length:s-t.offset,category:d(t.type)});}return l}getSemanticTokens(e,o){let n=this.cache.get(o);if(n&&n.text===e)return n.bareWordCandidate!==void 0?this.isKnownVariable(n.bareWordCandidate)?n.tokens:[]:n.tokens;if(!this.engine)return [];let i=this.engine.getLexer(),r=this.normalizeForHighlighting?this.classifyNormalized(e):i.getHighlightTokens(e);if(r.length===0)return this.putCache(o,e,[]),[];let l=i.classifyLine(e),t=[];if(l.hasInlineSolve){let s=i.findInlineSolves(e).filter(a=>this.parsesAsExpression(a.expression)).map(a=>({from:a.start,to:a.end}));for(let a of r){if(!a.category)continue;let m=a.offset,f=a.offset+a.length;s.some(u=>m>=u.from&&f<=u.to)&&t.push({from:m,to:f,category:a.category});}}else {let s=e.startsWith("> ")&&l.skip?e.slice(2):e;if(this.parsesAsExpression(s))for(let a of r)a.category&&t.push({from:a.offset,to:a.offset+a.length,category:a.category});}if(t.length===1&&t[0].category==="variable"){let s=e.slice(t[0].from,t[0].to);return this.putCache(o,e,t,s),this.isKnownVariable(s)?t:[]}return this.putCache(o,e,t),t}getCompletions(e,o){let n=/[A-Za-z0-9_]+$/.exec(e.slice(0,o));if(!n)return [];let i=n[0].toLowerCase();if(!this.engine)return [];let r=[];for(let t of this.variableNameSource())t.toLowerCase().startsWith(i)&&r.push({label:t,category:"variable"});let l=this.getStaticCompletionIndex().get(i[0]);if(l)for(let t of l)t.lowerLabel.startsWith(i)&&r.push(t.item);return r.sort((t,s)=>{let a=(C[t.category]??3)-(C[s.category]??3);return a!==0?a:t.label.localeCompare(s.label)}),r.slice(0,I)}getStaticCompletionCandidates(){if(this.staticCompletionCandidates)return this.staticCompletionCandidates;let e=[];for(let[o,n]of Object.entries(this.engine.getLexer().getKeywords())){let i=d(n);i&&e.push({label:o,category:i});}for(let o of a)e.push({label:o,category:"unit",detail:c(o)});return e.push(...this.engine.getPackageCompletionItems()),this.staticCompletionCandidates=e,e}getStaticCompletionIndex(){if(this.staticCompletionIndex)return this.staticCompletionIndex;let e=new Map;for(let o of this.getStaticCompletionCandidates()){let n=o.label.toLowerCase(),i=n[0];if(i===void 0)continue;let r=e.get(i);r===void 0&&(r=[],e.set(i,r)),r.push({item:o,lowerLabel:n});}return this.staticCompletionIndex=e,e}isKnownVariable(e){for(let o of this.variableNameSource())if(o===e)return true;return false}parsesAsExpression(e){return this.engine.tryCompileExpression(e)}putCache(e,o,n,i){if(!this.cache.has(e)&&this.cache.size>=T){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r);}this.cache.set(e,{text:o,tokens:n,bareWordCandidate:i});}invalidateLines(e){for(let o of e)this.cache.delete(o);}invalidateCache(){this.cache.clear(),this.staticCompletionCandidates=null,this.staticCompletionIndex=null;}};var y="solve-";function x(c,e=y){return `${e}${c}`}function E(c){return e=>`${c}${e}`}var S={keyword:"keyword",operator:"keyword",comparison:"keyword",bitwise:"keyword",function:"function",variable:"variable",unit:"type",datetime:"keyword",vector:"type"};function w(c){return {label:c.label,type:S[c.category]??"text",detail:c.detail}}export{y as DEFAULT_TOKEN_CLASS_PREFIX,p as LanguageService,w as completionItemToOption,E as createTokenClassName,x as tokenClassName};//# sourceMappingURL=language.js.map
1
+ import {c}from'./chunk-4CNYGIND.js';import {d}from'./chunk-JPFCXLJV.js';export{a as UNCATEGORIZED_TOKEN_TYPES,d as getTokenCategory,b as registerTokenCategory,c as unregisterTokenCategory}from'./chunk-JPFCXLJV.js';import {a}from'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';var I=50,C={variable:0,function:1,keyword:1,operator:1,comparison:1,bitwise:1,datetime:1,vector:1,unit:2},T=2e3,p=class{constructor(e,o){this.cache=new Map;this.staticCompletionCandidates=null;this.staticCompletionIndex=null;this.engine=e??null,this.variableNameSource=o?.variableNameSource??(()=>this.defaultVariableNames()),this.normalizeForHighlighting=o?.normalizeForHighlighting??false;}defaultVariableNames(){if(!this.engine)return [];let e=this.engine.getDag().getSnapshot(),o=new Set(Object.keys(e.consumers));for(let n of Object.values(e.writes))for(let i of n)o.add(i);return o}classifyNormalized(e){let o=this.engine.getLexer(),n=o.getHighlightTokenObjects(e);if(n.length===0)return [];let i=e.startsWith("> ")&&o.classifyLine(e).skip?e.slice(2):e,r;try{r=this.engine.getNormalizer().normalize(n);}catch{r=n;}let l=[];for(let t of r){let s;if(t.sourceEnd!==void 0)s=t.sourceEnd;else if(i.startsWith(t.text,t.offset))s=t.offset+t.text.length;else continue;l.push({type:t.type,value:t.value,offset:t.offset,col:t.col,length:s-t.offset,category:d(t.type)});}return l}getSemanticTokens(e,o){let n=this.cache.get(o);if(n&&n.text===e)return n.bareWordCandidate!==void 0?this.isKnownVariable(n.bareWordCandidate)?n.tokens:[]:n.tokens;if(!this.engine)return [];let i=this.engine.getLexer(),r=this.normalizeForHighlighting?this.classifyNormalized(e):i.getHighlightTokens(e);if(r.length===0)return this.putCache(o,e,[]),[];let l=i.classifyLine(e),t=[];if(l.hasInlineSolve){let s=i.findInlineSolves(e).filter(a=>this.parsesAsExpression(a.expression)).map(a=>({from:a.start,to:a.end}));for(let a of r){if(!a.category)continue;let m=a.offset,f=a.offset+a.length;s.some(u=>m>=u.from&&f<=u.to)&&t.push({from:m,to:f,category:a.category});}}else {let s=e.startsWith("> ")&&l.skip?e.slice(2):e;if(this.parsesAsExpression(s))for(let a of r)a.category&&t.push({from:a.offset,to:a.offset+a.length,category:a.category});}if(t.length===1&&t[0].category==="variable"){let s=e.slice(t[0].from,t[0].to);return this.putCache(o,e,t,s),this.isKnownVariable(s)?t:[]}return this.putCache(o,e,t),t}getCompletions(e,o){let n=/[A-Za-z0-9_]+$/.exec(e.slice(0,o));if(!n)return [];let i=n[0].toLowerCase();if(!this.engine)return [];let r=[];for(let t of this.variableNameSource())t.toLowerCase().startsWith(i)&&r.push({label:t,category:"variable"});let l=this.getStaticCompletionIndex().get(i[0]);if(l)for(let t of l)t.lowerLabel.startsWith(i)&&r.push(t.item);return r.sort((t,s)=>{let a=(C[t.category]??3)-(C[s.category]??3);return a!==0?a:t.label.localeCompare(s.label)}),r.slice(0,I)}getStaticCompletionCandidates(){if(this.staticCompletionCandidates)return this.staticCompletionCandidates;let e=[];for(let[o,n]of Object.entries(this.engine.getLexer().getKeywords())){let i=d(n);i&&e.push({label:o,category:i});}for(let o of a)e.push({label:o,category:"unit",detail:c(o)});return e.push(...this.engine.getPackageCompletionItems()),this.staticCompletionCandidates=e,e}getStaticCompletionIndex(){if(this.staticCompletionIndex)return this.staticCompletionIndex;let e=new Map;for(let o of this.getStaticCompletionCandidates()){let n=o.label.toLowerCase(),i=n[0];if(i===void 0)continue;let r=e.get(i);r===void 0&&(r=[],e.set(i,r)),r.push({item:o,lowerLabel:n});}return this.staticCompletionIndex=e,e}isKnownVariable(e){for(let o of this.variableNameSource())if(o===e)return true;return false}parsesAsExpression(e){return this.engine.tryCompileExpression(e)}putCache(e,o,n,i){if(!this.cache.has(e)&&this.cache.size>=T){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r);}this.cache.set(e,{text:o,tokens:n,bareWordCandidate:i});}invalidateLines(e){for(let o of e)this.cache.delete(o);}invalidateCache(){this.cache.clear(),this.staticCompletionCandidates=null,this.staticCompletionIndex=null;}};var y="solve-";function x(c,e=y){return `${e}${c}`}function E(c){return e=>`${c}${e}`}var S={keyword:"keyword",operator:"keyword",comparison:"keyword",bitwise:"keyword",function:"function",variable:"variable",unit:"type",datetime:"keyword",vector:"type"};function w(c){return {label:c.label,type:S[c.category]??"text",detail:c.detail}}export{y as DEFAULT_TOKEN_CLASS_PREFIX,p as LanguageService,w as completionItemToOption,E as createTokenClassName,x as tokenClassName};//# sourceMappingURL=language.js.map
2
2
  //# sourceMappingURL=language.js.map
package/dist/lexer.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkTM752D4J_cjs=require('./chunk-TM752D4J.cjs');require('./chunk-Y7O4D3BJ.cjs');var chunkEAB6SSAV_cjs=require('./chunk-EAB6SSAV.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs');require('./chunk-S3DFU33X.cjs');var chunkIXOE2BQG_cjs=require('./chunk-IXOE2BQG.cjs');require('./chunk-XB3TWS7J.cjs'),require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"Lexer",{enumerable:true,get:function(){return chunkTM752D4J_cjs.b}});Object.defineProperty(exports,"LexerState",{enumerable:true,get:function(){return chunkTM752D4J_cjs.a}});Object.defineProperty(exports,"buildTokenLookup",{enumerable:true,get:function(){return chunkTM752D4J_cjs.d}});Object.defineProperty(exports,"sharedLexer",{enumerable:true,get:function(){return chunkTM752D4J_cjs.c}});Object.defineProperty(exports,"ExpressionLexer",{enumerable:true,get:function(){return chunkEAB6SSAV_cjs.b}});Object.defineProperty(exports,"LexerToken",{enumerable:true,get:function(){return chunkEAB6SSAV_cjs.a}});Object.defineProperty(exports,"TokenTypes",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.a}});Object.defineProperty(exports,"registerAllTokenTypes",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.e}});Object.defineProperty(exports,"registerTokenType",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.b}});Object.defineProperty(exports,"tokenTypeId",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.c}});Object.defineProperty(exports,"tokenTypeName",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.d}});Object.defineProperty(exports,"knownUnits",{enumerable:true,get:function(){return chunkIXOE2BQG_cjs.a}});//# sourceMappingURL=lexer.cjs.map
1
+ 'use strict';var chunkKRXO3MOW_cjs=require('./chunk-KRXO3MOW.cjs');require('./chunk-Y7O4D3BJ.cjs');var chunkUSQ4KL6S_cjs=require('./chunk-USQ4KL6S.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs');require('./chunk-S3DFU33X.cjs');var chunkJ4LSAHCY_cjs=require('./chunk-J4LSAHCY.cjs');require('./chunk-EZKR44MA.cjs'),require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"Lexer",{enumerable:true,get:function(){return chunkKRXO3MOW_cjs.b}});Object.defineProperty(exports,"LexerState",{enumerable:true,get:function(){return chunkKRXO3MOW_cjs.a}});Object.defineProperty(exports,"buildTokenLookup",{enumerable:true,get:function(){return chunkKRXO3MOW_cjs.d}});Object.defineProperty(exports,"sharedLexer",{enumerable:true,get:function(){return chunkKRXO3MOW_cjs.c}});Object.defineProperty(exports,"ExpressionLexer",{enumerable:true,get:function(){return chunkUSQ4KL6S_cjs.b}});Object.defineProperty(exports,"LexerToken",{enumerable:true,get:function(){return chunkUSQ4KL6S_cjs.a}});Object.defineProperty(exports,"TokenTypes",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.a}});Object.defineProperty(exports,"registerAllTokenTypes",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.e}});Object.defineProperty(exports,"registerTokenType",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.b}});Object.defineProperty(exports,"tokenTypeId",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.c}});Object.defineProperty(exports,"tokenTypeName",{enumerable:true,get:function(){return chunk5IJD5L3O_cjs.d}});Object.defineProperty(exports,"knownUnits",{enumerable:true,get:function(){return chunkJ4LSAHCY_cjs.a}});//# sourceMappingURL=lexer.cjs.map
2
2
  //# sourceMappingURL=lexer.cjs.map
package/dist/lexer.js CHANGED
@@ -1,2 +1,2 @@
1
- export{b as Lexer,a as LexerState,d as buildTokenLookup,c as sharedLexer}from'./chunk-6EPJNHSQ.js';import'./chunk-JPFCXLJV.js';export{b as ExpressionLexer,a as LexerToken}from'./chunk-BB5RRSGS.js';export{a as TokenTypes,e as registerAllTokenTypes,b as registerTokenType,c as tokenTypeId,d as tokenTypeName}from'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';export{a as knownUnits}from'./chunk-6NXOKM2O.js';import'./chunk-MDLR2PWN.js';import'./chunk-PIZQIQVM.js';//# sourceMappingURL=lexer.js.map
1
+ export{b as Lexer,a as LexerState,d as buildTokenLookup,c as sharedLexer}from'./chunk-FP6Z6PYR.js';import'./chunk-JPFCXLJV.js';export{b as ExpressionLexer,a as LexerToken}from'./chunk-AF7HQN6I.js';export{a as TokenTypes,e as registerAllTokenTypes,b as registerTokenType,c as tokenTypeId,d as tokenTypeName}from'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';export{a as knownUnits}from'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import'./chunk-PIZQIQVM.js';//# sourceMappingURL=lexer.js.map
2
2
  //# sourceMappingURL=lexer.js.map
@@ -1,2 +1,2 @@
1
- 'use strict';require('./chunk-NGBBNL4K.cjs');var chunkKLPKLTJZ_cjs=require('./chunk-KLPKLTJZ.cjs');require('./chunk-EAB6SSAV.cjs'),require('./chunk-5IJD5L3O.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-IXOE2BQG.cjs'),require('./chunk-XB3TWS7J.cjs'),require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"BUILTIN_PHRASES",{enumerable:true,get:function(){return chunkKLPKLTJZ_cjs.g}});Object.defineProperty(exports,"PhraseTrie",{enumerable:true,get:function(){return chunkKLPKLTJZ_cjs.a}});Object.defineProperty(exports,"TokenNormalizer",{enumerable:true,get:function(){return chunkKLPKLTJZ_cjs.c}});Object.defineProperty(exports,"createBuiltinNormalizerRules",{enumerable:true,get:function(){return chunkKLPKLTJZ_cjs.f}});Object.defineProperty(exports,"createFusedToken",{enumerable:true,get:function(){return chunkKLPKLTJZ_cjs.b}});Object.defineProperty(exports,"implicitMultiplyRule",{enumerable:true,get:function(){return chunkKLPKLTJZ_cjs.d}});//# sourceMappingURL=normalizer.cjs.map
1
+ 'use strict';require('./chunk-NGBBNL4K.cjs');var chunkSGIDBZ4T_cjs=require('./chunk-SGIDBZ4T.cjs');require('./chunk-USQ4KL6S.cjs'),require('./chunk-5IJD5L3O.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs'),require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"BUILTIN_PHRASES",{enumerable:true,get:function(){return chunkSGIDBZ4T_cjs.g}});Object.defineProperty(exports,"PhraseTrie",{enumerable:true,get:function(){return chunkSGIDBZ4T_cjs.a}});Object.defineProperty(exports,"TokenNormalizer",{enumerable:true,get:function(){return chunkSGIDBZ4T_cjs.c}});Object.defineProperty(exports,"createBuiltinNormalizerRules",{enumerable:true,get:function(){return chunkSGIDBZ4T_cjs.f}});Object.defineProperty(exports,"createFusedToken",{enumerable:true,get:function(){return chunkSGIDBZ4T_cjs.b}});Object.defineProperty(exports,"implicitMultiplyRule",{enumerable:true,get:function(){return chunkSGIDBZ4T_cjs.d}});//# sourceMappingURL=normalizer.cjs.map
2
2
  //# sourceMappingURL=normalizer.cjs.map
@@ -1,2 +1,2 @@
1
- import'./chunk-2RWAXT6O.js';export{g as BUILTIN_PHRASES,a as PhraseTrie,c as TokenNormalizer,f as createBuiltinNormalizerRules,b as createFusedToken,d as implicitMultiplyRule}from'./chunk-DLXG73JZ.js';import'./chunk-BB5RRSGS.js';import'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';import'./chunk-6NXOKM2O.js';import'./chunk-MDLR2PWN.js';import'./chunk-PIZQIQVM.js';//# sourceMappingURL=normalizer.js.map
1
+ import'./chunk-2RWAXT6O.js';export{g as BUILTIN_PHRASES,a as PhraseTrie,c as TokenNormalizer,f as createBuiltinNormalizerRules,b as createFusedToken,d as implicitMultiplyRule}from'./chunk-4DJJIUQF.js';import'./chunk-AF7HQN6I.js';import'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import'./chunk-PIZQIQVM.js';//# sourceMappingURL=normalizer.js.map
2
2
  //# sourceMappingURL=normalizer.js.map
package/dist/packages.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk3AES5ZGS_cjs=require('./chunk-3AES5ZGS.cjs');require('./chunk-TL545PXW.cjs');var chunk53JLDRXA_cjs=require('./chunk-53JLDRXA.cjs');require('./chunk-EN3CDYOS.cjs'),require('./chunk-KLPKLTJZ.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-HCPZRSHR.cjs'),require('./chunk-6YM67DWH.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-J7ABVGZH.cjs'),require('./chunk-75JLWK4L.cjs'),require('./chunk-BVSATTRX.cjs'),require('./chunk-EAB6SSAV.cjs'),require('./chunk-5IJD5L3O.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-IXOE2BQG.cjs'),require('./chunk-XB3TWS7J.cjs'),require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"ARITHMETIC_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.a}});Object.defineProperty(exports,"BIGINT_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.n}});Object.defineProperty(exports,"BUILTIN_PACKAGES",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.y}});Object.defineProperty(exports,"CONDITIONALS_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.o}});Object.defineProperty(exports,"CONVERTERS_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.p}});Object.defineProperty(exports,"CURRENCY_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.j}});Object.defineProperty(exports,"DATETIME_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.d}});Object.defineProperty(exports,"DICE_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.f}});Object.defineProperty(exports,"FINANCE_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.r}});Object.defineProperty(exports,"FUNCTION_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.c}});Object.defineProperty(exports,"LINES_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.v}});Object.defineProperty(exports,"MAPREDUCE_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.m}});Object.defineProperty(exports,"MATHPHRASES_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.q}});Object.defineProperty(exports,"MATRIX_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.l}});Object.defineProperty(exports,"PERCENTAGE_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.b}});Object.defineProperty(exports,"TABLES_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.w}});Object.defineProperty(exports,"TAGS_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.x}});Object.defineProperty(exports,"TIME_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.e}});Object.defineProperty(exports,"UOM_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.h}});Object.defineProperty(exports,"VARIABLES_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.g}});Object.defineProperty(exports,"VECTOR_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.k}});Object.defineProperty(exports,"WEATHER_PACKAGE",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.s}});Object.defineProperty(exports,"createCurrencyPackage",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.i}});Object.defineProperty(exports,"createKnowledgePackage",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.u}});Object.defineProperty(exports,"createStocksPackage",{enumerable:true,get:function(){return chunk3AES5ZGS_cjs.t}});Object.defineProperty(exports,"SYMBOLIC_PACKAGE",{enumerable:true,get:function(){return chunk53JLDRXA_cjs.a}});//# sourceMappingURL=packages.cjs.map
1
+ 'use strict';var chunk4UHAGMER_cjs=require('./chunk-4UHAGMER.cjs');require('./chunk-TL545PXW.cjs');var chunkN37PUZJR_cjs=require('./chunk-N37PUZJR.cjs');require('./chunk-EN3CDYOS.cjs'),require('./chunk-SGIDBZ4T.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-XDXIPVZB.cjs'),require('./chunk-6YM67DWH.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-J7ABVGZH.cjs'),require('./chunk-75JLWK4L.cjs'),require('./chunk-ZKFCKAIX.cjs'),require('./chunk-USQ4KL6S.cjs'),require('./chunk-5IJD5L3O.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs'),require('./chunk-CO2BI6WL.cjs');Object.defineProperty(exports,"ARITHMETIC_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.a}});Object.defineProperty(exports,"BIGINT_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.n}});Object.defineProperty(exports,"BUILTIN_PACKAGES",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.z}});Object.defineProperty(exports,"CONDITIONALS_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.o}});Object.defineProperty(exports,"CONVERTERS_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.p}});Object.defineProperty(exports,"CURRENCY_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.j}});Object.defineProperty(exports,"DATETIME_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.d}});Object.defineProperty(exports,"DICE_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.f}});Object.defineProperty(exports,"FINANCE_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.r}});Object.defineProperty(exports,"FUNCTION_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.c}});Object.defineProperty(exports,"LINES_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.w}});Object.defineProperty(exports,"MAPREDUCE_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.m}});Object.defineProperty(exports,"MATHPHRASES_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.q}});Object.defineProperty(exports,"MATRIX_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.l}});Object.defineProperty(exports,"PERCENTAGE_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.b}});Object.defineProperty(exports,"TABLES_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.x}});Object.defineProperty(exports,"TAGS_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.y}});Object.defineProperty(exports,"TIME_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.e}});Object.defineProperty(exports,"UOM_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.h}});Object.defineProperty(exports,"VARIABLES_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.g}});Object.defineProperty(exports,"VECTOR_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.k}});Object.defineProperty(exports,"WEATHER_PACKAGE",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.s}});Object.defineProperty(exports,"createCryptoPackage",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.u}});Object.defineProperty(exports,"createCurrencyPackage",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.i}});Object.defineProperty(exports,"createKnowledgePackage",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.v}});Object.defineProperty(exports,"createStocksPackage",{enumerable:true,get:function(){return chunk4UHAGMER_cjs.t}});Object.defineProperty(exports,"SYMBOLIC_PACKAGE",{enumerable:true,get:function(){return chunkN37PUZJR_cjs.a}});//# sourceMappingURL=packages.cjs.map
2
2
  //# sourceMappingURL=packages.cjs.map
@@ -602,6 +602,52 @@ interface StocksPackageConfig {
602
602
  */
603
603
  declare function createStocksPackage(config?: StocksPackageConfig): IEnginePackage;
604
604
 
605
+ /** A current crypto price, as returned by a host-supplied `fetchPrice`. */
606
+ interface CryptoQuote {
607
+ /** Current price of one coin, in `currency` (default "USD"). */
608
+ price: number;
609
+ /** ISO 4217 currency code the price is quoted in. Defaults to "USD". */
610
+ currency?: string;
611
+ }
612
+ /**
613
+ * Configuration for {@link createCryptoPackage}. Like stocks, and for the same
614
+ * reason, there is no free/keyless crypto price API to bundle: the host supplies
615
+ * the fetch, backed by whichever provider and key they have.
616
+ */
617
+ interface CryptoPackageConfig {
618
+ /**
619
+ * Fetch the current price for `coin` (an upper-cased symbol like `BTC`).
620
+ * Required for `crypto(...)` to return real data; without it, a crypto
621
+ * expression resolves to an honest `CRYPTO_NOT_CONFIGURED` error, never a
622
+ * faked or zero price.
623
+ */
624
+ fetchPrice?: (coin: string, signal: AbortSignal) => Promise<CryptoQuote>;
625
+ /** Query staleTime for a price, in ms. Default 60s; crypto moves continuously. */
626
+ staleTimeMs?: number;
627
+ /** Cadence, in ms, for proactive background refresh of an on-screen price. Omit to keep it pull-only. */
628
+ refetchIntervalMs?: number;
629
+ }
630
+
631
+ /**
632
+ * Live crypto prices, `crypto("BTC")`, returning the current price of one coin
633
+ * as a currency value.
634
+ *
635
+ * Because the price comes back as ordinary money, the rest of the language does
636
+ * the conversion for free: `0.5 * crypto("BTC")` is the value of half a coin,
637
+ * and `crypto("ETH") in GBP` converts through the currency package. So the
638
+ * "0.5 BTC in USD" a reader wants is `0.5 * crypto("BTC")`, in whatever currency
639
+ * the provider quotes (US dollars by default).
640
+ *
641
+ * **A factory, not a constant, and not in `BUILTIN_PACKAGES`**, for the same
642
+ * reason as stocks: there is no free, keyless crypto price API to bundle, so the
643
+ * host supplies `fetchPrice` (backed by whichever provider and key they have)
644
+ * via {@link createCryptoPackage}. Without it, a crypto expression resolves to a
645
+ * clearly-worded `CRYPTO_NOT_CONFIGURED` error, never a faked price. A host that
646
+ * wants it calls `createCryptoPackage({ fetchPrice })` and adds the result to
647
+ * its engine's `packages` array.
648
+ */
649
+ declare function createCryptoPackage(config?: CryptoPackageConfig): IEnginePackage;
650
+
605
651
  /**
606
652
  * Configuration for {@link createKnowledgePackage}. See
607
653
  * `KnowledgePackage.ts`'s module doc for the "bring your own answer
@@ -826,4 +872,4 @@ interface IVector4 {
826
872
  w: number;
827
873
  }
828
874
 
829
- export { ARITHMETIC_PACKAGE, BIGINT_PACKAGE, BUILTIN_PACKAGES, CONDITIONALS_PACKAGE, CONVERTERS_PACKAGE, CURRENCY_PACKAGE, type CityWeather, type CurrencyPackageConfig, DATETIME_PACKAGE, DICE_PACKAGE, FINANCE_PACKAGE, FUNCTION_PACKAGE, type HistoricalRateProvider, type IVector2, type IVector3, type IVector4, type KnowledgePackageConfig, LINES_PACKAGE, MAPREDUCE_PACKAGE, MATHPHRASES_PACKAGE, MATRIX_PACKAGE, PERCENTAGE_PACKAGE, SYMBOLIC_PACKAGE, type StockHistoricalQuote, type StockQuote, type StocksPackageConfig, TABLES_PACKAGE, TAGS_PACKAGE, TIME_PACKAGE, UOM_PACKAGE, VARIABLES_PACKAGE, VECTOR_PACKAGE, WEATHER_PACKAGE, type WeatherQueryKind, createCurrencyPackage, createKnowledgePackage, createStocksPackage };
875
+ export { ARITHMETIC_PACKAGE, BIGINT_PACKAGE, BUILTIN_PACKAGES, CONDITIONALS_PACKAGE, CONVERTERS_PACKAGE, CURRENCY_PACKAGE, type CityWeather, type CurrencyPackageConfig, DATETIME_PACKAGE, DICE_PACKAGE, FINANCE_PACKAGE, FUNCTION_PACKAGE, type HistoricalRateProvider, type IVector2, type IVector3, type IVector4, type KnowledgePackageConfig, LINES_PACKAGE, MAPREDUCE_PACKAGE, MATHPHRASES_PACKAGE, MATRIX_PACKAGE, PERCENTAGE_PACKAGE, SYMBOLIC_PACKAGE, type StockHistoricalQuote, type StockQuote, type StocksPackageConfig, TABLES_PACKAGE, TAGS_PACKAGE, TIME_PACKAGE, UOM_PACKAGE, VARIABLES_PACKAGE, VECTOR_PACKAGE, WEATHER_PACKAGE, type WeatherQueryKind, createCryptoPackage, createCurrencyPackage, createKnowledgePackage, createStocksPackage };