solve-engine 2.31.1 → 2.33.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-CqGtaT_v.d.cts → EngineError-Bm4OYmw8.d.cts} +6 -0
- package/dist/{EngineError-CqGtaT_v.d.ts → EngineError-Bm4OYmw8.d.ts} +6 -0
- package/dist/{Lexer-CqFjYoRA.d.ts → Lexer-DPn5dfCH.d.ts} +1 -13
- package/dist/{Lexer-sCI05tqO.d.cts → Lexer-DaWkCu84.d.cts} +1 -13
- package/dist/{PackageCompatibility-phvSFP4f.d.ts → PackageCompatibility-CkzZfoJ3.d.ts} +1 -1
- package/dist/{PackageCompatibility-Bn-T_xKW.d.cts → PackageCompatibility-E_5GtcQW.d.cts} +1 -1
- package/dist/{PackageRegistry-C78jVkI9.d.ts → PackageRegistry-DSqic8kz.d.ts} +132 -23
- package/dist/{PackageRegistry-B-C1duZw.d.cts → PackageRegistry-js47hr28.d.cts} +132 -23
- package/dist/{Parselet-Dgymjxzd.d.ts → Parselet-CQjcHOKw.d.ts} +13 -6
- package/dist/{Parselet-DF3864la.d.cts → Parselet-s1sRRn8H.d.cts} +13 -6
- package/dist/{TokenNormalizer-Pe3_390t.d.cts → TokenNormalizer-D382VSYh.d.cts} +4 -1
- package/dist/{TokenNormalizer-IF7nPRMp.d.ts → TokenNormalizer-DAzPp-j1.d.ts} +4 -1
- package/dist/{VMBuiltins-BkKzhj6C.d.cts → VMBuiltins-JCavlQUj.d.cts} +53 -18
- package/dist/{VMBuiltins-Du9y8sEo.d.ts → VMBuiltins-qgzA6qGi.d.ts} +53 -18
- package/dist/{VMCheckpoints-WdUQrdc9.d.cts → VMCheckpoints-BxPzmdu0.d.cts} +2 -2
- package/dist/{VMCheckpoints-gvy_yxYh.d.ts → VMCheckpoints-DjjE92mf.d.ts} +2 -2
- package/dist/{Value-BYHw-x7q.d.cts → Value-2TIKi-YL.d.cts} +19 -0
- package/dist/{Value-BYHw-x7q.d.ts → Value-2TIKi-YL.d.ts} +19 -0
- package/dist/{WorkerError-DTrl3Jag.d.ts → WorkerError-BaN8_eok.d.ts} +1 -1
- package/dist/{WorkerError-CRoM8Ju1.d.cts → WorkerError-CexHHmbb.d.cts} +1 -1
- package/dist/{chunk-AGCNMEP2.cjs → chunk-3MG7VIPL.cjs} +2 -2
- package/dist/{chunk-AGCNMEP2.cjs.map → chunk-3MG7VIPL.cjs.map} +1 -1
- package/dist/chunk-4ASM522I.js +2 -0
- package/dist/chunk-4ASM522I.js.map +1 -0
- package/dist/chunk-4M3FZRGL.cjs +5 -0
- package/dist/chunk-4M3FZRGL.cjs.map +1 -0
- package/dist/{chunk-KH4QXKLT.js → chunk-4MD5L23F.js} +2 -2
- package/dist/{chunk-KH4QXKLT.js.map → chunk-4MD5L23F.js.map} +1 -1
- package/dist/{chunk-IQVSCL2R.js → chunk-4XWZXP6I.js} +3 -3
- package/dist/{chunk-IQVSCL2R.js.map → chunk-4XWZXP6I.js.map} +1 -1
- package/dist/{chunk-BSGZ3OEL.cjs → chunk-6DCSGINN.cjs} +3 -3
- package/dist/{chunk-BSGZ3OEL.cjs.map → chunk-6DCSGINN.cjs.map} +1 -1
- package/dist/{chunk-RELMEWY6.js → chunk-6G2NES2I.js} +2 -2
- package/dist/chunk-6G2NES2I.js.map +1 -0
- package/dist/{chunk-CDE2ZUGG.js → chunk-6NL7RBAG.js} +2 -2
- package/dist/{chunk-CDE2ZUGG.js.map → chunk-6NL7RBAG.js.map} +1 -1
- package/dist/{chunk-SUAGBRQ7.cjs → chunk-6SYU4MH7.cjs} +2 -2
- package/dist/chunk-6SYU4MH7.cjs.map +1 -0
- package/dist/chunk-72J5V7SN.cjs +2 -0
- package/dist/chunk-72J5V7SN.cjs.map +1 -0
- package/dist/chunk-7CRVRPV7.cjs +3 -0
- package/dist/chunk-7CRVRPV7.cjs.map +1 -0
- package/dist/chunk-ADK7LGYN.js +5 -0
- package/dist/chunk-ADK7LGYN.js.map +1 -0
- package/dist/chunk-APYRNAU2.js +2 -0
- package/dist/chunk-APYRNAU2.js.map +1 -0
- package/dist/{chunk-KBRSNJMQ.js → chunk-D55NMAGM.js} +3 -3
- package/dist/{chunk-KBRSNJMQ.js.map → chunk-D55NMAGM.js.map} +1 -1
- package/dist/chunk-DB5ISONG.js +2 -0
- package/dist/chunk-DB5ISONG.js.map +1 -0
- package/dist/chunk-EOKHRS2T.js +2 -0
- package/dist/chunk-EOKHRS2T.js.map +1 -0
- package/dist/{chunk-NQFCXLEF.js → chunk-EOO6M65F.js} +2 -2
- package/dist/{chunk-NQFCXLEF.js.map → chunk-EOO6M65F.js.map} +1 -1
- package/dist/{chunk-A764BY7L.cjs → chunk-EQNKDTMX.cjs} +2 -2
- package/dist/{chunk-A764BY7L.cjs.map → chunk-EQNKDTMX.cjs.map} +1 -1
- package/dist/chunk-FESR6PZI.cjs +2 -0
- package/dist/chunk-FESR6PZI.cjs.map +1 -0
- package/dist/chunk-G5TZ6TDA.js +2 -0
- package/dist/chunk-G5TZ6TDA.js.map +1 -0
- package/dist/chunk-GDLYXRMA.cjs +2 -0
- package/dist/chunk-GDLYXRMA.cjs.map +1 -0
- package/dist/chunk-HOU7QTE7.js +3 -0
- package/dist/chunk-HOU7QTE7.js.map +1 -0
- package/dist/{chunk-VYQNPCM5.cjs → chunk-HPV4CKCC.cjs} +2 -2
- package/dist/{chunk-VYQNPCM5.cjs.map → chunk-HPV4CKCC.cjs.map} +1 -1
- package/dist/{chunk-7DJYS5PO.cjs → chunk-HSTGWWU2.cjs} +2 -2
- package/dist/{chunk-7DJYS5PO.cjs.map → chunk-HSTGWWU2.cjs.map} +1 -1
- package/dist/{chunk-OE2DBN4K.js → chunk-INMJ7ZXL.js} +2 -2
- package/dist/chunk-INMJ7ZXL.js.map +1 -0
- package/dist/{chunk-TP5EQCGH.js → chunk-J3YC3IQD.js} +2 -2
- package/dist/{chunk-TP5EQCGH.js.map → chunk-J3YC3IQD.js.map} +1 -1
- package/dist/{chunk-5AKT36UK.cjs → chunk-K3PZ66XR.cjs} +2 -2
- package/dist/{chunk-5AKT36UK.cjs.map → chunk-K3PZ66XR.cjs.map} +1 -1
- package/dist/chunk-LI6LYJDA.cjs +2 -0
- package/dist/chunk-LI6LYJDA.cjs.map +1 -0
- package/dist/{chunk-WQGHJAW2.cjs → chunk-M4UC2PB6.cjs} +2 -2
- package/dist/{chunk-WQGHJAW2.cjs.map → chunk-M4UC2PB6.cjs.map} +1 -1
- package/dist/chunk-O7HF345B.js +2 -0
- package/dist/chunk-O7HF345B.js.map +1 -0
- package/dist/{chunk-CM2WM5CM.cjs → chunk-OBZJKZ2F.cjs} +2 -2
- package/dist/{chunk-CM2WM5CM.cjs.map → chunk-OBZJKZ2F.cjs.map} +1 -1
- package/dist/{chunk-Q7TBBV62.cjs → chunk-P5YWBIIU.cjs} +2 -2
- package/dist/chunk-P5YWBIIU.cjs.map +1 -0
- package/dist/chunk-PICFFFJV.js +3 -0
- package/dist/chunk-PICFFFJV.js.map +1 -0
- package/dist/{chunk-P43SV4NJ.cjs → chunk-QOOTRUY7.cjs} +3 -3
- package/dist/{chunk-P43SV4NJ.cjs.map → chunk-QOOTRUY7.cjs.map} +1 -1
- package/dist/chunk-R3W53ZMP.cjs +2 -0
- package/dist/chunk-R3W53ZMP.cjs.map +1 -0
- package/dist/chunk-RMDCGYZM.js +2 -0
- package/dist/chunk-RMDCGYZM.js.map +1 -0
- package/dist/{chunk-CB3EXUM2.js → chunk-RU3KGJRA.js} +2 -2
- package/dist/chunk-RU3KGJRA.js.map +1 -0
- package/dist/chunk-S3SPDK6N.cjs +2 -0
- package/dist/chunk-S3SPDK6N.cjs.map +1 -0
- package/dist/chunk-SF5QVUEI.cjs +3 -0
- package/dist/chunk-SF5QVUEI.cjs.map +1 -0
- package/dist/{chunk-FXB5GCBT.js → chunk-TJKN466F.js} +2 -2
- package/dist/{chunk-FXB5GCBT.js.map → chunk-TJKN466F.js.map} +1 -1
- package/dist/{chunk-VLX7ZVK4.js → chunk-U5MESNRT.js} +2 -2
- package/dist/{chunk-VLX7ZVK4.js.map → chunk-U5MESNRT.js.map} +1 -1
- package/dist/{chunk-YWF6C2IO.cjs → chunk-WFT3XUSH.cjs} +2 -2
- package/dist/{chunk-YWF6C2IO.cjs.map → chunk-WFT3XUSH.cjs.map} +1 -1
- package/dist/{chunk-3ZGFAE3Q.js → chunk-X2GQAKL2.js} +2 -2
- package/dist/{chunk-3ZGFAE3Q.js.map → chunk-X2GQAKL2.js.map} +1 -1
- package/dist/{chunk-G3POUURF.js → chunk-YID47OPR.js} +2 -2
- package/dist/{chunk-G3POUURF.js.map → chunk-YID47OPR.js.map} +1 -1
- package/dist/chunk-YV4GDW5A.cjs +2 -0
- package/dist/chunk-YV4GDW5A.cjs.map +1 -0
- package/dist/chunk-ZSXQP7PD.cjs +2 -0
- package/dist/chunk-ZSXQP7PD.cjs.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +10 -10
- package/dist/engine.d.ts +10 -10
- package/dist/engine.js +1 -1
- package/dist/engine.worker.cjs +1 -1
- package/dist/engine.worker.cjs.map +1 -1
- package/dist/engine.worker.js +1 -1
- package/dist/engine.worker.js.map +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.d.cts +1 -1
- package/dist/format.d.ts +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -10
- package/dist/index.d.ts +10 -10
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/language.d.cts +9 -9
- package/dist/language.d.ts +9 -9
- 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.d.cts +2 -2
- package/dist/normalizer.d.ts +2 -2
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +8 -8
- package/dist/packages.d.ts +8 -8
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +3 -3
- package/dist/parser.d.ts +3 -3
- package/dist/parser.js +1 -1
- package/dist/{pipeline-BYkKNpql.d.cts → pipeline-Bum6y1B9.d.cts} +1 -1
- package/dist/{pipeline-Cl7KW8CB.d.ts → pipeline-DOo3KHaq.d.ts} +1 -1
- package/dist/resolvers.cjs +1 -1
- package/dist/resolvers.d.cts +69 -3
- package/dist/resolvers.d.ts +69 -3
- package/dist/resolvers.js +1 -1
- package/dist/temporal.cjs +1 -1
- package/dist/temporal.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +9 -9
- package/dist/testing.d.ts +9 -9
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +35 -2
- package/dist/uom.d.ts +35 -2
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +6 -6
- package/dist/vm.d.ts +6 -6
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +9 -9
- package/dist/worker.d.ts +9 -9
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-4DR5RBHQ.cjs +0 -2
- package/dist/chunk-4DR5RBHQ.cjs.map +0 -1
- package/dist/chunk-6LA7HC46.js +0 -3
- package/dist/chunk-6LA7HC46.js.map +0 -1
- package/dist/chunk-A755LVPT.cjs +0 -2
- package/dist/chunk-A755LVPT.cjs.map +0 -1
- package/dist/chunk-AF6NDOIE.js +0 -2
- package/dist/chunk-AF6NDOIE.js.map +0 -1
- package/dist/chunk-B2NL65FI.js +0 -2
- package/dist/chunk-B2NL65FI.js.map +0 -1
- package/dist/chunk-CB3EXUM2.js.map +0 -1
- package/dist/chunk-DUFEONVN.cjs +0 -3
- package/dist/chunk-DUFEONVN.cjs.map +0 -1
- package/dist/chunk-IJHL3LMH.js +0 -2
- package/dist/chunk-IJHL3LMH.js.map +0 -1
- package/dist/chunk-LCYQQFUH.cjs +0 -2
- package/dist/chunk-LCYQQFUH.cjs.map +0 -1
- package/dist/chunk-LP3JYC3A.js +0 -2
- package/dist/chunk-LP3JYC3A.js.map +0 -1
- package/dist/chunk-MDTIL3UT.cjs +0 -5
- package/dist/chunk-MDTIL3UT.cjs.map +0 -1
- package/dist/chunk-MZQ3ED6J.cjs +0 -3
- package/dist/chunk-MZQ3ED6J.cjs.map +0 -1
- package/dist/chunk-OE2DBN4K.js.map +0 -1
- package/dist/chunk-OM7NOHJF.cjs +0 -2
- package/dist/chunk-OM7NOHJF.cjs.map +0 -1
- package/dist/chunk-PTXUWGRR.js +0 -3
- package/dist/chunk-PTXUWGRR.js.map +0 -1
- package/dist/chunk-Q7TBBV62.cjs.map +0 -1
- package/dist/chunk-RELMEWY6.js.map +0 -1
- package/dist/chunk-SFM4XFGJ.js +0 -2
- package/dist/chunk-SFM4XFGJ.js.map +0 -1
- package/dist/chunk-SNYFNARL.js +0 -5
- package/dist/chunk-SNYFNARL.js.map +0 -1
- package/dist/chunk-SUAGBRQ7.cjs.map +0 -1
- package/dist/chunk-UNKZ5XRC.cjs +0 -2
- package/dist/chunk-UNKZ5XRC.cjs.map +0 -1
- package/dist/chunk-WU7SBKVU.cjs +0 -2
- package/dist/chunk-WU7SBKVU.cjs.map +0 -1
- package/dist/chunk-X5K72MBV.js +0 -2
- package/dist/chunk-X5K72MBV.js.map +0 -1
- package/dist/chunk-ZVPZQ66D.cjs +0 -2
- package/dist/chunk-ZVPZQ66D.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors/EngineError.ts","../src/errors/Result.ts","../src/errors/ErrorCode.ts"],"names":["ErrorCategory","_EngineError","category","init","recoverable","skipStack","errorCtor","previousLimit","chain","current","lines","EngineError","ErrorFactory","_ErrorFactory","defaultRecoverable","codeOrInit","message","context","normalizeUnknownError","error","ok","value","err","isOk","r","isErr","map","fn","mapErr","andThen","unwrapOr","fallback","match","arms","combine","results","values","throwIfErr","tryCatch","normalize","e","tryCatchAsync","CoreErrorCodes","DatetimeErrorCodes"],"mappings":"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","file":"chunk-RELMEWY6.js","sourcesContent":["/**\n * The engine's structured error type, the \"Rust/Go-style, verbose, easy to\n * tell the issue\" half of the error-handling redesign (the other half is\n * `Result.ts`).\n *\n * Historical note: an earlier version of this class (`UnifiedErrorFramework.ts`,\n * still the import path most of the codebase uses. See that file, now a\n * pure re-export barrel) had a much larger field set (`severity`,\n * `recovery`, a 5-value enum, `ErrorRecoveryManager`) that was almost\n * entirely dead: nothing downstream ever read `.severity`/`.recovery`,\n * only `.message` reliably survived to a caller. This version is smaller\n * and deliberately keeps only fields something actually consumes.\n */\n\nimport type { ErrorCode } from \"@solve-js/errors/ErrorCode\";\n\n/** A character-offset (and optional line/col) span into the original expression text, for a future \"underline the offending token\" UI, not yet wired to one. */\nexport interface SourceSpan {\n start: number;\n end: number;\n line?: number;\n col?: number;\n}\n\n/**\n * Error classification, kept from the original framework, now actually\n * consulted: it's the `format()` header and lets host code group errors\n * by pipeline stage without string-matching `.code`.\n */\nexport enum ErrorCategory {\n /** Errors during expression parsing. */\n PARSING = \"PARSING\",\n /** Errors during bytecode execution. */\n EXECUTION = \"EXECUTION\",\n /** Errors from input validation (safety limits, config). */\n VALIDATION = \"VALIDATION\",\n /** Errors from external services/APIs (currency rates, weather, stocks). */\n EXTERNAL = \"EXTERNAL\",\n /** Internal engine invariant violations. See `recoverable`'s doc comment. */\n INTERNAL = \"INTERNAL\",\n /** Configuration errors. */\n CONFIG = \"CONFIG\",\n}\n\n/** Fields accepted when constructing an {@link EngineError}. */\nexport interface EngineErrorInit {\n /** Catalog code. See `errors/ErrorCode.ts`. Not a free string: every code used by a BUILT-IN package should be registered there so `ErrorCodeCatalog.spec.ts` can catch collisions/typos. Third-party packages may still use any string here, `EngineError.code`'s runtime type is `string`. */\n code: ErrorCode | (string & {});\n /** Short, single-line, `Error.message`-compatible. Existing `.toThrow(/pattern/)`/`.message` assertions keep working against this field, richer detail goes in `expected`/`found`/`suggestion`, not crammed into this string. */\n message: string;\n /** What the parser/validator/VM expected to see, in plain words, e.g. \"a city name\", \"a 4-digit year\", \"end of expression\". */\n expected?: string;\n /** What was actually found instead, e.g. \"end of expression\", `NUMBER \"5\"`, the offending token's literal text. */\n found?: string;\n /** An actionable, worked-example fix, e.g. `e.g. \"weather in London\"`. Mirrors this codebase's best existing messages (`WEATHER_EXPECTED_CITY`, `AS_CONVERTER_EXPECTED_NAME`). */\n suggestion?: string;\n /**\n * Whether this engine instance is still usable. `true` for everything that\n * went wrong on ONE line, whether the line's fault (bad syntax, an unknown\n * variable, a safety limit exceeded), the environment's (an external API\n * down), or the engine's own (corrupted bytecode, a stack underflow from a\n * buggy plugin). `false` is for the far rarer case where there is no working\n * engine to go on with: a configuration or package-registration failure,\n * which is what `ErrorFactory.config()` is for and the only factory method\n * that still defaults to it.\n *\n * The category answers a different question, and the two used to be answered\n * as one. Category INTERNAL says whose fault this is, the engine's, worth\n * reporting as a bug. `recoverable` says whether the host may carry on, and\n * after an internal slip on one line it may:\n * `__tests__/hardening/RobustnessEngineLifecycle.spec.ts` alternates a\n * throwing line with a good one five hundred times and every answer stays\n * correct. Reporting that as `isFatal()` told a host the opposite, and a host\n * that honours the name would tear a document down over one bad line.\n *\n * This has never gated \"does evaluation of the rest of the document\n * continue\"; with this engine's per-line containment it always does, even for\n * a `recoverable: false` error (see `ARCHITECTURE.md`'s async-batcher/Tier-2\n * hardening notes). It gates what a host is TOLD. See\n * {@link EngineError.isFatal}.\n */\n recoverable?: boolean;\n /** Character-offset span into the source expression, when available. Not yet threaded through every call site, populate opportunistically, don't block on retrofitting every existing throw site. */\n span?: SourceSpan;\n /** Free-form structured context. The one field the pre-existing framework's real consumer (`ThreeTierEvaluator.ts`'s DAG-preservation-on-compile-error path) actually reads, kept name- and shape-compatible on purpose. */\n context?: Record<string, unknown>;\n /** The underlying error this one wraps, if any, passed straight through to native `Error.cause` (ES2022), so Node's default printer, most loggers, and `instanceof Error` tooling understand the chain for free. */\n cause?: unknown;\n}\n\n/**\n * The engine's structured error type. Still a real `Error` subclass (so\n * `throw`/`catch`/`instanceof Error` all keep working exactly as before),\n * but now every field except the removed `severity`/`recovery` pair is\n * something real code reads.\n */\nexport class EngineError extends Error {\n readonly category: ErrorCategory;\n readonly code: string;\n readonly expected?: string;\n readonly found?: string;\n readonly suggestion?: string;\n readonly recoverable: boolean;\n readonly span?: SourceSpan;\n readonly context?: Record<string, unknown>;\n readonly timestamp: Date;\n /**\n * Set explicitly (not via `super(message, {cause})`). This repo's\n * `tsconfig.json` targets ES6/ES5-ES7 lib, which predates TypeScript's\n * ES2022 `Error` constructor `cause`-option overload. `Error.prototype.cause`\n * is still a real runtime feature in every target this engine actually\n * runs in (Node 16.9+, all evergreen browsers, Electron/Obsidian's\n * bundled Chromium) regardless of the TS lib target used to type-check\n * against it, assigning it directly gets the same Node-printer/logger\n * interop with no build-config change needed.\n */\n readonly cause?: unknown;\n\n /**\n * Whether a recoverable error captures a JavaScript stack trace.\n *\n * Off, because a recoverable EngineError is a value rather than a fault. A\n * line of prose in a notepad is not an expression, so parsing it fails, and\n * that failure is the answer for that line rather than a bug to debug. The\n * engine builds one such error per non-expression line.\n *\n * Capturing a stack is not cheap, and its cost grows with how deep the stack\n * is when it happens. Measured through `parseDocument`, where the throw site\n * sits about a dozen frames down, each capture cost around 62 microseconds\n * and a 250-line document built 74 of them: a CPU profile put the\n * constructor at 46% of the whole pipeline, more than lexing, normalising,\n * parsing and executing put together.\n *\n * Turn it on to debug where a recoverable error is raised from. Errors that\n * are NOT recoverable always capture, since those are the genuine faults.\n *\n * @example\n * ```ts\n * EngineError.captureRecoverableStacks = true;\n * ```\n */\n static captureRecoverableStacks = false;\n\n constructor(category: ErrorCategory, init: EngineErrorInit) {\n // Before super(), which is legal as long as `this` is untouched. V8 reads\n // `Error.stackTraceLimit` while constructing the Error, so zeroing it\n // across the super() call is what actually skips the capture; there is no\n // per-instance switch for it.\n const recoverable = init.recoverable ?? true;\n const skipStack = recoverable && !EngineError.captureRecoverableStacks;\n // `stackTraceLimit` is a V8 extension, present in Node and every\n // Chromium-based browser but absent from the DOM lib, so it is reached\n // through a narrow local view rather than by widening the global type.\n // Where it does not exist, reading and writing it are both harmless and\n // the stack is captured as before.\n const errorCtor = Error as unknown as { stackTraceLimit?: number };\n const previousLimit = errorCtor.stackTraceLimit;\n if (skipStack) errorCtor.stackTraceLimit = 0;\n super(init.message);\n if (skipStack) errorCtor.stackTraceLimit = previousLimit;\n\n this.name = \"EngineError\";\n this.category = category;\n this.code = init.code;\n this.expected = init.expected;\n this.found = init.found;\n this.suggestion = init.suggestion;\n this.recoverable = recoverable;\n this.span = init.span;\n this.context = init.context;\n this.cause = init.cause;\n this.timestamp = new Date();\n // Only for the faults. super() has already captured a stack for those, and\n // this second call recaptures it purely to drop this constructor's own\n // frame; doing that for every error meant paying the whole cost twice.\n if (!skipStack && Error.captureStackTrace) {\n Error.captureStackTrace(this, EngineError);\n }\n }\n\n /** `!recoverable`. See `EngineErrorInit.recoverable`'s doc comment for what this actually gates (message framing/telemetry, not whether evaluation continues). */\n isFatal(): boolean {\n return !this.recoverable;\n }\n\n /** Walk `.cause` repeatedly, collecting the full chain (this error first). */\n causeChain(): unknown[] {\n const chain: unknown[] = [this];\n let current: unknown = this.cause;\n while (current !== undefined && current !== null) {\n chain.push(current);\n current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined;\n }\n return chain;\n }\n\n /**\n * Rust/Go-style multi-line renderer, the NEW thing a host/CLI/test\n * reaches for when it wants the full, verbose picture, as distinct from\n * `.message` (kept short and stable for existing assertions). Example:\n *\n * ```\n * error[WEATHER_EXPECTED_CITY]: Expected a city name after \"weather in\"\n * expected: a city name\n * found: end of expression\n * suggestion: e.g. \"weather in London\"\n * ```\n */\n format(): string {\n const lines = [`error[${this.code}]: ${this.message}`];\n if (this.expected) lines.push(` expected: ${this.expected}`);\n if (this.found) lines.push(` found: ${this.found}`);\n if (this.suggestion) lines.push(` suggestion: ${this.suggestion}`);\n return lines.join(\"\\n\");\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n category: this.category,\n code: this.code,\n message: this.message,\n expected: this.expected,\n found: this.found,\n suggestion: this.suggestion,\n recoverable: this.recoverable,\n span: this.span,\n context: this.context,\n timestamp: this.timestamp.toISOString(),\n };\n }\n}\n\n/**\n * Factory for creating classified `EngineError`s. Every method accepts\n * EITHER the original, minimal 3-arg shape (`code, message, context?`\n * every existing call site across the codebase keeps compiling unchanged)\n * OR the richer `EngineErrorInit` object (for `expected`/`found`/\n * `suggestion`/`recoverable`/`span`/`cause`), upgrade a call site to the\n * richer form only when you're already touching it, no separate churn\n * pass required.\n */\nexport class ErrorFactory {\n private static build(\n category: ErrorCategory,\n defaultRecoverable: boolean,\n codeOrInit: string | EngineErrorInit,\n message?: string,\n context?: Record<string, unknown>,\n ): EngineError {\n const init: EngineErrorInit =\n typeof codeOrInit === \"string\"\n ? { code: codeOrInit, message: message!, context }\n : codeOrInit;\n return new EngineError(category, { recoverable: defaultRecoverable, ...init });\n }\n\n static validation(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static validation(init: EngineErrorInit): EngineError;\n static validation(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.VALIDATION, true, codeOrInit, message, context);\n }\n\n static parsing(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static parsing(init: EngineErrorInit): EngineError;\n static parsing(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.PARSING, true, codeOrInit, message, context);\n }\n\n static execution(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static execution(init: EngineErrorInit): EngineError;\n static execution(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXECUTION, true, codeOrInit, message, context);\n }\n\n static external(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static external(init: EngineErrorInit): EngineError;\n static external(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXTERNAL, true, codeOrInit, message, context);\n }\n\n /**\n * Reserve for genuine engine-internal invariant violations (corrupted\n * bytecode, a stack underflow from a buggy plugin, an \"impossible\" state),\n * not for user-input errors: the category is a bug report.\n *\n * Defaults `recoverable: true` all the same, because every one of these sites\n * is an invariant that failed on ONE line and none of them leaves the engine\n * unusable. This used to default to `false`, which conflated \"the engine's\n * fault\" with \"the engine is finished\" and told a host to tear a document\n * down over a line it could simply have shown an error against. A site that\n * has looked at its own case and concluded the instance really is gone can\n * still pass `recoverable: false` explicitly. See {@link\n * EngineErrorInit.recoverable}.\n */\n static internal(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static internal(init: EngineErrorInit): EngineError;\n static internal(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.INTERNAL, true, codeOrInit, message, context);\n }\n\n /** Defaults `recoverable: false`, and is now the only method that does: a configuration or package-registration failure is the one class that leaves no working engine to carry on with, rather than one bad line in a document. */\n static config(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static config(init: EngineErrorInit): EngineError;\n static config(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.CONFIG, false, codeOrInit, message, context);\n }\n}\n\n/**\n * Normalize any thrown value into an `EngineError`, an `EngineError`\n * passes through as-is; a plain `Error` gets wrapped (message preserved,\n * original attached via `cause`); anything else becomes a generic\n * \"unknown error\" wrapping the stringified value. Used at every\n * throw-space/Result-space boundary (`Result.tryCatch`'s default\n * `normalize`, the VM's outer execution try/catch, `AsyncResolutionBatcher`'s\n * per-line containment) so a raw `TypeError` from a genuine engine bug\n * still surfaces as a structured, catalogued error instead of an opaque\n * uncaught exception.\n *\n * Both branches state RECOVERABLE explicitly, while keeping the INTERNAL\n * category. The two fields answer different questions and were previously\n * answering the same one:\n *\n * category INTERNAL whose fault is this? The engine's. Worth reporting.\n * recoverable is this engine instance still usable? Yes.\n *\n * Everything reaching here is by definition something the engine did not\n * anticipate on ONE line, and per-line containment means the next line\n * evaluates normally, which `__tests__/hardening/RobustnessEngineLifecycle`\n * demonstrates over hundreds of alternating failure/success pairs. Reporting\n * that as `isFatal()` told a host the opposite, and a host that honours the\n * name would tear a document down over a single bad line. The \"this is an\n * engine bug rather than your syntax\" signal a caller wants for telemetry is\n * the CATEGORY, which is unchanged.\n *\n * The flag is written out here rather than inherited from\n * `ErrorFactory.internal()`, which now defaults the same way, so that this\n * function's contract survives a future change to that default.\n */\nexport function normalizeUnknownError(error: unknown): EngineError {\n if (error instanceof EngineError) return error;\n if (error instanceof Error) {\n return ErrorFactory.internal({\n code: \"UNEXPECTED_ERROR\",\n message: error.message,\n context: { originalErrorName: error.name },\n cause: error,\n recoverable: true,\n });\n }\n return ErrorFactory.internal({\n code: \"UNKNOWN_ERROR\",\n message: \"An unknown error occurred\",\n context: { error: String(error) },\n recoverable: true,\n });\n}\n","import { type EngineError, normalizeUnknownError } from \"@solve-js/errors/EngineError\";\n\n/**\n * A Rust-style `Result<T, E>`, the value half of this engine's error-handling\n * redesign. `E` defaults to `EngineError` (this engine's structured error\n * type) but every combinator here is generic over `E`, so `Result` works\n * equally well for a domain that isn't `EngineError`-shaped.\n *\n * This exact shape used to live in `errors/UnifiedErrorFramework.ts` (kept\n * there as a barrel re-export for backward compatibility), moved here as\n * its own module because it's genuinely generic (no dependency on\n * `EngineError` beyond the default type parameter) and because the engine\n * is migrating callers to it incrementally: parsing/VM/package code that\n * expects \"a failure is a possibility, not an exception\" returns\n * `Result<T, EngineError>` instead of throwing; two explicit adapters\n * {@link throwIfErr} and {@link tryCatch}, are the sanctioned way to cross\n * the boundary between Result-based code and still-throw-based code during\n * the migration (and permanently, at the public API boundary. See\n * `ExpressionEngine.evaluateExpression()`'s documented throw contract).\n */\nexport type Result<T, E = EngineError> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\n/** Wrap a successful value. */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/** Wrap a failure. */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n/**\n * Narrow a {@link Result} to its success arm.\n *\n * @param r - The result to test.\n * @returns True when it succeeded, narrowing `r` so `r.value` is reachable.\n */\nexport function isOk<T, E>(r: Result<T, E>): r is { ok: true; value: T } {\n return r.ok;\n}\n\n/**\n * Narrow a {@link Result} to its failure arm.\n *\n * @param r - The result to test.\n * @returns True when it failed, narrowing `r` so `r.error` is reachable.\n */\nexport function isErr<T, E>(r: Result<T, E>): r is { ok: false; error: E } {\n return !r.ok;\n}\n\n/** Transform the success value; a failure passes through untouched. */\nexport function map<T, U, E>(r: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return r.ok ? ok(fn(r.value)) : r;\n}\n\n/** Transform the error; a success passes through untouched. */\nexport function mapErr<T, E, F>(r: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return r.ok ? r : err(fn(r.error));\n}\n\n/** Chain a Result-returning operation onto a success (a.k.a. flatMap/bind). */\nexport function andThen<T, U, E>(r: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {\n return r.ok ? fn(r.value) : r;\n}\n\n/** Unwrap a success, or return `fallback` for a failure. Never throws. */\nexport function unwrapOr<T, E>(r: Result<T, E>, fallback: T): T {\n return r.ok ? r.value : fallback;\n}\n\n/** Exhaustive pattern-match, the `match`/`switch` a Rust enum gets for free. */\nexport function match<T, E, R>(r: Result<T, E>, arms: { ok: (value: T) => R; err: (error: E) => R }): R {\n return r.ok ? arms.ok(r.value) : arms.err(r.error);\n}\n\n/**\n * Combine several Results into one, succeeds with a tuple of all values\n * iff every input succeeded; otherwise fails with the FIRST error\n * encountered (left-to-right), matching this codebase's existing\n * fail-fast convention elsewhere (e.g. `BytecodeBuilder`'s constant-pool\n * limit checks).\n */\nexport function combine<T extends readonly unknown[], E>(\n results: { [K in keyof T]: Result<T[K], E> },\n): Result<T, E> {\n const values: unknown[] = [];\n for (const r of results as readonly Result<unknown, E>[]) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values as unknown as T);\n}\n\n/**\n * Cross from Result-space back to throw-space, the sanctioned boundary\n * adapter for callers (public API surface, older not-yet-migrated code,\n * tests) that still want exception-based control flow. Throws `r.error`\n * as-is (an `EngineError` is already a real `Error` subclass, so this\n * needs no wrapping).\n */\nexport function throwIfErr<T, E>(r: Result<T, E>): T {\n if (r.ok) return r.value;\n throw r.error;\n}\n\n/**\n * Cross from throw-space into Result-space, runs `fn`, converting any\n * thrown value into a Result via `normalize` (defaults to\n * {@link normalizeUnknownError}). The inverse of {@link throwIfErr}; the\n * pairing that lets Result-based and throw-based code interoperate during\n * an incremental migration instead of requiring a single flag-day rewrite.\n */\nexport function tryCatch<T>(\n fn: () => T,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Result<T, EngineError> {\n try {\n return ok(fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n\n/** Async sibling of {@link tryCatch}. */\nexport async function tryCatchAsync<T>(\n fn: () => Promise<T>,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Promise<Result<T, EngineError>> {\n try {\n return ok(await fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n","/**\n * The built-in error-code catalog, one typed const object per domain\n * unioned together here for autocomplete/exhaustiveness in core engine\n * code. Deliberately NOT one central enum: `IEnginePackage` is documented\n * public SDK surface for third-party packages (see `api/PackageRegistry.ts`),\n * and a closed enum would block an external package author from defining\n * their own codes without editing this file. `EngineError.code`'s runtime\n * type stays `string` for exactly that reason. This catalog is for the\n * codes THIS repo owns and wants collision/typo checking on (see\n * `__tests__/errors/ErrorCodeCatalog.spec.ts`), not a hard runtime\n * whitelist.\n *\n * As each package migrates to `Result<void, EngineError>` (see this\n * session's error-handling-refactor plan, Phase 5), it should export its\n * own small `XxxErrorCodes` const object co-located with its parselets\n * exactly like `CoreErrorCodes` below, just scoped to one domain, and get\n * unioned into `ErrorCode` here. Until a package migrates, its existing\n * free-string codes keep working (ErrorFactory accepts any string); they\n * just aren't caught by the catalog's uniqueness/orphan checks yet.\n */\n\n/**\n * Codes used directly by the parser/VM/engine/errors layers themselves\n * confirmed against the current source, not aspirational. Grouped by\n * pipeline stage via the comments, not a naming prefix (these predate any\n * naming convention and renaming them is out of scope for introducing the\n * catalog, only NEW codes need to follow a scoped/prefixed style, see\n * `STACK_UNDERFLOW` etc. below).\n */\nexport const CoreErrorCodes = {\n // ── Parser (parser/PrecedenceParser.ts, parser/BytecodeBuilder.ts, parser/PhrasePattern.ts) ──\n INVALID_NUMBER_LITERAL: \"INVALID_NUMBER_LITERAL\",\n /** A `\"` that never meets its closing partner (`lexer/ExpressionLexer.ts`'s `tokenizeString()`). Previously the tokenizer ran off the end of the input and returned what it had, so `\"abc` lexed to an ordinary String and an unterminated literal was indistinguishable from a terminated one. */\n UNTERMINATED_STRING: \"UNTERMINATED_STRING\",\n NO_PREFIX_PARSELET: \"NO_PREFIX_PARSELET\",\n UNEXPECTED_END_OF_INPUT: \"UNEXPECTED_END_OF_INPUT\",\n UNEXPECTED_TOKEN_TYPE: \"UNEXPECTED_TOKEN_TYPE\",\n NESTING_DEPTH_EXCEEDED: \"NESTING_DEPTH_EXCEEDED\",\n UNEXPECTED_END: \"UNEXPECTED_END\",\n UNEXPECTED_TRAILING_TOKEN: \"UNEXPECTED_TRAILING_TOKEN\",\n PARSE_ERROR: \"PARSE_ERROR\",\n TOO_MANY_NUMERIC_CONSTANTS: \"TOO_MANY_NUMERIC_CONSTANTS\",\n /** A raw bytecode operand outside 0 to 255, or a jump patch outside the emitted stream (`parser/BytecodeBuilder.ts`'s `emitIndex`, `emitByte`, `patchJump`). `build()` keeps one byte per operand, so 300 used to become 44 with no error and the program read the wrong constant or plugin function. A package-authoring fault, reported at compile time. */\n BYTECODE_OPERAND_OUT_OF_RANGE: \"BYTECODE_OPERAND_OUT_OF_RANGE\",\n TOO_MANY_STRING_CONSTANTS: \"TOO_MANY_STRING_CONSTANTS\",\n NO_MATCHING_PHRASE_ALTERNATIVE: \"NO_MATCHING_PHRASE_ALTERNATIVE\",\n INVALID_PHRASE_PATTERN: \"INVALID_PHRASE_PATTERN\",\n PHRASE_KEYWORD_MISMATCH: \"PHRASE_KEYWORD_MISMATCH\",\n /** User-defined-function definition parsing (`f(x, y) = ...`), an invalid token where a parameter name was expected. */\n USER_FUNCTION_INVALID_PARAM_NAME: \"USER_FUNCTION_INVALID_PARAM_NAME\",\n /** `f() = ...` with zero parameters, indistinguishable from a plain no-arg function call, so rejected at definition time. */\n USER_FUNCTION_NO_PARAMS: \"USER_FUNCTION_NO_PARAMS\",\n /** A user-defined function body calling an async plugin (weather/stocks/currency/...), rejected at definition time; v1 scope excludes async function bodies. */\n FUNCTION_BODY_MUST_BE_SYNCHRONOUS: \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n /** `BytecodeBuilder`'s `userFunctionBodies` side-table exceeding its capacity. Same class as `TOO_MANY_NUMERIC_CONSTANTS`/`TOO_MANY_STRING_CONSTANTS` below. */\n TOO_MANY_FUNCTION_DEFINITIONS: \"TOO_MANY_FUNCTION_DEFINITIONS\",\n /** `BytecodeBuilder`'s `anonymousBodies` side-table (map/reduce inline transform bodies) exceeding its capacity. Same class as `TOO_MANY_FUNCTION_DEFINITIONS` above. */\n TOO_MANY_ANONYMOUS_BODIES: \"TOO_MANY_ANONYMOUS_BODIES\",\n /** New with the 2.0 descriptor redesign: a parselet emits a plugin call by NAME (`BytecodeBuilder.emitPluginCall(name, argCount)`) and the engine resolves that name to the index it assigned at registration. This fires when the name is absent from the builder's name->index map: the package used a `pluginFunctions` name it never declared, or the expression was parsed before that package registered. Not a user-input error; a package-authoring/registration fault. See `parser/BytecodeBuilder.ts`'s `emitPluginCall()`. */\n UNKNOWN_PLUGIN_FUNCTION: \"UNKNOWN_PLUGIN_FUNCTION\",\n\n // ── VM (vm/VM.ts, vm/OpRegistry.ts, vm/VMBuiltins.ts) ──\n EVALUATION_ERROR: \"EVALUATION_ERROR\",\n INSTRUCTION_LIMIT_EXCEEDED: \"INSTRUCTION_LIMIT_EXCEEDED\",\n STACK_LIMIT_EXCEEDED: \"STACK_LIMIT_EXCEEDED\",\n /** One evaluation asking for more elements (collection Values, matrix cells) than `vm.maxAllocatedElements` allows. The counter the two limits above cannot be: both are checked between opcodes, so neither can see what a single opcode allocates inside a loop of its own. See `vm/AllocationBudget.ts`. Recoverable, since it describes this expression rather than the engine. */\n ALLOCATION_LIMIT_EXCEEDED: \"ALLOCATION_LIMIT_EXCEEDED\",\n /** New this phase. See `VM.ts`'s `safePop()`: a stack-underflow (corrupted bytecode, a buggy plugin) is now a controlled EngineError instead of a raw TypeError. Category INTERNAL, since it is an engine or plugin fault rather than a typed line, but recoverable: it happened on one line and the engine is still usable. */\n STACK_UNDERFLOW: \"STACK_UNDERFLOW\",\n UNDEFINED_VARIABLE: \"UNDEFINED_VARIABLE\",\n /** New this phase, the Tier-2/`LOAD_GLOBAL_VAR` hardening: a global variable read before its async preflight resolved, surfaced as a controlled error instead of pushing `undefined`. */\n GLOBAL_VARIABLE_NOT_RESOLVED: \"GLOBAL_VARIABLE_NOT_RESOLVED\",\n UNKNOWN_FUNCTION: \"UNKNOWN_FUNCTION\",\n /** `unwrapEvalResult()`'s pending-when-expecting-value case, a caller-contract violation, not user-input. */\n UNEXPECTED_PENDING_RESULT: \"UNEXPECTED_PENDING_RESULT\",\n /** User-defined-function call/definition errors (`CALL_USER_FUNCTION`/`DEFINE_USER_FUNCTION` opcodes), calling a name with no matching definition, calling with the wrong argument count, and the deliberate v1 restriction that a function body can't itself contain async work. */\n UNDEFINED_FUNCTION: \"UNDEFINED_FUNCTION\",\n FUNCTION_ARITY_MISMATCH: \"FUNCTION_ARITY_MISMATCH\",\n /** The same mistake against a BUILT-IN rather than a user-defined function (`sqrt()`, `atan2(1)`, `sqrt(1,2,3)`). Separate from `FUNCTION_ARITY_MISMATCH` above because the two are raised by different opcodes and a host may want to word them differently. Checked at the `CALL_BUILTIN` dispatch against `vm/VMBuiltinArity.ts`; recoverable, since it is a typo in the line, not an engine fault. */\n BUILTIN_ARITY_MISMATCH: \"BUILTIN_ARITY_MISMATCH\",\n USER_FUNCTION_ASYNC_UNSUPPORTED: \"USER_FUNCTION_ASYNC_UNSUPPORTED\",\n /** A map/reduce transform body (inline expression or user-defined function) calling an async plugin. Same v1 scope restriction as `USER_FUNCTION_ASYNC_UNSUPPORTED` above, enforced both at parse time (`MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS`, packages/mapreduce/) and as a defense-in-depth runtime backstop here. */\n MAP_REDUCE_ASYNC_UNSUPPORTED: \"MAP_REDUCE_ASYNC_UNSUPPORTED\",\n /** An algebra verb's expression argument (`BIND_UNKNOWN`'s body) calling an async plugin. Same v1 scope restriction as the two above, and likewise refused at parse time first (`SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS`, packages/symbolic/). */\n SYMBOLIC_ASYNC_UNSUPPORTED: \"SYMBOLIC_ASYNC_UNSUPPORTED\",\n /** `explainLine()` asked to derive a line that resolves data asynchronously (a live-data or async-plugin line). A derivation is a sequence of settled intermediate values, which a pending result has none of, so the line is refused rather than explained with a hole in it. */\n EXPLAIN_ASYNC_UNSUPPORTED: \"EXPLAIN_ASYNC_UNSUPPORTED\",\n /** `pushCallFrame()`'s recursion guard, a nested `CALL_USER_FUNCTION` re-enters `executeBytecode()`, so `maxInstructions` alone can't catch e.g. `f(x) = f(x)`; this is the dedicated backstop. `recoverable: true` (the default for `.execution()`), ordinary user-written infinite recursion, not an engine bug; the guard exists precisely so it surfaces as a clear error instead of overflowing the native call stack uncatchably. */\n FUNCTION_RECURSION_LIMIT_EXCEEDED: \"FUNCTION_RECURSION_LIMIT_EXCEEDED\",\n /** The companion to the code above, and the half it could never see: how MANY user-defined-function calls one evaluation makes, rather than how deeply they nest. A twenty-two-line doubling chain nests twenty-two deep (legal) and makes two million calls (a fatal heap abort). Counted in `vm/AllocationBudget.ts`, because the tally has to survive `executeBytecode()` re-entering itself. Recoverable. */\n FUNCTION_CALL_LIMIT_EXCEEDED: \"FUNCTION_CALL_LIMIT_EXCEEDED\",\n /** A `<date> + N workdays` offset outside `date.maxOffsetYears`/`minOffsetYears`. Workdays are the one date offset that walks the calendar a day at a time, so the one whose cost is the offset; every other one moves a Date field once. Recoverable. */\n DATE_OFFSET_LIMIT_EXCEEDED: \"DATE_OFFSET_LIMIT_EXCEEDED\",\n /** The anchor of `N working days after/before/from <expr>` was not a date (e.g. `5 working days after 3`). The grammar guarantees the count is a number, so this only fires on the anchor. Emitted as a recoverable Error value, not thrown, matching the datetime package's other type guards. See `vm/VM.ts`'s `DATE_WORKDAY_OFFSET` case. */\n WORKDAY_OFFSET_EXPECTED_DATE: \"WORKDAY_OFFSET_EXPECTED_DATE\",\n /** An endpoint of `working days between <expr> and <expr>` was not a date. Recoverable Error value. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_EXPECTED_DATES: \"WORKDAYS_BETWEEN_EXPECTED_DATES\",\n /** The two endpoints of `working days between <expr> and <expr>` are further apart than `date.maxOffsetYears`/`minOffsetYears` allow the count's calendar walk to run. Recoverable Error value, the between-count's equivalent of `DATE_OFFSET_LIMIT_EXCEEDED`. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_RANGE_TOO_LARGE: \"WORKDAYS_BETWEEN_RANGE_TOO_LARGE\",\n /** A `<<`/`>>` with a bigint operand whose exact result would pass `MAX_EXACT_SHIFT_BITS`, whichever operand is the bigint. Both spellings refuse as of 1.0.0: a bigint on the left used to fall through to `x * 2^n` in doubles and report a 19,870-digit integer as Infinity. See `vm/VM.ts`'s `bigIntShift()`. Recoverable. */\n BIGINT_SHIFT_LIMIT_EXCEEDED: \"BIGINT_SHIFT_LIMIT_EXCEEDED\",\n /** The same ceiling for `^`, the operator it was written for: `2n ^ 100000` asks for the same 100,001-bit integer `1n << 100000` does, so the two spellings answer the same way. Also new in 1.0.0, and for the same reason: this used to fall through to the double path and answer Infinity. A fractional or negative exponent (`4n ^ 0.5`, `2n ^ -1`) has no exact answer to bound and still uses the double path. See `vm/VM.ts`'s `MAX_EXACT_POW_BITS`. Recoverable. */\n BIGINT_POW_LIMIT_EXCEEDED: \"BIGINT_POW_LIMIT_EXCEEDED\",\n /** An operand with no whole-number form (a fraction, an infinity, a NaN) meeting a bigint: `1n + 0.5`, `1n & 1.5`, `5n/pi`. `BigInt()` answers those with a raw RangeError, which the VM relabelled UNEXPECTED_ERROR, so a typo in the line was reported as an engine fault. Recoverable; see `vm/VMConversion.ts`'s `toBigIntOperand()`. */\n BIGINT_INEXACT_OPERAND: \"BIGINT_INEXACT_OPERAND\",\n /** `10n / 0n` and `10n mod 0n`. Deliberately NOT what `1 / 0` does, which is Infinity: a bigint division is exact integer division (`7n / 2n` is 3n), and integer division by zero has no answer, exactly as it has none in C, Java, Python or JavaScript's own BigInt. Previously V8's own RangeError, relabelled UNEXPECTED_ERROR. Recoverable; see `vm/VMConversion.ts`'s `bigIntDivisionByZero()`. */\n BIGINT_DIVISION_BY_ZERO: \"BIGINT_DIVISION_BY_ZERO\",\n /** `DEFINE_USER_FUNCTION`'s body-index lookup failing, a compiler/VM invariant violation (the opcode stream referenced a `userFunctionBodies` slot that doesn't exist), never a user-input error. */\n INTERNAL_MISSING_FUNCTION_BODY: \"INTERNAL_MISSING_FUNCTION_BODY\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE`'s anonymous-body-index lookup failing. Same class as `INTERNAL_MISSING_FUNCTION_BODY` above, for the `anonymousBodies` side-table instead of `userFunctionBodies`. */\n INTERNAL_MISSING_ANONYMOUS_BODY: \"INTERNAL_MISSING_ANONYMOUS_BODY\",\n /** `CALL_BUILTIN` naming an index no builtin is registered at. It used to pop its arguments and push nothing, so the opcode after it read a neighbour's operand as its own; now an Error value on the stack, the shape `map`/`reduce` already used for the same fault. Bytecode-level, so unreachable from source without a compiler or snapshot fault. */\n UNKNOWN_BUILTIN_FUNCTION: \"UNKNOWN_BUILTIN_FUNCTION\",\n\n // ── Malformed bytecode on the public `./vm` surface (vm/VM.ts) ──\n //\n // `executeBytecode` is exported, so a bytecode program is caller input in\n // the same sense an expression string is, and these five say so. They are\n // VALIDATION rather than INTERNAL for exactly that reason: before they\n // existed, every one of these cases reached a raw TypeError (`BigInt(undefined)`,\n // `code.toUpperCase()` on a boolean, destructuring a program that was not\n // there), which normalised to UNEXPECTED_ERROR and told the caller the\n // engine was broken when their eleven bytes were. Reachable from ordinary\n // source only through a compiler bug, which is why the messages name the\n // opcode and the operand rather than the user's line.\n /** An operand byte read past the end of the stream: the program ends in the middle of an instruction. */\n MALFORMED_BYTECODE_TRUNCATED: \"MALFORMED_BYTECODE_TRUNCATED\",\n /** A constant-pool operand indexing a `numbers`/`strings` entry that does not exist, or that is not of the pool's type. */\n MALFORMED_BYTECODE_CONSTANT_INDEX: \"MALFORMED_BYTECODE_CONSTANT_INDEX\",\n /** A unit or converter name read off the value stack that is not a string. Distinct from the pool case above: the operand is a Value another opcode pushed, not a pool entry. */\n MALFORMED_BYTECODE_OPERAND_TYPE: \"MALFORMED_BYTECODE_OPERAND_TYPE\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE` carrying a body kind other than 0/1/2. Used to fall through every arm with no body and recurse into `executeBytecode(undefined)`. */\n MALFORMED_BYTECODE_BODY_KIND: \"MALFORMED_BYTECODE_BODY_KIND\",\n /** A `PUSH_BIGINT` pool entry that is not a whole number, e.g. `\"1.000\"`. `BigInt()` answers that with a raw SyntaxError. */\n MALFORMED_BYTECODE_BIGINT_LITERAL: \"MALFORMED_BYTECODE_BIGINT_LITERAL\",\n /** `executeBytecode()` called with something that is not a runnable program at all. Checked before the destructure that used to throw outside the function's own try/catch. */\n MALFORMED_BYTECODE_PROGRAM: \"MALFORMED_BYTECODE_PROGRAM\",\n\n // ── Symbolic algebra (symbolic/, vm/SymbolicOps.ts) ──\n /** A coefficient grew past `RATIONAL_MAX_BITS`, e.g. repeated exact elimination multiplying denominators together. */\n SYMBOLIC_RATIONAL_OVERFLOW: \"SYMBOLIC_RATIONAL_OVERFLOW\",\n /** `NaN` or `±Infinity` reaching a symbolic expression, neither of which has an exact rational value. */\n SYMBOLIC_NONFINITE_OPERAND: \"SYMBOLIC_NONFINITE_OPERAND\",\n /** Division by an exactly-zero rational. Exact, unlike the double comparison it replaced, which could not distinguish a true zero from `5.551e-17`. */\n SYMBOLIC_DIVISION_BY_ZERO: \"SYMBOLIC_DIVISION_BY_ZERO\",\n /** A tree exceeding `SYMBOLIC_MAX_NODES` entering the simplifier. */\n SYMBOLIC_NODE_LIMIT_EXCEEDED: \"SYMBOLIC_NODE_LIMIT_EXCEEDED\",\n /** A builtin with no symbolic reading (`min`, `random`, the finance block, ...) applied to an expression still containing an unknown. Returned rather than computing against `toNumber()`'s placeholder zero. */\n SYMBOLIC_UNSUPPORTED_FUNCTION: \"SYMBOLIC_UNSUPPORTED_FUNCTION\",\n /** The rational-root search exceeding `FACTOR_MAX_ROOT_CANDIDATES`. The candidate set is the product of two divisor sets, so a highly-composite coefficient escapes quickly. */\n SYMBOLIC_FACTOR_LIMIT_EXCEEDED: \"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n /** An equation outside what the solver attempts: not a polynomial, above the degree ceiling, or non-linear in the unknown while another unknown is present. */\n SYMBOLIC_SOLVE_UNSUPPORTED: \"SYMBOLIC_SOLVE_UNSUPPORTED\",\n /** Some but not all of an equation's roots were found. Reported rather than returned, because a partial list of roots looks exactly like a complete one. */\n SYMBOLIC_SOLVE_INCOMPLETE: \"SYMBOLIC_SOLVE_INCOMPLETE\",\n /** `solve`'s second argument not being a bare name. */\n SOLVE_REQUIRES_VARIABLE_NAME: \"SOLVE_REQUIRES_VARIABLE_NAME\",\n /** A derivative order outside 0..`DERIVATIVE_MAX_ORDER`. */\n SYMBOLIC_DERIVATIVE_ORDER_LIMIT: \"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\",\n /** An expression with no known elementary antiderivative. Reported rather than approximated, since a wrong integral is indistinguishable from a right one at the point of use. */\n SYMBOLIC_INTEGRAL_UNSUPPORTED: \"SYMBOLIC_INTEGRAL_UNSUPPORTED\",\n /** A Taylor degree outside 0..`TAYLOR_MAX_DEGREE`. */\n SYMBOLIC_TAYLOR_DEGREE_LIMIT: \"SYMBOLIC_TAYLOR_DEGREE_LIMIT\",\n /** A Taylor coefficient that does not reduce to an exact number at the expansion point. */\n SYMBOLIC_TAYLOR_INEXACT: \"SYMBOLIC_TAYLOR_INEXACT\",\n /** An algebra verb's variable-name argument not being a bare name. */\n SYMBOLIC_REQUIRES_VARIABLE_NAME: \"SYMBOLIC_REQUIRES_VARIABLE_NAME\",\n /** `jacobian` called with expressions containing no unknown to differentiate against. */\n SYMBOLIC_JACOBIAN_NO_VARIABLES: \"SYMBOLIC_JACOBIAN_NO_VARIABLES\",\n /** A finite number whose decimal form could not be read back, which the regex covering every `Number.prototype.toString` output should make unreachable. */\n INTERNAL_RATIONAL_PARSE: \"INTERNAL_RATIONAL_PARSE\",\n\n // ── Engine (engine/ExpressionEngine.ts, engine/ExpressionEngineSafety.ts, engine/AsyncResolutionBatcher.ts) ──\n EXPRESSION_TOO_LONG: \"EXPRESSION_TOO_LONG\",\n EXPRESSION_TOO_COMPLEX: \"EXPRESSION_TOO_COMPLEX\",\n /** A document with more lines than `performance.maxDocumentLines`. The per-line limits above bound what one line may ask for and say nothing about how many lines there are; two hundred thousand of `1 + 1` exhausted the heap on the line records alone. Recoverable. */\n DOCUMENT_TOO_LARGE: \"DOCUMENT_TOO_LARGE\",\n NORMALIZED_TOKEN_LIMIT_EXCEEDED: \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n /** `\"=>\"` with nothing before it, needs an expression or variable name to solve/simplify. */\n THEREFORE_REQUIRES_EXPRESSION: \"THEREFORE_REQUIRES_EXPRESSION\",\n /** A `\"=>\"`-triggered expression called an async plugin (weather/stocks/currency). Same v1 scope restriction as user-function/map-reduce bodies. */\n THEREFORE_ASYNC_UNSUPPORTED: \"THEREFORE_ASYNC_UNSUPPORTED\",\n /** A compound assignment (`name += expr` / `name -= expr`) with nothing on the right, a line half-typed on the way to `total += 5`. */\n COMPOUND_ASSIGN_REQUIRES_EXPRESSION: \"COMPOUND_ASSIGN_REQUIRES_EXPRESSION\",\n /** A running total (`+= / -=`) whose right-hand side calls an async plugin (weather/stocks/currency). The same v1 scope restriction as the `\"=>\"` and user-function bodies. */\n COMPOUND_ASSIGN_ASYNC_UNSUPPORTED: \"COMPOUND_ASSIGN_ASYNC_UNSUPPORTED\",\n /** A savings-goal contribution period that is not one of daily/weekly/monthly/yearly (`how long to save $X at $Y <period>`). Names the accepted set. */\n UNKNOWN_SAVINGS_PERIOD: \"UNKNOWN_SAVINGS_PERIOD\",\n /** Colon-separated numbers that are not a time any clock can show (\"24:00\", \"9:60\", \"100:5\"). Raised by the labeled-line fallback, which used to answer them with whatever stood after the colon. */\n INVALID_TIME_LITERAL: \"INVALID_TIME_LITERAL\",\n /** A live-data form evaluated on an engine whose host switched the network off (`network.enabled: false`, see `constants/Configuration.ts`'s `NetworkConfig`). A recoverable Error value, raised by the VM for a currency conversion with no primed rate and for a plugin function that returned a promise, and by `createQueryResolver`'s plugin function when its preflight was skipped. Names the setting, so the reader knows it is policy rather than an outage. */\n NETWORK_DISABLED: \"NETWORK_DISABLED\",\n\n // ── Temporal calendar backend (temporal/TemporalCalendar.ts) ──\n /** `createTemporalCalendar()` was handed something that is not a usable `Temporal` implementation: no `Now.instant`, `Now.timeZoneId`, `Instant.fromEpochMilliseconds` or `PlainDateTime.from`. Raised at construction, naming the missing member, rather than letting the first date computation fail on it obscurely. */\n TEMPORAL_IMPLEMENTATION_INVALID: \"TEMPORAL_IMPLEMENTATION_INVALID\",\n /** The `timeZone` given to `createTemporalCalendar()` is not one the `Temporal` implementation knows. Raised at construction, so a misspelt zone is a configuration error the host sees once, not a `RangeError` from inside every date the engine computes. */\n TEMPORAL_TIME_ZONE_UNKNOWN: \"TEMPORAL_TIME_ZONE_UNKNOWN\",\n\n // ── Snapshot / restore (engine/EngineSnapshot.ts, engine/ExpressionEngine.ts) ──\n /** `fromJSON()` handed an object that is not a snapshot at all, or whose serialised-shape version does not match this engine's reader. The versioning gate that refuses an incompatible snapshot clearly rather than restoring it wrongly. See `engine/EngineSnapshot.ts`'s `assertRestorable()`. */\n SNAPSHOT_VERSION_MISMATCH: \"SNAPSHOT_VERSION_MISMATCH\",\n /** A snapshot with the right envelope but internally inconsistent contents (an unrecognised number sentinel, an unknown value tag). Distinct from a version mismatch: the format is right, the payload is not. */\n SNAPSHOT_MALFORMED: \"SNAPSHOT_MALFORMED\",\n /** A value the v1 snapshot format cannot yet represent (a symbolic/algebra value, a symbolic matrix cell). Deferred to a follow-up; refused by name rather than dropped silently. */\n SNAPSHOT_UNSUPPORTED_VALUE: \"SNAPSHOT_UNSUPPORTED_VALUE\",\n\n // ── Config (constants/Configuration.ts) ──\n CONFIG_PATH_NOT_FOUND: \"CONFIG_PATH_NOT_FOUND\",\n INVALID_CONFIG_PATH: \"INVALID_CONFIG_PATH\",\n CONFIG_SECTION_NOT_FOUND: \"CONFIG_SECTION_NOT_FOUND\",\n CONFIG_PROPERTY_NOT_FOUND: \"CONFIG_PROPERTY_NOT_FOUND\",\n\n // ── Package/lexer registration-time collisions (lexer/ExpressionLexer.ts) ──\n /** `calendar: \"temporal\"` was asked for on a runtime with no `Temporal`. Refused rather than silently computing on `Date`, because a host that named Temporal did so to be sure what it was computing on. Recoverable. */\n CALENDAR_TEMPORAL_UNAVAILABLE: \"CALENDAR_TEMPORAL_UNAVAILABLE\",\n /** A trip form (`cost to drive ...`) was written without the `at` that separates its parts. Recoverable. */\n TRIP_EXPECTED_AT: \"TRIP_EXPECTED_AT\",\n /** A width and a height were written with nothing asked of the pair (`1920x1080` on its own). Recoverable. */\n DIMENSIONS_EXPECTED_FORM: \"DIMENSIONS_EXPECTED_FORM\",\n /** A `resize` was written without one of its parts: the dimensions, the `to`, the size, or the side it names. Recoverable. */\n RESIZE_EXPECTED_SHAPE: \"RESIZE_EXPECTED_SHAPE\",\n PLUGIN_OPERATOR_COLLISION: \"PLUGIN_OPERATOR_COLLISION\",\n PLUGIN_KEYWORD_COLLISION: \"PLUGIN_KEYWORD_COLLISION\",\n PLUGIN_UNIT_COLLISION: \"PLUGIN_UNIT_COLLISION\",\n /** A package's declared `IEnginePackage.engineVersion` semver range doesn't satisfy the running engine's ENGINE_VERSION. See api/EngineVersionCompatibility.ts. */\n PACKAGE_ENGINE_VERSION_MISMATCH: \"PACKAGE_ENGINE_VERSION_MISMATCH\",\n /** A package's declared `IEnginePackage.engineVersion` isn't a parseable semver range at all (a typo in the package's own descriptor). */\n PACKAGE_ENGINE_VERSION_INVALID_RANGE: \"PACKAGE_ENGINE_VERSION_INVALID_RANGE\",\n /** `OpRegistry.allocateOpcode()`'s dynamic opcode pool (started at 201) exhausted, too many packages calling it. */\n OPCODE_POOL_EXHAUSTED: \"OPCODE_POOL_EXHAUSTED\",\n /** `VMBuiltins.allocatePluginFunctionIndex()`'s index pool (up to 65536, two opcode-stream bytes) exhausted. */\n PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED: \"PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED\",\n /** A plugin-function index exceeds the two-byte (65535) `CALL_PLUGIN_WIDE` bytecode operand. */\n PLUGIN_FUNCTION_INDEX_TOO_LARGE: \"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\n // ── vm/Value.ts caller-contract violations (check isRateUnit()/isTimecodeUnit() first) ──\n INVALID_RATE_UNIT: \"INVALID_RATE_UNIT\",\n INVALID_TIMECODE_UNIT: \"INVALID_TIMECODE_UNIT\",\n\n // ── errors/EngineError.ts's own fallback normalization ──\n UNEXPECTED_ERROR: \"UNEXPECTED_ERROR\",\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\",\n} as const;\n\n/** Every error code the engine's own layers can produce, from {@link CoreErrorCodes}. */\nexport type CoreErrorCode = (typeof CoreErrorCodes)[keyof typeof CoreErrorCodes];\n\n/**\n * Codes for the datetime forms whose failure is raised OUTSIDE the datetime\n * package.\n *\n * These sit here rather than beside the datetime parselets, which is where a\n * package's own code object belongs, because the two sites that raise them are\n * `vm/VM.ts` (the `in <zone>` branch of the unit-conversion opcode) and\n * `calendar/DateCalendar.ts` (the zone-bound backend factory), and neither may\n * import from `packages/`. A code object in the datetime package would put the\n * name a core file needs on the wrong side of that line.\n */\nexport const DatetimeErrorCodes = {\n /** `2026-04-03 in Atlantis`: a Datetime met `in <name>` and the name is neither a zone this engine knows nor a unit. Before this code the epoch-millisecond payload was simply labelled with the name, and the line answered a fourteen-digit quantity in a unit called Atlantis. */\n DATETIME_ZONE_UNKNOWN: \"DATETIME_ZONE_UNKNOWN\",\n /** `2026-04-03 in furlongs`: the same handler, where the name IS a real unit. Separate from `DATETIME_ZONE_UNKNOWN` because the two mistakes have different fixes: one is a misspelt zone, the other is a category error, and a message that suggests checking the spelling of `furlongs` would be no help at all. */\n DATETIME_NOT_CONVERTIBLE: \"DATETIME_NOT_CONVERTIBLE\",\n /** `dateCalendarInZone(\"Europe/Atlantis\")`: the zone-bound `Date` backend factory, given a zone this runtime's `Intl` cannot format with. Raised at construction rather than per line, because a backend that cannot compute in the zone it was asked for must not silently answer in another one. */\n DATE_ZONE_UNKNOWN: \"DATE_ZONE_UNKNOWN\",\n} as const;\n\n/** Every code from {@link DatetimeErrorCodes}. */\nexport type DatetimeErrorCode = (typeof DatetimeErrorCodes)[keyof typeof DatetimeErrorCodes];\n\n/**\n * The aggregated catalog type. Currently `CoreErrorCode` and\n * `DatetimeErrorCode`, union in each package's own code-object type here as\n * Phase 5 converts it, e.g. `CoreErrorCode | WeatherErrorCode | ...`.\n */\nexport type ErrorCode = CoreErrorCode | DatetimeErrorCode;\n"]}
|
package/dist/chunk-SFM4XFGJ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {b}from'./chunk-PTXUWGRR.js';import {n}from'./chunk-X5K72MBV.js';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??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$1=_[p],s=_[i];if(this.exchange.isCurrency(n$1)&&this.exchange.isCurrency(s)&&n$1.toUpperCase()!==s.toUpperCase()&&this.exchange.getRateSync(n$1,s)===null){let I=n$1.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$1,s,h).then(T=>n(T)),staleTime:300*1e3});return {queryKey:a.join(":"),resolver:g,packageId:U,signal:S,metadata:{fromUnit:n$1,toUnit:s}}}}o=m(c,o);}return null}destroy(){}};export{m as a,A as b};//# sourceMappingURL=chunk-SFM4XFGJ.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-SFM4XFGJ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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":"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","file":"chunk-SFM4XFGJ.js","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"]}
|
package/dist/chunk-SNYFNARL.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import {b as b$3,a as a$5}from'./chunk-CB3EXUM2.js';import {a as a$3}from'./chunk-IJHL3LMH.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {d as d$1,a as a$2,b,c as c$5}from'./chunk-AF6NDOIE.js';import {a as a$4,b as b$4,c as c$8}from'./chunk-JP4JMQOG.js';import {c as c$a,a as a$a}from'./chunk-IQVSCL2R.js';import {h as h$1,t,p,o,n as n$1,l,i,m,k,b as b$9,q,s as s$1,g,r as r$1,j as j$1}from'./chunk-FXB5GCBT.js';import {d as d$2}from'./chunk-VLX7ZVK4.js';import {c as c$3,d as d$3,b as b$8}from'./chunk-B2NL65FI.js';import {b as b$7}from'./chunk-76F3LCIL.js';import {c as c$6,a as a$7,b as b$b}from'./chunk-TCZSPH4A.js';import {K as K$1,x,F as F$1,H,I,i as i$1}from'./chunk-OE2DBN4K.js';import {_,da}from'./chunk-KH4QXKLT.js';import {b as b$5}from'./chunk-NQFCXLEF.js';import {P,n,O,t as t$1,l as l$1,L,u,N,M,s,r,m as m$1,g as g$1}from'./chunk-X5K72MBV.js';import {a as a$1,c as c$2,b as b$1}from'./chunk-TP5EQCGH.js';import {c as c$1,b as b$2}from'./chunk-CDE2ZUGG.js';import {b as b$6,c as c$7}from'./chunk-JPFCXLJV.js';import {c as c$4,a as a$8}from'./chunk-LP3JYC3A.js';import {a,c as c$9}from'./chunk-FAO6DQ74.js';import {a as a$9}from'./chunk-LHLW7JLS.js';import {c,d,b as b$a}from'./chunk-RELMEWY6.js';function jt(r,e,t,n,i){let s=t[e],o=n[e];if(!s||!o)return;let c=new Set(Object.keys(s));for(let l of Object.keys(o))c.has(l)&&i.push({kind:r,severity:"warning",detail:`Both "${t.name}" and "${n.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${l}" \u2014 the later-registered one silently wins.`,packages:[t.name,n.name]});}function Wt(r,e){let t=[];if(jt("prefixParseletTokenType","prefixParselets",r,e,t),jt("infixParseletTokenType","infixParselets",r,e,t),r.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let c=r.phrases[s];c!==void 0&&c!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") fuse the phrase "${s}" to DIFFERENT token types \u2014 PhraseTrie has no collision detection of its own, so the later-registered mapping silently wins with no other signal.`,packages:[r.name,e.name]});}if(r.asConverters&&e.asConverters)for(let s of Object.keys(e.asConverters)){let o=s.toLowerCase();Object.keys(r.asConverters).some(c=>c.toLowerCase()===o)&&t.push({kind:"converterName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register an "as ${s}" converter \u2014 the later-registered handler silently wins.`,packages:[r.name,e.name]});}if(r.pluginFunctions&&e.pluginFunctions){let s=new Set(Object.keys(r.pluginFunctions));for(let o of Object.keys(e.pluginFunctions))s.has(o)&&t.push({kind:"pluginFunctionName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register a plugin function named "${o}" \u2014 the later registration wins in the engine's name-to-index map. Give each package's functions package-unique names.`,packages:[r.name,e.name]});}if(r.normalizerRules&&e.normalizerRules){let s=new Set(r.normalizerRules.map(o=>o.name));for(let o of e.normalizerRules)s.has(o.name)&&t.push({kind:"normalizerRuleName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register a normalizer rule named "${o.name}" \u2014 the normalizer unregisters rules by name, so removing either package would drop both rules. Give each package's rules a package-unique name.`,packages:[r.name,e.name]});}let n=r.lexerVocabulary,i=e.lexerVocabulary;if(n?.keywords&&i?.keywords)for(let[s,o]of Object.entries(i.keywords)){let c=n.keywords[s];c!==void 0&&c!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer keyword "${s}" for DIFFERENT token types \u2014 whichever package registers second wins, and the loser's grammar becomes silently unreachable for that word.`,packages:[r.name,e.name]});}if(n?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let c=n.operators[s];c!==void 0&&c!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer operator "${s}" for DIFFERENT token types.`,packages:[r.name,e.name]});}if(r.asyncResolvers&&e.asyncResolvers){let s=new Set(r.asyncResolvers.map(o=>o.namespace));for(let o of e.asyncResolvers)s.has(o.namespace)&&t.push({kind:"asyncResolverNamespace",severity:"error",detail:`Both "${r.name}" and "${e.name}" register an async resolver under the namespace "${o.namespace}" \u2014 ResolverRegistry is keyed by namespace, so one resolver's cache/preflight state will silently clobber the other's.`,packages:[r.name,e.name]});}if(r.tokenCategories&&e.tokenCategories)for(let[s,o]of Object.entries(e.tokenCategories)){let c=r.tokenCategories[s];c!==void 0&&c!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") declare a highlight category for token type "${s}" \u2014 cosmetic only, but the later registration wins.`,packages:[r.name,e.name]});}return t}function Jr(r,e){let t=[];for(let n of e)n===r||n.name===r.name||t.push(...Wt(n,r));return {compatible:!t.some(n=>n.severity==="error"),conflicts:t}}var ve=class{constructor(){this.prefixOwners=new Map;this.infixOwners=new Map;this.phraseOwners=new Map;this.converterOwners=new Map;this.pluginFnOwners=new Map;this.ruleOwners=new Map;this.keywordOwners=new Map;this.operatorOwners=new Map;this.resolverOwners=new Map;this.categoryOwners=new Map;}check(e){let t=new Set,n=(s,o)=>{let c=s.get(o);c&&c!==e&&c.name!==e.name&&t.add(c);};if(e.prefixParselets)for(let s of Object.keys(e.prefixParselets))n(this.prefixOwners,s);if(e.infixParselets)for(let s of Object.keys(e.infixParselets))n(this.infixOwners,s);if(e.phrases)for(let s of Object.keys(e.phrases))n(this.phraseOwners,s);if(e.asConverters)for(let s of Object.keys(e.asConverters))n(this.converterOwners,s.toLowerCase());if(e.pluginFunctions)for(let s of Object.keys(e.pluginFunctions))n(this.pluginFnOwners,s);if(e.normalizerRules)for(let s of e.normalizerRules)n(this.ruleOwners,s.name);if(e.lexerVocabulary?.keywords)for(let s of Object.keys(e.lexerVocabulary.keywords))n(this.keywordOwners,s);if(e.lexerVocabulary?.operators)for(let s of Object.keys(e.lexerVocabulary.operators))n(this.operatorOwners,s);if(e.asyncResolvers)for(let s of e.asyncResolvers)n(this.resolverOwners,s.namespace);if(e.tokenCategories)for(let s of Object.keys(e.tokenCategories))n(this.categoryOwners,s);let i=[];for(let s of t)i.push(...Wt(s,e));return i}add(e){let t=(n,i)=>{n.has(i)||n.set(i,e);};if(e.prefixParselets)for(let n of Object.keys(e.prefixParselets))t(this.prefixOwners,n);if(e.infixParselets)for(let n of Object.keys(e.infixParselets))t(this.infixOwners,n);if(e.phrases)for(let n of Object.keys(e.phrases))t(this.phraseOwners,n);if(e.asConverters)for(let n of Object.keys(e.asConverters))t(this.converterOwners,n.toLowerCase());if(e.pluginFunctions)for(let n of Object.keys(e.pluginFunctions))t(this.pluginFnOwners,n);if(e.normalizerRules)for(let n of e.normalizerRules)t(this.ruleOwners,n.name);if(e.lexerVocabulary?.keywords)for(let n of Object.keys(e.lexerVocabulary.keywords))t(this.keywordOwners,n);if(e.lexerVocabulary?.operators)for(let n of Object.keys(e.lexerVocabulary.operators))t(this.operatorOwners,n);if(e.asyncResolvers)for(let n of e.asyncResolvers)t(this.resolverOwners,n.namespace);if(e.tokenCategories)for(let n of Object.keys(e.tokenCategories))t(this.categoryOwners,n);}rebuild(e){for(let t of [this.prefixOwners,this.infixOwners,this.phraseOwners,this.converterOwners,this.pluginFnOwners,this.ruleOwners,this.keywordOwners,this.operatorOwners,this.resolverOwners,this.categoryOwners])t.clear();for(let t of e)this.add(t);}};var Cr=/(\d+)\.(\d+)\.(\d+)/,Tr=/^\d+$/;function Ht(r){let e=Cr.exec(r.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Nr(r,e){return r[0]-e[0]||r[1]-e[1]||r[2]-e[2]}function De(r){let e=r.split(".");if(e.length===0||e.length>3)return null;let t=[0,0,0];for(let n=0;n<e.length;n++){if(!Tr.test(e[n]))return null;t[n]=Number(e[n]);}return [t[0],t[1],t[2]]}function wr([r,e,t]){let n=r>0?[r+1,0,0]:e>0?[0,e+1,0]:[0,0,t+1];return [{op:">=",v:[r,e,t]},{op:"<",v:n}]}function Rr([r,e,t]){return [{op:">=",v:[r,e,t]},{op:"<",v:[r,e+1,0]}]}function Ar(r){if(r===""||r==="*"||r==="x"||r==="X")return [];if(r[0]==="^"){let i=De(r.slice(1));return i&&wr(i)}if(r[0]==="~"){let i=De(r.slice(1));return i&&Rr(i)}let e=/^(>=|<=|>|<|=)/.exec(r),t=e?e[1]:"=",n=De(e?r.slice(e[1].length):r);return n&&[{op:t,v:n}]}function Kt(r){let e=[];for(let t of r.split("||")){let n=t.trim().split(/\s+/).filter(s=>s!==""),i=[];for(let s of n){let o=Ar(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Gt(r){return Kt(r.trim())!==null}function Pr(r,e){let t=Nr(r,e.v);switch(e.op){case "<":return t<0;case "<=":return t<=0;case ">":return t>0;case ">=":return t>=0;case "=":return t===0}}function qt(r,e){let t=Kt(e.trim());return t===null?false:t.some(n=>n.every(i=>Pr(r,i)))}function Or(r,e=a$1){if(!r.engineVersion)return {compatible:true};if(!Gt(r.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:r.engineVersion,engineVersion:e};let t=Ht(e);return t===null||!qt(t,r.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:r.engineVersion,engineVersion:e}:{compatible:true}}function Qt(r,e=a$1){let t=Or(r,e);if(!t.compatible)throw t.reason==="invalid-range"?c.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${r.name}" declares an invalid engineVersion range: "${t.declaredRange}" is not a valid semver range.`,expected:'a valid semver range string (e.g. "^0.1.0", ">=0.2.0 <1.0.0")',found:`"${t.declaredRange}"`,suggestion:`This is a range-syntax typo in "${r.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:r.name,declaredRange:t.declaredRange}}):c.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${r.name}" declares engineVersion "${t.declaredRange}", which is not satisfied by the running engine version "${t.engineVersion}".`,expected:`an engine version satisfying "${t.declaredRange}"`,found:`engine version "${t.engineVersion}"`,suggestion:`Update "${r.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:r.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var ee="solve-engine/snapshot",Q=1;function $(r){return Number.isFinite(r)?r:Number.isNaN(r)?"NaN":r>0?"Infinity":"-Infinity"}function F(r){if(typeof r=="number")return r;if(r==="NaN")return NaN;if(r==="Infinity")return 1/0;if(r==="-Infinity")return -1/0;throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds an unrecognised number sentinel: ${JSON.stringify(r)}`,expected:'a JSON number, or one of "NaN", "Infinity", "-Infinity"',found:JSON.stringify(r)})}var V={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function Yt(r){return {coef:r.coef.toString(),scale:r.scale}}function Xt(r){return {coef:BigInt(r.coef),scale:r.scale}}function Lr(r){return {n:r.n.toString(),d:r.d.toString()}}function Ir(r){return {n:BigInt(r.n),d:BigInt(r.d)}}function Jt(r){return g$1[r]??String(r)}function Ve(r,e){throw c.validation({code:V.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Jt(r)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Jt(r)} value`,suggestion:"Symbolic (algebra) values are deferred to a follow-up. Evaluate the document without the symbolic line, or re-derive it after restoring.",context:{valueType:r,location:e}})}function Me(r,e){switch(r.type){case 0:{let t={t:0,v:$(r.value)};return r.exact!==void 0&&(t.exact=Yt(r.exact)),r.rational!==void 0&&(t.rational=Lr(r.rational)),t}case 1:{let t=r.value;return typeof t=="bigint"?{t:1,v:t.toString(),big:true,base:r.unit}:{t:1,v:$(t),base:r.unit}}case 2:return {t:2,v:r.value.toString()};case 3:return {t:3,v:r.value};case 4:{let t={t:4,v:$(r.value)};return r.grain!==void 0&&(t.g=r.grain),r.zone!==void 0&&(t.z=r.zone),t}case 5:return {t:5,v:$(r.value)};case 6:{let t={t:6,v:$(r.value),unit:r.unit??""};return r.exact!==void 0&&(t.exact=Yt(r.exact)),t}case 7:{let t=r.value;t.hasSymbolic&&Ve(9,`${e} (symbolic matrix cell)`);let n=t.data.map(i=>Dr(i,e));return {t:7,rows:t.rows,cols:t.cols,data:n}}case 8:{let t=r.value;return {t:8,min:$(t.min),max:$(t.max)}}case 10:return {t:10,v:r.value};case 13:return {t:13,code:r.value,message:r.unit??""};default:return Ve(r.type,e)}}function Dr(r,e){return typeof r=="boolean"?r:typeof r=="number"?$(r):Ve(9,`${e} (symbolic matrix cell)`)}function Be(r){switch(r.t){case 0:{let e=new m$1(0,F(r.v));return r.exact!==void 0&&(e.exact=Xt(r.exact)),r.rational!==void 0&&(e.rational=Ir(r.rational)),e}case 1:{let e=r.big?BigInt(r.v):F(r.v);return new m$1(1,e,r.base)}case 2:return new m$1(2,BigInt(r.v));case 3:return new m$1(3,r.v);case 4:{let e=new m$1(4,F(r.v));return r.g!==void 0&&(e.grain=r.g),r.z!==void 0&&(e.zone=r.z),e}case 5:return new m$1(5,F(r.v));case 6:{let e=new m$1(6,F(r.v),r.unit);return r.exact!==void 0&&(e.exact=Xt(r.exact)),e}case 7:{let e=r.data.map(n=>typeof n=="boolean"?n:F(n)),t={rows:r.rows,cols:r.cols,data:e,hasSymbolic:false};return new m$1(7,t)}case 8:return new m$1(8,{min:F(r.min),max:F(r.max)});case 10:return new m$1(10,r.v);case 13:return new m$1(13,r.code,r.message);default:throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds a value with an unknown type tag: ${JSON.stringify(r.t)}`,expected:"a known SerializedValue type tag",found:JSON.stringify(r.t)})}}function ue(r){let e={opcodes:Array.from(r.opcodes),numbers:Array.from(r.numbers,$),strings:r.strings.slice(),hasAsync:r.hasAsync};return r.constants&&(e.constants=Array.from(r.constants.entries())),r.userFunctionBodies&&(e.userFunctionBodies=r.userFunctionBodies.map(Ue)),r.anonymousBodies&&(e.anonymousBodies=r.anonymousBodies.map(t=>({params:t.params.slice(),program:ue(t.program)}))),e}function pe(r){let e={opcodes:Uint8Array.from(r.opcodes),numbers:Float64Array.from(r.numbers,F),strings:r.strings.slice(),hasAsync:r.hasAsync};return r.constants&&(e.constants=new Map(r.constants)),r.userFunctionBodies&&(e.userFunctionBodies=r.userFunctionBodies.map(_e)),r.anonymousBodies&&(e.anonymousBodies=r.anonymousBodies.map(t=>({params:t.params.slice(),program:pe(t.program)}))),e}function Ue(r){return {name:r.name,params:r.params.slice(),program:ue(r.program)}}function _e(r){return {name:r.name,params:r.params.slice(),program:pe(r.program)}}function rr(r){if(typeof r!="object"||r===null)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${ee}"`,found:r===null?"null":typeof r});let e=r;if(e.format!==ee)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${ee}"`,found:JSON.stringify(e.format)});if(e.version!==Q)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${Q}.`,expected:`snapshot version ${Q}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:Q,engineVersion:e.engineVersion}});Br(r);}var Zt=32;function Vr(r){return r===null?"null":Array.isArray(r)?`an array of ${r.length}`:typeof r=="object"?"an object":`${typeof r} ${JSON.stringify(r)}`.slice(0,80)}function h(r,e,t){throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot is malformed at ${r}: expected ${e}.`,expected:e,found:Vr(t),suggestion:"Regenerate the snapshot with ExpressionEngine.toJSON(), or re-evaluate the document from source.",context:{location:r}})}function j(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function z(r){return typeof r=="number"||r==="NaN"||r==="Infinity"||r==="-Infinity"}function ce(r){return typeof r=="string"&&/^-?\d+$/.test(r)}function be(r,e){(!Array.isArray(r)||!r.every(t=>typeof t=="string"))&&h(e,"an array of strings",r);}function er(r,e){(!j(r)||!ce(r.coef)||typeof r.scale!="number")&&h(e,"a decimal as { coef: digits, scale: number }",r);}function Mr(r,e){(!j(r)||!ce(r.n)||!ce(r.d))&&h(e,"a rational as { n: digits, d: digits }",r);}function tr(r,e){switch(j(r)||h(e,"a serialised value object",r),r.t){case 0:z(r.v)||h(`${e}.v`,"a number",r.v),r.exact!==void 0&&er(r.exact,`${e}.exact`),r.rational!==void 0&&Mr(r.rational,`${e}.rational`);return;case 1:(r.big?!ce(r.v):!z(r.v))&&h(`${e}.v`,r.big?"an integer string":"a number",r.v),r.base!==void 0&&typeof r.base!="string"&&h(`${e}.base`,"a base name",r.base);return;case 2:ce(r.v)||h(`${e}.v`,"an integer string",r.v);return;case 3:typeof r.v!="string"&&h(`${e}.v`,"a string",r.v);return;case 4:z(r.v)||h(`${e}.v`,"a number",r.v),r.g!==void 0&&r.g!=="date"&&r.g!=="datetime"&&r.g!=="instant"&&h(`${e}.g`,'one of "date", "datetime" or "instant"',r.g),r.z!==void 0&&typeof r.z!="string"&&h(`${e}.z`,"a zone reference",r.z);return;case 5:z(r.v)||h(`${e}.v`,"a number",r.v);return;case 6:z(r.v)||h(`${e}.v`,"a number",r.v),typeof r.unit!="string"&&h(`${e}.unit`,"a unit name",r.unit),r.exact!==void 0&&er(r.exact,`${e}.exact`);return;case 7:{let{rows:t,cols:n,data:i}=r;(!Number.isInteger(t)||t<0)&&h(`${e}.rows`,"a non-negative integer",t),(!Number.isInteger(n)||n<0)&&h(`${e}.cols`,"a non-negative integer",n),(!Array.isArray(i)||i.length!==t*n)&&h(`${e}.data`,`an array of ${t} \xD7 ${n} cells`,i),i.every(s=>typeof s=="boolean"||z(s))||h(`${e}.data`,"numeric or boolean cells",i);return}case 8:(!z(r.min)||!z(r.max))&&h(e,"a range with numeric min and max",r);return;case 10:typeof r.v!="boolean"&&h(`${e}.v`,"a boolean",r.v);return;case 13:(typeof r.code!="string"||typeof r.message!="string")&&h(e,"an error with a string code and message",r);return;default:return}}function Ee(r,e,t){if(t>Zt&&h(e,`function bodies nested at most ${Zt} deep`,"deeper nesting"),j(r)||h(e,"a serialised program object",r),(!Array.isArray(r.opcodes)||!r.opcodes.every(n=>Number.isInteger(n)&&n>=0&&n<=255))&&h(`${e}.opcodes`,"an array of bytes (integers 0 to 255)",r.opcodes),(!Array.isArray(r.numbers)||!r.numbers.every(z))&&h(`${e}.numbers`,"an array of numbers",r.numbers),be(r.strings,`${e}.strings`),typeof r.hasAsync!="boolean"&&h(`${e}.hasAsync`,"a boolean",r.hasAsync),r.constants!==void 0){let n=i=>Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number";(!Array.isArray(r.constants)||!r.constants.every(n))&&h(`${e}.constants`,"an array of [number, number] pairs",r.constants);}r.userFunctionBodies!==void 0&&(Array.isArray(r.userFunctionBodies)||h(`${e}.userFunctionBodies`,"an array of functions",r.userFunctionBodies),r.userFunctionBodies.forEach((n,i)=>nr(n,`${e}.userFunctionBodies[${i}]`,t+1))),r.anonymousBodies!==void 0&&(Array.isArray(r.anonymousBodies)||h(`${e}.anonymousBodies`,"an array of bodies",r.anonymousBodies),r.anonymousBodies.forEach((n,i)=>{let s=`${e}.anonymousBodies[${i}]`;j(n)||h(s,"a body object",n),be(n.params,`${s}.params`),Ee(n.program,`${s}.program`,t+1);}));}function nr(r,e,t){j(r)||h(e,"a function object",r),typeof r.name!="string"&&h(`${e}.name`,"a function name",r.name),be(r.params,`${e}.params`),Ee(r.program,`${e}.program`,t);}function Br(r){r.locale!==void 0&&typeof r.locale!="string"&&h("locale","a locale code",r.locale),j(r.variables)||h("variables","an object of values by name",r.variables);for(let[e,t]of Object.entries(r.variables))tr(t,`variables.${e}`);Array.isArray(r.userFunctions)||h("userFunctions","an array of functions",r.userFunctions),r.userFunctions.forEach((e,t)=>nr(e,`userFunctions[${t}]`,1)),Array.isArray(r.lineCache)||h("lineCache","an array of cached lines",r.lineCache),r.lineCache.forEach((e,t)=>{let n=`lineCache[${t}]`;j(e)||h(n,"a cached line",e),Number.isInteger(e.line)||h(`${n}.line`,"a line number",e.line),typeof e.expression!="string"&&h(`${n}.expression`,"the line's expression text",e.expression),tr(e.result,`${n}.result`),Ee(e.bytecode,`${n}.bytecode`,1),be(e.reads,`${n}.reads`),e.writeVar!==null&&typeof e.writeVar!="string"&&h(`${n}.writeVar`,"a variable name or null",e.writeVar);}),Array.isArray(r.bytecodeCache)||h("bytecodeCache","an array of compiled expressions",r.bytecodeCache),r.bytecodeCache.forEach((e,t)=>{let n=`bytecodeCache[${t}]`;(!j(e)||typeof e.expression!="string")&&h(n,"an { expression, program } pair",e),Ee(e.program,`${n}.program`,1);});}var ir=null;function cn(r){ir=r;}function Fe(){return ir}var sr=3e4,or=50,xe=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{let e=Fe();return e===null?(this._available=!1,!1):(e().terminate(),this._available=!0,!0)}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let n=[];for(let l of e){let a=t.get(l);if(!a||a.bytecode.opcodes.length===0)continue;let u=a.bytecode.opcodes,p=a.bytecode.numbers,f=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),m=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);n.push({lineNumber:l,opcodesBuffer:f,numbersBuffer:m,opcodesLength:u.length,numbersLength:p.length,strings:[...a.bytecode.strings]});}if(n.length===0)return Promise.resolve([]);let i=[];for(let l of n)l.opcodesBuffer.byteLength>0&&i.push(l.opcodesBuffer),l.numbersBuffer.byteLength>0&&i.push(l.numbersBuffer);let s=this.nextId++,o=this.nextWorkerIndex(),c=this.workers[o];return new Promise(l=>{let a=setTimeout(()=>{this.pendingBatches.has(s)&&this.failWorker(o,"WORKER_TIMEOUT",`Evaluation did not finish within ${sr/1e3} seconds; the worker was replaced`);},sr);this.pendingBatches.set(s,{id:s,lineNumbers:n.map(u=>u.lineNumber),workerIndex:o,resolve:u=>{clearTimeout(a),l(u);}}),c.postMessage({type:"EXECUTE_BATCH",id:s,items:n},i);})}clear(){for(let[,e]of this.pendingBatches)e.resolve([]);this.pendingBatches.clear();for(let e of this.workers)e.terminate();this.workers=[],this.nextWorker=0;}destroy(){this.terminated=true,this.clear();}ensureWorkers(){if(!(this.workers.length>0))for(let e=0;e<this.poolSize;e++)this.spawnWorker(e);}spawnWorker(e){let t=Fe();if(t===null)return;let n=t();n.onmessage=i=>{this.handleWorkerMessage(i.data);},n.onerror=i=>{console.error(`[ExecutionPool] Worker ${e} error:`,i.message),this.failWorker(e,"WORKER_EXECUTION_ERROR",`Worker failed: ${i.message}`);},this.workers[e]=n;}failWorker(e,t,n){if(this.workers.length!==0){this.workers[e]?.terminate(),this.terminated||this.spawnWorker(e);for(let[i,s]of this.pendingBatches)s.workerIndex===e&&(this.pendingBatches.delete(i),s.resolve(Ur(s.lineNumbers,t,n)));}}nextWorkerIndex(){let e=this.nextWorker;return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function Ur(r,e,t){return r.map(n=>({lineNumber:n,valueType:13,value:0,unit:t,isPending:false,errorCode:e}))}function ar(r$1){switch(r$1.valueType){case 0:return n(r$1.value);case 1:return r(r$1.value);case 2:return s(BigInt(r$1.value));case 3:return t$1(String(r$1.value));case 4:return M(r$1.value);case 5:return N(r$1.value);case 6:return u(r$1.value,r$1.unit??"");case 7:return n(r$1.value);case 10:return L(r$1.value!==0);case 12:return O(r$1.queryKey??"");case 13:return P(r$1.errorCode??"WORKER_EXECUTION_ERROR",r$1.unit??"Unknown worker error");default:return n(r$1.value)}}var Se=class Se{constructor(e,t,n,i=Se.DEFAULT_HIGH_WATER_MARK){this.pending=[];this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.warnedAboutMissingHook=false;this.dag=e,this.lineCache=t,this.vm=n,this.highWaterMark=i,this._eventStream=this.createEventStream();}warnIfUnwired(){this.onLineResult||this.listenerCount>0||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved, but nothing is listening for it: no reader is attached to engine.getEventStream() and AsyncResolutionBatcher.onLineResult is not set. The value is in the cache; without one of those the line keeps showing as pending. Read the event stream and re-evaluate the lines it names (see the async guide), or set onLineResult to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}add(e){this.cleared=false;for(let t of this.pending)if(t.packageId===e.packageId&&t.queryKey===e.queryKey)return;this.pending.push(e),this.scheduled||(this.scheduled=true,queueMicrotask(()=>{try{this.flush();}catch(t){let n=d(t);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${n.format()}`);}}));}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.length}get dedupCount(){let e=new Set;for(let t of this.pending)e.add(`${t.packageId}:${t.queryKey}`);return Math.max(0,this.pending.length-e.size)}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=[],this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=this.createEventStream(),this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.length===0)return;let e=this.pending;this.pending=[];let t=new Map;for(let a of e){let u=`${a.packageId}:${a.queryKey}`;t.set(u,a);}let n=[],i=[];for(let a of t.values())a.isError?n.push(a):i.push(a);for(let a of n)a.signal.aborted||this.notifyListeners({type:"error",queryKey:a.queryKey,packageId:a.packageId,error:a.error??new Error("Unknown async resolution error")});let s=new Set,o=[],c=[...i,...n];for(let a of c){if(a.signal.aborted)continue;o.push(a.queryKey);let u=this.dag.getAffectedLinesByDataSource(a.packageId,[a.queryKey]);for(let p of u)s.add(p);}if(s.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:o});return}let l=this.topologicalSort(Array.from(s));if(l.length>or){let a=new Map;for(let u of l)a.set(u,this.lineCache.getEntryForLine(u));this.reExecuteViaWorkerPool(l,a,o).catch(u=>{let p=d(u);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${p.format()}`);});return}this.reExecuteMainThread(l,o);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,n=new Map,i=new Map;for(let c of e)t.set(c,0),n.set(c,[]);for(let c of e){let l=this.dag.getWrites(c);for(let a of l)i.set(a,c);}for(let c of e){let l=this.dag.getDependencies(c);for(let a of l){let u=i.get(a);u!==void 0&&u!==c&&(n.get(u).push(c),t.set(c,(t.get(c)??0)+1));}}let s=[];for(let[c,l]of t)l===0&&s.push(c);if(s.length===0&&e.length>0)return [...e].sort((c,l)=>c-l);let o=[];for(;s.length>0;){let c=s.shift();o.push(c);for(let l of n.get(c)??[]){let a=(t.get(l)??1)-1;t.set(l,a),a===0&&s.push(l);}}if(o.length<e.length){let c=e.filter(l=>!o.includes(l)).sort((l,a)=>l-a);o.push(...c);}return o}async reExecuteViaWorkerPool(e,t,n){this.executionPool||(this.executionPool=new xe);let i=this.executionPool.executeBatch(e,t);if(!i){this.reExecuteMainThread(e,n,t);return}this.workerOffloadDispatchCount++;let s=await i;if(this.cleared)return;let o=[];for(let c of s){let l=t.get(c.lineNumber);if(!l||c.isPending)continue;let a=ar(c);l.result=a,this.warnIfUnwired(),this.onLineResult?.(c.lineNumber,a),o.push(c.lineNumber);}this.cleared||(o.length>0||n.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:n});}reExecuteMainThread(e,t,n){let i=[];for(let s of e){let o=n?n.get(s):this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let c=this.vm.getStack().length;try{let l=d$1(o.bytecode,this.vm,void 0,void 0,{lineIndex:s,networkEnabled:this.vm.context.networkEnabled,calendar:this.vm.context.calendar});for(;this.vm.getStack().length>c;)this.vm.pop();if(l.type==="value")o.result=l.value,this.warnIfUnwired(),this.onLineResult?.(s,l.value),i.push(s);else if(l.type==="error"){let a=P(l.error.code,l.error.message);o.result=a,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(s,a),i.push(s);}}catch(l){for(;this.vm.getStack().length>c;)this.vm.pop();let a=d(l),u=P(a.code,a.message);o.result=u,this.warnIfUnwired(),this.onLineResult?.(s,u),i.push(s);}}return (i.length>0||t.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:i,affectedQueryKeys:t}),i}notifyListeners(e){if(this._testCaptures&&this._testCaptures.push(e),this._streamController)try{this._streamController.enqueue(e);}catch{}}};Se.DEFAULT_HIGH_WATER_MARK=64;var ke=Se;function ze(r,e){if(r.length>e.maxExpressionLength){let t=c.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${r.length})`,{expressionLength:r.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function $e(r,e){let t=0,n=0,i=0;for(let o of r)o.type==="FUNC"&&t++,(o.value==="("||o.type==="LPAREN")&&(n++,i=Math.max(i,n)),(o.value===")"||o.type==="RPAREN")&&n--;let s=r.length+t*5+i*10;if(s>e.maxComplexity){let o=c.validation("EXPRESSION_TOO_COMPLEX",`Expression complexity score ${s} exceeds maximum of ${e.maxComplexity}`,{complexity:s,maxComplexity:e.maxComplexity});return {passed:false,complexityScore:s,errorMessage:o.message,engineError:o}}return {passed:true,complexityScore:s}}function de(r){return r.type==="IDENT"||r.type==="UNIT"}function _r(r){return r.type==="NUMBER"||r.type==="TO"||r.type==="IN"||r.type==="RPAREN"}function lr(r,e){let t=0;for(let n=e;n<r.length;n++)if(r[n].type==="LPAREN")t++;else if(r[n].type==="RPAREN"&&(t--,t===0))return n;return null}function Fr(r){let e=new Set;for(let t=0;t<r.length;t++){if(!de(r[t])||t>0&&r[t-1].type==="COLON"||r[t+1]?.type!=="LPAREN")continue;let n=lr(r,t+1);if(n!==null&&r[n+1]?.type==="EQUALS")for(let i=t+2;i<n;i++)de(r[i])&&e.add(r[i].value);}return e}function Ce(r){let e=[],t=[],n=Fr(r);for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="GLOBAL"){if(i+2<r.length&&r[i+1].type==="COLON"&&de(r[i+2])){let o=K$1(r[i+2].value);e.push(o),i+3<r.length&&r[i+3].type==="EQUALS"&&t.push(o);}continue}if(s.type==="COLON"){if(i>0&&r[i-1].type==="GLOBAL")continue;if(i+1<r.length&&de(r[i+1])){let o=r[i+1].value;e.push(o),i+2<r.length&&r[i+2].type==="EQUALS"&&t.push(o);}}if(de(s)){if(i>0&&r[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&_r(r[i-1])||n.has(s.value))continue;if(r[i+1]?.type==="LPAREN"){let c=lr(r,i+1);if(c!==null&&r[c+1]?.type==="EQUALS"){e.push(s.value),t.push(s.value);continue}}e.push(s.value);let o=r[i+1]?.type;(o==="EQUALS"||o==="PLUS_EQUALS"||o==="MINUS_EQUALS")&&t.push(s.value);}}return {reads:e,writes:t}}function Cn(r){return c$1.classifyLine(r).skip}function Tn(r,e){return c$1.findInlineSolves(r).map(n=>({start:n.start,end:n.end,expression:n.expression,lineNumber:e,columnNumber:n.columnNumber}))}var K=class{constructor(e,t,n,i){this.result=e;this.bytecode=t;this.readVariables=n;this.writeVariable=i;}},Te=class r{constructor(){this.byLine=new Map;this.count=0;}static exprKey(e){return e??""}static displayKey(e,t){return t===""?`${e}`:`${e}:${t}`}get(e,t){return this.byLine.get(e)?.get(r.exprKey(t))}getEntryForLine(e){let t=this.byLine.get(e);if(t)for(let n of t.values())return n}set(e,t,n){let i=this.byLine.get(e);i||(i=new Map,this.byLine.set(e,i));let s=r.exprKey(n);i.size>0&&!i.has(s)&&(this.count-=i.size,i.clear()),i.has(s)||this.count++,i.set(s,t);}has(e,t){return this.byLine.get(e)?.has(r.exprKey(t))??false}remove(e,t){let n=this.byLine.get(e);n&&n.delete(r.exprKey(t))&&(this.count--,n.size===0&&this.byLine.delete(e));}removeAllForLine(e){let t=this.byLine.get(e);t&&(this.count-=t.size,this.byLine.delete(e));}clearLine(e){this.removeAllForLine(e);}get size(){return this.count}clear(){this.byLine.clear(),this.count=0;}forEach(e){for(let[t,n]of this.byLine)for(let[i,s]of n)e(r.displayKey(t,i),s);}snapshotEntries(){let e=[];for(let[t,n]of this.byLine)for(let[i,s]of n)e.push({line:t,expression:i,entry:s});return e}keys(){let e=[];for(let[t,n]of this.byLine)for(let i of n.keys())e.push(r.displayKey(t,i));return e}};function je(r,e){let t=e.fields(r),n=String(t.month0+1).padStart(2,"0"),i=String(t.day).padStart(2,"0");return `${t.year}-${n}-${i}`}function zr(r,e){if(r instanceof Date)return je(r.getTime(),e);if(typeof r=="number")return Number.isFinite(r)?je(r,e):null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(r.trim());return t?`${t[1]}-${t[2]}-${t[3]}`:null}function cr(r,e){if(r===void 0)return;if(typeof r=="function")return n=>r(new Date(n));let t=new Set;for(let n of r){let i=zr(n,e);i!==null&&t.add(i);}return n=>t.has(je(n,e))}function $r(r,e){if(!r||r.type!==e.type||r.value!==e.value)return true;let t=r.unit,n=e.unit;return t!==n}var Ne=class r{constructor(e,t){this.dag=e;this.enqueue=t;this.entries=new Map;}get size(){return this.entries.size}static idOf(e,t){return JSON.stringify([e,t])}register(e){if(!(e.intervalMs>0))return;let t=r.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let n=setInterval(()=>{this.tick(t);},e.intervalMs);n.unref?.(),this.entries.set(t,{...e,timer:n,lastValue:null,inFlight:false});}async tick(e){let t=this.entries.get(e);if(t&&!t.inFlight){if(this.isDead(t)){this.stop(e);return}t.inFlight=true;try{let n=await t.refetch(),i=this.entries.get(e);if(!i)return;n&&$r(i.lastValue,n)&&(i.lastValue=n,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let n=this.entries.get(e);n&&(n.inFlight=false);}}}isDead(e){return this.dag.getAffectedLinesByDataSource(e.packageId,[e.queryKey]).size===0}reconcile(){for(let[e,t]of this.entries)this.isDead(t)&&this.stop(e);}stop(e){let t=this.entries.get(e);t&&(clearInterval(t.timer),this.entries.delete(e));}clearAll(){for(let e of this.entries.values())clearInterval(e.timer);this.entries.clear();}};var U=class{static enable(){this.enabled=true;}static disable(){this.enabled=false;}static isEnabled(){return this.enabled}static track(e,t,n){if(!this.enabled)return {result:t(),alloc:null};let i=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,s=typeof process<"u"&&process.hrtime?process.hrtime():performance.now(),o=t(),c=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,l=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,a=c?c[0]*1e9+c[1]:(performance.now()-s)*1e6,u=i&&l?l.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:a,...n};return {result:o,alloc:p}}static generateReport(e,t){let n=[];n.push(t?`## ${t}`:"## Pipeline Allocation Report"),n.push(""),n.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),n.push("");let i=this.aggregate(e);if(i.length===0)return n.push("_No telemetry data._"),n.join(`
|
|
2
|
-
`);n.push("### Per-Stage Breakdown"),n.push(""),n.push("| Stage | Count | Mean Wall (\xB5s) | Mean Alloc (bytes) | Min (\xB5s) | Max (\xB5s) | p50 (\xB5s) | p95 (\xB5s) | p99 (\xB5s) |"),n.push("|-------|:-----:|:--------------:|:------------------:|:--------:|:--------:|:--------:|:--------:|:--------:|");for(let l of i)n.push(`| ${l.stage} | ${l.count} | ${(l.meanWallTimeNs/1e3).toFixed(2)} | ${l.meanAllocBytes.toFixed(0)} | ${(l.minWallTimeNs/1e3).toFixed(2)} | ${(l.maxWallTimeNs/1e3).toFixed(2)} | ${(l.p50WallTimeNs/1e3).toFixed(2)} | ${(l.p95WallTimeNs/1e3).toFixed(2)} | ${(l.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((l,a)=>l+a.totalAllocBytes,0),o=e.reduce((l,a)=>l+a.totalWallTimeNs,0),c=e.filter(l=>l.fastPath).length;return n.push(""),n.push("### Totals"),n.push(""),n.push(`- **Total wall time:** ${(o/1e6).toFixed(2)} ms (${e.length} runs)`),n.push(`- **Total heap allocated:** ${s.toLocaleString()} bytes`),n.push(`- **Fast-path runs:** ${c}/${e.length} (${(c/e.length*100).toFixed(0)}%)`),n.push(`- **Mean per-run:** ${(o/e.length/1e3).toFixed(2)} \xB5s, ${(s/e.length).toFixed(0)} bytes`),n.join(`
|
|
3
|
-
`)}static aggregate(e){let t=new Map;for(let i of e)for(let s of i.stages)t.has(s.stage)||t.set(s.stage,[]),t.get(s.stage).push(s);let n=[];for(let[i,s]of t){let o=s.map(a=>a.wallTimeNs).sort((a,u)=>a-u),c=s.map(a=>a.allocBytes),l=s.length;n.push({stage:i,count:l,meanAllocBytes:c.reduce((a,u)=>a+u,0)/l,meanWallTimeNs:o.reduce((a,u)=>a+u,0)/l,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:We(o,50),p95WallTimeNs:We(o,95),p99WallTimeNs:We(o,99)});}return n.sort((i,s)=>i.stage.localeCompare(s.stage)),n}static createTelemetry(e,t,n=false){let i=t.reduce((o,c)=>o+c.allocBytes,0),s=t.reduce((o,c)=>o+c.wallTimeNs,0);return {expression:e,stages:t,totalAllocBytes:i,totalWallTimeNs:s,fastPath:n}}};U.enabled=false;function We(r,e){if(r.length===0)return 0;if(r.length===1)return r[0];let t=e/100*(r.length-1),n=Math.floor(t),i=Math.ceil(t);if(n===i)return r[n];let s=t-n;return r[n]*(1-s)+r[i]*s}function ur(r){let e=r[r.length-1],t=e.length>1&&e.endsWith("s")?e.slice(0,-1):e;return [...r.slice(0,-1),t].join(" ")}var we=class{constructor(){this.byKey=new Map;this.longestName=0;}get isEmpty(){return this.byKey.size===0}get maxWordCount(){return this.longestName}define(e,t,n){let i=ur(e);this.byKey.set(i,{displayName:e.join(" "),ratioText:t,baseUnit:n}),e.length>this.longestName&&(this.longestName=e.length);}match(e){let t=Math.min(e.length,this.longestName);for(let n=t;n>=1;n--){let i=this.byKey.get(ur(e.slice(0,n)));if(i!==void 0)return {definition:i,wordCount:n}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function pr(r,e=82){return {name:"uom:user-unit",priority:e,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT"]}],match(t,n){if(r.isEmpty)return null;let i=t[n];if(i.type!=="NUMBER"&&i.type!=="RPAREN")return null;let s=[],o=r.maxWordCount;for(let d=n+1;d<t.length&&s.length<o&&t[d].type==="IDENT";d++)s.push(t[d].value);if(s.length===0)return null;let c=r.match(s);if(c===null||t[n+1+c.wordCount]?.type==="EQUALS")return null;let{ratioText:a,baseUnit:u}=c.definition,p=new a$8("STAR",c$9("STAR"),"*","*",i.offset,0,i.line,i.col),f=new a$8("NUMBER",c$9("NUMBER"),a,a,i.offset,0,i.line,i.col),m=new a$8("UNIT",c$9("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+c.wordCount,replacement:[i,p,f,m],ruleName:"uom:user-unit"}}}}var dr="engine:call-fusion";function fr(r,e=80){return {name:dr,priority:e,shape:[{types:["IDENT"]},{types:["LPAREN"]}],match(t,n){let i=t[n];if(!i||i.type!=="IDENT"||t[n+1]?.type!=="LPAREN"||t[n-1]?.type==="COLON")return null;let s=(i.value??"").toLowerCase(),o=r.get(s);return o===void 0?null:{consumed:1,replacement:[new a$8(o,c$9(o),s,i.value,i.offset,0,i.line,i.col)],ruleName:dr}}}}var jr={january:1,jan:1,february:2,feb:2,march:3,mar:3,april:4,apr:4,may:5,june:6,jun:6,july:7,jul:7,august:8,aug:8,september:9,sep:9,sept:9,october:10,oct:10,november:11,nov:11,december:12,dec:12};function gr(r){return r===void 0||r.type!=="IDENT"&&r.type!=="UNIT"?0:jr[(r.text??r.value??"").toLowerCase()]??0}var fe=/^\d+$/;function Re(r){return r.length===4}function te(r,e,t,n,i,s){let o="datetime:month-name-date",c=q(r,e,t,n,o,i);return c!==null?c:s==="arithmetic"||e<1||e>12||r<1||r>31?null:s$1(g.DATE_NOT_A_CALENDAR_DAY,`"${r$1(n)}" is not a real date: ${j$1(r,e,t)}.`,n,`${o}:unreadable`)}function hr(r){return r.fields(r.now()).year}function mr(r=64,e=()=>b$5,t=()=>"refuse"){return {name:"datetime:month-name-date",priority:r,startTokenTypes:["NUMBER","IDENT","UNIT"],match(n,i){let s=e(),o=t(),c=n[i];if(c?.type==="NUMBER"&&fe.test(c.text??"")){let m=gr(n[i+1]);if(m===0)return null;let d=Number(c.text);if(d<1||d>31)return null;let T=n[i+2];return T?.type==="NUMBER"&&fe.test(T.text??"")&&Re(T.text??"")?te(d,m,Number(T.text),n.slice(i,i+3),s,o):te(d,m,hr(s),n.slice(i,i+2),s,o)}let l=gr(c);if(l===0)return null;let a=n[i+1];if(a?.type!=="NUMBER"||!fe.test(a.text??""))return null;if(Re(a.text??""))return te(1,l,Number(a.text),n.slice(i,i+2),s,o);let u=Number(a.text),p=n[i+2],f=n[i+3];return p?.type==="COMMA"&&f?.type==="NUMBER"&&fe.test(f.text??"")&&Re(f.text??"")?te(u,l,Number(f.text),n.slice(i,i+4),s,o):p?.type==="NUMBER"&&fe.test(p.text??"")&&Re(p.text??"")?te(u,l,Number(p.text),n.slice(i,i+3),s,o):te(u,l,hr(s),n.slice(i,i+2),s,o)}}}var Wr=30,Hr=40,Kr=50,Gr=24;function qr(r){switch(r){case a.PLUS:case a.MINUS:return Wr;case a.STAR:case a.SLASH:case a.MOD:case a.OF:return Hr;case a.CARET:return Kr;case a.PCT_ON:case a.PCT_OFF:return Gr;default:return 0}}function Qr(r){switch(r){case a.PLUS:return "plus";case a.MINUS:return "minus";case a.STAR:return "times";case a.SLASH:return "divided by";case a.MOD:return "mod";case a.CARET:return "to the power of";case a.OF:return "of";case a.PCT_ON:return "plus";case a.PCT_OFF:return "less";default:return r.toLowerCase()}}function yr(r){return r.sourceEnd??r.offset+r.value.length}var Yr=new Set([a.NUMBER,a.BIGINT,a.IDENT,a.UNIT,a.PERCENT,a.PI,a.E,a.TRUE,a.FALSE,a.DOLLAR,a.POUND,a.EURO,a.YEN,a.RUBLE,a.WON,a.CURRENCY_SYMBOL]);function Xr(r){return !Yr.has(r)}var He=class{constructor(e){this.tokens=e;this.pos=0;}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}parseAll(){let e=this.parseExpression(0);if(this.pos!==this.tokens.length)throw new Error("explain: unconsumed tokens");return e}parseExpression(e){let t=this.parseOperand();for(;;){let n=this.peek();if(!n)break;let i=qr(n.type);if(i===0||i<=e)break;this.next();let s=n.type===a.CARET?i-1:i,o=this.parseExpression(s);t={kind:"binary",op:n.type,left:t,right:o,start:t.start,end:o.end};}return t}parseOperand(){let e=this.peek();if(!e)throw new Error("explain: expected an operand");if(e.type===a.LPAREN)return this.parseGroup();let t=e.offset,n=false;for(;this.peek()&&(this.peek().type===a.PLUS||this.peek().type===a.MINUS);)this.next(),n=true;if(n&&this.peek()&&this.peek().type===a.LPAREN){let s=this.parseGroup();return {kind:"wrap",child:s,start:t,end:s.end}}let i=-1;for(;this.peek()&&!Xr(this.peek().type);)i=yr(this.next());if(i===-1)throw new Error("explain: expected an operand");return {kind:"leaf",start:t,end:i}}parseGroup(){let e=this.next(),t=this.parseExpression(0),n=this.peek();if(!n||n.type!==a.RPAREN)throw new Error("explain: unbalanced parentheses");return this.next(),{kind:"wrap",child:t,start:e.offset,end:yr(n)}}},Ke=class{constructor(e,t,n){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=a$9(n).display.resultPrefix;}build(e){return this.emit(e),{steps:this.steps,result:this.valueOf(e)}}emit(e){if(e.kind!=="leaf"){if(e.kind==="wrap"){this.emit(e.child);return}this.emit(e.left),this.emit(e.right),this.steps.push({description:this.describe(e),value:this.valueOf(e)});}}describe(e){let t=Qr(e.op);return e.op===a.PCT_ON||e.op===a.PCT_OFF?`${this.operand(e.right)} ${t} ${this.operand(e.left)}`:`${this.operand(e.left)} ${t} ${this.operand(e.right)}`}operand(e){return e.kind==="leaf"?this.source.slice(e.start,e.end).trim():this.render(this.valueOf(e))}valueOf(e){let t=this.cache.get(e);if(t)return t;let n=this.evaluate(this.source.slice(e.start,e.end));return this.cache.set(e,n),n}render(e){let t=c$a(e,a$a);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function Ge(r){let{expression:e,tokens:t,evaluate:n,locale:i,readings:s=[]}=r,o=a=>s.filter(u=>u.needsNote).map(u=>({description:u.note,value:a})),c=()=>{let a=n(e);return {expression:e,steps:o(a),result:a}},l;try{l=new He(t).parseAll();}catch{return c()}try{let{steps:a,result:u}=new Ke(e,n,i).build(l);return {expression:e,steps:[...o(u),...a],result:u}}catch{return c()}}var Y=class Y{constructor(e={}){this.dag=new a$2;this.lineCache=new Te;this.accumulatorNames=new Set;this.scopeManager=new b;this.resolverRegistry=new a$3;this.packageContributions=new Map;this.registeredPackages=new Map;this.callFusions=new Map;this.callFusionOwners=new Map;this.compatIndex=new ve;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.backgroundRefreshSignal=new AbortController().signal;this.userUnits=new we;this.bytecodeCache=new Map;this.compiledFrontHalf=new Map;this.failedParses=new Map;this.pluginFunctionIndexByName=new Map;this.builderPool=[new d$2(this.pluginFunctionIndexByName),new d$2(this.pluginFunctionIndexByName),new d$2(this.pluginFunctionIndexByName),new d$2(this.pluginFunctionIndexByName)];this.builderPoolIndex=0;this.lastTelemetry=null;let{locale:t$1="en",diagnostics:n=false,config:i,packages:s,calendar:o}=e;this.localeCode=t$1,this.config=c$2(b$1,i??{}),this.dateReading=h$1(this.config.date),this.lexer=new b$2(t$1),this.registry=new b$3,this.context=x({networkEnabled:this.config.network.enabled,calendar:o}),n?(this.diagnosticPipeline=new a$4,this.timelineCollector=new b$4,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new a$4,this.normalizer=new c$3;for(let[l,a]of Object.entries(c$4))this.normalizer.addPhrase(l,a);this.normalizer.register(d$3(50,l=>this.normalizer.canStartPhrase(l))),this.normalizer.register(pr(this.userUnits)),this.normalizer.register(fr(this.callFusions));let c=s??[];for(let l of c)try{this.registerPackage(l);}catch(a){let u=d(a);console.error(`[ExpressionEngine] Failed to register package "${l.name}" \u2014 skipping it and continuing construction with the remaining packages: ${u.format()}`);}if(this.registry.hasPrefix("DATETIME_LITERAL")&&this.registry.hasPrefix("DATETIME_LITERAL_UNREADABLE")){let l=()=>this.context.calendar;this.normalizer.register(t(()=>this.dateReading.order,l,()=>this.config.date.onAmbiguous)),this.normalizer.register(mr(void 0,l,()=>this.config.date.onAmbiguous));}this.parser=new a$5(this.registry,this.config.validation.maxNestingDepth,t$1,this.pluginFunctionIndexByName,this.context.calendar),this.vm=c$5(this.context.opRegistry,this.config.vm.maxStackDepth,this.config.vm.maxInstructions,void 0,this.config.vm.maxCollectionSize,this.config.vm.maxAllocatedElements,this.config.vm.maxFunctionCalls,this.config.date.maxOffsetYears,this.config.date.minOffsetYears,this.context,cr(this.config.date.holidays,this.context.calendar)),this.queryClient=c$6(),this.batcher=new ke(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new Ne(this.dag,(l,a)=>this.batcher.add({queryKey:a,packageId:l,signal:this.backgroundRefreshSignal,isError:false})):null,e.warmup===true&&this.warmUp();}setDocumentModel(e){this.documentModel=e;}getDocumentModel(){return this.documentModel}warmUp(){let e=new d$2(this.pluginFunctionIndexByName);for(let t of Y.WARMUP_EXPRESSIONS)try{this.lexer.resetExpression(t);let n=[];for(let o of this.lexer)o.type!=="COMMENT"&&n.push(o);let i=this.normalizer.normalize(n);e.reset(),this.parser.load(i),this.parser.parseExpression(0,e);let s=e.build();this.vm.reset(),d$1(s,this.vm);}catch{}this.vm.reset();}makeLineContext(e){let t=this.documentModel,n=t?null:this.batchScanResults,i=t?null:this.batchParsedLines;return {lineIndex:e,getLineResult:t?s=>t.getLineAt(s)?.result??void 0:i?s=>i[s-1]?.result??void 0:void 0,isLineBoundary:t?s=>{let o=t.getLineAt(s);return o?o.isEmpty||/^\s*#/.test(o.text):true}:n?s=>{let o=n[s-1];return o?o.classification.skip||/^\s*#/.test(o.text):true}:void 0,getLineReads:t?s=>{let o=t.getLineAt(s);if(!(!o||o.bytecodes.length===0))return o.reads}:void 0,evaluateLineWithBinding:t?(s,o,c,l)=>this.evaluateLineWithBinding(s,o,c,l):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,networkEnabled:this.config.network.enabled,calendar:this.context.calendar,getLineText:t?s=>t.getLineAt(s)?.text:n?s=>n[s-1]?.text:void 0}}evaluateLineWithBinding(e,t,n,i){let s=this.documentModel;if(!s)return P("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=Y.GOAL_SEEK_MAX_NESTING_DEPTH)return P("GOAL_SEEK_NESTED","A goal-seek line cannot target another goal-seek line, since each already re-runs its target many times.");let o=s.getLineAt(e);if(!o||o.bytecodes.length===0)return P("GOAL_SEEK_LINE_NOT_READY",`Line ${e} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(o.isVariableDef)return P("GOAL_SEEK_TARGET_IS_DEFINITION",`Line ${e} defines a variable, so re-running it would overwrite that variable. Target the line that uses ${t}, not the one that sets a value.`);let c=o.bytecodes[0];this.goalSeekDepth++;try{let l=new Map([[t,n]]),a=this.vm.getStack().length;this.vm.pushCallFrame(l);try{let u=d$1(c,this.vm,void 0,void 0,this.makeLineContext(e),i);return u.type==="pending"?P("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?P(u.error.code??"GOAL_SEEK_TARGET_ERROR",u.error.message):u.value}finally{for(this.vm.popCallFrame();this.vm.getStack().length>a;)this.vm.pop();}}catch(l){return P("GOAL_SEEK_TARGET_ERROR",d(l).message)}finally{this.goalSeekDepth--;}}frontHalfCached(e){return this.compiledFrontHalf.has(e)&&this.bytecodeCache.has(e)||this.failedParses.has(e)}clearCompiledCache(){this.bytecodeCache.clear(),this.compiledFrontHalf.clear(),this.failedParses.clear();}cacheBytecode(e,t,n){let i=this.config.performance.defaultCacheSize;if(this.bytecodeCache.size>=i){let s=this.bytecodeCache.keys().next().value;s!==void 0&&(this.bytecodeCache.delete(s),this.compiledFrontHalf.delete(s));}this.bytecodeCache.set(e,t),this.compiledFrontHalf.set(e,n);}rememberFailedParse(e,t){if(this.failedParses.size>=this.config.performance.defaultCacheSize){let n=this.failedParses.keys().next().value;n!==void 0&&this.failedParses.delete(n);}this.failedParses.set(e,t);}getEventStream(){return this.batcher.getEventStream()}getBatcher(){return this.batcher}registerPackage(e){Qt(e),this.packageContributions.has(e.name)&&(console.warn(`[ExpressionEngine] Package "${e.name}" is already registered. Unregistering the previous registration before re-registering.`),this.unregisterPackage(e.name));let t=this.compatIndex.check(e);for(let i of t)(i.severity==="error"?console.error:console.warn)(`[ExpressionEngine] Package compatibility ${i.severity} (${i.kind}): ${i.detail}`);let n={pluginFunctionIndices:[],pluginFunctionNames:[],resolverNamespaces:[],tokenCategories:[],lexerVocabulary:e.lexerVocabulary,asConverterNames:[],normalizerRuleNames:[],callFusionNames:[]};if(e.lexerVocabulary&&this.lexer.registerVocabulary(e.lexerVocabulary),e.prefixParselets)for(let[i,s]of Object.entries(e.prefixParselets))this.registry.registerPrefix(i,s);if(e.infixParselets)for(let[i,s]of Object.entries(e.infixParselets))this.registry.registerInfix(i,s);if(e.pluginFunctions)for(let[i,s]of Object.entries(e.pluginFunctions)){let o=F$1(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),n.pluginFunctionIndices.push(o),n.pluginFunctionNames.push(i);}if(e.asyncResolvers)for(let i of e.asyncResolvers)this.resolverRegistry.register(i),n.resolverNamespaces.push(i.namespace);if(e.phrases)for(let[i,s]of Object.entries(e.phrases))this.normalizer.addPhrase(i,s);if(e.normalizerRules)for(let i of e.normalizerRules)this.normalizer.register(i),n.normalizerRuleNames.push(i.name);if(e.callFusions)for(let[i,s]of Object.entries(e.callFusions)){let o=i.toLowerCase(),c=this.callFusionOwners.get(o);c?c.push({pkg:e.name,tokenType:s}):this.callFusionOwners.set(o,[{pkg:e.name,tokenType:s}]),this.callFusions.set(o,s),n.callFusionNames.push(o);}if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))b$6(i,s),n.tokenCategories.push(i);if(e.completionItems&&this.packageCompletionItems.set(e.name,e.completionItems),e.asConverters)for(let[i,s]of Object.entries(e.asConverters))H(i,s),n.asConverterNames.push(i);this.packageContributions.set(e.name,n),this.registeredPackages.set(e.name,e),this.compatIndex.add(e),this.clearCompiledCache();}unregisterPackage(e){let t=this.packageContributions.get(e);if(!t)return false;for(let n of t.pluginFunctionIndices)delete this.context.pluginFunctions[n],delete this.context.pluginFunctionOwners[n];for(let n of t.pluginFunctionNames)this.pluginFunctionIndexByName.delete(n);for(let n of t.resolverNamespaces)this.resolverRegistry.unregister(n);for(let n of t.tokenCategories)c$7(n);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let n of t.asConverterNames)I(n);for(let n of t.normalizerRuleNames)this.normalizer.unregister(n);for(let n of t.callFusionNames){let i=(this.callFusionOwners.get(n)??[]).filter(s=>s.pkg!==e);i.length===0?(this.callFusionOwners.delete(n),this.callFusions.delete(n)):(this.callFusionOwners.set(n,i),this.callFusions.set(n,i[i.length-1].tokenType));}return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.compatIndex.rebuild(this.registeredPackages.values()),this.clearCompiledCache(),true}getConfig(){return {...this.config}}getDateReading(){return this.dateReading}readDates(e){let{tokens:t}=this.lexToTokens(e,void 0,false),n=this.normalizer.normalize(t.filter(s=>s.type!=="COMMENT")),i=[];for(let s of n){let o$1=s.type===p;if(!o$1&&s.type!==o)continue;let c=s.offset,l=s.sourceEnd??s.offset+s.text.length;i.push(this.describeDateLiteral(e.slice(c,l),c,l,s,o$1));}return i}describeDateLiteral(e,t,n,i$1,s){let o=n$1(e);if(o!==null){let a=l(o,this.dateReading.order,this.config.date.onAmbiguous,this.context.calendar),u=i(o.groups[0],o.groups[1],o.groups[2],o.separator)==="iso",p=this.dateReading.order==="auto"?o.separator==="hyphen"?"MDY":"DMY":this.dateReading.order,f=u?{order:"ISO",orderSource:"iso",locale:void 0}:{order:p,orderSource:this.dateReading.orderSource,locale:this.dateReading.locale};return a.kind==="date"?m({text:e,start:t,end:n,iso:k(a.day,a.month,a.year),...f,contested:a.alternative!==void 0,shortYear:a.shortYear,alternative:a.alternative},o.separator):m({text:e,start:t,end:n,iso:null,...f,contested:false,shortYear:false,problem:a.kind==="refuse"?a.code:void 0},o.separator,a.kind==="refuse"?a.message:void 0)}if(s){let a=i$1.fault??{code:"DATE_NOT_A_CALENDAR_DAY",message:`"${i$1.value}" is not a date this engine can read.`};return m({text:e,start:t,end:n,iso:null,order:null,orderSource:"spelled",contested:false,shortYear:false,problem:a.code},"slash",a.message)}let c=this.context.calendar.fields(Number(i$1.value)),l$1=/^\d{4}-/.test(e)?"iso":"spelled";return m({text:e,start:t,end:n,iso:k(c.day,c.month0+1,c.year),order:l$1==="iso"?"ISO":"spelled",orderSource:l$1,contested:false,shortYear:false},"slash")}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,n,i,s,o){this.lineCache.set(e,new K(t,n,i,s.length>0?s[0]:null),o);}executeAndStore(e,t,n,i,s,o,c,l){let a=this.vm.getStack().length,u=new AbortController,p=()=>u.abort();this.keystrokeSignal?.addEventListener("abort",p,{once:true}),a$6.localControllerCreated("executeAndStore"),this.keystrokeSignal&&a$6.signalLinked("executeAndStore"),this.vm.activeSignal=u.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeAndStore"),this.keystrokeSignal?.removeEventListener("abort",p),u.abort();},a$7(this.queryClient);let f=d$1(e,this.vm,c,l,this.makeLineContext(t));for(;this.vm.getStack().length>a;)this.vm.pop();if(f.type==="pending"){this.resolveAsync(f),this.dag.registerLineDataSourceDependency(t,f.packageId||o,[f.queryKey]);let m=O(f.queryKey);return this.storeLineResult(t,m,e,i,s,n),m}if(f.type==="error")throw this.keystrokeSignal?.removeEventListener("abort",p),f.error;return this.keystrokeSignal?.removeEventListener("abort",p),this.dag.registerLine(t,i,s),this.storeLineResult(t,f.value,e,i,s,n),f.value}executeRaw(e,t=-1){let n=this.vm.getStack().length,i=new AbortController,s=()=>i.abort();this.keystrokeSignal?.addEventListener("abort",s,{once:true}),a$6.localControllerCreated("executeRaw"),this.keystrokeSignal&&a$6.signalLinked("executeRaw"),this.vm.activeSignal=i.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeRaw"),this.keystrokeSignal?.removeEventListener("abort",s),i.abort();},a$7(this.queryClient);let o=d$1(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>n;)this.vm.pop();return o.type!=="pending"&&this.keystrokeSignal?.removeEventListener("abort",s),o}async resolveAsync(e){let{queryKey:t,resolver:n,packageId:i,signal:s}=e,o=i||"_engine";try{if(await n,s.aborted){a$6.staleDataDiscarded(t,"signal aborted after resolve");return}this.batcher.add({queryKey:t,packageId:o,signal:s,isError:!1});}catch(c){if(s.aborted){a$6.staleDataDiscarded(t,"signal aborted after error");return}let l=c instanceof Error?c:new Error(String(c));this.batcher.add({queryKey:t,packageId:o,signal:s,isError:true,error:l});}}registerBackgroundRefresh(e){this.backgroundRefresh&&(e.refetchIntervalMs===void 0||!e.refetch||this.backgroundRefresh.register({packageId:e.packageId||"_engine",queryKey:e.queryKey,intervalMs:e.refetchIntervalMs,refetch:e.refetch}));}getBackgroundRefreshCount(){return this.backgroundRefresh?.size??0}parseDocument(e,t={inputType:"markdown"}){let n=this.config.performance.maxDocumentLines;if(b$7(e,n)>n)throw c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${n.toLocaleString("en-US")} lines, which is the most the engine will process in one pass`,{maxLines:n});this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let i=this.lexer.scanDocument(e),s=this.processScanResults(i),o={lines:s,totalLines:s.length,errors:[]};for(let l of s){l.error&&o.errors.push(`Line ${l.lineNumber}: ${l.error}`);for(let a of l.inlineSolves)a.error&&o.errors.push(`Line ${l.lineNumber}: ${a.error}`);}if(t.includeDiagnostics??false){let l=this.diagnosticPipeline.collectReports();l.length>0&&(o.diagnostics=l[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
|
|
4
|
-
`),n=this.lexer.scanDocument(t);return this.processScanResults(n)}processScanResults(e){let t=[],n=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;try{for(let s of e){let o=s.text,c=s.lineNumber,l=s.startOffset,a=s.endOffset,u=s.classification.skip,p=s.inlineSolves.map(d=>({start:d.start,end:d.end,expression:d.expression,lineNumber:c,columnNumber:d.columnNumber})),f=p.length>0,m={lineNumber:c,text:o,startPosition:l,endPosition:a,isEmpty:u,hasInlineSolves:f,inlineSolves:p,expression:null,result:null,error:null};if(s.error)m.error=s.error.message;else if(!u){let d=o.trim().startsWith(":");if(f&&!d)for(let T of p)try{T.result=this.evaluateLine(c,T.expression);}catch(b){let R=b instanceof Error?b.message:String(b);T.error=R;}else {let T=s.classification.contentOffset,R=(T===void 0?o:o.slice(T-l)).trim();if(R)try{let L=this.evaluateLineWithPreTokenized(c,R,s.tokens);m.expression=R,m.result=L[0];}catch(L){let G=L instanceof Error?L.message:String(L);m.error=G;}}}t.push(m);}}finally{this.batchScanResults=n,this.batchParsedLines=i;}return t}evaluateLineWithPreTokenized(e,t,n){let i=[],s=false;for(let o of n)(o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o);return [this.evaluateWithTokens(e,t,i,s)]}parseExpression(e,t,n,i=true){this.parser.setBuilder(e),this.parser.load(t,this.config.validation.autoBalanceParens?n:false),this.parser.parseExpression(0);let s=this.parser.peek();if(s){if(s.type==="EQUALS"&&!this.parser.peekAt(1))return;for(let o=i?t.length-1:0;o>=1;o--){if(t[o].type!=="COLON"||o+1>=t.length)continue;let c$1=true;for(let l=0;l<o;l++){let a=t[l].type;if(a!=="NUMBER"&&a!=="COLON"){c$1=false;break}}if(c$1){let l=t.slice(0,o+2).map(a=>a.value).join("");throw c.parsing("INVALID_TIME_LITERAL",`"${l}" is not a valid time`,{tokenType:t[o].type,tokenValue:l})}e.reset();try{this.parseExpression(e,t.slice(o+1),n,!1);return}catch{}}throw c.parsing({code:"UNEXPECTED_TRAILING_TOKEN",message:`Unexpected token after expression: "${s.value}"`,context:{tokenType:s.type,tokenValue:s.value},span:{start:s.offset,end:s.sourceEnd??s.offset+s.text.length,line:s.line,col:s.col}})}}compileAdHoc(e){let t=new d$2(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let n=d$1(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(n.type==="error")throw n.error;if(n.type==="pending")throw c.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return n.value}simplifySymbolically(e,t=-1){return this.executeSymbolicTolerant(this.compileAdHoc(e),t)}parseFactorChain(e){if(e.length===0||e.length%2===0)return null;let t=[];for(let n=0;n<e.length;n++)if(n%2===0){if(e[n].type!=="IDENT"&&e[n].type!=="UNIT")return null;t.push(e[n].value);}else if(e[n].type!=="STAR")return null;return t}solveEquation(e,t=-1){let n=[];for(let c of e.factorNames){let l=this.vm.getVar(c);if(l===void 0)return P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${c}" is not yet defined.`);if(l.type!==7)return P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${c}" must be a Matrix (got a different value type).`);n.push(l);}let i=n[0].value;for(let c=1;c<n.length;c++){let l=_(i,n[c].value);if(l.type===13)return l;i=l.value;}let s=da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):_(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t=1;e[t].type==="STAR"&&t++;let n=[];for(;t<e.length&&e[t].type==="IDENT";)n.push(e[t].value),t++;if(n.length===0||e[t]?.type!=="EQUALS"||(t++,e[t]?.type!=="NUMBER"))return null;let i=e[t];if(t++,e[t]?.type!=="UNIT")return null;let s=e[t];return t++,t!==e.length?null:(this.userUnits.define(n,i.value,s.value),this.clearCompiledCache(),t$1(`${n.join(" ")} defined`))}tryCompoundAssignment(e,t=-1){if(e.length<2)return null;let n$1=e[0],i=e[1],s=n$1.type==="IDENT"||n$1.type==="UNIT",o=i.type==="PLUS_EQUALS"||i.type==="MINUS_EQUALS";if(!s||!o)return null;let c$1=e.slice(2);if(c$1.length===0)throw c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${n$1.value} ${i.value}" needs an expression on the right, e.g. "${n$1.value} ${i.value} 10".`);let l=n$1.value;this.accumulatorNames.add(l),this.vm.getVar(l)===void 0&&this.vm.setVar(l,n(0));let a=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$8("IDENT",l,[n$1]),b$8(a.type,a.text,[i]),b$8("LPAREN","(",[i]),...c$1,b$8("RPAREN",")",[i])],p=d$1(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(p.type==="error")throw p.error;if(p.type==="pending")throw c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(l,p.value),p.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e,t=-1){if(e.length===0)return null;if(e[e.length-1].type==="THEREFORE"){let a=e.slice(0,-1);if(a.length===0)throw c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(a.length===1&&(a[0].type==="IDENT"||a[0].type==="UNIT")){let u=a[0].value,p=this.vm.getEquation(u),f=this.vm.getScalarEquation(u);if(p){let m=this.solveEquation(p,t);if(!(m.type===13&&m.value==="EQUATION_FACTOR_NOT_MATRIX")||!f)return m}if(f)return this.solveScalarEquation(f,t)}return this.simplifySymbolically(a,t)}if(b$9(e))return this.simplifySymbolically(e,t);if(e[0].type==="COLON"||e[0].type==="GLOBAL"||e[0].type==="GOAL_SEEK")return null;let i=e.findIndex(a=>a.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e,i);let o=e.slice(i+1);if(s.length===1){let a=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],a),a}let c$1=s[s.length-1],l=s.slice(0,-1);return this.vm.defineEquation(c$1,l,this.compileAdHoc(o)),this.vm.defineScalarEquation(c$1,this.compileAdHoc(e.slice(0,i)),this.compileAdHoc(o)),t$1(`${c$1} stored as an equation \u2014 solve with "${c$1} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let n=e.slice(0,t),i=e.slice(t+1);if(i.some(c=>c.type==="EQUALS"))return null;let s=this.equationUnknowns(n,i);if(s.length!==1)return null;let o=s[0];return this.vm.defineScalarEquation(o,this.compileAdHoc(n),this.compileAdHoc(i)),t$1(`${o} stored as an equation \u2014 solve with "${o} =>"`)}equationUnknowns(e,t){let n=[];for(let i of [...e,...t])i.type!=="IDENT"&&i.type!=="UNIT"||this.vm.getVar(i.value)===void 0&&(this.vm.hasUserFunction(i.value)||n.includes(i.value)||n.push(i.value));return n}solveScalarEquation(e,t=-1){let n=this.executeSymbolicTolerant(e.lhsProgram,t),i=this.executeSymbolicTolerant(e.rhsProgram,t);return i$1(n,i,e.variable)}lexToTokens(e,t,n=true){let i=[],s=false;if(n&&!t&&this.frontHalfCached(e))return {tokens:i,hasParens:s,compiled:true};this.lexer.resetExpression(e);for(let o of this.lexer)o.type!=="COMMENT"&&((o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o),t?.(o));return {tokens:i,hasParens:s,compiled:false}}prepareExpression(e,t,n,i,s=-1){let o=this.bytecodeCache.get(e);if(o&&!i){let b=this.compiledFrontHalf.get(e);if(b)return {kind:"ready",normalizedTokens:b.normalizedTokens,reads:b.reads,writes:b.writes,program:o,cached:true}}let c=i?void 0:this.failedParses.get(e),l;if(c)l=c.normalizedTokens;else {let b=ze(e,this.config.validation);if(!b.passed)return {kind:"error",stage:"length",error:b.error.engineError};let R=t.filter(G=>G.type!=="COMMENT");if(R.length===0)return {kind:"empty"};l=this.normalizer.normalize(R,i);let L=$e(l,this.config.validation);if(!L.passed)return {kind:"error",stage:"complexity",error:L.engineError,normalizedTokens:l}}let a,u=null;try{if(a=this.tryDefineUserUnit(l),a===null){let b=this.tryCompoundAssignment(l,s);b!==null&&(a=b,u=Ce(l));}a===null&&(a=this.trySymbolicGrammar(l,s));}catch(b){let{reads:R,writes:L}=Ce(l);return {kind:"error",stage:"parse",error:d(b),reads:R,writes:L,normalizedTokens:l}}if(a!==null)return {kind:"symbolic-solve",normalizedTokens:l,value:a,reads:u?.reads,writes:u?.writes};if(c)return {kind:"error",stage:"parse",error:c.error,reads:c.reads,writes:c.writes,normalizedTokens:l};let{reads:p,writes:f}=Ce(l);if(o)return this.compiledFrontHalf.set(e,{normalizedTokens:l,reads:p,writes:f}),{kind:"ready",normalizedTokens:l,reads:p,writes:f,program:o,cached:true};let m=this.builderPool[this.builderPoolIndex++%this.builderPool.length];m.reset();let d$1,T=null;try{let b=U.track("parser",()=>(this.parseExpression(m,l,n),m.build()));d$1=b.result,T=b.alloc;}catch(b){let R=d(b);return this.rememberFailedParse(e,{error:R,normalizedTokens:l,reads:p,writes:f}),{kind:"error",stage:"parse",error:R,reads:p,writes:f,normalizedTokens:l}}return this.cacheBytecode(e,d$1,{normalizedTokens:l,reads:p,writes:f}),{kind:"ready",normalizedTokens:l,reads:p,writes:f,program:d$1,cached:false,parserAlloc:T}}preflightAsync(e,t,n,i,s,o){if(!(t.hasAsync||this.resolverRegistry.size>0))return {kind:"proceed"};let c=new AbortController,l=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.signalLinked("preflightAsync");let a=c.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",a,this.queryClient,this.config.network.enabled);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(n,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=O(u.queryKey);return this.storeLineResult(n,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",l),{kind:"proceed"}}evaluateWithTokens(e,t,n$1,i){let s=this.prepareExpression(t,n$1,i,void 0,e);if(s.kind==="empty"){let p=n(0);return this.lineCache.set(e,new K(p,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),p}if(s.kind==="error")throw s.error;if(s.kind==="symbolic-solve")return this.storeLineResult(e,s.value,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},s.reads??[],s.writes??[],t),s.value;let{normalizedTokens:o,reads:c,writes:l,program:a}=s,u=this.preflightAsync(o,a,e,t,c,l);return u.kind==="pending"?u.value:this.executeAndStore(a,e,t,c,l,"_engine")}evaluateLine(e,t){let n=this.evaluateLineWithDebug(e,t);if(n.error)throw n.engineError?n.engineError:c.execution("EVALUATION_ERROR",n.error,{lineNumber:e});return l$1(n.value)}evaluateLineWithDebug(e,t,n="expression"){let i=t.match(/^s`([^`]*)`$/);if(i){let s=i[1];return {...this.evaluateExpressionWithDiagnostic(s,e,n),inlineSolve:{start:0,end:t.length,expression:s,lineNumber:e,columnNumber:1}}}return this.evaluateExpressionWithDiagnostic(t,e,n)}addDiagnosticStage(e,t,n,i,s,o,c,l,a){e.push({stage:t,label:n,icon:i,colorClass:s,stepNumber:o,elapsedNs:c,skipped:l,output:a});}evaluateExpressionWithDiagnostic(e,t,n$1="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,c$1=U.isEnabled(),l=[],a=[],u=0,p=ze(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(a,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:false,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength,errorMessage:p.error.error}),{...p.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:c$8.PipelineStart,elapsedNs:0,expression:e,inputType:n$1}),this.addDiagnosticStage(a,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:n$1}),this.addDiagnosticStage(a,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:true,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength}));let f=s?y=>{i.fireTokenEmitted({type:c$8.TokenEmitted,elapsedNs:0,expression:e,token:{type:y.type,value:y.value,offset:y.offset||0,line:y.line||t,col:y.col||0}});}:void 0,m=U.track("lexer",()=>this.lexToTokens(e,f)),d$1=m.result.tokens,T=m.result.hasParens,b=m.result.compiled;if(c$1&&m.alloc&&l.push(m.alloc),s){let y={};for(let O of d$1)y[O.type]=(y[O.type]||0)+1;this.addDiagnosticStage(a,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:d$1.length,tokenTypes:y,hasParens:T,locale:this.localeCode,tokens:[...d$1]});let A=[];for(let O=0;O<d$1.length;O++){let se=d$1[O];if(se.type==="INLINE_SOLVE_START"){let M=-1;for(let W=O+1;W<d$1.length;W++)if(d$1[W].type==="BACKTICK_OPEN"){M=W;break}if(M>O){let kr=d$1.slice(O+1,M).map(Sr=>Sr.value).join("");A.push({startTokenIndex:O,endTokenIndex:M,expression:kr,columnNumber:se.col||1}),O=M;}}}this.addDiagnosticStage(a,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:A.length>0,inlineSolveSpans:A});}if(!b&&d$1.length===0){let y=n(0);return this.lineCache.set(t,new K(y,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:y,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let R=0,L=[],G=new Map,br=s?y=>{R++,L.push(y),G.set(y.rule,(G.get(y.rule)||0)+1),i.fireTokenFused({type:c$8.TokenFused,elapsedNs:0,expression:e,ruleName:y.rule,sourceTokenCount:y.sourceTokens.length,fusedTokenType:y.fusedToken.type,fusedTokenValue:y.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:c$8.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:d$1.length});let D=this.bytecodeCache.get(e);s&&!D&&this.parser.setDiagnosticPipeline(i,e);let v=this.prepareExpression(e,d$1,T,br,t);b&&v.kind==="ready"&&(d$1=v.normalizedTokens),c$1&&v.kind==="ready"&&v.parserAlloc&&l.push(v.parserAlloc),s&&!D&&this.parser.setDiagnosticPipeline(void 0,"");let k=v.kind==="empty"?d$1:v.normalizedTokens??d$1;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:c$8.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:k.length,fusionsCount:R}),this.addDiagnosticStage(a,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:k.length,fusions:L,rulesApplied:[...G.entries()].map(([y,A])=>({rule:y,count:A})),tokens:[...k],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(k)})):this.addDiagnosticStage(a,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:d$1.length,fusions:[],rulesApplied:[],tokens:[...d$1],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(d$1)})),v.kind==="empty"||v.kind==="error"&&v.stage==="length"){if(s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:v.kind==="empty",totalTokens:d$1.length,totalOpcodes:0}),v.kind==="empty"){let y=n(0);return this.lineCache.set(t,new K(y,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:y,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0}}let re=$e(k,this.config.validation);if(v.kind==="error"&&v.stage==="complexity")return s&&(this.addDiagnosticStage(a,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:re.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0},errorMessage:re.errorMessage}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:re.errorMessage,engineError:re.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(a,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:re.complexityScore??k.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0}}),v.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:0});let y={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,v.value,y,v.reads??[],v.writes??[],e),{value:v.value,tokens:k,program:y,debug:void 0,diagnostic:void 0}}let ge=v.reads??[],ne=v.writes??[];if(s&&(this.addDiagnosticStage(a,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ge,writes:ne,isAssignment:ne.length>0}),this.addDiagnosticStage(a,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!D,cacheSize:this.bytecodeCache.size,cacheKey:e}),D?i.fireCacheHit({type:c$8.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$8.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),v.kind==="error"&&v.stage==="parse")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0}),{value:n(0),tokens:k,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0};if(v.kind!=="ready")throw c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let x=v.program;s&&(this.addDiagnosticStage(a,"parser","Parser","\u{1F333}","parser",8,u,!!D,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(a,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!D,{type:"compiler",opcodeCount:x.opcodes.length,numberConstants:x.numbers.length,stringConstants:x.strings.length,hasAsync:x.hasAsync,cached:!!D}),i.fireBytecodeBuilt({type:c$8.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:x.opcodes.length,numbersLength:x.numbers.length,stringsLength:x.strings.length,isCached:!!D}));let Er=x.hasAsync||this.resolverRegistry.size>0,ie=this.preflightAsync(k,x,t,e,ge,ne);if(s&&(ie.kind==="pending"?this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:ie.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Er?this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:0,skippedGuard:true})),ie.kind==="pending")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:ie.value,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(a,ie.value,k,x,null):void 0};let xr=s&&this.config.diagnostic.vmTraceEnabled===true,N;try{let y=U.track("vm",()=>this.executeAndStore(x,t,e,ge,ne,"_engine",xr?i:void 0,e),{cacheHit:!!D});N=y.result,c$1&&y.alloc&&l.push(y.alloc);}catch(y){let A=d(y);return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:n(0),tokens:k,program:x,error:A.message,engineError:A,debug:void 0,diagnostic:void 0}}let he=N.type===12;if(s){let y=he?"pending":String(N.value??""),A=he?"Pending":N.unit?"Uom":"Number";this.addDiagnosticStage(a,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:x.opcodes.length,stackDepth:this.vm.getStack().length,resultType:A,resultValue:y,isPending:he});}if(he)return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:N,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(a,N,k,x,null):void 0};if(c$1&&l.length>0&&(this.lastTelemetry=U.createTelemetry(e,l,!!D)),s&&(this.addDiagnosticStage(a,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:ge,writesRegistered:ne,dataSourcesRegistered:[]}),this.addDiagnosticStage(a,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(a,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(N.value),formattedValue:String(N.value),valueType:N.type===0?"Number":"Value",unit:N.unit}),i.fireVmHalt({type:c$8.VmHalt,elapsedNs:0,expression:e,result:N?{type:N.type,value:N.value,unit:N.unit}:void 0}),this.addDiagnosticStage(a,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length,cacheHit:!!D}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length})),s){let A=i.collectReports()[0]?.toJSON(),O=A;if(A){let se=A.parselets.slice(o),M={};for(let W of se)M[W.parseletCategory]=(M[W.parseletCategory]??0)+1;O={...A,parselets:se,summary:{...A.summary,totalParselets:Object.keys(M).length,parseCategories:M}};}return {value:N,tokens:k,program:x,debug:O,diagnostic:this.buildDiagnosticResult(a,N,k,x,null)}}return {value:N,tokens:k,program:x}}buildDiagnosticResult(e,t,n,i,s){return {stages:e,value:t,tokens:n,program:i,error:s,dagSnapshot:this.dag.getSnapshot(),cacheSnapshot:this.getCacheSnapshot(),batcherMetrics:this.getBatcherMetrics(),checkpoints:this.getCheckpoints()}}reEvaluateLine(e,t){let n=this.lineCache.get(e,t);if(!n)return;let i=this.bytecodeCache.get(t);if(!i)return;if(n.bytecode.hasAsync||this.resolverRegistry.size>0){let c=new AbortController,l=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.signalLinked("reEvaluateLine preflight");let a=c.signal,u=this.resolverRegistry.preflightAll([],n.bytecode,"_engine",a,this.queryClient,this.config.network.enabled);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return n.result=o,o}getDag(){return this.dag}getLineCache(){return this.lineCache}getBytecodeCache(){return this.bytecodeCache}getVM(){return this.vm}getContext(){return this.context}getScopeManager(){return this.scopeManager}getLexer(){return this.lexer}getNormalizer(){return this.normalizer}getPackageCompletionItems(){let e=[];for(let t of this.packageCompletionItems.values())e.push(...t);return e}getParseletRegistry(){return {prefix:this.registry.getAllPrefix(),infix:this.registry.getAllInfix()}}tokenizeForClassification(e){this.lexer.resetExpression(e);let n=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return n.length===0?[]:this.normalizer.normalize(n)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?a$6.keystrokeSignalSet(e.aborted):a$6.keystrokeSignalCleared(),this.keystrokeSignal=e;}getCacheSnapshot(){let e=[];for(let[o,c]of this.bytecodeCache)e.push({expression:o,opcodesLength:c.opcodes.length,numbersLength:c.numbers.length,stringsLength:c.strings.length,hasAsync:c.hasAsync});let t=[];for(let o of this.lineCache.keys()){let c=o.indexOf(":"),l=c>0?parseInt(o.slice(0,c),10)||0:parseInt(o,10)||0,a=c>0?o.slice(c+1):void 0,u=a!==void 0?this.lineCache.get(l,a):this.lineCache.getEntryForLine(l);u&&t.push({key:o,lineNumber:l,resultType:String(u.result?.type??""),resultValue:String(u.result?.value??""),reads:u.readVariables??[],writeVar:u.writeVariable??null});}let s=this.queryClient.getQueryCache().getAll().map(o=>{let c=o.state.status==="success"?"resolved":o.state.status==="error"?"error":"in_flight";return {packageId:o.queryKey[0]??"unknown",resolvedCount:o.state.status==="success"?1:0,inFlightCount:o.state.status!=="success"&&o.state.status!=="error"?1:0,errorCount:o.state.status==="error"?1:0,entries:[{key:o.queryKey.join(":"),status:c}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e,void 0,false),n=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(n);return Ge({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode,readings:this.readDates(e)})}evaluateIsolated(e){let{tokens:t,hasParens:n$1}=this.lexToTokens(e),i=this.prepareExpression(e,t,n$1,void 0,-1);if(i.kind==="empty")return n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw c.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let t=this.lexToTokens(e),{hasParens:n}=t,i=this.prepareExpression(e,t.tokens,n),s=t.compiled&&i.kind==="ready"?i.normalizedTokens:t.tokens;if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new b$a(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:s,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens:n}=this.lexToTokens(e);return this.prepareExpression(e,t,n).kind!=="error"}executeCached(e,t=-1){if(e.opcodes.length===0)return n(0);let n$1=this.executeRaw(e,t);if(n$1.type==="pending")return this.resolveAsync(n$1),O(n$1.queryKey);if(n$1.type==="error")throw n$1.error;return n$1.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let n=this.evaluateLine(-1,e);return n.isFault()?NaN:n.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),b$b()===this.queryClient&&a$7(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.clearCompiledCache(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let a of Object.keys(e.dataSourceDeps)){let u=Number(a);Number.isNaN(u)||t.add(u);}let n=this.lineCache.snapshotEntries(),i=new Map;for(let{line:a,entry:u}of n){let p=t.has(a)||u.bytecode.hasAsync;p&&t.add(a);let f=u.writeVariable;if(f){let m=i.get(f);(!m||a>=m.line)&&i.set(f,{line:a,async:p});}}let s={};for(let[a,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(a)?.async)try{s[a]=Me(u,`variable "${a}"`);}catch(p){if(p instanceof b$a&&p.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(Ue),c=[];for(let{line:a,expression:u,entry:p}of n){if(t.has(a)||p.result.type===12)continue;let f;try{f=Me(p.result,`line ${a}`);}catch(m){if(m instanceof b$a&&m.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw m}c.push({line:a,expression:u,result:f,bytecode:ue(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let l=Array.from(this.bytecodeCache.entries()).map(([a,u])=>({expression:a,program:ue(u)}));return {format:ee,version:Q,engineVersion:a$1,locale:this.localeCode,variables:s,userFunctions:o,lineCache:c,bytecodeCache:l}}static fromJSON(e,t={}){rr(e);let n=t.locale??e.locale??"en",i=new Y({locale:n,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages,calendar:t.calendar});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,n]of Object.entries(e.variables))this.vm.setVar(t,Be(n));for(let t of e.userFunctions){let n=_e(t);this.vm.defineUserFunction(n.name,n.params,n.program);}for(let t of e.lineCache){let n=new K(Be(t.result),pe(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,n,t.expression),this.dag.registerLine(t.line,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:n}of e.bytecodeCache)this.bytecodeCache.set(t,pe(n));}evaluateIncremental(e,t){let n$1=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,n(t));let i=new Map;for(let s of n$1){let o=this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let c=this.executeRaw(o.bytecode,s);if(c.type==="pending"){this.resolveAsync(c);continue}if(c.type==="error"){let a=P(c.error.code,c.error.message);i.set(s,a),o.result=a;continue}let l=c.value;i.set(s,l),o.result=l;}return i}};Y.GOAL_SEEK_MAX_NESTING_DEPTH=1,Y.WARMUP_EXPRESSIONS=["1 + 2 * 3","10.5 / 2 - 0.25","50% of 200","3 kg + 400 g","sqrt(144) + max(1, 2)","1 < 2 && 3 >= 3","half of 250",'"text" + "joined"'];var vr=Y;export{Jr as a,Or as b,Qt as c,ee as d,Q as e,V as f,cn as g,Fe as h,ke as i,ze as j,$e as k,Ce as l,Cn as m,Tn as n,vr as o};//# sourceMappingURL=chunk-SNYFNARL.js.map
|
|
5
|
-
//# sourceMappingURL=chunk-SNYFNARL.js.map
|