solve-engine 2.38.14 → 2.38.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/{PackageCompatibility-ByCnkoxf.d.cts → PackageCompatibility-C-3vPMKp.d.cts} +1 -1
  2. package/dist/{PackageCompatibility-WzScL1Av.d.ts → PackageCompatibility-zdsKvwQI.d.ts} +1 -1
  3. package/dist/{PackageRegistry-11ThI3Qg.d.ts → PackageRegistry-CStmqgw_.d.ts} +1 -1
  4. package/dist/{PackageRegistry-BN4zOado.d.cts → PackageRegistry-DiHxyxrn.d.cts} +1 -1
  5. package/dist/{VMBuiltins-5ATHQ045.d.cts → VMBuiltins-BwqFO2TY.d.cts} +12 -0
  6. package/dist/{VMBuiltins-BbNZtVJc.d.ts → VMBuiltins-h09nijID.d.ts} +12 -0
  7. package/dist/chunk-44BWHZ5V.js +2 -0
  8. package/dist/chunk-44BWHZ5V.js.map +1 -0
  9. package/dist/{chunk-VR35R5MV.cjs → chunk-6UW4JJZV.cjs} +3 -3
  10. package/dist/chunk-6UW4JJZV.cjs.map +1 -0
  11. package/dist/{chunk-54MEZ574.cjs → chunk-A3CNNRFM.cjs} +2 -2
  12. package/dist/{chunk-54MEZ574.cjs.map → chunk-A3CNNRFM.cjs.map} +1 -1
  13. package/dist/{chunk-5M4F7PCU.js → chunk-BIV4K7B2.js} +2 -2
  14. package/dist/{chunk-5M4F7PCU.js.map → chunk-BIV4K7B2.js.map} +1 -1
  15. package/dist/chunk-ENLFOXF3.js +5 -0
  16. package/dist/chunk-ENLFOXF3.js.map +1 -0
  17. package/dist/chunk-HFES6BF5.cjs +2 -0
  18. package/dist/chunk-HFES6BF5.cjs.map +1 -0
  19. package/dist/chunk-ZGA7X625.cjs +5 -0
  20. package/dist/chunk-ZGA7X625.cjs.map +1 -0
  21. package/dist/chunk-ZYXFJ4X2.js +3 -0
  22. package/dist/chunk-ZYXFJ4X2.js.map +1 -0
  23. package/dist/constants.cjs +1 -1
  24. package/dist/constants.js +1 -1
  25. package/dist/engine.cjs +1 -1
  26. package/dist/engine.d.cts +4 -4
  27. package/dist/engine.d.ts +4 -4
  28. package/dist/engine.js +1 -1
  29. package/dist/engine.worker.cjs +1 -1
  30. package/dist/engine.worker.js +1 -1
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.d.cts +4 -4
  33. package/dist/index.d.ts +4 -4
  34. package/dist/index.js +1 -1
  35. package/dist/language.d.cts +3 -3
  36. package/dist/language.d.ts +3 -3
  37. package/dist/packages.d.cts +2 -2
  38. package/dist/packages.d.ts +2 -2
  39. package/dist/testing.cjs +2 -2
  40. package/dist/testing.d.cts +3 -3
  41. package/dist/testing.d.ts +3 -3
  42. package/dist/testing.js +1 -1
  43. package/dist/vm.cjs +1 -1
  44. package/dist/vm.d.cts +1 -1
  45. package/dist/vm.d.ts +1 -1
  46. package/dist/vm.js +1 -1
  47. package/dist/worker.cjs +2 -2
  48. package/dist/worker.d.cts +2 -2
  49. package/dist/worker.d.ts +2 -2
  50. package/dist/worker.js +1 -1
  51. package/package.json +1 -1
  52. package/dist/chunk-CH6NLOVG.js +0 -2
  53. package/dist/chunk-CH6NLOVG.js.map +0 -1
  54. package/dist/chunk-NGHH4QKV.js +0 -5
  55. package/dist/chunk-NGHH4QKV.js.map +0 -1
  56. package/dist/chunk-OXZWX5WY.cjs +0 -2
  57. package/dist/chunk-OXZWX5WY.cjs.map +0 -1
  58. package/dist/chunk-UM5A6VXI.js +0 -3
  59. package/dist/chunk-UM5A6VXI.js.map +0 -1
  60. package/dist/chunk-V52TAWYV.cjs +0 -5
  61. package/dist/chunk-V52TAWYV.cjs.map +0 -1
  62. package/dist/chunk-VR35R5MV.cjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ 'use strict';var f=class{constructor(t){this.checkpoints=[];this.vm=t;}snapshot(t,e,n){if(n.length===0)return null;let i=this.indexOfCheckpointAt(t),s=i>=0?i:this.insertionIndexFor(t),r=s>0?this.checkpoints[s-1]:null,h=Object.create(null),u=Object.create(null);for(let o of n){if(this.vm.hasUserFunction(o)){let l=this.vm.getUserFunction(o);l&&(u[o]=l);continue}let p=this.vm.getVar(o);p!==void 0&&(h[o]=p);}let c={lineNumber:t,lineId:e,variables:h,functions:u,parent:r};i>=0?this.checkpoints[i]=c:this.checkpoints.splice(s,0,c);let a=this.checkpoints[s+1];return a!==void 0&&(a.parent=c),c}restoreTo(t){let e=this.nearestCheckpointIndex(t);this.vm.reset();for(let n=0;n<=e;n++){let i=this.checkpoints[n];for(let s of Object.keys(i.variables))this.vm.setVar(s,i.variables[s]);for(let s of Object.keys(i.functions)){let r=i.functions[s];this.vm.defineUserFunction(r.name,r.params,r.program);}}}indexOfCheckpointAt(t){let e=this.nearestCheckpointIndex(t);return e>=0&&this.checkpoints[e].lineNumber===t?e:-1}insertionIndexFor(t){return this.nearestCheckpointIndex(t)+1}nearestCheckpointIndex(t){let e=0,n=this.checkpoints.length-1,i=-1;for(;e<=n;){let s=e+n>>1;this.checkpoints[s].lineNumber<=t?(i=s,e=s+1):n=s-1;}return i}updateCheckpointAt(t,e){let n=this.getCheckpointAt(t);if(!n)return false;for(let i of e){if(this.vm.hasUserFunction(i)){let r=this.vm.getUserFunction(i);r&&(n.functions[i]=r);continue}let s=this.vm.getVar(i);s!==void 0&&(n.variables[i]=s);}return true}applyCheckpointAt(t){let e=this.getCheckpointAt(t);if(!e)return false;for(let n of Object.keys(e.variables))this.vm.setVar(n,e.variables[n]);for(let n of Object.keys(e.functions)){let i=e.functions[n];this.vm.defineUserFunction(i.name,i.params,i.program);}return true}getNearestCheckpoint(t){let e=this.nearestCheckpointIndex(t);return e<0?null:this.checkpoints[e]}getCheckpointAt(t){let e=this.nearestCheckpointIndex(t);if(e<0)return;let n=this.checkpoints[e];return n.lineNumber===t?n:void 0}getAllCheckpoints(){return this.checkpoints}lookupVariable(t){if(this.checkpoints.length===0)return;let e=this.checkpoints[this.checkpoints.length-1];for(;e;){if(Object.prototype.hasOwnProperty.call(e.variables,t))return e.variables[t];e=e.parent;}}clear(){this.checkpoints=[];}get count(){return this.checkpoints.length}get isEmpty(){return this.checkpoints.length===0}get vmInstance(){return this.vm}};exports.a=f;//# sourceMappingURL=chunk-HFES6BF5.cjs.map
2
+ //# sourceMappingURL=chunk-HFES6BF5.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","existing","insertAt","parent","variables","functions","name","fn","val","checkpoint","next","targetIndex","i","cp","key","index","low","high","result","mid","value","candidate"],"mappings":"aAuFO,IAAMA,CAAAA,CAAN,KAAqB,CAM3B,WAAA,CAAYC,CAAAA,CAAQ,CAJpB,IAAA,CAAQ,WAAA,CAA8B,EAAC,CAKtC,IAAA,CAAK,EAAA,CAAKA,EACX,CAqBA,QAAA,CACCC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACsB,CACtB,GAAIA,CAAAA,CAAc,MAAA,GAAW,CAAA,CAAG,OAAO,IAAA,CAqBvC,IAAMC,CAAAA,CAAW,IAAA,CAAK,mBAAA,CAAoBH,CAAU,CAAA,CAC9CI,CAAAA,CAAWD,CAAAA,EAAY,CAAA,CAAIA,CAAAA,CAAW,IAAA,CAAK,iBAAA,CAAkBH,CAAU,CAAA,CACvEK,CAAAA,CAASD,CAAAA,CAAW,CAAA,CAAI,IAAA,CAAK,WAAA,CAAYA,CAAAA,CAAW,CAAC,CAAA,CAAI,IAAA,CAgBzDE,CAAAA,CAAmC,MAAA,CAAO,MAAA,CAAO,IAAI,CAAA,CACrDC,CAAAA,CAA6C,MAAA,CAAO,MAAA,CAAO,IAAI,CAAA,CAMrE,IAAA,IAAWC,CAAAA,IAAQN,EAAe,CACjC,GAAI,IAAA,CAAK,EAAA,CAAG,eAAA,CAAgBM,CAAI,CAAA,CAAG,CAClC,IAAMC,CAAAA,CAAK,IAAA,CAAK,EAAA,CAAG,eAAA,CAAgBD,CAAI,CAAA,CACnCC,CAAAA,GAAIF,CAAAA,CAAUC,CAAI,CAAA,CAAIC,CAAAA,CAAAA,CAC1B,QACD,CACA,IAAMC,CAAAA,CAAM,IAAA,CAAK,EAAA,CAAG,MAAA,CAAOF,CAAI,CAAA,CAC3BE,CAAAA,GAAQ,MAAA,GACXJ,CAAAA,CAAUE,CAAI,CAAA,CAAIE,CAAAA,EAEpB,CAEA,IAAMC,CAAAA,CAA2B,CAChC,UAAA,CAAAX,CAAAA,CACA,MAAA,CAAAC,CAAAA,CACA,SAAA,CAAAK,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,MAAA,CAAAF,CACD,CAAA,CACIF,CAAAA,EAAY,CAAA,CAAG,IAAA,CAAK,WAAA,CAAYA,CAAQ,CAAA,CAAIQ,CAAAA,CAC3C,IAAA,CAAK,WAAA,CAAY,MAAA,CAAOP,CAAAA,CAAU,CAAA,CAAGO,CAAU,CAAA,CAEpD,IAAMC,CAAAA,CAAO,IAAA,CAAK,WAAA,CAAYR,CAAAA,CAAW,CAAC,CAAA,CAC1C,OAAIQ,CAAAA,GAAS,MAAA,GAAWA,CAAAA,CAAK,MAAA,CAASD,CAAAA,CAAAA,CAC/BA,CACR,CAqBA,SAAA,CAAUX,CAAAA,CAA0B,CAgBnC,IAAMa,CAAAA,CAAc,IAAA,CAAK,sBAAA,CAAuBb,CAAU,CAAA,CAE1D,IAAA,CAAK,EAAA,CAAG,KAAA,EAAM,CACd,IAAA,IAASc,CAAAA,CAAI,CAAA,CAAGA,CAAAA,EAAKD,CAAAA,CAAaC,CAAAA,EAAAA,CAAK,CACtC,IAAMC,CAAAA,CAAK,IAAA,CAAK,WAAA,CAAYD,CAAC,CAAA,CAG7B,IAAA,IAAWE,CAAAA,IAAO,MAAA,CAAO,IAAA,CAAKD,CAAAA,CAAG,SAAS,CAAA,CACzC,IAAA,CAAK,EAAA,CAAG,MAAA,CAAOC,CAAAA,CAAKD,CAAAA,CAAG,SAAA,CAAUC,CAAG,CAAC,CAAA,CAKtC,IAAA,IAAWA,CAAAA,IAAO,MAAA,CAAO,IAAA,CAAKD,CAAAA,CAAG,SAAS,CAAA,CAAG,CAC5C,IAAMN,CAAAA,CAAKM,CAAAA,CAAG,SAAA,CAAUC,CAAG,CAAA,CAC3B,IAAA,CAAK,EAAA,CAAG,kBAAA,CAAmBP,CAAAA,CAAG,IAAA,CAAMA,CAAAA,CAAG,MAAA,CAAQA,CAAAA,CAAG,OAAO,EAC1D,CACD,CACD,CAGQ,mBAAA,CAAoBT,CAAAA,CAA4B,CACvD,IAAMiB,CAAAA,CAAQ,IAAA,CAAK,sBAAA,CAAuBjB,CAAU,CAAA,CACpD,OAAOiB,CAAAA,EAAS,CAAA,EAAK,IAAA,CAAK,WAAA,CAAYA,CAAK,CAAA,CAAE,UAAA,GAAejB,CAAAA,CAAaiB,CAAAA,CAAQ,EAClF,CAGQ,iBAAA,CAAkBjB,CAAAA,CAA4B,CACrD,OAAO,IAAA,CAAK,sBAAA,CAAuBA,CAAU,CAAA,CAAI,CAClD,CASQ,sBAAA,CAAuBA,CAAAA,CAA4B,CAC1D,IAAIkB,CAAAA,CAAM,CAAA,CACNC,CAAAA,CAAO,IAAA,CAAK,WAAA,CAAY,MAAA,CAAS,CAAA,CACjCC,CAAAA,CAAS,EAAA,CACb,KAAOF,CAAAA,EAAOC,GAAM,CACnB,IAAME,CAAAA,CAAOH,CAAAA,CAAMC,CAAAA,EAAS,CAAA,CACxB,IAAA,CAAK,WAAA,CAAYE,CAAG,CAAA,CAAE,UAAA,EAAcrB,CAAAA,EACvCoB,CAAAA,CAASC,CAAAA,CACTH,CAAAA,CAAMG,CAAAA,CAAM,CAAA,EAEZF,CAAAA,CAAOE,CAAAA,CAAM,EAEf,CACA,OAAOD,CACR,CAqBA,kBAAA,CAAmBpB,CAAAA,CAAoBE,CAAAA,CAAkC,CACxE,IAAMS,CAAAA,CAAa,IAAA,CAAK,eAAA,CAAgBX,CAAU,CAAA,CAClD,GAAI,CAACW,CAAAA,CAAY,OAAO,MAAA,CACxB,IAAA,IAAWH,CAAAA,IAAQN,CAAAA,CAAe,CACjC,GAAI,IAAA,CAAK,EAAA,CAAG,eAAA,CAAgBM,CAAI,CAAA,CAAG,CAClC,IAAMC,CAAAA,CAAK,IAAA,CAAK,EAAA,CAAG,eAAA,CAAgBD,CAAI,CAAA,CACnCC,CAAAA,GAAIE,CAAAA,CAAW,SAAA,CAAUH,CAAI,CAAA,CAAIC,CAAAA,CAAAA,CACrC,QACD,CACA,IAAMa,CAAAA,CAAQ,IAAA,CAAK,EAAA,CAAG,MAAA,CAAOd,CAAI,CAAA,CAC7Bc,CAAAA,GAAU,MAAA,GAAWX,CAAAA,CAAW,SAAA,CAAUH,CAAI,CAAA,CAAIc,CAAAA,EACvD,CACA,OAAO,KACR,CAeA,iBAAA,CAAkBtB,CAAAA,CAA6B,CAC9C,IAAMW,CAAAA,CAAa,IAAA,CAAK,eAAA,CAAgBX,CAAU,CAAA,CAClD,GAAI,CAACW,CAAAA,CAAY,OAAO,MAAA,CACxB,IAAA,IAAWK,CAAAA,IAAO,MAAA,CAAO,IAAA,CAAKL,CAAAA,CAAW,SAAS,CAAA,CACjD,IAAA,CAAK,EAAA,CAAG,MAAA,CAAOK,CAAAA,CAAKL,CAAAA,CAAW,SAAA,CAAUK,CAAG,CAAC,CAAA,CAE9C,IAAA,IAAWA,CAAAA,IAAO,MAAA,CAAO,IAAA,CAAKL,CAAAA,CAAW,SAAS,CAAA,CAAG,CACpD,IAAMF,CAAAA,CAAKE,CAAAA,CAAW,SAAA,CAAUK,CAAG,CAAA,CACnC,IAAA,CAAK,EAAA,CAAG,mBAAmBP,CAAAA,CAAG,IAAA,CAAMA,CAAAA,CAAG,MAAA,CAAQA,CAAAA,CAAG,OAAO,EAC1D,CACA,OAAO,KACR,CAaA,oBAAA,CAAqBT,CAAAA,CAAyC,CAC7D,IAAMiB,CAAAA,CAAQ,IAAA,CAAK,sBAAA,CAAuBjB,CAAU,CAAA,CACpD,OAAOiB,CAAAA,CAAQ,CAAA,CAAI,IAAA,CAAO,IAAA,CAAK,WAAA,CAAYA,CAAK,CACjD,CAMA,eAAA,CAAgBjB,CAAAA,CAA8C,CAG7D,IAAMiB,CAAAA,CAAQ,IAAA,CAAK,sBAAA,CAAuBjB,CAAU,CAAA,CACpD,GAAIiB,CAAAA,CAAQ,CAAA,CAAG,OACf,IAAMM,CAAAA,CAAY,IAAA,CAAK,WAAA,CAAYN,CAAK,CAAA,CACxC,OAAOM,CAAAA,CAAU,UAAA,GAAevB,CAAAA,CAAauB,CAAAA,CAAY,MAC1D,CAMA,iBAAA,EAA6C,CAC5C,OAAO,IAAA,CAAK,WACb,CAgBA,cAAA,CAAef,CAAAA,CAAiC,CAC/C,GAAI,IAAA,CAAK,WAAA,CAAY,MAAA,GAAW,CAAA,CAAG,OAEnC,IAAIG,CAAAA,CAAkC,IAAA,CAAK,WAAA,CAAY,IAAA,CAAK,WAAA,CAAY,MAAA,CAAS,CAAC,CAAA,CAClF,KAAOA,CAAAA,EAAY,CAClB,GAAI,MAAA,CAAO,SAAA,CAAU,cAAA,CAAe,IAAA,CAAKA,CAAAA,CAAW,SAAA,CAAWH,CAAI,CAAA,CAClE,OAAOG,CAAAA,CAAW,SAAA,CAAUH,CAAI,CAAA,CAEjCG,CAAAA,CAAaA,EAAW,OACzB,CAED,CAQA,KAAA,EAAc,CACb,IAAA,CAAK,WAAA,CAAc,GACpB,CAGA,IAAI,KAAA,EAAgB,CACnB,OAAO,IAAA,CAAK,WAAA,CAAY,MACzB,CAGA,IAAI,OAAA,EAAmB,CACtB,OAAO,IAAA,CAAK,WAAA,CAAY,MAAA,GAAW,CACpC,CAGA,IAAI,UAAA,EAAiB,CACpB,OAAO,IAAA,CAAK,EACb,CACD","file":"chunk-HFES6BF5.cjs","sourcesContent":["import { Value } from \"@solve-js/vm/Value\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\nimport type { UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\n\n// ── VMCheckpoint ────────────────────────────────────────────────────────\n\n/**\n * A point-in-time snapshot of VM variable state.\n *\n * Each checkpoint holds only the variables that CHANGED at its line, and\n * reaches the rest through its `parent` link. A lookup walks that chain until\n * it finds the name; a restore walks it from the root applying each link's own\n * bindings in turn, so a later line's value naturally overwrites an earlier\n * one's.\n *\n * ```text\n * Checkpoint 0 (root): {} // empty scope\n * Checkpoint 1 (:x=5): { x: 5 } parent → 0\n * Checkpoint 2 (:y=8): { y: 8 } parent → 1\n * Checkpoint 3 (:x=3): { x: 3 } parent → 2 // shadows x=5\n * ```\n *\n * To look up `x` at checkpoint 3: find own `x=3` → done.\n * To look up `y` at checkpoint 3: not own → walk parent to checkpoint 2 → `y=8`.\n * To look up `z` at checkpoint 3: not found anywhere → undefined.\n *\n * **Memory:** O(number of variable definitions) heap, independent of\n * document length. Typical Obsidian documents have < 100 variable defs,\n * so total checkpoint heap is < 10 KB.\n */\nexport interface VMCheckpoint {\n\t/** 1-based line number where this checkpoint was created. */\n\tlineNumber: number;\n\t/** Persistent line ID from DocumentModel. */\n\tlineId: number;\n\t/**\n\t * Variable name → Value at this checkpoint.\n\t * Only the variables set or updated at this line; the rest are reached\n\t * through {@link VMCheckpoint.parent}.\n\t */\n\tvariables: Record<string, Value>;\n\t/**\n\t * User-defined-function name → definition at this checkpoint. SEPARATE\n\t * from `variables` above (not prototypally chained the same way\n\t * `restoreTo()` replays every checkpoint in the chain in order, so a\n\t * later redefinition of the same function name naturally overwrites an\n\t * earlier one during replay, without needing its own prototype walk).\n\t *\n\t * Without this field, a function definition's checkpoint entry would be\n\t * SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every\n\t * written name, which returns `undefined` for a function name (function\n\t * defs live in `vm.userFunctions`, not the flat variable store), and a\n\t * `val !== undefined` guard silently skipped it. A scroll-triggered\n\t * `restoreTo()` would then reset the VM and replay only `variables`,\n\t * making a function defined above the new viewport vanish (calling it\n\t * would throw `UNDEFINED_FUNCTION`) even though the document still\n\t * shows its definition line as clean/cached.\n\t */\n\tfunctions: Record<string, UserFunctionDef>;\n\t/** Parent checkpoint (closer to document start), or null for root. */\n\tparent: VMCheckpoint | null;\n}\n\n// ── VMCheckpointer ──────────────────────────────────────────────────────\n\n/**\n * Manages VM state checkpoints for the three-tier evaluation strategy.\n *\n * **Checkpoint creation:** After a variable-definition line executes\n * (Tier 1 or Tier 3), `snapshot()` records the current values of the\n * written variables. The checkpoint is linked via prototypal inheritance\n * to the previous checkpoint, so only changed variables consume memory.\n *\n * **Checkpoint restoration:** Before evaluating a viewport whose start line\n * is not line 1, `restoreTo(lineNumber)` resets the VM and replays all\n * variable definitions up to and including that line. This avoids\n * re-evaluating the entire document from line 1 on every scroll.\n *\n * **Thread safety:** Checkpoints are created synchronously on the main\n * thread during evaluation. They are immutable after creation (Value is\n * an immutable type), so no synchronization is needed.\n *\n * **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`\n * to find the checkpoint just before the new viewport start, then call\n * `restoreTo()` to set up the VM before evaluating only the visible lines.\n * This is the key to O(visible lines) scrolling instead of O(document).\n */\nexport class VMCheckpointer {\n\t/** Ordered array of checkpoints (ascending lineNumber). */\n\tprivate checkpoints: VMCheckpoint[] = [];\n\t/** The VM instance whose variables are snapshotted/restored. */\n\tprivate vm: VM;\n\n\tconstructor(vm: VM) {\n\t\tthis.vm = vm;\n\t}\n\n\t// ── Snapshot ─────────────────────────────────────────────────────\n\n\t/**\n\t * Create a checkpoint at the current line, recording the VM values of\n\t * the specified variables.\n\t *\n\t * Records only what this line wrote; the rest is reached through the\n\t * parent link rather than copied.\n\t *\n\t * A line that is snapshotted again drops every checkpoint at or after it\n\t * first, so the list stays in document order and the new checkpoint\n\t * inherits from the line before it rather than from one after it. See the\n\t * body for what went wrong without that.\n\t *\n\t * @param lineNumber 1-based line position.\n\t * @param lineId Persistent line ID from DocumentModel.\n\t * @param variableNames Names of variables that were written at this line.\n\t * @returns The new checkpoint, or null if no variable names provided.\n\t */\n\tsnapshot(\n\t\tlineNumber: number,\n\t\tlineId: number,\n\t\tvariableNames: string[]\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\t// This line's own entry is replaced, and nothing else is touched.\n\t\t//\n\t\t// The list is a sequence of document positions and `restoreTo` reads it\n\t\t// as one, so a re-run must not append after entries that come later in\n\t\t// the document: editing line 2 of a document whose lines 1, 2 and 3 each\n\t\t// define something left the list as [1, 2, 3, 2], and a restore to line\n\t\t// 2 then found the stale entry.\n\t\t//\n\t\t// Replacing rather than truncating is the part that took a second go.\n\t\t// Dropping every entry at or after the line is sound only for a pass\n\t\t// running from line 1, which re-takes them as it continues. A pass\n\t\t// limited to a viewport does not: it re-snapshots the top of the\n\t\t// document and never reaches the definitions below its end line, so the\n\t\t// chain lost them, and `restoreTo` then RESET the VM and replayed a\n\t\t// prefix that no longer mentioned them. A line further down reading one\n\t\t// answered `Undefined variable` where it had answered a number. Absent\n\t\t// is worse than stale here: a stale entry is what the document is\n\t\t// currently showing anyway, and the pass corrects it when it reaches\n\t\t// that line.\n\t\tconst existing = this.indexOfCheckpointAt(lineNumber);\n\t\tconst insertAt = existing >= 0 ? existing : this.insertionIndexFor(lineNumber);\n\t\tconst parent = insertAt > 0 ? this.checkpoints[insertAt - 1] : null;\n\n\t\t// Each checkpoint holds only what its line wrote, and reaches the rest\n\t\t// through `parent`. It used to reach it through the prototype chain\n\t\t// instead, which held the same entries and cost the same memory, and\n\t\t// made the chain as deep as the document has definitions: a null\n\t\t// prototype is a flat object, and one per definition is a chain two\n\t\t// thousand deep on a document of two thousand definitions. Creating and\n\t\t// reading those took a pass over such a document from 6.0 ms to 23.1 ms.\n\t\t//\n\t\t// Nothing needed the inheritance. `restoreTo` walks `parent` and applies\n\t\t// each checkpoint's OWN keys, which is the same set either way, and the\n\t\t// one reader that did walk the prototype now walks `parent` too.\n\t\t//\n\t\t// Null-prototyped rather than `{}`, so a variable named `constructor` or\n\t\t// `toString` is a key like any other.\n\t\tconst variables: Record<string, Value> = Object.create(null) as Record<string, Value>;\n\t\tconst functions: Record<string, UserFunctionDef> = Object.create(null) as Record<string, UserFunctionDef>;\n\n\t\t// Record current VM values for the written names, routing each into\n\t\t// the right bag (a name is either a variable or a user-defined\n\t\t// function, never both; see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional).\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst val = this.vm.getVar(name);\n\t\t\tif (val !== undefined) {\n\t\t\t\tvariables[name] = val;\n\t\t\t}\n\t\t}\n\n\t\tconst checkpoint: VMCheckpoint = {\n\t\t\tlineNumber,\n\t\t\tlineId,\n\t\t\tvariables,\n\t\t\tfunctions,\n\t\t\tparent,\n\t\t};\n\t\tif (existing >= 0) this.checkpoints[existing] = checkpoint;\n\t\telse this.checkpoints.splice(insertAt, 0, checkpoint);\n\t\t// The entry after this one now follows a different object.\n\t\tconst next = this.checkpoints[insertAt + 1];\n\t\tif (next !== undefined) next.parent = checkpoint;\n\t\treturn checkpoint;\n\t}\n\n\t// ── Restore ──────────────────────────────────────────────────────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,\n\t * then replays all variable definitions from root → that checkpoint\n\t * into the VM via `setVar()`. The VM's stack is also reset.\n\t *\n\t * If no checkpoint exists at or before the target line, the VM is\n\t * fully reset (empty scope, empty stack).\n\t *\n\t * **Performance:** O(total variable definitions before the line), since\n\t * each checkpoint in the chain contributes only the names its own line\n\t * wrote.\n\t *\n\t * @param lineNumber Target 1-based line number. The VM will have the\n\t * state that existed AFTER evaluating lines up to `lineNumber`.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\t// The chain from the root to the target IS the array up to that index.\n\t\t//\n\t\t// Every checkpoint is created with the one before it in the array as its\n\t\t// parent (see {@link snapshot}), and the array is kept in document\n\t\t// order, so walking parent links would visit exactly these entries in\n\t\t// exactly this order. Reading the array instead of the links costs no\n\t\t// allocation, and it was the links that made this quadratic: the walk\n\t\t// runs target-to-root, so the chain was assembled by `unshift`ing each\n\t\t// entry onto the front, which shifts every entry already there. A\n\t\t// document with two thousand definitions did four million shifts per\n\t\t// restore, and a scroll restores.\n\t\t//\n\t\t// `CheckpointsStayInDocumentOrder.spec.ts` asserts the invariant this\n\t\t// relies on, so a change that broke it would fail there rather than\n\t\t// quietly restoring the wrong state here.\n\t\tconst targetIndex = this.nearestCheckpointIndex(lineNumber);\n\n\t\tthis.vm.reset();\n\t\tfor (let i = 0; i <= targetIndex; i++) {\n\t\t\tconst cp = this.checkpoints[i];\n\t\t\t// Only the names this checkpoint's own line wrote; the ones before\n\t\t\t// it are applied by their own entries earlier in this same walk.\n\t\t\tfor (const key of Object.keys(cp.variables)) {\n\t\t\t\tthis.vm.setVar(key, cp.variables[key]);\n\t\t\t}\n\t\t\t// Replay function definitions the same way, a later checkpoint's\n\t\t\t// redefinition of the same name naturally overwrites an earlier\n\t\t\t// one since the walk runs root-to-target.\n\t\t\tfor (const key of Object.keys(cp.functions)) {\n\t\t\t\tconst fn = cp.functions[key];\n\t\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The index of the checkpoint recorded exactly at `lineNumber`, or -1. */\n\tprivate indexOfCheckpointAt(lineNumber: number): number {\n\t\tconst index = this.nearestCheckpointIndex(lineNumber);\n\t\treturn index >= 0 && this.checkpoints[index].lineNumber === lineNumber ? index : -1;\n\t}\n\n\t/** Where a checkpoint for `lineNumber` belongs, keeping the list in order. */\n\tprivate insertionIndexFor(lineNumber: number): number {\n\t\treturn this.nearestCheckpointIndex(lineNumber) + 1;\n\t}\n\n\t/**\n\t * The index of the last checkpoint at or before `lineNumber`, or -1.\n\t *\n\t * A binary search rather than a scan. The array is in document order, and\n\t * this is asked once per scroll and once per async batch, on a document\n\t * that can hold a checkpoint per definition.\n\t */\n\tprivate nearestCheckpointIndex(lineNumber: number): number {\n\t\tlet low = 0;\n\t\tlet high = this.checkpoints.length - 1;\n\t\tlet result = -1;\n\t\twhile (low <= high) {\n\t\t\tconst mid = (low + high) >> 1;\n\t\t\tif (this.checkpoints[mid].lineNumber <= lineNumber) {\n\t\t\t\tresult = mid;\n\t\t\t\tlow = mid + 1;\n\t\t\t} else {\n\t\t\t\thigh = mid - 1;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Record what `lineNumber` has just written, without disturbing the chain\n\t * after it.\n\t *\n\t * {@link snapshot} drops every checkpoint at or after the line, which is\n\t * right for a pass running forward in document order: it re-takes them as it\n\t * goes. A caller re-running a few lines out of a document does not, and\n\t * dropping the entries for lines it will never visit would lose the very\n\t * bindings it is sweeping through them to collect. So this overwrites in\n\t * place instead.\n\t *\n\t * Safe against the prototype chain, because it replaces only the\n\t * checkpoint's OWN bindings: a later checkpoint that also writes the name\n\t * holds its own copy and goes on shadowing this one.\n\t *\n\t * @param lineNumber 1-based line whose recorded bindings are refreshed.\n\t * @param variableNames The names it wrote.\n\t * @returns Whether a checkpoint existed at that line to update.\n\t */\n\tupdateCheckpointAt(lineNumber: number, variableNames: string[]): boolean {\n\t\tconst checkpoint = this.getCheckpointAt(lineNumber);\n\t\tif (!checkpoint) return false;\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) checkpoint.functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst value = this.vm.getVar(name);\n\t\t\tif (value !== undefined) checkpoint.variables[name] = value;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Apply the bindings recorded AT `lineNumber`, leaving the rest of the VM\n\t * alone.\n\t *\n\t * {@link restoreTo} rebuilds the whole prefix, which costs the chain every\n\t * time it is called. A caller moving forward through the document already\n\t * holds the prefix up to the line before, and needs only what this line\n\t * added: restoring once and then applying each line in turn as it is passed\n\t * costs the chain once rather than once per line.\n\t *\n\t * @param lineNumber 1-based line whose own bindings are applied.\n\t * @returns Whether a checkpoint existed at that line.\n\t */\n\tapplyCheckpointAt(lineNumber: number): boolean {\n\t\tconst checkpoint = this.getCheckpointAt(lineNumber);\n\t\tif (!checkpoint) return false;\n\t\tfor (const key of Object.keys(checkpoint.variables)) {\n\t\t\tthis.vm.setVar(key, checkpoint.variables[key]);\n\t\t}\n\t\tfor (const key of Object.keys(checkpoint.functions)) {\n\t\t\tconst fn = checkpoint.functions[key];\n\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t}\n\t\treturn true;\n\t}\n\n\t// ── Queries ──────────────────────────────────────────────────────\n\n\t/**\n\t * Find the nearest checkpoint at or before the given line number.\n\t *\n\t * Uses linear scan (checkpoints are sorted by lineNumber and the list\n\t * is short, typically < 20 for Obsidian documents). Can be upgraded\n\t * to binary search if needed for documents with 1000+ variable defs.\n\t *\n\t * @returns The nearest checkpoint, or null if none exists before the line.\n\t */\n\tgetNearestCheckpoint(lineNumber: number): VMCheckpoint | null {\n\t\tconst index = this.nearestCheckpointIndex(lineNumber);\n\t\treturn index < 0 ? null : this.checkpoints[index];\n\t}\n\n\t/**\n\t * Get a specific checkpoint by its line number.\n\t * @returns The checkpoint, or undefined if not found.\n\t */\n\tgetCheckpointAt(lineNumber: number): VMCheckpoint | undefined {\n\t\t// Searched, not scanned: the async sweep asks this once for every line\n\t\t// it walks past, and a scan would make that walk quadratic.\n\t\tconst index = this.nearestCheckpointIndex(lineNumber);\n\t\tif (index < 0) return undefined;\n\t\tconst candidate = this.checkpoints[index];\n\t\treturn candidate.lineNumber === lineNumber ? candidate : undefined;\n\t}\n\n\t/**\n\t * Get the entire checkpoint chain from root to the last checkpoint.\n\t * Useful for debugging and serialization.\n\t */\n\tgetAllCheckpoints(): readonly VMCheckpoint[] {\n\t\treturn this.checkpoints;\n\t}\n\n\t/**\n\t * Look up a variable's value through the checkpoint chain.\n\t *\n\t * Walks the prototype chain starting from the most recent checkpoint,\n\t * looking for the variable name as an own property. This is O(depth)\n\t * where depth is the number of checkpoints since the variable was\n\t * last set.\n\t *\n\t * **Note:** This queries the checkpointer's snapshot, not the VM.\n\t * The VM may have been modified since the last snapshot (e.g., by\n\t * Tier 2 execution of non-variable-def lines that don't create checkpoints).\n\t *\n\t * @returns The Value, or undefined if the variable was never set.\n\t */\n\tlookupVariable(name: string): Value | undefined {\n\t\tif (this.checkpoints.length === 0) return undefined;\n\n\t\tlet checkpoint: VMCheckpoint | null = this.checkpoints[this.checkpoints.length - 1];\n\t\twhile (checkpoint) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(checkpoint.variables, name)) {\n\t\t\t\treturn checkpoint.variables[name];\n\t\t\t}\n\t\t\tcheckpoint = checkpoint.parent;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────\n\n\t/**\n\t * Clear all checkpoints. The underlying VM is NOT reset, call\n\t * `vm.reset()` separately if needed.\n\t */\n\tclear(): void {\n\t\tthis.checkpoints = [];\n\t}\n\n\t/** Number of checkpoints stored. */\n\tget count(): number {\n\t\treturn this.checkpoints.length;\n\t}\n\n\t/** Returns true if no checkpoints have been created. */\n\tget isEmpty(): boolean {\n\t\treturn this.checkpoints.length === 0;\n\t}\n\n\t/** The associated VM instance. */\n\tget vmInstance(): VM {\n\t\treturn this.vm;\n\t}\n}\n"]}
@@ -0,0 +1,5 @@
1
+ 'use strict';var chunkP5YWBIIU_cjs=require('./chunk-P5YWBIIU.cjs'),chunkR3W53ZMP_cjs=require('./chunk-R3W53ZMP.cjs'),chunkTTFO4YDP_cjs=require('./chunk-TTFO4YDP.cjs'),chunkDTOSRC6E_cjs=require('./chunk-DTOSRC6E.cjs'),chunkHG4NPDN5_cjs=require('./chunk-HG4NPDN5.cjs'),chunkJUIHUG4M_cjs=require('./chunk-JUIHUG4M.cjs'),chunkU54BIYXO_cjs=require('./chunk-U54BIYXO.cjs'),chunkK3PZ66XR_cjs=require('./chunk-K3PZ66XR.cjs'),chunkYV4GDW5A_cjs=require('./chunk-YV4GDW5A.cjs'),chunkUURM7P3P_cjs=require('./chunk-UURM7P3P.cjs'),chunkZLRJ7TDP_cjs=require('./chunk-ZLRJ7TDP.cjs'),chunk6ADFAXTZ_cjs=require('./chunk-6ADFAXTZ.cjs'),chunk5N4XDULO_cjs=require('./chunk-5N4XDULO.cjs'),chunkEQNKDTMX_cjs=require('./chunk-EQNKDTMX.cjs'),chunkNH74IT7B_cjs=require('./chunk-NH74IT7B.cjs'),chunkA3CNNRFM_cjs=require('./chunk-A3CNNRFM.cjs'),chunk3MG7VIPL_cjs=require('./chunk-3MG7VIPL.cjs'),chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),chunk72J5V7SN_cjs=require('./chunk-72J5V7SN.cjs'),chunkYBQOQTVL_cjs=require('./chunk-YBQOQTVL.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs'),chunk6SYU4MH7_cjs=require('./chunk-6SYU4MH7.cjs');function Yt(n,e,t,r,i){let s=t[e],o=r[e];if(!s||!o)return;let c=new Set(Object.keys(s));for(let a of Object.keys(o))c.has(a)&&i.push({kind:n,severity:"warning",detail:`Both "${t.name}" and "${r.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${a}" \u2014 the later-registered one silently wins.`,packages:[t.name,r.name]});}function Qt(n,e){let t=[];if(Yt("prefixParseletTokenType","prefixParselets",n,e,t),Yt("infixParseletTokenType","infixParselets",n,e,t),n.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let c=n.phrases[s];c!==void 0&&c!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${n.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:[n.name,e.name]});}if(n.asConverters&&e.asConverters)for(let s of Object.keys(e.asConverters)){let o=s.toLowerCase();Object.keys(n.asConverters).some(c=>c.toLowerCase()===o)&&t.push({kind:"converterName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register an "as ${s}" converter \u2014 the later-registered handler silently wins.`,packages:[n.name,e.name]});}if(n.pluginFunctions&&e.pluginFunctions){let s=new Set(Object.keys(n.pluginFunctions));for(let o of Object.keys(e.pluginFunctions))s.has(o)&&t.push({kind:"pluginFunctionName",severity:"warning",detail:`Both "${n.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:[n.name,e.name]});}if(n.normalizerRules&&e.normalizerRules){let s=new Set(n.normalizerRules.map(o=>o.name));for(let o of e.normalizerRules)s.has(o.name)&&t.push({kind:"normalizerRuleName",severity:"warning",detail:`Both "${n.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:[n.name,e.name]});}let r=n.lexerVocabulary,i=e.lexerVocabulary;if(r?.keywords&&i?.keywords)for(let[s,o]of Object.entries(i.keywords)){let c=r.keywords[s];c!==void 0&&c!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${n.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:[n.name,e.name]});}if(r?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let c=r.operators[s];c!==void 0&&c!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${n.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer operator "${s}" for DIFFERENT token types.`,packages:[n.name,e.name]});}if(n.asyncResolvers&&e.asyncResolvers){let s=new Set(n.asyncResolvers.map(o=>o.namespace));for(let o of e.asyncResolvers)s.has(o.namespace)&&t.push({kind:"asyncResolverNamespace",severity:"error",detail:`Both "${n.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:[n.name,e.name]});}if(n.tokenCategories&&e.tokenCategories)for(let[s,o]of Object.entries(e.tokenCategories)){let c=n.tokenCategories[s];c!==void 0&&c!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${n.name}" (-> "${c}") and "${e.name}" (-> "${o}") declare a highlight category for token type "${s}" \u2014 cosmetic only, but the later registration wins.`,packages:[n.name,e.name]});}return t}function ir(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...Qt(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var be=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,r=(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))r(this.prefixOwners,s);if(e.infixParselets)for(let s of Object.keys(e.infixParselets))r(this.infixOwners,s);if(e.phrases)for(let s of Object.keys(e.phrases))r(this.phraseOwners,s);if(e.asConverters)for(let s of Object.keys(e.asConverters))r(this.converterOwners,s.toLowerCase());if(e.pluginFunctions)for(let s of Object.keys(e.pluginFunctions))r(this.pluginFnOwners,s);if(e.normalizerRules)for(let s of e.normalizerRules)r(this.ruleOwners,s.name);if(e.lexerVocabulary?.keywords)for(let s of Object.keys(e.lexerVocabulary.keywords))r(this.keywordOwners,s);if(e.lexerVocabulary?.operators)for(let s of Object.keys(e.lexerVocabulary.operators))r(this.operatorOwners,s);if(e.asyncResolvers)for(let s of e.asyncResolvers)r(this.resolverOwners,s.namespace);if(e.tokenCategories)for(let s of Object.keys(e.tokenCategories))r(this.categoryOwners,s);let i=[];for(let s of t)i.push(...Qt(s,e));return i}add(e){let t=(r,i)=>{r.has(i)||r.set(i,e);};if(e.prefixParselets)for(let r of Object.keys(e.prefixParselets))t(this.prefixOwners,r);if(e.infixParselets)for(let r of Object.keys(e.infixParselets))t(this.infixOwners,r);if(e.phrases)for(let r of Object.keys(e.phrases))t(this.phraseOwners,r);if(e.asConverters)for(let r of Object.keys(e.asConverters))t(this.converterOwners,r.toLowerCase());if(e.pluginFunctions)for(let r of Object.keys(e.pluginFunctions))t(this.pluginFnOwners,r);if(e.normalizerRules)for(let r of e.normalizerRules)t(this.ruleOwners,r.name);if(e.lexerVocabulary?.keywords)for(let r of Object.keys(e.lexerVocabulary.keywords))t(this.keywordOwners,r);if(e.lexerVocabulary?.operators)for(let r of Object.keys(e.lexerVocabulary.operators))t(this.operatorOwners,r);if(e.asyncResolvers)for(let r of e.asyncResolvers)t(this.resolverOwners,r.namespace);if(e.tokenCategories)for(let r of Object.keys(e.tokenCategories))t(this.categoryOwners,r);}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 Pn=/(\d+)\.(\d+)\.(\d+)/,Ln=/^\d+$/;function Xt(n){let e=Pn.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function On(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function Me(n){let e=n.split(".");if(e.length===0||e.length>3)return null;let t=[0,0,0];for(let r=0;r<e.length;r++){if(!Ln.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function In([n,e,t]){let r=n>0?[n+1,0,0]:e>0?[0,e+1,0]:[0,0,t+1];return [{op:">=",v:[n,e,t]},{op:"<",v:r}]}function Dn([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function Mn(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=Me(n.slice(1));return i&&In(i)}if(n[0]==="~"){let i=Me(n.slice(1));return i&&Dn(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=Me(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function Jt(n){let e=[];for(let t of n.split("||")){let r=t.trim().split(/\s+/).filter(s=>s!==""),i=[];for(let s of r){let o=Mn(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Zt(n){return Jt(n.trim())!==null}function Vn(n,e){let t=On(n,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 en(n,e){let t=Jt(e.trim());return t===null?false:t.some(r=>r.every(i=>Vn(n,i)))}function Bn(n,e=chunkA3CNNRFM_cjs.a){if(!n.engineVersion)return {compatible:true};if(!Zt(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=Xt(e);return t===null||!en(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function tn(n,e=chunkA3CNNRFM_cjs.a){let t=Bn(n,e);if(!t.compatible)throw t.reason==="invalid-range"?chunk6SYU4MH7_cjs.c.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${n.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 "${n.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:n.name,declaredRange:t.declaredRange}}):chunk6SYU4MH7_cjs.c.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${n.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 "${n.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:n.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var Z="solve-engine/snapshot",Q=1;function W(n){return Number.isFinite(n)?n:Number.isNaN(n)?"NaN":n>0?"Infinity":"-Infinity"}function $(n){if(typeof n=="number")return n;if(n==="NaN")return NaN;if(n==="Infinity")return 1/0;if(n==="-Infinity")return -1/0;throw chunk6SYU4MH7_cjs.c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds an unrecognised number sentinel: ${JSON.stringify(n)}`,expected:'a JSON number, or one of "NaN", "Infinity", "-Infinity"',found:JSON.stringify(n)})}var V={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function nn(n){return {coef:n.coef.toString(),scale:n.scale}}function rn(n){return {coef:BigInt(n.coef),scale:n.scale}}function Fn(n){return {n:n.n.toString(),d:n.d.toString()}}function _n(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function sn(n){return chunkNH74IT7B_cjs.g[n]??String(n)}function Ve(n,e){throw chunk6SYU4MH7_cjs.c.validation({code:V.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${sn(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${sn(n)} 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:n,location:e}})}function Be(n,e){switch(n.type){case 0:{let t={t:0,v:W(n.value)};return n.exact!==void 0&&(t.exact=nn(n.exact)),n.rational!==void 0&&(t.rational=Fn(n.rational)),t}case 1:{let t=n.value;return typeof t=="bigint"?{t:1,v:t.toString(),big:true,base:n.unit}:{t:1,v:W(t),base:n.unit}}case 2:return {t:2,v:n.value.toString()};case 3:return {t:3,v:n.value};case 4:{let t={t:4,v:W(n.value)};return n.grain!==void 0&&(t.g=n.grain),n.zone!==void 0&&(t.z=n.zone),t}case 5:return {t:5,v:W(n.value)};case 6:{let t={t:6,v:W(n.value),unit:n.unit??""};return n.exact!==void 0&&(t.exact=nn(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&Ve(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>Un(i,e));return {t:7,rows:t.rows,cols:t.cols,data:r}}case 8:{let t=n.value;return {t:8,min:W(t.min),max:W(t.max)}}case 10:return {t:10,v:n.value};case 13:return {t:13,code:n.value,message:n.unit??""};default:return Ve(n.type,e)}}function Un(n,e){return typeof n=="boolean"?n:typeof n=="number"?W(n):Ve(9,`${e} (symbolic matrix cell)`)}function Fe(n){switch(n.t){case 0:{let e=new chunkNH74IT7B_cjs.m(0,$(n.v));return n.exact!==void 0&&(e.exact=rn(n.exact)),n.rational!==void 0&&(e.rational=_n(n.rational)),e}case 1:{let e=n.big?BigInt(n.v):$(n.v);return new chunkNH74IT7B_cjs.m(1,e,n.base)}case 2:return new chunkNH74IT7B_cjs.m(2,BigInt(n.v));case 3:return new chunkNH74IT7B_cjs.m(3,n.v);case 4:{let e=new chunkNH74IT7B_cjs.m(4,$(n.v));return n.g!==void 0&&(e.grain=n.g),n.z!==void 0&&(e.zone=n.z),e}case 5:return new chunkNH74IT7B_cjs.m(5,$(n.v));case 6:{let e=new chunkNH74IT7B_cjs.m(6,$(n.v),n.unit);return n.exact!==void 0&&(e.exact=rn(n.exact)),e}case 7:{let e=n.data.map(r=>typeof r=="boolean"?r:$(r)),t={rows:n.rows,cols:n.cols,data:e,hasSymbolic:false};return new chunkNH74IT7B_cjs.m(7,t)}case 8:return new chunkNH74IT7B_cjs.m(8,{min:$(n.min),max:$(n.max)});case 10:return new chunkNH74IT7B_cjs.m(10,n.v);case 13:return new chunkNH74IT7B_cjs.m(13,n.code,n.message);default:throw chunk6SYU4MH7_cjs.c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds a value with an unknown type tag: ${JSON.stringify(n.t)}`,expected:"a known SerializedValue type tag",found:JSON.stringify(n.t)})}}function ue(n){let e={opcodes:Array.from(n.opcodes),numbers:Array.from(n.numbers,W),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=Array.from(n.constants.entries())),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(_e)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:ue(t.program)}))),e}function pe(n){let e={opcodes:Uint8Array.from(n.opcodes),numbers:Float64Array.from(n.numbers,$),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=new Map(n.constants)),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Ue)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:pe(t.program)}))),e}function _e(n){return {name:n.name,params:n.params.slice(),program:ue(n.program)}}function Ue(n){return {name:n.name,params:n.params.slice(),program:pe(n.program)}}function cn(n){if(typeof n!="object"||n===null)throw chunk6SYU4MH7_cjs.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 "${Z}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==Z)throw chunk6SYU4MH7_cjs.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 "${Z}"`,found:JSON.stringify(e.format)});if(e.version!==Q)throw chunk6SYU4MH7_cjs.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}});jn(n);}var on=32;function zn(n){return n===null?"null":Array.isArray(n)?`an array of ${n.length}`:typeof n=="object"?"an object":`${typeof n} ${JSON.stringify(n)}`.slice(0,80)}function g(n,e,t){throw chunk6SYU4MH7_cjs.c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot is malformed at ${n}: expected ${e}.`,expected:e,found:zn(t),suggestion:"Regenerate the snapshot with ExpressionEngine.toJSON(), or re-evaluate the document from source.",context:{location:n}})}function H(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function j(n){return typeof n=="number"||n==="NaN"||n==="Infinity"||n==="-Infinity"}function ce(n){return typeof n=="string"&&/^-?\d+$/.test(n)}function Ee(n,e){(!Array.isArray(n)||!n.every(t=>typeof t=="string"))&&g(e,"an array of strings",n);}function an(n,e){(!H(n)||!ce(n.coef)||typeof n.scale!="number")&&g(e,"a decimal as { coef: digits, scale: number }",n);}function $n(n,e){(!H(n)||!ce(n.n)||!ce(n.d))&&g(e,"a rational as { n: digits, d: digits }",n);}function ln(n,e){switch(H(n)||g(e,"a serialised value object",n),n.t){case 0:j(n.v)||g(`${e}.v`,"a number",n.v),n.exact!==void 0&&an(n.exact,`${e}.exact`),n.rational!==void 0&&$n(n.rational,`${e}.rational`);return;case 1:(n.big?!ce(n.v):!j(n.v))&&g(`${e}.v`,n.big?"an integer string":"a number",n.v),n.base!==void 0&&typeof n.base!="string"&&g(`${e}.base`,"a base name",n.base);return;case 2:ce(n.v)||g(`${e}.v`,"an integer string",n.v);return;case 3:typeof n.v!="string"&&g(`${e}.v`,"a string",n.v);return;case 4:j(n.v)||g(`${e}.v`,"a number",n.v),n.g!==void 0&&n.g!=="date"&&n.g!=="datetime"&&n.g!=="instant"&&g(`${e}.g`,'one of "date", "datetime" or "instant"',n.g),n.z!==void 0&&typeof n.z!="string"&&g(`${e}.z`,"a zone reference",n.z);return;case 5:j(n.v)||g(`${e}.v`,"a number",n.v);return;case 6:j(n.v)||g(`${e}.v`,"a number",n.v),typeof n.unit!="string"&&g(`${e}.unit`,"a unit name",n.unit),n.exact!==void 0&&an(n.exact,`${e}.exact`);return;case 7:{let{rows:t,cols:r,data:i}=n;(!Number.isInteger(t)||t<0)&&g(`${e}.rows`,"a non-negative integer",t),(!Number.isInteger(r)||r<0)&&g(`${e}.cols`,"a non-negative integer",r),(!Array.isArray(i)||i.length!==t*r)&&g(`${e}.data`,`an array of ${t} \xD7 ${r} cells`,i),i.every(s=>typeof s=="boolean"||j(s))||g(`${e}.data`,"numeric or boolean cells",i);return}case 8:(!j(n.min)||!j(n.max))&&g(e,"a range with numeric min and max",n);return;case 10:typeof n.v!="boolean"&&g(`${e}.v`,"a boolean",n.v);return;case 13:(typeof n.code!="string"||typeof n.message!="string")&&g(e,"an error with a string code and message",n);return;default:return}}function xe(n,e,t){if(t>on&&g(e,`function bodies nested at most ${on} deep`,"deeper nesting"),H(n)||g(e,"a serialised program object",n),(!Array.isArray(n.opcodes)||!n.opcodes.every(r=>Number.isInteger(r)&&r>=0&&r<=255))&&g(`${e}.opcodes`,"an array of bytes (integers 0 to 255)",n.opcodes),(!Array.isArray(n.numbers)||!n.numbers.every(j))&&g(`${e}.numbers`,"an array of numbers",n.numbers),Ee(n.strings,`${e}.strings`),typeof n.hasAsync!="boolean"&&g(`${e}.hasAsync`,"a boolean",n.hasAsync),n.constants!==void 0){let r=i=>Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number";(!Array.isArray(n.constants)||!n.constants.every(r))&&g(`${e}.constants`,"an array of [number, number] pairs",n.constants);}n.userFunctionBodies!==void 0&&(Array.isArray(n.userFunctionBodies)||g(`${e}.userFunctionBodies`,"an array of functions",n.userFunctionBodies),n.userFunctionBodies.forEach((r,i)=>un(r,`${e}.userFunctionBodies[${i}]`,t+1))),n.anonymousBodies!==void 0&&(Array.isArray(n.anonymousBodies)||g(`${e}.anonymousBodies`,"an array of bodies",n.anonymousBodies),n.anonymousBodies.forEach((r,i)=>{let s=`${e}.anonymousBodies[${i}]`;H(r)||g(s,"a body object",r),Ee(r.params,`${s}.params`),xe(r.program,`${s}.program`,t+1);}));}function un(n,e,t){H(n)||g(e,"a function object",n),typeof n.name!="string"&&g(`${e}.name`,"a function name",n.name),Ee(n.params,`${e}.params`),xe(n.program,`${e}.program`,t);}function jn(n){n.locale!==void 0&&typeof n.locale!="string"&&g("locale","a locale code",n.locale),H(n.variables)||g("variables","an object of values by name",n.variables);for(let[e,t]of Object.entries(n.variables))ln(t,`variables.${e}`);Array.isArray(n.userFunctions)||g("userFunctions","an array of functions",n.userFunctions),n.userFunctions.forEach((e,t)=>un(e,`userFunctions[${t}]`,1)),Array.isArray(n.lineCache)||g("lineCache","an array of cached lines",n.lineCache),n.lineCache.forEach((e,t)=>{let r=`lineCache[${t}]`;H(e)||g(r,"a cached line",e),Number.isInteger(e.line)||g(`${r}.line`,"a line number",e.line),typeof e.expression!="string"&&g(`${r}.expression`,"the line's expression text",e.expression),ln(e.result,`${r}.result`),xe(e.bytecode,`${r}.bytecode`,1),Ee(e.reads,`${r}.reads`),e.writeVar!==null&&typeof e.writeVar!="string"&&g(`${r}.writeVar`,"a variable name or null",e.writeVar);}),Array.isArray(n.bytecodeCache)||g("bytecodeCache","an array of compiled expressions",n.bytecodeCache),n.bytecodeCache.forEach((e,t)=>{let r=`bytecodeCache[${t}]`;(!H(e)||typeof e.expression!="string")&&g(r,"an { expression, program } pair",e),xe(e.program,`${r}.program`,1);});}var pn=null;function gr(n){pn=n;}function ze(){return pn}var dn=3e4,fn=50,Se=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=ze();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 r=[];for(let a of e){let l=t.get(a);if(!l||l.bytecode.opcodes.length===0)continue;let u=l.bytecode.opcodes,p=l.bytecode.numbers,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),y=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);r.push({lineNumber:a,opcodesBuffer:h,numbersBuffer:y,opcodesLength:u.length,numbersLength:p.length,strings:[...l.bytecode.strings]});}if(r.length===0)return Promise.resolve([]);let i=[];for(let a of r)a.opcodesBuffer.byteLength>0&&i.push(a.opcodesBuffer),a.numbersBuffer.byteLength>0&&i.push(a.numbersBuffer);let s=this.nextId++,o=this.nextWorkerIndex(),c=this.workers[o];return new Promise(a=>{let l=setTimeout(()=>{this.pendingBatches.has(s)&&this.failWorker(o,"WORKER_TIMEOUT",`Evaluation did not finish within ${dn/1e3} seconds; the worker was replaced`);},dn);this.pendingBatches.set(s,{id:s,lineNumbers:r.map(u=>u.lineNumber),workerIndex:o,resolve:u=>{clearTimeout(l),a(u);}}),c.postMessage({type:"EXECUTE_BATCH",id:s,items:r},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=ze();if(t===null)return;let r=t();r.onmessage=i=>{this.handleWorkerMessage(i.data);},r.onerror=i=>{console.error(`[ExecutionPool] Worker ${e} error:`,i.message),this.failWorker(e,"WORKER_EXECUTION_ERROR",`Worker failed: ${i.message}`);},this.workers[e]=r;}failWorker(e,t,r){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(Wn(s.lineNumbers,t,r)));}}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 Wn(n,e,t){return n.map(r=>({lineNumber:r,valueType:13,value:0,unit:t,isPending:false,errorCode:e}))}function gn(n){switch(n.valueType){case 0:return chunkNH74IT7B_cjs.n(n.value);case 1:return chunkNH74IT7B_cjs.r(n.value);case 2:return chunkNH74IT7B_cjs.s(BigInt(n.value));case 3:return chunkNH74IT7B_cjs.t(String(n.value));case 4:return chunkNH74IT7B_cjs.M(n.value);case 5:return chunkNH74IT7B_cjs.N(n.value);case 6:return chunkNH74IT7B_cjs.u(n.value,n.unit??"");case 7:return chunkNH74IT7B_cjs.n(n.value);case 10:return chunkNH74IT7B_cjs.L(n.value!==0);case 12:return chunkNH74IT7B_cjs.O(n.queryKey??"");case 13:return chunkNH74IT7B_cjs.P(n.errorCode??"WORKER_EXECUTION_ERROR",n.unit??"Unknown worker error");default:return chunkNH74IT7B_cjs.n(n.value)}}var ee=class ee{constructor(e,t,r,i=ee.DEFAULT_HIGH_WATER_MARK){this.pending=new Map;this.collapsed=0;this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.checkpointer=null;this.warnedAboutMissingHook=false;this.flushesWithoutYielding=0;this.yieldProbeArmed=false;this.dag=e,this.lineCache=t,this.vm=r,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;let t=`${e.packageId}:${e.queryKey}`;if(this.pending.has(t)){this.collapsed++;return}if(this.pending.set(t,e),!this.scheduled){this.scheduled=true;let r=this.flushesWithoutYielding>=ee.MAX_CHAINED_FLUSHES,i=()=>{try{this.flush();}catch(s){let o=chunk6SYU4MH7_cjs.d(s);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${o.format()}`);}};r?setTimeout(i,0):queueMicrotask(i);}}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.size}get dedupCount(){return this.collapsed}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=new Map,this.collapsed=0,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.size===0)return;this.flushesWithoutYielding++,this.yieldProbeArmed||(this.yieldProbeArmed=true,setTimeout(()=>{this.flushesWithoutYielding=0,this.yieldProbeArmed=false;},0));let e=this.pending;this.pending=new Map,this.collapsed=0;let t=[],r=[];for(let a of e.values())a.isError?t.push(a):r.push(a);for(let a of t)a.signal.aborted||this.notifyListeners({type:"error",queryKey:a.queryKey,packageId:a.packageId,error:a.error??new Error("Unknown async resolution error")});let i=new Set,s=[],o=[...r,...t];for(let a of o){if(a.signal.aborted)continue;s.push(a.queryKey);let l=this.dag.getAffectedLinesByDataSource(a.packageId,[a.queryKey]);for(let u of l)i.add(u);}{let a=[...i],l=u=>{i.has(u)||(i.add(u),a.push(u));};for(let u=0;u<a.length;u++){let p=a[u];for(let h of this.dag.getWrites(p))for(let y of this.dag.getAffectedLines(h))l(y);for(let h of this.dag.getAffectedLinesByPosition(p))l(h);}}if(i.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:s});return}let c=this.topologicalSort(Array.from(i));if(c.length>fn){let a=new Map;for(let l of c)a.set(l,this.lineCache.getEntryForLine(l));this.reExecuteViaWorkerPool(c,a,s).catch(l=>{let u=chunk6SYU4MH7_cjs.d(l);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${u.format()}`);});return}this.reExecuteMainThread(c,s);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,r=new Map,i=new Map;for(let c of e)t.set(c,0),r.set(c,[]);for(let c of e){let a=this.dag.getWrites(c);for(let l of a)i.set(l,c);}for(let c of e){let a=this.dag.getReads(c);for(let l of a){let u=i.get(l);u!==void 0&&u!==c&&(r.get(u).push(c),t.set(c,(t.get(c)??0)+1));}}let s=[];for(let[c,a]of t)a===0&&s.push(c);if(s.length===0&&e.length>0)return [...e].sort((c,a)=>c-a);let o=[];for(let c=0;c<s.length;c++){let a=s[c];o.push(a);for(let l of r.get(a)??[]){let u=(t.get(l)??1)-1;t.set(l,u),u===0&&s.push(l);}}if(o.length<e.length){let c=new Set(o),a=e.filter(l=>!c.has(l)).sort((l,u)=>l-u);o.push(...a);}return o}async reExecuteViaWorkerPool(e,t,r){this.executionPool||(this.executionPool=new Se);let i=this.executionPool.executeBatch(e,t);if(!i){this.reExecuteMainThread(e,r,t);return}this.workerOffloadDispatchCount++;let s=await i;if(this.cleared)return;let o=[];for(let c of s){let a=t.get(c.lineNumber);if(!a||c.isPending)continue;let l=gn(c);a.result=l,this.warnIfUnwired(),this.onLineResult?.(c.lineNumber,l),o.push(c.lineNumber);}this.cleared||(o.length>0||r.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:r});}prepareSweep(e){if(e.length===0)return null;let t=e[0];for(let r=1;r<e.length;r++)e[r]<t&&(t=e[r]);return this.checkpointer.restoreTo(t-1),{at:t-1}}sweepTo(e,t){for(let r=e.at+1;r<t;r++)this.checkpointer.applyCheckpointAt(r);t>e.at&&(e.at=t);}reExecuteMainThread(e,t,r){let i=[],s=this.checkpointer!==null?this.prepareSweep(e):null;for(let o of e){s!==null&&this.sweepTo(s,o);let c=r?r.get(o):this.lineCache.getEntryForLine(o);if(!c||c.bytecode.opcodes.length===0)continue;let a=this.vm.getStack().length;try{let l=chunkDTOSRC6E_cjs.c(c.bytecode,this.vm,void 0,void 0,{lineIndex:o,networkEnabled:this.vm.context.networkEnabled,calendar:this.vm.context.calendar});for(;this.vm.getStack().length>a;)this.vm.pop();if(l.type==="value")s!==null&&c.writeVariable!==null&&this.checkpointer.updateCheckpointAt(o,[c.writeVariable]),c.result=l.value,this.warnIfUnwired(),this.onLineResult?.(o,l.value),i.push(o);else if(l.type==="error"){let u=chunkNH74IT7B_cjs.P(l.error.code,l.error.message);c.result=u,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(o,u),i.push(o);}}catch(l){for(;this.vm.getStack().length>a;)this.vm.pop();let u=chunk6SYU4MH7_cjs.d(l),p=chunkNH74IT7B_cjs.P(u.code,u.message);c.result=p,this.warnIfUnwired(),this.onLineResult?.(o,p),i.push(o);}}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{}}};ee.DEFAULT_HIGH_WATER_MARK=64,ee.MAX_CHAINED_FLUSHES=4;var ke=ee;function $e(n,e){if(n.length>e.maxExpressionLength){let t=chunk6SYU4MH7_cjs.c.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${n.length})`,{expressionLength:n.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:chunkNH74IT7B_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function je(n,e){let t=0,r=0,i=0;for(let o of n)o.type==="FUNC"&&t++,(o.value==="("||o.type==="LPAREN")&&(r++,i=Math.max(i,r)),(o.value===")"||o.type==="RPAREN")&&r--;let s=n.length+t*5+i*10;if(s>e.maxComplexity){let o=chunk6SYU4MH7_cjs.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(n){return n.type==="IDENT"||n.type==="UNIT"}function Hn(n){return n.type==="NUMBER"||n.type==="TO"||n.type==="IN"||n.type==="RPAREN"}function hn(n,e){let t=0;for(let r=e;r<n.length;r++)if(n[r].type==="LPAREN")t++;else if(n[r].type==="RPAREN"&&(t--,t===0))return r;return null}function Kn(n){let e=new Set;for(let t=0;t<n.length;t++){if(!de(n[t])||t>0&&n[t-1].type==="COLON"||n[t+1]?.type!=="LPAREN")continue;let r=hn(n,t+1);if(r!==null&&n[r+1]?.type==="EQUALS")for(let i=t+2;i<r;i++)de(n[i])&&e.add(n[i].value);}return e}function Ce(n){let e=[],t=[],r=Kn(n);for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="GLOBAL"){if(i+2<n.length&&n[i+1].type==="COLON"&&de(n[i+2])){let o=chunk6ADFAXTZ_cjs.N(n[i+2].value);e.push(o),i+3<n.length&&n[i+3].type==="EQUALS"&&t.push(o);}continue}if(s.type==="COLON"){if(i>0&&n[i-1].type==="GLOBAL")continue;if(i+1<n.length&&de(n[i+1])){let o=n[i+1].value;e.push(o),i+2<n.length&&n[i+2].type==="EQUALS"&&t.push(o);}}if(de(s)){if(i>0&&n[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&Hn(n[i-1])||r.has(s.value))continue;if(n[i+1]?.type==="LPAREN"){let c=hn(n,i+1);if(c!==null&&n[c+1]?.type==="EQUALS"){e.push(s.value),t.push(s.value);continue}}e.push(s.value);let o=n[i+1]?.type;(o==="EQUALS"||o==="PLUS_EQUALS"||o==="MINUS_EQUALS")&&t.push(s.value);}}return {reads:e,writes:t}}function Ar(n){return chunk3MG7VIPL_cjs.c.classifyLine(n).skip}function Pr(n,e){return chunk3MG7VIPL_cjs.c.findInlineSolves(n).map(r=>({start:r.start,end:r.end,expression:r.expression,lineNumber:e,columnNumber:r.columnNumber}))}var q=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},Te=class n{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(n.exprKey(t))}getEntryForLine(e){let t=this.byLine.get(e);if(t)for(let r of t.values())return r}set(e,t,r){let i=this.byLine.get(e);i||(i=new Map,this.byLine.set(e,i));let s=n.exprKey(r);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(n.exprKey(t))??false}remove(e,t){let r=this.byLine.get(e);r&&r.delete(n.exprKey(t))&&(this.count--,r.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,r]of this.byLine)for(let[i,s]of r)e(n.displayKey(t,i),s);}snapshotEntries(){let e=[];for(let[t,r]of this.byLine)for(let[i,s]of r)e.push({line:t,expression:i,entry:s});return e}keys(){let e=[];for(let[t,r]of this.byLine)for(let i of r.keys())e.push(n.displayKey(t,i));return e}};function We(n,e){let t=e.fields(n),r=String(t.month0+1).padStart(2,"0"),i=String(t.day).padStart(2,"0");return `${t.year}-${r}-${i}`}function Gn(n,e){if(n instanceof Date)return We(n.getTime(),e);if(typeof n=="number")return Number.isFinite(n)?We(n,e):null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return t?`${t[1]}-${t[2]}-${t[3]}`:null}function mn(n,e){if(n===void 0)return;if(typeof n=="function")return r=>n(new Date(r));let t=new Set;for(let r of n){let i=Gn(r,e);i!==null&&t.add(i);}return r=>t.has(We(r,e))}function qn(n,e){if(!n||n.type!==e.type||n.value!==e.value)return true;let t=n.unit,r=e.unit;return t!==r}var Re=class n{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=n.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let r=setInterval(()=>{this.tick(t);},e.intervalMs);r.unref?.(),this.entries.set(t,{...e,timer:r,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 r=await t.refetch(),i=this.entries.get(e);if(!i)return;r&&qn(i.lastValue,r)&&(i.lastValue=r,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let r=this.entries.get(e);r&&(r.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 _=class{static enable(){this.enabled=true;}static disable(){this.enabled=false;}static isEnabled(){return this.enabled}static track(e,t,r){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,a=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,l=c?c[0]*1e9+c[1]:(performance.now()-s)*1e6,u=i&&a?a.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:l,...r};return {result:o,alloc:p}}static generateReport(e,t){let r=[];r.push(t?`## ${t}`:"## Pipeline Allocation Report"),r.push(""),r.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),r.push("");let i=this.aggregate(e);if(i.length===0)return r.push("_No telemetry data._"),r.join(`
2
+ `);r.push("### Per-Stage Breakdown"),r.push(""),r.push("| Stage | Count | Mean Wall (\xB5s) | Mean Alloc (bytes) | Min (\xB5s) | Max (\xB5s) | p50 (\xB5s) | p95 (\xB5s) | p99 (\xB5s) |"),r.push("|-------|:-----:|:--------------:|:------------------:|:--------:|:--------:|:--------:|:--------:|:--------:|");for(let a of i)r.push(`| ${a.stage} | ${a.count} | ${(a.meanWallTimeNs/1e3).toFixed(2)} | ${a.meanAllocBytes.toFixed(0)} | ${(a.minWallTimeNs/1e3).toFixed(2)} | ${(a.maxWallTimeNs/1e3).toFixed(2)} | ${(a.p50WallTimeNs/1e3).toFixed(2)} | ${(a.p95WallTimeNs/1e3).toFixed(2)} | ${(a.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((a,l)=>a+l.totalAllocBytes,0),o=e.reduce((a,l)=>a+l.totalWallTimeNs,0),c=e.filter(a=>a.fastPath).length;return r.push(""),r.push("### Totals"),r.push(""),r.push(`- **Total wall time:** ${(o/1e6).toFixed(2)} ms (${e.length} runs)`),r.push(`- **Total heap allocated:** ${s.toLocaleString()} bytes`),r.push(`- **Fast-path runs:** ${c}/${e.length} (${(c/e.length*100).toFixed(0)}%)`),r.push(`- **Mean per-run:** ${(o/e.length/1e3).toFixed(2)} \xB5s, ${(s/e.length).toFixed(0)} bytes`),r.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 r=[];for(let[i,s]of t){let o=s.map(l=>l.wallTimeNs).sort((l,u)=>l-u),c=s.map(l=>l.allocBytes),a=s.length;r.push({stage:i,count:a,meanAllocBytes:c.reduce((l,u)=>l+u,0)/a,meanWallTimeNs:o.reduce((l,u)=>l+u,0)/a,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:He(o,50),p95WallTimeNs:He(o,95),p99WallTimeNs:He(o,99)});}return r.sort((i,s)=>i.stage.localeCompare(s.stage)),r}static createTelemetry(e,t,r=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:r}}};_.enabled=false;function He(n,e){if(n.length===0)return 0;if(n.length===1)return n[0];let t=e/100*(n.length-1),r=Math.floor(t),i=Math.ceil(t);if(r===i)return n[r];let s=t-r;return n[r]*(1-s)+n[i]*s}function yn(n){let e=n[n.length-1],t=e.length>1&&e.endsWith("s")?e.slice(0,-1):e;return [...n.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,r){let i=yn(e),s=this.byKey.get(i),o=s===void 0||s.ratioText!==t||s.baseUnit!==r;return this.byKey.set(i,{displayName:e.join(" "),ratioText:t,baseUnit:r}),e.length>this.longestName&&(this.longestName=e.length),o}match(e){let t=Math.min(e.length,this.longestName);for(let r=t;r>=1;r--){let i=this.byKey.get(yn(e.slice(0,r)));if(i!==void 0)return {definition:i,wordCount:r}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function vn(n,e=82){return {name:"uom:user-unit",priority:e,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT"]}],match(t,r){if(n.isEmpty)return null;let i=t[r];if(i.type!=="NUMBER"&&i.type!=="RPAREN")return null;let s=[],o=n.maxWordCount;for(let d=r+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=n.match(s);if(c===null||t[r+1+c.wordCount]?.type==="EQUALS")return null;let{ratioText:l,baseUnit:u}=c.definition,p=new chunk72J5V7SN_cjs.a("STAR",chunkYBQOQTVL_cjs.c("STAR"),"*","*",i.offset,0,i.line,i.col),h=new chunk72J5V7SN_cjs.a("NUMBER",chunkYBQOQTVL_cjs.c("NUMBER"),l,l,i.offset,0,i.line,i.col),y=new chunk72J5V7SN_cjs.a("UNIT",chunkYBQOQTVL_cjs.c("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+c.wordCount,replacement:[i,p,h,y],ruleName:"uom:user-unit"}}}}var bn="engine:call-fusion";function En(n,e=80){return {name:bn,priority:e,shape:[{types:["IDENT"]},{types:["LPAREN"]}],match(t,r){let i=t[r];if(!i||i.type!=="IDENT"||t[r+1]?.type!=="LPAREN"||t[r-1]?.type==="COLON")return null;let s=(i.value??"").toLowerCase(),o=n.get(s);return o===void 0?null:{consumed:1,replacement:[new chunk72J5V7SN_cjs.a(o,chunkYBQOQTVL_cjs.c(o),s,i.value,i.offset,0,i.line,i.col)],ruleName:bn}}}}var Yn={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 xn(n){return n===void 0||n.type!=="IDENT"&&n.type!=="UNIT"?0:Yn[(n.text??n.value??"").toLowerCase()]??0}var fe=/^\d+$/;function Ne(n){return n.length===4}function te(n,e,t,r,i,s){let o="datetime:month-name-date",c=chunkU54BIYXO_cjs.t(n,e,t,r,o,i);return c!==null?c:s==="arithmetic"||e<1||e>12||n<1||n>31?null:chunkU54BIYXO_cjs.v(chunkU54BIYXO_cjs.j.DATE_NOT_A_CALENDAR_DAY,`"${chunkU54BIYXO_cjs.u(r)}" is not a real date: ${chunkU54BIYXO_cjs.m(n,e,t)}.`,r,`${o}:unreadable`)}function Sn(n){return n.fields(n.now()).year}function kn(n=64,e=()=>chunkEQNKDTMX_cjs.b,t=()=>"refuse"){return {name:"datetime:month-name-date",priority:n,startTokenTypes:["NUMBER","IDENT","UNIT"],match(r,i){let s=e(),o=t(),c=r[i];if(c?.type==="NUMBER"&&fe.test(c.text??"")){let y=xn(r[i+1]);if(y===0)return null;let d=Number(c.text);if(d<1||d>31)return null;let S=r[i+2];return S?.type==="NUMBER"&&fe.test(S.text??"")&&Ne(S.text??"")?te(d,y,Number(S.text),r.slice(i,i+3),s,o):te(d,y,Sn(s),r.slice(i,i+2),s,o)}let a=xn(c);if(a===0)return null;let l=r[i+1];if(l?.type!=="NUMBER"||!fe.test(l.text??""))return null;if(Ne(l.text??""))return te(1,a,Number(l.text),r.slice(i,i+2),s,o);let u=Number(l.text),p=r[i+2],h=r[i+3];return p?.type==="COMMA"&&h?.type==="NUMBER"&&fe.test(h.text??"")&&Ne(h.text??"")?te(u,a,Number(h.text),r.slice(i,i+4),s,o):p?.type==="NUMBER"&&fe.test(p.text??"")&&Ne(p.text??"")?te(u,a,Number(p.text),r.slice(i,i+3),s,o):te(u,a,Sn(s),r.slice(i,i+2),s,o)}}}var Qn=30,Xn=40,Jn=50,Zn=24;function er(n){switch(n){case chunkYBQOQTVL_cjs.a.PLUS:case chunkYBQOQTVL_cjs.a.MINUS:return Qn;case chunkYBQOQTVL_cjs.a.STAR:case chunkYBQOQTVL_cjs.a.SLASH:case chunkYBQOQTVL_cjs.a.MOD:case chunkYBQOQTVL_cjs.a.OF:return Xn;case chunkYBQOQTVL_cjs.a.CARET:return Jn;case chunkYBQOQTVL_cjs.a.PCT_ON:case chunkYBQOQTVL_cjs.a.PCT_OFF:return Zn;default:return 0}}function tr(n){switch(n){case chunkYBQOQTVL_cjs.a.PLUS:return "plus";case chunkYBQOQTVL_cjs.a.MINUS:return "minus";case chunkYBQOQTVL_cjs.a.STAR:return "times";case chunkYBQOQTVL_cjs.a.SLASH:return "divided by";case chunkYBQOQTVL_cjs.a.MOD:return "mod";case chunkYBQOQTVL_cjs.a.CARET:return "to the power of";case chunkYBQOQTVL_cjs.a.OF:return "of";case chunkYBQOQTVL_cjs.a.PCT_ON:return "plus";case chunkYBQOQTVL_cjs.a.PCT_OFF:return "less";default:return n.toLowerCase()}}function Cn(n){return n.sourceEnd??n.offset+n.value.length}var nr=new Set([chunkYBQOQTVL_cjs.a.NUMBER,chunkYBQOQTVL_cjs.a.BIGINT,chunkYBQOQTVL_cjs.a.IDENT,chunkYBQOQTVL_cjs.a.UNIT,chunkYBQOQTVL_cjs.a.PERCENT,chunkYBQOQTVL_cjs.a.PI,chunkYBQOQTVL_cjs.a.E,chunkYBQOQTVL_cjs.a.TRUE,chunkYBQOQTVL_cjs.a.FALSE,chunkYBQOQTVL_cjs.a.DOLLAR,chunkYBQOQTVL_cjs.a.POUND,chunkYBQOQTVL_cjs.a.EURO,chunkYBQOQTVL_cjs.a.YEN,chunkYBQOQTVL_cjs.a.RUBLE,chunkYBQOQTVL_cjs.a.WON,chunkYBQOQTVL_cjs.a.CURRENCY_SYMBOL]);function rr(n){return !nr.has(n)}var Ke=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 r=this.peek();if(!r)break;let i=er(r.type);if(i===0||i<=e)break;this.next();let s=r.type===chunkYBQOQTVL_cjs.a.CARET?i-1:i,o=this.parseExpression(s);t={kind:"binary",op:r.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===chunkYBQOQTVL_cjs.a.LPAREN)return this.parseGroup();let t=e.offset,r=false;for(;this.peek()&&(this.peek().type===chunkYBQOQTVL_cjs.a.PLUS||this.peek().type===chunkYBQOQTVL_cjs.a.MINUS);)this.next(),r=true;if(r&&this.peek()&&this.peek().type===chunkYBQOQTVL_cjs.a.LPAREN){let s=this.parseGroup();return {kind:"wrap",child:s,start:t,end:s.end}}let i=-1;for(;this.peek()&&!rr(this.peek().type);)i=Cn(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),r=this.peek();if(!r||r.type!==chunkYBQOQTVL_cjs.a.RPAREN)throw new Error("explain: unbalanced parentheses");return this.next(),{kind:"wrap",child:t,start:e.offset,end:Cn(r)}}},Ge=class{constructor(e,t,r){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=chunkS3DFU33X_cjs.a(r).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=tr(e.op);return e.op===chunkYBQOQTVL_cjs.a.PCT_ON||e.op===chunkYBQOQTVL_cjs.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 r=this.evaluate(this.source.slice(e.start,e.end));return this.cache.set(e,r),r}render(e){let t=chunkJUIHUG4M_cjs.c(e,chunkJUIHUG4M_cjs.a);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function qe(n){let{expression:e,tokens:t,evaluate:r,locale:i,readings:s=[]}=n,o=l=>s.filter(u=>u.needsNote).map(u=>({description:u.note,value:l})),c=()=>{let l=r(e);return {expression:e,steps:o(l),result:l}},a;try{a=new Ke(t).parseAll();}catch{return c()}try{let{steps:l,result:u}=new Ge(e,r,i).build(a);return {expression:e,steps:[...o(u),...l],result:u}}catch{return c()}}function Ye(n){let e=chunkNH74IT7B_cjs.t(n);return chunkNH74IT7B_cjs.j()?chunkNH74IT7B_cjs.k(e):e}var U=class U{constructor(e={}){this.dag=new chunk6ADFAXTZ_cjs.b;this.asyncFailures=new Map;this.lineCache=new Te;this.accumulatorNames=new Set;this.scopeManager=new chunkDTOSRC6E_cjs.a;this.resolverRegistry=new chunkR3W53ZMP_cjs.a;this.packageContributions=new Map;this.registeredPackages=new Map;this.callFusions=new Map;this.callFusionOwners=new Map;this.compatIndex=new be;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.batchTagIndex=null;this.lineContext=null;this.lineContextDoc=null;this.lineContextScan=null;this.lineContextParsed=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.backgroundRefreshSignal=new AbortController().signal;this.inertSignal=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 chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName),new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName),new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName),new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName)];this.builderPoolIndex=0;this.lastTelemetry=null;let{locale:t="en",diagnostics:r=false,config:i,packages:s,calendar:o}=e;this.localeCode=t,this.config=chunkA3CNNRFM_cjs.c(chunkA3CNNRFM_cjs.b,i??{}),this.dateReading=chunkU54BIYXO_cjs.k(this.config.date),this.lexer=new chunk3MG7VIPL_cjs.b(t),this.registry=new chunkP5YWBIIU_cjs.b,this.context=chunk6ADFAXTZ_cjs.A({networkEnabled:this.config.network.enabled,calendar:o}),r?(this.diagnosticPipeline=new chunkHG4NPDN5_cjs.a,this.timelineCollector=new chunkHG4NPDN5_cjs.b,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new chunkHG4NPDN5_cjs.a,this.normalizer=new chunkYV4GDW5A_cjs.c;for(let[a,l]of Object.entries(chunk72J5V7SN_cjs.c))this.normalizer.addPhrase(a,l);this.normalizer.register(chunkYV4GDW5A_cjs.d(50,a=>this.normalizer.canStartPhrase(a))),this.normalizer.register(vn(this.userUnits)),this.normalizer.register(En(this.callFusions));let c=s??[];for(let a of c)try{this.registerPackage(a);}catch(l){let u=chunk6SYU4MH7_cjs.d(l);console.error(`[ExpressionEngine] Failed to register package "${a.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 a=()=>this.context.calendar;this.normalizer.register(chunkU54BIYXO_cjs.w(()=>this.dateReading.order,a,()=>this.config.date.onAmbiguous)),this.normalizer.register(kn(void 0,a,()=>this.config.date.onAmbiguous));}this.parser=new chunkP5YWBIIU_cjs.a(this.registry,this.config.validation.maxNestingDepth,t,this.pluginFunctionIndexByName,this.context.calendar),this.vm=chunkDTOSRC6E_cjs.b(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,mn(this.config.date.holidays,this.context.calendar)),this.queryClient=chunkZLRJ7TDP_cjs.c(),this.batcher=new ke(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new Re(this.dag,(a,l)=>this.batcher.add({queryKey:l,packageId:a,signal:this.backgroundRefreshSignal,isError:false})):null,e.warmup===true&&this.warmUp();}setDocumentModel(e){this.documentModel=e;}getDocumentModel(){return this.documentModel}warmUp(){let e=new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName);for(let t of U.WARMUP_EXPRESSIONS)try{this.lexer.resetExpression(t);let r=[];for(let o of this.lexer)o.type!=="COMMENT"&&r.push(o);let i=this.normalizer.normalize(r);e.reset(),this.parser.load(i),this.parser.parseExpression(0,e);let s=e.build();this.vm.reset(),chunkDTOSRC6E_cjs.c(s,this.vm);}catch{}this.vm.reset();}makeLineContext(e){let t=this.documentModel,r=t?null:this.batchScanResults,i=t?null:this.batchParsedLines,s=this.lineContext;return (s===null||this.lineContextDoc!==t||this.lineContextScan!==r||this.lineContextParsed!==i)&&(s=this.buildLineContext(t,r,i,e),this.lineContext=s,this.lineContextDoc=t,this.lineContextScan=r,this.lineContextParsed=i),s.lineIndex=e,s}buildLineContext(e,t,r,i){let s=this.dag,o;return o={lineIndex:i,getLineResult:e?a=>(s.registerLinePositionDependency(o.lineIndex,a),e.getLineAt(a)?.result??void 0):r?a=>r[a-1]?.result??void 0:void 0,isLineBoundary:e?a=>{let l=e.getLineAt(a);return l?l.isEmpty||/^\s*#/.test(l.text):true}:t?a=>{let l=t[a-1];return l?l.classification.skip||/^\s*#/.test(l.text):true}:void 0,getLineReads:e?a=>{let l=e.getLineAt(a);if(!(!l||l.bytecodes.length===0))return l.reads}:void 0,evaluateLineWithBinding:e?(a,l,u,p)=>this.evaluateLineWithBinding(a,l,u,p):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,networkEnabled:this.config.network.enabled,calendar:this.context.calendar,getLineText:e?a=>e.getLineAt(a)?.text:t?a=>t[a-1]?.text:void 0,getTaggedLines:e?a=>e.linesCarryingTag(a):t?a=>this.batchLinesCarryingTag(t,a):void 0},o}evaluateLineWithBinding(e,t,r,i){let s=this.documentModel;if(!s)return chunkNH74IT7B_cjs.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>=U.GOAL_SEEK_MAX_NESTING_DEPTH)return chunkNH74IT7B_cjs.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 chunkNH74IT7B_cjs.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 chunkNH74IT7B_cjs.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 a=new Map([[t,r]]),l=this.vm.getStack().length;this.vm.pushCallFrame(a);try{let u=chunkDTOSRC6E_cjs.c(c,this.vm,void 0,void 0,this.buildLineContext(s,null,null,e),i);return u.type==="pending"?chunkNH74IT7B_cjs.P("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?chunkNH74IT7B_cjs.P(u.error.code??"GOAL_SEEK_TARGET_ERROR",u.error.message):u.value}finally{for(this.vm.popCallFrame();this.vm.getStack().length>l;)this.vm.pop();}}catch(a){return chunkNH74IT7B_cjs.P("GOAL_SEEK_TARGET_ERROR",chunk6SYU4MH7_cjs.d(a).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,r){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,r);}touchCompiled(e,t){this.bytecodeCache.size<this.config.performance.defaultCacheSize||(this.bytecodeCache.delete(e),this.bytecodeCache.set(e,t));}rememberFailedParse(e,t){if(this.failedParses.size>=this.config.performance.defaultCacheSize){let r=this.failedParses.keys().next().value;r!==void 0&&this.failedParses.delete(r);}this.failedParses.set(e,t);}touchFailedParse(e,t){this.failedParses.size<this.config.performance.defaultCacheSize||(this.failedParses.delete(e),this.failedParses.set(e,t));}getEventStream(){return this.batcher.getEventStream()}getBatcher(){return this.batcher}registerPackage(e){tn(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 r={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=chunk6ADFAXTZ_cjs.I(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),r.pluginFunctionIndices.push(o),r.pluginFunctionNames.push(i);}if(e.asyncResolvers)for(let i of e.asyncResolvers)this.resolverRegistry.register(i),r.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),r.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),r.callFusionNames.push(o);}if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))chunkY7O4D3BJ_cjs.b(i,s),r.tokenCategories.push(i);if(e.completionItems&&this.packageCompletionItems.set(e.name,e.completionItems),e.asConverters)for(let[i,s]of Object.entries(e.asConverters))chunk6ADFAXTZ_cjs.K(i,s),r.asConverterNames.push(i);this.packageContributions.set(e.name,r),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 r of t.pluginFunctionIndices)delete this.context.pluginFunctions[r],delete this.context.pluginFunctionOwners[r];for(let r of t.pluginFunctionNames)this.pluginFunctionIndexByName.delete(r);for(let r of t.resolverNamespaces)this.resolverRegistry.unregister(r);for(let r of t.tokenCategories)chunkY7O4D3BJ_cjs.c(r);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let r of t.asConverterNames)chunk6ADFAXTZ_cjs.L(r);for(let r of t.normalizerRuleNames)this.normalizer.unregister(r);for(let r of t.callFusionNames){let i=(this.callFusionOwners.get(r)??[]).filter(s=>s.pkg!==e);i.length===0?(this.callFusionOwners.delete(r),this.callFusions.delete(r)):(this.callFusionOwners.set(r,i),this.callFusions.set(r,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),r=this.normalizer.normalize(t.filter(s=>s.type!=="COMMENT")),i=[];for(let s of r){let o=s.type===chunkU54BIYXO_cjs.s;if(!o&&s.type!==chunkU54BIYXO_cjs.r)continue;let c=s.offset,a=s.sourceEnd??s.offset+s.text.length;i.push(this.describeDateLiteral(e.slice(c,a),c,a,s,o));}return i}describeDateLiteral(e,t,r,i,s){let o=chunkU54BIYXO_cjs.q(e);if(o!==null){let l=chunkU54BIYXO_cjs.o(o,this.dateReading.order,this.config.date.onAmbiguous,this.context.calendar),u=chunkU54BIYXO_cjs.l(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,h=u?{order:"ISO",orderSource:"iso",locale:void 0}:{order:p,orderSource:this.dateReading.orderSource,locale:this.dateReading.locale};return l.kind==="date"?chunkU54BIYXO_cjs.p({text:e,start:t,end:r,iso:chunkU54BIYXO_cjs.n(l.day,l.month,l.year),...h,contested:l.alternative!==void 0,shortYear:l.shortYear,alternative:l.alternative},o.separator):chunkU54BIYXO_cjs.p({text:e,start:t,end:r,iso:null,...h,contested:false,shortYear:false,problem:l.kind==="refuse"?l.code:void 0},o.separator,l.kind==="refuse"?l.message:void 0)}if(s){let l=i.fault??{code:"DATE_NOT_A_CALENDAR_DAY",message:`"${i.value}" is not a date this engine can read.`};return chunkU54BIYXO_cjs.p({text:e,start:t,end:r,iso:null,order:null,orderSource:"spelled",contested:false,shortYear:false,problem:l.code},"slash",l.message)}let c=this.context.calendar.fields(Number(i.value)),a=/^\d{4}-/.test(e)?"iso":"spelled";return chunkU54BIYXO_cjs.p({text:e,start:t,end:r,iso:chunkU54BIYXO_cjs.n(c.day,c.month0+1,c.year),order:a==="iso"?"ISO":"spelled",orderSource:a,contested:false,shortYear:false},"slash")}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,r,i,s,o){this.lineCache.set(e,new q(t,r,i,s.length>0?s[0]:null),o);}mayResolve(e){return e.hasAsync||this.resolverRegistry.mayIntercept(e)}armCancellation(e,t){if(!this.mayResolve(e))return this.vm.activeSignal=this.inertSignal,this.vm.abortCurrent=void 0,null;let r=new AbortController,i=()=>r.abort(),s=this.keystrokeSignal;s?.addEventListener("abort",i,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated(t),s&&chunkTTFO4YDP_cjs.a.signalLinked(t);let o=()=>s?.removeEventListener("abort",i);return this.vm.activeSignal=r.signal,this.vm.abortCurrent=()=>{chunkTTFO4YDP_cjs.a.signalUnlinked(t),o(),r.abort();},o}registerLineWithTags(e,t,r,i){let s=chunkU54BIYXO_cjs.a(t,r,i);this.dag.registerLine(e,s.reads,s.writes);}executeAndStore(e,t,r,i,s,o,c,a){let l=this.vm.getStack().length,u=this.armCancellation(e,"executeAndStore");chunkZLRJ7TDP_cjs.a(this.queryClient);let p=chunkDTOSRC6E_cjs.c(e,this.vm,c,a,this.makeLineContext(t));for(;this.vm.getStack().length>l;)this.vm.pop();if(p.type==="pending"){let h=`${p.packageId||o}:${p.queryKey}`,y=this.asyncFailures.get(h)??0;if(y>=U.MAX_ASYNC_FAILURES){u?.();let S=chunkNH74IT7B_cjs.P("ASYNC_RESOLVER_FAILED",`This value could not be fetched after ${y} attempts, so it is reported rather than retried. Edit the line to try again.`);return this.storeLineResult(t,S,e,i,s,r),S}this.resolveAsync(p),this.dag.registerLineDataSourceDependency(t,p.packageId||o,[p.queryKey]);let d=chunkNH74IT7B_cjs.O(p.queryKey);return this.storeLineResult(t,d,e,i,s,r),d}if(p.type==="error")throw u?.(),p.error;return u?.(),this.registerLineWithTags(t,r,i,s),this.storeLineResult(t,p.value,e,i,s,r),p.value}executeRaw(e,t=-1){let r=this.vm.getStack().length,i=this.armCancellation(e,"executeRaw");chunkZLRJ7TDP_cjs.a(this.queryClient);let s=chunkDTOSRC6E_cjs.c(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>r;)this.vm.pop();return s.type!=="pending"&&i?.(),s}async resolveAsync(e){let{queryKey:t,resolver:r,packageId:i,signal:s}=e,o=i||"_engine",c=`${o}:${t}`;try{if(await r,this.asyncFailures.delete(c),s.aborted){chunkTTFO4YDP_cjs.a.staleDataDiscarded(t,"signal aborted after resolve");return}this.batcher.add({queryKey:t,packageId:o,signal:s,isError:!1});}catch(a){if(s.aborted){chunkTTFO4YDP_cjs.a.staleDataDiscarded(t,"signal aborted after error");return}let l=a instanceof Error?a:new Error(String(a)),u=(this.asyncFailures.get(c)??0)+1;if(this.asyncFailures.set(c,u),u>U.MAX_ASYNC_FAILURES)return;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 r=this.config.performance.maxDocumentLines;if(chunkUURM7P3P_cjs.b(e,r)>r)throw chunk6SYU4MH7_cjs.c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${r.toLocaleString("en-US")} lines, which is the most the engine will process in one pass`,{maxLines:r});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 a of s){a.error&&o.errors.push(`Line ${a.lineNumber}: ${a.error}`);for(let l of a.inlineSolves)l.error&&o.errors.push(`Line ${a.lineNumber}: ${l.error}`);}if(t.includeDiagnostics??false){let a=this.diagnosticPipeline.collectReports();a.length>0&&(o.diagnostics=a[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
4
+ `),r=this.lexer.scanDocument(t);return this.processScanResults(r)}batchLinesCarryingTag(e,t){let r=this.batchTagIndex;if(r===null){r=new Map;for(let i=0;i<e.length;i++){let s=e[i].text;if(!(s.indexOf("#")<0))for(let o of chunkU54BIYXO_cjs.b(s)){let c=r.get(o);c===void 0?r.set(o,[i+1]):c.push(i+1);}}this.batchTagIndex=r;}return r.get(t.toLowerCase())??[]}processScanResults(e){let t=[],r=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;let s=this.batchTagIndex;this.batchTagIndex=null;try{for(let o of e){let c=o.text,a=o.lineNumber,l=o.startOffset,u=o.endOffset,p=o.classification.skip,h=o.inlineSolves.map(S=>({start:S.start,end:S.end,expression:S.expression,lineNumber:a,columnNumber:S.columnNumber})),y=h.length>0,d={lineNumber:a,text:c,startPosition:l,endPosition:u,isEmpty:p,hasInlineSolves:y,inlineSolves:h,expression:null,result:null,error:null};if(o.error)d.error=o.error.message;else if(!p){let S=c.trim().startsWith(":");if(y&&!S)for(let b of h)try{b.result=this.evaluateLine(a,b.expression);}catch(A){let L=A instanceof Error?A.message:String(A);b.error=L;}else {let b=o.classification.contentOffset,L=(b===void 0?c:c.slice(b-l)).trim();if(L)try{let D=this.evaluateLineWithPreTokenized(a,L,o.tokens);d.expression=L,d.result=D[0];}catch(D){let Ae=D instanceof Error?D.message:String(D);d.error=Ae;}}}t.push(d);}}finally{this.batchScanResults=r,this.batchParsedLines=i,this.batchTagIndex=s,this.lineContext=null;}return t}evaluateLineWithPreTokenized(e,t,r){let i=[],s=false;for(let o of r)(o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o);return [this.evaluateWithTokens(e,t,i,s)]}parseExpression(e,t,r,i=true){this.parser.setBuilder(e),this.parser.load(t,this.config.validation.autoBalanceParens?r: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=true;for(let a=0;a<o;a++){let l=t[a].type;if(l!=="NUMBER"&&l!=="COLON"){c=false;break}}if(c){let a=t.slice(0,o+2).map(l=>l.value).join("");throw chunk6SYU4MH7_cjs.c.parsing("INVALID_TIME_LITERAL",`"${a}" is not a valid time`,{tokenType:t[o].type,tokenValue:a})}e.reset();try{this.parseExpression(e,t.slice(o+1),r,!1);return}catch{}}throw chunk6SYU4MH7_cjs.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 chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=chunkDTOSRC6E_cjs.c(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw chunk6SYU4MH7_cjs.c.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return r.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 r=0;r<e.length;r++)if(r%2===0){if(e[r].type!=="IDENT"&&e[r].type!=="UNIT")return null;t.push(e[r].value);}else if(e[r].type!=="STAR")return null;return t}solveEquation(e,t=-1){let r=[];for(let c of e.factorNames){let a=this.vm.getVar(c);if(a===void 0)return chunkNH74IT7B_cjs.P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${c}" is not yet defined.`);if(a.type!==7)return chunkNH74IT7B_cjs.P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${c}" must be a Matrix (got a different value type).`);r.push(a);}let i=r[0].value;for(let c=1;c<r.length;c++){let a=chunk5N4XDULO_cjs._(i,r[c].value);if(a.type===13)return a;i=a.value;}let s=chunk5N4XDULO_cjs.da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?chunkNH74IT7B_cjs.P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):chunk5N4XDULO_cjs._(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 r=[];for(;t<e.length&&e[t].type==="IDENT";)r.push(e[t].value),t++;if(r.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(r,i.value,s.value)&&(this.clearCompiledCache(),this.documentModel?.invalidateAll()),Ye(`${r.join(" ")} defined`))}tryCompoundAssignment(e,t=-1){if(e.length<2)return null;let r=e[0],i=e[1],s=r.type==="IDENT"||r.type==="UNIT",o=i.type==="PLUS_EQUALS"||i.type==="MINUS_EQUALS";if(!s||!o)return null;let c=e.slice(2);if(c.length===0)throw chunk6SYU4MH7_cjs.c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${r.value} ${i.value}" needs an expression on the right, e.g. "${r.value} ${i.value} 10".`);let a=r.value;this.accumulatorNames.add(a),this.vm.getVar(a)===void 0&&this.vm.setVar(a,chunkNH74IT7B_cjs.n(0));let l=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[chunkYV4GDW5A_cjs.b("IDENT",a,[r]),chunkYV4GDW5A_cjs.b(l.type,l.text,[i]),chunkYV4GDW5A_cjs.b("LPAREN","(",[i]),...c,chunkYV4GDW5A_cjs.b("RPAREN",")",[i])],p=chunkDTOSRC6E_cjs.c(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 chunk6SYU4MH7_cjs.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(a,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 l=e.slice(0,-1);if(l.length===0)throw chunk6SYU4MH7_cjs.c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(l.length===1&&(l[0].type==="IDENT"||l[0].type==="UNIT")){let u=l[0].value,p=this.vm.getEquation(u),h=this.vm.getScalarEquation(u);if(p){let y=this.solveEquation(p,t);if(!(y.type===13&&y.value==="EQUATION_FACTOR_NOT_MATRIX")||!h)return y}if(h)return this.solveScalarEquation(h,t)}return this.simplifySymbolically(l,t)}if(chunkU54BIYXO_cjs.e(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(l=>l.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 l=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],l),l}let c=s[s.length-1],a=s.slice(0,-1);return this.vm.defineEquation(c,a,this.compileAdHoc(o)),this.vm.defineScalarEquation(c,this.compileAdHoc(e.slice(0,i)),this.compileAdHoc(o)),Ye(`${c} stored as an equation \u2014 solve with "${c} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let r=e.slice(0,t),i=e.slice(t+1);if(i.some(c=>c.type==="EQUALS"))return null;let s=this.equationUnknowns(r,i);if(s.length!==1)return null;let o=s[0];return this.vm.defineScalarEquation(o,this.compileAdHoc(r),this.compileAdHoc(i)),Ye(`${o} stored as an equation \u2014 solve with "${o} =>"`)}equationUnknowns(e,t){let r=[];for(let i of [...e,...t])i.type!=="IDENT"&&i.type!=="UNIT"||this.vm.getVar(i.value)===void 0&&(this.vm.hasUserFunction(i.value)||r.includes(i.value)||r.push(i.value));return r}solveScalarEquation(e,t=-1){let r=this.executeSymbolicTolerant(e.lhsProgram,t),i=this.executeSymbolicTolerant(e.rhsProgram,t);return chunk6ADFAXTZ_cjs.k(r,i,e.variable)}lexToTokens(e,t,r=true){let i=[],s=false;if(r&&!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,r,i,s=-1){let o=this.bytecodeCache.get(e);if(o&&!i){let b=this.compiledFrontHalf.get(e);if(b)return this.touchCompiled(e,o),{kind:"ready",normalizedTokens:b.normalizedTokens,reads:b.reads,writes:b.writes,program:o,cached:true}}let c=i?void 0:this.failedParses.get(e),a;if(c)this.touchFailedParse(e,c),a=c.normalizedTokens;else {let b=$e(e,this.config.validation);if(!b.passed)return {kind:"error",stage:"length",error:b.error.engineError};let A=t.filter(D=>D.type!=="COMMENT");if(A.length===0)return {kind:"empty"};a=this.normalizer.normalize(A,i);let L=je(a,this.config.validation);if(!L.passed)return {kind:"error",stage:"complexity",error:L.engineError,normalizedTokens:a}}let l,u=null;try{if(l=this.tryDefineUserUnit(a),l===null){let b=this.tryCompoundAssignment(a,s);b!==null&&(l=b,u=Ce(a));}l===null&&(l=this.trySymbolicGrammar(a,s));}catch(b){let{reads:A,writes:L}=Ce(a);return {kind:"error",stage:"parse",error:chunk6SYU4MH7_cjs.d(b),reads:A,writes:L,normalizedTokens:a}}if(l!==null)return {kind:"symbolic-solve",normalizedTokens:a,value:l,reads:u?.reads,writes:u?.writes};if(c)return {kind:"error",stage:"parse",error:c.error,reads:c.reads,writes:c.writes,normalizedTokens:a};let{reads:p,writes:h}=Ce(a);if(o)return this.compiledFrontHalf.set(e,{normalizedTokens:a,reads:p,writes:h}),this.touchCompiled(e,o),{kind:"ready",normalizedTokens:a,reads:p,writes:h,program:o,cached:true};let y=this.builderPool[this.builderPoolIndex++%this.builderPool.length];y.reset();let d,S=null;try{let b=_.track("parser",()=>(this.parseExpression(y,a,r),y.build()));d=b.result,S=b.alloc;}catch(b){let A=chunk6SYU4MH7_cjs.d(b);return this.rememberFailedParse(e,{error:A,normalizedTokens:a,reads:p,writes:h}),{kind:"error",stage:"parse",error:A,reads:p,writes:h,normalizedTokens:a}}return this.cacheBytecode(e,d,{normalizedTokens:a,reads:p,writes:h}),{kind:"ready",normalizedTokens:a,reads:p,writes:h,program:d,cached:false,parserAlloc:S}}preflightAsync(e,t,r,i,s,o){if(!this.mayResolve(t))return {kind:"proceed"};let c=new AbortController,a=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("preflightAsync"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("preflightAsync");let l=c.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",l,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(r,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=chunkNH74IT7B_cjs.O(u.queryKey);return this.storeLineResult(r,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",a),{kind:"proceed"}}evaluateWithTokens(e,t,r,i){let s=this.prepareExpression(t,r,i,void 0,e);if(s.kind==="empty"){let p=chunkNH74IT7B_cjs.n(0);return this.lineCache.set(e,new q(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:a,program:l}=s,u=this.preflightAsync(o,l,e,t,c,a);return u.kind==="pending"?u.value:this.executeAndStore(l,e,t,c,a,"_engine")}evaluateLine(e,t){let r=this.evaluateLineWithDebug(e,t);if(r.error)throw r.engineError?r.engineError:chunk6SYU4MH7_cjs.c.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return chunkNH74IT7B_cjs.l(r.value)}evaluateLineWithDebug(e,t,r="expression"){let i=t.match(/^s`([^`]*)`$/);if(i){let s=i[1];return {...this.evaluateExpressionWithDiagnostic(s,e,r),inlineSolve:{start:0,end:t.length,expression:s,lineNumber:e,columnNumber:1}}}return this.evaluateExpressionWithDiagnostic(t,e,r)}addDiagnosticStage(e,t,r,i,s,o,c,a,l){e.push({stage:t,label:r,icon:i,colorClass:s,stepNumber:o,elapsedNs:c,skipped:a,output:l});}evaluateExpressionWithDiagnostic(e,t,r="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,c=_.isEnabled(),a=[],l=[],u=0,p=$e(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(l,"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:chunkHG4NPDN5_cjs.c.PipelineStart,elapsedNs:0,expression:e,inputType:r}),this.addDiagnosticStage(l,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:r}),this.addDiagnosticStage(l,"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 h=s?m=>{i.fireTokenEmitted({type:chunkHG4NPDN5_cjs.c.TokenEmitted,elapsedNs:0,expression:e,token:{type:m.type,value:m.value,offset:m.offset||0,line:m.line||t,col:m.col||0}});}:void 0,y=_.track("lexer",()=>this.lexToTokens(e,h)),d=y.result.tokens,S=y.result.hasParens,b=y.result.compiled;if(c&&y.alloc&&a.push(y.alloc),s){let m={};for(let P of d)m[P.type]=(m[P.type]||0)+1;this.addDiagnosticStage(l,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:d.length,tokenTypes:m,hasParens:S,locale:this.localeCode,tokens:[...d]});let N=[];for(let P=0;P<d.length;P++){let se=d[P];if(se.type==="INLINE_SOLVE_START"){let B=-1;for(let K=P+1;K<d.length;K++)if(d[K].type==="BACKTICK_OPEN"){B=K;break}if(B>P){let Nn=d.slice(P+1,B).map(An=>An.value).join("");N.push({startTokenIndex:P,endTokenIndex:B,expression:Nn,columnNumber:se.col||1}),P=B;}}}this.addDiagnosticStage(l,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:N.length>0,inlineSolveSpans:N});}if(!b&&d.length===0){let m=chunkNH74IT7B_cjs.n(0);return this.lineCache.set(t,new q(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:m,tokens:d,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let A=0,L=[],D=new Map,Ae=s?m=>{A++,L.push(m),D.set(m.rule,(D.get(m.rule)||0)+1),i.fireTokenFused({type:chunkHG4NPDN5_cjs.c.TokenFused,elapsedNs:0,expression:e,ruleName:m.rule,sourceTokenCount:m.sourceTokens.length,fusedTokenType:m.fusedToken.type,fusedTokenValue:m.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:chunkHG4NPDN5_cjs.c.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:d.length});let M=this.bytecodeCache.get(e);s&&!M&&this.parser.setDiagnosticPipeline(i,e);let v=this.prepareExpression(e,d,S,Ae,t);b&&v.kind==="ready"&&(d=v.normalizedTokens),c&&v.kind==="ready"&&v.parserAlloc&&a.push(v.parserAlloc),s&&!M&&this.parser.setDiagnosticPipeline(void 0,"");let k=v.kind==="empty"?d:v.normalizedTokens??d;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:chunkHG4NPDN5_cjs.c.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:k.length,fusionsCount:A}),this.addDiagnosticStage(l,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:d.length,outputTokenCount:k.length,fusions:L,rulesApplied:[...D.entries()].map(([m,N])=>({rule:m,count:N})),tokens:[...k],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(k)})):this.addDiagnosticStage(l,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:d.length,outputTokenCount:d.length,fusions:[],rulesApplied:[],tokens:[...d],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(d)})),v.kind==="empty"||v.kind==="error"&&v.stage==="length"){if(s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:v.kind==="empty",totalTokens:d.length,totalOpcodes:0}),v.kind==="empty"){let m=chunkNH74IT7B_cjs.n(0);return this.lineCache.set(t,new q(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:m,tokens:d,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:chunkNH74IT7B_cjs.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 ne=je(k,this.config.validation);if(v.kind==="error"&&v.stage==="complexity")return s&&(this.addDiagnosticStage(l,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:ne.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0},errorMessage:ne.errorMessage}),i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d.length,totalOpcodes:0})),{value:chunkNH74IT7B_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:ne.errorMessage,engineError:ne.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(l,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:ne.complexityScore??k.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0}}),v.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d.length,totalOpcodes:0});let m={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,v.value,m,v.reads??[],v.writes??[],e),{value:v.value,tokens:k,program:m,debug:void 0,diagnostic:void 0}}let ge=v.reads??[],re=v.writes??[];if(s&&(this.addDiagnosticStage(l,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ge,writes:re,isAssignment:re.length>0}),this.addDiagnosticStage(l,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!M,cacheSize:this.bytecodeCache.size,cacheKey:e}),M?i.fireCacheHit({type:chunkHG4NPDN5_cjs.c.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:chunkHG4NPDN5_cjs.c.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),v.kind==="error"&&v.stage==="parse")return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d.length,totalOpcodes:0}),{value:chunkNH74IT7B_cjs.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 chunk6SYU4MH7_cjs.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(l,"parser","Parser","\u{1F333}","parser",8,u,!!M,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(l,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!M,{type:"compiler",opcodeCount:x.opcodes.length,numberConstants:x.numbers.length,stringConstants:x.strings.length,hasAsync:x.hasAsync,cached:!!M}),i.fireBytecodeBuilt({type:chunkHG4NPDN5_cjs.c.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:x.opcodes.length,numbersLength:x.numbers.length,stringsLength:x.strings.length,isCached:!!M}));let Rn=this.mayResolve(x),ie=this.preflightAsync(k,x,t,e,ge,re);if(s&&(ie.kind==="pending"?this.addDiagnosticStage(l,"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}):Rn?this.addDiagnosticStage(l,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(l,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:true})),ie.kind==="pending")return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d.length,totalOpcodes:x.opcodes.length}),{value:ie.value,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(l,ie.value,k,x,null):void 0};let wn=s&&this.config.diagnostic.vmTraceEnabled===true,w;try{let m=_.track("vm",()=>this.executeAndStore(x,t,e,ge,re,"_engine",wn?i:void 0,e),{cacheHit:!!M});w=m.result,c&&m.alloc&&a.push(m.alloc);}catch(m){let N=chunk6SYU4MH7_cjs.d(m);return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d.length,totalOpcodes:x.opcodes.length}),{value:chunkNH74IT7B_cjs.n(0),tokens:k,program:x,error:N.message,engineError:N,debug:void 0,diagnostic:void 0}}let he=w.type===12;if(s){let m=he?"pending":String(w.value??""),N=he?"Pending":w.unit?"Uom":"Number";this.addDiagnosticStage(l,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:x.opcodes.length,stackDepth:this.vm.getStack().length,resultType:N,resultValue:m,isPending:he});}if(he)return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d.length,totalOpcodes:x.opcodes.length}),{value:w,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(l,w,k,x,null):void 0};if(c&&a.length>0&&(this.lastTelemetry=_.createTelemetry(e,a,!!M)),s&&(this.addDiagnosticStage(l,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:ge,writesRegistered:re,dataSourcesRegistered:[]}),this.addDiagnosticStage(l,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(l,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(w.value),formattedValue:String(w.value),valueType:w.type===0?"Number":"Value",unit:w.unit}),i.fireVmHalt({type:chunkHG4NPDN5_cjs.c.VmHalt,elapsedNs:0,expression:e,result:w?{type:w.type,value:w.value,unit:w.unit}:void 0}),this.addDiagnosticStage(l,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:d.length,totalOpcodes:x.opcodes.length,cacheHit:!!M}),i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d.length,totalOpcodes:x.opcodes.length})),s){let N=i.collectReports()[0]?.toJSON(),P=N;if(N){let se=N.parselets.slice(o),B={};for(let K of se)B[K.parseletCategory]=(B[K.parseletCategory]??0)+1;P={...N,parselets:se,summary:{...N.summary,totalParselets:Object.keys(B).length,parseCategories:B}};}return {value:w,tokens:k,program:x,debug:P,diagnostic:this.buildDiagnosticResult(l,w,k,x,null)}}return {value:w,tokens:k,program:x}}buildDiagnosticResult(e,t,r,i,s){return {stages:e,value:t,tokens:r,program:i,error:s,dagSnapshot:this.dag.getSnapshot(),cacheSnapshot:this.getCacheSnapshot(),batcherMetrics:this.getBatcherMetrics(),checkpoints:this.getCheckpoints()}}reEvaluateLine(e,t){let r=this.lineCache.get(e,t);if(!r)return;let i=this.bytecodeCache.get(t);if(!i)return;if(this.touchCompiled(t,i),this.mayResolve(r.bytecode)){let c=new AbortController,a=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("reEvaluateLine preflight");let l=c.signal,u=this.resolverRegistry.preflightAll([],r.bytecode,"_engine",l,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),chunkNH74IT7B_cjs.O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",a);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),chunkNH74IT7B_cjs.O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return r.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 r=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return r.length===0?[]:this.normalizer.normalize(r)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?chunkTTFO4YDP_cjs.a.keystrokeSignalSet(e.aborted):chunkTTFO4YDP_cjs.a.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(":"),a=c>0?parseInt(o.slice(0,c),10)||0:parseInt(o,10)||0,l=c>0?o.slice(c+1):void 0,u=l!==void 0?this.lineCache.get(a,l):this.lineCache.getEntryForLine(a);u&&t.push({key:o,lineNumber:a,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),r=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(r);return qe({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode,readings:this.readDates(e)})}evaluateIsolated(e){let{tokens:t,hasParens:r}=this.lexToTokens(e),i=this.prepareExpression(e,t,r,void 0,-1);if(i.kind==="empty")return chunkNH74IT7B_cjs.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 chunk6SYU4MH7_cjs.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:r}=t,i=this.prepareExpression(e,t.tokens,r),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 chunk6SYU4MH7_cjs.b(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:r}=this.lexToTokens(e);return this.prepareExpression(e,t,r).kind!=="error"}executeCached(e,t=-1){if(e.opcodes.length===0)return chunkNH74IT7B_cjs.n(0);let r=this.executeRaw(e,t);if(r.type==="pending")return this.resolveAsync(r),chunkNH74IT7B_cjs.O(r.queryKey);if(r.type==="error")throw r.error;return r.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 r=this.evaluateLine(-1,e);return r.isFault()?NaN:r.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.asyncFailures.clear(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),chunkZLRJ7TDP_cjs.b()===this.queryClient&&chunkZLRJ7TDP_cjs.a(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.clearCompiledCache(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null,this.lineContext=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let l of Object.keys(e.dataSourceDeps)){let u=Number(l);Number.isNaN(u)||t.add(u);}let r=this.lineCache.snapshotEntries(),i=new Map;for(let{line:l,entry:u}of r){let p=t.has(l)||u.bytecode.hasAsync;p&&t.add(l);let h=u.writeVariable;if(h){let y=i.get(h);(!y||l>=y.line)&&i.set(h,{line:l,async:p});}}let s={};for(let[l,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(l)?.async)try{s[l]=Be(u,`variable "${l}"`);}catch(p){if(p instanceof chunk6SYU4MH7_cjs.b&&p.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(_e),c=[];for(let{line:l,expression:u,entry:p}of r){if(t.has(l)||p.result.type===12)continue;let h;try{h=Be(p.result,`line ${l}`);}catch(y){if(y instanceof chunk6SYU4MH7_cjs.b&&y.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw y}c.push({line:l,expression:u,result:h,bytecode:ue(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let a=Array.from(this.bytecodeCache.entries()).map(([l,u])=>({expression:l,program:ue(u)}));return {format:Z,version:Q,engineVersion:chunkA3CNNRFM_cjs.a,locale:this.localeCode,variables:s,userFunctions:o,lineCache:c,bytecodeCache:a}}static fromJSON(e,t={}){cn(e);let r=t.locale??e.locale??"en",i=new U({locale:r,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages,calendar:t.calendar});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,r]of Object.entries(e.variables))this.vm.setVar(t,Fe(r));for(let t of e.userFunctions){let r=Ue(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new q(Fe(t.result),pe(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,r,t.expression),this.registerLineWithTags(t.line,t.expression,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:r}of e.bytecodeCache)this.bytecodeCache.set(t,pe(r));}evaluateIncremental(e,t){let r=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,chunkNH74IT7B_cjs.n(t));let i=new Map;for(let s of r){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 l=chunkNH74IT7B_cjs.P(c.error.code,c.error.message);i.set(s,l),o.result=l;continue}let a=c.value;i.set(s,a),o.result=a;}return i}};U.MAX_ASYNC_FAILURES=3,U.GOAL_SEEK_MAX_NESTING_DEPTH=1,U.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 Tn=U;exports.a=ir;exports.b=Bn;exports.c=tn;exports.d=Z;exports.e=Q;exports.f=V;exports.g=gr;exports.h=ze;exports.i=ke;exports.j=$e;exports.k=je;exports.l=Ce;exports.m=Ar;exports.n=Pr;exports.o=Tn;//# sourceMappingURL=chunk-ZGA7X625.cjs.map
5
+ //# sourceMappingURL=chunk-ZGA7X625.cjs.map