solve-engine 2.28.0 → 2.30.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.
- package/dist/{EngineError-CA2tiVaI.d.cts → EngineError-CqGtaT_v.d.cts} +4 -0
- package/dist/{EngineError-CA2tiVaI.d.ts → EngineError-CqGtaT_v.d.ts} +4 -0
- package/dist/{Lexer-B62Hn9I-.d.ts → Lexer-CqFjYoRA.d.ts} +1 -1
- package/dist/{Lexer-DOXatsjO.d.cts → Lexer-sCI05tqO.d.cts} +1 -1
- package/dist/{PackageCompatibility-DW18LqED.d.cts → PackageCompatibility-Bn-T_xKW.d.cts} +1 -1
- package/dist/{PackageCompatibility-DT1IPlQx.d.ts → PackageCompatibility-phvSFP4f.d.ts} +1 -1
- package/dist/{PackageRegistry-CevYUzRn.d.cts → PackageRegistry-B-C1duZw.d.cts} +3 -3
- package/dist/{PackageRegistry-Dl9kNP14.d.ts → PackageRegistry-C78jVkI9.d.ts} +3 -3
- package/dist/{VMBuiltins-AIivGl0a.d.cts → VMBuiltins-BkKzhj6C.d.cts} +1 -1
- package/dist/{VMBuiltins-CbuFfIgQ.d.ts → VMBuiltins-Du9y8sEo.d.ts} +1 -1
- package/dist/{VMCheckpoints-BVrJwfZY.d.cts → VMCheckpoints-WdUQrdc9.d.cts} +1 -1
- package/dist/{VMCheckpoints-DFCl63K5.d.ts → VMCheckpoints-gvy_yxYh.d.ts} +1 -1
- package/dist/{WorkerError-DDtwl4oH.d.cts → WorkerError-CRoM8Ju1.d.cts} +1 -1
- package/dist/{WorkerError-BuO9MrRr.d.ts → WorkerError-DTrl3Jag.d.ts} +1 -1
- package/dist/{chunk-IEBWLNI5.js → chunk-2PGGPFF3.js} +2 -2
- package/dist/{chunk-IEBWLNI5.js.map → chunk-2PGGPFF3.js.map} +1 -1
- package/dist/{chunk-I6WGOM3C.js → chunk-3ZGFAE3Q.js} +2 -2
- package/dist/{chunk-I6WGOM3C.js.map → chunk-3ZGFAE3Q.js.map} +1 -1
- package/dist/{chunk-UMW5PO42.cjs → chunk-4DR5RBHQ.cjs} +2 -2
- package/dist/{chunk-UMW5PO42.cjs.map → chunk-4DR5RBHQ.cjs.map} +1 -1
- package/dist/{chunk-WXOJ3DS3.cjs → chunk-5AKT36UK.cjs} +2 -2
- package/dist/{chunk-WXOJ3DS3.cjs.map → chunk-5AKT36UK.cjs.map} +1 -1
- package/dist/{chunk-MKBB7IVN.cjs → chunk-7DJYS5PO.cjs} +2 -2
- package/dist/{chunk-MKBB7IVN.cjs.map → chunk-7DJYS5PO.cjs.map} +1 -1
- package/dist/{chunk-KYE5BWPN.cjs → chunk-A755LVPT.cjs} +2 -2
- package/dist/{chunk-KYE5BWPN.cjs.map → chunk-A755LVPT.cjs.map} +1 -1
- package/dist/{chunk-5J2XDCSV.cjs → chunk-A764BY7L.cjs} +2 -2
- package/dist/{chunk-5J2XDCSV.cjs.map → chunk-A764BY7L.cjs.map} +1 -1
- package/dist/{chunk-TTHCH7V2.cjs → chunk-AGCNMEP2.cjs} +2 -2
- package/dist/{chunk-TTHCH7V2.cjs.map → chunk-AGCNMEP2.cjs.map} +1 -1
- package/dist/{chunk-MONPHAHO.js → chunk-B2NL65FI.js} +2 -2
- package/dist/{chunk-MONPHAHO.js.map → chunk-B2NL65FI.js.map} +1 -1
- package/dist/{chunk-RRJ77SF6.js → chunk-CB3EXUM2.js} +2 -2
- package/dist/{chunk-RRJ77SF6.js.map → chunk-CB3EXUM2.js.map} +1 -1
- package/dist/{chunk-OKSAUK5C.js → chunk-CDE2ZUGG.js} +2 -2
- package/dist/{chunk-OKSAUK5C.js.map → chunk-CDE2ZUGG.js.map} +1 -1
- package/dist/{chunk-POIHAKBX.js → chunk-CIC2YO2M.js} +2 -2
- package/dist/{chunk-POIHAKBX.js.map → chunk-CIC2YO2M.js.map} +1 -1
- package/dist/{chunk-YLTNXYA7.cjs → chunk-CM2WM5CM.cjs} +2 -2
- package/dist/{chunk-YLTNXYA7.cjs.map → chunk-CM2WM5CM.cjs.map} +1 -1
- package/dist/{chunk-2YNRIT2L.cjs → chunk-DUFEONVN.cjs} +3 -3
- package/dist/{chunk-2YNRIT2L.cjs.map → chunk-DUFEONVN.cjs.map} +1 -1
- package/dist/{chunk-JHHSQ2YR.js → chunk-FNSQ6O4Y.js} +3 -3
- package/dist/{chunk-JHHSQ2YR.js.map → chunk-FNSQ6O4Y.js.map} +1 -1
- package/dist/{chunk-7ASISMXA.js → chunk-FXB5GCBT.js} +2 -2
- package/dist/{chunk-7ASISMXA.js.map → chunk-FXB5GCBT.js.map} +1 -1
- package/dist/{chunk-2RLNVS6G.js → chunk-G3POUURF.js} +2 -2
- package/dist/{chunk-2RLNVS6G.js.map → chunk-G3POUURF.js.map} +1 -1
- package/dist/{chunk-2G3AW6OQ.cjs → chunk-GWV273KZ.cjs} +2 -2
- package/dist/{chunk-2G3AW6OQ.cjs.map → chunk-GWV273KZ.cjs.map} +1 -1
- package/dist/{chunk-N22D5ZD4.js → chunk-IQVSCL2R.js} +3 -3
- package/dist/{chunk-N22D5ZD4.js.map → chunk-IQVSCL2R.js.map} +1 -1
- package/dist/{chunk-6T5HPIZX.js → chunk-KH4QXKLT.js} +2 -2
- package/dist/{chunk-6T5HPIZX.js.map → chunk-KH4QXKLT.js.map} +1 -1
- package/dist/{chunk-OLATJABN.js → chunk-LP3JYC3A.js} +2 -2
- package/dist/{chunk-OLATJABN.js.map → chunk-LP3JYC3A.js.map} +1 -1
- package/dist/{chunk-FSNBYRNA.cjs → chunk-NNRTDLGC.cjs} +3 -3
- package/dist/{chunk-FSNBYRNA.cjs.map → chunk-NNRTDLGC.cjs.map} +1 -1
- package/dist/{chunk-APU5LON7.js → chunk-NOZKHMML.js} +3 -3
- package/dist/{chunk-APU5LON7.js.map → chunk-NOZKHMML.js.map} +1 -1
- package/dist/{chunk-A7RRWNLE.js → chunk-NQFCXLEF.js} +2 -2
- package/dist/{chunk-A7RRWNLE.js.map → chunk-NQFCXLEF.js.map} +1 -1
- package/dist/{chunk-O5ZLOZPH.cjs → chunk-OM7NOHJF.cjs} +2 -2
- package/dist/{chunk-O5ZLOZPH.cjs.map → chunk-OM7NOHJF.cjs.map} +1 -1
- package/dist/{chunk-QXGKONTZ.cjs → chunk-P43SV4NJ.cjs} +3 -3
- package/dist/{chunk-QXGKONTZ.cjs.map → chunk-P43SV4NJ.cjs.map} +1 -1
- package/dist/{chunk-IIBR4LVH.cjs → chunk-PNHTC3FM.cjs} +4 -4
- package/dist/{chunk-IIBR4LVH.cjs.map → chunk-PNHTC3FM.cjs.map} +1 -1
- package/dist/{chunk-DDVDRWCK.js → chunk-PTXUWGRR.js} +3 -3
- package/dist/{chunk-DDVDRWCK.js.map → chunk-PTXUWGRR.js.map} +1 -1
- package/dist/{chunk-GWEINEJG.cjs → chunk-Q7TBBV62.cjs} +2 -2
- package/dist/{chunk-GWEINEJG.cjs.map → chunk-Q7TBBV62.cjs.map} +1 -1
- package/dist/chunk-RAFOQ4T5.cjs +2 -0
- package/dist/{chunk-5NQE5JMU.cjs.map → chunk-RAFOQ4T5.cjs.map} +1 -1
- package/dist/{chunk-Z5DA5UXY.js → chunk-RELMEWY6.js} +2 -2
- package/dist/chunk-RELMEWY6.js.map +1 -0
- package/dist/{chunk-RVNW627Y.cjs → chunk-RHRAONDK.cjs} +2 -2
- package/dist/{chunk-RVNW627Y.cjs.map → chunk-RHRAONDK.cjs.map} +1 -1
- package/dist/{chunk-Z5VBXZ4A.js → chunk-SFM4XFGJ.js} +2 -2
- package/dist/{chunk-Z5VBXZ4A.js.map → chunk-SFM4XFGJ.js.map} +1 -1
- package/dist/{chunk-HTAT4MGN.cjs → chunk-SUAGBRQ7.cjs} +2 -2
- package/dist/chunk-SUAGBRQ7.cjs.map +1 -0
- package/dist/chunk-V7LXOTCU.js +3 -0
- package/dist/chunk-V7LXOTCU.js.map +1 -0
- package/dist/{chunk-7ZYYWSLT.js → chunk-VLX7ZVK4.js} +2 -2
- package/dist/{chunk-7ZYYWSLT.js.map → chunk-VLX7ZVK4.js.map} +1 -1
- package/dist/chunk-W7NN77PH.cjs +3 -0
- package/dist/chunk-W7NN77PH.cjs.map +1 -0
- package/dist/{chunk-W5BBKLNS.cjs → chunk-WQGHJAW2.cjs} +2 -2
- package/dist/{chunk-W5BBKLNS.cjs.map → chunk-WQGHJAW2.cjs.map} +1 -1
- package/dist/{chunk-U7CNADCJ.cjs → chunk-WU7SBKVU.cjs} +2 -2
- package/dist/{chunk-U7CNADCJ.cjs.map → chunk-WU7SBKVU.cjs.map} +1 -1
- package/dist/{chunk-LV7PJ2MU.js → chunk-X5K72MBV.js} +2 -2
- package/dist/{chunk-LV7PJ2MU.js.map → chunk-X5K72MBV.js.map} +1 -1
- package/dist/{chunk-IAL64FCP.js → chunk-YN5H54GM.js} +2 -2
- package/dist/{chunk-IAL64FCP.js.map → chunk-YN5H54GM.js.map} +1 -1
- package/dist/{chunk-UBKWHRFL.cjs → chunk-YWF6C2IO.cjs} +2 -2
- package/dist/{chunk-UBKWHRFL.cjs.map → chunk-YWF6C2IO.cjs.map} +1 -1
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +6 -6
- package/dist/engine.d.ts +6 -6
- package/dist/engine.js +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/language.d.cts +5 -5
- package/dist/language.d.ts +5 -5
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.d.cts +3 -3
- package/dist/lexer.d.ts +3 -3
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +4 -4
- package/dist/packages.d.ts +4 -4
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.js +1 -1
- package/dist/temporal.cjs +1 -1
- package/dist/temporal.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +5 -5
- package/dist/testing.d.ts +5 -5
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +3 -3
- package/dist/vm.d.ts +3 -3
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.d.cts +5 -5
- package/dist/worker.d.ts +5 -5
- package/dist/worker.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3LWK33TJ.js +0 -3
- package/dist/chunk-3LWK33TJ.js.map +0 -1
- package/dist/chunk-5NQE5JMU.cjs +0 -2
- package/dist/chunk-HTAT4MGN.cjs.map +0 -1
- package/dist/chunk-YIXCPLCN.cjs +0 -3
- package/dist/chunk-YIXCPLCN.cjs.map +0 -1
- package/dist/chunk-Z5DA5UXY.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":["BindingPower","BUILTIN_INFIX_BP","TokenTypes","_bpTable","buildBindingPowerTable","maxId","name","id","tokenTypeId","table","bp","invalidateBindingPowerTable","MAX_CONSTANT_POOL_INDEX","NEGATIVE_ZERO_KEY","checkedOperand","value","what","ErrorFactory","EMPTY_STRINGS","EMPTY_NUMBERS","BytecodeBuilder","pluginFunctionIndex","argCount","index","op","n","key","idx","s","b","params","program","position","target","buf","opLen","numLen","reuseOpcodes","reuseNumbers","opcodes","numbers","i","CHAINED_DOT_THOUSANDS_GROUPS","DIGITS_ONLY","bigIntLiteralDigits","raw","localeCode","withoutSuffix","digits","stripLocaleGrouping","separator","text","thousandsSeparator","getLocale"],"mappings":"uKAWO,IAAMA,CAAAA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\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when declaring an infix parselet in a\n * package's `infixParselets`. See the built-in packages for examples of\n * picking an appropriate level (e.g. arithmetic `+`/`-` use `Sum`, `*`/`/`\n * use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nexport const BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/** The `numberIndex` key for negative zero, which `Map` would otherwise fold into positive zero. */\nconst NEGATIVE_ZERO_KEY = \"-0\";\n\n/**\n * An operand that fits the byte the opcode stream stores it in, or a\n * structured refusal. `build()` copies the stream into a `Uint8Array`, which\n * keeps the low eight bits of whatever it is given: an operand of 300 used to\n * become 44 with no error, and the program then read a different constant,\n * plugin function or argument count from the one the parselet emitted. Every\n * raw operand goes through here, so a package author's mistake is reported at\n * compile time as a fault in the package rather than answered with a wrong\n * number.\n */\nfunction checkedOperand(value: number, what: string): number {\n\tif (!Number.isInteger(value) || value < 0 || value > 255) {\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t`A bytecode ${what} must be an integer from 0 to 255, but ${value} was emitted; the opcode stream stores one byte per operand.`,\n\t\t\t{ value, what }\n\t\t);\n\t}\n\treturn value;\n}\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\t/**\n\t * Numeric constants by opcode position, restored from a snapshot.\n\t *\n\t * Nothing in the compile path writes this: numbers are emitted inline into\n\t * {@link numbers} instead. `build()` used to attach an empty Map to every\n\t * program anyway, which was one allocation per compiled expression, around a\n\t * tenth of parse-and-compile time, for a collection that was never read.\n\t * It is left off now, and only {@link EngineSnapshot} sets it when restoring\n\t * a program that carried one; every reader already guards on its absence.\n\t */\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Shared empty collections for programs that emit none.\n *\n * `build()` runs once per compiled expression, so an empty array allocated\n * there is an allocation per line of every document. Most programs emit no\n * strings at all (only the unit and datetime parselets do), and one that emits\n * no numbers is common too, so both were routinely allocating an empty\n * container that nothing would ever read.\n *\n * Sharing them is safe because a built program is read-only downstream: the VM\n * and the snapshot writer only index and iterate these, and nothing in the\n * engine pushes to `program.strings` or `program.numbers`. They are frozen so\n * that a future writer fails loudly here rather than silently corrupting every\n * other program that shares the instance.\n */\nconst EMPTY_STRINGS: readonly string[] = Object.freeze([]);\nconst EMPTY_NUMBERS = new Float64Array(0);\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\t/** Value (or {@link NEGATIVE_ZERO_KEY}) to its slot in `numbers`, so a repeated literal is emitted once. */\n\tprivate numberIndex = new Map<number | string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/**\n\t * The per-engine `plugin function name -> registry index` map, wired in by\n\t * the engine so {@link emitPluginCall} can resolve a name at emit time. The\n\t * same object reference is shared with every builder in an engine (the pool\n\t * and each ad-hoc nested-body builder), and the engine populates it as\n\t * packages register, so a parselet never sees the numeric index.\n\t */\n\tconstructor(private readonly pluginFunctionIndex?: ReadonlyMap<string, number>) {}\n\n\t/** The name->index map, so a nested-body builder inherits the same resolution. */\n\tget pluginIndexMap(): ReadonlyMap<string, number> | undefined {\n\t\treturn this.pluginFunctionIndex;\n\t}\n\n\t/**\n\t * Emit a plugin-function call by NAME. The engine assigns each registered\n\t * `pluginFunctions` entry an index at registration; this resolves the name to\n\t * that index and emits `CALL_PLUGIN` + index + argCount. Package authors emit\n\t * through this rather than a hand-allocated index.\n\t */\n\temitPluginCall(name: string, argCount: number): void {\n\t\tconst index = this.pluginFunctionIndex?.get(name);\n\t\tif (index === undefined) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"UNKNOWN_PLUGIN_FUNCTION\",\n\t\t\t\t`No registered plugin function named \"${name}\". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,\n\t\t\t\t{ functionName: name },\n\t\t\t);\n\t\t}\n\t\t// One byte covers the first 256 plugin functions; beyond that, the\n\t\t// wide opcode carries a two-byte little-endian index. Emitting the\n\t\t// narrow form whenever it fits keeps existing bytecode and snapshots\n\t\t// byte-for-byte unchanged. The index cannot exceed 65535 because the\n\t\t// allocator (allocatePluginFunctionIndex) caps it, but guard anyway so\n\t\t// a stray index is a clear error rather than a silently truncated byte.\n\t\tif (index > 0xffff) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\t\t\t\t`Plugin-function index ${index} exceeds the two-byte bytecode limit (65535).`,\n\t\t\t\t{ index },\n\t\t\t);\n\t\t}\n\t\tif (index <= 0xff) {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN);\n\t\t\tthis.emitIndex(index);\n\t\t} else {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN_WIDE);\n\t\t\tthis.emitIndex(index & 0xff); // low byte\n\t\t\tthis.emitIndex((index >> 8) & 0xff); // high byte\n\t\t}\n\t\tthis.emitIndex(argCount);\n\t}\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN || op === OpCode.CALL_PLUGIN_WIDE) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: interns `n` into the program's constant pool\n\t * (deduplicated, like {@link emitString}) and writes its index into the\n\t * opcode stream (read back by the VM as e.g. `PUSH_NUMBER <idx>`).\n\t *\n\t * Deduplicated so that the 256-entry pool counts distinct values rather\n\t * than occurrences: a long line of repeated literals used to exhaust it\n\t * long before it held 256 different numbers. Negative zero keeps its own\n\t * slot, because `1 / -0` is not `1 / 0`; NaN shares one, since every NaN\n\t * reads the same.\n\t *\n\t * @throws If the pool would exceed 256 distinct entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst key = Object.is(n, -0) ? NEGATIVE_ZERO_KEY : n;\n\t\tlet idx = this.numberIndex.get(key);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.numbers.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.numbers.push(n);\n\t\t\tthis.numberIndex.set(key, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(checkedOperand(idx, \"index\"));\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(checkedOperand(b, \"byte\"));\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tif (position < 0 || position >= this.opcodes.length) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t\t`patchJump was asked to write at position ${position}, outside the ${this.opcodes.length} bytes emitted so far.`,\n\t\t\t\t{ position, length: this.opcodes.length }\n\t\t\t);\n\t\t}\n\t\tthis.opcodes[position] = checkedOperand(target, \"jump target\");\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: this.numbers.length > 0 ? new Float64Array(this.numbers) : EMPTY_NUMBERS,\n\t\t\t// Defensive copy when there is anything to copy: reset()'s\n\t\t\t// `.length = 0` would otherwise clear a reference the program still\n\t\t\t// holds. An empty one needs no copy, so it shares the frozen\n\t\t\t// singleton instead of allocating per program.\n\t\t\tstrings: this.strings.length > 0 ? [...this.strings] : (EMPTY_STRINGS as string[]),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tif (this.numbers.length > 0) {\n\t\t\tthis.numbers.length = 0;\n\t\t\tthis.numberIndex.clear();\n\t\t}\n\t\t// Guarded on being non-empty. reset() runs once per compiled expression\n\t\t// and a CPU profile put it at over a tenth of parse-and-compile, which\n\t\t// is a lot for clearing collections that are usually already empty:\n\t\t// most expressions emit no strings, and user function bodies are rarer\n\t\t// still. Emptying an empty Map is not free, and neither is the write\n\t\t// barrier on a length assignment.\n\t\tif (this.strings.length > 0) {\n\t\t\tthis.strings.length = 0;\n\t\t\tthis.stringIndex.clear();\n\t\t}\n\t\tthis._hasAsync = false;\n\t\tif (this.userFunctionBodies.length > 0) this.userFunctionBodies.length = 0;\n\t\tif (this.anonymousBodies.length > 0) this.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":["BindingPower","BUILTIN_INFIX_BP","TokenTypes","_bpTable","buildBindingPowerTable","maxId","name","id","tokenTypeId","table","bp","invalidateBindingPowerTable","MAX_CONSTANT_POOL_INDEX","NEGATIVE_ZERO_KEY","checkedOperand","value","what","ErrorFactory","EMPTY_STRINGS","EMPTY_NUMBERS","BytecodeBuilder","pluginFunctionIndex","argCount","index","op","n","key","idx","s","b","params","program","position","target","buf","opLen","numLen","reuseOpcodes","reuseNumbers","opcodes","numbers","i","CHAINED_DOT_THOUSANDS_GROUPS","DIGITS_ONLY","bigIntLiteralDigits","raw","localeCode","withoutSuffix","digits","stripLocaleGrouping","separator","text","thousandsSeparator","getLocale"],"mappings":"uKAWO,IAAMA,CAAAA,CAAe,CAC1B,MAAA,CAAQ,CAAA,CACR,UAAA,CAAY,EAAA,CACZ,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CAaZ,WAAA,CAAa,EAAA,CAab,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CACZ,UAAA,CAAY,EAAA,CACZ,WAAA,CAAa,EAAA,CACb,KAAA,CAAO,EAAA,CACP,GAAA,CAAK,EAAA,CACL,OAAA,CAAS,EAAA,CAMT,WAAA,CAAa,EAAA,CAIb,QAAA,CAAU,GACV,MAAA,CAAQ,EAAA,CACR,OAAA,CAAS,EAAA,CACT,IAAA,CAAM,EACR,EAiDO,IAAMC,CAAAA,CAA2C,CAEtD,CAACC,mBAAAA,CAAW,IAAI,EAAOF,CAAAA,CAAa,GAAA,CACpC,CAACE,mBAAAA,CAAW,KAAK,EAAMF,CAAAA,CAAa,GAAA,CACpC,CAACE,mBAAAA,CAAW,IAAI,EAAOF,CAAAA,CAAa,OAAA,CACpC,CAACE,mBAAAA,CAAW,KAAK,EAAMF,CAAAA,CAAa,OAAA,CACpC,CAACE,mBAAAA,CAAW,GAAG,EAAQF,CAAAA,C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B,wBAAA,CACA,CAAA,CAAA,EAAI4B,CAAG,CAAA,0BAAA,EAA6BK,CAAS,CAAA,4BAAA,EAA+BJ,CAAU,CAAA,0DAAA,CAAA,CACtF,CAAE,GAAA,CAAAD,CAAAA,CAAK,UAAA,CAAAC,CAAAA,CAAY,SAAA,CAAAI,CAAU,CAC9B,CACD,CACA,OAAOF,CACR,CASA,SAASC,CAAAA,CAAoBE,CAAAA,CAAcL,CAAAA,CAA4B,CACtE,IAAMM,CAAAA,CAAqBC,mBAAAA,CAAUP,CAAU,CAAA,CAAE,OAAA,CAAQ,kBAAA,CACzD,OAAOM,CAAAA,CAAqBD,CAAAA,CAAK,KAAA,CAAMC,CAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAAID,CACvE","file":"chunk-5AKT36UK.cjs","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when declaring an infix parselet in a\n * package's `infixParselets`. See the built-in packages for examples of\n * picking an appropriate level (e.g. arithmetic `+`/`-` use `Sum`, `*`/`/`\n * use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nexport const BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/** The `numberIndex` key for negative zero, which `Map` would otherwise fold into positive zero. */\nconst NEGATIVE_ZERO_KEY = \"-0\";\n\n/**\n * An operand that fits the byte the opcode stream stores it in, or a\n * structured refusal. `build()` copies the stream into a `Uint8Array`, which\n * keeps the low eight bits of whatever it is given: an operand of 300 used to\n * become 44 with no error, and the program then read a different constant,\n * plugin function or argument count from the one the parselet emitted. Every\n * raw operand goes through here, so a package author's mistake is reported at\n * compile time as a fault in the package rather than answered with a wrong\n * number.\n */\nfunction checkedOperand(value: number, what: string): number {\n\tif (!Number.isInteger(value) || value < 0 || value > 255) {\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t`A bytecode ${what} must be an integer from 0 to 255, but ${value} was emitted; the opcode stream stores one byte per operand.`,\n\t\t\t{ value, what }\n\t\t);\n\t}\n\treturn value;\n}\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\t/**\n\t * Numeric constants by opcode position, restored from a snapshot.\n\t *\n\t * Nothing in the compile path writes this: numbers are emitted inline into\n\t * {@link numbers} instead. `build()` used to attach an empty Map to every\n\t * program anyway, which was one allocation per compiled expression, around a\n\t * tenth of parse-and-compile time, for a collection that was never read.\n\t * It is left off now, and only {@link EngineSnapshot} sets it when restoring\n\t * a program that carried one; every reader already guards on its absence.\n\t */\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Shared empty collections for programs that emit none.\n *\n * `build()` runs once per compiled expression, so an empty array allocated\n * there is an allocation per line of every document. Most programs emit no\n * strings at all (only the unit and datetime parselets do), and one that emits\n * no numbers is common too, so both were routinely allocating an empty\n * container that nothing would ever read.\n *\n * Sharing them is safe because a built program is read-only downstream: the VM\n * and the snapshot writer only index and iterate these, and nothing in the\n * engine pushes to `program.strings` or `program.numbers`. They are frozen so\n * that a future writer fails loudly here rather than silently corrupting every\n * other program that shares the instance.\n */\nconst EMPTY_STRINGS: readonly string[] = Object.freeze([]);\nconst EMPTY_NUMBERS = new Float64Array(0);\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\t/** Value (or {@link NEGATIVE_ZERO_KEY}) to its slot in `numbers`, so a repeated literal is emitted once. */\n\tprivate numberIndex = new Map<number | string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/**\n\t * The per-engine `plugin function name -> registry index` map, wired in by\n\t * the engine so {@link emitPluginCall} can resolve a name at emit time. The\n\t * same object reference is shared with every builder in an engine (the pool\n\t * and each ad-hoc nested-body builder), and the engine populates it as\n\t * packages register, so a parselet never sees the numeric index.\n\t */\n\tconstructor(private readonly pluginFunctionIndex?: ReadonlyMap<string, number>) {}\n\n\t/** The name->index map, so a nested-body builder inherits the same resolution. */\n\tget pluginIndexMap(): ReadonlyMap<string, number> | undefined {\n\t\treturn this.pluginFunctionIndex;\n\t}\n\n\t/**\n\t * Emit a plugin-function call by NAME. The engine assigns each registered\n\t * `pluginFunctions` entry an index at registration; this resolves the name to\n\t * that index and emits `CALL_PLUGIN` + index + argCount. Package authors emit\n\t * through this rather than a hand-allocated index.\n\t */\n\temitPluginCall(name: string, argCount: number): void {\n\t\tconst index = this.pluginFunctionIndex?.get(name);\n\t\tif (index === undefined) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"UNKNOWN_PLUGIN_FUNCTION\",\n\t\t\t\t`No registered plugin function named \"${name}\". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,\n\t\t\t\t{ functionName: name },\n\t\t\t);\n\t\t}\n\t\t// One byte covers the first 256 plugin functions; beyond that, the\n\t\t// wide opcode carries a two-byte little-endian index. Emitting the\n\t\t// narrow form whenever it fits keeps existing bytecode and snapshots\n\t\t// byte-for-byte unchanged. The index cannot exceed 65535 because the\n\t\t// allocator (allocatePluginFunctionIndex) caps it, but guard anyway so\n\t\t// a stray index is a clear error rather than a silently truncated byte.\n\t\tif (index > 0xffff) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\t\t\t\t`Plugin-function index ${index} exceeds the two-byte bytecode limit (65535).`,\n\t\t\t\t{ index },\n\t\t\t);\n\t\t}\n\t\tif (index <= 0xff) {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN);\n\t\t\tthis.emitIndex(index);\n\t\t} else {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN_WIDE);\n\t\t\tthis.emitIndex(index & 0xff); // low byte\n\t\t\tthis.emitIndex((index >> 8) & 0xff); // high byte\n\t\t}\n\t\tthis.emitIndex(argCount);\n\t}\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN || op === OpCode.CALL_PLUGIN_WIDE) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: interns `n` into the program's constant pool\n\t * (deduplicated, like {@link emitString}) and writes its index into the\n\t * opcode stream (read back by the VM as e.g. `PUSH_NUMBER <idx>`).\n\t *\n\t * Deduplicated so that the 256-entry pool counts distinct values rather\n\t * than occurrences: a long line of repeated literals used to exhaust it\n\t * long before it held 256 different numbers. Negative zero keeps its own\n\t * slot, because `1 / -0` is not `1 / 0`; NaN shares one, since every NaN\n\t * reads the same.\n\t *\n\t * @throws If the pool would exceed 256 distinct entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst key = Object.is(n, -0) ? NEGATIVE_ZERO_KEY : n;\n\t\tlet idx = this.numberIndex.get(key);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.numbers.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.numbers.push(n);\n\t\t\tthis.numberIndex.set(key, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(checkedOperand(idx, \"index\"));\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(checkedOperand(b, \"byte\"));\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tif (position < 0 || position >= this.opcodes.length) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t\t`patchJump was asked to write at position ${position}, outside the ${this.opcodes.length} bytes emitted so far.`,\n\t\t\t\t{ position, length: this.opcodes.length }\n\t\t\t);\n\t\t}\n\t\tthis.opcodes[position] = checkedOperand(target, \"jump target\");\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: this.numbers.length > 0 ? new Float64Array(this.numbers) : EMPTY_NUMBERS,\n\t\t\t// Defensive copy when there is anything to copy: reset()'s\n\t\t\t// `.length = 0` would otherwise clear a reference the program still\n\t\t\t// holds. An empty one needs no copy, so it shares the frozen\n\t\t\t// singleton instead of allocating per program.\n\t\t\tstrings: this.strings.length > 0 ? [...this.strings] : (EMPTY_STRINGS as string[]),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tif (this.numbers.length > 0) {\n\t\t\tthis.numbers.length = 0;\n\t\t\tthis.numberIndex.clear();\n\t\t}\n\t\t// Guarded on being non-empty. reset() runs once per compiled expression\n\t\t// and a CPU profile put it at over a tenth of parse-and-compile, which\n\t\t// is a lot for clearing collections that are usually already empty:\n\t\t// most expressions emit no strings, and user function bodies are rarer\n\t\t// still. Emptying an empty Map is not free, and neither is the write\n\t\t// barrier on a length assignment.\n\t\tif (this.strings.length > 0) {\n\t\t\tthis.strings.length = 0;\n\t\t\tthis.stringIndex.clear();\n\t\t}\n\t\tthis._hasAsync = false;\n\t\tif (this.userFunctionBodies.length > 0) this.userFunctionBodies.length = 0;\n\t\tif (this.anonymousBodies.length > 0) this.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
'use strict';var chunkSUAGBRQ7_cjs=require('./chunk-SUAGBRQ7.cjs');var o={WORKER_CANCELLED:"WORKER_CANCELLED",WORKER_TERMINATED:"WORKER_TERMINATED",WORKER_TRANSPORT_FAILED:"WORKER_TRANSPORT_FAILED",WORKER_UNKNOWN_METHOD:"WORKER_UNKNOWN_METHOD",WORKER_NOT_INITIALISED:"WORKER_NOT_INITIALISED",WORKER_UNKNOWN_PACKAGE:"WORKER_UNKNOWN_PACKAGE"};function t(r){let e={name:r.name,category:r.category,code:r.code,message:r.message,recoverable:r.recoverable};return r.expected!==void 0&&(e.expected=r.expected),r.found!==void 0&&(e.found=r.found),r.suggestion!==void 0&&(e.suggestion=r.suggestion),r.span!==void 0&&(e.span=r.span),e}function a(r){let e=Object.values(chunkSUAGBRQ7_cjs.a).includes(r.category)?r.category:"INTERNAL";return new chunkSUAGBRQ7_cjs.b(e,{code:r.code,message:r.message,expected:r.expected,found:r.found,suggestion:r.suggestion,recoverable:r.recoverable,span:r.span})}function s(r){return chunkSUAGBRQ7_cjs.c.execution(o.WORKER_CANCELLED,r?`The worker request "${r}" was cancelled`:"The worker request was cancelled",r?{method:r}:void 0)}function c(){return chunkSUAGBRQ7_cjs.c.execution(o.WORKER_TERMINATED,"The worker engine was terminated before this request completed")}function g(r){return chunkSUAGBRQ7_cjs.c.external(o.WORKER_TRANSPORT_FAILED,`The worker transport failed: ${r}`,{detail:r})}exports.a=o;exports.b=t;exports.c=a;exports.d=s;exports.e=c;exports.f=g;//# sourceMappingURL=chunk-7DJYS5PO.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-7DJYS5PO.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors/WorkerError.ts"],"names":["WorkerErrorCodes","serializeEngineError","error","dto","deserializeEngineError","category","ErrorCategory","EngineError","workerCancelledError","method","ErrorFactory","workerTerminatedError","workerTransportError","detail"],"mappings":"mEAoBO,IAAMA,EAAmB,CAE/B,gBAAA,CAAkB,kBAAA,CAElB,iBAAA,CAAmB,oBAEnB,uBAAA,CAAyB,yBAAA,CAEzB,qBAAA,CAAuB,uBAAA,CAEvB,uBAAwB,wBAAA,CAExB,sBAAA,CAAwB,wBACzB,EAyBO,SAASC,CAAAA,CAAqBC,CAAAA,CAA2C,CAC/E,IAAMC,EAA6B,CAClC,IAAA,CAAMD,CAAAA,CAAM,IAAA,CACZ,SAAUA,CAAAA,CAAM,QAAA,CAChB,IAAA,CAAMA,CAAAA,CAAM,KACZ,OAAA,CAASA,CAAAA,CAAM,QACf,WAAA,CAAaA,CAAAA,CAAM,WACpB,CAAA,CAIA,OAAIA,CAAAA,CAAM,QAAA,GAAa,SAAWC,CAAAA,CAAI,QAAA,CAAWD,CAAAA,CAAM,QAAA,CAAA,CACnDA,EAAM,KAAA,GAAU,MAAA,GAAWC,CAAAA,CAAI,KAAA,CAAQD,EAAM,KAAA,CAAA,CAC7CA,CAAAA,CAAM,aAAe,MAAA,GAAWC,CAAAA,CAAI,WAAaD,CAAAA,CAAM,UAAA,CAAA,CAGvDA,CAAAA,CAAM,IAAA,GAAS,SAAWC,CAAAA,CAAI,IAAA,CAAOD,CAAAA,CAAM,IAAA,CAAA,CACxCC,CACR,CAWO,SAASC,CAAAA,CAAuBD,CAAAA,CAAyC,CAC/E,IAAME,CAAAA,CAAW,OAAO,MAAA,CAAOC,mBAAa,EAAE,QAAA,CAASH,CAAAA,CAAI,QAAQ,CAAA,CAChEA,EAAI,QAAA,CAAA,UAAA,CAEP,OAAO,IAAII,mBAAAA,CAAYF,EAAU,CAChC,IAAA,CAAMF,CAAAA,CAAI,IAAA,CACV,QAASA,CAAAA,CAAI,OAAA,CACb,SAAUA,CAAAA,CAAI,QAAA,CACd,MAAOA,CAAAA,CAAI,KAAA,CACX,UAAA,CAAYA,CAAAA,CAAI,WAChB,WAAA,CAAaA,CAAAA,CAAI,WAAA,CACjB,IAAA,CAAMA,EAAI,IACX,CAAC,CACF,CAGO,SAASK,CAAAA,CAAqBC,CAAAA,CAA8B,CAClE,OAAOC,mBAAAA,CAAa,UACnBV,CAAAA,CAAiB,gBAAA,CACjBS,CAAAA,CACG,CAAA,oBAAA,EAAuBA,CAAM,CAAA,eAAA,CAAA,CAC7B,kCAAA,CACHA,CAAAA,CAAS,CAAE,OAAAA,CAAO,CAAA,CAAI,MACvB,CACD,CAGO,SAASE,CAAAA,EAAqC,CACpD,OAAOD,mBAAAA,CAAa,UACnBV,CAAAA,CAAiB,iBAAA,CACjB,gEACD,CACD,CAGO,SAASY,CAAAA,CAAqBC,CAAAA,CAA6B,CACjE,OAAOH,mBAAAA,CAAa,QAAA,CACnBV,CAAAA,CAAiB,uBAAA,CACjB,gCAAgCa,CAAM,CAAA,CAAA,CACtC,CAAE,MAAA,CAAAA,CAAO,CACV,CACD","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/errors/WorkerError.ts"],"names":["WorkerErrorCodes","serializeEngineError","error","dto","deserializeEngineError","category","ErrorCategory","EngineError","workerCancelledError","method","ErrorFactory","workerTerminatedError","workerTrans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AA,CAAMA,EAAI,IACX,CAAC,CACF,CAGO,SAASK,CAAAA,CAAqBC,CAAAA,CAA8B,CAClE,OAAOC,mBAAAA,CAAa,UACnBV,CAAAA,CAAiB,gBAAA,CACjBS,CAAAA,CACG,CAAA,oBAAA,EAAuBA,CAAM,CAAA,eAAA,CAAA,CAC7B,kCAAA,CACHA,CAAAA,CAAS,CAAE,OAAAA,CAAO,CAAA,CAAI,MACvB,CACD,CAGO,SAASE,CAAAA,EAAqC,CACpD,OAAOD,mBAAAA,CAAa,UACnBV,CAAAA,CAAiB,iBAAA,CACjB,gEACD,CACD,CAGO,SAASY,CAAAA,CAAqBC,CAAAA,CAA6B,CACjE,OAAOH,mBAAAA,CAAa,QAAA,CACnBV,CAAAA,CAAiB,uBAAA,CACjB,gCAAgCa,CAAM,CAAA,CAAA,CACtC,CAAE,MAAA,CAAAA,CAAO,CACV,CACD","file":"chunk-7DJYS5PO.cjs","sourcesContent":["/**\n * Structured errors for the off-main-thread worker harness, and the pair of\n * functions that carry an {@link EngineError} across a `postMessage` boundary.\n *\n * A worker runs in another thread, so a failure there cannot be `throw`n back\n * into the caller's stack. It has to be encoded, posted, and rebuilt on the\n * main side, and it must arrive as a real structured error rather than a lost\n * promise or an opaque string. {@link serializeEngineError} projects an\n * `EngineError` onto a plain, clone-safe object; {@link deserializeEngineError}\n * rebuilds one from that object so the main-side `catch` sees the same\n * `code`/`category`/`message` it would have seen in-process.\n */\n\nimport { EngineError, ErrorCategory, ErrorFactory, type SourceSpan } from \"./EngineError\";\n\n/**\n * Codes the worker harness owns, co-located here rather than unioned into the\n * core catalog, matching the convention `errors/ErrorCode.ts` documents for a\n * domain that keeps its own small code object.\n */\nexport const WorkerErrorCodes = {\n\t/** The caller aborted the request through its `AbortSignal`. */\n\tWORKER_CANCELLED: \"WORKER_CANCELLED\",\n\t/** The worker engine was torn down while a request was still in flight. */\n\tWORKER_TERMINATED: \"WORKER_TERMINATED\",\n\t/** The transport failed or the worker exited before answering. */\n\tWORKER_TRANSPORT_FAILED: \"WORKER_TRANSPORT_FAILED\",\n\t/** A request named a method the runtime does not expose. */\n\tWORKER_UNKNOWN_METHOD: \"WORKER_UNKNOWN_METHOD\",\n\t/** A request arrived before the runtime finished building its engine. */\n\tWORKER_NOT_INITIALISED: \"WORKER_NOT_INITIALISED\",\n\t/** An init named a package the runtime could not resolve. */\n\tWORKER_UNKNOWN_PACKAGE: \"WORKER_UNKNOWN_PACKAGE\",\n} as const;\n\n/**\n * A structured error flattened for transport.\n *\n * Every field is a string, a boolean, or an object of numbers, so the whole\n * thing survives both `structuredClone` (what `postMessage` uses) and\n * `JSON.stringify` (what a host may log). `context`, `cause` and `timestamp`\n * are deliberately dropped rather than posted: a context can hold a value that\n * is not clone-safe, and none of the three is part of what a main-side handler\n * branches on.\n */\nexport interface SerializedEngineError {\n\tname: string;\n\tcategory: ErrorCategory;\n\tcode: string;\n\tmessage: string;\n\texpected?: string;\n\tfound?: string;\n\tsuggestion?: string;\n\trecoverable: boolean;\n\tspan?: SourceSpan;\n}\n\n/** Flatten an {@link EngineError} into a clone-safe {@link SerializedEngineError}. */\nexport function serializeEngineError(error: EngineError): SerializedEngineError {\n\tconst dto: SerializedEngineError = {\n\t\tname: error.name,\n\t\tcategory: error.category,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\trecoverable: error.recoverable,\n\t};\n\t// Only the optional string fields that were actually set cross the wire, so\n\t// a rebuilt error has `undefined` exactly where the original did rather than\n\t// an explicit `undefined` property a deep-equal would trip on.\n\tif (error.expected !== undefined) dto.expected = error.expected;\n\tif (error.found !== undefined) dto.found = error.found;\n\tif (error.suggestion !== undefined) dto.suggestion = error.suggestion;\n\t// A span is character offsets (plain numbers), so it is safe to carry and\n\t// useful for a host that highlights the failing range.\n\tif (error.span !== undefined) dto.span = error.span;\n\treturn dto;\n}\n\n/**\n * Rebuild an {@link EngineError} from its transported form.\n *\n * The category string round-trips straight back into the `ErrorCategory` enum\n * (its members ARE their own string values), so a main-side `catch` reads the\n * same category the worker raised. A malformed category (a message that was not\n * produced by {@link serializeEngineError}) falls back to `INTERNAL` rather than\n * constructing an error with an invalid category.\n */\nexport function deserializeEngineError(dto: SerializedEngineError): EngineError {\n\tconst category = Object.values(ErrorCategory).includes(dto.category)\n\t\t? dto.category\n\t\t: ErrorCategory.INTERNAL;\n\treturn new EngineError(category, {\n\t\tcode: dto.code,\n\t\tmessage: dto.message,\n\t\texpected: dto.expected,\n\t\tfound: dto.found,\n\t\tsuggestion: dto.suggestion,\n\t\trecoverable: dto.recoverable,\n\t\tspan: dto.span,\n\t});\n}\n\n/** The error a request rejects with when its caller aborts through an `AbortSignal`. */\nexport function workerCancelledError(method?: string): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_CANCELLED,\n\t\tmethod\n\t\t\t? `The worker request \"${method}\" was cancelled`\n\t\t\t: \"The worker request was cancelled\",\n\t\tmethod ? { method } : undefined,\n\t);\n}\n\n/** The error every pending request rejects with when the worker engine is terminated. */\nexport function workerTerminatedError(): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_TERMINATED,\n\t\t\"The worker engine was terminated before this request completed\",\n\t);\n}\n\n/** The error a request rejects with when the transport fails or the worker exits early. */\nexport function workerTransportError(detail: string): EngineError {\n\treturn ErrorFactory.external(\n\t\tWorkerErrorCodes.WORKER_TRANSPORT_FAILED,\n\t\t`The worker transport failed: ${detail}`,\n\t\t{ detail },\n\t);\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
'use strict';var chunkDUFEONVN_cjs=require('./chunk-DUFEONVN.cjs'),chunkOM7NOHJF_cjs=require('./chunk-OM7NOHJF.cjs');var u=[10,11,12,13,14,16,60,61,62,63,150,159,95,96],E=[50,51,151,152,160],C=[157,158,161],L=(()=>{let r=new Array(256).fill(0);for(let e of u)r[e]=1;for(let e of E)r[e]=2;for(let e of C)r[e]=3;return r})();[...u,...E,...C];function m(r,e){return e+1+(L[r[e]]??0)}var R="currency",A=class{constructor(e){this.namespace=R;this.exchange=e??chunkDUFEONVN_cjs.b;}preflight(e,N,U,S,y){let{opcodes:c,strings:_}=N,f=c.length,o=0,i=-1,p=-1;for(;o<f;){let t=c[o];if(t===13&&(p=i,i=c[o+1]),(t===84||t===81||t===20||t===21||t===22||t===23)&&p>=0&&i>=0){let n=_[p],s=_[i];if(this.exchange.isCurrency(n)&&this.exchange.isCurrency(s)&&n.toUpperCase()!==s.toUpperCase()&&this.exchange.getRateSync(n,s)===null){let I=n.toUpperCase(),d=s.toUpperCase(),a=[R,I,d];if(y.getQueryData(a)!==void 0){o++;continue}let g=y.fetchQuery({queryKey:a,queryFn:({signal:h})=>this.exchange.getRate(n,s,h).then(T=>chunkOM7NOHJF_cjs.n(T)),staleTime:300*1e3});return {queryKey:a.join(":"),resolver:g,packageId:U,signal:S,metadata:{fromUnit:n,toUnit:s}}}}o=m(c,o);}return null}destroy(){}};exports.a=m;exports.b=A;//# sourceMappingURL=chunk-A755LVPT.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-A755LVPT.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parser/OperandWidth.ts","../src/uom/CurrencyResolver.ts"],"names":["ONE_OPERAND","TWO_OPERANDS","THREE_OPERANDS","OPERAND_BYTES","widths","op","nextInstruction","opcodes","index","CURRENCY_NS","CurrencyAsyncResolver","exchange","currencyExchangeService","_tokens","bytecode","packageId","signal","queryClient","strings","len","i","lastStrIdx","prevStrIdx","fromUnit","toUnit","fromUpper","toUpper","cacheKey","resolver","qSignal","rate","numberValue"],"mappings":"qHAwBA,IAAMA,CAAAA,CAAiC,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA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E,MAAA,CAAQE,CAAQ,IACpB,IAAA,CAAK,QAAA,CAAS,OAAA,CAAQN,CAAAA,CAAUC,CAAAA,CAAQK,CAAO,CAAA,CAAE,IAAA,CAAMC,CAAAA,EAASC,mBAAAA,CAAYD,CAAI,CAAC,CAAA,CAEzF,SAAA,CAAW,GAAA,CAAS,GACrB,CAAC,CAAA,CAED,OAAO,CAAE,QAAA,CAAUH,CAAAA,CAAS,IAAA,CAAK,GAAG,CAAA,CAAG,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAb,CAAAA,CAAW,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAU,CAAE,SAAAO,CAAAA,CAAU,MAAA,CAAAC,CAAO,CAAE,CACpG,CAEF,CAKDJ,CAAAA,CAAId,EAAgBC,CAAAA,CAASa,CAAC,EAC/B,CAEA,OAAO,IACR,CAEA,OAAA,EAAgB,CAEhB,CACD","file":"chunk-KYE5BWPN.cjs","sourcesContent":["/**\n * How many operand bytes follow each opcode, and how to step over one.\n *\n * Anything walking a bytecode stream without executing it needs this: the\n * resolver preflight scanners look for specific opcodes and must skip past\n * everything else without mistaking an operand byte for an instruction.\n *\n * It used to be a hand-copied switch in each of those scanners. They had\n * already drifted: two counted `CALL_PLUGIN` as three bytes wide and the third\n * omitted it from that arm, so a stream containing one desynchronised there and\n * every opcode after it was read at the wrong offset. Adding an opcode meant\n * remembering every copy, and nothing checked that you had.\n *\n * `__tests__/parser/OperandWidth.spec.ts` asserts every opcode has a width, so\n * a new one fails a test rather than silently defaulting to zero operands.\n */\n\nimport { OpCode } from \"@solve-js/parser/OpCode\";\n\n/**\n * Opcodes taking one operand byte.\n *\n * A constant-pool index, or a variable-name index.\n */\nconst ONE_OPERAND: readonly OpCode[] = [\n\tOpCode.PUSH_NUMBER,\n\tOpCode.PUSH_BIGINT,\n\tOpCode.PUSH_HEX,\n\tOpCode.PUSH_STRING,\n\tOpCode.PUSH_BOOLEAN,\n\t// Its operand is a string-pool index holding the exact decimal text, so a\n\t// scanner must step over one byte exactly as it does for PUSH_STRING.\n\tOpCode.PUSH_DECIMAL,\n\tOpCode.LOAD_VAR,\n\tOpCode.STORE_VAR,\n\tOpCode.LOAD_GLOBAL_VAR,\n\tOpCode.STORE_GLOBAL_VAR,\n\tOpCode.DEFINE_USER_FUNCTION,\n\tOpCode.BIND_UNKNOWN,\n\t// Its operand is a constant-pool index, like PUSH_NUMBER's: the epoch-ms\n\t// was resolved at parse time and stored in `numbers`. Omitting it made\n\t// every scanner read that index byte as an opcode, so an ordinary date\n\t// literal desynchronised the whole preflight walk.\n\tOpCode.DATE_LITERAL,\n\t// One byte, the offset direction (0 forward, 1 backward) for \"N working\n\t// days after/before/from <date>\". See WorkdayOffsetParselet. DATE_WORKDAYS_BETWEEN\n\t// takes no operand and so is not listed here.\n\tOpCode.DATE_WORKDAY_OFFSET,\n];\n\n/**\n * Opcodes taking two operand bytes.\n *\n * A callable index plus an argument count, or a matrix's row and column counts.\n */\nconst TWO_OPERANDS: readonly OpCode[] = [\n\tOpCode.CALL_PLUGIN,\n\tOpCode.CALL_BUILTIN,\n\tOpCode.CALL_USER_FUNCTION,\n\tOpCode.MAT_NEW,\n\t// A body index plus the pooled source-expression string.\n\tOpCode.PLOT_INVOKE,\n];\n\n/**\n * Opcodes taking three operand bytes.\n *\n * The map and reduce invocations, which carry a body index alongside their\n * other operands.\n */\n// CALL_PLUGIN_WIDE: a two-byte plugin index plus the one-byte argument count.\nconst THREE_OPERANDS: readonly OpCode[] = [OpCode.MAP_INVOKE, OpCode.REDUCE_INVOKE, OpCode.CALL_PLUGIN_WIDE];\n\n/**\n * Operand byte count for every opcode, indexed by opcode value.\n *\n * A dense array rather than a map, because the preflight scanners run on every\n * keystroke and this is read once per instruction.\n */\nexport const OPERAND_BYTES: readonly number[] = (() => {\n\tconst widths = new Array<number>(256).fill(0);\n\tfor (const op of ONE_OPERAND) widths[op] = 1;\n\tfor (const op of TWO_OPERANDS) widths[op] = 2;\n\tfor (const op of THREE_OPERANDS) widths[op] = 3;\n\treturn widths;\n})();\n\n/**\n * Every opcode that takes at least one operand.\n *\n * Exported so a test can assert the table stays complete as opcodes are added.\n */\nexport const OPCODES_WITH_OPERANDS: readonly OpCode[] = [\n\t...ONE_OPERAND,\n\t...TWO_OPERANDS,\n\t...THREE_OPERANDS,\n];\n\n/**\n * Offset of the instruction after the one at `index`.\n *\n * @param opcodes - The bytecode stream.\n * @param index - Offset of an opcode, not of an operand byte. Passing an\n * operand offset yields nonsense, which is the failure mode this exists to\n * prevent: a caller stepping by hand and getting one width wrong reads the rest\n * of the stream misaligned.\n * @returns Offset of the next opcode. May be past the end when the instruction\n * at `index` is the last one, so callers loop while it is under `opcodes.length`.\n */\nexport function nextInstruction(opcodes: Uint8Array, index: number): number {\n\treturn index + 1 + (OPERAND_BYTES[opcodes[index]] ?? 0);\n}\n","/**\n * Currency async resolver, bridges CurrencyExchangeService to the\n * IAsyncResolver interface for the Suspense architecture.\n *\n * Uses TanStack Query (injected via queryClient) as the single cache layer.\n */\nimport type { QueryClient } from \"@tanstack/query-core\";\nimport type { Token } from \"@solve-js/lexer\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { numberValue } from \"@solve-js/vm/Value\";\nimport {\n\tcurrencyExchangeService,\n\tCurrencyExchangeService,\n} from \"@solve-js/uom/CurrencyExchange\";\nimport type { IAsyncResolver, AsyncCheckResult } from \"@solve-js/resolvers/ResolverRegistry\";\nimport { nextInstruction } from \"@solve-js/parser/OperandWidth\";\n\nconst CURRENCY_NS = \"currency\";\n\n/**\n * Fetches exchange rates before the VM runs, so a conversion has real numbers.\n *\n * Until rates arrive the line evaluates to a pending value rather than a\n * guessed one, and re-evaluates when they land.\n */\nexport class CurrencyAsyncResolver implements IAsyncResolver {\n\treadonly namespace = CURRENCY_NS;\n\n\tprivate exchange: CurrencyExchangeService;\n\n\tconstructor(exchange?: CurrencyExchangeService) {\n\t\tthis.exchange = exchange ?? currencyExchangeService;\n\t}\n\n\tpreflight(_tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null {\n\t\tconst { opcodes, strings } = bytecode;\n\t\tconst len = opcodes.length;\n\t\tlet i = 0;\n\n\t\tlet lastStrIdx = -1;\n\t\tlet prevStrIdx = -1;\n\n\t\twhile (i < len) {\n\t\t\tconst op = opcodes[i] as OpCode;\n\n\t\t\tif (op === OpCode.PUSH_STRING) {\n\t\t\t\tprevStrIdx = lastStrIdx;\n\t\t\t\tlastStrIdx = opcodes[i + 1];\n\t\t\t}\n\n\t\t\t// Explicit \"X to Y\"/\"X in Y\" conversions (UOM_CONVERT_IN/_TO) are\n\t\t\t// the obvious case, but arithmetic directly on two differently-\n\t\t\t// denominated currency literals, \"0.01 BTC + 1 ETH\", needs the\n\t\t\t// exact same preflight fetch and previously never got it: this\n\t\t\t// scanner only looked for the CONVERT opcodes, so ADD/SUB/MUL/DIV\n\t\t\t// between two currency UOMs skipped preflight entirely, ran with\n\t\t\t// no cached rate, and fell through to the VM's silent-wrong-math\n\t\t\t// fallback instead of ever reaching a network fetch.\n\t\t\tconst isCurrencyCombiningOp =\n\t\t\t\top === OpCode.UOM_CONVERT_IN || op === OpCode.UOM_CONVERT_TO ||\n\t\t\t\top === OpCode.ADD || op === OpCode.SUB || op === OpCode.MUL || op === OpCode.DIV;\n\t\t\tif (isCurrencyCombiningOp) {\n\t\t\t\tif (prevStrIdx >= 0 && lastStrIdx >= 0) {\n\t\t\t\t\tconst fromUnit = strings[prevStrIdx];\n\t\t\t\t\tconst toUnit = strings[lastStrIdx];\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.exchange.isCurrency(fromUnit) &&\n\t\t\t\t\t\tthis.exchange.isCurrency(toUnit) &&\n\t\t\t\t\t\tfromUnit.toUpperCase() !== toUnit.toUpperCase()\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst syncRate = this.exchange.getRateSync(fromUnit, toUnit);\n\t\t\t\t\t\tif (syncRate === null) {\n\t\t\t\t\t\t\tconst fromUpper = fromUnit.toUpperCase();\n\t\t\t\t\t\t\tconst toUpper = toUnit.toUpperCase();\n\n\t\t\t\t\t\t\t// Check TanStack Query cache\n\t\t\t\t\t\t\tconst cacheKey = [CURRENCY_NS, fromUpper, toUpper];\n\t\t\t\t\t\t\tif (queryClient.getQueryData(cacheKey) !== undefined) {\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Fetch via TanStack Query (dedup + retry automatic)\n\t\t\t\t\t\t\tconst resolver = queryClient.fetchQuery({\n\t\t\t\t\t\t\t\tqueryKey: cacheKey,\n\t\t\t\t\t\t\t\tqueryFn: ({ signal: qSignal }) => {\n\t\t\t\t\t\t\t\t\treturn this.exchange.getRate(fromUnit, toUnit, qSignal).then((rate) => numberValue(rate));\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn { queryKey: cacheKey.join(\":\"), resolver, packageId, signal, metadata: { fromUnit, toUnit } };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Step over this instruction and its operands. Shared table, because\n\t\t\t// three hand-copied versions of this had already drifted.\n\t\t\ti = nextInstruction(opcodes, i);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tdestroy(): void {\n\t\t// Cache cleared by ResolverRegistry.unregister() via removeQueries({ queryKey: [\"currency\"] })\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parser/OperandWidth.ts","../src/uom/CurrencyResolver.ts"],"names":["ONE_OPERAND","TWO_OPERANDS","THREE_OPERANDS","OPERAND_BYTES","widths","op","nextInstruction","opcodes","index","CURRENCY_NS","CurrencyAsyncResolver","exchange","currencyExchangeService","_tokens","bytecode","packageId","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,EAAY,CAG7BG,CAAAA,CAAW,CAAClB,EAAagB,CAAAA,CAAWC,CAAO,CAAA,CACjD,GAAIT,CAAAA,CAAY,YAAA,CAAaU,CAAQ,CAAA,GAAM,OAAW,CACrDP,CAAAA,EAAAA,CACA,QACD,CAGA,IAAMQ,CAAAA,CAAWX,CAAAA,CAAY,UAAA,CAAW,CACvC,QAAA,CAAUU,CAAAA,CACV,OAAA,CAAS,CAAC,CAAE,MAAA,CAAQE,CAAQ,IACpB,IAAA,CAAK,QAAA,CAAS,OAAA,CAAQN,CAAAA,CAAUC,CAAAA,CAAQK,CAAO,CAAA,CAAE,IAAA,CAAMC,CAAAA,EAASC,mBAAAA,CAAYD,CAAI,CAAC,CAAA,CAEzF,SAAA,CAAW,GAAA,CAAS,GACrB,CAAC,CAAA,CAED,OAAO,CAAE,QAAA,CAAUH,CAAAA,CAAS,IAAA,CAAK,GAAG,CAAA,CAAG,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAb,CAAAA,CAAW,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAU,CAAE,SAAAO,CAAAA,CAAU,MAAA,CAAAC,CAAO,CAAE,CACpG,CAEF,CAKDJ,CAAAA,CAAId,EAAgBC,CAAAA,CAASa,CAAC,EAC/B,CAEA,OAAO,IACR,CAEA,OAAA,EAAgB,CAEhB,CACD","file":"chunk-A755LVPT.cjs","sourcesContent":["/**\n * How many operand bytes follow each opcode, and how to step over one.\n *\n * Anything walking a bytecode stream without executing it needs this: the\n * resolver preflight scanners look for specific opcodes and must skip past\n * everything else without mistaking an operand byte for an instruction.\n *\n * It used to be a hand-copied switch in each of those scanners. They had\n * already drifted: two counted `CALL_PLUGIN` as three bytes wide and the third\n * omitted it from that arm, so a stream containing one desynchronised there and\n * every opcode after it was read at the wrong offset. Adding an opcode meant\n * remembering every copy, and nothing checked that you had.\n *\n * `__tests__/parser/OperandWidth.spec.ts` asserts every opcode has a width, so\n * a new one fails a test rather than silently defaulting to zero operands.\n */\n\nimport { OpCode } from \"@solve-js/parser/OpCode\";\n\n/**\n * Opcodes taking one operand byte.\n *\n * A constant-pool index, or a variable-name index.\n */\nconst ONE_OPERAND: readonly OpCode[] = [\n\tOpCode.PUSH_NUMBER,\n\tOpCode.PUSH_BIGINT,\n\tOpCode.PUSH_HEX,\n\tOpCode.PUSH_STRING,\n\tOpCode.PUSH_BOOLEAN,\n\t// Its operand is a string-pool index holding the exact decimal text, so a\n\t// scanner must step over one byte exactly as it does for PUSH_STRING.\n\tOpCode.PUSH_DECIMAL,\n\tOpCode.LOAD_VAR,\n\tOpCode.STORE_VAR,\n\tOpCode.LOAD_GLOBAL_VAR,\n\tOpCode.STORE_GLOBAL_VAR,\n\tOpCode.DEFINE_USER_FUNCTION,\n\tOpCode.BIND_UNKNOWN,\n\t// Its operand is a constant-pool index, like PUSH_NUMBER's: the epoch-ms\n\t// was resolved at parse time and stored in `numbers`. Omitting it made\n\t// every scanner read that index byte as an opcode, so an ordinary date\n\t// literal desynchronised the whole preflight walk.\n\tOpCode.DATE_LITERAL,\n\t// One byte, the offset direction (0 forward, 1 backward) for \"N working\n\t// days after/before/from <date>\". See WorkdayOffsetParselet. DATE_WORKDAYS_BETWEEN\n\t// takes no operand and so is not listed here.\n\tOpCode.DATE_WORKDAY_OFFSET,\n];\n\n/**\n * Opcodes taking two operand bytes.\n *\n * A callable index plus an argument count, or a matrix's row and column counts.\n */\nconst TWO_OPERANDS: readonly OpCode[] = [\n\tOpCode.CALL_PLUGIN,\n\tOpCode.CALL_BUILTIN,\n\tOpCode.CALL_USER_FUNCTION,\n\tOpCode.MAT_NEW,\n\t// A body index plus the pooled source-expression string.\n\tOpCode.PLOT_INVOKE,\n];\n\n/**\n * Opcodes taking three operand bytes.\n *\n * The map and reduce invocations, which carry a body index alongside their\n * other operands.\n */\n// CALL_PLUGIN_WIDE: a two-byte plugin index plus the one-byte argument count.\nconst THREE_OPERANDS: readonly OpCode[] = [OpCode.MAP_INVOKE, OpCode.REDUCE_INVOKE, OpCode.CALL_PLUGIN_WIDE];\n\n/**\n * Operand byte count for every opcode, indexed by opcode value.\n *\n * A dense array rather than a map, because the preflight scanners run on every\n * keystroke and this is read once per instruction.\n */\nexport const OPERAND_BYTES: readonly number[] = (() => {\n\tconst widths = new Array<number>(256).fill(0);\n\tfor (const op of ONE_OPERAND) widths[op] = 1;\n\tfor (const op of TWO_OPERANDS) widths[op] = 2;\n\tfor (const op of THREE_OPERANDS) widths[op] = 3;\n\treturn widths;\n})();\n\n/**\n * Every opcode that takes at least one operand.\n *\n * Exported so a test can assert the table stays complete as opcodes are added.\n */\nexport const OPCODES_WITH_OPERANDS: readonly OpCode[] = [\n\t...ONE_OPERAND,\n\t...TWO_OPERANDS,\n\t...THREE_OPERANDS,\n];\n\n/**\n * Offset of the instruction after the one at `index`.\n *\n * @param opcodes - The bytecode stream.\n * @param index - Offset of an opcode, not of an operand byte. Passing an\n * operand offset yields nonsense, which is the failure mode this exists to\n * prevent: a caller stepping by hand and getting one width wrong reads the rest\n * of the stream misaligned.\n * @returns Offset of the next opcode. May be past the end when the instruction\n * at `index` is the last one, so callers loop while it is under `opcodes.length`.\n */\nexport function nextInstruction(opcodes: Uint8Array, index: number): number {\n\treturn index + 1 + (OPERAND_BYTES[opcodes[index]] ?? 0);\n}\n","/**\n * Currency async resolver, bridges CurrencyExchangeService to the\n * IAsyncResolver interface for the Suspense architecture.\n *\n * Uses TanStack Query (injected via queryClient) as the single cache layer.\n */\nimport type { QueryClient } from \"@tanstack/query-core\";\nimport type { Token } from \"@solve-js/lexer\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { numberValue } from \"@solve-js/vm/Value\";\nimport {\n\tcurrencyExchangeService,\n\tCurrencyExchangeService,\n} from \"@solve-js/uom/CurrencyExchange\";\nimport type { IAsyncResolver, AsyncCheckResult } from \"@solve-js/resolvers/ResolverRegistry\";\nimport { nextInstruction } from \"@solve-js/parser/OperandWidth\";\n\nconst CURRENCY_NS = \"currency\";\n\n/**\n * Fetches exchange rates before the VM runs, so a conversion has real numbers.\n *\n * Until rates arrive the line evaluates to a pending value rather than a\n * guessed one, and re-evaluates when they land.\n */\nexport class CurrencyAsyncResolver implements IAsyncResolver {\n\treadonly namespace = CURRENCY_NS;\n\n\tprivate exchange: CurrencyExchangeService;\n\n\tconstructor(exchange?: CurrencyExchangeService) {\n\t\tthis.exchange = exchange ?? currencyExchangeService;\n\t}\n\n\tpreflight(_tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null {\n\t\tconst { opcodes, strings } = bytecode;\n\t\tconst len = opcodes.length;\n\t\tlet i = 0;\n\n\t\tlet lastStrIdx = -1;\n\t\tlet prevStrIdx = -1;\n\n\t\twhile (i < len) {\n\t\t\tconst op = opcodes[i] as OpCode;\n\n\t\t\tif (op === OpCode.PUSH_STRING) {\n\t\t\t\tprevStrIdx = lastStrIdx;\n\t\t\t\tlastStrIdx = opcodes[i + 1];\n\t\t\t}\n\n\t\t\t// Explicit \"X to Y\"/\"X in Y\" conversions (UOM_CONVERT_IN/_TO) are\n\t\t\t// the obvious case, but arithmetic directly on two differently-\n\t\t\t// denominated currency literals, \"0.01 BTC + 1 ETH\", needs the\n\t\t\t// exact same preflight fetch and previously never got it: this\n\t\t\t// scanner only looked for the CONVERT opcodes, so ADD/SUB/MUL/DIV\n\t\t\t// between two currency UOMs skipped preflight entirely, ran with\n\t\t\t// no cached rate, and fell through to the VM's silent-wrong-math\n\t\t\t// fallback instead of ever reaching a network fetch.\n\t\t\tconst isCurrencyCombiningOp =\n\t\t\t\top === OpCode.UOM_CONVERT_IN || op === OpCode.UOM_CONVERT_TO ||\n\t\t\t\top === OpCode.ADD || op === OpCode.SUB || op === OpCode.MUL || op === OpCode.DIV;\n\t\t\tif (isCurrencyCombiningOp) {\n\t\t\t\tif (prevStrIdx >= 0 && lastStrIdx >= 0) {\n\t\t\t\t\tconst fromUnit = strings[prevStrIdx];\n\t\t\t\t\tconst toUnit = strings[lastStrIdx];\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.exchange.isCurrency(fromUnit) &&\n\t\t\t\t\t\tthis.exchange.isCurrency(toUnit) &&\n\t\t\t\t\t\tfromUnit.toUpperCase() !== toUnit.toUpperCase()\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst syncRate = this.exchange.getRateSync(fromUnit, toUnit);\n\t\t\t\t\t\tif (syncRate === null) {\n\t\t\t\t\t\t\tconst fromUpper = fromUnit.toUpperCase();\n\t\t\t\t\t\t\tconst toUpper = toUnit.toUpperCase();\n\n\t\t\t\t\t\t\t// Check TanStack Query cache\n\t\t\t\t\t\t\tconst cacheKey = [CURRENCY_NS, fromUpper, toUpper];\n\t\t\t\t\t\t\tif (queryClient.getQueryData(cacheKey) !== undefined) {\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Fetch via TanStack Query (dedup + retry automatic)\n\t\t\t\t\t\t\tconst resolver = queryClient.fetchQuery({\n\t\t\t\t\t\t\t\tqueryKey: cacheKey,\n\t\t\t\t\t\t\t\tqueryFn: ({ signal: qSignal }) => {\n\t\t\t\t\t\t\t\t\treturn this.exchange.getRate(fromUnit, toUnit, qSignal).then((rate) => numberValue(rate));\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn { queryKey: cacheKey.join(\":\"), resolver, packageId, signal, metadata: { fromUnit, toUnit } };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Step over this instruction and its operands. Shared table, because\n\t\t\t// three hand-copied versions of this had already drifted.\n\t\t\ti = nextInstruction(opcodes, i);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tdestroy(): void {\n\t\t// Cache cleared by ResolverRegistry.unregister() via removeQueries({ queryKey: [\"currency\"] })\n\t}\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkE4HAKNBQ_cjs=require('./chunk-E4HAKNBQ.cjs'),
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
'use strict';var chunkE4HAKNBQ_cjs=require('./chunk-E4HAKNBQ.cjs'),chunkSUAGBRQ7_cjs=require('./chunk-SUAGBRQ7.cjs');var s=class{now(){return Date.now()}fields(t){let e=new Date(t);return {year:e.getFullYear(),month0:e.getMonth(),day:e.getDate(),weekday:e.getDay(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),millisecond:e.getMilliseconds()}}localMidnight(t,e,n){return new Date(t,e,n).getTime()}localWallClock(t,e,n,r){let a=new Date(t,e,n,0,0,0,0);return a.setMinutes(r),a.getTime()}addDays(t,e){let n=new Date(t);return n.setDate(n.getDate()+e),n.getTime()}addMonths(t,e){let n=new Date(t),r=n.getDate();return n.setDate(1),n.setMonth(n.getMonth()+e),n.setDate(Math.min(r,chunkE4HAKNBQ_cjs.b(n.getFullYear(),n.getMonth()))),n.getTime()}utcOffsetMinutes(t){return 0-new Date(t).getTimezoneOffset()}parseIso8601(t){return new Date(t).getTime()}formatLongDate(t,e){return new Date(t).toLocaleDateString(e,{weekday:"long",year:"numeric",month:"long",day:"numeric"})}formatTimeOfDay(t,e){return new Date(t).toLocaleTimeString(e)}zoneOffsetMinutes(t,e){let n=chunkE4HAKNBQ_cjs.l(t,e);return Math.round((chunkE4HAKNBQ_cjs.a(n.year,n.month0,n.day,n.hour,n.minute,n.second)-e)/6e4)||0}fieldsInZone(t,e){return chunkE4HAKNBQ_cjs.l(t,e)}formatTimeInZone(t,e){return chunkE4HAKNBQ_cjs.m(t,e)}formatDateInZone(t,e){return chunkE4HAKNBQ_cjs.n(t,e)}},k=new s;function L(o){return o?.calendar??k}var O=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?$/,l=class extends s{constructor(e){super();this.namedZone=e;}zone(){return this.namedZone}fields(e){let n=chunkE4HAKNBQ_cjs.l(this.namedZone,e),r=((chunkE4HAKNBQ_cjs.c(n.year,n.month0,n.day)+4)%7+7)%7;return {year:n.year,month0:n.month0,day:n.day,weekday:r,hour:n.hour,minute:n.minute,second:n.second,millisecond:(e%1e3+1e3)%1e3}}localMidnight(e,n,r){return chunkE4HAKNBQ_cjs.j(e,n,r,0,0,this.namedZone,this)}localWallClock(e,n,r,a){return chunkE4HAKNBQ_cjs.j(e,n,r,0,a,this.namedZone,this)}addDays(e,n){let r=chunkE4HAKNBQ_cjs.l(this.namedZone,e);return this.reanchor(r,r.day+n,e)}addMonths(e,n){let r=chunkE4HAKNBQ_cjs.l(this.namedZone,e),a=new Date(Date.UTC(r.year,r.month0+n,1)),i=Math.min(r.day,chunkE4HAKNBQ_cjs.b(a.getUTCFullYear(),a.getUTCMonth()));return chunkE4HAKNBQ_cjs.j(a.getUTCFullYear(),a.getUTCMonth(),i,r.hour,r.minute,this.namedZone,this)+r.second*1e3+(e%1e3+1e3)%1e3}utcOffsetMinutes(e){return this.zoneOffsetMinutes(this.namedZone,e)}parseIso8601(e){let n=O.exec(e.trim());if(n===null)return super.parseIso8601(e);let[,r,a,i,w,p,c,b]=n,I=b===void 0?0:Number(b.slice(0,3).padEnd(3,"0"));return chunkE4HAKNBQ_cjs.j(Number(r),Number(a)-1,Number(i),Number(w),Number(p),this.namedZone,this)+(c===void 0?0:Number(c))*1e3+I}formatLongDate(e,n){return chunkE4HAKNBQ_cjs.o(this.namedZone,e,n)}formatTimeOfDay(e,n){return chunkE4HAKNBQ_cjs.p(this.namedZone,e,n)}reanchor(e,n,r){return chunkE4HAKNBQ_cjs.j(e.year,e.month0,n,e.hour,e.minute,this.namedZone,this)+e.second*1e3+(r%1e3+1e3)%1e3}};function U(o){if(!chunkE4HAKNBQ_cjs.k(o))throw chunkSUAGBRQ7_cjs.c.config(chunkSUAGBRQ7_cjs.s.DATE_ZONE_UNKNOWN,`dateCalendarInZone("${o}") is not a time zone this runtime knows.`);return new l(o)}exports.a=s;exports.b=k;exports.c=L;exports.d=U;//# sourceMappingURL=chunk-A764BY7L.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-A764BY7L.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/calendar/DateCalendar.ts"],"names":["DateCalendar","epochMs","d","year","month0","day","minutesPastMidnight","anchored","days","date","months","dayOfMonth","daysInMonth","text","locale","zone","f","zonedFields","utcMs","timeInZone","dateInZone","DATE_CALENDAR","calendarOf","context","ISO_LOCAL_DATE_TIME","ZonedDateCalendar","namedZone","weekday","dayNumber","zonedWallClockToUtcMs","target","clampedDay","matched","month","hour","minute","second","fraction","millisecond","longDateInZone","timeOfDayInZone","dateCalendarInZone","isSupportedZone","ErrorFactory","DatetimeErrorCodes"],"mappings":"qHA0BO,IAAMA,EAAN,KAA8C,CACpD,GAAA,EAAc,CACb,OAAO,IAAA,CAAK,GAAA,EACb,CAEA,OAAOC,CAAAA,CAAiC,CACvC,IAAMC,CAAAA,CAAI,IAAI,IAAA,CAAKD,CAAO,CAAA,CAC1B,OAAO,CACN,IAAA,CAAMC,CAAAA,CAAE,WAAA,EAAY,CACpB,OAAQA,CAAAA,CAAE,QAAA,EAAS,CACnB,GAAA,CAAKA,EAAE,OAAA,EAAQ,CACf,QAASA,CAAAA,CAAE,MAAA,GACX,IAAA,CAAMA,CAAAA,CAAE,QAAA,EAAS,CACjB,OAAQA,CAAAA,CAAE,UAAA,EAAW,CACrB,MAAA,CAAQA,EAAE,UAAA,EAAW,CACrB,WAAA,CAAaA,CAAAA,CAAE,iBAChB,CACD,CAEA,aAAA,CAAcC,EAAcC,CAAAA,CAAgBC,CAAAA,CAAqB,CAChE,OAAO,IAAI,IAAA,CAAKF,CAAAA,CAAMC,CAAAA,CAAQC,CAAG,EAAE,OAAA,EACpC,CAEA,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G,MAAA,CAAO6B,CAAI,CAAA,CAAG,MAAA,CAAOC,CAAM,CAAA,CAAG,IAAA,CAAK,UAAW,IAAI,CAAA,CAAA,CACzHC,IAAW,MAAA,CAAY,CAAA,CAAI,MAAA,CAAOA,CAAM,GAAK,GAAA,CAAOE,CACzD,CAEA,cAAA,CAAerC,EAAiBa,CAAAA,CAAwB,CACvD,OAAOyB,mBAAAA,CAAe,KAAK,SAAA,CAAWtC,CAAAA,CAASa,CAAM,CACtD,CAEA,eAAA,CAAgBb,CAAAA,CAAiBa,CAAAA,CAAwB,CACxD,OAAO0B,mBAAAA,CAAgB,IAAA,CAAK,SAAA,CAAWvC,CAAAA,CAASa,CAAM,CACvD,CAGQ,QAAA,CAASE,CAAAA,CAAgBX,EAAaJ,CAAAA,CAAyB,CACtE,OAAO4B,mBAAAA,CAAsBb,CAAAA,CAAE,KAAMA,CAAAA,CAAE,MAAA,CAAQX,CAAAA,CAAKW,CAAAA,CAAE,KAAMA,CAAAA,CAAE,MAAA,CAAQ,IAAA,CAAK,SAAA,CAAW,IAAI,CAAA,CACvFA,CAAAA,CAAE,MAAA,CAAS,GAAA,CAAA,CAAUf,EAAU,GAAA,CAAQ,GAAA,EAAQ,GACnD,CACD,CAAA,CA6BO,SAASwC,CAAAA,CAAmB1B,CAAAA,CAA+B,CACjE,GAAI,CAAC2B,mBAAAA,CAAgB3B,CAAI,CAAA,CACxB,MAAM4B,oBAAa,MAAA,CAClBC,mBAAAA,CAAmB,iBAAA,CACnB,CAAA,oBAAA,EAAuB7B,CAAI,CAAA,yCAAA,CAC5B,CAAA,CAED,OAAO,IAAIU,CAAAA,CAAkBV,CAAI,CAClC","file":"chunk-5J2XDCSV.cjs","sourcesContent":["import { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { DatetimeErrorCodes } from \"@solve-js/errors/ErrorCode\";\nimport type { CalendarBackend, CalendarFields, ZonedFields } from \"./CalendarBackend\";\nimport { dayNumber, daysInMonth, utcMs } from \"./Gregorian\";\nimport { dateInZone, isSupportedZone, longDateInZone, timeInZone, timeOfDayInZone, zonedFields, zonedWallClockToUtcMs } from \"./IntlZone\";\n\n/**\n * The default {@link CalendarBackend}: the JavaScript `Date` object, read in\n * the host process's time zone, with `Intl.DateTimeFormat` for named zones.\n *\n * This is the calendar code the engine has always run, moved behind the\n * interface method by method rather than rewritten, so a host that configures\n * nothing sees the same instants and the same strings it did before the\n * backend existed. Where `Date` has a quirk (a two-digit year in a\n * constructor maps to the 1900s, an out-of-range instant answers `NaN`), the\n * quirk is kept here deliberately: the point of this backend is to be the\n * behaviour the `Temporal` backend is measured against, not to improve on it.\n *\n * It stays the default because it is the one calendar every supported runtime\n * has. `Temporal` ships unflagged in Node 26 and in current Chrome, Firefox\n * and Deno, but not in Safari or in the Node 22 and 24 the engine supports,\n * and the smallest polyfill adds about twenty kilobytes gzipped to a bundle\n * that a host doing plain arithmetic never needs. A host that wants\n * `Temporal` opts in through the engine's `calendar` option with the backend\n * from `solve-engine/temporal`, and pays for it only then.\n */\nexport class DateCalendar implements CalendarBackend {\n\tnow(): number {\n\t\treturn Date.now();\n\t}\n\n\tfields(epochMs: number): CalendarFields {\n\t\tconst d = new Date(epochMs);\n\t\treturn {\n\t\t\tyear: d.getFullYear(),\n\t\t\tmonth0: d.getMonth(),\n\t\t\tday: d.getDate(),\n\t\t\tweekday: d.getDay(),\n\t\t\thour: d.getHours(),\n\t\t\tminute: d.getMinutes(),\n\t\t\tsecond: d.getSeconds(),\n\t\t\tmillisecond: d.getMilliseconds(),\n\t\t};\n\t}\n\n\tlocalMidnight(year: number, month0: number, day: number): number {\n\t\treturn new Date(year, month0, day).getTime();\n\t}\n\n\tlocalWallClock(year: number, month0: number, day: number, minutesPastMidnight: number): number {\n\t\t// Anchored at midnight and then moved by the minutes FIELD, so the\n\t\t// result is the wall-clock reading asked for whatever the day's length.\n\t\tconst anchored = new Date(year, month0, day, 0, 0, 0, 0);\n\t\tanchored.setMinutes(minutesPastMidnight);\n\t\treturn anchored.getTime();\n\t}\n\n\taddDays(epochMs: number, days: number): number {\n\t\tconst date = new Date(epochMs);\n\t\tdate.setDate(date.getDate() + days);\n\t\treturn date.getTime();\n\t}\n\n\taddMonths(epochMs: number, months: number): number {\n\t\tconst date = new Date(epochMs);\n\t\tconst dayOfMonth = date.getDate();\n\t\t// Parked on the 1st before the month field moves: `setMonth()` keeps\n\t\t// the day number, so a 31st aimed at a 30-day month would overflow\n\t\t// into the month after it. Clamping afterwards is what keeps the month\n\t\t// the caller asked for.\n\t\tdate.setDate(1);\n\t\tdate.setMonth(date.getMonth() + months);\n\t\tdate.setDate(Math.min(dayOfMonth, daysInMonth(date.getFullYear(), date.getMonth())));\n\t\treturn date.getTime();\n\t}\n\n\tutcOffsetMinutes(epochMs: number): number {\n\t\t// `getTimezoneOffset()` is (UTC minus local), so its sign is inverted\n\t\t// relative to the \"+HH:MM ahead of UTC\" reading every caller wants.\n\t\t// Subtracted from zero rather than negated, so a zero offset is 0 and\n\t\t// not -0, which a second backend could not be expected to reproduce.\n\t\treturn 0 - new Date(epochMs).getTimezoneOffset();\n\t}\n\n\tparseIso8601(text: string): number {\n\t\treturn new Date(text).getTime();\n\t}\n\n\tformatLongDate(epochMs: number, locale: string): string {\n\t\treturn new Date(epochMs).toLocaleDateString(locale, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" });\n\t}\n\n\tformatTimeOfDay(epochMs: number, locale: string): string {\n\t\treturn new Date(epochMs).toLocaleTimeString(locale);\n\t}\n\n\tzoneOffsetMinutes(zone: string, epochMs: number): number {\n\t\t// The `Intl` round trip: read the instant as the zone's wall-clock\n\t\t// fields, re-read those fields as if they were UTC, and the difference\n\t\t// from the instant is the zone's offset then, daylight saving included.\n\t\tconst f = zonedFields(zone, epochMs);\n\t\t// `|| 0` folds the -0 a negative sub-minute difference rounds to.\n\t\treturn Math.round((utcMs(f.year, f.month0, f.day, f.hour, f.minute, f.second) - epochMs) / 60000) || 0;\n\t}\n\n\tfieldsInZone(zone: string, epochMs: number): ZonedFields {\n\t\treturn zonedFields(zone, epochMs);\n\t}\n\n\tformatTimeInZone(zone: string, epochMs: number): string {\n\t\treturn timeInZone(zone, epochMs);\n\t}\n\n\tformatDateInZone(zone: string, epochMs: number): string {\n\t\treturn dateInZone(zone, epochMs);\n\t}\n}\n\n/**\n * The one `Date` backend, shared by every engine that configures no other.\n *\n * Stateless, so sharing is safe: it holds no zone of its own and reads the\n * process's. It is also what the sites with no engine in hand use (the\n * normaliser rules that fuse a literal, `days in <period>`, the stocks and\n * historical-currency date phrases, and `formatValue`), which is why an\n * engine's own backend is the default here rather than a second copy.\n */\nexport const DATE_CALENDAR: CalendarBackend = new DateCalendar();\n\n/**\n * The backend a plugin function or converter should compute with: the one\n * on its execution context, or the `Date` backend when the handler was\n * called with no context (a direct call from a test, or an `as` converter\n * invoked outside the VM).\n *\n * @param context - The execution context the handler received, if any.\n * @returns The engine's backend when the context carries one, else {@link DATE_CALENDAR}.\n */\nexport function calendarOf(context?: { readonly calendar?: CalendarBackend }): CalendarBackend {\n\treturn context?.calendar ?? DATE_CALENDAR;\n}\n\n/**\n * The `Date` backend, computing in a named IANA zone instead of the host\n * process's.\n *\n * Every zone-free answer is inherited unchanged from {@link DateCalendar}:\n * `now()` is still the clock, `parseIso8601` still reads the two ECMAScript\n * spellings, and the four named-zone methods already took the zone as an\n * argument. What changes is what \"local\" means, which is exactly the set of\n * questions {@link CalendarBackend} says depends on a zone: which day an\n * instant falls on, what a wall-clock reading names, what a day or a month\n * later is, and what the offset from UTC is.\n *\n * Those are answered through `Intl`, the same data the base class already\n * reads named zones with, so the accuracy is the same and nothing new is\n * bundled. The one place it is a simplification is a wall clock that a\n * daylight-saving transition made ambiguous or non-existent (01:30 on a\n * spring-forward morning): {@link zonedWallClockToUtcMs} resolves it one way,\n * and a `Temporal` backend's `disambiguation: 'compatible'` may resolve it an\n * hour differently.\n */\n/**\n * An ISO 8601 date-time with a time of day and NO offset and no `Z`: the one\n * spelling whose instant depends on which zone reads it. Anchored at both\n * ends, so a date-only string and anything carrying an offset fall through to\n * the base class untouched.\n */\nconst ISO_LOCAL_DATE_TIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?$/;\n\nclass ZonedDateCalendar extends DateCalendar {\n\t/**\n\t * @param namedZone - An IANA zone name `Intl` accepts.\n\t */\n\tconstructor(private readonly namedZone: string) {\n\t\tsuper();\n\t}\n\n\tzone(): string {\n\t\treturn this.namedZone;\n\t}\n\n\tfields(epochMs: number): CalendarFields {\n\t\tconst f = zonedFields(this.namedZone, epochMs);\n\t\t// `zonedFields` answers no weekday and no millisecond: the weekday is a\n\t\t// pure function of the zoned date (`Gregorian.dayNumber`, counting from a\n\t\t// Thursday), and the millisecond is the instant's own, which no zone\n\t\t// offset in use is fractional enough to move.\n\t\tconst weekday = (((dayNumber(f.year, f.month0, f.day) + 4) % 7) + 7) % 7;\n\t\treturn {\n\t\t\tyear: f.year, month0: f.month0, day: f.day, weekday,\n\t\t\thour: f.hour, minute: f.minute, second: f.second,\n\t\t\tmillisecond: ((epochMs % 1000) + 1000) % 1000,\n\t\t};\n\t}\n\n\tlocalMidnight(year: number, month0: number, day: number): number {\n\t\treturn zonedWallClockToUtcMs(year, month0, day, 0, 0, this.namedZone, this);\n\t}\n\n\tlocalWallClock(year: number, month0: number, day: number, minutesPastMidnight: number): number {\n\t\t// The minutes go in as the MINUTE field, not as elapsed time, so a\n\t\t// reading of 540 is 09:00 on that date even on a 23-hour day. `Date.UTC`\n\t\t// rolls a minute field past 59 into the hour, which is what makes one\n\t\t// argument enough.\n\t\treturn zonedWallClockToUtcMs(year, month0, day, 0, minutesPastMidnight, this.namedZone, this);\n\t}\n\n\taddDays(epochMs: number, days: number): number {\n\t\tconst f = zonedFields(this.namedZone, epochMs);\n\t\treturn this.reanchor(f, f.day + days, epochMs);\n\t}\n\n\taddMonths(epochMs: number, months: number): number {\n\t\tconst f = zonedFields(this.namedZone, epochMs);\n\t\tconst target = new Date(Date.UTC(f.year, f.month0 + months, 1));\n\t\tconst clampedDay = Math.min(f.day, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()));\n\t\treturn zonedWallClockToUtcMs(\n\t\t\ttarget.getUTCFullYear(), target.getUTCMonth(), clampedDay,\n\t\t\tf.hour, f.minute, this.namedZone, this,\n\t\t) + f.second * 1000 + (((epochMs % 1000) + 1000) % 1000);\n\t}\n\n\tutcOffsetMinutes(epochMs: number): number {\n\t\treturn this.zoneOffsetMinutes(this.namedZone, epochMs);\n\t}\n\n\tparseIso8601(text: string): number {\n\t\t// The one reading in that contract that depends on a zone: a date-time\n\t\t// with no offset and no `Z` is LOCAL time, and local here is the named\n\t\t// zone. Without this the backend contradicted itself, computing\n\t\t// `2026-04-03` at New York midnight while reading `2026-04-03T09:30` as\n\t\t// half past nine in the host process's zone. It is also what the\n\t\t// `Temporal` backend already does (`TemporalCalendar.parseIso8601`\n\t\t// resolves a bare wall clock in its own zone), so the two agree.\n\t\t//\n\t\t// Everything else is the base class byte for byte: a date-only string is\n\t\t// still UTC midnight and an explicit offset is still subtracted, both\n\t\t// frozen by the interface's contract.\n\t\tconst matched = ISO_LOCAL_DATE_TIME.exec(text.trim());\n\t\tif (matched === null) return super.parseIso8601(text);\n\t\tconst [, year, month, day, hour, minute, second, fraction] = matched;\n\t\tconst millisecond = fraction === undefined ? 0 : Number(fraction.slice(0, 3).padEnd(3, \"0\"));\n\t\treturn zonedWallClockToUtcMs(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), this.namedZone, this)\n\t\t\t+ (second === undefined ? 0 : Number(second)) * 1000 + millisecond;\n\t}\n\n\tformatLongDate(epochMs: number, locale: string): string {\n\t\treturn longDateInZone(this.namedZone, epochMs, locale);\n\t}\n\n\tformatTimeOfDay(epochMs: number, locale: string): string {\n\t\treturn timeOfDayInZone(this.namedZone, epochMs, locale);\n\t}\n\n\t/** Rebuild an instant on a (possibly overflowed) day, holding its wall clock down to the millisecond. */\n\tprivate reanchor(f: ZonedFields, day: number, epochMs: number): number {\n\t\treturn zonedWallClockToUtcMs(f.year, f.month0, day, f.hour, f.minute, this.namedZone, this)\n\t\t\t+ f.second * 1000 + (((epochMs % 1000) + 1000) % 1000);\n\t}\n}\n\n/**\n * A `Date` backend that computes in a named time zone rather than the host\n * process's.\n *\n * This is how a host pins the zone the engine reads dates in, and it is the\n * only knob for it: the zone belongs to the calendar backend, which already\n * owns what \"local\" means, so there is deliberately no `date.zone` config\n * field to drift against it.\n *\n * ```ts\n * import { createEngine, dateCalendarInZone } from \"solve-engine\";\n * const engine = createEngine({ calendar: dateCalendarInZone(\"Asia/Tokyo\") });\n * ```\n *\n * It ships on the `Date` backend on purpose. `Temporal` is undefined on Node\n * 24 and in Safari, so \"pass a `Temporal` backend\" would put the zone out of\n * reach for most hosts today; `Temporal` stays an accuracy upgrade for the\n * ambiguous wall clocks around a daylight-saving transition, never a\n * prerequisite for naming a zone at all.\n *\n * @param zone - An IANA zone name, e.g. `\"Asia/Tokyo\"`.\n * @returns A backend whose local zone is that one.\n * @throws A `DATE_ZONE_UNKNOWN` config error when this runtime's `Intl` does\n * not know the zone. Refused here rather than per line, because a backend\n * that cannot compute in the zone it was asked for must not quietly answer\n * in another one.\n */\nexport function dateCalendarInZone(zone: string): CalendarBackend {\n\tif (!isSupportedZone(zone)) {\n\t\tthrow ErrorFactory.config(\n\t\t\tDatetimeErrorCodes.DATE_ZONE_UNKNOWN,\n\t\t\t`dateCalendarInZone(\"${zone}\") is not a time zone this runtime knows.`,\n\t\t);\n\t}\n\treturn new ZonedDateCalendar(zone);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/calendar/DateCalendar.ts"],"names":["DateCalendar","epochMs","d","year","month0","day","minutesPastMidnight","anchored","days","date","months","dayOfMonth","daysInMonth","text","locale","zone","f","zonedFields","utcMs","timeInZone","dateInZone","DATE_CALENDAR","calendarOf","context","ISO_LOCAL_DATE_TIME","ZonedDateCalendar","namedZone","weekday","dayNumber","zonedWallClockToUtcMs","target","clampedDay","matched","month","hour","minute","second","fraction","millisecond","longDateInZone","timeOfDayInZone","dateCalendarInZone","isSupportedZone","ErrorFactory","DatetimeErrorCodes"],"mappings":"qHA0BO,IAAMA,EAAN,KAA8C,CACpD,GAAA,EAAc,CACb,OAAO,IAAA,CAAK,GAAA,EACb,CAEA,OAAOC,CAAAA,CAAiC,CACvC,IAAMC,CAAAA,CAAI,IAAI,IAAA,CAAKD,CAAO,CAAA,CAC1B,OAAO,CACN,IAAA,CAAMC,CAAAA,CAAE,WAAA,EAAY,CACpB,OAAQA,CAAAA,CAAE,QAAA,EAAS,CACnB,GAAA,CAAKA,EAAE,OAAA,EAAQ,CACf,QAASA,CAAAA,CAAE,MAAA,GACX,IAAA,CAAMA,CAAAA,CAAE,QAAA,EAAS,CACjB,OAAQA,CAAAA,CAAE,UAAA,EAAW,CACrB,MAAA,CAAQA,EAAE,UAAA,EAAW,CACrB,WAAA,CAAaA,CAAAA,CAAE,iBAChB,CACD,CAEA,aAAA,CAAcC,EAAcC,CAAAA,CAAgBC,CAAAA,CAAqB,CAChE,OAAO,IAAI,IAAA,CAAKF,CAAAA,CAAMC,CAAAA,CAAQC,CAAG,EAAE,OAAA,EACpC,CAEA,cAAA,CAAeF,EAAcC,CAAAA,CAAgBC,CAAAA,CAAaC,EAAqC,CAG9F,IAAMC,EAAW,IAAI,IAAA,CAAKJ,CAAAA,CAAMC,CAAAA,CAAQC,EAAK,CAAA,CAAG,CAAA,CAAG,CAAA,CAAG,CAAC,EACvD,OAAAE,CAAAA,CAAS,UAAA,CAAWD,CAAmB,EAChCC,CAAAA,CAAS,OAAA,EACjB,CAEA,QAAQN,CAAAA,CAAiBO,CAAAA,CAAsB,CAC9C,IAAMC,EAAO,IAAI,IAAA,CAAKR,CAAO,CAAA,CAC7B,OAAAQ,CAAAA,CAAK,OAAA,CAAQA,CAAAA,CAAK,OAAA,GAAYD,CAAI,CAAA,CAC3BC,EAA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AA,CAASE,CAAAA,CAAgBX,EAAaJ,CAAAA,CAAyB,CACtE,OAAO4B,mBAAAA,CAAsBb,CAAAA,CAAE,KAAMA,CAAAA,CAAE,MAAA,CAAQX,CAAAA,CAAKW,CAAAA,CAAE,KAAMA,CAAAA,CAAE,MAAA,CAAQ,IAAA,CAAK,SAAA,CAAW,IAAI,CAAA,CACvFA,CAAAA,CAAE,MAAA,CAAS,GAAA,CAAA,CAAUf,EAAU,GAAA,CAAQ,GAAA,EAAQ,GACnD,CACD,CAAA,CA6BO,SAASwC,CAAAA,CAAmB1B,CAAAA,CAA+B,CACjE,GAAI,CAAC2B,mBAAAA,CAAgB3B,CAAI,CAAA,CACxB,MAAM4B,oBAAa,MAAA,CAClBC,mBAAAA,CAAmB,iBAAA,CACnB,CAAA,oBAAA,EAAuB7B,CAAI,CAAA,yCAAA,CAC5B,CAAA,CAED,OAAO,IAAIU,CAAAA,CAAkBV,CAAI,CAClC","file":"chunk-A764BY7L.cjs","sourcesContent":["import { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { DatetimeErrorCodes } from \"@solve-js/errors/ErrorCode\";\nimport type { CalendarBackend, CalendarFields, ZonedFields } from \"./CalendarBackend\";\nimport { dayNumber, daysInMonth, utcMs } from \"./Gregorian\";\nimport { dateInZone, isSupportedZone, longDateInZone, timeInZone, timeOfDayInZone, zonedFields, zonedWallClockToUtcMs } from \"./IntlZone\";\n\n/**\n * The default {@link CalendarBackend}: the JavaScript `Date` object, read in\n * the host process's time zone, with `Intl.DateTimeFormat` for named zones.\n *\n * This is the calendar code the engine has always run, moved behind the\n * interface method by method rather than rewritten, so a host that configures\n * nothing sees the same instants and the same strings it did before the\n * backend existed. Where `Date` has a quirk (a two-digit year in a\n * constructor maps to the 1900s, an out-of-range instant answers `NaN`), the\n * quirk is kept here deliberately: the point of this backend is to be the\n * behaviour the `Temporal` backend is measured against, not to improve on it.\n *\n * It stays the default because it is the one calendar every supported runtime\n * has. `Temporal` ships unflagged in Node 26 and in current Chrome, Firefox\n * and Deno, but not in Safari or in the Node 22 and 24 the engine supports,\n * and the smallest polyfill adds about twenty kilobytes gzipped to a bundle\n * that a host doing plain arithmetic never needs. A host that wants\n * `Temporal` opts in through the engine's `calendar` option with the backend\n * from `solve-engine/temporal`, and pays for it only then.\n */\nexport class DateCalendar implements CalendarBackend {\n\tnow(): number {\n\t\treturn Date.now();\n\t}\n\n\tfields(epochMs: number): CalendarFields {\n\t\tconst d = new Date(epochMs);\n\t\treturn {\n\t\t\tyear: d.getFullYear(),\n\t\t\tmonth0: d.getMonth(),\n\t\t\tday: d.getDate(),\n\t\t\tweekday: d.getDay(),\n\t\t\thour: d.getHours(),\n\t\t\tminute: d.getMinutes(),\n\t\t\tsecond: d.getSeconds(),\n\t\t\tmillisecond: d.getMilliseconds(),\n\t\t};\n\t}\n\n\tlocalMidnight(year: number, month0: number, day: number): number {\n\t\treturn new Date(year, month0, day).getTime();\n\t}\n\n\tlocalWallClock(year: number, month0: number, day: number, minutesPastMidnight: number): number {\n\t\t// Anchored at midnight and then moved by the minutes FIELD, so the\n\t\t// result is the wall-clock reading asked for whatever the day's length.\n\t\tconst anchored = new Date(year, month0, day, 0, 0, 0, 0);\n\t\tanchored.setMinutes(minutesPastMidnight);\n\t\treturn anchored.getTime();\n\t}\n\n\taddDays(epochMs: number, days: number): number {\n\t\tconst date = new Date(epochMs);\n\t\tdate.setDate(date.getDate() + days);\n\t\treturn date.getTime();\n\t}\n\n\taddMonths(epochMs: number, months: number): number {\n\t\tconst date = new Date(epochMs);\n\t\tconst dayOfMonth = date.getDate();\n\t\t// Parked on the 1st before the month field moves: `setMonth()` keeps\n\t\t// the day number, so a 31st aimed at a 30-day month would overflow\n\t\t// into the month after it. Clamping afterwards is what keeps the month\n\t\t// the caller asked for.\n\t\tdate.setDate(1);\n\t\tdate.setMonth(date.getMonth() + months);\n\t\tdate.setDate(Math.min(dayOfMonth, daysInMonth(date.getFullYear(), date.getMonth())));\n\t\treturn date.getTime();\n\t}\n\n\tutcOffsetMinutes(epochMs: number): number {\n\t\t// `getTimezoneOffset()` is (UTC minus local), so its sign is inverted\n\t\t// relative to the \"+HH:MM ahead of UTC\" reading every caller wants.\n\t\t// Subtracted from zero rather than negated, so a zero offset is 0 and\n\t\t// not -0, which a second backend could not be expected to reproduce.\n\t\treturn 0 - new Date(epochMs).getTimezoneOffset();\n\t}\n\n\tparseIso8601(text: string): number {\n\t\treturn new Date(text).getTime();\n\t}\n\n\tformatLongDate(epochMs: number, locale: string): string {\n\t\treturn new Date(epochMs).toLocaleDateString(locale, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" });\n\t}\n\n\tformatTimeOfDay(epochMs: number, locale: string): string {\n\t\treturn new Date(epochMs).toLocaleTimeString(locale);\n\t}\n\n\tzoneOffsetMinutes(zone: string, epochMs: number): number {\n\t\t// The `Intl` round trip: read the instant as the zone's wall-clock\n\t\t// fields, re-read those fields as if they were UTC, and the difference\n\t\t// from the instant is the zone's offset then, daylight saving included.\n\t\tconst f = zonedFields(zone, epochMs);\n\t\t// `|| 0` folds the -0 a negative sub-minute difference rounds to.\n\t\treturn Math.round((utcMs(f.year, f.month0, f.day, f.hour, f.minute, f.second) - epochMs) / 60000) || 0;\n\t}\n\n\tfieldsInZone(zone: string, epochMs: number): ZonedFields {\n\t\treturn zonedFields(zone, epochMs);\n\t}\n\n\tformatTimeInZone(zone: string, epochMs: number): string {\n\t\treturn timeInZone(zone, epochMs);\n\t}\n\n\tformatDateInZone(zone: string, epochMs: number): string {\n\t\treturn dateInZone(zone, epochMs);\n\t}\n}\n\n/**\n * The one `Date` backend, shared by every engine that configures no other.\n *\n * Stateless, so sharing is safe: it holds no zone of its own and reads the\n * process's. It is also what the sites with no engine in hand use (the\n * normaliser rules that fuse a literal, `days in <period>`, the stocks and\n * historical-currency date phrases, and `formatValue`), which is why an\n * engine's own backend is the default here rather than a second copy.\n */\nexport const DATE_CALENDAR: CalendarBackend = new DateCalendar();\n\n/**\n * The backend a plugin function or converter should compute with: the one\n * on its execution context, or the `Date` backend when the handler was\n * called with no context (a direct call from a test, or an `as` converter\n * invoked outside the VM).\n *\n * @param context - The execution context the handler received, if any.\n * @returns The engine's backend when the context carries one, else {@link DATE_CALENDAR}.\n */\nexport function calendarOf(context?: { readonly calendar?: CalendarBackend }): CalendarBackend {\n\treturn context?.calendar ?? DATE_CALENDAR;\n}\n\n/**\n * The `Date` backend, computing in a named IANA zone instead of the host\n * process's.\n *\n * Every zone-free answer is inherited unchanged from {@link DateCalendar}:\n * `now()` is still the clock, `parseIso8601` still reads the two ECMAScript\n * spellings, and the four named-zone methods already took the zone as an\n * argument. What changes is what \"local\" means, which is exactly the set of\n * questions {@link CalendarBackend} says depends on a zone: which day an\n * instant falls on, what a wall-clock reading names, what a day or a month\n * later is, and what the offset from UTC is.\n *\n * Those are answered through `Intl`, the same data the base class already\n * reads named zones with, so the accuracy is the same and nothing new is\n * bundled. The one place it is a simplification is a wall clock that a\n * daylight-saving transition made ambiguous or non-existent (01:30 on a\n * spring-forward morning): {@link zonedWallClockToUtcMs} resolves it one way,\n * and a `Temporal` backend's `disambiguation: 'compatible'` may resolve it an\n * hour differently.\n */\n/**\n * An ISO 8601 date-time with a time of day and NO offset and no `Z`: the one\n * spelling whose instant depends on which zone reads it. Anchored at both\n * ends, so a date-only string and anything carrying an offset fall through to\n * the base class untouched.\n */\nconst ISO_LOCAL_DATE_TIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?$/;\n\nclass ZonedDateCalendar extends DateCalendar {\n\t/**\n\t * @param namedZone - An IANA zone name `Intl` accepts.\n\t */\n\tconstructor(private readonly namedZone: string) {\n\t\tsuper();\n\t}\n\n\tzone(): string {\n\t\treturn this.namedZone;\n\t}\n\n\tfields(epochMs: number): CalendarFields {\n\t\tconst f = zonedFields(this.namedZone, epochMs);\n\t\t// `zonedFields` answers no weekday and no millisecond: the weekday is a\n\t\t// pure function of the zoned date (`Gregorian.dayNumber`, counting from a\n\t\t// Thursday), and the millisecond is the instant's own, which no zone\n\t\t// offset in use is fractional enough to move.\n\t\tconst weekday = (((dayNumber(f.year, f.month0, f.day) + 4) % 7) + 7) % 7;\n\t\treturn {\n\t\t\tyear: f.year, month0: f.month0, day: f.day, weekday,\n\t\t\thour: f.hour, minute: f.minute, second: f.second,\n\t\t\tmillisecond: ((epochMs % 1000) + 1000) % 1000,\n\t\t};\n\t}\n\n\tlocalMidnight(year: number, month0: number, day: number): number {\n\t\treturn zonedWallClockToUtcMs(year, month0, day, 0, 0, this.namedZone, this);\n\t}\n\n\tlocalWallClock(year: number, month0: number, day: number, minutesPastMidnight: number): number {\n\t\t// The minutes go in as the MINUTE field, not as elapsed time, so a\n\t\t// reading of 540 is 09:00 on that date even on a 23-hour day. `Date.UTC`\n\t\t// rolls a minute field past 59 into the hour, which is what makes one\n\t\t// argument enough.\n\t\treturn zonedWallClockToUtcMs(year, month0, day, 0, minutesPastMidnight, this.namedZone, this);\n\t}\n\n\taddDays(epochMs: number, days: number): number {\n\t\tconst f = zonedFields(this.namedZone, epochMs);\n\t\treturn this.reanchor(f, f.day + days, epochMs);\n\t}\n\n\taddMonths(epochMs: number, months: number): number {\n\t\tconst f = zonedFields(this.namedZone, epochMs);\n\t\tconst target = new Date(Date.UTC(f.year, f.month0 + months, 1));\n\t\tconst clampedDay = Math.min(f.day, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()));\n\t\treturn zonedWallClockToUtcMs(\n\t\t\ttarget.getUTCFullYear(), target.getUTCMonth(), clampedDay,\n\t\t\tf.hour, f.minute, this.namedZone, this,\n\t\t) + f.second * 1000 + (((epochMs % 1000) + 1000) % 1000);\n\t}\n\n\tutcOffsetMinutes(epochMs: number): number {\n\t\treturn this.zoneOffsetMinutes(this.namedZone, epochMs);\n\t}\n\n\tparseIso8601(text: string): number {\n\t\t// The one reading in that contract that depends on a zone: a date-time\n\t\t// with no offset and no `Z` is LOCAL time, and local here is the named\n\t\t// zone. Without this the backend contradicted itself, computing\n\t\t// `2026-04-03` at New York midnight while reading `2026-04-03T09:30` as\n\t\t// half past nine in the host process's zone. It is also what the\n\t\t// `Temporal` backend already does (`TemporalCalendar.parseIso8601`\n\t\t// resolves a bare wall clock in its own zone), so the two agree.\n\t\t//\n\t\t// Everything else is the base class byte for byte: a date-only string is\n\t\t// still UTC midnight and an explicit offset is still subtracted, both\n\t\t// frozen by the interface's contract.\n\t\tconst matched = ISO_LOCAL_DATE_TIME.exec(text.trim());\n\t\tif (matched === null) return super.parseIso8601(text);\n\t\tconst [, year, month, day, hour, minute, second, fraction] = matched;\n\t\tconst millisecond = fraction === undefined ? 0 : Number(fraction.slice(0, 3).padEnd(3, \"0\"));\n\t\treturn zonedWallClockToUtcMs(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), this.namedZone, this)\n\t\t\t+ (second === undefined ? 0 : Number(second)) * 1000 + millisecond;\n\t}\n\n\tformatLongDate(epochMs: number, locale: string): string {\n\t\treturn longDateInZone(this.namedZone, epochMs, locale);\n\t}\n\n\tformatTimeOfDay(epochMs: number, locale: string): string {\n\t\treturn timeOfDayInZone(this.namedZone, epochMs, locale);\n\t}\n\n\t/** Rebuild an instant on a (possibly overflowed) day, holding its wall clock down to the millisecond. */\n\tprivate reanchor(f: ZonedFields, day: number, epochMs: number): number {\n\t\treturn zonedWallClockToUtcMs(f.year, f.month0, day, f.hour, f.minute, this.namedZone, this)\n\t\t\t+ f.second * 1000 + (((epochMs % 1000) + 1000) % 1000);\n\t}\n}\n\n/**\n * A `Date` backend that computes in a named time zone rather than the host\n * process's.\n *\n * This is how a host pins the zone the engine reads dates in, and it is the\n * only knob for it: the zone belongs to the calendar backend, which already\n * owns what \"local\" means, so there is deliberately no `date.zone` config\n * field to drift against it.\n *\n * ```ts\n * import { createEngine, dateCalendarInZone } from \"solve-engine\";\n * const engine = createEngine({ calendar: dateCalendarInZone(\"Asia/Tokyo\") });\n * ```\n *\n * It ships on the `Date` backend on purpose. `Temporal` is undefined on Node\n * 24 and in Safari, so \"pass a `Temporal` backend\" would put the zone out of\n * reach for most hosts today; `Temporal` stays an accuracy upgrade for the\n * ambiguous wall clocks around a daylight-saving transition, never a\n * prerequisite for naming a zone at all.\n *\n * @param zone - An IANA zone name, e.g. `\"Asia/Tokyo\"`.\n * @returns A backend whose local zone is that one.\n * @throws A `DATE_ZONE_UNKNOWN` config error when this runtime's `Intl` does\n * not know the zone. Refused here rather than per line, because a backend\n * that cannot compute in the zone it was asked for must not quietly answer\n * in another one.\n */\nexport function dateCalendarInZone(zone: string): CalendarBackend {\n\tif (!isSupportedZone(zone)) {\n\t\tthrow ErrorFactory.config(\n\t\t\tDatetimeErrorCodes.DATE_ZONE_UNKNOWN,\n\t\t\t`dateCalendarInZone(\"${zone}\") is not a time zone this runtime knows.`,\n\t\t);\n\t}\n\treturn new ZonedDateCalendar(zone);\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
'use strict';var chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),chunkWU7SBKVU_cjs=require('./chunk-WU7SBKVU.cjs'),chunkSUAGBRQ7_cjs=require('./chunk-SUAGBRQ7.cjs');var h=(s=>(s.Main="main",s.Inline="inline",s.String="string",s))(h||{});var n=class{constructor(e="en",t){this.currentState="main";this.hasPeeked=false;this.tokens=[];this.tokenIdx=0;this.expressionLexer=new chunkWU7SBKVU_cjs.b(e);}reset(e,t){let s=t??"main";if(this.currentState=s,this.hasPeeked=false,this.peekedToken=void 0,s==="main"){if(this.expressionLexer.classifyLine(e).skip){this.tokens=[],this.tokenIdx=0;return}this.expressionLexer.reset(e),this.tokens=this.expressionLexer.tokenizeAll(),this.tokenIdx=0;}else this.expressionLexer.reset(e),this.tokens=this.expressionLexer.tokenizeAll(),this.tokenIdx=0;}classifyLine(e){return this.expressionLexer.classifyLine(e)}findInlineSolves(e){return this.expressionLexer.findInlineSolves(e)}getKeywords(){return this.expressionLexer.getKeywords()}next(){if(this.hasPeeked)return this.hasPeeked=false,this.peekedToken;if(this.tokenIdx<this.tokens.length)return this.tokens[this.tokenIdx++]}peek(){return this.hasPeeked?this.peekedToken:(this.peekedToken=this.next(),this.hasPeeked=true,this.peekedToken)}[Symbol.iterator](){return this.tokens[Symbol.iterator]()}registerVocabulary(e){this.expressionLexer.registerVocabulary(e);}unregisterVocabulary(e){this.expressionLexer.unregisterVocabulary(e);}resetExpression(e){this.currentState="main",this.hasPeeked=false,this.peekedToken=void 0,this.expressionLexer.reset(e),this.tokens=this.expressionLexer.tokenizeAll(),this.tokenIdx=0;}scanDocument(e){return this.expressionLexer.scanDocument(e)}getState(){return this.currentState}setState(e){this.currentState=e;}getHighlightTokens(e){let t=this.expressionLexer.classifyLine(e);return t.skip&&e.startsWith("> ")?this.collectHighlightTokens(e.slice(2)):t.skip?[]:this.collectHighlightTokens(e)}getHighlightTokenObjects(e){let t=this.expressionLexer.classifyLine(e);return t.skip&&e.startsWith("> ")?this.collectTokenObjects(e.slice(2)):t.skip?[]:this.collectTokenObjects(e)}collectTokenObjects(e){this.currentState="main",this.hasPeeked=false,this.peekedToken=void 0,this.expressionLexer.reset(e);let t=[];try{this.expressionLexer.tokenizeInto(t);}catch(i){if(!(i instanceof chunkSUAGBRQ7_cjs.b))throw i}let s=[];for(let i of t)i.type==="WS"||i.type==="NEWLINE"||i.type.startsWith("MD_")||i.type==="INLINE_SOLVE_START"||i.type==="BACKTICK_CLOSE"||s.push(i);return this.tokens=s,this.tokenIdx=0,s}collectHighlightTokens(e){return this.collectTokenObjects(e).map(t=>({type:t.type,value:t.value,offset:t.offset,col:t.col,length:t.text.length,category:chunkY7O4D3BJ_cjs.d(t.type)}))}},d=new n("en",void 0);exports.a=h;exports.b=n;exports.c=d;//# sourceMappingURL=chunk-AGCNMEP2.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-AGCNMEP2.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lexer/LexerState.ts","../src/lexer/Lexer.ts"],"names":["LexerState","Lexer","localeCode","_tokenLookup","ExpressionLexer","input","state","newState","lineText","plugin","text","classification","raw","thrown","EngineError","result","token","getTokenCategory","sharedLexer"],"mappings":"uKAMO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GACXA,EAAA,IAAA,CAAO,MAAA,CACPA,EAAA,MAAA,CAAS,QAAA,CACTA,CAAAA,CAAA,MAAA,CAAS,QAAA,CAHEA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,ICcL,IAAMC,CAAAA,CAAN,KAAY,CAkBjB,WAAA,CAAYC,CAAAA,CAAa,KAAMC,CAAAA,CAA4B,CAf3D,IAAA,CAAQ,YAAA,CAA2B,MAAA,CAEnC,IAAA,CAAQ,UAAY,KAAA,CAIpB,IAAA,CAAQ,MAAA,CAAkB,EAAC,CAC3B,IAAA,CAAQ,SAAmB,CAAA,CASzB,IAAA,CAAK,eAAA,CAAkB,IAAIC,mBAAAA,CAAgBF,CAAU,EACvD,CAEA,KAAA,CAAMG,CAAAA,CAAeC,CAAAA,CAA0B,CAC7C,IAAMC,EAAWD,CAAAA,EAAS,MAAA,CAQ1B,GAPA,IAAA,CAAK,YAAA,CAAeC,CAAAA,CACpB,KAAK,SAAA,CAAY,KAAA,CACjB,KAAK,WAAA,CAAc,MAAA,CAKfA,IAAa,MAAA,CAAiB,CAEhC,GADuB,IAAA,CAAK,eAAA,CAAgB,YAAA,CAAaF,CAAK,CAAA,CAC3C,IAAA,CAAM,CACvB,IAAA,CAAK,MAAA,CAAS,GACd,IAAA,CAAK,QAAA,CAAW,CAAA,CAChB,MACF,CAEA,IAAA,CAAK,gBAAgB,KAAA,CAAMA,CAAK,CAAA,CAChC,IAAA,CAAK,MAAA,CAAS,IAAA,CAAK,gBAAgB,WAAA,EAAY,CA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K,eAAA,CAAgB,KAAA,CAAMA,CAAQ,CAAA,CACnC,IAAMI,EAAe,EAAC,CACtB,GAAI,CACF,IAAA,CAAK,eAAA,CAAgB,aAAaA,CAAG,EACvC,CAAA,MAASC,CAAAA,CAAQ,CACf,GAAI,EAAEA,CAAAA,YAAkBC,mBAAAA,CAAAA,CAAc,MAAMD,CAC9C,CACA,IAAME,EAAkB,EAAC,CACzB,IAAA,IAAWC,CAAAA,IAASJ,CAAAA,CACdI,CAAAA,CAAM,OAAS,IAAA,EAAQA,CAAAA,CAAM,IAAA,GAAS,SAAA,EACtCA,CAAAA,CAAM,IAAA,CAAK,WAAW,KAAK,CAAA,EAC3BA,CAAAA,CAAM,IAAA,GAAS,oBAAA,EAAwBA,CAAAA,CAAM,OAAS,gBAAA,EAC1DD,CAAAA,CAAO,IAAA,CAAKC,CAAK,CAAA,CAEnB,OAAA,IAAA,CAAK,OAASD,CAAAA,CACd,IAAA,CAAK,QAAA,CAAW,CAAA,CACTA,CACT,CAEQ,uBAAuBP,CAAAA,CAAqI,CAClK,OAAO,IAAA,CAAK,mBAAA,CAAoBA,CAAQ,EAAE,GAAA,CAAIQ,CAAAA,GAAU,CACtD,IAAA,CAAMA,CAAAA,CAAM,IAAA,CACZ,MAAOA,CAAAA,CAAM,KAAA,CACb,MAAA,CAAQA,CAAAA,CAAM,MAAA,CACd,GAAA,CAAKA,EAAM,GAAA,CAIX,MAAA,CAAQA,CAAAA,CAAM,IAAA,CAAK,MAAA,CACnB,QAAA,CAAUC,oBAAiBD,CAAAA,CAAM,IAAI,CACvC,CAAA,CAAE,CACJ,CACF,EAcaE,CAAAA,CAAc,IAAIjB,CAAAA,CAAM,IAAA,CAAM,MAAS","file":"chunk-TTHCH7V2.cjs","sourcesContent":["/**\n * Lexer state machine modes.\n * - Main: document-level scanning with markdown classification\n * - Inline: expression embedded in markdown inline solve (`s\\`...\\``)\n * - String: inside a double-quoted string literal\n */\nexport enum LexerState {\n\tMain = \"main\",\n\tInline = \"inline\",\n\tString = \"string\",\n}\n","import { ExpressionLexer, LineClassification, LexerVocabulary, type ScanLineResult } from \"./ExpressionLexer\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { EngineError } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { LexerState } from \"@solve-js/lexer/LexerState\";\nimport { getTokenCategory } from \"@solve-js/language/TokenCategoryMap\";\nimport type { TokenCategory } from \"@solve-js/language/TokenCategory\";\nimport type { TokenLookup } from \"@solve-js/lexer/TokenClassRegistry\";\n\n/**\n * Public tokenizer wrapper around {@link ExpressionLexer}.\n *\n * `ExpressionLexer` does the actual character-by-character scanning;\n * `Lexer` adds a materialized-token-array streaming interface\n * (`next()`/`peek()`) plus line-classification state (`reset()`) so\n * callers can iterate a line's tokens without re-scanning on each peek.\n *\n * Each `ExpressionEngine` instance owns its own `Lexer`, and packages\n * extend it via {@link registerVocabulary} (keywords, operators, units)\n * see `IEnginePackage.lexerVocabulary`.\n */\nexport class Lexer {\n /** Expression-mode lexer (Phase A: V8-optimized, replaces moo) */\n private expressionLexer: ExpressionLexer;\n private currentState: LexerState = LexerState.Main;\n private peekedToken: Token | undefined;\n private hasPeeked = false;\n\n // Materialized token array from the last reset() call, used for\n // next()/peek() streaming access.\n private tokens: Token[] = [];\n private tokenIdx: number = 0;\n\n /**\n * @param localeCode - Locale code (e.g., \"en\", \"de\"). Defaults to \"en\".\n * @param _tokenLookup - Ignored. The lexer never read the lookup it was\n * handed; the parameter stays so existing callers compile.\n * @deprecated Removed in 3.0.\n */\n constructor(localeCode = \"en\", _tokenLookup?: TokenLookup) {\n this.expressionLexer = new ExpressionLexer(localeCode);\n }\n\n reset(input: string, state?: LexerState): void {\n const newState = state ?? LexerState.Main;\n this.currentState = newState;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n\n // Phase B: Main state classifies the line with the markdown scanner.\n // Skip lines (headings, fences, HRs, etc.) produce empty token arrays.\n // Expression lines and lines with inline solves are tokenized normally.\n if (newState === LexerState.Main) {\n const classification = this.expressionLexer.classifyLine(input);\n if (classification.skip) {\n this.tokens = [];\n this.tokenIdx = 0;\n return;\n }\n // Expression line or markdown line with inline solves, tokenize.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n } else {\n // Non-main states (Inline, String), expression tokenization.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n }\n\n /**\n * Classify a single line of markdown text (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n classifyLine(lineText: string): LineClassification {\n return this.expressionLexer.classifyLine(lineText);\n }\n\n /**\n * Find all inline solve markers in a line (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n findInlineSolves(lineText: string) {\n return this.expressionLexer.findInlineSolves(lineText);\n }\n\n /**\n * Every keyword this lexer currently recognizes (locale + plugin-contributed),\n * mapped to the token type it lexes to. Delegates to the ExpressionLexer.\n */\n getKeywords(): Record<string, string> {\n return this.expressionLexer.getKeywords();\n }\n\n next(): Token | undefined {\n if (this.hasPeeked) {\n this.hasPeeked = false;\n return this.peekedToken;\n }\n // Materialized token array (ExpressionLexer path).\n if (this.tokenIdx < this.tokens.length) {\n return this.tokens[this.tokenIdx++];\n }\n return undefined;\n }\n\n peek(): Token | undefined {\n if (this.hasPeeked) return this.peekedToken;\n this.peekedToken = this.next();\n this.hasPeeked = true;\n return this.peekedToken;\n }\n\n [Symbol.iterator](): Iterator<Token> {\n return this.tokens[Symbol.iterator]();\n }\n\n /**\n * Register a plugin to extend the lexer with custom tokens.\n * Delegates to the underlying ExpressionLexer.\n *\n * @see LexerVocabulary for the supported extension points.\n */\n registerVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.registerVocabulary(plugin);\n }\n\n /**\n * Unregister a plugin, removing its custom tokens from the lexer.\n * Delegates to the underlying ExpressionLexer.\n */\n unregisterVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.unregisterVocabulary(plugin);\n }\n\n /**\n * Reset the lexer for expression-only text, skips the classifyLine()\n * overhead in reset() for callers that already know the input is an\n * evaluable expression (e.g., after isEmptyLine() confirmed non-skip).\n */\n resetExpression(input: string): void {\n this.currentState = LexerState.Main;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n\n /**\n * Scan a full document in one pass, classifying each line and\n * tokenizing non-skipped lines. Delegates to ExpressionLexer.\n *\n * @returns ScanLineResult[], one per line, with classification + tokens.\n */\n scanDocument(text: string): ScanLineResult[] {\n return this.expressionLexer.scanDocument(text);\n }\n\n getState(): LexerState {\n return this.currentState;\n }\n\n setState(state: LexerState): void {\n this.currentState = state;\n }\n\n getHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n\n // For blockquote lines, strip the \"> \" prefix and tokenize the expression content.\n // This lets expressions inside blockquotes (e.g., \"> 1 + 2\") get syntax highlighted\n // while pure structural lines (headings, code fences) remain unhighlighted.\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectHighlightTokens(lineText.slice(2));\n }\n\n if (classification.skip) {\n return [];\n }\n\n return this.collectHighlightTokens(lineText);\n }\n\n /**\n * The same tokens {@link getHighlightTokens} reduces, before reduction.\n *\n * Exists because normalization operates on tokens, not on the flattened\n * shape, and a consumer that wants phrase-fused highlighting has to run the\n * normalizer between the two. See `LanguageService.getSemanticTokens`.\n *\n * @param lineText - One line of source.\n * @returns Every token on the line that is worth painting, unreduced.\n */\n getHighlightTokenObjects(lineText: string): Token[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectTokenObjects(lineText.slice(2));\n }\n if (classification.skip) return [];\n return this.collectTokenObjects(lineText);\n }\n\n private collectTokenObjects(lineText: string): Token[] {\n // Scanned into an array this method owns rather than through\n // resetExpression(), which has nothing to hand back when the line faults\n // part way. Highlighting is painted while the line is still being typed,\n // and an unterminated string is what a line looks like between the\n // opening quote and the closing one: the tokens read before the fault are\n // the right thing to paint, and letting the throw escape blanked the line.\n this.currentState = LexerState.Main;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n this.expressionLexer.reset(lineText);\n const raw: Token[] = [];\n try {\n this.expressionLexer.tokenizeInto(raw);\n } catch (thrown) {\n if (!(thrown instanceof EngineError)) throw thrown;\n }\n const result: Token[] = [];\n for (const token of raw) {\n if (token.type === \"WS\" || token.type === \"NEWLINE\") continue;\n if (token.type.startsWith(\"MD_\")) continue;\n if (token.type === \"INLINE_SOLVE_START\" || token.type === \"BACKTICK_CLOSE\") continue;\n result.push(token);\n }\n this.tokens = result;\n this.tokenIdx = 0;\n return result;\n }\n\n private collectHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n return this.collectTokenObjects(lineText).map(token => ({\n type: token.type,\n value: token.value,\n offset: token.offset,\n col: token.col,\n // `text`, not `value`: this is a span into the source, and the two\n // differ for a string literal, whose value is the payload while its\n // text still carries the quote characters the reader typed.\n length: token.text.length,\n category: getTokenCategory(token.type),\n }));\n }\n}\n\n/**\n * A lexer for operations that do not depend on registered vocabulary.\n *\n * Line classification and inline-solve detection read characters looking for\n * headings, comment markers, fences and backtick spans, and never consult the\n * keyword, unit or operator tables. Every lexer therefore returns the same\n * answer, so the callers that have no engine to ask can use this one. Checked\n * by `__tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts`.\n *\n * Do not tokenize with this. An engine's own lexer carries the vocabulary its\n * packages registered; this one carries none.\n */\nexport const sharedLexer = new Lexer(\"en\", undefined);"]}
|
|
1
|
+
{"version":3,"sources":["../src/lexer/LexerState.ts","../src/lexer/Lexer.ts"],"names":["LexerState","Lexer","localeCode","_tokenLookup","ExpressionLexer","input","state","newState","lineText","plugin","text","classification","raw","thrown","EngineError","result","token","getTokenCategory","sharedLexer"],"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EAAC,CACzB,IAAA,IAAWC,CAAAA,IAASJ,CAAAA,CACdI,CAAAA,CAAM,OAAS,IAAA,EAAQA,CAAAA,CAAM,IAAA,GAAS,SAAA,EACtCA,CAAAA,CAAM,IAAA,CAAK,WAAW,KAAK,CAAA,EAC3BA,CAAAA,CAAM,IAAA,GAAS,oBAAA,EAAwBA,CAAAA,CAAM,OAAS,gBAAA,EAC1DD,CAAAA,CAAO,IAAA,CAAKC,CAAK,CAAA,CAEnB,OAAA,IAAA,CAAK,OAASD,CAAAA,CACd,IAAA,CAAK,QAAA,CAAW,CAAA,CACTA,CACT,CAEQ,uBAAuBP,CAAAA,CAAqI,CAClK,OAAO,IAAA,CAAK,mBAAA,CAAoBA,CAAQ,EAAE,GAAA,CAAIQ,CAAAA,GAAU,CACtD,IAAA,CAAMA,CAAAA,CAAM,IAAA,CACZ,MAAOA,CAAAA,CAAM,KAAA,CACb,MAAA,CAAQA,CAAAA,CAAM,MAAA,CACd,GAAA,CAAKA,EAAM,GAAA,CAIX,MAAA,CAAQA,CAAAA,CAAM,IAAA,CAAK,MAAA,CACnB,QAAA,CAAUC,oBAAiBD,CAAAA,CAAM,IAAI,CACvC,CAAA,CAAE,CACJ,CACF,EAcaE,CAAAA,CAAc,IAAIjB,CAAAA,CAAM,IAAA,CAAM,MAAS","file":"chunk-AGCNMEP2.cjs","sourcesContent":["/**\n * Lexer state machine modes.\n * - Main: document-level scanning with markdown classification\n * - Inline: expression embedded in markdown inline solve (`s\\`...\\``)\n * - String: inside a double-quoted string literal\n */\nexport enum LexerState {\n\tMain = \"main\",\n\tInline = \"inline\",\n\tString = \"string\",\n}\n","import { ExpressionLexer, LineClassification, LexerVocabulary, type ScanLineResult } from \"./ExpressionLexer\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { EngineError } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { LexerState } from \"@solve-js/lexer/LexerState\";\nimport { getTokenCategory } from \"@solve-js/language/TokenCategoryMap\";\nimport type { TokenCategory } from \"@solve-js/language/TokenCategory\";\nimport type { TokenLookup } from \"@solve-js/lexer/TokenClassRegistry\";\n\n/**\n * Public tokenizer wrapper around {@link ExpressionLexer}.\n *\n * `ExpressionLexer` does the actual character-by-character scanning;\n * `Lexer` adds a materialized-token-array streaming interface\n * (`next()`/`peek()`) plus line-classification state (`reset()`) so\n * callers can iterate a line's tokens without re-scanning on each peek.\n *\n * Each `ExpressionEngine` instance owns its own `Lexer`, and packages\n * extend it via {@link registerVocabulary} (keywords, operators, units)\n * see `IEnginePackage.lexerVocabulary`.\n */\nexport class Lexer {\n /** Expression-mode lexer (Phase A: V8-optimized, replaces moo) */\n private expressionLexer: ExpressionLexer;\n private currentState: LexerState = LexerState.Main;\n private peekedToken: Token | undefined;\n private hasPeeked = false;\n\n // Materialized token array from the last reset() call, used for\n // next()/peek() streaming access.\n private tokens: Token[] = [];\n private tokenIdx: number = 0;\n\n /**\n * @param localeCode - Locale code (e.g., \"en\", \"de\"). Defaults to \"en\".\n * @param _tokenLookup - Ignored. The lexer never read the lookup it was\n * handed; the parameter stays so existing callers compile.\n * @deprecated Removed in 3.0.\n */\n constructor(localeCode = \"en\", _tokenLookup?: TokenLookup) {\n this.expressionLexer = new ExpressionLexer(localeCode);\n }\n\n reset(input: string, state?: LexerState): void {\n const newState = state ?? LexerState.Main;\n this.currentState = newState;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n\n // Phase B: Main state classifies the line with the markdown scanner.\n // Skip lines (headings, fences, HRs, etc.) produce empty token arrays.\n // Expression lines and lines with inline solves are tokenized normally.\n if (newState === LexerState.Main) {\n const classification = this.expressionLexer.classifyLine(input);\n if (classification.skip) {\n this.tokens = [];\n this.tokenIdx = 0;\n return;\n }\n // Expression line or markdown line with inline solves, tokenize.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n } else {\n // Non-main states (Inline, String), expression tokenization.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n }\n\n /**\n * Classify a single line of markdown text (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n classifyLine(lineText: string): LineClassification {\n return this.expressionLexer.classifyLine(lineText);\n }\n\n /**\n * Find all inline solve markers in a line (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n findInlineSolves(lineText: string) {\n return this.expressionLexer.findInlineSolves(lineText);\n }\n\n /**\n * Every keyword this lexer currently recognizes (locale + plugin-contributed),\n * mapped to the token type it lexes to. Delegates to the ExpressionLexer.\n */\n getKeywords(): Record<string, string> {\n return this.expressionLexer.getKeywords();\n }\n\n next(): Token | undefined {\n if (this.hasPeeked) {\n this.hasPeeked = false;\n return this.peekedToken;\n }\n // Materialized token array (ExpressionLexer path).\n if (this.tokenIdx < this.tokens.length) {\n return this.tokens[this.tokenIdx++];\n }\n return undefined;\n }\n\n peek(): Token | undefined {\n if (this.hasPeeked) return this.peekedToken;\n this.peekedToken = this.next();\n this.hasPeeked = true;\n return this.peekedToken;\n }\n\n [Symbol.iterator](): Iterator<Token> {\n return this.tokens[Symbol.iterator]();\n }\n\n /**\n * Register a plugin to extend the lexer with custom tokens.\n * Delegates to the underlying ExpressionLexer.\n *\n * @see LexerVocabulary for the supported extension points.\n */\n registerVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.registerVocabulary(plugin);\n }\n\n /**\n * Unregister a plugin, removing its custom tokens from the lexer.\n * Delegates to the underlying ExpressionLexer.\n */\n unregisterVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.unregisterVocabulary(plugin);\n }\n\n /**\n * Reset the lexer for expression-only text, skips the classifyLine()\n * overhead in reset() for callers that already know the input is an\n * evaluable expression (e.g., after isEmptyLine() confirmed non-skip).\n */\n resetExpression(input: string): void {\n this.currentState = LexerState.Main;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n\n /**\n * Scan a full document in one pass, classifying each line and\n * tokenizing non-skipped lines. Delegates to ExpressionLexer.\n *\n * @returns ScanLineResult[], one per line, with classification + tokens.\n */\n scanDocument(text: string): ScanLineResult[] {\n return this.expressionLexer.scanDocument(text);\n }\n\n getState(): LexerState {\n return this.currentState;\n }\n\n setState(state: LexerState): void {\n this.currentState = state;\n }\n\n getHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n\n // For blockquote lines, strip the \"> \" prefix and tokenize the expression content.\n // This lets expressions inside blockquotes (e.g., \"> 1 + 2\") get syntax highlighted\n // while pure structural lines (headings, code fences) remain unhighlighted.\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectHighlightTokens(lineText.slice(2));\n }\n\n if (classification.skip) {\n return [];\n }\n\n return this.collectHighlightTokens(lineText);\n }\n\n /**\n * The same tokens {@link getHighlightTokens} reduces, before reduction.\n *\n * Exists because normalization operates on tokens, not on the flattened\n * shape, and a consumer that wants phrase-fused highlighting has to run the\n * normalizer between the two. See `LanguageService.getSemanticTokens`.\n *\n * @param lineText - One line of source.\n * @returns Every token on the line that is worth painting, unreduced.\n */\n getHighlightTokenObjects(lineText: string): Token[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectTokenObjects(lineText.slice(2));\n }\n if (classification.skip) return [];\n return this.collectTokenObjects(lineText);\n }\n\n private collectTokenObjects(lineText: string): Token[] {\n // Scanned into an array this method owns rather than through\n // resetExpression(), which has nothing to hand back when the line faults\n // part way. Highlighting is painted while the line is still being typed,\n // and an unterminated string is what a line looks like between the\n // opening quote and the closing one: the tokens read before the fault are\n // the right thing to paint, and letting the throw escape blanked the line.\n this.currentState = LexerState.Main;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n this.expressionLexer.reset(lineText);\n const raw: Token[] = [];\n try {\n this.expressionLexer.tokenizeInto(raw);\n } catch (thrown) {\n if (!(thrown instanceof EngineError)) throw thrown;\n }\n const result: Token[] = [];\n for (const token of raw) {\n if (token.type === \"WS\" || token.type === \"NEWLINE\") continue;\n if (token.type.startsWith(\"MD_\")) continue;\n if (token.type === \"INLINE_SOLVE_START\" || token.type === \"BACKTICK_CLOSE\") continue;\n result.push(token);\n }\n this.tokens = result;\n this.tokenIdx = 0;\n return result;\n }\n\n private collectHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n return this.collectTokenObjects(lineText).map(token => ({\n type: token.type,\n value: token.value,\n offset: token.offset,\n col: token.col,\n // `text`, not `value`: this is a span into the source, and the two\n // differ for a string literal, whose value is the payload while its\n // text still carries the quote characters the reader typed.\n length: token.text.length,\n category: getTokenCategory(token.type),\n }));\n }\n}\n\n/**\n * A lexer for operations that do not depend on registered vocabulary.\n *\n * Line classification and inline-solve detection read characters looking for\n * headings, comment markers, fences and backtick spans, and never consult the\n * keyword, unit or operator tables. Every lexer therefore returns the same\n * answer, so the callers that have no engine to ask can use this one. Checked\n * by `__tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts`.\n *\n * Do not tokenize with this. An engine's own lexer carries the vocabulary its\n * packages registered; this one carries none.\n */\nexport const sharedLexer = new Lexer(\"en\", undefined);"]}
|