solve-engine 2.16.0 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/dist/{BytecodeBuilder-CRYfrFfq.d.cts → BytecodeBuilder-aqVa7Plx.d.cts} +10 -0
  2. package/dist/{BytecodeBuilder-CRYfrFfq.d.ts → BytecodeBuilder-aqVa7Plx.d.ts} +10 -0
  3. package/dist/{EngineError-Cv5q4Rbv.d.cts → EngineError-DTk7I7hZ.d.cts} +24 -0
  4. package/dist/{EngineError-Cv5q4Rbv.d.ts → EngineError-DTk7I7hZ.d.ts} +24 -0
  5. package/dist/{PackageCompatibility-CHQ4kDT8.d.ts → PackageCompatibility-BGXSFuL9.d.ts} +1 -1
  6. package/dist/{PackageCompatibility-BET0iFb9.d.cts → PackageCompatibility-BZCqaTOO.d.cts} +1 -1
  7. package/dist/{PackageRegistry-YmfowYr1.d.ts → PackageRegistry-BRoVOYzg.d.ts} +78 -5
  8. package/dist/{PackageRegistry-DzmG-Rvu.d.cts → PackageRegistry-rMGnTh7W.d.cts} +78 -5
  9. package/dist/{Parselet-CK0bNO1l.d.ts → Parselet-B-WyUtX4.d.ts} +5 -1
  10. package/dist/{Parselet-DOGmj6N6.d.cts → Parselet-Bkbp9CKD.d.cts} +5 -1
  11. package/dist/{ScopeManager-BtqiTVjG.d.cts → ScopeManager-bCYewWVt.d.cts} +2 -2
  12. package/dist/{ScopeManager-C6c1WmJD.d.ts → ScopeManager-gB9UengK.d.ts} +2 -2
  13. package/dist/{TokenNormalizer-BfTHg1qt.d.cts → TokenNormalizer-MXaKLJ_m.d.cts} +182 -0
  14. package/dist/{TokenNormalizer-d7F1KQFs.d.ts → TokenNormalizer-OTPS0Otq.d.ts} +182 -0
  15. package/dist/{VMCheckpoints-DJdvpliw.d.ts → VMCheckpoints-BDRY1Kx8.d.ts} +2 -2
  16. package/dist/{VMCheckpoints-BFDlaGse.d.cts → VMCheckpoints-DGar9Yg8.d.cts} +2 -2
  17. package/dist/{WorkerError-FH7KXX4_.d.cts → WorkerError-DGBNM3gA.d.cts} +1 -1
  18. package/dist/{WorkerError-J3v3ix_z.d.ts → WorkerError-DpZgKRks.d.ts} +1 -1
  19. package/dist/{chunk-UZSPBFZN.js → chunk-2DPKJ2SM.js} +2 -2
  20. package/dist/{chunk-UZSPBFZN.js.map → chunk-2DPKJ2SM.js.map} +1 -1
  21. package/dist/{chunk-O3ALJLYC.js → chunk-3GR46UOX.js} +2 -2
  22. package/dist/{chunk-O3ALJLYC.js.map → chunk-3GR46UOX.js.map} +1 -1
  23. package/dist/{chunk-PREIL3IB.cjs → chunk-3SSMOVWB.cjs} +2 -2
  24. package/dist/{chunk-PREIL3IB.cjs.map → chunk-3SSMOVWB.cjs.map} +1 -1
  25. package/dist/{chunk-VOTTSM4L.cjs → chunk-43FUDMIP.cjs} +3 -3
  26. package/dist/{chunk-VOTTSM4L.cjs.map → chunk-43FUDMIP.cjs.map} +1 -1
  27. package/dist/{chunk-XK23K3EJ.js → chunk-4ETS224G.js} +2 -2
  28. package/dist/{chunk-XK23K3EJ.js.map → chunk-4ETS224G.js.map} +1 -1
  29. package/dist/chunk-4XXUXRST.js +2 -0
  30. package/dist/chunk-4XXUXRST.js.map +1 -0
  31. package/dist/{chunk-55B4PSPM.js → chunk-6ERKCASV.js} +2 -2
  32. package/dist/{chunk-55B4PSPM.js.map → chunk-6ERKCASV.js.map} +1 -1
  33. package/dist/{chunk-GWCBPITD.cjs → chunk-6YM67DWH.cjs} +3 -3
  34. package/dist/{chunk-GWCBPITD.cjs.map → chunk-6YM67DWH.cjs.map} +1 -1
  35. package/dist/{chunk-6U66HQKQ.cjs → chunk-75JLWK4L.cjs} +2 -2
  36. package/dist/{chunk-6U66HQKQ.cjs.map → chunk-75JLWK4L.cjs.map} +1 -1
  37. package/dist/chunk-AYRVYGQO.js +3 -0
  38. package/dist/chunk-AYRVYGQO.js.map +1 -0
  39. package/dist/{chunk-VJP4GGCW.cjs → chunk-BNCBB4H5.cjs} +2 -2
  40. package/dist/{chunk-VJP4GGCW.cjs.map → chunk-BNCBB4H5.cjs.map} +1 -1
  41. package/dist/chunk-CCTO74QZ.js +5 -0
  42. package/dist/chunk-CCTO74QZ.js.map +1 -0
  43. package/dist/chunk-CO2BI6WL.cjs +3 -0
  44. package/dist/chunk-CO2BI6WL.cjs.map +1 -0
  45. package/dist/chunk-EN3CDYOS.cjs +2 -0
  46. package/dist/chunk-EN3CDYOS.cjs.map +1 -0
  47. package/dist/{chunk-GWJJRH32.js → chunk-EQDT42JG.js} +3 -3
  48. package/dist/{chunk-GWJJRH32.js.map → chunk-EQDT42JG.js.map} +1 -1
  49. package/dist/chunk-G2MFTERZ.cjs +2 -0
  50. package/dist/chunk-G2MFTERZ.cjs.map +1 -0
  51. package/dist/chunk-G63TMUL2.js +2 -0
  52. package/dist/chunk-G63TMUL2.js.map +1 -0
  53. package/dist/{chunk-5EX2FCM3.js → chunk-GE5VBDFX.js} +3 -3
  54. package/dist/{chunk-5EX2FCM3.js.map → chunk-GE5VBDFX.js.map} +1 -1
  55. package/dist/{chunk-UUAFDZK6.cjs → chunk-H3JXNH7X.cjs} +3 -3
  56. package/dist/{chunk-UUAFDZK6.cjs.map → chunk-H3JXNH7X.cjs.map} +1 -1
  57. package/dist/{chunk-2XZCLDHJ.cjs → chunk-J7ABVGZH.cjs} +2 -2
  58. package/dist/{chunk-2XZCLDHJ.cjs.map → chunk-J7ABVGZH.cjs.map} +1 -1
  59. package/dist/chunk-JVMINMAB.js +2 -0
  60. package/dist/chunk-JVMINMAB.js.map +1 -0
  61. package/dist/chunk-JYLNQOPU.cjs +2 -0
  62. package/dist/chunk-JYLNQOPU.cjs.map +1 -0
  63. package/dist/{chunk-JOIQFDZQ.js → chunk-KEA5HRL3.js} +2 -2
  64. package/dist/{chunk-JOIQFDZQ.js.map → chunk-KEA5HRL3.js.map} +1 -1
  65. package/dist/chunk-KWA257PC.cjs +3 -0
  66. package/dist/chunk-KWA257PC.cjs.map +1 -0
  67. package/dist/{chunk-TVE2DNPU.js → chunk-LJFS3XHW.js} +2 -2
  68. package/dist/{chunk-TVE2DNPU.js.map → chunk-LJFS3XHW.js.map} +1 -1
  69. package/dist/{chunk-C5MP74ER.js → chunk-MRRMIBHE.js} +2 -2
  70. package/dist/{chunk-C5MP74ER.js.map → chunk-MRRMIBHE.js.map} +1 -1
  71. package/dist/chunk-N64ZK6CL.cjs +2 -0
  72. package/dist/{chunk-EEVUKZ5B.cjs.map → chunk-N64ZK6CL.cjs.map} +1 -1
  73. package/dist/chunk-O3BDXOQJ.js +2 -0
  74. package/dist/chunk-O3BDXOQJ.js.map +1 -0
  75. package/dist/chunk-PHNSXQ4L.cjs +2 -0
  76. package/dist/chunk-PHNSXQ4L.cjs.map +1 -0
  77. package/dist/chunk-PIZQIQVM.js +3 -0
  78. package/dist/chunk-PIZQIQVM.js.map +1 -0
  79. package/dist/{chunk-IPOU3JTA.js → chunk-QTSDIDAS.js} +3 -3
  80. package/dist/{chunk-IPOU3JTA.js.map → chunk-QTSDIDAS.js.map} +1 -1
  81. package/dist/{chunk-P4ETODMP.js → chunk-RLTH2H3U.js} +2 -2
  82. package/dist/{chunk-P4ETODMP.js.map → chunk-RLTH2H3U.js.map} +1 -1
  83. package/dist/{chunk-WOIJPV7Z.js → chunk-SEOIKHYK.js} +2 -2
  84. package/dist/{chunk-WOIJPV7Z.js.map → chunk-SEOIKHYK.js.map} +1 -1
  85. package/dist/{chunk-XZYZS4BP.cjs → chunk-TCHKFSZD.cjs} +2 -2
  86. package/dist/{chunk-XZYZS4BP.cjs.map → chunk-TCHKFSZD.cjs.map} +1 -1
  87. package/dist/{chunk-W5ELYJ4Z.cjs → chunk-TL545PXW.cjs} +2 -2
  88. package/dist/{chunk-W5ELYJ4Z.cjs.map → chunk-TL545PXW.cjs.map} +1 -1
  89. package/dist/{chunk-FAGFPVYK.cjs → chunk-TRDOYAKJ.cjs} +2 -2
  90. package/dist/{chunk-FAGFPVYK.cjs.map → chunk-TRDOYAKJ.cjs.map} +1 -1
  91. package/dist/chunk-X7DFJS7R.cjs +5 -0
  92. package/dist/chunk-X7DFJS7R.cjs.map +1 -0
  93. package/dist/{chunk-EXCFCHAT.cjs → chunk-XPJGDGJF.cjs} +2 -2
  94. package/dist/{chunk-EXCFCHAT.cjs.map → chunk-XPJGDGJF.cjs.map} +1 -1
  95. package/dist/constants.cjs +1 -1
  96. package/dist/constants.js +1 -1
  97. package/dist/engine.cjs +1 -1
  98. package/dist/engine.d.cts +8 -8
  99. package/dist/engine.d.ts +8 -8
  100. package/dist/engine.js +1 -1
  101. package/dist/errors.cjs +1 -1
  102. package/dist/errors.d.cts +3 -3
  103. package/dist/errors.d.ts +3 -3
  104. package/dist/errors.js +1 -1
  105. package/dist/format.cjs +1 -1
  106. package/dist/format.js +1 -1
  107. package/dist/index.cjs +1 -1
  108. package/dist/index.d.cts +8 -8
  109. package/dist/index.d.ts +8 -8
  110. package/dist/index.js +1 -1
  111. package/dist/language.d.cts +7 -7
  112. package/dist/language.d.ts +7 -7
  113. package/dist/lexer.cjs +1 -1
  114. package/dist/lexer.js +1 -1
  115. package/dist/normalizer.cjs +1 -1
  116. package/dist/normalizer.d.cts +2 -2
  117. package/dist/normalizer.d.ts +2 -2
  118. package/dist/normalizer.js +1 -1
  119. package/dist/packages.cjs +1 -1
  120. package/dist/packages.d.cts +6 -6
  121. package/dist/packages.d.ts +6 -6
  122. package/dist/packages.js +1 -1
  123. package/dist/parser.cjs +1 -1
  124. package/dist/parser.d.cts +2 -2
  125. package/dist/parser.d.ts +2 -2
  126. package/dist/parser.js +1 -1
  127. package/dist/resolvers.d.cts +1 -1
  128. package/dist/resolvers.d.ts +1 -1
  129. package/dist/testing.cjs +2 -2
  130. package/dist/testing.d.cts +7 -7
  131. package/dist/testing.d.ts +7 -7
  132. package/dist/testing.js +1 -1
  133. package/dist/uom.cjs +1 -1
  134. package/dist/uom.d.cts +1 -1
  135. package/dist/uom.d.ts +1 -1
  136. package/dist/uom.js +1 -1
  137. package/dist/vm.cjs +1 -1
  138. package/dist/vm.d.cts +5 -5
  139. package/dist/vm.d.ts +5 -5
  140. package/dist/vm.js +1 -1
  141. package/dist/worker.cjs +2 -2
  142. package/dist/worker.d.cts +7 -7
  143. package/dist/worker.d.ts +7 -7
  144. package/dist/worker.js +1 -1
  145. package/package.json +1 -1
  146. package/dist/chunk-35RNQ2OQ.js +0 -5
  147. package/dist/chunk-35RNQ2OQ.js.map +0 -1
  148. package/dist/chunk-5CWVWMIY.js +0 -2
  149. package/dist/chunk-5CWVWMIY.js.map +0 -1
  150. package/dist/chunk-7EMZOBGW.cjs +0 -3
  151. package/dist/chunk-7EMZOBGW.cjs.map +0 -1
  152. package/dist/chunk-CUDPOWXA.js +0 -2
  153. package/dist/chunk-CUDPOWXA.js.map +0 -1
  154. package/dist/chunk-EEVUKZ5B.cjs +0 -2
  155. package/dist/chunk-ERMNQ5QJ.js +0 -2
  156. package/dist/chunk-ERMNQ5QJ.js.map +0 -1
  157. package/dist/chunk-FVQWN5HZ.cjs +0 -2
  158. package/dist/chunk-FVQWN5HZ.cjs.map +0 -1
  159. package/dist/chunk-IMXSVHQK.cjs +0 -2
  160. package/dist/chunk-IMXSVHQK.cjs.map +0 -1
  161. package/dist/chunk-LZSSAH5D.cjs +0 -2
  162. package/dist/chunk-LZSSAH5D.cjs.map +0 -1
  163. package/dist/chunk-NAZ6PGLS.cjs +0 -3
  164. package/dist/chunk-NAZ6PGLS.cjs.map +0 -1
  165. package/dist/chunk-Q3PSTNSY.js +0 -2
  166. package/dist/chunk-Q3PSTNSY.js.map +0 -1
  167. package/dist/chunk-SPOECHDG.cjs +0 -5
  168. package/dist/chunk-SPOECHDG.cjs.map +0 -1
  169. package/dist/chunk-W64AWQCX.js +0 -3
  170. package/dist/chunk-W64AWQCX.js.map +0 -1
  171. package/dist/chunk-YAZ4DUJJ.js +0 -3
  172. package/dist/chunk-YAZ4DUJJ.js.map +0 -1
  173. package/dist/chunk-Z4BXU65Y.cjs +0 -2
  174. package/dist/chunk-Z4BXU65Y.cjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import {a as a$1,b,c as c$1}from'./chunk-YAZ4DUJJ.js';var o={WORKER_CANCELLED:"WORKER_CANCELLED",WORKER_TERMINATED:"WORKER_TERMINATED",WORKER_TRANSPORT_FAILED:"WORKER_TRANSPORT_FAILED",WORKER_UNKNOWN_METHOD:"WORKER_UNKNOWN_METHOD",WORKER_NOT_INITIALISED:"WORKER_NOT_INITIALISED",WORKER_UNKNOWN_PACKAGE:"WORKER_UNKNOWN_PACKAGE"};function t(r){let e={name:r.name,category:r.category,code:r.code,message:r.message,recoverable:r.recoverable};return r.expected!==void 0&&(e.expected=r.expected),r.found!==void 0&&(e.found=r.found),r.suggestion!==void 0&&(e.suggestion=r.suggestion),r.span!==void 0&&(e.span=r.span),e}function a(r){let e=Object.values(a$1).includes(r.category)?r.category:"INTERNAL";return new b(e,{code:r.code,message:r.message,expected:r.expected,found:r.found,suggestion:r.suggestion,recoverable:r.recoverable,span:r.span})}function s(r){return c$1.execution(o.WORKER_CANCELLED,r?`The worker request "${r}" was cancelled`:"The worker request was cancelled",r?{method:r}:void 0)}function c(){return c$1.execution(o.WORKER_TERMINATED,"The worker engine was terminated before this request completed")}function g(r){return c$1.external(o.WORKER_TRANSPORT_FAILED,`The worker transport failed: ${r}`,{detail:r})}export{o as a,t as b,a as c,s as d,c as e,g as f};//# sourceMappingURL=chunk-XK23K3EJ.js.map
2
- //# sourceMappingURL=chunk-XK23K3EJ.js.map
1
+ import {a as a$1,b,c as c$1}from'./chunk-PIZQIQVM.js';var o={WORKER_CANCELLED:"WORKER_CANCELLED",WORKER_TERMINATED:"WORKER_TERMINATED",WORKER_TRANSPORT_FAILED:"WORKER_TRANSPORT_FAILED",WORKER_UNKNOWN_METHOD:"WORKER_UNKNOWN_METHOD",WORKER_NOT_INITIALISED:"WORKER_NOT_INITIALISED",WORKER_UNKNOWN_PACKAGE:"WORKER_UNKNOWN_PACKAGE"};function t(r){let e={name:r.name,category:r.category,code:r.code,message:r.message,recoverable:r.recoverable};return r.expected!==void 0&&(e.expected=r.expected),r.found!==void 0&&(e.found=r.found),r.suggestion!==void 0&&(e.suggestion=r.suggestion),r.span!==void 0&&(e.span=r.span),e}function a(r){let e=Object.values(a$1).includes(r.category)?r.category:"INTERNAL";return new b(e,{code:r.code,message:r.message,expected:r.expected,found:r.found,suggestion:r.suggestion,recoverable:r.recoverable,span:r.span})}function s(r){return c$1.execution(o.WORKER_CANCELLED,r?`The worker request "${r}" was cancelled`:"The worker request was cancelled",r?{method:r}:void 0)}function c(){return c$1.execution(o.WORKER_TERMINATED,"The worker engine was terminated before this request completed")}function g(r){return c$1.external(o.WORKER_TRANSPORT_FAILED,`The worker transport failed: ${r}`,{detail:r})}export{o as a,t as b,a as c,s as d,c as e,g as f};//# sourceMappingURL=chunk-4ETS224G.js.map
2
+ //# sourceMappingURL=chunk-4ETS224G.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors/WorkerError.ts"],"names":["WorkerErrorCodes","serializeEngineError","error","dto","deserializeEngineError","category","ErrorCategory","EngineError","workerCancelledError","method","ErrorFactory","workerTerminatedError","workerTransportError","detail"],"mappings":"sDAoBO,IAAMA,EAAmB,CAE/B,gBAAA,CAAkB,kBAAA,CAElB,iBAAA,CAAmB,oBAEnB,uBAAA,CAAyB,yBAAA,CAEzB,qBAAA,CAAuB,uBAAA,CAEvB,uBAAwB,wBAAA,CAExB,sBAAA,CAAwB,wBACzB,EAyBO,SAASC,CAAAA,CAAqBC,CAAAA,CAA2C,CAC/E,IAAMC,EAA6B,CAClC,IAAA,CAAMD,CAAAA,CAAM,IAAA,CACZ,SAAUA,CAAAA,CAAM,QAAA,CAChB,IAAA,CAAMA,CAAAA,CAAM,KACZ,OAAA,CAASA,CAAAA,CAAM,QACf,WAAA,CAAaA,CAAAA,CAAM,WACpB,CAAA,CAIA,OAAIA,CAAAA,CAAM,QAAA,GA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,gCAAgCa,CAAM,CAAA,CAAA,CACtC,CAAE,MAAA,CAAAA,CAAO,CACV,CACD","file":"chunk-XK23K3EJ.js","sourcesContent":["/**\n * Structured errors for the off-main-thread worker harness, and the pair of\n * functions that carry an {@link EngineError} across a `postMessage` boundary.\n *\n * A worker runs in another thread, so a failure there cannot be `throw`n back\n * into the caller's stack. It has to be encoded, posted, and rebuilt on the\n * main side, and it must arrive as a real structured error rather than a lost\n * promise or an opaque string. {@link serializeEngineError} projects an\n * `EngineError` onto a plain, clone-safe object; {@link deserializeEngineError}\n * rebuilds one from that object so the main-side `catch` sees the same\n * `code`/`category`/`message` it would have seen in-process.\n */\n\nimport { EngineError, ErrorCategory, ErrorFactory, type SourceSpan } from \"./EngineError\";\n\n/**\n * Codes the worker harness owns, co-located here rather than unioned into the\n * core catalog, matching the convention `errors/ErrorCode.ts` documents for a\n * domain that keeps its own small code object.\n */\nexport const WorkerErrorCodes = {\n\t/** The caller aborted the request through its `AbortSignal`. */\n\tWORKER_CANCELLED: \"WORKER_CANCELLED\",\n\t/** The worker engine was torn down while a request was still in flight. */\n\tWORKER_TERMINATED: \"WORKER_TERMINATED\",\n\t/** The transport failed or the worker exited before answering. */\n\tWORKER_TRANSPORT_FAILED: \"WORKER_TRANSPORT_FAILED\",\n\t/** A request named a method the runtime does not expose. */\n\tWORKER_UNKNOWN_METHOD: \"WORKER_UNKNOWN_METHOD\",\n\t/** A request arrived before the runtime finished building its engine. */\n\tWORKER_NOT_INITIALISED: \"WORKER_NOT_INITIALISED\",\n\t/** An init named a package the runtime could not resolve. */\n\tWORKER_UNKNOWN_PACKAGE: \"WORKER_UNKNOWN_PACKAGE\",\n} as const;\n\n/**\n * A structured error flattened for transport.\n *\n * Every field is a string, a boolean, or an object of numbers, so the whole\n * thing survives both `structuredClone` (what `postMessage` uses) and\n * `JSON.stringify` (what a host may log). `context`, `cause` and `timestamp`\n * are deliberately dropped rather than posted: a context can hold a value that\n * is not clone-safe, and none of the three is part of what a main-side handler\n * branches on.\n */\nexport interface SerializedEngineError {\n\tname: string;\n\tcategory: ErrorCategory;\n\tcode: string;\n\tmessage: string;\n\texpected?: string;\n\tfound?: string;\n\tsuggestion?: string;\n\trecoverable: boolean;\n\tspan?: SourceSpan;\n}\n\n/** Flatten an {@link EngineError} into a clone-safe {@link SerializedEngineError}. */\nexport function serializeEngineError(error: EngineError): SerializedEngineError {\n\tconst dto: SerializedEngineError = {\n\t\tname: error.name,\n\t\tcategory: error.category,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\trecoverable: error.recoverable,\n\t};\n\t// Only the optional string fields that were actually set cross the wire, so\n\t// a rebuilt error has `undefined` exactly where the original did rather than\n\t// an explicit `undefined` property a deep-equal would trip on.\n\tif (error.expected !== undefined) dto.expected = error.expected;\n\tif (error.found !== undefined) dto.found = error.found;\n\tif (error.suggestion !== undefined) dto.suggestion = error.suggestion;\n\t// A span is character offsets (plain numbers), so it is safe to carry and\n\t// useful for a host that highlights the failing range.\n\tif (error.span !== undefined) dto.span = error.span;\n\treturn dto;\n}\n\n/**\n * Rebuild an {@link EngineError} from its transported form.\n *\n * The category string round-trips straight back into the `ErrorCategory` enum\n * (its members ARE their own string values), so a main-side `catch` reads the\n * same category the worker raised. A malformed category (a message that was not\n * produced by {@link serializeEngineError}) falls back to `INTERNAL` rather than\n * constructing an error with an invalid category.\n */\nexport function deserializeEngineError(dto: SerializedEngineError): EngineError {\n\tconst category = Object.values(ErrorCategory).includes(dto.category)\n\t\t? dto.category\n\t\t: ErrorCategory.INTERNAL;\n\treturn new EngineError(category, {\n\t\tcode: dto.code,\n\t\tmessage: dto.message,\n\t\texpected: dto.expected,\n\t\tfound: dto.found,\n\t\tsuggestion: dto.suggestion,\n\t\trecoverable: dto.recoverable,\n\t\tspan: dto.span,\n\t});\n}\n\n/** The error a request rejects with when its caller aborts through an `AbortSignal`. */\nexport function workerCancelledError(method?: string): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_CANCELLED,\n\t\tmethod\n\t\t\t? `The worker request \"${method}\" was cancelled`\n\t\t\t: \"The worker request was cancelled\",\n\t\tmethod ? { method } : undefined,\n\t);\n}\n\n/** The error every pending request rejects with when the worker engine is terminated. */\nexport function workerTerminatedError(): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_TERMINATED,\n\t\t\"The worker engine was terminated before this request completed\",\n\t);\n}\n\n/** The error a request rejects with when the transport fails or the worker exits early. */\nexport function workerTransportError(detail: string): EngineError {\n\treturn ErrorFactory.external(\n\t\tWorkerErrorCodes.WORKER_TRANSPORT_FAILED,\n\t\t`The worker transport failed: ${detail}`,\n\t\t{ detail },\n\t);\n}\n"]}
1
+ {"version":3,"sources":["../src/errors/WorkerError.ts"],"names":["WorkerErrorCodes","serializeEngineError","error","dto","deserializeEngineError","category","ErrorCategory","EngineError","workerCancelledError","method","ErrorFactory","workerTerminatedError","workerTransportError","detail"],"mappings":"sDAoBO,IAAMA,EAAmB,CAE/B,gBAAA,CAAkB,kBAAA,CAElB,iBAAA,CAAmB,oBAEnB,uBAAA,CAAyB,yBAAA,CAEzB,qBAAA,CAAuB,uBAAA,CAEvB,uBAAwB,wBAAA,CAExB,sBAAA,CAAwB,wBACzB,EAyBO,SAASC,CAAAA,CAAqBC,CAAAA,CAA2C,CAC/E,IAAMC,EAA6B,CAClC,IAAA,CAAMD,CAAAA,CAAM,IAAA,CACZ,SAAUA,CAAAA,CAAM,QAAA,CAChB,IAAA,CAAMA,CAAAA,CAAM,KACZ,OAAA,CAASA,CAAAA,CAAM,QACf,WAAA,CAAaA,CAAAA,CAAM,WACpB,CAAA,CAIA,OAAIA,CAAAA,CAAM,QAAA,GAAa,SAAWC,CAAAA,CAAI,QAAA,CAAWD,CAAAA,CAAM,QAAA,CAAA,CACnDA,EAAM,KAAA,GAAU,MAAA,GAAWC,CAAAA,CAAI,KAAA,CAAQD,EAAM,KAAA,CAAA,CAC7CA,CAAAA,CAAM,aAAe,MAAA,GAAWC,CAAAA,CAAI,WAAaD,CAAAA,CAAM,UAAA,CAAA,CAGvDA,CAAAA,CAAM,IAAA,GAAS,SAAWC,CAAAA,CAAI,IAAA,CAAOD,CAAAA,CAAM,IAAA,CAAA,CACxCC,CACR,CAWO,SAASC,CAAAA,CAAuBD,CAAAA,CAAyC,CAC/E,IAAME,CAAAA,CAAW,OAAO,MAAA,CAAOC,GAAa,EAAE,QAAA,CAASH,CAAAA,CAAI,QAAQ,CAAA,CAChEA,EAAI,QAAA,CAAA,UAAA,CAEP,OAAO,IAAII,CAAAA,CAAYF,EAAU,CAChC,IAAA,CAAMF,CAAAA,CAAI,IAAA,CACV,QAASA,CAAAA,CAAI,OAAA,CACb,SAAUA,CAAAA,CAAI,QAAA,CACd,MAAOA,CAAAA,CAAI,KAAA,CACX,UAAA,CAAYA,CAAAA,CAAI,WAChB,WAAA,CAAaA,CAAAA,CAAI,WAAA,CACjB,IAAA,CAAMA,EAAI,IACX,CAAC,CACF,CAGO,SAASK,CAAAA,CAAqBC,CAAAA,CAA8B,CAClE,OAAOC,GAAAA,CAAa,UACnBV,CAAAA,CAAiB,gBAAA,CACjBS,CAAAA,CACG,CAAA,oBAAA,EAAuBA,CAAM,CAAA,eAAA,CAAA,CAC7B,kCAAA,CACHA,CAAAA,CAAS,CAAE,OAAAA,CAAO,CAAA,CAAI,MACvB,CACD,CAGO,SAASE,CAAAA,EAAqC,CACpD,OAAOD,GAAAA,CAAa,UACnBV,CAAAA,CAAiB,iBAAA,CACjB,gEACD,CACD,CAGO,SAASY,CAAAA,CAAqBC,CAAAA,CAA6B,CACjE,OAAOH,GAAAA,CAAa,QAAA,CACnBV,CAAAA,CAAiB,uBAAA,CACjB,gCAAgCa,CAAM,CAAA,CAAA,CACtC,CAAE,MAAA,CAAAA,CAAO,CACV,CACD","file":"chunk-4ETS224G.js","sourcesContent":["/**\n * Structured errors for the off-main-thread worker harness, and the pair of\n * functions that carry an {@link EngineError} across a `postMessage` boundary.\n *\n * A worker runs in another thread, so a failure there cannot be `throw`n back\n * into the caller's stack. It has to be encoded, posted, and rebuilt on the\n * main side, and it must arrive as a real structured error rather than a lost\n * promise or an opaque string. {@link serializeEngineError} projects an\n * `EngineError` onto a plain, clone-safe object; {@link deserializeEngineError}\n * rebuilds one from that object so the main-side `catch` sees the same\n * `code`/`category`/`message` it would have seen in-process.\n */\n\nimport { EngineError, ErrorCategory, ErrorFactory, type SourceSpan } from \"./EngineError\";\n\n/**\n * Codes the worker harness owns, co-located here rather than unioned into the\n * core catalog, matching the convention `errors/ErrorCode.ts` documents for a\n * domain that keeps its own small code object.\n */\nexport const WorkerErrorCodes = {\n\t/** The caller aborted the request through its `AbortSignal`. */\n\tWORKER_CANCELLED: \"WORKER_CANCELLED\",\n\t/** The worker engine was torn down while a request was still in flight. */\n\tWORKER_TERMINATED: \"WORKER_TERMINATED\",\n\t/** The transport failed or the worker exited before answering. */\n\tWORKER_TRANSPORT_FAILED: \"WORKER_TRANSPORT_FAILED\",\n\t/** A request named a method the runtime does not expose. */\n\tWORKER_UNKNOWN_METHOD: \"WORKER_UNKNOWN_METHOD\",\n\t/** A request arrived before the runtime finished building its engine. */\n\tWORKER_NOT_INITIALISED: \"WORKER_NOT_INITIALISED\",\n\t/** An init named a package the runtime could not resolve. */\n\tWORKER_UNKNOWN_PACKAGE: \"WORKER_UNKNOWN_PACKAGE\",\n} as const;\n\n/**\n * A structured error flattened for transport.\n *\n * Every field is a string, a boolean, or an object of numbers, so the whole\n * thing survives both `structuredClone` (what `postMessage` uses) and\n * `JSON.stringify` (what a host may log). `context`, `cause` and `timestamp`\n * are deliberately dropped rather than posted: a context can hold a value that\n * is not clone-safe, and none of the three is part of what a main-side handler\n * branches on.\n */\nexport interface SerializedEngineError {\n\tname: string;\n\tcategory: ErrorCategory;\n\tcode: string;\n\tmessage: string;\n\texpected?: string;\n\tfound?: string;\n\tsuggestion?: string;\n\trecoverable: boolean;\n\tspan?: SourceSpan;\n}\n\n/** Flatten an {@link EngineError} into a clone-safe {@link SerializedEngineError}. */\nexport function serializeEngineError(error: EngineError): SerializedEngineError {\n\tconst dto: SerializedEngineError = {\n\t\tname: error.name,\n\t\tcategory: error.category,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\trecoverable: error.recoverable,\n\t};\n\t// Only the optional string fields that were actually set cross the wire, so\n\t// a rebuilt error has `undefined` exactly where the original did rather than\n\t// an explicit `undefined` property a deep-equal would trip on.\n\tif (error.expected !== undefined) dto.expected = error.expected;\n\tif (error.found !== undefined) dto.found = error.found;\n\tif (error.suggestion !== undefined) dto.suggestion = error.suggestion;\n\t// A span is character offsets (plain numbers), so it is safe to carry and\n\t// useful for a host that highlights the failing range.\n\tif (error.span !== undefined) dto.span = error.span;\n\treturn dto;\n}\n\n/**\n * Rebuild an {@link EngineError} from its transported form.\n *\n * The category string round-trips straight back into the `ErrorCategory` enum\n * (its members ARE their own string values), so a main-side `catch` reads the\n * same category the worker raised. A malformed category (a message that was not\n * produced by {@link serializeEngineError}) falls back to `INTERNAL` rather than\n * constructing an error with an invalid category.\n */\nexport function deserializeEngineError(dto: SerializedEngineError): EngineError {\n\tconst category = Object.values(ErrorCategory).includes(dto.category)\n\t\t? dto.category\n\t\t: ErrorCategory.INTERNAL;\n\treturn new EngineError(category, {\n\t\tcode: dto.code,\n\t\tmessage: dto.message,\n\t\texpected: dto.expected,\n\t\tfound: dto.found,\n\t\tsuggestion: dto.suggestion,\n\t\trecoverable: dto.recoverable,\n\t\tspan: dto.span,\n\t});\n}\n\n/** The error a request rejects with when its caller aborts through an `AbortSignal`. */\nexport function workerCancelledError(method?: string): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_CANCELLED,\n\t\tmethod\n\t\t\t? `The worker request \"${method}\" was cancelled`\n\t\t\t: \"The worker request was cancelled\",\n\t\tmethod ? { method } : undefined,\n\t);\n}\n\n/** The error every pending request rejects with when the worker engine is terminated. */\nexport function workerTerminatedError(): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_TERMINATED,\n\t\t\"The worker engine was terminated before this request completed\",\n\t);\n}\n\n/** The error a request rejects with when the transport fails or the worker exits early. */\nexport function workerTransportError(detail: string): EngineError {\n\treturn ErrorFactory.external(\n\t\tWorkerErrorCodes.WORKER_TRANSPORT_FAILED,\n\t\t`The worker transport failed: ${detail}`,\n\t\t{ detail },\n\t);\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {a,d as d$1}from'./chunk-O3BDXOQJ.js';import {a as a$1}from'./chunk-LJFS3XHW.js';import {c}from'./chunk-IJMNVBIS.js';import {c as c$1}from'./chunk-PIZQIQVM.js';var A=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(67),e.emitIndex(1);}};var O=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(68),e.emitIndex(1);}};function L(t,o){let r=t.peek();if(!r||r.type!=="IDENT"&&r.type!=="UNIT")throw c$1.parsing("SYMBOLIC_REQUIRES_VARIABLE_NAME",`${o} needs the name of an unknown here, as in ${o}(x^2, x).`,{found:r?.type??"end of input"});return t.consume(),r.value}function x(t,o){t.emitOpcode(13),t.emitString(o);}function N(t,o,r){let e=new d$1(o.pluginIndexMap);t.parseExpression(a.Lowest,e),t.setBuilder(o);let n=e.build();if(n.hasAsync)throw c$1.parsing("SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS",`${r}'s expression must be synchronous (no weather/stocks/currency calls).`);return n}function I(t,o,r){let e=t.emitAnonymousBody([r],o);t.emitOpcode(159),t.emitIndex(e);}var R=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"solve"),m=o.match("EQUALS")?N(o,e,"solve"):null;o.consume("COMMA");let l=o.peek();if(!l||l.type!=="IDENT"&&l.type!=="UNIT")throw c$1.parsing("SOLVE_REQUIRES_VARIABLE_NAME","solve's second argument must be the name of the unknown to solve for, as in solve(x^2-4=0, x).",{found:l?.type??"end of input"});o.consume(),I(e,n,l.value),m?I(e,m,l.value):(e.emitOpcode(10),e.emitNumber(0)),x(e,l.value),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(69),e.emitIndex(3);}};var g=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"der");o.consume("COMMA");let m=L(o,"der");I(e,n,m),x(e,m),o.match("COMMA")?o.parseExpression(a.Lowest,e):(e.emitOpcode(10),e.emitNumber(1)),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(70),e.emitIndex(3);}};var C=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"integral");o.consume("COMMA");let m=L(o,"integral");I(e,n,m),x(e,m),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(71),e.emitIndex(2);}};var M=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=N(o,e,"taylor");o.consume("COMMA");let m=L(o,"taylor");I(e,n,m),x(e,m),o.consume("EQUALS"),o.parseExpression(a.Lowest,e),o.consume("COMMA"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(72),e.emitIndex(4);}};var S=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN");let n=0;do o.parseExpression(a.Lowest,e),n++;while(o.match("COMMA"));o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(73),e.emitIndex(n);}};var k=class{constructor(){this.category="Symbolic";}parse(o,r,e){e.emitOpcode(10),e.emitNumber(Number(r.value)),e.emitOpcode(51),e.emitIndex(74),e.emitIndex(1);}};var v=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(75),e.emitIndex(1);}};var w=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(76),e.emitIndex(1);}};var U=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(77),e.emitIndex(1);}};var h=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(78),e.emitIndex(1);}};var F=class{constructor(){this.category="Symbolic";}parse(o,r,e){o.consume("LPAREN"),o.parseExpression(a.Lowest,e),o.consume("RPAREN"),e.emitOpcode(51),e.emitIndex(79),e.emitIndex(1);}};function V(t=75){return {name:"symbolic:imaginary-literal",priority:t,shape:[{types:["NUMBER"]},{types:["IDENT"],values:["i"]}],match(o,r){let e=o[r];if(!e||e.type!=="NUMBER")return null;let n=o[r+1];return !n||n.type!=="IDENT"||n.value!=="i"||n.offset!==e.offset+e.value.length||o[r+2]?.type==="LPAREN"?null:{consumed:2,replacement:[new a$1("IMAGINARY",c("IMAGINARY"),e.value,e.value,e.offset,0,e.line,e.col)],ruleName:"symbolic:imaginary-literal"}}}}var $={expand:"EXPAND_FN",factor:"FACTOR_FN",solve:"SOLVE_FN",der:"DER_FN",derivative:"DER_FN",integral:"INTEGRAL_FN",taylor:"TAYLOR_FN",jacobian:"JACOBIAN_FN",conj:"CONJ_FN",re:"RE_FN",im:"IM_FN",cancel:"CANCEL_FN",apart:"APART_FN"};function j(t=80){return {name:"symbolic:call",priority:t,shape:[{types:["IDENT"],values:Object.keys($)},{types:["LPAREN"]}],match(o,r){let e=o[r];if(!e||e.type!=="IDENT")return null;let n=$[e.value.toLowerCase()];return !n||o[r+1]?.type!=="LPAREN"?null:{consumed:1,replacement:[new a$1(n,c(n),e.value,e.value,e.offset,0,e.line,e.col)],ruleName:"symbolic:call"}}}}var H=[{word:"expand",tokenType:"EXPAND_FN",builtinIndex:67,example:"expand((x+1)*(x+2))",expected:"x^2+3x+2",docPage:"expanding.md"},{word:"factor",tokenType:"FACTOR_FN",builtinIndex:68,example:"factor(x^2-4)",expected:"(x-2)*(x+2)",docPage:"factoring.md"},{word:"solve",tokenType:"SOLVE_FN",builtinIndex:69,example:"solve(x^2-4=0, x)",expected:"= [-2, 2]",docPage:"solving-equations.md"},{word:"der",tokenType:"DER_FN",builtinIndex:70,example:"der(x^3, x)",expected:"3x^2",docPage:"calculus.md"},{word:"integral",tokenType:"INTEGRAL_FN",builtinIndex:71,example:"integral(x^2, x)",expected:"1/3x^3",docPage:"calculus.md"},{word:"taylor",tokenType:"TAYLOR_FN",builtinIndex:72,example:"taylor(exp(x), x=0, 3)",expected:"1/6x^3+0.5x^2+x+1",docPage:"calculus.md"},{word:"jacobian",tokenType:"JACOBIAN_FN",builtinIndex:73,example:"jacobian(x*y, x+y)",expected:"= [y, x; 1, 1]",docPage:"calculus.md"},{word:"conj",tokenType:"CONJ_FN",builtinIndex:75,example:"conj(2+3i)",expected:"2-3i",docPage:"complex.md"},{word:"re",tokenType:"RE_FN",builtinIndex:76,example:"re(2+3i)",expected:"= 2",docPage:"complex.md"},{word:"im",tokenType:"IM_FN",builtinIndex:77,example:"im(2+3i)",expected:"= 3",docPage:"complex.md"},{word:"cancel",tokenType:"CANCEL_FN",builtinIndex:78,example:"cancel((x^2-1)/(x-1))",expected:"x+1",docPage:"cancelling-fractions.md"},{word:"apart",tokenType:"APART_FN",builtinIndex:79,example:"apart((3x+5)/(x^2-1))",expected:"4/(x-1)-1/(x+1)",docPage:"splitting-fractions.md"}],le={name:"solve-symbolic",normalizerRules:[j(),V()],prefixParselets:{EXPAND_FN:new A,FACTOR_FN:new O,SOLVE_FN:new R,DER_FN:new g,INTEGRAL_FN:new C,TAYLOR_FN:new M,JACOBIAN_FN:new S,IMAGINARY:new k,CONJ_FN:new v,RE_FN:new w,IM_FN:new U,CANCEL_FN:new h,APART_FN:new F},tokenCategories:{EXPAND_FN:"keyword",FACTOR_FN:"keyword",SOLVE_FN:"keyword",DER_FN:"keyword",INTEGRAL_FN:"keyword",TAYLOR_FN:"keyword",JACOBIAN_FN:"keyword",IMAGINARY:"number",CONJ_FN:"keyword",RE_FN:"keyword",IM_FN:"keyword",CANCEL_FN:"keyword",APART_FN:"keyword"}},ae=new Set(H.map(t=>t.tokenType));function se(t){return t.some(o=>ae.has(o.type))}var ce=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function J(t){let o=t.trim();if(o.length>=2&&o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1)),!ce.test(o))return null;let r=new Date(o).getTime();return Number.isNaN(r)?null:r}function Eo(t){let o=new Date(t),r=E=>String(E).padStart(2,"0"),e=o.getFullYear(),n=r(o.getMonth()+1),m=r(o.getDate()),l=r(o.getHours()),s=r(o.getMinutes()),c=r(o.getSeconds()),p=-o.getTimezoneOffset(),y=p>=0?"+":"-",a=Math.abs(p),f=r(Math.floor(a/60)),u=r(a%60);return `${e}-${n}-${m}T${l}:${s}:${c}${y}${f}:${u}`}var pe=1e12;function Ao(t){return Math.abs(t)>=pe?t:t*1e3}var D="DATETIME_LITERAL",K=c(D),Y=/^\d+$/,ue=/^\d{1,2}\.\d{1,2}$/,de=/^\.(\d{2}|\d{4})$/,d=/^\d{1,2}$/;function fe(t){for(let o=0;o<t.length-1;o++){let r=t[o];if((r.sourceEnd??r.offset+r.text.length)!==t[o+1].offset)return false}return true}function b(t){if(t.length===4)return Number(t);if(t.length===2){let o=Number(t);return o<=68?2e3+o:1900+o}return null}function P(t,o,r,e,n){if(o<1||o>12||t<1||t>31)return null;let m=new Date(r,o-1,t);if(m.getFullYear()!==r||m.getMonth()!==o-1||m.getDate()!==t)return null;let l=e[0],s=e.map(p=>p.value).join(""),c=new a$1(D,K,String(m.getTime()),s,l.offset,0,l.line,l.col);return {consumed:e.length,replacement:[c],ruleName:n}}var Ne=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?/,Ie=new Set(["NUMBER","MINUS","PLUS","COLON","IDENT"]),xe=16;function ye(t,o,r){let e=t[o];if(e.sourceEnd!==void 0)return null;let n=e.text,m=e.offset+e.text.length,l=[e];for(let f=o+1;f<t.length&&l.length<xe;f++){let u=t[f];if(u.sourceEnd!==void 0||u.offset!==m||!Ie.has(u.type))break;n+=u.text,m=u.offset+u.text.length,l.push(u);}let s=Ne.exec(n);if(s===null)return null;let c=0,p=0;for(let f of l)if(p+=f.text.length,c++,p>=s[0].length)break;if(p!==s[0].length)return null;let y=J(s[0]);if(y===null)return null;let a=new a$1(D,K,String(y),s[0],e.offset,0,e.line,e.col,e.offset+s[0].length);return {consumed:c,replacement:[a],ruleName:r}}function Te(t,o,r,e){if(e==="YMD")return t.length!==4||!d.test(o)||!d.test(r)?null:{year:Number(t),month:Number(o),day:Number(r)};if(!d.test(t)||!d.test(o))return null;let n=b(r);return n===null?null:e==="DMY"?{day:Number(t),month:Number(o),year:n}:{day:Number(o),month:Number(t),year:n}}function Mo(t=()=>"auto"){return {name:"datetime:date-literal",priority:70,shape:[{types:["NUMBER"]}],match(o,r){let e=o[r];if(e.type!=="NUMBER")return null;if(ue.test(e.value)){let a=o[r+1];if(a&&a.type==="NUMBER"&&de.test(a.value)){let[f,u]=e.value.split("."),E=b(a.value.slice(1));if(E!==null){let z=P(Number(f),Number(u),E,[e,a],"datetime:date-literal:dot");if(z)return z}}return null}if(e.value.length===4&&Y.test(e.value)){let a=ye(o,r,"datetime:date-literal:iso-timestamp");if(a)return a}if(!Y.test(e.value))return null;let n=o[r+1];if(!n||n.type!=="SLASH"&&n.type!=="MINUS")return null;let m=o[r+2],l=o[r+3],s=o[r+4];if(!m||m.type!=="NUMBER"||!Y.test(m.value)||!l||l.type!==n.type||!s||s.type!=="NUMBER"||!Y.test(s.value))return null;let c=[e,n,m,l,s];if(!fe(c))return null;let p=t();if(p!=="auto"){let a=Te(e.value,m.value,s.value,p);return a===null?null:P(a.day,a.month,a.year,c,`datetime:date-literal:${p.toLowerCase()}`)}if(n.type==="SLASH"){if(!d.test(e.value)||!d.test(m.value))return null;let a=b(s.value);return a===null?null:P(Number(e.value),Number(m.value),a,c,"datetime:date-literal:european")}if(e.value.length===4)return !d.test(m.value)||!d.test(s.value)?null:P(Number(s.value),Number(m.value),Number(e.value),c,"datetime:date-literal:iso");if(!d.test(e.value)||!d.test(m.value))return null;let y=b(s.value);return y===null?null:P(Number(m.value),Number(e.value),y,c,"datetime:date-literal:us")}}}export{le as a,se as b,J as c,Eo as d,Ao as e,D as f,P as g,Mo as h};//# sourceMappingURL=chunk-4XXUXRST.js.map
2
+ //# sourceMappingURL=chunk-4XXUXRST.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/packages/symbolic/parselets/ExpandParselet.ts","../src/packages/symbolic/parselets/FactorParselet.ts","../src/packages/symbolic/parselets/VariableArgument.ts","../src/packages/symbolic/parselets/SolveParselet.ts","../src/packages/symbolic/parselets/DerParselet.ts","../src/packages/symbolic/parselets/IntegralParselet.ts","../src/packages/symbolic/parselets/TaylorParselet.ts","../src/packages/symbolic/parselets/JacobianParselet.ts","../src/packages/symbolic/parselets/ImaginaryParselet.ts","../src/packages/symbolic/parselets/ConjParselet.ts","../src/packages/symbolic/parselets/ReParselet.ts","../src/packages/symbolic/parselets/ImParselet.ts","../src/packages/symbolic/parselets/CancelParselet.ts","../src/packages/symbolic/parselets/ApartParselet.ts","../src/packages/symbolic/normalizer/ImaginaryLiteralNormalizerRule.ts","../src/packages/symbolic/normalizer/SymbolicCallNormalizerRule.ts","../src/packages/symbolic/SymbolicPackage.ts","../src/packages/datetime/Iso8601.ts","../src/packages/datetime/normalizer/DateLiteralNormalizerRule.ts"],"names":["ExpandParselet","parser","_token","builder","BindingPower","FactorParselet","readVariableName","verb","token","ErrorFactory","emitVariableName","name","parseBoundExpression","inner","BytecodeBuilder","program","emitBoundExpression","index","SolveParselet","left","right","variable","DerParselet","expression","IntegralParselet","TaylorParselet","JacobianParselet","count","ImaginaryParselet","_parser","ConjParselet","ReParselet","ImParselet","CancelParselet","ApartParselet","imaginaryLiteralNormalizerRule","priority","tokens","pos","number","suffix","LexerToken","tokenTypeId","SYMBOLIC_WORD_TO_TOKEN_TYPE","symbolicCallNormalizerRule","tokenType","SYMBOLIC_FUNCTIONS","SYMBOLIC_PACKAGE","SYMBOLIC_TOKEN_TYPES","fn","containsSymbolicCall","ISO8601_PATTERN","parseIso8601","s","trimmed","ms","formatIso8601Local","epochMs","d","pad","n","year","month","day","hours","minutes","seconds","offsetMinutesTotal","sign","absOffset","offsetHours","offsetMinutes","MS_TIMESTAMP_THRESHOLD","unixTimestampToEpochMs","DATETIME_LITERAL_TYPE","DATETIME_LITERAL_TYPE_ID","PLAIN_INTEGER","DOT_DAY_MONTH","DOT_LEADING_YEAR","DAY_OR_MONTH","writtenAsOneRun","i","resolveYear","digits","yy","buildDateToken","sourceTokens","ruleName","date","first","text","t","fusedToken","ISO_TIMESTAMP","ISO_TOKEN_TYPES","ISO_MAX_TOKENS","fuseIsoTimestamp","runEnd","window","next","matched","consumed","covered","resolveOrderedGroups","g0","g1","g2","order","dateLiteralNormalizerRule","getInputOrder","t0","t1","dayText","monthText","match","timestamp","sep1","sep2","t2","resolved"],"mappings":"uKAoBO,IAAMA,CAAAA,CAAN,KAA+C,CAA/C,WAAA,EAAA,CACN,KAAS,QAAA,CAAW,WAAA,CAEpB,KAAA,CAAMC,CAAAA,CAAgBC,CAAAA,CAAeC,CAAAA,CAAgC,CACpEF,CAAAA,CAAO,QAAQ,QAAQ,CAAA,CACvBA,CAAAA,CAAO,eAAA,CAAgBG,CAAAA,CAAa,MAAA,CAAQD,CAAO,CAAA,CACnDF,EAAO,OAAA,CAAQ,QAAQ,CAAA,CAEvBE,CAAAA,CAAQ,UA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,CAAOqB,CAAAA,CAAYoC,CAAAA,CAAG,KAAK,CAAA,CACjC,OAAIzD,CAAAA,GAAS,IAAA,CAAa,IAAA,CACnBwB,CAAAA,CAAe,MAAA,CAAOyB,CAAAA,CAAG,KAAK,CAAA,CAAG,OAAOC,CAAAA,CAAG,KAAK,CAAA,CAAGlD,CAAAA,CAAMyB,CAAAA,CAAc,gCAAgC,CAChH,CAGA,GAAIwB,CAAAA,CAAG,KAAA,CAAM,MAAA,GAAW,CAAA,CACtB,OAAI,CAAC/B,CAAAA,CAAa,IAAA,CAAKgC,EAAG,KAAK,CAAA,EAAK,CAAChC,CAAAA,CAAa,IAAA,CAAKuC,CAAAA,CAAG,KAAK,CAAA,CAAU,KAElEjC,CAAAA,CAAe,MAAA,CAAOiC,CAAAA,CAAG,KAAK,CAAA,CAAG,MAAA,CAAOP,CAAAA,CAAG,KAAK,EAAG,MAAA,CAAOD,CAAAA,CAAG,KAAK,CAAA,CAAGxB,CAAAA,CAAc,2BAA2B,CAAA,CAEvH,GAAI,CAACP,CAAAA,CAAa,IAAA,CAAK+B,CAAAA,CAAG,KAAK,CAAA,EAAK,CAAC/B,CAAAA,CAAa,IAAA,CAAKgC,EAAG,KAAK,CAAA,CAAG,OAAO,IAAA,CACzE,IAAMlD,CAAAA,CAAOqB,CAAAA,CAAYoC,CAAAA,CAAG,KAAK,CAAA,CACjC,OAAIzD,CAAAA,GAAS,IAAA,CAAa,IAAA,CAEnBwB,CAAAA,CAAe,MAAA,CAAO0B,CAAAA,CAAG,KAAK,CAAA,CAAG,MAAA,CAAOD,CAAAA,CAAG,KAAK,EAAGjD,CAAAA,CAAMyB,CAAAA,CAAc,0BAA0B,CAC1G,CACF,CACF","file":"chunk-4XXUXRST.js","sourcesContent":["import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_EXPAND } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `expand(expr)`, multiplying out every product and power.\n *\n * A dedicated parselet rather than a `builtinNameToIndex` entry reached through\n * the ordinary `FunctionCallParselet`, because that route needs the lexer to\n * emit `FUNC` for the word, which means a `keywordMap` entry, which would stop\n * `expand` working as an ordinary variable name. See\n * `normalizer/SymbolicCallNormalizerRule.ts`.\n *\n * The emitted bytecode is an ordinary `CALL_BUILTIN`, so no new opcode and no\n * new VM dispatch arm is involved.\n */\nexport class ExpandParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_EXPAND);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_FACTOR } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `factor(expr)`, writing a polynomial as a product of irreducible factors over the rationals.\n *\n * A dedicated parselet rather than a `builtinNameToIndex` entry reached through\n * the ordinary `FunctionCallParselet`, because that route needs the lexer to\n * emit `FUNC` for the word, which means a `keywordMap` entry, which would stop\n * `expand` working as an ordinary variable name. See\n * `normalizer/SymbolicCallNormalizerRule.ts`.\n *\n * The emitted bytecode is an ordinary `CALL_BUILTIN`, so no new opcode and no\n * new VM dispatch arm is involved.\n */\nexport class FactorParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_FACTOR);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { Parser } from \"@solve-js/parser/Parser\";\nimport { BytecodeBuilder, type BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Reads a bare variable name argument and returns it, consuming the token.\n *\n * Shared by every algebra verb that takes \"which unknown\" as an argument.\n * Compiling the name as an ordinary variable read would require it to already\n * have a value, which is precisely what differentiating or solving with respect\n * to it says it does not.\n *\n * Requiring `IDENT` or `UNIT` here gives the same reserved-word protection\n * `VariableParselet` relies on: a keyword always lexes as its own token type,\n * so it can never reach this position and be taken for a variable name.\n *\n * @param parser - The parser, positioned at the name.\n * @param verb - The calling verb's name, for the error message.\n * @returns The name as written.\n * @throws {EngineError} `SYMBOLIC_REQUIRES_VARIABLE_NAME` when the next token is\n * not a bare name.\n */\nexport function readVariableName(parser: Parser, verb: string): string {\n\tconst token = parser.peek();\n\tif (!token || (token.type !== \"IDENT\" && token.type !== \"UNIT\")) {\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"SYMBOLIC_REQUIRES_VARIABLE_NAME\",\n\t\t\t`${verb} needs the name of an unknown here, as in ${verb}(x^2, x).`,\n\t\t\t{ found: token?.type ?? \"end of input\" },\n\t\t);\n\t}\n\tparser.consume();\n\treturn token.value;\n}\n\n/** Emits an already-read unknown's name as the String argument the algebra builtins read it as. */\nexport function emitVariableName(builder: BytecodeBuilder, name: string): void {\n\tbuilder.emitOpcode(OpCode.PUSH_STRING);\n\tbuilder.emitString(name);\n}\n\n/**\n * Parses an algebra verb's expression argument into its own independent\n * program, rather than emitting it inline.\n *\n * The verb names its unknown AFTER the expression (`der(x^2, x)`), so the\n * expression has to be held rather than emitted: only once the name is known\n * can it be paired with {@link emitBoundExpression}, which is what makes the\n * name shadow any document value it happens to share. Compiled into an\n * isolated builder exactly like a user-defined function body or a map/reduce\n * transform, and `parseExpression` leaves `parser.builder` pointing at the\n * isolated one with no automatic restore, so the caller's builder is put back\n * before returning.\n *\n * @param parser - The parser, positioned at the start of the expression.\n * @param builder - The builder to restore afterwards.\n * @param verb - The calling verb's name, for the error message.\n * @returns The compiled expression, to be handed to {@link emitBoundExpression}.\n */\nexport function parseBoundExpression(parser: Parser, builder: BytecodeBuilder, verb: string): BytecodeProgram {\n\tconst inner = new BytecodeBuilder(builder.pluginIndexMap);\n\tparser.parseExpression(BindingPower.Lowest, inner);\n\tparser.setBuilder(builder);\n\tconst program = inner.build();\n\tif (program.hasAsync) {\n\t\t// Same v1 restriction every other deferred body carries (user-defined\n\t\t// functions, map/reduce transforms): a reentrant execution cannot\n\t\t// suspend and resume the outer expression around an async result.\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS\",\n\t\t\t`${verb}'s expression must be synchronous (no weather/stocks/currency calls).`,\n\t\t);\n\t}\n\treturn program;\n}\n\n/**\n * Emits a held expression so that it evaluates with `name` bound to itself.\n *\n * This is what makes `der(x^2, x)` mean the derivative of a square rather than\n * the derivative of a constant on a page that also says `:x = 5`. Naming `x` as\n * the verb's argument declares it bound, so within the expression it is an\n * unknown and nothing else, exactly the way a function's parameter shadows a\n * document variable of the same name inside its body. Before this, the\n * expression was compiled inline and its `x` was an ordinary variable read, so\n * the verb received 25 and answered 0 with no indication that it had not been\n * asked the question the user wrote.\n *\n * @param builder - The builder to emit into.\n * @param program - The expression, from {@link parseBoundExpression}.\n * @param name - The unknown the verb named, bound for the expression's evaluation.\n */\nexport function emitBoundExpression(builder: BytecodeBuilder, program: BytecodeProgram, name: string): void {\n\tconst index = builder.emitAnonymousBody([name], program);\n\tbuilder.emitOpcode(OpCode.BIND_UNKNOWN);\n\tbuilder.emitIndex(index);\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { SYMBOLIC_BUILTIN_SOLVE } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `solve(equation, variable)`, for example `solve(x^2-4=0, x)`.\n *\n * Two things here cannot go through the ordinary function-call grammar, which\n * is why this is a hand-written parselet.\n *\n * The first argument contains a bare `=`, which no infix parselet consumes, so\n * an ordinary argument list would fail to parse it. This reads the two sides\n * separately and lets a missing right-hand side default to zero, so\n * `solve(x^2-4, x)` means the same as `solve(x^2-4=0, x)`.\n *\n * The second argument is a *name*, not a value. Compiling it as a `LOAD_VAR`\n * would demand that the variable already exist, which is exactly what solving\n * for it says it does not. Emitting it as a `PUSH_STRING` instead means the\n * builtin receives a plain String value and the VM needs no change at all.\n *\n * Both sides of the equation are held until that name has been read, so each\n * evaluates with the unknown bound to itself rather than to whatever value the\n * document may already have given it. See {@link emitBoundExpression}: with\n * `:x = 5` above it, `solve(x^2-4=0, x)` was solving `21 = 0` and reporting,\n * accurately for the question it was asked and uselessly for the one written,\n * that there is no solution.\n */\nexport class SolveParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst left = parseBoundExpression(parser, builder, \"solve\");\n\t\tconst right = parser.match(\"EQUALS\") ? parseBoundExpression(parser, builder, \"solve\") : null;\n\n\t\tparser.consume(\"COMMA\");\n\t\t// Requiring IDENT or UNIT here is the same protection VariableParselet\n\t\t// relies on: a reserved word always lexes as its own token type, so it\n\t\t// can never reach this position and be mistaken for a variable name.\n\t\tconst variable = parser.peek();\n\t\tif (!variable || (variable.type !== \"IDENT\" && variable.type !== \"UNIT\")) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"SOLVE_REQUIRES_VARIABLE_NAME\",\n\t\t\t\t`solve's second argument must be the name of the unknown to solve for, as in solve(x^2-4=0, x).`,\n\t\t\t\t{ found: variable?.type ?? \"end of input\" },\n\t\t\t);\n\t\t}\n\t\tparser.consume();\n\n\t\temitBoundExpression(builder, left, variable.value);\n\t\tif (right) {\n\t\t\temitBoundExpression(builder, right, variable.value);\n\t\t} else {\n\t\t\t// No `=` written, so the equation is \"this expression equals zero\".\n\t\t\tbuilder.emitOpcode(OpCode.PUSH_NUMBER);\n\t\t\tbuilder.emitNumber(0);\n\t\t}\n\t\temitVariableName(builder, variable.value);\n\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_SOLVE);\n\t\tbuilder.emitIndex(3);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_DER } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { readVariableName, emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `der(expr, variable)` and `der(expr, variable, order)`, the symbolic\n * derivative. `derivative` is accepted as the same thing.\n *\n * The variable is emitted as a string rather than compiled as a variable read,\n * for the reason given in {@link readVariableName}, and `expr` is held until\n * that name is known so it can be evaluated with the name bound. See\n * {@link emitBoundExpression}.\n */\nexport class DerParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst expression = parseBoundExpression(parser, builder, \"der\");\n\t\tparser.consume(\"COMMA\");\n\t\tconst variable = readVariableName(parser, \"der\");\n\t\temitBoundExpression(builder, expression, variable);\n\t\temitVariableName(builder, variable);\n\n\t\t// The order is optional and defaults to a first derivative.\n\t\tif (parser.match(\"COMMA\")) {\n\t\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\t} else {\n\t\t\tbuilder.emitOpcode(OpCode.PUSH_NUMBER);\n\t\t\tbuilder.emitNumber(1);\n\t\t}\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_DER);\n\t\tbuilder.emitIndex(3);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { SYMBOLIC_BUILTIN_INTEGRAL } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { readVariableName, emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `integral(expr, variable)`, the indefinite integral, without a constant of\n * integration. `expr` is held until the variable is read so that the named\n * unknown shadows any document value of the same name, see\n * {@link emitBoundExpression}.\n */\nexport class IntegralParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst expression = parseBoundExpression(parser, builder, \"integral\");\n\t\tparser.consume(\"COMMA\");\n\t\tconst variable = readVariableName(parser, \"integral\");\n\t\temitBoundExpression(builder, expression, variable);\n\t\temitVariableName(builder, variable);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_INTEGRAL);\n\t\tbuilder.emitIndex(2);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_TAYLOR } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\nimport { readVariableName, emitVariableName, parseBoundExpression, emitBoundExpression } from \"@solve-js/packages/symbolic/parselets/VariableArgument\";\n\n/**\n * `taylor(expr, variable = point, degree)`, matching Calca's own spelling.\n *\n * The `variable = point` argument is why this needs a hand-written parselet:\n * `EQUALS` has no infix parselet, so an ordinary argument list cannot parse it.\n * Reading the name and the point separately also means the name never has to\n * exist as a variable, and `expr` is held until the name is known so that the\n * name shadows any document value it shares (see {@link emitBoundExpression}).\n * The expansion point is an ordinary value expression and is not shadowed: it\n * is a number, not the unknown.\n */\nexport class TaylorParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tconst expression = parseBoundExpression(parser, builder, \"taylor\");\n\t\tparser.consume(\"COMMA\");\n\t\tconst variable = readVariableName(parser, \"taylor\");\n\t\temitBoundExpression(builder, expression, variable);\n\t\temitVariableName(builder, variable);\n\t\tparser.consume(\"EQUALS\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"COMMA\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_TAYLOR);\n\t\tbuilder.emitIndex(4);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_JACOBIAN } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `jacobian(f1, f2, ...)`, the matrix of partial derivatives.\n *\n * Variadic, and the variables are not named: they are taken from the union of\n * the functions' own unknowns, sorted, which is what Calca does. Row `i` is the\n * gradient of the `i`-th function.\n */\nexport class JacobianParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tlet count = 0;\n\t\tdo {\n\t\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\t\tcount++;\n\t\t} while (parser.match(\"COMMA\"));\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_JACOBIAN);\n\t\tbuilder.emitIndex(count);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { SYMBOLIC_BUILTIN_IMAGINARY } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * An imaginary literal, `3i`, fused by\n * `normalizer/ImaginaryLiteralNormalizerRule.ts`.\n *\n * The token carries the numeric part as its value; this pushes that number and\n * lets the builtin turn it into an exact imaginary value. Going through a\n * builtin rather than a dedicated opcode keeps the VM dispatch table untouched,\n * the same choice every other algebra verb made.\n */\nexport class ImaginaryParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(_parser: Parser, token: Token, builder: BytecodeBuilder): void {\n\t\tbuilder.emitOpcode(OpCode.PUSH_NUMBER);\n\t\tbuilder.emitNumber(Number(token.value));\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_IMAGINARY);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_CONJ } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `conj(z)`, the complex conjugate.\n *\n * A dedicated parselet rather than a keywordMap entry, for the reason given in\n * `normalizer/SymbolicCallNormalizerRule.ts`: `re` and `im` are short words a\n * person may well use as variable names.\n */\nexport class ConjParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_CONJ);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_RE } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `re(z)`, the real part of a complex value.\n *\n * A dedicated parselet rather than a keywordMap entry, for the reason given in\n * `normalizer/SymbolicCallNormalizerRule.ts`: `re` and `im` are short words a\n * person may well use as variable names.\n */\nexport class ReParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_RE);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_IM } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `im(z)`, the imaginary part of a complex value.\n *\n * A dedicated parselet rather than a keywordMap entry, for the reason given in\n * `normalizer/SymbolicCallNormalizerRule.ts`: `re` and `im` are short words a\n * person may well use as variable names.\n */\nexport class ImParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_IM);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_CANCEL } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `cancel(expr)`, reducing a quotient of polynomials to lowest terms.\n *\n * The simplifier already cancels a common factor automatically; this is the\n * explicit form, for when the intent is to reduce a fraction rather than to\n * evaluate something that happens to contain one.\n */\nexport class CancelParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_CANCEL);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport { Parser } from \"@solve-js/parser/Parser\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport { SYMBOLIC_BUILTIN_APART } from \"@solve-js/packages/symbolic/SymbolicBuiltinIndex\";\n\n/**\n * `apart(expr)`, splitting a rational function into partial fractions.\n *\n * The inverse of putting a sum of fractions over a common denominator, and the\n * step that makes a rational function integrable.\n */\nexport class ApartParselet implements PrefixParselet {\n\treadonly category = \"Symbolic\";\n\n\tparse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n\t\tparser.consume(\"LPAREN\");\n\t\tparser.parseExpression(BindingPower.Lowest, builder);\n\t\tparser.consume(\"RPAREN\");\n\n\t\tbuilder.emitOpcode(OpCode.CALL_BUILTIN);\n\t\tbuilder.emitIndex(SYMBOLIC_BUILTIN_APART);\n\t\tbuilder.emitIndex(1);\n\t}\n}\n","import type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"@solve-js/normalizer/NormalizerRule\";\n\n/**\n * Fuses `3i` into a single imaginary literal, but only when the `i` is written\n * flush against the number.\n *\n * `i` is not claimed as a keyword, and deliberately so. It is one of the most\n * common variable names there is, and this engine's whole trigger-word policy\n * exists to avoid taking words a person would reasonably assign to. `:i = 5`\n * has to keep working, and after this rule it does: the rule only fires on a\n * number immediately followed by the letter, which is the same shape the\n * magnitude suffixes use, and `2.5k` set that precedent.\n *\n * Adjacency is checked by source offset rather than by token order, so `3i` is\n * an imaginary literal while `3 i` and `3 * i` are a number multiplied by a\n * variable named `i`. That is the distinction that keeps both readings\n * available, and it is the reason a bare `i` on its own is still a variable.\n * Write `1i` for the imaginary unit alone.\n */\nexport function imaginaryLiteralNormalizerRule(priority = 75): NormalizerRule {\n\treturn {\n\t\tname: \"symbolic:imaginary-literal\",\n\t\tpriority,\n\t\t// Derived from this rule's own opening guards; see RuleSlot on why an\n\t\t// over-broad slot is safe and an over-narrow one is not.\n\t\tshape: [{ types: [\"NUMBER\"] }, { types: [\"IDENT\"], values: [\"i\"] }],\n\t\tmatch(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t\tconst number = tokens[pos];\n\t\t\tif (!number || number.type !== \"NUMBER\") return null;\n\n\t\t\tconst suffix = tokens[pos + 1];\n\t\t\tif (!suffix || suffix.type !== \"IDENT\" || suffix.value !== \"i\") return null;\n\n\t\t\t// Flush against the number, with no space between them.\n\t\t\tif (suffix.offset !== number.offset + number.value.length) return null;\n\n\t\t\t// A following `(` would make this a call, as in `3i(x)`, which is not a\n\t\t\t// shape this claims.\n\t\t\tif (tokens[pos + 2]?.type === \"LPAREN\") return null;\n\n\t\t\treturn {\n\t\t\t\tconsumed: 2,\n\t\t\t\treplacement: [\n\t\t\t\t\tnew LexerToken(\n\t\t\t\t\t\t\"IMAGINARY\",\n\t\t\t\t\t\ttokenTypeId(\"IMAGINARY\"),\n\t\t\t\t\t\tnumber.value,\n\t\t\t\t\t\tnumber.value,\n\t\t\t\t\t\tnumber.offset,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tnumber.line,\n\t\t\t\t\t\tnumber.col,\n\t\t\t\t\t),\n\t\t\t\t],\n\t\t\t\truleName: \"symbolic:imaginary-literal\",\n\t\t\t};\n\t\t},\n\t};\n}\n","import type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"@solve-js/normalizer/NormalizerRule\";\n\n/**\n * The algebra verbs, mapped to the token type each becomes when it is being\n * called.\n *\n * Kept in one place so {@link SYMBOLIC_FUNCTIONS} in `SymbolicPackage.ts` and\n * this rule cannot disagree about which words the package claims.\n */\nexport const SYMBOLIC_WORD_TO_TOKEN_TYPE: Readonly<Record<string, string>> = {\n\texpand: \"EXPAND_FN\",\n\tfactor: \"FACTOR_FN\",\n\tsolve: \"SOLVE_FN\",\n\tder: \"DER_FN\",\n\tderivative: \"DER_FN\",\n\tintegral: \"INTEGRAL_FN\",\n\ttaylor: \"TAYLOR_FN\",\n\tjacobian: \"JACOBIAN_FN\",\n\tconj: \"CONJ_FN\",\n\tre: \"RE_FN\",\n\tim: \"IM_FN\",\n\tcancel: \"CANCEL_FN\",\n\tapart: \"APART_FN\",\n};\n\n/**\n * Fuses an algebra verb into its own token type, but only when the bare word is\n * immediately followed by `(`.\n *\n * None of these words may be a plain `keywordMap` entry, and the reason is\n * concrete rather than stylistic. A `keywordMap` entry makes the lexer emit a\n * reserved token type everywhere the word appears, which would break\n * `:factor = 1.5` and `:solve = 2` as ordinary variable names. `solve` is also\n * the product's own name and `factor` is an everyday English noun, so both are\n * words a user will reasonably assign to.\n *\n * Mirrors `packages/mapreduce/normalizer/MapReduceCallNormalizerRule.ts`, which\n * exists for exactly this reason for `map`/`reduce`/`sum`/`prod`.\n *\n * @param priority - Rule ordering within the normalizer, defaulting to the same\n * band the map/reduce call rule uses.\n * @returns The normalizer rule.\n */\nexport function symbolicCallNormalizerRule(priority = 80): NormalizerRule {\n\treturn {\n\t\tname: \"symbolic:call\",\n\t\tpriority,\n\t\t// Derived from this rule's own opening guards; see RuleSlot on why an\n\t\t// over-broad slot is safe and an over-narrow one is not.\n\t\tshape: [{ types: [\"IDENT\"], values: Object.keys(SYMBOLIC_WORD_TO_TOKEN_TYPE) }, { types: [\"LPAREN\"] }],\n\t\tmatch(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t\tconst token = tokens[pos];\n\t\t\tif (!token || token.type !== \"IDENT\") return null;\n\t\t\tconst tokenType = SYMBOLIC_WORD_TO_TOKEN_TYPE[token.value.toLowerCase()];\n\t\t\tif (!tokenType) return null;\n\t\t\tif (tokens[pos + 1]?.type !== \"LPAREN\") return null;\n\n\t\t\treturn {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [\n\t\t\t\t\tnew LexerToken(tokenType, tokenTypeId(tokenType), token.value, token.value, token.offset, 0, token.line, token.col),\n\t\t\t\t],\n\t\t\t\truleName: \"symbolic:call\",\n\t\t\t};\n\t\t},\n\t};\n}\n","import type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { ExpandParselet } from \"./parselets/ExpandParselet\";\nimport { FactorParselet } from \"./parselets/FactorParselet\";\nimport { SolveParselet } from \"./parselets/SolveParselet\";\nimport { DerParselet } from \"./parselets/DerParselet\";\nimport { IntegralParselet } from \"./parselets/IntegralParselet\";\nimport { TaylorParselet } from \"./parselets/TaylorParselet\";\nimport { JacobianParselet } from \"./parselets/JacobianParselet\";\nimport { ImaginaryParselet } from \"./parselets/ImaginaryParselet\";\nimport { ConjParselet } from \"./parselets/ConjParselet\";\nimport { ReParselet } from \"./parselets/ReParselet\";\nimport { ImParselet } from \"./parselets/ImParselet\";\nimport { CancelParselet } from \"./parselets/CancelParselet\";\nimport { ApartParselet } from \"./parselets/ApartParselet\";\nimport { imaginaryLiteralNormalizerRule } from \"./normalizer/ImaginaryLiteralNormalizerRule\";\nimport { symbolicCallNormalizerRule } from \"./normalizer/SymbolicCallNormalizerRule\";\nimport {\n\tSYMBOLIC_BUILTIN_EXPAND,\n\tSYMBOLIC_BUILTIN_FACTOR,\n\tSYMBOLIC_BUILTIN_SOLVE,\n\tSYMBOLIC_BUILTIN_DER,\n\tSYMBOLIC_BUILTIN_INTEGRAL,\n\tSYMBOLIC_BUILTIN_TAYLOR,\n\tSYMBOLIC_BUILTIN_JACOBIAN,\n\tSYMBOLIC_BUILTIN_CONJ,\n\tSYMBOLIC_BUILTIN_RE,\n\tSYMBOLIC_BUILTIN_IM,\n\tSYMBOLIC_BUILTIN_CANCEL,\n\tSYMBOLIC_BUILTIN_APART,\n} from \"./SymbolicBuiltinIndex\";\n\n/**\n * One algebra verb's whole surface, in a single row.\n *\n * Everything a verb needs in order to work is listed here rather than being\n * spread across the normalizer, the parselet registry, the builtin table and\n * the docs, so `__tests__/engine/SymbolicSurfaceParity.spec.ts` can check the\n * pieces actually agree. Shipping a verb whose index has no implementation, or\n * whose parselet is registered under a token type the normalizer never mints,\n * then becomes a failing test rather than a silent dead feature.\n */\nexport interface SymbolicFunctionSurface {\n\t/** The bare word a user types. */\n\treadonly word: string;\n\t/** The token type the normalizer fuses it into when it is followed by `(`. */\n\treadonly tokenType: string;\n\t/** The `CALL_BUILTIN` index its parselet emits. */\n\treadonly builtinIndex: number;\n\t/** A working example, executed by the parity spec through every public entry point. */\n\treadonly example: string;\n\t/** That example's expected formatted result. */\n\treadonly expected: string;\n\t/** The documentation page under `docs/src/content/docs/syntax/` that must show it. */\n\treadonly docPage: string;\n}\n\n/** Every algebra verb this package registers. */\nexport const SYMBOLIC_FUNCTIONS: readonly SymbolicFunctionSurface[] = [\n\t{\n\t\tword: \"expand\",\n\t\ttokenType: \"EXPAND_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_EXPAND,\n\t\texample: \"expand((x+1)*(x+2))\",\n\t\texpected: \"x^2+3x+2\",\n\t\tdocPage: \"expanding.md\",\n\t},\n\t{\n\t\tword: \"factor\",\n\t\ttokenType: \"FACTOR_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_FACTOR,\n\t\texample: \"factor(x^2-4)\",\n\t\texpected: \"(x-2)*(x+2)\",\n\t\tdocPage: \"factoring.md\",\n\t},\n\t{\n\t\tword: \"solve\",\n\t\ttokenType: \"SOLVE_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_SOLVE,\n\t\texample: \"solve(x^2-4=0, x)\",\n\t\texpected: \"= [-2, 2]\",\n\t\tdocPage: \"solving-equations.md\",\n\t},\n\t{\n\t\tword: \"der\",\n\t\ttokenType: \"DER_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_DER,\n\t\texample: \"der(x^3, x)\",\n\t\texpected: \"3x^2\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"integral\",\n\t\ttokenType: \"INTEGRAL_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_INTEGRAL,\n\t\texample: \"integral(x^2, x)\",\n\t\texpected: \"1/3x^3\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"taylor\",\n\t\ttokenType: \"TAYLOR_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_TAYLOR,\n\t\texample: \"taylor(exp(x), x=0, 3)\",\n\t\texpected: \"1/6x^3+0.5x^2+x+1\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"jacobian\",\n\t\ttokenType: \"JACOBIAN_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_JACOBIAN,\n\t\texample: \"jacobian(x*y, x+y)\",\n\t\texpected: \"= [y, x; 1, 1]\",\n\t\tdocPage: \"calculus.md\",\n\t},\n\t{\n\t\tword: \"conj\",\n\t\ttokenType: \"CONJ_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_CONJ,\n\t\texample: \"conj(2+3i)\",\n\t\texpected: \"2-3i\",\n\t\tdocPage: \"complex.md\",\n\t},\n\t{\n\t\tword: \"re\",\n\t\ttokenType: \"RE_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_RE,\n\t\texample: \"re(2+3i)\",\n\t\texpected: \"= 2\",\n\t\tdocPage: \"complex.md\",\n\t},\n\t{\n\t\tword: \"im\",\n\t\ttokenType: \"IM_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_IM,\n\t\texample: \"im(2+3i)\",\n\t\texpected: \"= 3\",\n\t\tdocPage: \"complex.md\",\n\t},\n\t{\n\t\tword: \"cancel\",\n\t\ttokenType: \"CANCEL_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_CANCEL,\n\t\texample: \"cancel((x^2-1)/(x-1))\",\n\t\texpected: \"x+1\",\n\t\tdocPage: \"cancelling-fractions.md\",\n\t},\n\t{\n\t\tword: \"apart\",\n\t\ttokenType: \"APART_FN\",\n\t\tbuiltinIndex: SYMBOLIC_BUILTIN_APART,\n\t\texample: \"apart((3x+5)/(x^2-1))\",\n\t\texpected: \"4/(x-1)-1/(x+1)\",\n\t\tdocPage: \"splitting-fractions.md\",\n\t},\n];\n\n/**\n * Symbolic algebra verbs: multiplying out, and (in later phases) factoring,\n * solving and calculus.\n *\n * The algebra itself lives in `symbolic/`, which is pure mathematics over the\n * expression tree. This package is only the grammar surface: which words become\n * which tokens, and which parselet emits which builtin call.\n *\n * None of these words is a bare `keywordMap` entry. See\n * `normalizer/SymbolicCallNormalizerRule.ts` for why that matters.\n */\nexport const SYMBOLIC_PACKAGE: IEnginePackage = {\n\tname: \"solve-symbolic\",\n\tnormalizerRules: [symbolicCallNormalizerRule(), imaginaryLiteralNormalizerRule()],\n\tprefixParselets: {\n\t\tEXPAND_FN: new ExpandParselet(),\n\t\tFACTOR_FN: new FactorParselet(),\n\t\tSOLVE_FN: new SolveParselet(),\n\t\tDER_FN: new DerParselet(),\n\t\tINTEGRAL_FN: new IntegralParselet(),\n\t\tTAYLOR_FN: new TaylorParselet(),\n\t\tJACOBIAN_FN: new JacobianParselet(),\n\t\tIMAGINARY: new ImaginaryParselet(),\n\t\tCONJ_FN: new ConjParselet(),\n\t\tRE_FN: new ReParselet(),\n\t\tIM_FN: new ImParselet(),\n\t\tCANCEL_FN: new CancelParselet(),\n\t\tAPART_FN: new ApartParselet(),\n\t},\n\ttokenCategories: {\n\t\tEXPAND_FN: \"keyword\",\n\t\tFACTOR_FN: \"keyword\",\n\t\tSOLVE_FN: \"keyword\",\n\t\tDER_FN: \"keyword\",\n\t\tINTEGRAL_FN: \"keyword\",\n\t\tTAYLOR_FN: \"keyword\",\n\t\tJACOBIAN_FN: \"keyword\",\n\t\tIMAGINARY: \"number\",\n\t\tCONJ_FN: \"keyword\",\n\t\tRE_FN: \"keyword\",\n\t\tIM_FN: \"keyword\",\n\t\tCANCEL_FN: \"keyword\",\n\t\tAPART_FN: \"keyword\",\n\t},\n};\n\n/** The token types the algebra verbs fuse into, for the engine's own \"is this line symbolic\" check. */\nconst SYMBOLIC_TOKEN_TYPES: ReadonlySet<string> = new Set(SYMBOLIC_FUNCTIONS.map(fn => fn.tokenType));\n\n/**\n * Whether a normalized token list calls an algebra verb.\n *\n * `engine/ExpressionEngine.ts` uses this to evaluate such a line in\n * symbolic-tolerant mode without requiring a trailing `=>`, since asking to\n * expand or factor something is already a statement that its unknowns are meant\n * to stay unknown.\n *\n * @param tokens - The normalized tokens for one line.\n * @returns True when any token is an algebra verb.\n */\nexport function containsSymbolicCall(tokens: readonly { type: string }[]): boolean {\n\treturn tokens.some(token => SYMBOLIC_TOKEN_TYPES.has(token.type));\n}\n","/**\n * ISO8601 string <-> epoch-ms helpers backing the datetime package's\n * `<ISO8601 string> to date` and `<date/time> as iso8601` features.\n *\n * SCOPE, revised in 1.0.0: {@link parseIso8601} is now reached by BOTH input\n * shapes. A quoted string literal (`\"2019-04-01T15:30:00+11:00\" to date`)\n * always came here; the bare, unquoted form now does too, fused into one\n * DATETIME_LITERAL by `normalizer/DateLiteralNormalizerRule.ts` before the\n * parser sees it.\n *\n * This file used to record that the bare form was out of scope because it is\n * ambiguous with arithmetic (`2019 - 04 - 01` reads as two subtractions) and\n * would need a dedicated lexer change. The date half of that ambiguity was\n * already settled by the normalizer rule, and the differential run against\n * 1.0.0-beta.6 showed what leaving the other half cost: a bare\n * `2019-04-01T15:30:00+11:00` read its `+11:00` as a clock time being ADDED to\n * the date, and answered TODAY at 11:00. Not the instant, not an error, and\n * formatted as a date, which is the most convincing way to be wrong. The two\n * spellings now answer identically, which is the only defensible arrangement\n * when one of them was always right.\n */\n\n/**\n * Matches a (reasonably) well-formed ISO8601 date or date-time string:\n * `YYYY-MM-DD` optionally followed by `THH:MM[:SS[.fff]][Z|+HH:MM|-HH:MM]`.\n * Deliberately stricter than the native `Date` constructor's very lenient\n * parsing (which also accepts things like `\"April 1, 2019\"`), only a\n * string actually ISO8601-shaped is accepted here, so `\"not a date\" to\n * date` fails loudly instead of silently parsing as `Invalid Date` (or,\n * worse, something the native parser guesses at).\n */\nconst ISO8601_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n/**\n * Parse an ISO8601-shaped string into epoch milliseconds.\n *\n * Delegates the actual parsing to the native `Date` constructor, which\n * fully implements the ISO8601 extended format (including \"Z\"/\"+HH:MM\"\n * offsets and a fractional-seconds component) per the ECMA-262 Date Time\n * String Format spec, no custom parsing logic needed, just a stricter\n * shape gate in front of it (see {@link ISO8601_PATTERN}'s doc comment).\n *\n * A date-only string (`\"2019-04-01\"`) parses as UTC midnight; a date-time\n * with no offset and no \"Z\" (`\"2019-04-01T15:30:00\"`) parses in the HOST\n * SYSTEM's local timezone, both are the native `Date` constructor's own\n * spec-mandated behavior, not something this function adds.\n *\n * @returns epoch ms, or `null` if `s` isn't ISO8601-shaped or doesn't\n * parse to a valid instant.\n */\nexport function parseIso8601(s: string): number | null {\n // A `ValueType.String` Value's `.value` used to retain its original\n // surrounding double-quotes, because `tokenizeString()` set the token's\n // value to the raw source slice and `OpCode.PUSH_STRING` pushed that\n // verbatim. It no longer does: the token's `value` is the payload and its\n // `text` is the quoted slice. The strip below stays because this function\n // is also reachable with text that came from somewhere other than a\n // literal, and stripping a pair that is not there is a no-op.\n let trimmed = s.trim();\n if (trimmed.length >= 2 && trimmed.startsWith('\"') && trimmed.endsWith('\"')) {\n trimmed = trimmed.slice(1, -1);\n }\n if (!ISO8601_PATTERN.test(trimmed)) return null;\n const ms = new Date(trimmed).getTime();\n return Number.isNaN(ms) ? null : ms;\n}\n\n/**\n * Format epoch milliseconds as an ISO8601 string with an explicit\n * `+HH:MM`/`-HH:MM` offset, e.g. `\"2019-04-01T15:30:00+11:00\"`.\n *\n * DESIGN NOTE: uses the HOST SYSTEM's local timezone offset for the\n * offset component. This engine's `Datetime` representation is a bare\n * epoch-ms number with no zone tag (see `packages/time/TimePackage.ts`'s\n * doc comment for the same limitation affecting timezone conversion), so\n * there is no per-expression timezone context to draw on otherwise, the\n * process's own local offset (`Date.getTimezoneOffset()`) is the only\n * notion of \"local\" available. No milliseconds component is emitted,\n * matching the precision of the task's own worked example.\n */\nexport function formatIso8601Local(epochMs: number): string {\n const d = new Date(epochMs);\n const pad = (n: number) => String(n).padStart(2, \"0\");\n\n const year = d.getFullYear();\n const month = pad(d.getMonth() + 1);\n const day = pad(d.getDate());\n const hours = pad(d.getHours());\n const minutes = pad(d.getMinutes());\n const seconds = pad(d.getSeconds());\n\n // getTimezoneOffset() is (UTC - local) in minutes, i.e. the SIGN is\n // inverted relative to a \"+HH:MM ahead of UTC\" display offset.\n const offsetMinutesTotal = -d.getTimezoneOffset();\n const sign = offsetMinutesTotal >= 0 ? \"+\" : \"-\";\n const absOffset = Math.abs(offsetMinutesTotal);\n const offsetHours = pad(Math.floor(absOffset / 60));\n const offsetMinutes = pad(absOffset % 60);\n\n return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}${sign}${offsetHours}:${offsetMinutes}`;\n}\n\n/**\n * Magnitude threshold distinguishing a millisecond Unix timestamp from a\n * second Unix timestamp: values at or above this are treated as\n * milliseconds, below it as seconds.\n *\n * Chosen so that \"now\" in EITHER unit sits comfortably on its own side:\n * seconds-since-epoch for the foreseeable future stays in the ~1.7-2.5\n * billion range (1e9-1e10-ish), nowhere near 1e12, while the SAME\n * instant in milliseconds is ~1000x larger, comfortably past 1e12\n * (e.g. \"2024-12-10\" is ~1.73e9 seconds or ~1.73e12 ms). 1e12 sits well\n * clear of both real-world ranges for at least the next few centuries of\n * second-timestamps, so this is a safe, simple magnitude gate rather than\n * a fragile exact boundary.\n */\nconst MS_TIMESTAMP_THRESHOLD = 1e12;\n\n/**\n * Interpret a bare numeric Unix timestamp as epoch milliseconds, applying\n * the magnitude-based seconds-vs-milliseconds disambiguation described by\n * {@link MS_TIMESTAMP_THRESHOLD}.\n */\nexport function unixTimestampToEpochMs(n: number): number {\n return Math.abs(n) >= MS_TIMESTAMP_THRESHOLD ? n : n * 1000;\n}\n","import type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"@solve-js/normalizer/NormalizerRule\";\nimport { parseIso8601 } from \"@solve-js/packages/datetime/Iso8601\";\nimport type { DateInputOrder } from \"@solve-js/constants/Configuration\";\n\n/**\n * Token type a fused date literal is rewritten to.\n *\n * One type covers every supported ordering, so the parselet handles the shape\n * rather than the locale.\n */\nexport const DATETIME_LITERAL_TYPE = \"DATETIME_LITERAL\";\nconst DATETIME_LITERAL_TYPE_ID = tokenTypeId(DATETIME_LITERAL_TYPE);\n\n/** A pure digit string, guards against fusing hex/scientific/bigint-suffixed NUMBER tokens. */\nconst PLAIN_INTEGER = /^\\d+$/;\n\n/** First NUMBER token of a dot-separated literal: the lexer's decimal scanner\n * merges \"DD.MM\" into one float-shaped token (see module doc below). */\nconst DOT_DAY_MONTH = /^\\d{1,2}\\.\\d{1,2}$/;\n\n/** Second NUMBER token of a dot-separated literal: the lexer re-enters\n * tokenizeNumber() AT the second dot, so the year keeps its leading dot. */\nconst DOT_LEADING_YEAR = /^\\.(\\d{2}|\\d{4})$/;\n\n/**\n * Day and month groups of a separator-separated literal, in any of the three\n * orderings below: one or two digits, padded or not.\n *\n * Deliberately NOT two digits exactly. Zero-padding is what ISO 8601 requires\n * of a serialized date, but it is not what people type: \"2024-5-3\" is an\n * ordinary way to write a date and has to keep working. The digit count is\n * still bounded because a group of three or more digits is not a date group at\n * all, and the calendar check in {@link buildDateToken} would not catch it on\n * its own (\"030\" reads back as day 30).\n *\n * What actually separates a date from the arithmetic it is spelled like is\n * adjacency, not padding. See {@link writtenAsOneRun}.\n */\nconst DAY_OR_MONTH = /^\\d{1,2}$/;\n\n/**\n * Whether every token in a run touches the next one in the source text, with\n * no whitespace anywhere between the first character and the last.\n *\n * This is the whole basis for telling a date literal apart from the\n * arithmetic it is spelled identically to. A date is written as one\n * uninterrupted run (\"2024-5-3\"); a subtraction chain is written with spaces\n * around its operators (\"2024 - 5 - 3\"). The lexer records that difference in\n * the token offsets and nowhere else, since the tokens themselves are the same\n * five either way:\n *\n * 2024-5-3 NUMBER@0 MINUS@4 NUMBER@5 MINUS@6 NUMBER@7\n * 2024 - 5 - 3 NUMBER@0 MINUS@5 NUMBER@7 MINUS@9 NUMBER@11\n *\n * The same technique, for the same reason, is what tells \"5k\" from \"5 k\" in\n * `arithmetic/normalizer/LargeNumberSuffixNormalizerRule.ts`.\n *\n * ## Why this replaced a zero-padding requirement on the ISO branch\n * The ISO branch briefly required its month and day groups to be padded to two\n * digits, which did stop \"2024 - 5 - 3\" being answered as \"Friday, May 3,\n * 2024\" but also stopped \"2024-5-3\" being a date at all. Padding was never the\n * real distinction, and the rule's own US branch is the proof: it has always\n * accepted unpadded groups, so \"1-1-2020\" and \"12-25-2023\" are both dates\n * today. Requiring padding on one branch of the two was therefore an\n * inconsistency between two spellings of one rule rather than a policy.\n *\n * The US branch's own guard is a 2-or-4-digit trailing year plus the calendar\n * check, and it is NOT safe against spaced arithmetic on its own: before this\n * check existed, \"12 - 25 - 2023\" answered Christmas 2023 instead of -2036,\n * and \"1 - 1 - 2020\" answered New Year's Day instead of -2020. Applying\n * adjacency to the whole run rather than to one branch fixes that at the same\n * time and leaves both branches resting on the same reason.\n *\n * ## Padded but spaced\n * \"2024 - 05 - 03\" is subtraction under this check, and that is the intended\n * reading. Nobody types the spaces when they mean the date, so the spacing is\n * the clearest signal available about which was meant, and the padding is not:\n * a person subtracting may well write \"05\" for the same reason they write\n * \"05\" anywhere else. Choosing the date there would mean no spelling of that\n * subtraction existed.\n *\n * `sourceEnd` is preferred over `text.length` where it is set, because a token\n * an earlier rule fused carries replacement text rather than source text and\n * only `sourceEnd` still describes the span it covers (see\n * `normalizer/TokenNormalizer.ts`'s `createFusedToken`).\n */\nfunction writtenAsOneRun(tokens: Token[]): boolean {\n for (let i = 0; i < tokens.length - 1; i++) {\n const token = tokens[i];\n const end = token.sourceEnd ?? token.offset + token.text.length;\n if (end !== tokens[i + 1].offset) return false;\n }\n return true;\n}\n\n/**\n * Resolves a year token's raw digit text to a 4-digit year.\n *\n * Accepts exactly 2 or 4 digits (matching the wiki's documented formats).\n * A 2-digit year is windowed using the common glibc `strptime(\"%y\")`\n * convention: 00-68 -> 2000-2068, 69-99 -> 1969-1999. Any other digit\n * count (1 or 3 digits) is not a valid year shape and returns null so the\n * caller can decline the match and fall back to ordinary arithmetic.\n */\nfunction resolveYear(digits: string): number | null {\n if (digits.length === 4) return Number(digits);\n if (digits.length === 2) {\n const yy = Number(digits);\n return yy <= 68 ? 2000 + yy : 1900 + yy;\n }\n return null;\n}\n\n/**\n * Converts a validated day/month/year triple into a fused DATETIME_LITERAL\n * token, or null if the triple isn't a real calendar date (e.g. \"30\" for\n * February), letting the caller fall back to treating the source tokens\n * as ordinary arithmetic instead of a date.\n */\nexport function buildDateToken(\n day: number,\n month: number,\n year: number,\n sourceTokens: Token[],\n ruleName: string,\n): NormalizerMatch | null {\n if (month < 1 || month > 12 || day < 1 || day > 31) return null;\n\n // Local midnight, consistent with formatDatetime()'s toLocaleString()\n // display and DATE_NOW's Date.now() epoch, both of which are local-time.\n const date = new Date(year, month - 1, day);\n // Reject calendar rollover (e.g. day=30 in February) rather than silently\n // normalizing to March 2, a rollover almost always means the tokens were\n // never a date to begin with (e.g. \"2-30-5\" as chained subtraction).\n if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {\n return null;\n }\n\n const first = sourceTokens[0];\n const text = sourceTokens.map((t) => t.value).join(\"\");\n const fusedToken = new LexerToken(\n DATETIME_LITERAL_TYPE,\n DATETIME_LITERAL_TYPE_ID,\n String(date.getTime()),\n text,\n first.offset,\n 0,\n first.line,\n first.col,\n );\n\n return { consumed: sourceTokens.length, replacement: [fusedToken], ruleName };\n}\n\n/**\n * A full ISO 8601 timestamp: an ISO date with a time of day, optionally\n * carrying a UTC offset or the `Z` that means one of zero.\n *\n * Anchored at the start and deliberately greedy about the offset, so\n * `...T15:30:00+11:00` matches through the offset rather than stopping at the\n * seconds and leaving `+11:00` behind as an addition. That is what the bare\n * form used to do: `2019-04-01T15:30:00+11:00` read the offset as a clock time\n * being ADDED to the date on its left, and answered today at 11:00. Both\n * halves of that were wrong and neither was visible, which is worse than the\n * bare form simply not being supported.\n *\n * The time of day is required. Without it this would match what the date-only\n * branches below already handle, and they carry the ambiguity rules\n * (adjacency, group shapes) that keep a subtraction chain a subtraction.\n *\n * Matched against reconstructed source text rather than token by token. The\n * lexer has no idea this is one literal, so it emits nine to fourteen tokens\n * for it with the shape depending on the spelling (`T15` arrives as an\n * identifier, `Z` as another, an offset as a PLUS or MINUS with two more\n * numbers), and enumerating those permutations in token patterns is how a\n * spelling gets missed.\n *\n * `T` and `Z` are uppercase only, matching `Iso8601.ts`'s own pattern, which is\n * what actually parses the match. Accepting a spelling here that the parser\n * then refuses would mean the bare form supported more shapes than the quoted\n * one, for no reason a reader could infer.\n */\nconst ISO_TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?/;\n\n/**\n * Token types a run of ISO 8601 timestamp text can lex into. Anything else\n * ends the run, so the reconstruction below can never reach across an operator\n * or a word that is not part of the literal.\n */\nconst ISO_TOKEN_TYPES = new Set([\"NUMBER\", \"MINUS\", \"PLUS\", \"COLON\", \"IDENT\"]);\n\n/**\n * How many tokens the longest supported spelling occupies. `2019-04-01T15:30:00.123+11:00`\n * is fourteen; the cap only bounds the walk, since the match itself decides\n * where the literal ends.\n */\nconst ISO_MAX_TOKENS = 16;\n\n/**\n * Fuses a bare (unquoted) ISO 8601 timestamp into one DATETIME_LITERAL.\n *\n * `Iso8601.ts` could always parse this shape, and still does the parsing here;\n * what it said could not be done without \"a much larger, dedicated lexer\n * change\" was recognising the bare form, on the grounds that it is ambiguous\n * with arithmetic. The date half of that ambiguity was settled by the rule this\n * helper sits inside (a date is written as one uninterrupted run, so\n * `2024 - 5 - 3` stays arithmetic), and the time half is not ambiguous at all:\n * no chain of subtractions contains a `T15:30`.\n *\n * Contiguity in the SOURCE is what makes that true, the same test\n * {@link writtenAsOneRun} applies to the date-only orderings. Every token has\n * to begin exactly where the previous one ended, so `2019-04-01 T15:30` with a\n * space in it, or `2019-04-01 + 11:00` with the offset written as an addition,\n * are left alone: the user who typed a space typed two things.\n *\n * A token an earlier normalizer rule already fused ends the run rather than\n * joining it. Its `text` is replacement text rather than source text (see\n * `normalizer/TokenNormalizer.ts`'s `createFusedToken`), so concatenating it\n * would reconstruct something the user never typed, and nothing that has\n * already been fused into a phrase is part of a timestamp anyway.\n *\n * @returns The fused match, or null when the tokens at `pos` are not a\n * timestamp, when the match would end mid-token, or when the shape is\n * ISO-like but names no real instant (`2019-04-01T25:00:00`).\n */\nfunction fuseIsoTimestamp(tokens: Token[], pos: number, ruleName: string): NormalizerMatch | null {\n const first = tokens[pos];\n if (first.sourceEnd !== undefined) return null;\n let text = first.text;\n let runEnd = first.offset + first.text.length;\n const window: Token[] = [first];\n for (let i = pos + 1; i < tokens.length && window.length < ISO_MAX_TOKENS; i++) {\n const next = tokens[i];\n if (next.sourceEnd !== undefined) break;\n if (next.offset !== runEnd || !ISO_TOKEN_TYPES.has(next.type)) break;\n text += next.text;\n runEnd = next.offset + next.text.length;\n window.push(next);\n }\n\n const matched = ISO_TIMESTAMP.exec(text);\n if (matched === null) return null;\n\n // The literal has to end where a token ends. A match that stopped halfway\n // through one would leave the parser holding a token whose text has already\n // been consumed, so decline and let the ordinary rules have it.\n let consumed = 0;\n let covered = 0;\n for (const token of window) {\n covered += token.text.length;\n consumed++;\n if (covered >= matched[0].length) break;\n }\n if (covered !== matched[0].length) return null;\n\n // The instant comes from the same parser the quoted form uses, so the two\n // spellings cannot drift apart: an offset means what it means there, and a\n // timestamp with no offset is local time, exactly as a bare date literal is\n // local midnight.\n const epochMs = parseIso8601(matched[0]);\n if (epochMs === null) return null;\n\n const fusedToken = new LexerToken(\n DATETIME_LITERAL_TYPE,\n DATETIME_LITERAL_TYPE_ID,\n String(epochMs),\n matched[0],\n first.offset,\n 0,\n first.line,\n first.col,\n first.offset + matched[0].length,\n );\n return { consumed, replacement: [fusedToken], ruleName };\n}\n\n/**\n * Maps the three numeric groups of a slash- or hyphen-separated literal to a\n * (day, month, year) triple under an explicit {@link DateInputOrder}, or null\n * when a group is the wrong shape for its role (a non-4-digit year in `YMD`, a\n * year group that is neither two nor four digits in `DMY`/`MDY`).\n *\n * Only reached when the host has fixed an order; `'auto'` keeps the historic\n * per-separator reading in the rule below and never calls this.\n */\nfunction resolveOrderedGroups(\n g0: string, g1: string, g2: string, order: Exclude<DateInputOrder, \"auto\">,\n): { day: number; month: number; year: number } | null {\n if (order === \"YMD\") {\n if (g0.length !== 4) return null;\n if (!DAY_OR_MONTH.test(g1) || !DAY_OR_MONTH.test(g2)) return null;\n return { year: Number(g0), month: Number(g1), day: Number(g2) };\n }\n // DMY and MDY: two 1-2 digit groups and a trailing 2- or 4-digit year.\n if (!DAY_OR_MONTH.test(g0) || !DAY_OR_MONTH.test(g1)) return null;\n const year = resolveYear(g2);\n if (year === null) return null;\n return order === \"DMY\"\n ? { day: Number(g0), month: Number(g1), year }\n : { day: Number(g1), month: Number(g0), year };\n}\n\n/**\n * NormalizerRule that fuses numeric date literals into a single\n * DATETIME_LITERAL token, per the documented \"Datetime Formats\":\n * - European: DD/MM/YYYY (5 tokens: NUMBER SLASH NUMBER SLASH NUMBER)\n * - US: MM-DD-YYYY (5 tokens: NUMBER MINUS NUMBER MINUS NUMBER)\n * - ISO 8601: YYYY-MM-DD (same 5-token shape as US, disambiguated by the\n * first group being exactly 4 digits)\n * - Dot: DD.MM.YYYY (2 tokens. See below)\n *\n * ## Why the dot format is a 2-token window, not 5\n * ExpressionLexer's tokenizeNumber() treats \".\" adjacent to digits on both\n * sides as a decimal point, not a separator. For \"25.12.2023\" the lexer\n * itself emits only two NUMBER tokens: \"25.12\" (day+month merged into one\n * float-shaped literal) and \".2023\" (the lexer re-enters number scanning\n * AT the second dot, so the year keeps a leading dot). There is no 5-token\n * NUMBER-DOT-NUMBER-DOT-NUMBER shape to match against, the fusion has to\n * happen post-hoc from that 2-token shape instead. This only works for the\n * literal typed with no internal whitespace (e.g. \"25.12.2023\"); a spaced\n * variant (\"25 .12 .2023\") produces three separate leading-dot tokens and\n * is intentionally not supported, out of scope for the documented format.\n *\n * ## Ambiguity with existing arithmetic\n * A date-shaped SLASH or MINUS chain (e.g. \"25/12/2023\" or \"12-25-2023\")\n * previously parsed as chained division/subtraction. This rule\n * deliberately reinterprets any such chain that resolves to a real\n * calendar date as a date literal instead, matching the documented\n * behavior. Chains that aren't valid dates (out-of-range day/month, a\n * February 30, a non-2/4-digit year) fall through unchanged.\n *\n * That reinterpretation only ever claims a chain written as one\n * uninterrupted run of characters. \"25/12/2023\" and \"12-25-2023\" are dates;\n * \"25 / 12 / 2023\" and \"12 - 25 - 2023\", written with the spaces an operator\n * normally gets, stay division and subtraction. {@link writtenAsOneRun}\n * carries the full reasoning, including why this is checked instead of\n * requiring an ISO date's zero-padding.\n *\n * ## Relationship to Iso8601.ts / DatePhrase.ts\n * This is the general-purpose \"bare numeric date literal\" implementation\n * those two files' doc comments referenced as landing on a sibling branch\n * (`feat/safety-limits-datetime-literals`), now ported here. It's\n * intentionally independent of both: `Iso8601.ts` only parses QUOTED\n * STRING literals (`\"2019-04-01...\" to date`), and the Stocks package's\n * `DatePhrase.ts` is a narrower, deliberately-diverging grammar (US-style\n * bare SLASH dates, 4-digit-year-only) scoped to stock-history queries\n * neither of those needed to change for this to land.\n */\nexport function dateLiteralNormalizerRule(\n getInputOrder: () => DateInputOrder = () => \"auto\",\n): NormalizerRule {\n return {\n name: \"datetime:date-literal\",\n priority: 70,\n // Derived from this rule's own opening guards; see RuleSlot on why an\n // over-broad slot is safe and an over-narrow one is not.\n shape: [{ types: [\"NUMBER\"] }],\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n const t0 = tokens[pos];\n if (t0.type !== \"NUMBER\") return null;\n\n // ── Dot format: 2-token window (see module doc) ──────────────────\n if (DOT_DAY_MONTH.test(t0.value)) {\n const t1 = tokens[pos + 1];\n if (t1 && t1.type === \"NUMBER\" && DOT_LEADING_YEAR.test(t1.value)) {\n const [dayText, monthText] = t0.value.split(\".\");\n const year = resolveYear(t1.value.slice(1));\n if (year !== null) {\n const match = buildDateToken(\n Number(dayText), Number(monthText), year,\n [t0, t1], \"datetime:date-literal:dot\",\n );\n if (match) return match;\n }\n }\n return null;\n }\n\n // ── ISO 8601 timestamp: as many tokens as the spelling takes ─────\n // Tried before the date-only windows below, which would otherwise fuse\n // the date half of a timestamp and leave the time half to be read as\n // arithmetic. See fuseIsoTimestamp().\n if (t0.value.length === 4 && PLAIN_INTEGER.test(t0.value)) {\n const timestamp = fuseIsoTimestamp(tokens, pos, \"datetime:date-literal:iso-timestamp\");\n if (timestamp) return timestamp;\n }\n\n // ── Slash / minus format: 5-token window ─────────────────────────\n if (!PLAIN_INTEGER.test(t0.value)) return null;\n const sep1 = tokens[pos + 1];\n if (!sep1 || (sep1.type !== \"SLASH\" && sep1.type !== \"MINUS\")) return null;\n const t1 = tokens[pos + 2];\n const sep2 = tokens[pos + 3];\n const t2 = tokens[pos + 4];\n if (!t1 || t1.type !== \"NUMBER\" || !PLAIN_INTEGER.test(t1.value)) return null;\n if (!sep2 || sep2.type !== sep1.type) return null;\n if (!t2 || t2.type !== \"NUMBER\" || !PLAIN_INTEGER.test(t2.value)) return null;\n\n const sourceTokens = [t0, sep1, t1, sep2, t2];\n // The one check that separates every ordering below from the arithmetic\n // it is spelled identically to, and the only one that applies to all\n // three equally. See writtenAsOneRun.\n if (!writtenAsOneRun(sourceTokens)) return null;\n\n // A host-fixed order (DMY/MDY/YMD) reads slash and hyphen dates the same\n // way, so a US reader's `12/25/2023` and an ISO `2023/12/25` both parse.\n // `'auto'` falls through to the historic per-separator reading below.\n const order = getInputOrder();\n if (order !== \"auto\") {\n const resolved = resolveOrderedGroups(t0.value, t1.value, t2.value, order);\n if (resolved === null) return null;\n return buildDateToken(\n resolved.day, resolved.month, resolved.year, sourceTokens,\n `datetime:date-literal:${order.toLowerCase()}`,\n );\n }\n\n if (sep1.type === \"SLASH\") {\n // European: DD/MM/YYYY (always, no ISO-slash variant is documented)\n if (!DAY_OR_MONTH.test(t0.value) || !DAY_OR_MONTH.test(t1.value)) return null;\n const year = resolveYear(t2.value);\n if (year === null) return null;\n return buildDateToken(Number(t0.value), Number(t1.value), year, sourceTokens, \"datetime:date-literal:european\");\n }\n\n // MINUS: ISO (YYYY-MM-DD) if the first group is exactly 4 digits, else US (MM-DD-YYYY)\n if (t0.value.length === 4) {\n if (!DAY_OR_MONTH.test(t1.value) || !DAY_OR_MONTH.test(t2.value)) return null;\n // year=t0, month=t1, day=t2, buildDateToken takes (day, month, year)\n return buildDateToken(Number(t2.value), Number(t1.value), Number(t0.value), sourceTokens, \"datetime:date-literal:iso\");\n }\n if (!DAY_OR_MONTH.test(t0.value) || !DAY_OR_MONTH.test(t1.value)) return null;\n const year = resolveYear(t2.value);\n if (year === null) return null;\n // month=t0, day=t1, year=t2, buildDateToken takes (day, month, year)\n return buildDateToken(Number(t1.value), Number(t0.value), year, sourceTokens, \"datetime:date-literal:us\");\n },\n };\n}\n"]}
@@ -1,2 +1,2 @@
1
- import {c as c$1}from'./chunk-YAZ4DUJJ.js';var d="2.16.0";var m=d;var l={date:{maxOffsetYears:100,minOffsetYears:-100,defaultFormat:"YYYY-MM-DD",inputOrder:"auto"},performance:{defaultCacheSize:2e3,maxDocumentLines:1e5},validation:{maxExpressionLength:2e3,maxComplexity:500,maxNestingDepth:50,autoBalanceParens:false},vm:{maxStackDepth:200,maxInstructions:5e4,maxCollectionSize:1e5,maxAllocatedElements:2e6,maxFunctionCalls:1e4,maxGoalSeekIterations:100},worker:{maxConcurrentWorkers:4,idleTimeoutMs:3e4,maxRetries:3,baseBackoffMs:1e3},diagnostic:{enabled:false,vmTraceEnabled:false},backgroundRefresh:{enabled:false}};function r(s,e){return {date:{...s.date,...e.date},performance:{...s.performance,...e.performance},validation:{...s.validation,...e.validation},vm:{...s.vm,...e.vm},worker:{...s.worker,...e.worker},diagnostic:{...s.diagnostic,...e.diagnostic},backgroundRefresh:{...s.backgroundRefresh,...e.backgroundRefresh}}}var c=class{constructor(e={}){this.config=r(l,e);}get(e){let o=e.split("."),t=this.config;for(let i of o)if(t&&typeof t=="object"&&i in t)t=t[i];else throw c$1.config("CONFIG_PATH_NOT_FOUND",`Configuration path not found: ${e}`,{path:e});return t}set(e,o){let t=e.split(".");if(t.length<2)throw c$1.config("INVALID_CONFIG_PATH",`Invalid path: ${e}. Must be in format 'section.property'`,{path:e});let i=t[0],u=t[1];if(!(i in this.config))throw c$1.config("CONFIG_SECTION_NOT_FOUND",`Configuration section not found: ${i}`,{section:i,path:e});let a=this.config[i];if(a&&typeof a=="object")a[u]=o;else throw c$1.config("CONFIG_PROPERTY_NOT_FOUND",`Configuration property not found: ${e}`,{path:e})}getConfig(){return r(this.config,{})}update(e){this.config=r(this.config,e);}reset(){this.config=r(l,{});}validate(){let e=[];return this.config.performance.maxDocumentLines>1e5&&e.push("maxDocumentLines cannot exceed 100,000"),this.config.date.maxOffsetYears>1e3&&e.push("maxOffsetYears cannot exceed 1000"),{valid:e.length===0,error:e.join("; "),warnings:[]}}};export{m as a,l as b,r as c,c as d};//# sourceMappingURL=chunk-55B4PSPM.js.map
2
- //# sourceMappingURL=chunk-55B4PSPM.js.map
1
+ import {c as c$1}from'./chunk-PIZQIQVM.js';var d="2.18.0";var m=d;var l={date:{maxOffsetYears:100,minOffsetYears:-100,defaultFormat:"YYYY-MM-DD",inputOrder:"auto"},performance:{defaultCacheSize:2e3,maxDocumentLines:1e5},validation:{maxExpressionLength:2e3,maxComplexity:500,maxNestingDepth:50,autoBalanceParens:false},vm:{maxStackDepth:200,maxInstructions:5e4,maxCollectionSize:1e5,maxAllocatedElements:2e6,maxFunctionCalls:1e4,maxGoalSeekIterations:100},worker:{maxConcurrentWorkers:4,idleTimeoutMs:3e4,maxRetries:3,baseBackoffMs:1e3},diagnostic:{enabled:false,vmTraceEnabled:false},backgroundRefresh:{enabled:false}};function r(s,e){return {date:{...s.date,...e.date},performance:{...s.performance,...e.performance},validation:{...s.validation,...e.validation},vm:{...s.vm,...e.vm},worker:{...s.worker,...e.worker},diagnostic:{...s.diagnostic,...e.diagnostic},backgroundRefresh:{...s.backgroundRefresh,...e.backgroundRefresh}}}var c=class{constructor(e={}){this.config=r(l,e);}get(e){let o=e.split("."),t=this.config;for(let i of o)if(t&&typeof t=="object"&&i in t)t=t[i];else throw c$1.config("CONFIG_PATH_NOT_FOUND",`Configuration path not found: ${e}`,{path:e});return t}set(e,o){let t=e.split(".");if(t.length<2)throw c$1.config("INVALID_CONFIG_PATH",`Invalid path: ${e}. Must be in format 'section.property'`,{path:e});let i=t[0],u=t[1];if(!(i in this.config))throw c$1.config("CONFIG_SECTION_NOT_FOUND",`Configuration section not found: ${i}`,{section:i,path:e});let a=this.config[i];if(a&&typeof a=="object")a[u]=o;else throw c$1.config("CONFIG_PROPERTY_NOT_FOUND",`Configuration property not found: ${e}`,{path:e})}getConfig(){return r(this.config,{})}update(e){this.config=r(this.config,e);}reset(){this.config=r(l,{});}validate(){let e=[];return this.config.performance.maxDocumentLines>1e5&&e.push("maxDocumentLines cannot exceed 100,000"),this.config.date.maxOffsetYears>1e3&&e.push("maxOffsetYears cannot exceed 1000"),{valid:e.length===0,error:e.join("; "),warnings:[]}}};export{m as a,l as b,r as c,c as d};//# sourceMappingURL=chunk-6ERKCASV.js.map
2
+ //# sourceMappingURL=chunk-6ERKCASV.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json","../src/constants/version.ts","../src/constants/Configuration.ts"],"names":["version","ENGINE_VERSION","DEFAULT_CONFIG","mergeEngineConfig","base","override","ConfigManager","config","path","keys","current","key","ErrorFactory","value","section","property","sectionConfig","errors"],"mappings":"2CAEE,IAAAA,EAAW,QAAA,CCcN,IAAMC,EAAyBD,ECkV/B,IAAME,EAA+B,CACzC,IAAA,CAAM,CAIJ,cAAA,CAAgB,IAChB,cAAA,CAAgB,IAAA,CAChB,cAAe,YAAA,CACf,UAAA,CAAY,MACd,CAAA,CACA,WAAA,CAAa,CAIX,gBAAA,CAAkB,IAalB,gBAAA,CAAkB,GACpB,EACC,UAAA,CAAY,CACV,oBAAqB,GAAA,CACrB,aAAA,CAAe,IACf,eAAA,CAAiB,EAAA,CACjB,kBAAmB,KACrB,CAAA,CACA,GAAI,CACF,aAAA,CAAe,IACf,eAAA,CAAiB,GAAA,CAKjB,iBAAA,CAAmB,GAAA,CAInB,qBAAsB,GAAA,CAMtB,gBAAA,CAAkB,IAMlB,qBAAA,CAAuB,GACzB,EACA,MAAA,CAAQ,CACN,oBAAA,CAAsB,CAAA,CACtB,cAAe,GAAA,CACf,UAAA,CAAY,EACZ,aAAA,CAAe,GACjB,EACA,UAAA,CAAY,CACV,OAAA,CAAS,KAAA,CACT,eAAgB,KAClB,CAAA,CACA,kBAAmB,CACjB,OAAA,CAAS,KACX,CACF,EAiBK,SAASC,CAAAA,CACdC,CAAAA,CACAC,EACc,CACd,OAAO,CACL,IAAA,CAAM,CAAE,GAAGD,CAAAA,CAAK,IAAA,CAAM,GAAGC,CAAAA,CAAS,IAAK,CAAA,CACvC,WAAA,CAAa,CAAE,GAAGD,CAAAA,CAAK,YAAa,GAAGC,CAAAA,CAAS,WAAY,CAAA,CAC5D,WAAY,CAAE,GAAGD,EAAK,UAAA,CAAY,GAAGC,EAAS,UAAW,CAAA,CACzD,EAAA,CAAI,CAAE,GAAGD,CAAAA,CAAK,EAAA,CAAI,GAAGC,CAAAA,CAAS,EAAG,EACjC,MAAA,CAAQ,CAAE,GAAGD,CAAAA,CAAK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CAAA,CAC3C,CAAE,QAAAA,CAAAA,CAAS,IAAA,CAAAN,CAAK,CAClB,CAAA,CAGF,IAAMQ,CAAAA,CAAgB,IAAA,CAAK,OAAOF,CAA6B,CAAA,CAC/D,GAAIE,CAAAA,EAAiB,OAAOA,CAAAA,EAAkB,QAAA,CAC3CA,EAAqDD,CAAQ,CAAA,CAAIF,OAElE,MAAMD,GAAAA,CAAa,OACjB,2BAAA,CACA,CAAA,kCAAA,EAAqCJ,CAAI,CAAA,CAAA,CACzC,CAAE,IAAA,CAAAA,CAAK,CACT,CAEJ,CAUA,WAA0B,CACxB,OAAOL,CAAAA,CAAkB,IAAA,CAAK,OAAQ,EAAE,CAC1C,CAKA,MAAA,CAAOI,EAAqC,CAC1C,IAAA,CAAK,OAASJ,CAAAA,CAAkB,IAAA,CAAK,OAAQI,CAAM,EACrD,CAcA,KAAA,EAAc,CACZ,KAAK,MAAA,CAASJ,CAAAA,CAAkBD,CAAAA,CAAgB,EAAE,EACpD,CAKA,UAA6B,CAC3B,IAAMe,EAAmB,EAAC,CAG1B,OAAI,IAAA,CAAK,MAAA,CAAO,YAAY,gBAAA,CAAmB,GAAA,EAC7CA,EAAO,IAAA,CAAK,wCAAwC,EAIlD,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,cAAA,CAAiB,KACpCA,CAAAA,CAAO,IAAA,CAAK,mCAAmC,CAAA,CAG1C,CACL,MAAOA,CAAAA,CAAO,MAAA,GAAW,EACzB,KAAA,CAAOA,CAAAA,CAAO,KAAK,IAAI,CAAA,CACvB,SAAU,EACZ,CACF,CACF","file":"chunk-55B4PSPM.js","sourcesContent":["{\n \"name\": \"solve-engine\",\n \"version\": \"2.16.0\",\n \"description\": \"An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.\",\n \"keywords\": [\n \"expression-evaluator\",\n \"calculator\",\n \"bytecode-vm\",\n \"parser\",\n \"lexer\",\n \"dsl\",\n \"markdown\",\n \"obsidian\"\n ],\n \"license\": \"MIT\",\n \"author\": \"Liam Riddell\",\n \"homepage\": \"https://liamriddell.github.io/solve-engine/\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/LiamRiddell/solve-engine.git\",\n \"directory\": \"packages/engine\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/LiamRiddell/solve-engine/issues\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"dist\",\n \"LICENSE\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./engine\": {\n \"import\": {\n \"types\": \"./dist/engine.d.ts\",\n \"default\": \"./dist/engine.js\"\n },\n \"require\": {\n \"types\": \"./dist/engine.d.cts\",\n \"default\": \"./dist/engine.cjs\"\n }\n },\n \"./vm\": {\n \"import\": {\n \"types\": \"./dist/vm.d.ts\",\n \"default\": \"./dist/vm.js\"\n },\n \"require\": {\n \"types\": \"./dist/vm.d.cts\",\n \"default\": \"./dist/vm.cjs\"\n }\n },\n \"./format\": {\n \"import\": {\n \"types\": \"./dist/format.d.ts\",\n \"default\": \"./dist/format.js\"\n },\n \"require\": {\n \"types\": \"./dist/format.d.cts\",\n \"default\": \"./dist/format.cjs\"\n }\n },\n \"./language\": {\n \"import\": {\n \"types\": \"./dist/language.d.ts\",\n \"default\": \"./dist/language.js\"\n },\n \"require\": {\n \"types\": \"./dist/language.d.cts\",\n \"default\": \"./dist/language.cjs\"\n }\n },\n \"./packages\": {\n \"import\": {\n \"types\": \"./dist/packages.d.ts\",\n \"default\": \"./dist/packages.js\"\n },\n \"require\": {\n \"types\": \"./dist/packages.d.cts\",\n \"default\": \"./dist/packages.cjs\"\n }\n },\n \"./constants\": {\n \"import\": {\n \"types\": \"./dist/constants.d.ts\",\n \"default\": \"./dist/constants.js\"\n },\n \"require\": {\n \"types\": \"./dist/constants.d.cts\",\n \"default\": \"./dist/constants.cjs\"\n }\n },\n \"./lexer\": {\n \"import\": {\n \"types\": \"./dist/lexer.d.ts\",\n \"default\": \"./dist/lexer.js\"\n },\n \"require\": {\n \"types\": \"./dist/lexer.d.cts\",\n \"default\": \"./dist/lexer.cjs\"\n }\n },\n \"./parser\": {\n \"import\": {\n \"types\": \"./dist/parser.d.ts\",\n \"default\": \"./dist/parser.js\"\n },\n \"require\": {\n \"types\": \"./dist/parser.d.cts\",\n \"default\": \"./dist/parser.cjs\"\n }\n },\n \"./normalizer\": {\n \"import\": {\n \"types\": \"./dist/normalizer.d.ts\",\n \"default\": \"./dist/normalizer.js\"\n },\n \"require\": {\n \"types\": \"./dist/normalizer.d.cts\",\n \"default\": \"./dist/normalizer.cjs\"\n }\n },\n \"./resolvers\": {\n \"import\": {\n \"types\": \"./dist/resolvers.d.ts\",\n \"default\": \"./dist/resolvers.js\"\n },\n \"require\": {\n \"types\": \"./dist/resolvers.d.cts\",\n \"default\": \"./dist/resolvers.cjs\"\n }\n },\n \"./errors\": {\n \"import\": {\n \"types\": \"./dist/errors.d.ts\",\n \"default\": \"./dist/errors.js\"\n },\n \"require\": {\n \"types\": \"./dist/errors.d.cts\",\n \"default\": \"./dist/errors.cjs\"\n }\n },\n \"./utilities\": {\n \"import\": {\n \"types\": \"./dist/utilities.d.ts\",\n \"default\": \"./dist/utilities.js\"\n },\n \"require\": {\n \"types\": \"./dist/utilities.d.cts\",\n \"default\": \"./dist/utilities.cjs\"\n }\n },\n \"./uom\": {\n \"import\": {\n \"types\": \"./dist/uom.d.ts\",\n \"default\": \"./dist/uom.js\"\n },\n \"require\": {\n \"types\": \"./dist/uom.d.cts\",\n \"default\": \"./dist/uom.cjs\"\n }\n },\n \"./services\": {\n \"import\": {\n \"types\": \"./dist/services.d.ts\",\n \"default\": \"./dist/services.js\"\n },\n \"require\": {\n \"types\": \"./dist/services.d.cts\",\n \"default\": \"./dist/services.cjs\"\n }\n },\n \"./worker\": {\n \"import\": {\n \"types\": \"./dist/worker.d.ts\",\n \"default\": \"./dist/worker.js\"\n },\n \"require\": {\n \"types\": \"./dist/worker.d.cts\",\n \"default\": \"./dist/worker.cjs\"\n }\n },\n \"./testing\": {\n \"import\": {\n \"types\": \"./dist/testing.d.ts\",\n \"default\": \"./dist/testing.js\"\n },\n \"require\": {\n \"types\": \"./dist/testing.d.cts\",\n \"default\": \"./dist/testing.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"prepublishOnly\": \"npm run build && node ../../scripts/assert-publishable.mjs .\",\n \"dev\": \"tsup --watch\",\n \"test\": \"jest --config jest.config.cjs --no-coverage\",\n \"typecheck\": \"tsgo --noEmit --skipLibCheck\",\n \"typecheck:tsc\": \"tsc --noEmit --skipLibCheck\"\n },\n \"dependencies\": {\n \"@tanstack/query-core\": \"^5.100.10\"\n },\n \"devDependencies\": {\n \"@jest/globals\": \"^30.4.1\",\n \"@types/node\": \"^26.2.0\",\n \"convert\": \"^7.0.0\",\n \"jest\": \"^30.4.2\",\n \"ts-jest\": \"^29.4.12\",\n \"tsup\": \"8.5.1\",\n \"typescript\": \"5.9.3\"\n },\n \"//sideEffects\": \"Load-bearing claim, not boilerplate. tsup's splitting emits bare chunk imports at the top of dist/index.js, and this field tells Rollup, webpack and Vite they may delete them, which esbuild reports as [ignored-bare-import] once per import during `npm run size`. The engine does have module-level work to lose: registerAllTokenTypes(), _PrecedenceParser.BP_TABLE and its cached token ids, and several process-wide registries. It is safe because every chunk doing that work is also imported for its bindings somewhere, so no bundler can drop it. That is a property of how tsup currently splits the code rather than a design guarantee, so `npm run smoke:bundled` (scripts/check-tree-shaking.mjs) proves it on every run of `npm run verify` instead of assuming it, and its header explains the two fixes if it ever stops holding.\",\n \"sideEffects\": false\n}\n","/**\n * The running engine's own semver version, sourced directly from this\n * package's package.json so it can never drift from what's actually\n * published. Exists so IEnginePackage.engineVersion range checks\n * (api/EngineVersionCompatibility.ts) have something real to check\n * against.\n */\nimport { version } from \"../../package.json\";\n\n/**\n * The running engine's version, taken from package.json.\n *\n * What a package's `engineVersion` range is checked against at registration.\n * A prerelease is compared by its coerced release version, so a 1.0.0 beta\n * satisfies `^1.0.0`. See `api/EngineVersionCompatibility.ts`.\n */\nexport const ENGINE_VERSION: string = version;\n","/**\n * Configuration Module for solve-js Engine\n * \n * This module provides the **single source of truth** for all engine configuration.\n * Every configurable aspect of the engine, from safety limits and performance\n * budgets to VM constraints and worker pool sizing, is defined here.\n * \n * ### Design principles\n * \n * 1. **Engine owns its config.** The engine defines its own config shape and defaults.\n * Consumers (e.g., the Obsidian plugin) pass partial overrides; all unspecified\n * fields fall back to `DEFAULT_CONFIG`.\n * \n * 2. **Self-documenting.** Every interface and field has descriptive JSDoc so the\n * config is understandable at a glance, whether you're using the engine as an\n * npm package or reading the source.\n * \n * 3. **Minimal consumer knowledge.** Consumers only need to pass `Partial<EngineConfig>`.\n * They don't need to replicate the full config shape, just the fields they\n * want to override.\n * \n * @module Configuration\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A host's test for whether a calendar date is a public holiday, given the\n * `Date` for that day at local midnight. Return `true` to exclude it from\n * working-day arithmetic.\n */\nexport type HolidayPredicate = (date: Date) => boolean;\n\n/**\n * The host-supplied public-holiday calendar, in the same \"bring your own data\"\n * shape the stocks and weather packages already use for a host callback (see\n * `packages/stocks/StocksPackage.ts`): weekends are decidable from the date\n * alone, holidays are not, so they come from the host or not at all.\n *\n * Either a {@link HolidayPredicate}, for a host that computes holidays itself\n * (an existing library, a region rule), or an iterable of specific dates as\n * `YYYY-MM-DD` strings, epoch-millisecond numbers or `Date` objects, for a host\n * that just has a list. Resolved to one internal predicate by\n * `vm/HolidayCalendar.ts`'s `resolveHolidayPredicate()`.\n *\n * Left unset, working-day arithmetic skips weekends only, which is the honest\n * default: the engine excludes exactly the days it can prove are non-working.\n */\nexport type HolidayCalendar = HolidayPredicate | Iterable<string | number | Date>;\n\n/**\n * Date-related configuration.\n * Controls the bounds and formatting for date/time expression evaluation\n * (e.g., `today + 20 days`, `last monday`).\n */\n/**\n * How an ambiguous all-numeric date literal is read.\n *\n * - `'auto'`: by separator, the historic behaviour. A slash date is\n * day-first (`25/12/2023`), a hyphen date is month-first (`12-25-2023`)\n * unless its first group is four digits, which makes it ISO (`2023-12-25`).\n * - `'DMY'` / `'MDY'` / `'YMD'`: a fixed order for every numeric separator, so\n * a host can match its readers' locale. `'MDY'` is what lets a US reader's\n * `12/25/2023` parse, which `'auto'` refuses because the slash defaults to\n * day-first.\n *\n * Only the all-numeric literals are affected. A spelled-out month (`March 9,\n * 2024`) is never ambiguous, and an ISO timestamp is always read as ISO.\n */\nexport type DateInputOrder = 'auto' | 'DMY' | 'MDY' | 'YMD';\n\n/** Date-related engine configuration: offset limits, input order, holidays. */\nexport interface DateConfig {\n /**\n * The order an ambiguous all-numeric date literal is read in. Defaults to\n * `'auto'` (by separator, the historic behaviour). See {@link DateInputOrder}.\n */\n readonly inputOrder: DateInputOrder;\n /**\n * How far forward a date offset whose COST grows with the offset may reach,\n * in years. Enforced by `vm/VM.ts`'s `addBusinessDays()`.\n *\n * Bounds the walk, not the calendar. Every other date offset in the engine\n * is arithmetic on a Date field, so `today + 100000 days` costs exactly what\n * one day costs and needs no ceiling; workdays are the one offset that has\n * to step day by day, because which days are skipped depends on where each\n * step lands. `today + 100000000 workdays` therefore froze the host for\n * thirteen seconds inside a single ADD opcode (where `vm.maxInstructions`\n * cannot see it) and then answered \"Invalid Date\", and a trillion never\n * returned at all.\n *\n * Release hardening: this field was declared, documented as a \"safety\n * limit\", and read nowhere, so it bounded nothing. A limit a host can\n * configure and the engine ignores is worse than no limit, because it reads\n * as protection that is not there.\n */\n readonly maxOffsetYears: number;\n /** How far BACK the same walk may reach, in years, as a negative number. See {@link maxOffsetYears}. */\n readonly minOffsetYears: number;\n /** Default date string format for display (moment.js format string) */\n readonly defaultFormat: string;\n /**\n * Public-holiday calendar for working-day arithmetic (`N working days after\n * <date>`, `working days between <date> and <date>`, `<date> + N workdays`).\n * See {@link HolidayCalendar}.\n *\n * Optional and unset by default: with no calendar, working-day arithmetic\n * skips weekends only. A host that wants holidays excluded too supplies one\n * here (`new ExpressionEngine({ config: { date: { holidays } } })`), the\n * same way stocks and weather take a host data source. Threaded into the VM\n * by `engine/ExpressionEngine.ts` exactly as {@link maxOffsetYears} is,\n * because working-day math is a VM operation several grammar forms share, so\n * the calendar has to be one source the VM owns rather than per-package state\n * the VM cannot see.\n */\n readonly holidays?: HolidayCalendar;\n}\n\n/**\n * Performance-related configuration.\n * Controls caching, timeouts, and processing limits to prevent runaway\n * resource consumption on large documents.\n */\nexport interface PerformanceConfig {\n /**\n * Maximum number of entries in {@link ExpressionEngine}'s bytecode cache\n * (per-instance, keyed by expression text) before the oldest entry is\n * evicted. Raise this for documents with many distinct expressions if\n * repeated re-evaluation (e.g. scrolling) is re-parsing instead of\n * hitting cache, bug fix (release hardening pass): this field used to\n * be read nowhere; the cache size was a hardcoded, unconfigurable\n * constant. Note this does NOT bound {@link LineCache}, which has no\n * size limit of its own.\n */\n readonly defaultCacheSize: number;\n /**\n * Maximum lines a document may have for the engine to process it in one\n * pass. Enforced by `ExpressionEngine.parseDocument()` and by\n * `engine/DocumentModel.ts`'s `setDocument()`, the two entry points that\n * take a whole document.\n *\n * A document costs memory per line whatever each line says: a parsed line\n * record, a cache entry, a dependency-graph node. Two hundred thousand\n * lines of `1 + 1` therefore exhausted the heap and aborted the process\n * before any per-line limit had anything to object to, which is the same\n * shape of hole as an unbounded expression and needs the same kind of\n * ceiling. Refusing the document names the limit; a host that genuinely has\n * a larger one raises this field.\n *\n * Release hardening: declared and read nowhere until now.\n */\n readonly maxDocumentLines: number;\n}\n\n/**\n * Validation / safety-limit configuration.\n * Protects against runaway expressions that could cause excessive memory use\n * or stack overflow. These limits are checked during lexing and parsing.\n */\n/** Bounds on untrusted input: expression length and nesting depth. */\nexport interface ValidationConfig {\n /** Maximum expression length in characters. Prevents excessively long strings from entering the pipeline. */\n readonly maxExpressionLength: number;\n /** Maximum expression complexity score (`tokens + functionCalls×5 + nestingDepth×10`). Protects against deeply nested or combinatorially complex expressions. */\n readonly maxComplexity: number;\n /** Maximum parentheses nesting depth. Prevents stack overflow in the recursive-descent parser. */\n readonly maxNestingDepth: number;\n /**\n * Auto-balance unmatched parentheses by appending missing closing parens\n * or prepending missing opening parens. When disabled, unbalanced expressions\n * cause parse errors instead of being silently corrected.\n *\n * Disabled by default for strict parsing. Enable for forgiving user input\n * (e.g., chat-style calculators where users often omit closing parens).\n * Has zero overhead when disabled, the O(n) paren-count scan is skipped.\n */\n readonly autoBalanceParens: boolean;\n}\n\n/**\n * Worker pool configuration.\n * Controls the parallel execution workers used for batch evaluation.\n */\nexport interface WorkerConfig {\n /** Maximum number of concurrent Web Workers allowed */\n readonly maxConcurrentWorkers: number;\n /** Time (ms) a worker stays alive while idle before being terminated */\n readonly idleTimeoutMs: number;\n /** Maximum retry attempts for a failed worker operation */\n readonly maxRetries: number;\n /** Base backoff delay (ms) between retries (exponential backoff applied on top) */\n readonly baseBackoffMs: number;\n} /**\n * Diagnostic / telemetry configuration.\n * Controls the diagnostic event pipeline for profiling and debugging.\n * All diagnostics are disabled by default for maximum production performance.\n */\n export interface DiagnosticConfig {\n /** Master switch: enable the diagnostic pipeline (collectors receive events for all pipeline stages) */\n readonly enabled: boolean;\n /** Enable VM trace mode, emits per-opcode execution events (very verbose; disables some optimizations) */\n readonly vmTraceEnabled: boolean;\n }\n\n /**\n * Proactive background refresh of live async values.\n *\n * Off by default. When a live value (a stock quote, an FX rate) has gone\n * stale, today it only refetches on the next re-evaluation (a keystroke), so a\n * note left open silently ages. With this enabled, the engine drives a refetch\n * on each such value's own cadence (the resolver's `refetchIntervalMs`) for the\n * values currently on screen, and pushes the fresh result to the host through\n * the same event stream the pull path uses. It needs timers and a live editor\n * consuming that stream, so a headless or batch host leaves it off.\n */\n export interface BackgroundRefreshConfig {\n /** Master switch. When false, no timers run and every value refreshes only on re-evaluation. */\n readonly enabled: boolean;\n }\n\n /**\n * Virtual Machine configuration.\n * Controls the internal bytecode VM that executes compiled expressions.\n */\n export interface VMConfig {\n /** Maximum stack depth (value slots) for VM execution, prevents stack overflow in recursive/pratt-parser generated bytecode */\n readonly maxStackDepth: number;\n /** Maximum opcodes executed per expression, halts runaway infinite loops */\n readonly maxInstructions: number;\n /**\n * Maximum elements a collection may be expanded to before `map`/`reduce`/\n * `sum`/`prod` will iterate it.\n *\n * A Range is stored as its two bounds and costs nothing until something\n * materializes it, at which point it becomes one Value per element. Twenty\n * characters (`sum(x, 1:100000000)`) therefore asked for a hundred million\n * of them, and neither `maxInstructions` nor `maxStackDepth` could see it:\n * the expansion happens inside a single opcode, so the instruction counter\n * is never consulted while it runs, and the elements never reach the value\n * stack. V8 aborted the whole process with \"Reached heap limit\", which a\n * host embedding the engine cannot catch.\n */\n readonly maxCollectionSize: number;\n /**\n * Maximum elements (collection Values, matrix cells) one evaluation may\n * materialize in total.\n *\n * `maxCollectionSize` above bounds a single collection. This bounds the sum\n * of everything an expression asks for, which is a different question and\n * the one that actually protects the host: two collections that are\n * individually legal are legal together, and an operation whose result is\n * the PRODUCT of two legal operands is bounded by neither of them. A matrix\n * multiply is exactly that shape, so three lines within every other limit\n * (`:a = map(1*x, 0:20000)`, `:b = transpose(a)`, `b * a`) asked for four\n * hundred million cells and aborted the process.\n *\n * Counted in elements rather than bytes, because a count is what a call\n * site has before it allocates. An element is 8 bytes as a numeric matrix\n * cell and closer to a hundred as a full Value, so the default is worth\n * roughly 16 MB of matrix or 200 MB of expanded collection: far past any\n * document and far short of what an editor cannot survive.\n */\n readonly maxAllocatedElements: number;\n /**\n * Maximum user-defined-function calls one evaluation may make in TOTAL,\n * however deeply or widely they nest.\n *\n * `maxFunctionRecursionDepth` bounds how DEEP calls nest and cannot see\n * how MANY there are, and those are different numbers. Twenty-two lines of\n * `f(n)(v) = f(n-1)(v) + f(n-1)(v)` reach a depth of only 22 against a\n * limit of 50, and make 2,097,152 calls doing it: a fatal heap abort in\n * under a second. `maxInstructions` cannot bound it either, because\n * `executeBytecode()` re-enters itself per call and each reentrant call\n * gets its OWN instruction count, so recursion refreshes its allowance on\n * the way in. This is the tally that does not refresh; see\n * `vm/AllocationBudget.ts`, which holds it for the same reason it holds\n * the element tally.\n *\n * Counted in calls rather than in the instructions they run, because the\n * call is the thing that multiplies: every call allocates a frame, its\n * arguments and its result whatever its body says.\n */\n readonly maxFunctionCalls: number;\n /**\n * Hard ceiling on how many bisection steps goal seek (`solve line N for\n * <var> = <target>`, see `packages/goalseek/`) may take before it gives up\n * with a structured error rather than continuing.\n *\n * Goal seek re-evaluates the target line's expression once per step while\n * narrowing an interval, and an untrusted document must never be able to\n * make that loop spin. `maxInstructions` bounds each individual\n * re-evaluation, but not how many of them the search performs, so this is\n * the tally that bounds the search itself, the same reason `maxFunctionCalls`\n * exists alongside `maxInstructions`. Bisection halves the interval every\n * step, so a hundred steps resolves an input to roughly one part in 2^100:\n * far past any precision a document needs, and a definite stop either way.\n */\n readonly maxGoalSeekIterations: number;\n }\n\n/**\n * Complete engine configuration.\n *\n * Every field has a default in `DEFAULT_CONFIG`. To customize, pass a\n * `Partial<EngineConfig>` when constructing `ExpressionEngine`. Only the\n * sections/fields you supply are overridden; all others use their defaults.\n *\n * @example\n * ```typescript\n * import { ExpressionEngine } from \"solve-js\";\n *\n * const engine = new ExpressionEngine({ config: {\n * validation: {\n * maxExpressionLength: 1000,\n * maxComplexity: 200,\n * },\n * // date, performance, vm, worker, diagnostic all use defaults\n * } });\n * ```\n */\nexport interface EngineConfig {\n /** Date/time expression evaluation bounds and formatting */\n readonly date: DateConfig;\n /** Performance budgets and cache sizing */\n readonly performance: PerformanceConfig;\n /** Safety limits for expression complexity */\n readonly validation: ValidationConfig;\n /** Internal bytecode VM configuration */\n readonly vm: VMConfig;\n /** Parallel worker pool configuration */\n readonly worker: WorkerConfig;\n /** Diagnostic pipeline configuration */\n readonly diagnostic: DiagnosticConfig;\n /** Proactive background refresh of live async values */\n readonly backgroundRefresh: BackgroundRefreshConfig;\n }\n\n/**\n * A partial {@link EngineConfig} override, one section at a time.\n *\n * Overrides are merged per section over {@link DEFAULT_CONFIG}, so you can set a\n * single field of one section (`{ validation: { maxExpressionLength: 1000 } }`)\n * and keep every other default in that section. A plain `Partial<EngineConfig>`\n * cannot express that, it demands a whole section object, which is why the\n * documented overrides never typechecked against it. This is the type the\n * constructor and {@link createEngine} accept.\n */\nexport type EngineConfigOverride = {\n readonly [K in keyof EngineConfig]?: Partial<EngineConfig[K]>;\n};\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: EngineConfig = {\n date: {\n // A century of workdays is about 26,000 steps, which is microseconds,\n // and past any offset a person means. The walk is what these bound; see\n // DateConfig above for why no other date offset needs a ceiling.\n maxOffsetYears: 100,\n minOffsetYears: -100,\n defaultFormat: 'YYYY-MM-DD',\n inputOrder: 'auto',\n },\n performance: {\n // Preserves the effective cache size the hardcoded (now-removed)\n // BYTECODE_CACHE_MAX_ENTRIES constant had, so wiring this field up\n // doesn't silently shrink the default cache for existing consumers.\n defaultCacheSize: 2000,\n // Raised from the 10,000 this field was declared with, which was never\n // enforced and turned out to be under what this engine already supports:\n // its paging design is tested against a 20,000-line document\n // (`engine/PageManager.ts` and its spec) and its throughput benchmark\n // parses a 50,000-line one. Twice the largest of those, and the same\n // number `ConfigManager.validate()` already refuses to go above.\n //\n // Measured under a 256MB heap: setting a 100,000-line document costs\n // 64MB, evaluating every line of a 20,000-line one costs 106MB, and\n // 200,000 lines aborts the process before a single expression is looked\n // at. A host with a small heap should lower this; the ceiling is here to\n // stop the size that cannot work anywhere.\n maxDocumentLines: 100000,\n },\n validation: {\n maxExpressionLength: 2000,\n maxComplexity: 500,\n maxNestingDepth: 50,\n autoBalanceParens: false,\n },\n vm: {\n maxStackDepth: 200,\n maxInstructions: 50000,\n // Two orders of magnitude above anything a person types by hand (the\n // longest range in the test suite is 1000 elements) and small enough\n // that expanding it is measured in milliseconds rather than in whether\n // the host survives.\n maxCollectionSize: 100000,\n // Twenty times the single-collection ceiling above, so an expression may\n // legitimately handle a number of large collections, and two hundred\n // times below the allocation that took the process down.\n maxAllocatedElements: 2000000,\n // Six hundred times the largest call count any test or example makes\n // (five levels of composition is sixteen calls), and small enough that\n // the calls it does allow cost single-digit megabytes rather than the\n // heap. A document that needs more than ten thousand calls on one line\n // is doing something a calculator was not built for.\n maxFunctionCalls: 10000,\n // A hundred bisection steps resolve an input to one part in 2^100, far\n // finer than any document needs and a firm stop for an untrusted one. A\n // continuous, monotonic relationship converges in tens of steps, well\n // under this; hitting it means the target is unreachable or the\n // relationship is not the smooth one goal seek assumes.\n maxGoalSeekIterations: 100,\n },\n worker: {\n maxConcurrentWorkers: 4,\n idleTimeoutMs: 30000,\n maxRetries: 3,\n baseBackoffMs: 1000,\n },\n diagnostic: {\n enabled: false,\n vmTraceEnabled: false,\n },\n backgroundRefresh: {\n enabled: false,\n },\n };\n\n/**\n * Merge a partial config override onto a base `EngineConfig`, section by\n * section, `{ ...base.section, ...override.section }` for each of the 7\n * top-level sections, not a single top-level spread.\n *\n * A shallow `{ ...base, ...override }` at the TOP level replaces an entire\n * section wholesale the moment a caller overrides even one field in it\n * (e.g. `{ performance: { defaultCacheSize: 500 } }` would silently drop\n * every other `performance.*` field back to `undefined`, not to its\n * default). This function exists specifically so every config consumer\n * shares one correct merge instead of each hand-rolling (and risking) its\n * own. `ConfigManager` and `ExpressionEngine` both call this rather than\n * either duplicating the section list or instantiating a whole\n * `ConfigManager` just to reuse its private merge logic.\n */\nexport function mergeEngineConfig(\n base: EngineConfig,\n override: EngineConfigOverride\n): EngineConfig {\n return {\n date: { ...base.date, ...override.date },\n performance: { ...base.performance, ...override.performance },\n validation: { ...base.validation, ...override.validation },\n vm: { ...base.vm, ...override.vm },\n worker: { ...base.worker, ...override.worker },\n diagnostic: { ...base.diagnostic, ...override.diagnostic },\n backgroundRefresh: { ...base.backgroundRefresh, ...override.backgroundRefresh },\n };\n}\n\n/**\n * Configuration manager for engine settings\n *\n * @example\n * ```typescript\n * const configManager = new ConfigManager();\n * configManager.set('performance.defaultCacheSize', 2000);\n * const cacheSize = configManager.get('performance.defaultCacheSize');\n * ```\n */\nexport class ConfigManager {\n private config: EngineConfig;\n\n constructor(config: Partial<EngineConfig> = {}) {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, config);\n }\n\n /**\n * Get configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @returns Configuration value\n */\n get<T>(path: string): T {\n const keys = path.split('.');\n let current: unknown = this.config;\n\n for (const key of keys) {\n if (current && typeof current === 'object' && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PATH_NOT_FOUND\",\n `Configuration path not found: ${path}`,\n { path }\n );\n }\n }\n\n return current as T;\n }\n\n /**\n * Set configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @param value - New value\n */\n set<T>(path: string, value: T): void {\n const keys = path.split('.');\n if (keys.length < 2) {\n throw ErrorFactory.config(\n \"INVALID_CONFIG_PATH\",\n `Invalid path: ${path}. Must be in format 'section.property'`,\n { path }\n );\n }\n \n const section = keys[0];\n const property = keys[1];\n \n if (!(section in this.config)) {\n throw ErrorFactory.config(\n \"CONFIG_SECTION_NOT_FOUND\",\n `Configuration section not found: ${section}`,\n { section, path }\n );\n }\n \n const sectionConfig = this.config[section as keyof EngineConfig];\n if (sectionConfig && typeof sectionConfig === 'object') {\n (sectionConfig as unknown as Record<string, unknown>)[property] = value;\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PROPERTY_NOT_FOUND\",\n `Configuration property not found: ${path}`,\n { path }\n );\n }\n }\n\n /**\n * Get complete configuration.\n *\n * A detached copy, section objects included. A top-level spread would hand\n * the caller this manager's own section objects, so `getConfig().vm.x = 1`\n * would be an undeclared back door into {@link set}, bypassing its path\n * validation and reaching every later {@link get}.\n */\n getConfig(): EngineConfig {\n return mergeEngineConfig(this.config, {});\n }\n\n /**\n * Update multiple configuration values\n */\n update(config: Partial<EngineConfig>): void {\n this.config = mergeEngineConfig(this.config, config);\n }\n\n /**\n * Reset to default configuration.\n *\n * Goes through {@link mergeEngineConfig} for the same reason the constructor\n * does. A top-level `{ ...DEFAULT_CONFIG }` copies the six section\n * references, not the sections, so after a reset this manager's\n * `performance` object WAS `DEFAULT_CONFIG.performance` and the next\n * `set('performance.x', ...)` wrote into the module constant. That constant\n * is what every `ExpressionEngine` is built from, so one manager's reset\n * could change the cache size, instruction ceiling or allocation budget of\n * every engine constructed later in the process.\n */\n reset(): void {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, {});\n }\n\n /**\n * Validate configuration values\n */\n validate(): ValidationResult {\n const errors: string[] = [];\n\n // Validate performance config\n if (this.config.performance.maxDocumentLines > 100000) {\n errors.push('maxDocumentLines cannot exceed 100,000');\n }\n\n // Validate date config\n if (this.config.date.maxOffsetYears > 1000) {\n errors.push('maxOffsetYears cannot exceed 1000');\n }\n\n return {\n valid: errors.length === 0,\n error: errors.join('; '),\n warnings: []\n };\n }\n}\n\n/**\n * Result type for {@link ConfigManager.validate}.\n */\nexport interface ValidationResult {\n valid: boolean;\n error?: string;\n warnings?: string[];\n}\n\n"]}
1
+ {"version":3,"sources":["../package.json","../src/constants/version.ts","../src/constants/Configuration.ts"],"names":["version","ENGINE_VERSION","DEFAULT_CONFIG","mergeEngineConfig","base","override","ConfigManager","config","path","keys","current","key","ErrorFactory","value","section","property","sectionConfig","errors"],"mappings":"2CAEE,IAAAA,EAAW,QAAA,CCcN,IAAMC,EAAyBD,ECkV/B,IAAME,EAA+B,CACzC,IAAA,CAAM,CAIJ,cAAA,CAAgB,IAChB,cAAA,CAAgB,IAAA,CAChB,cAAe,YAAA,CACf,UAAA,C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A,CAAA,kCAAA,EAAqCJ,CAAI,CAAA,CAAA,CACzC,CAAE,IAAA,CAAAA,CAAK,CACT,CAEJ,CAUA,WAA0B,CACxB,OAAOL,CAAAA,CAAkB,IAAA,CAAK,OAAQ,EAAE,CAC1C,CAKA,MAAA,CAAOI,EAAqC,CAC1C,IAAA,CAAK,OAASJ,CAAAA,CAAkB,IAAA,CAAK,OAAQI,CAAM,EACrD,CAcA,KAAA,EAAc,CACZ,KAAK,MAAA,CAASJ,CAAAA,CAAkBD,CAAAA,CAAgB,EAAE,EACpD,CAKA,UAA6B,CAC3B,IAAMe,EAAmB,EAAC,CAG1B,OAAI,IAAA,CAAK,MAAA,CAAO,YAAY,gBAAA,CAAmB,GAAA,EAC7CA,EAAO,IAAA,CAAK,wCAAwC,EAIlD,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,cAAA,CAAiB,KACpCA,CAAAA,CAAO,IAAA,CAAK,mCAAmC,CAAA,CAG1C,CACL,MAAOA,CAAAA,CAAO,MAAA,GAAW,EACzB,KAAA,CAAOA,CAAAA,CAAO,KAAK,IAAI,CAAA,CACvB,SAAU,EACZ,CACF,CACF","file":"chunk-6ERKCASV.js","sourcesContent":["{\n \"name\": \"solve-engine\",\n \"version\": \"2.18.0\",\n \"description\": \"An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.\",\n \"keywords\": [\n \"expression-evaluator\",\n \"calculator\",\n \"bytecode-vm\",\n \"parser\",\n \"lexer\",\n \"dsl\",\n \"markdown\",\n \"obsidian\"\n ],\n \"license\": \"MIT\",\n \"author\": \"Liam Riddell\",\n \"homepage\": \"https://liamriddell.github.io/solve-engine/\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/LiamRiddell/solve-engine.git\",\n \"directory\": \"packages/engine\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/LiamRiddell/solve-engine/issues\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"dist\",\n \"LICENSE\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./engine\": {\n \"import\": {\n \"types\": \"./dist/engine.d.ts\",\n \"default\": \"./dist/engine.js\"\n },\n \"require\": {\n \"types\": \"./dist/engine.d.cts\",\n \"default\": \"./dist/engine.cjs\"\n }\n },\n \"./vm\": {\n \"import\": {\n \"types\": \"./dist/vm.d.ts\",\n \"default\": \"./dist/vm.js\"\n },\n \"require\": {\n \"types\": \"./dist/vm.d.cts\",\n \"default\": \"./dist/vm.cjs\"\n }\n },\n \"./format\": {\n \"import\": {\n \"types\": \"./dist/format.d.ts\",\n \"default\": \"./dist/format.js\"\n },\n \"require\": {\n \"types\": \"./dist/format.d.cts\",\n \"default\": \"./dist/format.cjs\"\n }\n },\n \"./language\": {\n \"import\": {\n \"types\": \"./dist/language.d.ts\",\n \"default\": \"./dist/language.js\"\n },\n \"require\": {\n \"types\": \"./dist/language.d.cts\",\n \"default\": \"./dist/language.cjs\"\n }\n },\n \"./packages\": {\n \"import\": {\n \"types\": \"./dist/packages.d.ts\",\n \"default\": \"./dist/packages.js\"\n },\n \"require\": {\n \"types\": \"./dist/packages.d.cts\",\n \"default\": \"./dist/packages.cjs\"\n }\n },\n \"./constants\": {\n \"import\": {\n \"types\": \"./dist/constants.d.ts\",\n \"default\": \"./dist/constants.js\"\n },\n \"require\": {\n \"types\": \"./dist/constants.d.cts\",\n \"default\": \"./dist/constants.cjs\"\n }\n },\n \"./lexer\": {\n \"import\": {\n \"types\": \"./dist/lexer.d.ts\",\n \"default\": \"./dist/lexer.js\"\n },\n \"require\": {\n \"types\": \"./dist/lexer.d.cts\",\n \"default\": \"./dist/lexer.cjs\"\n }\n },\n \"./parser\": {\n \"import\": {\n \"types\": \"./dist/parser.d.ts\",\n \"default\": \"./dist/parser.js\"\n },\n \"require\": {\n \"types\": \"./dist/parser.d.cts\",\n \"default\": \"./dist/parser.cjs\"\n }\n },\n \"./normalizer\": {\n \"import\": {\n \"types\": \"./dist/normalizer.d.ts\",\n \"default\": \"./dist/normalizer.js\"\n },\n \"require\": {\n \"types\": \"./dist/normalizer.d.cts\",\n \"default\": \"./dist/normalizer.cjs\"\n }\n },\n \"./resolvers\": {\n \"import\": {\n \"types\": \"./dist/resolvers.d.ts\",\n \"default\": \"./dist/resolvers.js\"\n },\n \"require\": {\n \"types\": \"./dist/resolvers.d.cts\",\n \"default\": \"./dist/resolvers.cjs\"\n }\n },\n \"./errors\": {\n \"import\": {\n \"types\": \"./dist/errors.d.ts\",\n \"default\": \"./dist/errors.js\"\n },\n \"require\": {\n \"types\": \"./dist/errors.d.cts\",\n \"default\": \"./dist/errors.cjs\"\n }\n },\n \"./utilities\": {\n \"import\": {\n \"types\": \"./dist/utilities.d.ts\",\n \"default\": \"./dist/utilities.js\"\n },\n \"require\": {\n \"types\": \"./dist/utilities.d.cts\",\n \"default\": \"./dist/utilities.cjs\"\n }\n },\n \"./uom\": {\n \"import\": {\n \"types\": \"./dist/uom.d.ts\",\n \"default\": \"./dist/uom.js\"\n },\n \"require\": {\n \"types\": \"./dist/uom.d.cts\",\n \"default\": \"./dist/uom.cjs\"\n }\n },\n \"./services\": {\n \"import\": {\n \"types\": \"./dist/services.d.ts\",\n \"default\": \"./dist/services.js\"\n },\n \"require\": {\n \"types\": \"./dist/services.d.cts\",\n \"default\": \"./dist/services.cjs\"\n }\n },\n \"./worker\": {\n \"import\": {\n \"types\": \"./dist/worker.d.ts\",\n \"default\": \"./dist/worker.js\"\n },\n \"require\": {\n \"types\": \"./dist/worker.d.cts\",\n \"default\": \"./dist/worker.cjs\"\n }\n },\n \"./testing\": {\n \"import\": {\n \"types\": \"./dist/testing.d.ts\",\n \"default\": \"./dist/testing.js\"\n },\n \"require\": {\n \"types\": \"./dist/testing.d.cts\",\n \"default\": \"./dist/testing.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"prepublishOnly\": \"npm run build && node ../../scripts/assert-publishable.mjs .\",\n \"dev\": \"tsup --watch\",\n \"test\": \"jest --config jest.config.cjs --no-coverage\",\n \"typecheck\": \"tsgo --noEmit --skipLibCheck\",\n \"typecheck:tsc\": \"tsc --noEmit --skipLibCheck\"\n },\n \"dependencies\": {\n \"@tanstack/query-core\": \"^5.100.10\"\n },\n \"devDependencies\": {\n \"@jest/globals\": \"^30.4.1\",\n \"@types/node\": \"^26.2.0\",\n \"convert\": \"^7.0.0\",\n \"jest\": \"^30.4.2\",\n \"ts-jest\": \"^29.4.12\",\n \"tsup\": \"8.5.1\",\n \"typescript\": \"5.9.3\"\n },\n \"//sideEffects\": \"Load-bearing claim, not boilerplate. tsup's splitting emits bare chunk imports at the top of dist/index.js, and this field tells Rollup, webpack and Vite they may delete them, which esbuild reports as [ignored-bare-import] once per import during `npm run size`. The engine does have module-level work to lose: registerAllTokenTypes(), _PrecedenceParser.BP_TABLE and its cached token ids, and several process-wide registries. It is safe because every chunk doing that work is also imported for its bindings somewhere, so no bundler can drop it. That is a property of how tsup currently splits the code rather than a design guarantee, so `npm run smoke:bundled` (scripts/check-tree-shaking.mjs) proves it on every run of `npm run verify` instead of assuming it, and its header explains the two fixes if it ever stops holding.\",\n \"sideEffects\": false\n}\n","/**\n * The running engine's own semver version, sourced directly from this\n * package's package.json so it can never drift from what's actually\n * published. Exists so IEnginePackage.engineVersion range checks\n * (api/EngineVersionCompatibility.ts) have something real to check\n * against.\n */\nimport { version } from \"../../package.json\";\n\n/**\n * The running engine's version, taken from package.json.\n *\n * What a package's `engineVersion` range is checked against at registration.\n * A prerelease is compared by its coerced release version, so a 1.0.0 beta\n * satisfies `^1.0.0`. See `api/EngineVersionCompatibility.ts`.\n */\nexport const ENGINE_VERSION: string = version;\n","/**\n * Configuration Module for solve-js Engine\n * \n * This module provides the **single source of truth** for all engine configuration.\n * Every configurable aspect of the engine, from safety limits and performance\n * budgets to VM constraints and worker pool sizing, is defined here.\n * \n * ### Design principles\n * \n * 1. **Engine owns its config.** The engine defines its own config shape and defaults.\n * Consumers (e.g., the Obsidian plugin) pass partial overrides; all unspecified\n * fields fall back to `DEFAULT_CONFIG`.\n * \n * 2. **Self-documenting.** Every interface and field has descriptive JSDoc so the\n * config is understandable at a glance, whether you're using the engine as an\n * npm package or reading the source.\n * \n * 3. **Minimal consumer knowledge.** Consumers only need to pass `Partial<EngineConfig>`.\n * They don't need to replicate the full config shape, just the fields they\n * want to override.\n * \n * @module Configuration\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A host's test for whether a calendar date is a public holiday, given the\n * `Date` for that day at local midnight. Return `true` to exclude it from\n * working-day arithmetic.\n */\nexport type HolidayPredicate = (date: Date) => boolean;\n\n/**\n * The host-supplied public-holiday calendar, in the same \"bring your own data\"\n * shape the stocks and weather packages already use for a host callback (see\n * `packages/stocks/StocksPackage.ts`): weekends are decidable from the date\n * alone, holidays are not, so they come from the host or not at all.\n *\n * Either a {@link HolidayPredicate}, for a host that computes holidays itself\n * (an existing library, a region rule), or an iterable of specific dates as\n * `YYYY-MM-DD` strings, epoch-millisecond numbers or `Date` objects, for a host\n * that just has a list. Resolved to one internal predicate by\n * `vm/HolidayCalendar.ts`'s `resolveHolidayPredicate()`.\n *\n * Left unset, working-day arithmetic skips weekends only, which is the honest\n * default: the engine excludes exactly the days it can prove are non-working.\n */\nexport type HolidayCalendar = HolidayPredicate | Iterable<string | number | Date>;\n\n/**\n * Date-related configuration.\n * Controls the bounds and formatting for date/time expression evaluation\n * (e.g., `today + 20 days`, `last monday`).\n */\n/**\n * How an ambiguous all-numeric date literal is read.\n *\n * - `'auto'`: by separator, the historic behaviour. A slash date is\n * day-first (`25/12/2023`), a hyphen date is month-first (`12-25-2023`)\n * unless its first group is four digits, which makes it ISO (`2023-12-25`).\n * - `'DMY'` / `'MDY'` / `'YMD'`: a fixed order for every numeric separator, so\n * a host can match its readers' locale. `'MDY'` is what lets a US reader's\n * `12/25/2023` parse, which `'auto'` refuses because the slash defaults to\n * day-first.\n *\n * Only the all-numeric literals are affected. A spelled-out month (`March 9,\n * 2024`) is never ambiguous, and an ISO timestamp is always read as ISO.\n */\nexport type DateInputOrder = 'auto' | 'DMY' | 'MDY' | 'YMD';\n\n/** Date-related engine configuration: offset limits, input order, holidays. */\nexport interface DateConfig {\n /**\n * The order an ambiguous all-numeric date literal is read in. Defaults to\n * `'auto'` (by separator, the historic behaviour). See {@link DateInputOrder}.\n */\n readonly inputOrder: DateInputOrder;\n /**\n * How far forward a date offset whose COST grows with the offset may reach,\n * in years. Enforced by `vm/VM.ts`'s `addBusinessDays()`.\n *\n * Bounds the walk, not the calendar. Every other date offset in the engine\n * is arithmetic on a Date field, so `today + 100000 days` costs exactly what\n * one day costs and needs no ceiling; workdays are the one offset that has\n * to step day by day, because which days are skipped depends on where each\n * step lands. `today + 100000000 workdays` therefore froze the host for\n * thirteen seconds inside a single ADD opcode (where `vm.maxInstructions`\n * cannot see it) and then answered \"Invalid Date\", and a trillion never\n * returned at all.\n *\n * Release hardening: this field was declared, documented as a \"safety\n * limit\", and read nowhere, so it bounded nothing. A limit a host can\n * configure and the engine ignores is worse than no limit, because it reads\n * as protection that is not there.\n */\n readonly maxOffsetYears: number;\n /** How far BACK the same walk may reach, in years, as a negative number. See {@link maxOffsetYears}. */\n readonly minOffsetYears: number;\n /** Default date string format for display (moment.js format string) */\n readonly defaultFormat: string;\n /**\n * Public-holiday calendar for working-day arithmetic (`N working days after\n * <date>`, `working days between <date> and <date>`, `<date> + N workdays`).\n * See {@link HolidayCalendar}.\n *\n * Optional and unset by default: with no calendar, working-day arithmetic\n * skips weekends only. A host that wants holidays excluded too supplies one\n * here (`new ExpressionEngine({ config: { date: { holidays } } })`), the\n * same way stocks and weather take a host data source. Threaded into the VM\n * by `engine/ExpressionEngine.ts` exactly as {@link maxOffsetYears} is,\n * because working-day math is a VM operation several grammar forms share, so\n * the calendar has to be one source the VM owns rather than per-package state\n * the VM cannot see.\n */\n readonly holidays?: HolidayCalendar;\n}\n\n/**\n * Performance-related configuration.\n * Controls caching, timeouts, and processing limits to prevent runaway\n * resource consumption on large documents.\n */\nexport interface PerformanceConfig {\n /**\n * Maximum number of entries in {@link ExpressionEngine}'s bytecode cache\n * (per-instance, keyed by expression text) before the oldest entry is\n * evicted. Raise this for documents with many distinct expressions if\n * repeated re-evaluation (e.g. scrolling) is re-parsing instead of\n * hitting cache, bug fix (release hardening pass): this field used to\n * be read nowhere; the cache size was a hardcoded, unconfigurable\n * constant. Note this does NOT bound {@link LineCache}, which has no\n * size limit of its own.\n */\n readonly defaultCacheSize: number;\n /**\n * Maximum lines a document may have for the engine to process it in one\n * pass. Enforced by `ExpressionEngine.parseDocument()` and by\n * `engine/DocumentModel.ts`'s `setDocument()`, the two entry points that\n * take a whole document.\n *\n * A document costs memory per line whatever each line says: a parsed line\n * record, a cache entry, a dependency-graph node. Two hundred thousand\n * lines of `1 + 1` therefore exhausted the heap and aborted the process\n * before any per-line limit had anything to object to, which is the same\n * shape of hole as an unbounded expression and needs the same kind of\n * ceiling. Refusing the document names the limit; a host that genuinely has\n * a larger one raises this field.\n *\n * Release hardening: declared and read nowhere until now.\n */\n readonly maxDocumentLines: number;\n}\n\n/**\n * Validation / safety-limit configuration.\n * Protects against runaway expressions that could cause excessive memory use\n * or stack overflow. These limits are checked during lexing and parsing.\n */\n/** Bounds on untrusted input: expression length and nesting depth. */\nexport interface ValidationConfig {\n /** Maximum expression length in characters. Prevents excessively long strings from entering the pipeline. */\n readonly maxExpressionLength: number;\n /** Maximum expression complexity score (`tokens + functionCalls×5 + nestingDepth×10`). Protects against deeply nested or combinatorially complex expressions. */\n readonly maxComplexity: number;\n /** Maximum parentheses nesting depth. Prevents stack overflow in the recursive-descent parser. */\n readonly maxNestingDepth: number;\n /**\n * Auto-balance unmatched parentheses by appending missing closing parens\n * or prepending missing opening parens. When disabled, unbalanced expressions\n * cause parse errors instead of being silently corrected.\n *\n * Disabled by default for strict parsing. Enable for forgiving user input\n * (e.g., chat-style calculators where users often omit closing parens).\n * Has zero overhead when disabled, the O(n) paren-count scan is skipped.\n */\n readonly autoBalanceParens: boolean;\n}\n\n/**\n * Worker pool configuration.\n * Controls the parallel execution workers used for batch evaluation.\n */\nexport interface WorkerConfig {\n /** Maximum number of concurrent Web Workers allowed */\n readonly maxConcurrentWorkers: number;\n /** Time (ms) a worker stays alive while idle before being terminated */\n readonly idleTimeoutMs: number;\n /** Maximum retry attempts for a failed worker operation */\n readonly maxRetries: number;\n /** Base backoff delay (ms) between retries (exponential backoff applied on top) */\n readonly baseBackoffMs: number;\n} /**\n * Diagnostic / telemetry configuration.\n * Controls the diagnostic event pipeline for profiling and debugging.\n * All diagnostics are disabled by default for maximum production performance.\n */\n export interface DiagnosticConfig {\n /** Master switch: enable the diagnostic pipeline (collectors receive events for all pipeline stages) */\n readonly enabled: boolean;\n /** Enable VM trace mode, emits per-opcode execution events (very verbose; disables some optimizations) */\n readonly vmTraceEnabled: boolean;\n }\n\n /**\n * Proactive background refresh of live async values.\n *\n * Off by default. When a live value (a stock quote, an FX rate) has gone\n * stale, today it only refetches on the next re-evaluation (a keystroke), so a\n * note left open silently ages. With this enabled, the engine drives a refetch\n * on each such value's own cadence (the resolver's `refetchIntervalMs`) for the\n * values currently on screen, and pushes the fresh result to the host through\n * the same event stream the pull path uses. It needs timers and a live editor\n * consuming that stream, so a headless or batch host leaves it off.\n */\n export interface BackgroundRefreshConfig {\n /** Master switch. When false, no timers run and every value refreshes only on re-evaluation. */\n readonly enabled: boolean;\n }\n\n /**\n * Virtual Machine configuration.\n * Controls the internal bytecode VM that executes compiled expressions.\n */\n export interface VMConfig {\n /** Maximum stack depth (value slots) for VM execution, prevents stack overflow in recursive/pratt-parser generated bytecode */\n readonly maxStackDepth: number;\n /** Maximum opcodes executed per expression, halts runaway infinite loops */\n readonly maxInstructions: number;\n /**\n * Maximum elements a collection may be expanded to before `map`/`reduce`/\n * `sum`/`prod` will iterate it.\n *\n * A Range is stored as its two bounds and costs nothing until something\n * materializes it, at which point it becomes one Value per element. Twenty\n * characters (`sum(x, 1:100000000)`) therefore asked for a hundred million\n * of them, and neither `maxInstructions` nor `maxStackDepth` could see it:\n * the expansion happens inside a single opcode, so the instruction counter\n * is never consulted while it runs, and the elements never reach the value\n * stack. V8 aborted the whole process with \"Reached heap limit\", which a\n * host embedding the engine cannot catch.\n */\n readonly maxCollectionSize: number;\n /**\n * Maximum elements (collection Values, matrix cells) one evaluation may\n * materialize in total.\n *\n * `maxCollectionSize` above bounds a single collection. This bounds the sum\n * of everything an expression asks for, which is a different question and\n * the one that actually protects the host: two collections that are\n * individually legal are legal together, and an operation whose result is\n * the PRODUCT of two legal operands is bounded by neither of them. A matrix\n * multiply is exactly that shape, so three lines within every other limit\n * (`:a = map(1*x, 0:20000)`, `:b = transpose(a)`, `b * a`) asked for four\n * hundred million cells and aborted the process.\n *\n * Counted in elements rather than bytes, because a count is what a call\n * site has before it allocates. An element is 8 bytes as a numeric matrix\n * cell and closer to a hundred as a full Value, so the default is worth\n * roughly 16 MB of matrix or 200 MB of expanded collection: far past any\n * document and far short of what an editor cannot survive.\n */\n readonly maxAllocatedElements: number;\n /**\n * Maximum user-defined-function calls one evaluation may make in TOTAL,\n * however deeply or widely they nest.\n *\n * `maxFunctionRecursionDepth` bounds how DEEP calls nest and cannot see\n * how MANY there are, and those are different numbers. Twenty-two lines of\n * `f(n)(v) = f(n-1)(v) + f(n-1)(v)` reach a depth of only 22 against a\n * limit of 50, and make 2,097,152 calls doing it: a fatal heap abort in\n * under a second. `maxInstructions` cannot bound it either, because\n * `executeBytecode()` re-enters itself per call and each reentrant call\n * gets its OWN instruction count, so recursion refreshes its allowance on\n * the way in. This is the tally that does not refresh; see\n * `vm/AllocationBudget.ts`, which holds it for the same reason it holds\n * the element tally.\n *\n * Counted in calls rather than in the instructions they run, because the\n * call is the thing that multiplies: every call allocates a frame, its\n * arguments and its result whatever its body says.\n */\n readonly maxFunctionCalls: number;\n /**\n * Hard ceiling on how many bisection steps goal seek (`solve line N for\n * <var> = <target>`, see `packages/goalseek/`) may take before it gives up\n * with a structured error rather than continuing.\n *\n * Goal seek re-evaluates the target line's expression once per step while\n * narrowing an interval, and an untrusted document must never be able to\n * make that loop spin. `maxInstructions` bounds each individual\n * re-evaluation, but not how many of them the search performs, so this is\n * the tally that bounds the search itself, the same reason `maxFunctionCalls`\n * exists alongside `maxInstructions`. Bisection halves the interval every\n * step, so a hundred steps resolves an input to roughly one part in 2^100:\n * far past any precision a document needs, and a definite stop either way.\n */\n readonly maxGoalSeekIterations: number;\n }\n\n/**\n * Complete engine configuration.\n *\n * Every field has a default in `DEFAULT_CONFIG`. To customize, pass a\n * `Partial<EngineConfig>` when constructing `ExpressionEngine`. Only the\n * sections/fields you supply are overridden; all others use their defaults.\n *\n * @example\n * ```typescript\n * import { ExpressionEngine } from \"solve-js\";\n *\n * const engine = new ExpressionEngine({ config: {\n * validation: {\n * maxExpressionLength: 1000,\n * maxComplexity: 200,\n * },\n * // date, performance, vm, worker, diagnostic all use defaults\n * } });\n * ```\n */\nexport interface EngineConfig {\n /** Date/time expression evaluation bounds and formatting */\n readonly date: DateConfig;\n /** Performance budgets and cache sizing */\n readonly performance: PerformanceConfig;\n /** Safety limits for expression complexity */\n readonly validation: ValidationConfig;\n /** Internal bytecode VM configuration */\n readonly vm: VMConfig;\n /** Parallel worker pool configuration */\n readonly worker: WorkerConfig;\n /** Diagnostic pipeline configuration */\n readonly diagnostic: DiagnosticConfig;\n /** Proactive background refresh of live async values */\n readonly backgroundRefresh: BackgroundRefreshConfig;\n }\n\n/**\n * A partial {@link EngineConfig} override, one section at a time.\n *\n * Overrides are merged per section over {@link DEFAULT_CONFIG}, so you can set a\n * single field of one section (`{ validation: { maxExpressionLength: 1000 } }`)\n * and keep every other default in that section. A plain `Partial<EngineConfig>`\n * cannot express that, it demands a whole section object, which is why the\n * documented overrides never typechecked against it. This is the type the\n * constructor and {@link createEngine} accept.\n */\nexport type EngineConfigOverride = {\n readonly [K in keyof EngineConfig]?: Partial<EngineConfig[K]>;\n};\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: EngineConfig = {\n date: {\n // A century of workdays is about 26,000 steps, which is microseconds,\n // and past any offset a person means. The walk is what these bound; see\n // DateConfig above for why no other date offset needs a ceiling.\n maxOffsetYears: 100,\n minOffsetYears: -100,\n defaultFormat: 'YYYY-MM-DD',\n inputOrder: 'auto',\n },\n performance: {\n // Preserves the effective cache size the hardcoded (now-removed)\n // BYTECODE_CACHE_MAX_ENTRIES constant had, so wiring this field up\n // doesn't silently shrink the default cache for existing consumers.\n defaultCacheSize: 2000,\n // Raised from the 10,000 this field was declared with, which was never\n // enforced and turned out to be under what this engine already supports:\n // its paging design is tested against a 20,000-line document\n // (`engine/PageManager.ts` and its spec) and its throughput benchmark\n // parses a 50,000-line one. Twice the largest of those, and the same\n // number `ConfigManager.validate()` already refuses to go above.\n //\n // Measured under a 256MB heap: setting a 100,000-line document costs\n // 64MB, evaluating every line of a 20,000-line one costs 106MB, and\n // 200,000 lines aborts the process before a single expression is looked\n // at. A host with a small heap should lower this; the ceiling is here to\n // stop the size that cannot work anywhere.\n maxDocumentLines: 100000,\n },\n validation: {\n maxExpressionLength: 2000,\n maxComplexity: 500,\n maxNestingDepth: 50,\n autoBalanceParens: false,\n },\n vm: {\n maxStackDepth: 200,\n maxInstructions: 50000,\n // Two orders of magnitude above anything a person types by hand (the\n // longest range in the test suite is 1000 elements) and small enough\n // that expanding it is measured in milliseconds rather than in whether\n // the host survives.\n maxCollectionSize: 100000,\n // Twenty times the single-collection ceiling above, so an expression may\n // legitimately handle a number of large collections, and two hundred\n // times below the allocation that took the process down.\n maxAllocatedElements: 2000000,\n // Six hundred times the largest call count any test or example makes\n // (five levels of composition is sixteen calls), and small enough that\n // the calls it does allow cost single-digit megabytes rather than the\n // heap. A document that needs more than ten thousand calls on one line\n // is doing something a calculator was not built for.\n maxFunctionCalls: 10000,\n // A hundred bisection steps resolve an input to one part in 2^100, far\n // finer than any document needs and a firm stop for an untrusted one. A\n // continuous, monotonic relationship converges in tens of steps, well\n // under this; hitting it means the target is unreachable or the\n // relationship is not the smooth one goal seek assumes.\n maxGoalSeekIterations: 100,\n },\n worker: {\n maxConcurrentWorkers: 4,\n idleTimeoutMs: 30000,\n maxRetries: 3,\n baseBackoffMs: 1000,\n },\n diagnostic: {\n enabled: false,\n vmTraceEnabled: false,\n },\n backgroundRefresh: {\n enabled: false,\n },\n };\n\n/**\n * Merge a partial config override onto a base `EngineConfig`, section by\n * section, `{ ...base.section, ...override.section }` for each of the 7\n * top-level sections, not a single top-level spread.\n *\n * A shallow `{ ...base, ...override }` at the TOP level replaces an entire\n * section wholesale the moment a caller overrides even one field in it\n * (e.g. `{ performance: { defaultCacheSize: 500 } }` would silently drop\n * every other `performance.*` field back to `undefined`, not to its\n * default). This function exists specifically so every config consumer\n * shares one correct merge instead of each hand-rolling (and risking) its\n * own. `ConfigManager` and `ExpressionEngine` both call this rather than\n * either duplicating the section list or instantiating a whole\n * `ConfigManager` just to reuse its private merge logic.\n */\nexport function mergeEngineConfig(\n base: EngineConfig,\n override: EngineConfigOverride\n): EngineConfig {\n return {\n date: { ...base.date, ...override.date },\n performance: { ...base.performance, ...override.performance },\n validation: { ...base.validation, ...override.validation },\n vm: { ...base.vm, ...override.vm },\n worker: { ...base.worker, ...override.worker },\n diagnostic: { ...base.diagnostic, ...override.diagnostic },\n backgroundRefresh: { ...base.backgroundRefresh, ...override.backgroundRefresh },\n };\n}\n\n/**\n * Configuration manager for engine settings\n *\n * @example\n * ```typescript\n * const configManager = new ConfigManager();\n * configManager.set('performance.defaultCacheSize', 2000);\n * const cacheSize = configManager.get('performance.defaultCacheSize');\n * ```\n */\nexport class ConfigManager {\n private config: EngineConfig;\n\n constructor(config: Partial<EngineConfig> = {}) {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, config);\n }\n\n /**\n * Get configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @returns Configuration value\n */\n get<T>(path: string): T {\n const keys = path.split('.');\n let current: unknown = this.config;\n\n for (const key of keys) {\n if (current && typeof current === 'object' && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PATH_NOT_FOUND\",\n `Configuration path not found: ${path}`,\n { path }\n );\n }\n }\n\n return current as T;\n }\n\n /**\n * Set configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @param value - New value\n */\n set<T>(path: string, value: T): void {\n const keys = path.split('.');\n if (keys.length < 2) {\n throw ErrorFactory.config(\n \"INVALID_CONFIG_PATH\",\n `Invalid path: ${path}. Must be in format 'section.property'`,\n { path }\n );\n }\n \n const section = keys[0];\n const property = keys[1];\n \n if (!(section in this.config)) {\n throw ErrorFactory.config(\n \"CONFIG_SECTION_NOT_FOUND\",\n `Configuration section not found: ${section}`,\n { section, path }\n );\n }\n \n const sectionConfig = this.config[section as keyof EngineConfig];\n if (sectionConfig && typeof sectionConfig === 'object') {\n (sectionConfig as unknown as Record<string, unknown>)[property] = value;\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PROPERTY_NOT_FOUND\",\n `Configuration property not found: ${path}`,\n { path }\n );\n }\n }\n\n /**\n * Get complete configuration.\n *\n * A detached copy, section objects included. A top-level spread would hand\n * the caller this manager's own section objects, so `getConfig().vm.x = 1`\n * would be an undeclared back door into {@link set}, bypassing its path\n * validation and reaching every later {@link get}.\n */\n getConfig(): EngineConfig {\n return mergeEngineConfig(this.config, {});\n }\n\n /**\n * Update multiple configuration values\n */\n update(config: Partial<EngineConfig>): void {\n this.config = mergeEngineConfig(this.config, config);\n }\n\n /**\n * Reset to default configuration.\n *\n * Goes through {@link mergeEngineConfig} for the same reason the constructor\n * does. A top-level `{ ...DEFAULT_CONFIG }` copies the six section\n * references, not the sections, so after a reset this manager's\n * `performance` object WAS `DEFAULT_CONFIG.performance` and the next\n * `set('performance.x', ...)` wrote into the module constant. That constant\n * is what every `ExpressionEngine` is built from, so one manager's reset\n * could change the cache size, instruction ceiling or allocation budget of\n * every engine constructed later in the process.\n */\n reset(): void {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, {});\n }\n\n /**\n * Validate configuration values\n */\n validate(): ValidationResult {\n const errors: string[] = [];\n\n // Validate performance config\n if (this.config.performance.maxDocumentLines > 100000) {\n errors.push('maxDocumentLines cannot exceed 100,000');\n }\n\n // Validate date config\n if (this.config.date.maxOffsetYears > 1000) {\n errors.push('maxOffsetYears cannot exceed 1000');\n }\n\n return {\n valid: errors.length === 0,\n error: errors.join('; '),\n warnings: []\n };\n }\n}\n\n/**\n * Result type for {@link ConfigManager.validate}.\n */\nexport interface ValidationResult {\n valid: boolean;\n error?: string;\n warnings?: string[];\n}\n\n"]}
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkTLG7VZRX_cjs=require('./chunk-TLG7VZRX.cjs'),chunkNAZ6PGLS_cjs=require('./chunk-NAZ6PGLS.cjs');var T=new Set(["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLE","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VED","VES","VND","VUV","WST","XAF","XCD","XCG","XOF","XPF","YER","ZAR","ZMW","ZWG"]);function N(O){return T.has(O.toUpperCase())}var d={API_ERROR:"CURRENCY_API_ERROR",UNKNOWN_CODE:"UNKNOWN_CURRENCY_CODE",CRYPTO_API_ERROR:"CRYPTO_PRICE_API_ERROR"},o=class o{constructor(){this.baseTables=new Map;}isCryptoCode(t){return t.toUpperCase()in o.CRYPTO_IDS}async getRate(t,e,r){let n=t.toUpperCase(),s=e.toUpperCase();if(this.isCryptoCode(n)||this.isCryptoCode(s))return this.getCryptoRate(n,s,r);let{signal:C,cleanup:l}=chunkTLG7VZRX_cjs.a(r,o.FETCH_TIMEOUT_MS,"Currency API fetch");try{let a=await fetch(`https://api.frankfurter.dev/v2/rates?base=${n}`,{signal:C});if(!a.ok)throw chunkNAZ6PGLS_cjs.c.external(d.API_ERROR,`Currency API returned ${a.status}`,{status:a.status});let i=await a.json(),c=Array.isArray(i)?Object.fromEntries(i.filter(R=>{if(typeof R!="object"||R===null)return !1;let u=R;return typeof u.quote=="string"&&typeof u.rate=="number"}).map(R=>[R.quote.toUpperCase(),R.rate])):i.rates??{};if(c[s]===void 0)throw chunkNAZ6PGLS_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${s}`,{code:s});return this.baseTables.set(n,{fetchedAt:Date.now(),rates:{...c,[n]:1}}),c[s]}finally{l();}}async getCryptoRate(t,e,r){let{signal:n,cleanup:s}=chunkTLG7VZRX_cjs.a(r,o.FETCH_TIMEOUT_MS,"Crypto price API fetch");try{let C=this.isCryptoCode(t),l=this.isCryptoCode(e),a;if(C&&l){let i=o.CRYPTO_IDS[t],c=o.CRYPTO_IDS[e],R=await this.fetchCoinGeckoPrices([i,c],"usd",n),u=R[i]?.usd,P=R[c]?.usd;if(typeof u!="number")throw chunkNAZ6PGLS_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});if(typeof P!="number")throw chunkNAZ6PGLS_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});a=u/P;}else if(C){let i=o.CRYPTO_IDS[t],c=e.toLowerCase(),u=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof u!="number")throw chunkNAZ6PGLS_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});a=u;}else {let i=o.CRYPTO_IDS[e],c=t.toLowerCase(),u=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof u!="number")throw chunkNAZ6PGLS_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});a=1/u;}return this.baseTables.set(t,{fetchedAt:Date.now(),rates:{[t]:1,[e]:a}}),a}finally{s();}}async fetchCoinGeckoPrices(t,e,r){let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.join(",")}&vs_currencies=${e}`,s=await fetch(n,{signal:r});if(!s.ok)throw chunkNAZ6PGLS_cjs.c.external(d.CRYPTO_API_ERROR,`Crypto price API returned ${s.status}`,{status:s.status});return s.json()}primeRates(t,e){let r=t.toUpperCase();this.baseTables.set(r,{fetchedAt:Date.now(),rates:{...e,[r]:1}});}clearRates(){this.baseTables.clear();}getRateSync(t,e){let r=t.toUpperCase(),n=e.toUpperCase();if(r===n)return 1;let s=Date.now();for(let C of this.baseTables.values()){if(s-C.fetchedAt>o.RATE_FRESHNESS_MS)continue;let l=C.rates[r],a=C.rates[n];if(l&&a)return a/l}return null}async convert(t,e,r){let n=await this.getRate(e,r);return t*n}getAllRates(){let t=Date.now(),e={},r=false;for(let[n,s]of this.baseTables)if(!(t-s.fetchedAt>o.RATE_FRESHNESS_MS))for(let[C,l]of Object.entries(s.rates))e[`${n}:${C}`]=l,r=true;return r?e:null}hasRates(){return this.getAllRates()!==null}convertSync(t,e,r){let n=this.getRateSync(e,r);return n===null?null:t*n}isCurrency(t){return N(t)||this.isCryptoCode(t)}};o.RATE_FRESHNESS_MS=900*1e3,o.CRYPTO_IDS={BTC:"bitcoin",ETH:"ethereum",SOL:"solana",XRP:"ripple",ADA:"cardano",DOGE:"dogecoin",DOT:"polkadot"},o.FETCH_TIMEOUT_MS=1e4;var f=o,b=new f,h=b;
2
- exports.a=f;exports.b=b;exports.c=h;//# sourceMappingURL=chunk-GWCBPITD.cjs.map
3
- //# sourceMappingURL=chunk-GWCBPITD.cjs.map
1
+ 'use strict';var chunkTLG7VZRX_cjs=require('./chunk-TLG7VZRX.cjs'),chunkCO2BI6WL_cjs=require('./chunk-CO2BI6WL.cjs');var T=new Set(["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLE","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VED","VES","VND","VUV","WST","XAF","XCD","XCG","XOF","XPF","YER","ZAR","ZMW","ZWG"]);function N(O){return T.has(O.toUpperCase())}var d={API_ERROR:"CURRENCY_API_ERROR",UNKNOWN_CODE:"UNKNOWN_CURRENCY_CODE",CRYPTO_API_ERROR:"CRYPTO_PRICE_API_ERROR"},o=class o{constructor(){this.baseTables=new Map;}isCryptoCode(t){return t.toUpperCase()in o.CRYPTO_IDS}async getRate(t,e,r){let n=t.toUpperCase(),s=e.toUpperCase();if(this.isCryptoCode(n)||this.isCryptoCode(s))return this.getCryptoRate(n,s,r);let{signal:C,cleanup:l}=chunkTLG7VZRX_cjs.a(r,o.FETCH_TIMEOUT_MS,"Currency API fetch");try{let a=await fetch(`https://api.frankfurter.dev/v2/rates?base=${n}`,{signal:C});if(!a.ok)throw chunkCO2BI6WL_cjs.c.external(d.API_ERROR,`Currency API returned ${a.status}`,{status:a.status});let i=await a.json(),c=Array.isArray(i)?Object.fromEntries(i.filter(R=>{if(typeof R!="object"||R===null)return !1;let u=R;return typeof u.quote=="string"&&typeof u.rate=="number"}).map(R=>[R.quote.toUpperCase(),R.rate])):i.rates??{};if(c[s]===void 0)throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${s}`,{code:s});return this.baseTables.set(n,{fetchedAt:Date.now(),rates:{...c,[n]:1}}),c[s]}finally{l();}}async getCryptoRate(t,e,r){let{signal:n,cleanup:s}=chunkTLG7VZRX_cjs.a(r,o.FETCH_TIMEOUT_MS,"Crypto price API fetch");try{let C=this.isCryptoCode(t),l=this.isCryptoCode(e),a;if(C&&l){let i=o.CRYPTO_IDS[t],c=o.CRYPTO_IDS[e],R=await this.fetchCoinGeckoPrices([i,c],"usd",n),u=R[i]?.usd,P=R[c]?.usd;if(typeof u!="number")throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});if(typeof P!="number")throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});a=u/P;}else if(C){let i=o.CRYPTO_IDS[t],c=e.toLowerCase(),u=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof u!="number")throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});a=u;}else {let i=o.CRYPTO_IDS[e],c=t.toLowerCase(),u=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof u!="number")throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});a=1/u;}return this.baseTables.set(t,{fetchedAt:Date.now(),rates:{[t]:1,[e]:a}}),a}finally{s();}}async fetchCoinGeckoPrices(t,e,r){let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.join(",")}&vs_currencies=${e}`,s=await fetch(n,{signal:r});if(!s.ok)throw chunkCO2BI6WL_cjs.c.external(d.CRYPTO_API_ERROR,`Crypto price API returned ${s.status}`,{status:s.status});return s.json()}primeRates(t,e){let r=t.toUpperCase();this.baseTables.set(r,{fetchedAt:Date.now(),rates:{...e,[r]:1}});}clearRates(){this.baseTables.clear();}getRateSync(t,e){let r=t.toUpperCase(),n=e.toUpperCase();if(r===n)return 1;let s=Date.now();for(let C of this.baseTables.values()){if(s-C.fetchedAt>o.RATE_FRESHNESS_MS)continue;let l=C.rates[r],a=C.rates[n];if(l&&a)return a/l}return null}async convert(t,e,r){let n=await this.getRate(e,r);return t*n}getAllRates(){let t=Date.now(),e={},r=false;for(let[n,s]of this.baseTables)if(!(t-s.fetchedAt>o.RATE_FRESHNESS_MS))for(let[C,l]of Object.entries(s.rates))e[`${n}:${C}`]=l,r=true;return r?e:null}hasRates(){return this.getAllRates()!==null}convertSync(t,e,r){let n=this.getRateSync(e,r);return n===null?null:t*n}isCurrency(t){return N(t)||this.isCryptoCode(t)}};o.RATE_FRESHNESS_MS=900*1e3,o.CRYPTO_IDS={BTC:"bitcoin",ETH:"ethereum",SOL:"solana",XRP:"ripple",ADA:"cardano",DOGE:"dogecoin",DOT:"polkadot"},o.FETCH_TIMEOUT_MS=1e4;var f=o,b=new f,h=b;
2
+ exports.a=f;exports.b=b;exports.c=h;//# sourceMappingURL=chunk-6YM67DWH.cjs.map
3
+ //# sourceMappingURL=chunk-6YM67DWH.cjs.map