solve-engine 2.32.0 → 2.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/dist/{EngineError-CqGtaT_v.d.cts → EngineError-Bm4OYmw8.d.cts} +6 -0
  2. package/dist/{EngineError-CqGtaT_v.d.ts → EngineError-Bm4OYmw8.d.ts} +6 -0
  3. package/dist/{Lexer-CqFjYoRA.d.ts → Lexer-DPn5dfCH.d.ts} +1 -13
  4. package/dist/{Lexer-sCI05tqO.d.cts → Lexer-DaWkCu84.d.cts} +1 -13
  5. package/dist/{PackageCompatibility-phvSFP4f.d.ts → PackageCompatibility-CkzZfoJ3.d.ts} +1 -1
  6. package/dist/{PackageCompatibility-Bn-T_xKW.d.cts → PackageCompatibility-E_5GtcQW.d.cts} +1 -1
  7. package/dist/{PackageRegistry-C78jVkI9.d.ts → PackageRegistry-DSqic8kz.d.ts} +132 -23
  8. package/dist/{PackageRegistry-B-C1duZw.d.cts → PackageRegistry-js47hr28.d.cts} +132 -23
  9. package/dist/{Parselet-Dgymjxzd.d.ts → Parselet-CQjcHOKw.d.ts} +13 -6
  10. package/dist/{Parselet-DF3864la.d.cts → Parselet-s1sRRn8H.d.cts} +13 -6
  11. package/dist/{TokenNormalizer-Pe3_390t.d.cts → TokenNormalizer-D382VSYh.d.cts} +4 -1
  12. package/dist/{TokenNormalizer-IF7nPRMp.d.ts → TokenNormalizer-DAzPp-j1.d.ts} +4 -1
  13. package/dist/{VMBuiltins-BkKzhj6C.d.cts → VMBuiltins-JCavlQUj.d.cts} +53 -18
  14. package/dist/{VMBuiltins-Du9y8sEo.d.ts → VMBuiltins-qgzA6qGi.d.ts} +53 -18
  15. package/dist/{VMCheckpoints-WdUQrdc9.d.cts → VMCheckpoints-BxPzmdu0.d.cts} +2 -2
  16. package/dist/{VMCheckpoints-gvy_yxYh.d.ts → VMCheckpoints-DjjE92mf.d.ts} +2 -2
  17. package/dist/{Value-BYHw-x7q.d.cts → Value-2TIKi-YL.d.cts} +19 -0
  18. package/dist/{Value-BYHw-x7q.d.ts → Value-2TIKi-YL.d.ts} +19 -0
  19. package/dist/{WorkerError-DTrl3Jag.d.ts → WorkerError-BaN8_eok.d.ts} +1 -1
  20. package/dist/{WorkerError-CRoM8Ju1.d.cts → WorkerError-CexHHmbb.d.cts} +1 -1
  21. package/dist/{chunk-AGCNMEP2.cjs → chunk-3MG7VIPL.cjs} +2 -2
  22. package/dist/{chunk-AGCNMEP2.cjs.map → chunk-3MG7VIPL.cjs.map} +1 -1
  23. package/dist/chunk-4ASM522I.js +2 -0
  24. package/dist/chunk-4ASM522I.js.map +1 -0
  25. package/dist/chunk-4M3FZRGL.cjs +5 -0
  26. package/dist/chunk-4M3FZRGL.cjs.map +1 -0
  27. package/dist/{chunk-KH4QXKLT.js → chunk-4MD5L23F.js} +2 -2
  28. package/dist/{chunk-KH4QXKLT.js.map → chunk-4MD5L23F.js.map} +1 -1
  29. package/dist/{chunk-IQVSCL2R.js → chunk-4XWZXP6I.js} +3 -3
  30. package/dist/{chunk-IQVSCL2R.js.map → chunk-4XWZXP6I.js.map} +1 -1
  31. package/dist/{chunk-AXTYQFIV.cjs → chunk-6DCSGINN.cjs} +3 -3
  32. package/dist/{chunk-AXTYQFIV.cjs.map → chunk-6DCSGINN.cjs.map} +1 -1
  33. package/dist/{chunk-RELMEWY6.js → chunk-6G2NES2I.js} +2 -2
  34. package/dist/chunk-6G2NES2I.js.map +1 -0
  35. package/dist/{chunk-CDE2ZUGG.js → chunk-6NL7RBAG.js} +2 -2
  36. package/dist/{chunk-CDE2ZUGG.js.map → chunk-6NL7RBAG.js.map} +1 -1
  37. package/dist/{chunk-SUAGBRQ7.cjs → chunk-6SYU4MH7.cjs} +2 -2
  38. package/dist/chunk-6SYU4MH7.cjs.map +1 -0
  39. package/dist/chunk-72J5V7SN.cjs +2 -0
  40. package/dist/chunk-72J5V7SN.cjs.map +1 -0
  41. package/dist/chunk-7CRVRPV7.cjs +3 -0
  42. package/dist/chunk-7CRVRPV7.cjs.map +1 -0
  43. package/dist/chunk-ADK7LGYN.js +5 -0
  44. package/dist/chunk-ADK7LGYN.js.map +1 -0
  45. package/dist/chunk-APYRNAU2.js +2 -0
  46. package/dist/chunk-APYRNAU2.js.map +1 -0
  47. package/dist/{chunk-IJE4AEDX.js → chunk-D55NMAGM.js} +3 -3
  48. package/dist/{chunk-IJE4AEDX.js.map → chunk-D55NMAGM.js.map} +1 -1
  49. package/dist/chunk-DB5ISONG.js +2 -0
  50. package/dist/chunk-DB5ISONG.js.map +1 -0
  51. package/dist/chunk-EOKHRS2T.js +2 -0
  52. package/dist/chunk-EOKHRS2T.js.map +1 -0
  53. package/dist/{chunk-NQFCXLEF.js → chunk-EOO6M65F.js} +2 -2
  54. package/dist/{chunk-NQFCXLEF.js.map → chunk-EOO6M65F.js.map} +1 -1
  55. package/dist/{chunk-A764BY7L.cjs → chunk-EQNKDTMX.cjs} +2 -2
  56. package/dist/{chunk-A764BY7L.cjs.map → chunk-EQNKDTMX.cjs.map} +1 -1
  57. package/dist/chunk-FESR6PZI.cjs +2 -0
  58. package/dist/chunk-FESR6PZI.cjs.map +1 -0
  59. package/dist/chunk-G5TZ6TDA.js +2 -0
  60. package/dist/chunk-G5TZ6TDA.js.map +1 -0
  61. package/dist/chunk-GDLYXRMA.cjs +2 -0
  62. package/dist/chunk-GDLYXRMA.cjs.map +1 -0
  63. package/dist/chunk-HOU7QTE7.js +3 -0
  64. package/dist/chunk-HOU7QTE7.js.map +1 -0
  65. package/dist/{chunk-CAJTDZ5B.cjs → chunk-HPV4CKCC.cjs} +2 -2
  66. package/dist/{chunk-CAJTDZ5B.cjs.map → chunk-HPV4CKCC.cjs.map} +1 -1
  67. package/dist/{chunk-7DJYS5PO.cjs → chunk-HSTGWWU2.cjs} +2 -2
  68. package/dist/{chunk-7DJYS5PO.cjs.map → chunk-HSTGWWU2.cjs.map} +1 -1
  69. package/dist/{chunk-OE2DBN4K.js → chunk-INMJ7ZXL.js} +2 -2
  70. package/dist/chunk-INMJ7ZXL.js.map +1 -0
  71. package/dist/{chunk-TSJ4RQLZ.js → chunk-J3YC3IQD.js} +2 -2
  72. package/dist/{chunk-TSJ4RQLZ.js.map → chunk-J3YC3IQD.js.map} +1 -1
  73. package/dist/{chunk-5AKT36UK.cjs → chunk-K3PZ66XR.cjs} +2 -2
  74. package/dist/{chunk-5AKT36UK.cjs.map → chunk-K3PZ66XR.cjs.map} +1 -1
  75. package/dist/chunk-LI6LYJDA.cjs +2 -0
  76. package/dist/chunk-LI6LYJDA.cjs.map +1 -0
  77. package/dist/{chunk-WQGHJAW2.cjs → chunk-M4UC2PB6.cjs} +2 -2
  78. package/dist/{chunk-WQGHJAW2.cjs.map → chunk-M4UC2PB6.cjs.map} +1 -1
  79. package/dist/chunk-O7HF345B.js +2 -0
  80. package/dist/chunk-O7HF345B.js.map +1 -0
  81. package/dist/{chunk-CM2WM5CM.cjs → chunk-OBZJKZ2F.cjs} +2 -2
  82. package/dist/{chunk-CM2WM5CM.cjs.map → chunk-OBZJKZ2F.cjs.map} +1 -1
  83. package/dist/{chunk-Q7TBBV62.cjs → chunk-P5YWBIIU.cjs} +2 -2
  84. package/dist/chunk-P5YWBIIU.cjs.map +1 -0
  85. package/dist/chunk-PICFFFJV.js +3 -0
  86. package/dist/chunk-PICFFFJV.js.map +1 -0
  87. package/dist/{chunk-P43SV4NJ.cjs → chunk-QOOTRUY7.cjs} +3 -3
  88. package/dist/{chunk-P43SV4NJ.cjs.map → chunk-QOOTRUY7.cjs.map} +1 -1
  89. package/dist/chunk-R3W53ZMP.cjs +2 -0
  90. package/dist/chunk-R3W53ZMP.cjs.map +1 -0
  91. package/dist/chunk-RMDCGYZM.js +2 -0
  92. package/dist/chunk-RMDCGYZM.js.map +1 -0
  93. package/dist/{chunk-CB3EXUM2.js → chunk-RU3KGJRA.js} +2 -2
  94. package/dist/chunk-RU3KGJRA.js.map +1 -0
  95. package/dist/chunk-S3SPDK6N.cjs +2 -0
  96. package/dist/chunk-S3SPDK6N.cjs.map +1 -0
  97. package/dist/chunk-SF5QVUEI.cjs +3 -0
  98. package/dist/chunk-SF5QVUEI.cjs.map +1 -0
  99. package/dist/{chunk-FXB5GCBT.js → chunk-TJKN466F.js} +2 -2
  100. package/dist/{chunk-FXB5GCBT.js.map → chunk-TJKN466F.js.map} +1 -1
  101. package/dist/{chunk-VLX7ZVK4.js → chunk-U5MESNRT.js} +2 -2
  102. package/dist/{chunk-VLX7ZVK4.js.map → chunk-U5MESNRT.js.map} +1 -1
  103. package/dist/{chunk-YWF6C2IO.cjs → chunk-WFT3XUSH.cjs} +2 -2
  104. package/dist/{chunk-YWF6C2IO.cjs.map → chunk-WFT3XUSH.cjs.map} +1 -1
  105. package/dist/{chunk-3ZGFAE3Q.js → chunk-X2GQAKL2.js} +2 -2
  106. package/dist/{chunk-3ZGFAE3Q.js.map → chunk-X2GQAKL2.js.map} +1 -1
  107. package/dist/{chunk-G3POUURF.js → chunk-YID47OPR.js} +2 -2
  108. package/dist/{chunk-G3POUURF.js.map → chunk-YID47OPR.js.map} +1 -1
  109. package/dist/chunk-YV4GDW5A.cjs +2 -0
  110. package/dist/chunk-YV4GDW5A.cjs.map +1 -0
  111. package/dist/chunk-ZSXQP7PD.cjs +2 -0
  112. package/dist/chunk-ZSXQP7PD.cjs.map +1 -0
  113. package/dist/constants.cjs +1 -1
  114. package/dist/constants.js +1 -1
  115. package/dist/engine.cjs +1 -1
  116. package/dist/engine.d.cts +10 -10
  117. package/dist/engine.d.ts +10 -10
  118. package/dist/engine.js +1 -1
  119. package/dist/engine.worker.cjs +1 -1
  120. package/dist/engine.worker.cjs.map +1 -1
  121. package/dist/engine.worker.js +1 -1
  122. package/dist/engine.worker.js.map +1 -1
  123. package/dist/errors.cjs +1 -1
  124. package/dist/errors.d.cts +3 -3
  125. package/dist/errors.d.ts +3 -3
  126. package/dist/errors.js +1 -1
  127. package/dist/format.cjs +1 -1
  128. package/dist/format.d.cts +1 -1
  129. package/dist/format.d.ts +1 -1
  130. package/dist/format.js +1 -1
  131. package/dist/index.cjs +1 -1
  132. package/dist/index.cjs.map +1 -1
  133. package/dist/index.d.cts +10 -10
  134. package/dist/index.d.ts +10 -10
  135. package/dist/index.js +1 -1
  136. package/dist/index.js.map +1 -1
  137. package/dist/language.d.cts +9 -9
  138. package/dist/language.d.ts +9 -9
  139. package/dist/lexer.cjs +1 -1
  140. package/dist/lexer.d.cts +3 -3
  141. package/dist/lexer.d.ts +3 -3
  142. package/dist/lexer.js +1 -1
  143. package/dist/normalizer.cjs +1 -1
  144. package/dist/normalizer.d.cts +2 -2
  145. package/dist/normalizer.d.ts +2 -2
  146. package/dist/normalizer.js +1 -1
  147. package/dist/packages.cjs +1 -1
  148. package/dist/packages.d.cts +8 -8
  149. package/dist/packages.d.ts +8 -8
  150. package/dist/packages.js +1 -1
  151. package/dist/parser.cjs +1 -1
  152. package/dist/parser.d.cts +3 -3
  153. package/dist/parser.d.ts +3 -3
  154. package/dist/parser.js +1 -1
  155. package/dist/{pipeline-BYkKNpql.d.cts → pipeline-Bum6y1B9.d.cts} +1 -1
  156. package/dist/{pipeline-Cl7KW8CB.d.ts → pipeline-DOo3KHaq.d.ts} +1 -1
  157. package/dist/resolvers.cjs +1 -1
  158. package/dist/resolvers.d.cts +69 -3
  159. package/dist/resolvers.d.ts +69 -3
  160. package/dist/resolvers.js +1 -1
  161. package/dist/temporal.cjs +1 -1
  162. package/dist/temporal.js +1 -1
  163. package/dist/testing.cjs +2 -2
  164. package/dist/testing.cjs.map +1 -1
  165. package/dist/testing.d.cts +9 -9
  166. package/dist/testing.d.ts +9 -9
  167. package/dist/testing.js +1 -1
  168. package/dist/testing.js.map +1 -1
  169. package/dist/uom.cjs +1 -1
  170. package/dist/uom.d.cts +35 -2
  171. package/dist/uom.d.ts +35 -2
  172. package/dist/uom.js +1 -1
  173. package/dist/vm.cjs +1 -1
  174. package/dist/vm.d.cts +6 -6
  175. package/dist/vm.d.ts +6 -6
  176. package/dist/vm.js +1 -1
  177. package/dist/worker.cjs +2 -2
  178. package/dist/worker.cjs.map +1 -1
  179. package/dist/worker.d.cts +9 -9
  180. package/dist/worker.d.ts +9 -9
  181. package/dist/worker.js +1 -1
  182. package/dist/worker.js.map +1 -1
  183. package/package.json +1 -1
  184. package/dist/chunk-4DR5RBHQ.cjs +0 -2
  185. package/dist/chunk-4DR5RBHQ.cjs.map +0 -1
  186. package/dist/chunk-4IC5OARK.js +0 -3
  187. package/dist/chunk-4IC5OARK.js.map +0 -1
  188. package/dist/chunk-7ODHPWQC.js +0 -5
  189. package/dist/chunk-7ODHPWQC.js.map +0 -1
  190. package/dist/chunk-A755LVPT.cjs +0 -2
  191. package/dist/chunk-A755LVPT.cjs.map +0 -1
  192. package/dist/chunk-AF6NDOIE.js +0 -2
  193. package/dist/chunk-AF6NDOIE.js.map +0 -1
  194. package/dist/chunk-B2NL65FI.js +0 -2
  195. package/dist/chunk-B2NL65FI.js.map +0 -1
  196. package/dist/chunk-CB3EXUM2.js.map +0 -1
  197. package/dist/chunk-DUFEONVN.cjs +0 -3
  198. package/dist/chunk-DUFEONVN.cjs.map +0 -1
  199. package/dist/chunk-IJHL3LMH.js +0 -2
  200. package/dist/chunk-IJHL3LMH.js.map +0 -1
  201. package/dist/chunk-LCYQQFUH.cjs +0 -2
  202. package/dist/chunk-LCYQQFUH.cjs.map +0 -1
  203. package/dist/chunk-LP3JYC3A.js +0 -2
  204. package/dist/chunk-LP3JYC3A.js.map +0 -1
  205. package/dist/chunk-OE2DBN4K.js.map +0 -1
  206. package/dist/chunk-OKKGPINQ.cjs +0 -5
  207. package/dist/chunk-OKKGPINQ.cjs.map +0 -1
  208. package/dist/chunk-OM7NOHJF.cjs +0 -2
  209. package/dist/chunk-OM7NOHJF.cjs.map +0 -1
  210. package/dist/chunk-PTXUWGRR.js +0 -3
  211. package/dist/chunk-PTXUWGRR.js.map +0 -1
  212. package/dist/chunk-Q7TBBV62.cjs.map +0 -1
  213. package/dist/chunk-RELMEWY6.js.map +0 -1
  214. package/dist/chunk-SFM4XFGJ.js +0 -2
  215. package/dist/chunk-SFM4XFGJ.js.map +0 -1
  216. package/dist/chunk-SRAU3BLV.cjs +0 -3
  217. package/dist/chunk-SRAU3BLV.cjs.map +0 -1
  218. package/dist/chunk-SUAGBRQ7.cjs.map +0 -1
  219. package/dist/chunk-UNKZ5XRC.cjs +0 -2
  220. package/dist/chunk-UNKZ5XRC.cjs.map +0 -1
  221. package/dist/chunk-WU7SBKVU.cjs +0 -2
  222. package/dist/chunk-WU7SBKVU.cjs.map +0 -1
  223. package/dist/chunk-X5K72MBV.js +0 -2
  224. package/dist/chunk-X5K72MBV.js.map +0 -1
  225. package/dist/chunk-ZVPZQ66D.cjs +0 -2
  226. package/dist/chunk-ZVPZQ66D.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/worker/client.ts","../src/worker/serialize.ts","../src/worker/runtime.ts","../src/worker/transport.ts"],"names":["resolveDateOrderForWorker","config","date","resolveDateOrderPolicy","DEFAULT_CONFIG","WorkerEngineClient","transport","raw","options","id","resolve","reject","input","signal","parsing","parseOptions","lines","expression","listener","error","workerTerminatedError","entry","method","args","workerCancelledError","onAbort","message","value","deserializeEngineError","apply","createWorkerEngine","client","nonFiniteTag","n","serializeMatrix","m","cells","cell","formatSymbolic","serializeValue","settings","reading","dto","formatValue","r","c","toHexString","formatColour","pt","ip","serializeMaybe","serializeInlineSolve","solve","serializeParsedLine","line","serializeParsingResult","result","resolvePackages","available","names","byName","pkg","resolved","name","ErrorFactory","WorkerErrorCodes","startWorkerRuntime","BUILTIN_PACKAGES","engine","formatting","inFlight","retainedLines","documentController","stopEventPump","post","fail","serializeEngineError","normalizeUnknownError","retainLines","map","text","index","handleAsyncEvent","eng","event","lineNumber","startEventPump","reader","done","handleInit","packages","ExpressionEngine","DEFAULT_FORMATTING_SETTINGS","runMethod","handleRequest","controller","cloneMessage","createLinkedTransports","clientHandler","hostHandler","alive","deli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,KAAA,KACN,CACD,CACD","file":"worker.js","sourcesContent":["/**\n * The main-side half of the harness: an async proxy of the core evaluate\n * methods.\n *\n * {@link createWorkerEngine} performs the init handshake and resolves once the\n * worker's engine is built, so the returned {@link WorkerEngine} is ready to\n * call. Each call stamps a request id, tracks the pending promise, and settles\n * it when the matching answer arrives, so several requests can be outstanding at\n * once. An `AbortSignal` rejects the local promise and posts a `cancel` for the\n * same id, mapping keystroke-level cancellation onto the boundary rather than\n * re-inventing it.\n */\n\nimport { DEFAULT_CONFIG, type EngineConfigOverride } from \"@solve-js/constants/Configuration\";\nimport { resolveDateOrderPolicy } from \"@solve-js/packages/datetime/DateReading\";\nimport type { UnifiedParsingOptions } from \"@solve-js/types/ParsingResult\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport type { EngineError } from \"@solve-js/errors\";\nimport {\n\tdeserializeEngineError,\n\tworkerCancelledError,\n\tworkerTerminatedError,\n} from \"@solve-js/errors\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tWorkerMethod,\n\tWorkerRequestArgs,\n\tWorkerToMainMessage,\n} from \"./protocol\";\nimport type {\n\tSerializedWorkerValue,\n\tSerializedParsedLine,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/** Configuration for {@link createWorkerEngine}. */\nexport interface WorkerEngineOptions {\n\t/** The channel to the worker runtime. See `worker/transport.ts` for adapters. */\n\ttransport: WorkerTransport;\n\t/** Locale for keywords and number formatting; defaults to English worker-side. */\n\tlocaleCode?: string;\n\t/** Whether the worker builds its engine with diagnostics enabled. */\n\tdiagnostics?: boolean;\n\t/** Config overrides, merged per section over the defaults worker-side. */\n\tconfig?: EngineConfigOverride;\n\t/**\n\t * Names of built-in packages the worker should register. Omitted registers\n\t * them all. Names rather than the packages themselves, since a package\n\t * carries functions that cannot cross a `postMessage` boundary; a host with\n\t * a custom package bakes it into its own worker entry and selects it here by\n\t * name.\n\t */\n\tpackages?: string[];\n\t/** Formatting settings the worker uses when it renders a DTO's display text. */\n\tformatting?: FormattingSettings;\n}\n\n/** Per-call options common to every proxied method. */\nexport interface WorkerCallOptions {\n\t/** Abort the request. Rejects the returned promise and cancels the work worker-side. */\n\tsignal?: AbortSignal;\n}\n\n/**\n * One line whose result changed after a live value resolved worker-side, carried\n * as its freshly re-evaluated {@link SerializedWorkerValue}. The value the host renders\n * against `lineNumber`, recovered worker-side so the main thread needs no further\n * round-trip to display it.\n */\nexport interface WorkerAsyncUpdate {\n\tlineNumber: number;\n\tvalue: SerializedWorkerValue;\n}\n\n/**\n * A live-data resolution that failed worker-side. `error` is the same structured\n * {@link EngineError} an in-process resolver failure would surface, rebuilt from\n * its transported form, so a host branches on `code`/`category` as it always has.\n */\nexport interface WorkerAsyncError {\n\tqueryKey: string;\n\tpackageId: string;\n\terror: EngineError;\n}\n\n/**\n * An async proxy of {@link ExpressionEngine}'s core evaluate methods.\n *\n * Each method mirrors its synchronous counterpart but returns a Promise of the\n * serialisable DTO rather than a live `Value`, and accepts an `AbortSignal`.\n */\nexport interface WorkerEngine {\n\t/** Parse a whole document off-thread. Mirrors `ExpressionEngine.parseDocument`. */\n\tparseDocument(input: string, options?: UnifiedParsingOptions & WorkerCallOptions): Promise<SerializedParsingResult>;\n\t/** Evaluate an array of lines off-thread. Mirrors `ExpressionEngine.evaluateLines`. */\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]>;\n\t/** Evaluate a single expression off-thread. Mirrors `ExpressionEngine.evaluateExpression`. */\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedWorkerValue>;\n\t/**\n\t * Subscribe to live-data resolutions that land after a request already\n\t * answered.\n\t *\n\t * A currency, weather or historical-rate value resolves inside the worker some\n\t * time after `parseDocument` returned its pending result. When it does, the\n\t * affected lines are re-evaluated worker-side and their fresh values arrive\n\t * here as one batch. This is a subscription rather than a per-request promise\n\t * because a resolution is tied to no single request: it belongs to whichever\n\t * document is current when the value lands. Returns an unsubscribe function.\n\t */\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void;\n\t/**\n\t * Subscribe to live-data resolutions that failed. Returns an unsubscribe\n\t * function. See {@link onResolved}; this is its failure channel.\n\t */\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void;\n\t/** Reject every in-flight request and tear the transport down. Idempotent. */\n\tterminate(): void;\n}\n\n/** A promise awaiting one worker answer, plus the abort wiring to unhook when it settles. */\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: unknown) => void;\n\tsignal?: AbortSignal;\n\tonAbort?: () => void;\n}\n\n/**\n * Replaces `date.inputOrder: 'locale'` with the order this side resolves it\n * to, before the config crosses to the worker.\n *\n * `'locale'` means \"ask the reader's machine\", and the reader's machine is\n * this one. A worker re-inferring it would be asking a different environment\n * the same question: a worker thread can carry different `Intl` data (a\n * bundler-provided shim, a small-ICU runtime), so the same document could be\n * read day-first on the main thread and month-first in the worker with nothing\n * to show for it. The resolved order crosses instead, so both sides read the\n * document the same way, and `date.inputLocale` is dropped with it because it\n * has already done its work.\n *\n * Anything else passes through untouched, including an absent config.\n */\nfunction resolveDateOrderForWorker(config: EngineConfigOverride | undefined): EngineConfigOverride | undefined {\n\tif (config?.date?.inputOrder !== \"locale\") return config;\n\tconst date = { ...config.date, inputOrder: resolveDateOrderPolicy({ ...DEFAULT_CONFIG.date, ...config.date }).order };\n\tdelete date.inputLocale;\n\treturn { ...config, date };\n}\n\nclass WorkerEngineClient implements WorkerEngine {\n\tprivate readonly transport: WorkerTransport;\n\tprivate nextId = 1;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\t// Broadcast subscribers for async resolutions. Sets, not one callback each, so\n\t// several views can watch the same worker; a resolution is not tied to a\n\t// request id, so these live outside `pending`.\n\tprivate readonly resolvedListeners = new Set<(lines: WorkerAsyncUpdate[]) => void>();\n\tprivate readonly asyncErrorListeners = new Set<(error: WorkerAsyncError) => void>();\n\tprivate terminated = false;\n\n\tconstructor(transport: WorkerTransport) {\n\t\tthis.transport = transport;\n\t\tthis.transport.onMessage((raw) => this.onMessage(raw));\n\t}\n\n\t/** Perform the init handshake, resolving once the worker posts `ready`. */\n\tinit(options: WorkerEngineOptions): Promise<void> {\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve: () => resolve(), reject });\n\t\t\tthis.transport.postMessage({\n\t\t\t\tkind: \"init\",\n\t\t\t\tid,\n\t\t\t\tlocaleCode: options.localeCode,\n\t\t\t\tdiagnostics: options.diagnostics,\n\t\t\t\tconfig: resolveDateOrderForWorker(options.config),\n\t\t\t\tpackages: options.packages,\n\t\t\t\tformatting: options.formatting,\n\t\t\t});\n\t\t});\n\t}\n\n\tparseDocument(\n\t\tinput: string,\n\t\toptions?: UnifiedParsingOptions & WorkerCallOptions,\n\t): Promise<SerializedParsingResult> {\n\t\t// The signal stays main-side and drives a `cancel`; only the parsing\n\t\t// options cross, so an AbortSignal never reaches `postMessage`.\n\t\tconst { signal, ...parsing } = options ?? {};\n\t\tconst parseOptions = Object.keys(parsing).length > 0 ? (parsing as UnifiedParsingOptions) : undefined;\n\t\treturn this.call<SerializedParsingResult>(\"parseDocument\", [input, parseOptions], signal);\n\t}\n\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]> {\n\t\treturn this.call<SerializedParsedLine[]>(\"evaluateLines\", [lines], options?.signal);\n\t}\n\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedWorkerValue> {\n\t\treturn this.call<SerializedWorkerValue>(\"evaluateExpression\", [expression], options?.signal);\n\t}\n\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void {\n\t\tthis.resolvedListeners.add(listener);\n\t\treturn () => this.resolvedListeners.delete(listener);\n\t}\n\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void {\n\t\tthis.asyncErrorListeners.add(listener);\n\t\treturn () => this.asyncErrorListeners.delete(listener);\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) return;\n\t\tthis.terminated = true;\n\t\tconst error = workerTerminatedError();\n\t\tfor (const entry of this.pending.values()) {\n\t\t\tthis.unhook(entry);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t\t// No more resolutions can arrive across a torn-down transport, so drop the\n\t\t// subscribers rather than leaving them referenced for the client's lifetime.\n\t\tthis.resolvedListeners.clear();\n\t\tthis.asyncErrorListeners.clear();\n\t\tthis.transport.terminate();\n\t}\n\n\t/** Dispatch one request and return the promise that settles on its answer. */\n\tprivate call<T>(method: WorkerMethod, args: WorkerRequestArgs, signal?: AbortSignal): Promise<T> {\n\t\tif (this.terminated) return Promise.reject(workerTerminatedError());\n\t\tif (signal?.aborted) return Promise.reject(workerCancelledError(method));\n\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst entry: PendingRequest = { resolve: resolve as (value: unknown) => void, reject };\n\n\t\t\tif (signal) {\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\t// Nothing to do if the answer already arrived and settled this id.\n\t\t\t\t\tif (!this.pending.has(id)) return;\n\t\t\t\t\tthis.pending.delete(id);\n\t\t\t\t\tthis.transport.postMessage({ kind: \"cancel\", id });\n\t\t\t\t\treject(workerCancelledError(method));\n\t\t\t\t};\n\t\t\t\tentry.signal = signal;\n\t\t\t\tentry.onAbort = onAbort;\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\n\t\t\tthis.pending.set(id, entry);\n\t\t\tthis.transport.postMessage({ kind: \"request\", id, method, args });\n\t\t});\n\t}\n\n\t/** Route one incoming message to the request that is waiting on its id. */\n\tprivate onMessage(raw: unknown): void {\n\t\tconst message = raw as WorkerToMainMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"ready\":\n\t\t\tcase \"result\": {\n\t\t\t\tconst value = message.kind === \"result\" ? message.value : undefined;\n\t\t\t\tthis.settle(message.id, (entry) => entry.resolve(value));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"error\":\n\t\t\t\tthis.settle(message.id, (entry) => entry.reject(deserializeEngineError(message.error)));\n\t\t\t\tbreak;\n\t\t\tcase \"async-update\":\n\t\t\t\t// A broadcast, not an answer to a request: fan it out to every\n\t\t\t\t// subscriber. A copy of the listener set is iterated so a listener\n\t\t\t\t// that unsubscribes itself mid-callback cannot disturb the walk.\n\t\t\t\tfor (const listener of [...this.resolvedListeners]) listener(message.lines);\n\t\t\t\tbreak;\n\t\t\tcase \"async-error\":\n\t\t\t\tfor (const listener of [...this.asyncErrorListeners]) {\n\t\t\t\t\tlistener({\n\t\t\t\t\t\tqueryKey: message.queryKey,\n\t\t\t\t\t\tpackageId: message.packageId,\n\t\t\t\t\t\terror: deserializeEngineError(message.error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Remove a pending request by id and run the settle callback, if it is still pending. */\n\tprivate settle(id: number, apply: (entry: PendingRequest) => void): void {\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tthis.unhook(entry);\n\t\tapply(entry);\n\t}\n\n\t/** Detach an entry's abort listener so a settled request leaves nothing on the signal. */\n\tprivate unhook(entry: PendingRequest): void {\n\t\tif (entry.signal && entry.onAbort) entry.signal.removeEventListener(\"abort\", entry.onAbort);\n\t}\n}\n\n/**\n * Build a worker-backed engine and wait for it to be ready.\n *\n * ```ts\n * const { client, host } = createLinkedTransports();\n * startWorkerRuntime(host);\n * const engine = await createWorkerEngine({ transport: client });\n * const result = await engine.parseDocument(text);\n * ```\n *\n * In production `client` wraps a real `Worker` (see `eventTargetTransport` /\n * `messagePortTransport`), and `startWorkerRuntime` runs inside that worker.\n */\nexport async function createWorkerEngine(options: WorkerEngineOptions): Promise<WorkerEngine> {\n\tconst client = new WorkerEngineClient(options.transport);\n\tawait client.init(options);\n\treturn client;\n}\n","/**\n * Turn live engine results into the clone-safe DTOs the worker harness posts.\n *\n * These functions run on the worker side, just before a result crosses the\n * boundary, and are also what the main side re-runs on a synchronous result to\n * compare the two paths in tests. They are pure and deterministic given the\n * same {@link FormattingSettings}, so a value serialised on either side is\n * byte-for-byte the same DTO.\n */\n\nimport { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type ChartData, type IpCidrData } from \"@solve-js/vm/Value\";\nimport { formatValue } from \"@solve-js/format/FormatEngine\";\nimport { toHexString, formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport { formatSymbolic } from \"@solve-js/symbolic\";\nimport type { ParsedLine, InlineSolvePosition, ParsingResult } from \"@solve-js/types/ParsingResult\";\nimport type {\n\tSerializedWorkerValue,\n\tSerializedMatrix,\n\tSerializedParsedLine,\n\tSerializedInlineSolve,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/**\n * The JSON-safe string tag for a non-finite reading. `Infinity`/`-Infinity`/`NaN`\n * cannot cross `JSON` (which turns each into `null`), so this one string form is\n * what survives both `structuredClone` and `JSON`, and a host recovers the value\n * with `Number(tag)`. Shared by the scalar `nonFinite` field and matrix cells.\n */\nfunction nonFiniteTag(n: number): \"Infinity\" | \"-Infinity\" | \"NaN\" {\n\treturn n > 0 ? \"Infinity\" : n < 0 ? \"-Infinity\" : \"NaN\";\n}\n\n/** Project a matrix onto clone-safe cells: finite primitives pass through, symbolic cells and non-finite numbers become strings. */\nfunction serializeMatrix(m: MatrixData): SerializedMatrix {\n\tconst cells = m.data.map((cell: MatrixEntry): number | boolean | string => {\n\t\t// A `SymbolicNode` (the object-typed cell variant) flattens to its display\n\t\t// string. A non-finite number (a `[1/0, 2]` cell) cannot cross JSON any\n\t\t// more than a scalar reading can, so it takes the same string tag rather\n\t\t// than being passed through raw and turned into `null` by `JSON.stringify`\n\t\t// (which would diverge from the `structuredClone` path). A finite number\n\t\t// or a boolean is already clone-safe and passes through.\n\t\tif (typeof cell === \"object\" && cell !== null) return formatSymbolic(cell);\n\t\tif (typeof cell === \"number\" && !Number.isFinite(cell)) return nonFiniteTag(cell);\n\t\treturn cell;\n\t});\n\treturn { rows: m.rows, cols: m.cols, cells, hasSymbolic: m.hasSymbolic };\n}\n\n/**\n * Project a {@link Value} onto a {@link SerializedWorkerValue}.\n *\n * `text` and `number` are set for every value; the type-specific fields are\n * added only where the payload needs them, so the DTO stays minimal and a\n * deep-equal between the two evaluation paths does not trip on a property one\n * side left `undefined`.\n */\nexport function serializeValue(value: Value, settings?: FormattingSettings): SerializedWorkerValue {\n\tconst reading = value.toNumber();\n\tconst dto: SerializedWorkerValue = {\n\t\ttype: value.type,\n\t\ttext: formatValue(value, settings),\n\t\t// A non-finite reading (1/0, 0/0, an overflow) cannot cross JSON, which\n\t\t// turns it into null and breaks the round-trip the DTO guarantees. Keep\n\t\t// `number` finite and name the real value in `nonFinite` instead.\n\t\tnumber: Number.isFinite(reading) ? reading : 0,\n\t};\n\tif (!Number.isFinite(reading)) {\n\t\tdto.nonFinite = nonFiniteTag(reading);\n\t}\n\n\tif (value.unit !== undefined) dto.unit = value.unit;\n\tif (value.timedOut !== undefined) dto.timedOut = value.timedOut;\n\t// The two datetime sidecars cross as themselves: both are plain JSON\n\t// scalars, so the clone guarantee is untouched, and a worker result that\n\t// dropped them would answer a different question from the synchronous one.\n\tif (value.grain !== undefined) dto.grain = value.grain;\n\tif (value.zone !== undefined) dto.zone = value.zone;\n\n\tconst raw = value.value;\n\tif (typeof raw === \"bigint\") {\n\t\t// Covers BigInt values and a Hex value that carries a bigint magnitude:\n\t\t// a base-ten string is the one representation that neither loses\n\t\t// precision nor breaks JSON.\n\t\tdto.bigint = raw.toString();\n\t} else if (value.type === ValueType.Matrix) {\n\t\tdto.matrix = serializeMatrix(raw as MatrixData);\n\t} else if (value.type === ValueType.Range) {\n\t\tconst r = raw as RangeData;\n\t\tdto.range = { min: r.min, max: r.max };\n\t} else if (value.type === ValueType.Colour) {\n\t\tconst c = raw as ColourData;\n\t\tdto.colour = { hex: toHexString(c), r: c.r, g: c.g, b: c.b, a: c.a, format: c.format, css: formatColour(c) };\n\t} else if (value.type === ValueType.Chart) {\n\t\tconst c = raw as ChartData;\n\t\tdto.chart = {\n\t\t\tkind: c.kind,\n\t\t\tpoints: c.points.map((pt) => [pt[0], pt[1]]),\n\t\t\tlabel: c.label,\n\t\t\tdomain: [c.domain[0], c.domain[1]],\n\t\t\trange: [c.range[0], c.range[1]],\n\t\t\t...(c.expr !== undefined ? { expr: c.expr } : {}),\n\t\t};\n\t} else if (value.type === ValueType.IpCidr) {\n\t\tconst ip = raw as IpCidrData;\n\t\tdto.ipCidr = {\n\t\t\t...(ip.addr !== undefined ? { addr: ip.addr } : {}),\n\t\t\t...(ip.prefix !== undefined ? { prefix: ip.prefix } : {}),\n\t\t\ttext: formatValue(value).replace(/^=\\s*/, \"\"),\n\t\t};\n\t}\n\n\treturn dto;\n}\n\n/** Serialise a nullable value, the shape both `result` fields carry. */\nfunction serializeMaybe(value: Value | null | undefined, settings?: FormattingSettings): SerializedWorkerValue | null {\n\treturn value ? serializeValue(value, settings) : null;\n}\n\n/** Project an inline solve onto its DTO, serialising its result. */\nfunction serializeInlineSolve(solve: InlineSolvePosition, settings?: FormattingSettings): SerializedInlineSolve {\n\treturn {\n\t\tstart: solve.start,\n\t\tend: solve.end,\n\t\texpression: solve.expression,\n\t\tlineNumber: solve.lineNumber,\n\t\tcolumnNumber: solve.columnNumber,\n\t\tresult: serializeMaybe(solve.result, settings),\n\t\terror: solve.error ?? null,\n\t};\n}\n\n/** Project a parsed line onto its DTO, serialising its result and every inline solve. */\nexport function serializeParsedLine(line: ParsedLine, settings?: FormattingSettings): SerializedParsedLine {\n\treturn {\n\t\tlineNumber: line.lineNumber,\n\t\ttext: line.text,\n\t\tstartPosition: line.startPosition,\n\t\tendPosition: line.endPosition,\n\t\tisEmpty: line.isEmpty,\n\t\thasInlineSolves: line.hasInlineSolves,\n\t\tinlineSolves: line.inlineSolves.map((solve) => serializeInlineSolve(solve, settings)),\n\t\texpression: line.expression,\n\t\tresult: serializeMaybe(line.result, settings),\n\t\terror: line.error,\n\t};\n}\n\n/** Project a whole parsing result onto its DTO. */\nexport function serializeParsingResult(result: ParsingResult, settings?: FormattingSettings): SerializedParsingResult {\n\tconst dto: SerializedParsingResult = {\n\t\tlines: result.lines.map((line) => serializeParsedLine(line, settings)),\n\t\ttotalLines: result.totalLines,\n\t\terrors: [...result.errors],\n\t};\n\t// The diagnostics report is already the engine's own JSON form, so it\n\t// crosses unchanged; present only when the host asked for it.\n\tif (result.diagnostics !== undefined) dto.diagnostics = result.diagnostics;\n\treturn dto;\n}\n","/**\n * The worker-side half of the harness: it owns an {@link ExpressionEngine} and\n * answers the protocol.\n *\n * {@link startWorkerRuntime} is transport-agnostic, so the same function runs\n * behind a browser `Worker`, a Node `worker_threads` port, or an in-process\n * link. A host's worker entry file is two lines: adapt the environment onto a\n * {@link WorkerTransport} and call this.\n *\n * The runtime never posts a raw {@link Value}. Every result is projected onto a\n * DTO first (`worker/serialize.ts`), and every failure is caught and flattened\n * into a structured error, so a worker-side throw reaches the caller as an\n * `EngineError` rather than a lost promise.\n */\n\nimport { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport type { AsyncResolutionEvent } from \"@solve-js/engine/AsyncResolutionBatcher\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport { DEFAULT_FORMATTING_SETTINGS, type FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport type { CalendarBackend } from \"@solve-js/calendar/CalendarBackend\";\nimport {\n\tErrorFactory,\n\tnormalizeUnknownError,\n\tserializeEngineError,\n\tWorkerErrorCodes,\n} from \"@solve-js/errors\";\nimport { serializeParsingResult, serializeParsedLine, serializeValue } from \"./serialize\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tMainToWorkerMessage,\n\tInitMessage,\n\tRequestMessage,\n\tWorkerToMainMessage,\n\tAsyncResolvedLine,\n} from \"./protocol\";\n\n/** Options a host bakes into its own worker entry: its custom packages, and its calendar backend. */\nexport interface WorkerRuntimeOptions {\n\t/**\n\t * The packages available to register, defaulting to {@link BUILTIN_PACKAGES}.\n\t * A host with its own package authors a worker entry that passes them here,\n\t * then selects among them by name from the main side. This is how a\n\t * function-carrying package reaches the worker: baked into its bundle, never\n\t * posted across the boundary.\n\t */\n\tpackages?: IEnginePackage[];\n\t/**\n\t * The calendar backend the worker's engine computes dates with, and writes\n\t * them out with, as the engine's own `calendar` option. Defaults to the\n\t * built-in `Date` backend. Baked in here for the same reason a package is:\n\t * a backend is an object of functions and cannot be posted across the\n\t * boundary, so the main side's formatting settings never carry one.\n\t */\n\tcalendar?: CalendarBackend;\n}\n\n/**\n * Resolve the requested package names against the available set.\n *\n * Undefined names means \"all of them\". A name with no match is a configuration\n * failure the caller must see, not a silent omission that would leave a feature\n * quietly missing from every result.\n */\nfunction resolvePackages(available: IEnginePackage[], names: string[] | undefined): IEnginePackage[] {\n\tif (names === undefined) return available;\n\tconst byName = new Map(available.map((pkg) => [pkg.name, pkg]));\n\tconst resolved: IEnginePackage[] = [];\n\tfor (const name of names) {\n\t\tconst pkg = byName.get(name);\n\t\tif (!pkg) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_PACKAGE,\n\t\t\t\t`No package named \"${name}\" is available in this worker runtime`,\n\t\t\t\t{ name, available: [...byName.keys()] },\n\t\t\t);\n\t\t}\n\t\tresolved.push(pkg);\n\t}\n\treturn resolved;\n}\n\n/**\n * Attach the runtime to a transport and start serving.\n *\n * Returns a teardown function that clears the engine and detaches, for a host\n * that reuses a transport or shuts a worker down cleanly.\n */\nexport function startWorkerRuntime(transport: WorkerTransport, options: WorkerRuntimeOptions = {}): () => void {\n\tconst available = options.packages ?? BUILTIN_PACKAGES;\n\n\tlet engine: ExpressionEngine | null = null;\n\tlet formatting: FormattingSettings | undefined;\n\t// One AbortController per in-flight request, so a `cancel` can map onto the\n\t// engine's keystroke signal for exactly the request the caller aborted.\n\tconst inFlight = new Map<number, AbortController>();\n\n\t// The line texts of the current document, keyed by the line number the engine\n\t// evaluates them under (1-based for a document, -1 for a lone expression). An\n\t// async resolution names the lines whose result changed but not the new value,\n\t// so this is what the event pump re-reads a line from to recover it.\n\tlet retainedLines = new Map<number, string>();\n\n\t// The current document's abort controller, kept alive past the request that\n\t// created it so this document's async resolutions can still land. Aborted when\n\t// a new document supersedes it: aborting drops the old document's in-flight\n\t// resolutions at the engine's own staleness guard (an aborted signal is\n\t// discarded before it reaches the batcher), so a stale value never reaches the\n\t// host as if it were current. See {@link handleRequest}.\n\tlet documentController: AbortController | null = null;\n\n\t// Cancels the event-stream reader on teardown. Null until the pump starts.\n\tlet stopEventPump: (() => void) | null = null;\n\n\tconst post = (message: WorkerToMainMessage): void => transport.postMessage(message);\n\n\tconst fail = (id: number, error: unknown): void => {\n\t\tpost({ kind: \"error\", id, error: serializeEngineError(normalizeUnknownError(error)) });\n\t};\n\n\t/**\n\t * Record the line texts a request evaluates, so a later async resolution can\n\t * re-read exactly the lines it names. A whole document splits into 1-based\n\t * lines; a lone `evaluateExpression` maps onto the engine's `-1` sentinel, the\n\t * same line number the engine registers and later reports for it.\n\t */\n\tconst retainLines = (message: RequestMessage): Map<number, string> => {\n\t\tconst map = new Map<number, string>();\n\t\tif (message.method === \"parseDocument\") {\n\t\t\t(message.args[0] as string).split(\"\\n\").forEach((text, index) => map.set(index + 1, text));\n\t\t} else if (message.method === \"evaluateLines\") {\n\t\t\t(message.args[0] as string[]).forEach((text, index) => map.set(index + 1, text));\n\t\t} else {\n\t\t\tmap.set(-1, message.args[0] as string);\n\t\t}\n\t\treturn map;\n\t};\n\n\t/**\n\t * Turn one async resolution event into a message home.\n\t *\n\t * A `lines-updated` event names the lines whose result changed; the resolved\n\t * value lives in the engine's cache, so each named line is re-evaluated (which\n\t * now reads the settled value from that cache rather than starting a fresh\n\t * fetch) and serialised. A line the current document no longer retains belongs\n\t * to a superseded document and is skipped. An `error` event carries the failed\n\t * query straight across as a structured error.\n\t */\n\tconst handleAsyncEvent = (eng: ExpressionEngine, event: AsyncResolutionEvent): void => {\n\t\tif (event.type === \"error\") {\n\t\t\tpost({\n\t\t\t\tkind: \"async-error\",\n\t\t\t\tqueryKey: event.queryKey,\n\t\t\t\tpackageId: event.packageId,\n\t\t\t\terror: serializeEngineError(normalizeUnknownError(event.error)),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst lines: AsyncResolvedLine[] = [];\n\t\tfor (const lineNumber of event.lineNumbers) {\n\t\t\tconst text = retainedLines.get(lineNumber);\n\t\t\tif (text === undefined) continue;\n\t\t\ttry {\n\t\t\t\tconst value = eng.evaluateLine(lineNumber, text);\n\t\t\t\tif (value) lines.push({ lineNumber, value: serializeValue(value, formatting) });\n\t\t\t} catch {\n\t\t\t\t// A line that resolved into an error re-throws on re-evaluation; the\n\t\t\t\t// batcher's own `error` event is the channel for that, so this keeps\n\t\t\t\t// the update to the lines that produced a value rather than posting a\n\t\t\t\t// second, half-formed failure here.\n\t\t\t}\n\t\t}\n\t\tif (lines.length > 0) post({ kind: \"async-update\", lines });\n\t};\n\n\t/**\n\t * Drain the engine's async-resolution event stream for the life of the\n\t * runtime, posting each event home. Started once the engine exists; the reader\n\t * loop ends when the stream closes (engine cleared) or the returned canceller\n\t * runs at teardown.\n\t */\n\tconst startEventPump = (eng: ExpressionEngine): void => {\n\t\tstopEventPump?.();\n\t\tconst reader = eng.getEventStream().getReader();\n\t\tstopEventPump = () => void reader.cancel();\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) return;\n\t\t\t\t\thandleAsyncEvent(eng, value);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// The stream errored or was cancelled (teardown); the loop is done.\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst handleInit = (message: InitMessage): void => {\n\t\ttry {\n\t\t\tconst packages = resolvePackages(available, message.packages);\n\t\t\tengine = new ExpressionEngine({\n\t\t\t\tlocale: message.localeCode ?? \"en\",\n\t\t\t\tdiagnostics: message.diagnostics ?? false,\n\t\t\t\tconfig: message.config,\n\t\t\t\tpackages,\n\t\t\t\tcalendar: options.calendar,\n\t\t\t});\n\t\t\t// The display reads the same backend the engine computes with, so a\n\t\t\t// date in a DTO names the day it was computed on; the main side's\n\t\t\t// settings cannot carry the backend, so it is joined here.\n\t\t\tformatting = options.calendar\n\t\t\t\t? { ...(message.formatting ?? DEFAULT_FORMATTING_SETTINGS), calendar: options.calendar }\n\t\t\t\t: message.formatting;\n\t\t\t// Drain live-data resolutions for the engine's whole lifetime, so a\n\t\t\t// value that settles after a request already answered still reaches the\n\t\t\t// host. Started here, after the engine exists, and torn down with it.\n\t\t\tstartEventPump(engine);\n\t\t\tpost({ kind: \"ready\", id: message.id });\n\t\t} catch (error) {\n\t\t\t// A build failure leaves no engine; the caller's `createWorkerEngine`\n\t\t\t// promise rejects with this rather than hanging on a `ready` that\n\t\t\t// never comes.\n\t\t\tfail(message.id, error);\n\t\t}\n\t};\n\n\tconst runMethod = (eng: ExpressionEngine, message: RequestMessage): unknown => {\n\t\tconst { method, args } = message;\n\t\tswitch (method) {\n\t\t\tcase \"parseDocument\":\n\t\t\t\treturn serializeParsingResult(eng.parseDocument(args[0] as string, args[1] as never), formatting);\n\t\t\tcase \"evaluateLines\":\n\t\t\t\treturn eng.evaluateLines(args[0] as string[]).map((line) => serializeParsedLine(line, formatting));\n\t\t\tcase \"evaluateExpression\":\n\t\t\t\t// Mirrors ExpressionEngine.evaluateExpression: a single Value in,\n\t\t\t\t// a single serialized Value out.\n\t\t\t\treturn serializeValue(eng.evaluateExpression(args[0] as string), formatting);\n\t\t\tdefault:\n\t\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_METHOD,\n\t\t\t\t\t`The worker runtime has no method named \"${String(method)}\"`,\n\t\t\t\t\t{ method },\n\t\t\t\t);\n\t\t}\n\t};\n\n\tconst handleRequest = (message: RequestMessage): void => {\n\t\tconst eng = engine;\n\t\tif (!eng) {\n\t\t\tfail(\n\t\t\t\tmessage.id,\n\t\t\t\tErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_NOT_INITIALISED,\n\t\t\t\t\t\"The worker received a request before its engine finished initialising\",\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Supersede the previous document: abort its controller so any resolution\n\t\t// still in flight for it is dropped at the engine's staleness guard rather\n\t\t// than posted home as if it belonged to this request's document. The old\n\t\t// retained lines go with it. Every evaluate call shares one engine and one\n\t\t// document context, so the most recent call is the live one.\n\t\tdocumentController?.abort();\n\n\t\t// This request's controller doubles as the document controller: wired in as\n\t\t// the keystroke signal so a later `cancel` (or the next supersede) aborts\n\t\t// the async work this evaluation fires, the same mechanism a host uses on\n\t\t// the main thread. It is deliberately NOT aborted when the request settles,\n\t\t// so this document's live values can still resolve and stream back.\n\t\tconst controller = new AbortController();\n\t\tdocumentController = controller;\n\t\tretainedLines = retainLines(message);\n\t\tinFlight.set(message.id, controller);\n\t\teng.setKeystrokeSignal(controller.signal);\n\n\t\ttry {\n\t\t\tconst value = runMethod(eng, message);\n\t\t\tpost({ kind: \"result\", id: message.id, value });\n\t\t} catch (error) {\n\t\t\tfail(message.id, error);\n\t\t} finally {\n\t\t\tinFlight.delete(message.id);\n\t\t\teng.setKeystrokeSignal(null);\n\t\t}\n\t};\n\n\ttransport.onMessage((raw) => {\n\t\tconst message = raw as MainToWorkerMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"init\":\n\t\t\t\thandleInit(message);\n\t\t\t\tbreak;\n\t\t\tcase \"request\":\n\t\t\t\thandleRequest(message);\n\t\t\t\tbreak;\n\t\t\tcase \"cancel\":\n\t\t\t\t// Abort maps onto the keystroke signal for the named request; a\n\t\t\t\t// cancel that arrives after the request already settled finds no\n\t\t\t\t// controller and is a harmless no-op.\n\t\t\t\tinFlight.get(message.id)?.abort();\n\t\t\t\tbreak;\n\t\t}\n\t});\n\n\treturn () => {\n\t\tstopEventPump?.();\n\t\tstopEventPump = null;\n\t\tdocumentController?.abort();\n\t\tdocumentController = null;\n\t\tretainedLines = new Map();\n\t\tfor (const controller of inFlight.values()) controller.abort();\n\t\tinFlight.clear();\n\t\tengine?.clear();\n\t\tengine = null;\n\t\ttransport.terminate();\n\t};\n}\n","/**\n * The seam between the harness and whatever actually carries messages.\n *\n * Both the client (`worker/client.ts`) and the runtime (`worker/runtime.ts`)\n * talk to a {@link WorkerTransport} and nothing more, so the same code drives a\n * browser `Worker`, a Node `worker_threads` port, or an in-process pair. The\n * three factory functions below adapt each of those onto the interface; a host\n * with a transport this file does not cover can implement the three methods\n * directly.\n */\n\n/**\n * A bidirectional message channel with a single receive handler.\n *\n * `onMessage` registers the one handler the harness needs; calling it again\n * replaces the previous handler. `terminate` tears the channel down and is safe\n * to call more than once.\n */\nexport interface WorkerTransport {\n\t/** Send one message to the other end. The message must be clone-safe. */\n\tpostMessage(message: unknown): void;\n\t/** Register the handler that receives messages from the other end. */\n\tonMessage(handler: (message: unknown) => void): void;\n\t/** Tear the channel down. Idempotent. */\n\tterminate(): void;\n}\n\n/**\n * Clone a message the way `postMessage` would, so an in-process transport has\n * the same value semantics as a real one.\n *\n * The harness protocol is clone-safe by construction, so the `JSON` fallback\n * (for a runtime without a global `structuredClone`) is lossless here; the\n * structured-clone path is preferred because it is what a real worker uses and\n * because it throws loudly if a non-clone-safe value ever reaches it, which is\n * exactly the mistake the DTO layer exists to prevent.\n *\n * A function, not a module-level const, so this module does no work at load\n * time and stays deletable under the package's `sideEffects: false` claim; the\n * `typeof` probe runs once per message, which is free next to the clone itself.\n */\nfunction cloneMessage<T>(value: T): T {\n\treturn typeof globalThis.structuredClone === \"function\"\n\t\t? globalThis.structuredClone(value)\n\t\t: JSON.parse(JSON.stringify(value));\n}\n\n/**\n * A pair of linked in-process transports.\n *\n * `client` and `host` are two ends of one channel: a message posted on either\n * is cloned at post time and delivered to the other on a microtask, so delivery\n * is asynchronous (as a real worker's is) but deterministic (no timers, no I/O).\n * Wire `client` into {@link createWorkerEngine} and `host` into\n * {@link startWorkerRuntime} to run the whole protocol, DTO serialisation and\n * cancellation included, without a second thread. This is the transport tests\n * use, and a fit for a host that wants the message-passing shape on one thread.\n */\nexport function createLinkedTransports(): { client: WorkerTransport; host: WorkerTransport } {\n\tlet clientHandler: ((message: unknown) => void) | null = null;\n\tlet hostHandler: ((message: unknown) => void) | null = null;\n\tlet alive = true;\n\n\t// The handler is read at delivery time rather than post time so setup order\n\t// (post before the other end has registered) cannot drop a message.\n\tconst deliver = (target: () => ((message: unknown) => void) | null, message: unknown): void => {\n\t\tconst cloned = cloneMessage(message);\n\t\tqueueMicrotask(() => {\n\t\t\tif (!alive) return;\n\t\t\ttarget()?.(cloned);\n\t\t});\n\t};\n\n\tconst client: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => hostHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\tclientHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\tconst host: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => clientHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\thostHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\treturn { client, host };\n}\n\n/** The `postMessage`/`onmessage`/event-listener shape a browser `Worker`, a worker's `self`, or a DOM `MessagePort` presents. */\ninterface EventTargetLike {\n\tpostMessage(message: unknown): void;\n\taddEventListener?(type: \"message\", handler: (event: { data: unknown }) => void): void;\n\tonmessage?: ((event: { data: unknown }) => void) | null;\n\tterminate?(): void;\n\tclose?(): void;\n\tstart?(): void;\n}\n\n/**\n * Adapt a browser-style message target onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker global `self`, and a DOM\n * `MessagePort`: each posts with `postMessage` and receives a `MessageEvent`\n * whose `data` is the payload. A `MessagePort` is `start`ed here so it begins\n * dispatching. On the main side pass a `Worker`; inside a browser worker pass\n * `self`.\n */\nexport function eventTargetTransport(target: EventTargetLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => target.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tconst listener = (event: { data: unknown }): void => handler(event.data);\n\t\t\tif (typeof target.addEventListener === \"function\") {\n\t\t\t\ttarget.addEventListener(\"message\", listener);\n\t\t\t} else {\n\t\t\t\ttarget.onmessage = listener;\n\t\t\t}\n\t\t\ttarget.start?.();\n\t\t},\n\t\t// A main-side Worker terminates; a worker's own `self` closes. Calling\n\t\t// whichever exists keeps one adapter usable from both ends.\n\t\tterminate: () => {\n\t\t\ttarget.terminate?.();\n\t\t\ttarget.close?.();\n\t\t},\n\t};\n}\n\n/** The `postMessage`/`on(\"message\")` shape a Node `worker_threads` `Worker`, `parentPort`, or `MessagePort` presents. */\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n\ton(event: \"message\", handler: (message: unknown) => void): void;\n\tterminate?(): void;\n\tclose?(): void;\n}\n\n/**\n * Adapt a Node `worker_threads` port onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker's `parentPort`, and a\n * `worker_threads` `MessagePort`: each posts with `postMessage` and emits a\n * `\"message\"` event whose argument IS the payload (no `.data` wrapper, unlike\n * the DOM). On the main side pass the `Worker`; inside the worker pass\n * `parentPort`.\n */\nexport function messagePortTransport(port: MessagePortLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => port.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tport.on(\"message\", (message) => handler(message));\n\t\t},\n\t\tterminate: () => {\n\t\t\tport.terminate?.();\n\t\t\tport.close?.();\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"sources":["../src/worker/client.ts","../src/worker/serialize.ts","../src/worker/runtime.ts","../src/worker/transport.ts"],"names":["resolveDateOrderForWorker","config","date","resolveDateOrderPolicy","DEFAULT_CONFIG","WorkerEngineClient","transport","raw","options","id","resolve","reject","input","signal","parsing","parseOptions","lines","expression","listener","error","workerTerminatedError","entry","method","args","workerCancelledError","onAbort","message","value","deserializeEngineError","apply","createWorkerEngine","client","nonFiniteTag","n","serializeMatrix","m","cells","cell","formatSymbolic","serializeValue","settings","reading","dto","formatValue","r","c","toHexString","formatColour","pt","ip","serializeMaybe","serializeInlineSolve","solve","serializeParsedLine","line","serializeParsingResult","result","resolvePackages","available","names","byName","pkg","resolved","name","ErrorFactory","WorkerErrorCodes","startWorkerRuntime","BUILTIN_PACKAGES","engine","formatting","inFlight","retainedLines","documentController","stopEventPump","post","fail","serializeEngineError","normalizeUnknownError","retainLines","map","text","index","handleAsyncEvent","eng","event","lineNumber","startEventPump","reader","done","handleInit","packages","ExpressionEngine","DEFAULT_FORMATTING_SETTINGS","runMethod","handleRequest","controller","cloneMessage","createLinkedTransports","clientHandler","hostHandler","alive","deliver","target","cloned","handler","eventTargetTransport","messagePortTransport","port"],"mappings":"wqCA8IA,SAASA,CAAAA,CAA0BC,CAAAA,CAA4E,CAC9G,GAAIA,CAAAA,EAAQ,IAAA,EAAM,UAAA,GAAe,QAAA,CAAU,OAAOA,CAAAA,CAClD,IAAMC,CAAAA,CAAO,CAAE,GAAGD,CAAAA,CAAO,IAAA,CAAM,UAAA,CAAYE,CAAAA,CAAuB,CAAE,GAAGC,GAAAA,CAAe,IAAA,CAAM,GAAGH,CAAAA,CAAO,IAAK,CAAC,CAAA,CAAE,KAAM,CAAA,CACpH,cAAOC,CAAAA,CAAK,WAAA,CACL,CAAE,GAAGD,CAAAA,CAAQ,IAAA,CAAAC,CAAK,CAC1B,CAEA,IAAMG,CAAAA,CAAN,KAAiD,CAWhD,WAAA,CAAYC,CAAAA,CAA4B,CATxC,KAAQ,MAAA,CAAS,CAAA,CACjB,IAAA,CA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,SAAA,CAAY8E,CAAAA,EAAY,CACvB,IAAMtF,CAAAA,CAAYkE,GAAmCoB,CAAAA,CAAQpB,CAAAA,CAAM,IAAI,CAAA,CACnE,OAAOkB,CAAAA,CAAO,gBAAA,EAAqB,WACtCA,CAAAA,CAAO,gBAAA,CAAiB,SAAA,CAAWpF,CAAQ,EAE3CoF,CAAAA,CAAO,SAAA,CAAYpF,CAAAA,CAEpBoF,CAAAA,CAAO,UACR,CAAA,CAGA,UAAW,IAAM,CAChBA,EAAO,SAAA,IAAY,CACnBA,CAAAA,CAAO,KAAA,KACR,CACD,CACD,CAmBO,SAASI,GAAqBC,CAAAA,CAAwC,CAC5E,OAAO,CACN,YAAcjF,CAAAA,EAAYiF,CAAAA,CAAK,YAAYjF,CAAO,CAAA,CAClD,UAAY8E,CAAAA,EAAY,CACvBG,CAAAA,CAAK,EAAA,CAAG,UAAYjF,CAAAA,EAAY8E,CAAAA,CAAQ9E,CAAO,CAAC,EACjD,CAAA,CACA,SAAA,CAAW,IAAM,CAChBiF,EAAK,SAAA,IAAY,CACjBA,EAAK,KAAA,KACN,CACD,CACD","file":"worker.js","sourcesContent":["/**\n * The main-side half of the harness: an async proxy of the core evaluate\n * methods.\n *\n * {@link createWorkerEngine} performs the init handshake and resolves once the\n * worker's engine is built, so the returned {@link WorkerEngine} is ready to\n * call. Each call stamps a request id, tracks the pending promise, and settles\n * it when the matching answer arrives, so several requests can be outstanding at\n * once. An `AbortSignal` rejects the local promise and posts a `cancel` for the\n * same id, mapping keystroke-level cancellation onto the boundary rather than\n * re-inventing it.\n */\n\nimport { DEFAULT_CONFIG, type EngineConfigOverride } from \"@solve-js/constants/Configuration\";\nimport { resolveDateOrderPolicy } from \"@solve-js/packages/datetime/DateReading\";\nimport type { UnifiedParsingOptions } from \"@solve-js/types/ParsingResult\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport type { EngineError } from \"@solve-js/errors\";\nimport {\n\tdeserializeEngineError,\n\tworkerCancelledError,\n\tworkerTerminatedError,\n} from \"@solve-js/errors\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tWorkerMethod,\n\tWorkerRequestArgs,\n\tWorkerToMainMessage,\n} from \"./protocol\";\nimport type {\n\tSerializedWorkerValue,\n\tSerializedParsedLine,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/** Configuration for {@link createWorkerEngine}. */\nexport interface WorkerEngineOptions {\n\t/** The channel to the worker runtime. See `worker/transport.ts` for adapters. */\n\ttransport: WorkerTransport;\n\t/** Locale for keywords and number formatting; defaults to English worker-side. */\n\tlocaleCode?: string;\n\t/** Whether the worker builds its engine with diagnostics enabled. */\n\tdiagnostics?: boolean;\n\t/** Config overrides, merged per section over the defaults worker-side. */\n\tconfig?: EngineConfigOverride;\n\t/**\n\t * Names of built-in packages the worker should register. Omitted registers\n\t * them all. Names rather than the packages themselves, since a package\n\t * carries functions that cannot cross a `postMessage` boundary; a host with\n\t * a custom package bakes it into its own worker entry and selects it here by\n\t * name.\n\t */\n\tpackages?: string[];\n\t/** Formatting settings the worker uses when it renders a DTO's display text. */\n\tformatting?: FormattingSettings;\n}\n\n/** Per-call options common to every proxied method. */\nexport interface WorkerCallOptions {\n\t/** Abort the request. Rejects the returned promise and cancels the work worker-side. */\n\tsignal?: AbortSignal;\n}\n\n/**\n * One line whose result changed after a live value resolved worker-side, carried\n * as its freshly re-evaluated {@link SerializedWorkerValue}. The value the host renders\n * against `lineNumber`, recovered worker-side so the main thread needs no further\n * round-trip to display it.\n */\nexport interface WorkerAsyncUpdate {\n\tlineNumber: number;\n\tvalue: SerializedWorkerValue;\n}\n\n/**\n * A live-data resolution that failed worker-side. `error` is the same structured\n * {@link EngineError} an in-process resolver failure would surface, rebuilt from\n * its transported form, so a host branches on `code`/`category` as it always has.\n */\nexport interface WorkerAsyncError {\n\tqueryKey: string;\n\tpackageId: string;\n\terror: EngineError;\n}\n\n/**\n * An async proxy of {@link ExpressionEngine}'s core evaluate methods.\n *\n * Each method mirrors its synchronous counterpart but returns a Promise of the\n * serialisable DTO rather than a live `Value`, and accepts an `AbortSignal`.\n */\nexport interface WorkerEngine {\n\t/** Parse a whole document off-thread. Mirrors `ExpressionEngine.parseDocument`. */\n\tparseDocument(input: string, options?: UnifiedParsingOptions & WorkerCallOptions): Promise<SerializedParsingResult>;\n\t/** Evaluate an array of lines off-thread. Mirrors `ExpressionEngine.evaluateLines`. */\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]>;\n\t/** Evaluate a single expression off-thread. Mirrors `ExpressionEngine.evaluateExpression`. */\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedWorkerValue>;\n\t/**\n\t * Subscribe to live-data resolutions that land after a request already\n\t * answered.\n\t *\n\t * A currency, weather or historical-rate value resolves inside the worker some\n\t * time after `parseDocument` returned its pending result. When it does, the\n\t * affected lines are re-evaluated worker-side and their fresh values arrive\n\t * here as one batch. This is a subscription rather than a per-request promise\n\t * because a resolution is tied to no single request: it belongs to whichever\n\t * document is current when the value lands. Returns an unsubscribe function.\n\t */\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void;\n\t/**\n\t * Subscribe to live-data resolutions that failed. Returns an unsubscribe\n\t * function. See {@link onResolved}; this is its failure channel.\n\t */\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void;\n\t/** Reject every in-flight request and tear the transport down. Idempotent. */\n\tterminate(): void;\n}\n\n/** A promise awaiting one worker answer, plus the abort wiring to unhook when it settles. */\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: unknown) => void;\n\tsignal?: AbortSignal;\n\tonAbort?: () => void;\n}\n\n/**\n * Replaces `date.inputOrder: 'locale'` with the order this side resolves it\n * to, before the config crosses to the worker.\n *\n * `'locale'` means \"ask the reader's machine\", and the reader's machine is\n * this one. A worker re-inferring it would be asking a different environment\n * the same question: a worker thread can carry different `Intl` data (a\n * bundler-provided shim, a small-ICU runtime), so the same document could be\n * read day-first on the main thread and month-first in the worker with nothing\n * to show for it. The resolved order crosses instead, so both sides read the\n * document the same way, and `date.inputLocale` is dropped with it because it\n * has already done its work.\n *\n * Anything else passes through untouched, including an absent config.\n */\nfunction resolveDateOrderForWorker(config: EngineConfigOverride | undefined): EngineConfigOverride | undefined {\n\tif (config?.date?.inputOrder !== \"locale\") return config;\n\tconst date = { ...config.date, inputOrder: resolveDateOrderPolicy({ ...DEFAULT_CONFIG.date, ...config.date }).order };\n\tdelete date.inputLocale;\n\treturn { ...config, date };\n}\n\nclass WorkerEngineClient implements WorkerEngine {\n\tprivate readonly transport: WorkerTransport;\n\tprivate nextId = 1;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\t// Broadcast subscribers for async resolutions. Sets, not one callback each, so\n\t// several views can watch the same worker; a resolution is not tied to a\n\t// request id, so these live outside `pending`.\n\tprivate readonly resolvedListeners = new Set<(lines: WorkerAsyncUpdate[]) => void>();\n\tprivate readonly asyncErrorListeners = new Set<(error: WorkerAsyncError) => void>();\n\tprivate terminated = false;\n\n\tconstructor(transport: WorkerTransport) {\n\t\tthis.transport = transport;\n\t\tthis.transport.onMessage((raw) => this.onMessage(raw));\n\t}\n\n\t/** Perform the init handshake, resolving once the worker posts `ready`. */\n\tinit(options: WorkerEngineOptions): Promise<void> {\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve: () => resolve(), reject });\n\t\t\tthis.transport.postMessage({\n\t\t\t\tkind: \"init\",\n\t\t\t\tid,\n\t\t\t\tlocaleCode: options.localeCode,\n\t\t\t\tdiagnostics: options.diagnostics,\n\t\t\t\tconfig: resolveDateOrderForWorker(options.config),\n\t\t\t\tpackages: options.packages,\n\t\t\t\tformatting: options.formatting,\n\t\t\t});\n\t\t});\n\t}\n\n\tparseDocument(\n\t\tinput: string,\n\t\toptions?: UnifiedParsingOptions & WorkerCallOptions,\n\t): Promise<SerializedParsingResult> {\n\t\t// The signal stays main-side and drives a `cancel`; only the parsing\n\t\t// options cross, so an AbortSignal never reaches `postMessage`.\n\t\tconst { signal, ...parsing } = options ?? {};\n\t\tconst parseOptions = Object.keys(parsing).length > 0 ? (parsing as UnifiedParsingOptions) : undefined;\n\t\treturn this.call<SerializedParsingResult>(\"parseDocument\", [input, parseOptions], signal);\n\t}\n\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]> {\n\t\treturn this.call<SerializedParsedLine[]>(\"evaluateLines\", [lines], options?.signal);\n\t}\n\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedWorkerValue> {\n\t\treturn this.call<SerializedWorkerValue>(\"evaluateExpression\", [expression], options?.signal);\n\t}\n\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void {\n\t\tthis.resolvedListeners.add(listener);\n\t\treturn () => this.resolvedListeners.delete(listener);\n\t}\n\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void {\n\t\tthis.asyncErrorListeners.add(listener);\n\t\treturn () => this.asyncErrorListeners.delete(listener);\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) return;\n\t\tthis.terminated = true;\n\t\tconst error = workerTerminatedError();\n\t\tfor (const entry of this.pending.values()) {\n\t\t\tthis.unhook(entry);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t\t// No more resolutions can arrive across a torn-down transport, so drop the\n\t\t// subscribers rather than leaving them referenced for the client's lifetime.\n\t\tthis.resolvedListeners.clear();\n\t\tthis.asyncErrorListeners.clear();\n\t\tthis.transport.terminate();\n\t}\n\n\t/** Dispatch one request and return the promise that settles on its answer. */\n\tprivate call<T>(method: WorkerMethod, args: WorkerRequestArgs, signal?: AbortSignal): Promise<T> {\n\t\tif (this.terminated) return Promise.reject(workerTerminatedError());\n\t\tif (signal?.aborted) return Promise.reject(workerCancelledError(method));\n\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst entry: PendingRequest = { resolve: resolve as (value: unknown) => void, reject };\n\n\t\t\tif (signal) {\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\t// Nothing to do if the answer already arrived and settled this id.\n\t\t\t\t\tif (!this.pending.has(id)) return;\n\t\t\t\t\tthis.pending.delete(id);\n\t\t\t\t\tthis.transport.postMessage({ kind: \"cancel\", id });\n\t\t\t\t\treject(workerCancelledError(method));\n\t\t\t\t};\n\t\t\t\tentry.signal = signal;\n\t\t\t\tentry.onAbort = onAbort;\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\n\t\t\tthis.pending.set(id, entry);\n\t\t\tthis.transport.postMessage({ kind: \"request\", id, method, args });\n\t\t});\n\t}\n\n\t/** Route one incoming message to the request that is waiting on its id. */\n\tprivate onMessage(raw: unknown): void {\n\t\tconst message = raw as WorkerToMainMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"ready\":\n\t\t\tcase \"result\": {\n\t\t\t\tconst value = message.kind === \"result\" ? message.value : undefined;\n\t\t\t\tthis.settle(message.id, (entry) => entry.resolve(value));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"error\":\n\t\t\t\tthis.settle(message.id, (entry) => entry.reject(deserializeEngineError(message.error)));\n\t\t\t\tbreak;\n\t\t\tcase \"async-update\":\n\t\t\t\t// A broadcast, not an answer to a request: fan it out to every\n\t\t\t\t// subscriber. A copy of the listener set is iterated so a listener\n\t\t\t\t// that unsubscribes itself mid-callback cannot disturb the walk.\n\t\t\t\tfor (const listener of [...this.resolvedListeners]) listener(message.lines);\n\t\t\t\tbreak;\n\t\t\tcase \"async-error\":\n\t\t\t\tfor (const listener of [...this.asyncErrorListeners]) {\n\t\t\t\t\tlistener({\n\t\t\t\t\t\tqueryKey: message.queryKey,\n\t\t\t\t\t\tpackageId: message.packageId,\n\t\t\t\t\t\terror: deserializeEngineError(message.error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Remove a pending request by id and run the settle callback, if it is still pending. */\n\tprivate settle(id: number, apply: (entry: PendingRequest) => void): void {\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tthis.unhook(entry);\n\t\tapply(entry);\n\t}\n\n\t/** Detach an entry's abort listener so a settled request leaves nothing on the signal. */\n\tprivate unhook(entry: PendingRequest): void {\n\t\tif (entry.signal && entry.onAbort) entry.signal.removeEventListener(\"abort\", entry.onAbort);\n\t}\n}\n\n/**\n * Build a worker-backed engine and wait for it to be ready.\n *\n * ```ts\n * const { client, host } = createLinkedTransports();\n * startWorkerRuntime(host);\n * const engine = await createWorkerEngine({ transport: client });\n * const result = await engine.parseDocument(text);\n * ```\n *\n * In production `client` wraps a real `Worker` (see `eventTargetTransport` /\n * `messagePortTransport`), and `startWorkerRuntime` runs inside that worker.\n */\nexport async function createWorkerEngine(options: WorkerEngineOptions): Promise<WorkerEngine> {\n\tconst client = new WorkerEngineClient(options.transport);\n\tawait client.init(options);\n\treturn client;\n}\n","/**\n * Turn live engine results into the clone-safe DTOs the worker harness posts.\n *\n * These functions run on the worker side, just before a result crosses the\n * boundary, and are also what the main side re-runs on a synchronous result to\n * compare the two paths in tests. They are pure and deterministic given the\n * same {@link FormattingSettings}, so a value serialised on either side is\n * byte-for-byte the same DTO.\n */\n\nimport { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type ChartData, type IpCidrData } from \"@solve-js/vm/Value\";\nimport { formatValue } from \"@solve-js/format/FormatEngine\";\nimport { toHexString, formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport { formatSymbolic } from \"@solve-js/symbolic\";\nimport type { ParsedLine, InlineSolvePosition, ParsingResult } from \"@solve-js/types/ParsingResult\";\nimport type {\n\tSerializedWorkerValue,\n\tSerializedMatrix,\n\tSerializedParsedLine,\n\tSerializedInlineSolve,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/**\n * The JSON-safe string tag for a non-finite reading. `Infinity`/`-Infinity`/`NaN`\n * cannot cross `JSON` (which turns each into `null`), so this one string form is\n * what survives both `structuredClone` and `JSON`, and a host recovers the value\n * with `Number(tag)`. Shared by the scalar `nonFinite` field and matrix cells.\n */\nfunction nonFiniteTag(n: number): \"Infinity\" | \"-Infinity\" | \"NaN\" {\n\treturn n > 0 ? \"Infinity\" : n < 0 ? \"-Infinity\" : \"NaN\";\n}\n\n/** Project a matrix onto clone-safe cells: finite primitives pass through, symbolic cells and non-finite numbers become strings. */\nfunction serializeMatrix(m: MatrixData): SerializedMatrix {\n\tconst cells = m.data.map((cell: MatrixEntry): number | boolean | string => {\n\t\t// A `SymbolicNode` (the object-typed cell variant) flattens to its display\n\t\t// string. A non-finite number (a `[1/0, 2]` cell) cannot cross JSON any\n\t\t// more than a scalar reading can, so it takes the same string tag rather\n\t\t// than being passed through raw and turned into `null` by `JSON.stringify`\n\t\t// (which would diverge from the `structuredClone` path). A finite number\n\t\t// or a boolean is already clone-safe and passes through.\n\t\tif (typeof cell === \"object\" && cell !== null) return formatSymbolic(cell);\n\t\tif (typeof cell === \"number\" && !Number.isFinite(cell)) return nonFiniteTag(cell);\n\t\treturn cell;\n\t});\n\treturn { rows: m.rows, cols: m.cols, cells, hasSymbolic: m.hasSymbolic };\n}\n\n/**\n * Project a {@link Value} onto a {@link SerializedWorkerValue}.\n *\n * `text` and `number` are set for every value; the type-specific fields are\n * added only where the payload needs them, so the DTO stays minimal and a\n * deep-equal between the two evaluation paths does not trip on a property one\n * side left `undefined`.\n */\nexport function serializeValue(value: Value, settings?: FormattingSettings): SerializedWorkerValue {\n\tconst reading = value.toNumber();\n\tconst dto: SerializedWorkerValue = {\n\t\ttype: value.type,\n\t\ttext: formatValue(value, settings),\n\t\t// A non-finite reading (1/0, 0/0, an overflow) cannot cross JSON, which\n\t\t// turns it into null and breaks the round-trip the DTO guarantees. Keep\n\t\t// `number` finite and name the real value in `nonFinite` instead.\n\t\tnumber: Number.isFinite(reading) ? reading : 0,\n\t};\n\tif (!Number.isFinite(reading)) {\n\t\tdto.nonFinite = nonFiniteTag(reading);\n\t}\n\n\tif (value.unit !== undefined) dto.unit = value.unit;\n\tif (value.timedOut !== undefined) dto.timedOut = value.timedOut;\n\t// The two datetime sidecars cross as themselves: both are plain JSON\n\t// scalars, so the clone guarantee is untouched, and a worker result that\n\t// dropped them would answer a different question from the synchronous one.\n\tif (value.grain !== undefined) dto.grain = value.grain;\n\tif (value.zone !== undefined) dto.zone = value.zone;\n\n\tconst raw = value.value;\n\tif (typeof raw === \"bigint\") {\n\t\t// Covers BigInt values and a Hex value that carries a bigint magnitude:\n\t\t// a base-ten string is the one representation that neither loses\n\t\t// precision nor breaks JSON.\n\t\tdto.bigint = raw.toString();\n\t} else if (value.type === ValueType.Matrix) {\n\t\tdto.matrix = serializeMatrix(raw as MatrixData);\n\t} else if (value.type === ValueType.Range) {\n\t\tconst r = raw as RangeData;\n\t\tdto.range = { min: r.min, max: r.max };\n\t} else if (value.type === ValueType.Colour) {\n\t\tconst c = raw as ColourData;\n\t\tdto.colour = { hex: toHexString(c), r: c.r, g: c.g, b: c.b, a: c.a, format: c.format, css: formatColour(c) };\n\t} else if (value.type === ValueType.Chart) {\n\t\tconst c = raw as ChartData;\n\t\tdto.chart = {\n\t\t\tkind: c.kind,\n\t\t\tpoints: c.points.map((pt) => [pt[0], pt[1]]),\n\t\t\tlabel: c.label,\n\t\t\tdomain: [c.domain[0], c.domain[1]],\n\t\t\trange: [c.range[0], c.range[1]],\n\t\t\t...(c.expr !== undefined ? { expr: c.expr } : {}),\n\t\t};\n\t} else if (value.type === ValueType.IpCidr) {\n\t\tconst ip = raw as IpCidrData;\n\t\tdto.ipCidr = {\n\t\t\t...(ip.addr !== undefined ? { addr: ip.addr } : {}),\n\t\t\t...(ip.prefix !== undefined ? { prefix: ip.prefix } : {}),\n\t\t\ttext: formatValue(value).replace(/^=\\s*/, \"\"),\n\t\t};\n\t}\n\n\treturn dto;\n}\n\n/** Serialise a nullable value, the shape both `result` fields carry. */\nfunction serializeMaybe(value: Value | null | undefined, settings?: FormattingSettings): SerializedWorkerValue | null {\n\treturn value ? serializeValue(value, settings) : null;\n}\n\n/** Project an inline solve onto its DTO, serialising its result. */\nfunction serializeInlineSolve(solve: InlineSolvePosition, settings?: FormattingSettings): SerializedInlineSolve {\n\treturn {\n\t\tstart: solve.start,\n\t\tend: solve.end,\n\t\texpression: solve.expression,\n\t\tlineNumber: solve.lineNumber,\n\t\tcolumnNumber: solve.columnNumber,\n\t\tresult: serializeMaybe(solve.result, settings),\n\t\terror: solve.error ?? null,\n\t};\n}\n\n/** Project a parsed line onto its DTO, serialising its result and every inline solve. */\nexport function serializeParsedLine(line: ParsedLine, settings?: FormattingSettings): SerializedParsedLine {\n\treturn {\n\t\tlineNumber: line.lineNumber,\n\t\ttext: line.text,\n\t\tstartPosition: line.startPosition,\n\t\tendPosition: line.endPosition,\n\t\tisEmpty: line.isEmpty,\n\t\thasInlineSolves: line.hasInlineSolves,\n\t\tinlineSolves: line.inlineSolves.map((solve) => serializeInlineSolve(solve, settings)),\n\t\texpression: line.expression,\n\t\tresult: serializeMaybe(line.result, settings),\n\t\terror: line.error,\n\t};\n}\n\n/** Project a whole parsing result onto its DTO. */\nexport function serializeParsingResult(result: ParsingResult, settings?: FormattingSettings): SerializedParsingResult {\n\tconst dto: SerializedParsingResult = {\n\t\tlines: result.lines.map((line) => serializeParsedLine(line, settings)),\n\t\ttotalLines: result.totalLines,\n\t\terrors: [...result.errors],\n\t};\n\t// The diagnostics report is already the engine's own JSON form, so it\n\t// crosses unchanged; present only when the host asked for it.\n\tif (result.diagnostics !== undefined) dto.diagnostics = result.diagnostics;\n\treturn dto;\n}\n","/**\n * The worker-side half of the harness: it owns an {@link ExpressionEngine} and\n * answers the protocol.\n *\n * {@link startWorkerRuntime} is transport-agnostic, so the same function runs\n * behind a browser `Worker`, a Node `worker_threads` port, or an in-process\n * link. A host's worker entry file is two lines: adapt the environment onto a\n * {@link WorkerTransport} and call this.\n *\n * The runtime never posts a raw {@link Value}. Every result is projected onto a\n * DTO first (`worker/serialize.ts`), and every failure is caught and flattened\n * into a structured error, so a worker-side throw reaches the caller as an\n * `EngineError` rather than a lost promise.\n */\n\nimport { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport type { AsyncResolutionEvent } from \"@solve-js/engine/AsyncResolutionBatcher\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport { DEFAULT_FORMATTING_SETTINGS, type FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport type { CalendarBackend } from \"@solve-js/calendar/CalendarBackend\";\nimport {\n\tErrorFactory,\n\tnormalizeUnknownError,\n\tserializeEngineError,\n\tWorkerErrorCodes,\n} from \"@solve-js/errors\";\nimport { serializeParsingResult, serializeParsedLine, serializeValue } from \"./serialize\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tMainToWorkerMessage,\n\tInitMessage,\n\tRequestMessage,\n\tWorkerToMainMessage,\n\tAsyncResolvedLine,\n} from \"./protocol\";\n\n/** Options a host bakes into its own worker entry: its custom packages, and its calendar backend. */\nexport interface WorkerRuntimeOptions {\n\t/**\n\t * The packages available to register, defaulting to {@link BUILTIN_PACKAGES}.\n\t * A host with its own package authors a worker entry that passes them here,\n\t * then selects among them by name from the main side. This is how a\n\t * function-carrying package reaches the worker: baked into its bundle, never\n\t * posted across the boundary.\n\t */\n\tpackages?: IEnginePackage[];\n\t/**\n\t * The calendar backend the worker's engine computes dates with, and writes\n\t * them out with, as the engine's own `calendar` option. Defaults to the\n\t * built-in `Date` backend. Baked in here for the same reason a package is:\n\t * a backend is an object of functions and cannot be posted across the\n\t * boundary, so the main side's formatting settings never carry one.\n\t */\n\tcalendar?: CalendarBackend;\n}\n\n/**\n * Resolve the requested package names against the available set.\n *\n * Undefined names means \"all of them\". A name with no match is a configuration\n * failure the caller must see, not a silent omission that would leave a feature\n * quietly missing from every result.\n */\nfunction resolvePackages(available: IEnginePackage[], names: string[] | undefined): IEnginePackage[] {\n\tif (names === undefined) return available;\n\tconst byName = new Map(available.map((pkg) => [pkg.name, pkg]));\n\tconst resolved: IEnginePackage[] = [];\n\tfor (const name of names) {\n\t\tconst pkg = byName.get(name);\n\t\tif (!pkg) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_PACKAGE,\n\t\t\t\t`No package named \"${name}\" is available in this worker runtime`,\n\t\t\t\t{ name, available: [...byName.keys()] },\n\t\t\t);\n\t\t}\n\t\tresolved.push(pkg);\n\t}\n\treturn resolved;\n}\n\n/**\n * Attach the runtime to a transport and start serving.\n *\n * Returns a teardown function that clears the engine and detaches, for a host\n * that reuses a transport or shuts a worker down cleanly.\n */\nexport function startWorkerRuntime(transport: WorkerTransport, options: WorkerRuntimeOptions = {}): () => void {\n\tconst available = options.packages ?? BUILTIN_PACKAGES;\n\n\tlet engine: ExpressionEngine | null = null;\n\tlet formatting: FormattingSettings | undefined;\n\t// One AbortController per in-flight request, so a `cancel` can map onto the\n\t// engine's keystroke signal for exactly the request the caller aborted.\n\tconst inFlight = new Map<number, AbortController>();\n\n\t// The line texts of the current document, keyed by the line number the engine\n\t// evaluates them under (1-based for a document, -1 for a lone expression). An\n\t// async resolution names the lines whose result changed but not the new value,\n\t// so this is what the event pump re-reads a line from to recover it.\n\tlet retainedLines = new Map<number, string>();\n\n\t// The current document's abort controller, kept alive past the request that\n\t// created it so this document's async resolutions can still land. Aborted when\n\t// a new document supersedes it: aborting drops the old document's in-flight\n\t// resolutions at the engine's own staleness guard (an aborted signal is\n\t// discarded before it reaches the batcher), so a stale value never reaches the\n\t// host as if it were current. See {@link handleRequest}.\n\tlet documentController: AbortController | null = null;\n\n\t// Cancels the event-stream reader on teardown. Null until the pump starts.\n\tlet stopEventPump: (() => void) | null = null;\n\n\tconst post = (message: WorkerToMainMessage): void => transport.postMessage(message);\n\n\tconst fail = (id: number, error: unknown): void => {\n\t\tpost({ kind: \"error\", id, error: serializeEngineError(normalizeUnknownError(error)) });\n\t};\n\n\t/**\n\t * Record the line texts a request evaluates, so a later async resolution can\n\t * re-read exactly the lines it names. A whole document splits into 1-based\n\t * lines; a lone `evaluateExpression` maps onto the engine's `-1` sentinel, the\n\t * same line number the engine registers and later reports for it.\n\t */\n\tconst retainLines = (message: RequestMessage): Map<number, string> => {\n\t\tconst map = new Map<number, string>();\n\t\tif (message.method === \"parseDocument\") {\n\t\t\t(message.args[0] as string).split(\"\\n\").forEach((text, index) => map.set(index + 1, text));\n\t\t} else if (message.method === \"evaluateLines\") {\n\t\t\t(message.args[0] as string[]).forEach((text, index) => map.set(index + 1, text));\n\t\t} else {\n\t\t\tmap.set(-1, message.args[0] as string);\n\t\t}\n\t\treturn map;\n\t};\n\n\t/**\n\t * Turn one async resolution event into a message home.\n\t *\n\t * A `lines-updated` event names the lines whose result changed; the resolved\n\t * value lives in the engine's cache, so each named line is re-evaluated (which\n\t * now reads the settled value from that cache rather than starting a fresh\n\t * fetch) and serialised. A line the current document no longer retains belongs\n\t * to a superseded document and is skipped. An `error` event carries the failed\n\t * query straight across as a structured error.\n\t */\n\tconst handleAsyncEvent = (eng: ExpressionEngine, event: AsyncResolutionEvent): void => {\n\t\tif (event.type === \"error\") {\n\t\t\tpost({\n\t\t\t\tkind: \"async-error\",\n\t\t\t\tqueryKey: event.queryKey,\n\t\t\t\tpackageId: event.packageId,\n\t\t\t\terror: serializeEngineError(normalizeUnknownError(event.error)),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst lines: AsyncResolvedLine[] = [];\n\t\tfor (const lineNumber of event.lineNumbers) {\n\t\t\tconst text = retainedLines.get(lineNumber);\n\t\t\tif (text === undefined) continue;\n\t\t\ttry {\n\t\t\t\tconst value = eng.evaluateLine(lineNumber, text);\n\t\t\t\tif (value) lines.push({ lineNumber, value: serializeValue(value, formatting) });\n\t\t\t} catch {\n\t\t\t\t// A line that resolved into an error re-throws on re-evaluation; the\n\t\t\t\t// batcher's own `error` event is the channel for that, so this keeps\n\t\t\t\t// the update to the lines that produced a value rather than posting a\n\t\t\t\t// second, half-formed failure here.\n\t\t\t}\n\t\t}\n\t\tif (lines.length > 0) post({ kind: \"async-update\", lines });\n\t};\n\n\t/**\n\t * Drain the engine's async-resolution event stream for the life of the\n\t * runtime, posting each event home. Started once the engine exists; the reader\n\t * loop ends when the stream closes (engine cleared) or the returned canceller\n\t * runs at teardown.\n\t */\n\tconst startEventPump = (eng: ExpressionEngine): void => {\n\t\tstopEventPump?.();\n\t\tconst reader = eng.getEventStream().getReader();\n\t\tstopEventPump = () => void reader.cancel();\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) return;\n\t\t\t\t\thandleAsyncEvent(eng, value);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// The stream errored or was cancelled (teardown); the loop is done.\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst handleInit = (message: InitMessage): void => {\n\t\ttry {\n\t\t\tconst packages = resolvePackages(available, message.packages);\n\t\t\tengine = new ExpressionEngine({\n\t\t\t\tlocale: message.localeCode ?? \"en\",\n\t\t\t\tdiagnostics: message.diagnostics ?? false,\n\t\t\t\tconfig: message.config,\n\t\t\t\tpackages,\n\t\t\t\tcalendar: options.calendar,\n\t\t\t});\n\t\t\t// The display reads the same backend the engine computes with, so a\n\t\t\t// date in a DTO names the day it was computed on; the main side's\n\t\t\t// settings cannot carry the backend, so it is joined here.\n\t\t\tformatting = options.calendar\n\t\t\t\t? { ...(message.formatting ?? DEFAULT_FORMATTING_SETTINGS), calendar: options.calendar }\n\t\t\t\t: message.formatting;\n\t\t\t// Drain live-data resolutions for the engine's whole lifetime, so a\n\t\t\t// value that settles after a request already answered still reaches the\n\t\t\t// host. Started here, after the engine exists, and torn down with it.\n\t\t\tstartEventPump(engine);\n\t\t\tpost({ kind: \"ready\", id: message.id });\n\t\t} catch (error) {\n\t\t\t// A build failure leaves no engine; the caller's `createWorkerEngine`\n\t\t\t// promise rejects with this rather than hanging on a `ready` that\n\t\t\t// never comes.\n\t\t\tfail(message.id, error);\n\t\t}\n\t};\n\n\tconst runMethod = (eng: ExpressionEngine, message: RequestMessage): unknown => {\n\t\tconst { method, args } = message;\n\t\tswitch (method) {\n\t\t\tcase \"parseDocument\":\n\t\t\t\treturn serializeParsingResult(eng.parseDocument(args[0] as string, args[1] as never), formatting);\n\t\t\tcase \"evaluateLines\":\n\t\t\t\treturn eng.evaluateLines(args[0] as string[]).map((line) => serializeParsedLine(line, formatting));\n\t\t\tcase \"evaluateExpression\":\n\t\t\t\t// Mirrors ExpressionEngine.evaluateExpression: a single Value in,\n\t\t\t\t// a single serialized Value out.\n\t\t\t\treturn serializeValue(eng.evaluateExpression(args[0] as string), formatting);\n\t\t\tdefault:\n\t\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_METHOD,\n\t\t\t\t\t`The worker runtime has no method named \"${String(method)}\"`,\n\t\t\t\t\t{ method },\n\t\t\t\t);\n\t\t}\n\t};\n\n\tconst handleRequest = (message: RequestMessage): void => {\n\t\tconst eng = engine;\n\t\tif (!eng) {\n\t\t\tfail(\n\t\t\t\tmessage.id,\n\t\t\t\tErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_NOT_INITIALISED,\n\t\t\t\t\t\"The worker received a request before its engine finished initialising\",\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Supersede the previous document: abort its controller so any resolution\n\t\t// still in flight for it is dropped at the engine's staleness guard rather\n\t\t// than posted home as if it belonged to this request's document. The old\n\t\t// retained lines go with it. Every evaluate call shares one engine and one\n\t\t// document context, so the most recent call is the live one.\n\t\tdocumentController?.abort();\n\n\t\t// This request's controller doubles as the document controller: wired in as\n\t\t// the keystroke signal so a later `cancel` (or the next supersede) aborts\n\t\t// the async work this evaluation fires, the same mechanism a host uses on\n\t\t// the main thread. It is deliberately NOT aborted when the request settles,\n\t\t// so this document's live values can still resolve and stream back.\n\t\tconst controller = new AbortController();\n\t\tdocumentController = controller;\n\t\tretainedLines = retainLines(message);\n\t\tinFlight.set(message.id, controller);\n\t\teng.setKeystrokeSignal(controller.signal);\n\n\t\ttry {\n\t\t\tconst value = runMethod(eng, message);\n\t\t\tpost({ kind: \"result\", id: message.id, value });\n\t\t} catch (error) {\n\t\t\tfail(message.id, error);\n\t\t} finally {\n\t\t\tinFlight.delete(message.id);\n\t\t\teng.setKeystrokeSignal(null);\n\t\t}\n\t};\n\n\ttransport.onMessage((raw) => {\n\t\tconst message = raw as MainToWorkerMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"init\":\n\t\t\t\thandleInit(message);\n\t\t\t\tbreak;\n\t\t\tcase \"request\":\n\t\t\t\thandleRequest(message);\n\t\t\t\tbreak;\n\t\t\tcase \"cancel\":\n\t\t\t\t// Abort maps onto the keystroke signal for the named request; a\n\t\t\t\t// cancel that arrives after the request already settled finds no\n\t\t\t\t// controller and is a harmless no-op.\n\t\t\t\tinFlight.get(message.id)?.abort();\n\t\t\t\tbreak;\n\t\t}\n\t});\n\n\treturn () => {\n\t\tstopEventPump?.();\n\t\tstopEventPump = null;\n\t\tdocumentController?.abort();\n\t\tdocumentController = null;\n\t\tretainedLines = new Map();\n\t\tfor (const controller of inFlight.values()) controller.abort();\n\t\tinFlight.clear();\n\t\tengine?.clear();\n\t\tengine = null;\n\t\ttransport.terminate();\n\t};\n}\n","/**\n * The seam between the harness and whatever actually carries messages.\n *\n * Both the client (`worker/client.ts`) and the runtime (`worker/runtime.ts`)\n * talk to a {@link WorkerTransport} and nothing more, so the same code drives a\n * browser `Worker`, a Node `worker_threads` port, or an in-process pair. The\n * three factory functions below adapt each of those onto the interface; a host\n * with a transport this file does not cover can implement the three methods\n * directly.\n */\n\n/**\n * A bidirectional message channel with a single receive handler.\n *\n * `onMessage` registers the one handler the harness needs; calling it again\n * replaces the previous handler. `terminate` tears the channel down and is safe\n * to call more than once.\n */\nexport interface WorkerTransport {\n\t/** Send one message to the other end. The message must be clone-safe. */\n\tpostMessage(message: unknown): void;\n\t/** Register the handler that receives messages from the other end. */\n\tonMessage(handler: (message: unknown) => void): void;\n\t/** Tear the channel down. Idempotent. */\n\tterminate(): void;\n}\n\n/**\n * Clone a message the way `postMessage` would, so an in-process transport has\n * the same value semantics as a real one.\n *\n * The harness protocol is clone-safe by construction, so the `JSON` fallback\n * (for a runtime without a global `structuredClone`) is lossless here; the\n * structured-clone path is preferred because it is what a real worker uses and\n * because it throws loudly if a non-clone-safe value ever reaches it, which is\n * exactly the mistake the DTO layer exists to prevent.\n *\n * A function, not a module-level const, so this module does no work at load\n * time and stays deletable under the package's `sideEffects: false` claim; the\n * `typeof` probe runs once per message, which is free next to the clone itself.\n */\nfunction cloneMessage<T>(value: T): T {\n\treturn typeof globalThis.structuredClone === \"function\"\n\t\t? globalThis.structuredClone(value)\n\t\t: JSON.parse(JSON.stringify(value));\n}\n\n/**\n * A pair of linked in-process transports.\n *\n * `client` and `host` are two ends of one channel: a message posted on either\n * is cloned at post time and delivered to the other on a microtask, so delivery\n * is asynchronous (as a real worker's is) but deterministic (no timers, no I/O).\n * Wire `client` into {@link createWorkerEngine} and `host` into\n * {@link startWorkerRuntime} to run the whole protocol, DTO serialisation and\n * cancellation included, without a second thread. This is the transport tests\n * use, and a fit for a host that wants the message-passing shape on one thread.\n */\nexport function createLinkedTransports(): { client: WorkerTransport; host: WorkerTransport } {\n\tlet clientHandler: ((message: unknown) => void) | null = null;\n\tlet hostHandler: ((message: unknown) => void) | null = null;\n\tlet alive = true;\n\n\t// The handler is read at delivery time rather than post time so setup order\n\t// (post before the other end has registered) cannot drop a message.\n\tconst deliver = (target: () => ((message: unknown) => void) | null, message: unknown): void => {\n\t\tconst cloned = cloneMessage(message);\n\t\tqueueMicrotask(() => {\n\t\t\tif (!alive) return;\n\t\t\ttarget()?.(cloned);\n\t\t});\n\t};\n\n\tconst client: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => hostHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\tclientHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\tconst host: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => clientHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\thostHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\treturn { client, host };\n}\n\n/** The `postMessage`/`onmessage`/event-listener shape a browser `Worker`, a worker's `self`, or a DOM `MessagePort` presents. */\ninterface EventTargetLike {\n\tpostMessage(message: unknown): void;\n\taddEventListener?(type: \"message\", handler: (event: { data: unknown }) => void): void;\n\tonmessage?: ((event: { data: unknown }) => void) | null;\n\tterminate?(): void;\n\tclose?(): void;\n\tstart?(): void;\n}\n\n/**\n * Adapt a browser-style message target onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker global `self`, and a DOM\n * `MessagePort`: each posts with `postMessage` and receives a `MessageEvent`\n * whose `data` is the payload. A `MessagePort` is `start`ed here so it begins\n * dispatching. On the main side pass a `Worker`; inside a browser worker pass\n * `self`.\n */\nexport function eventTargetTransport(target: EventTargetLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => target.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tconst listener = (event: { data: unknown }): void => handler(event.data);\n\t\t\tif (typeof target.addEventListener === \"function\") {\n\t\t\t\ttarget.addEventListener(\"message\", listener);\n\t\t\t} else {\n\t\t\t\ttarget.onmessage = listener;\n\t\t\t}\n\t\t\ttarget.start?.();\n\t\t},\n\t\t// A main-side Worker terminates; a worker's own `self` closes. Calling\n\t\t// whichever exists keeps one adapter usable from both ends.\n\t\tterminate: () => {\n\t\t\ttarget.terminate?.();\n\t\t\ttarget.close?.();\n\t\t},\n\t};\n}\n\n/** The `postMessage`/`on(\"message\")` shape a Node `worker_threads` `Worker`, `parentPort`, or `MessagePort` presents. */\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n\ton(event: \"message\", handler: (message: unknown) => void): void;\n\tterminate?(): void;\n\tclose?(): void;\n}\n\n/**\n * Adapt a Node `worker_threads` port onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker's `parentPort`, and a\n * `worker_threads` `MessagePort`: each posts with `postMessage` and emits a\n * `\"message\"` event whose argument IS the payload (no `.data` wrapper, unlike\n * the DOM). On the main side pass the `Worker`; inside the worker pass\n * `parentPort`.\n */\nexport function messagePortTransport(port: MessagePortLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => port.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tport.on(\"message\", (message) => handler(message));\n\t\t},\n\t\tterminate: () => {\n\t\t\tport.terminate?.();\n\t\t\tport.close?.();\n\t\t},\n\t};\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "solve-engine",
3
- "version": "2.32.0",
3
+ "version": "2.33.0",
4
4
  "description": "An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.",
5
5
  "keywords": [
6
6
  "expression-evaluator",
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkWU7SBKVU_cjs=require('./chunk-WU7SBKVU.cjs'),chunkYBQOQTVL_cjs=require('./chunk-YBQOQTVL.cjs'),chunkSUAGBRQ7_cjs=require('./chunk-SUAGBRQ7.cjs');var N=32,L=2;function v(a){return a.shape!==void 0?a.shape:a.startTokenTypes!==void 0?[{types:a.startTokenTypes}]:[]}var x=class{constructor(e){this.rules=e;let r=e.length,t=Math.max(1,Math.ceil(r/N));this.words=t,this.scratch=new Uint32Array(t);let s=e.map(v),n=0;for(let l of s)for(let c of l)for(let f of c.types??[])n=Math.max(n,chunkYBQOQTVL_cjs.c(f));this.typeRows=n+1;let i=0;for(let l of s)i=Math.max(i,l.length);i=Math.min(i,L),this.allRules=new Uint32Array(t);for(let l=0;l<r;l++)this.allRules[l/N|0]|=1<<l%N;let u=[];for(let l=0;l<i;l++)u.push(this.buildPlane(s,l,t));this.planes=u;}buildPlane(e,r,t){let s={byType:new Uint32Array(this.typeRows*t),typeAny:new Uint32Array(t),atEnd:new Uint32Array(t),typeHasValues:new Uint8Array(this.typeRows),byValue:new Map,valueAny:new Uint32Array(t)};for(let n=0;n<e.length;n++){let i=e[n][r],u=n/N|0,l=1<<n%N,c=i?.types;if(c===void 0)s.typeAny[u]|=l,s.atEnd[u]|=l;else for(let p of c)s.byType[chunkYBQOQTVL_cjs.c(p)*t+u]|=l;let f=i?.values;if(f===void 0)s.valueAny[u]|=l;else {for(let p of f){let h=p.toLowerCase(),o=s.byValue.get(h);o===void 0&&(o=new Uint32Array(t),s.byValue.set(h,o)),o[u]|=l;}if(c===void 0)s.typeHasValues.fill(1);else for(let p of c){let h=chunkYBQOQTVL_cjs.c(p);h<this.typeRows&&(s.typeHasValues[h]=1);}}}return s}get size(){return this.rules.length}get depth(){return this.planes.length}candidates(e,r){let t=this.words,s=this.scratch,n=this.planes,i=e.length;if(n.length===0)return s.set(this.allRules),s;for(let u=0;u<n.length;u++){let l=n[u],c=r+u;if(c>=i){if(u===0)s.set(l.atEnd);else for(let o=0;o<t;o++)s[o]&=l.atEnd[o];continue}let f=e[c],p=f.typeId,h=p>=0&&p<this.typeRows?p*t:-1;if(u===0)if(h>=0)for(let o=0;o<t;o++)s[o]=l.byType[h+o]|l.typeAny[o];else s.set(l.typeAny);else if(h>=0)for(let o=0;o<t;o++)s[o]&=l.byType[h+o]|l.typeAny[o];else for(let o=0;o<t;o++)s[o]&=l.typeAny[o];if(h>=0&&l.typeHasValues[p]===1){let o=f.value,R=O(o)?o.toLowerCase():o,g=l.byValue.get(R);for(let T=0;T<t;T++)s[T]&=(g===void 0?0:g[T])|l.valueAny[T];}if(S(s))return s}return s}};function S(a){for(let e=0;e<a.length;e++)if(a[e]!==0)return false;return true}function O(a){for(let e=0;e<a.length;e++){let r=a.charCodeAt(e);if(r>=65&&r<=90)return true}return false}var B={maxPasses:100,maxTokens:1e4,onFusion:()=>{},ignoreRuleIndex:false};function C(a,e,r){let t=r[0],s=r[r.length-1],n=new chunkWU7SBKVU_cjs.a(a,chunkYBQOQTVL_cjs.c(a),e,e,t.offset,t.lineBreaks??0,t.line,t.col);return n.sourceEnd=s.sourceEnd??s.offset+s.text.length,n}function z(a,e){let r=e[e.length-1];r&&(a.sourceEnd=r.sourceEnd??r.offset+r.text.length);}var _=["NUMBER","HEX","BIGINT","FLOAT","LSHIFT","RSHIFT","BIT_AND","BIT_OR","BIT_XOR","LPAREN","RPAREN","LBRACKET","RBRACKET","COMMA","COLON","EQUALS","THEREFORE","PIPE","AMPERSAND","AT","SEMICOLON","QUESTION","EXCLAMATION","EOF","WS","NEWLINE"],M=(()=>{let a=_.map(t=>chunkYBQOQTVL_cjs.c(t)),e=Math.max(...a)+1,r=new Uint8Array(e);for(let t of a)r[t]=1;return r})(),P=new Set;function D(a){a.shape!==void 0&&a.shape.length>0||a.startTokenTypes===void 0&&a.unshapedReason===void 0&&(P.has(a.name)||(P.add(a.name),console.warn(`[TokenNormalizer] Rule "${a.name}" declares no \`shape\`, so it is tried at every token of every line and slows down documents that never use it. Declare the tokens it can start at, e.g. shape: [{ types: ["IDENT"], values: ["myword"] }, { types: ["LPAREN"] }]. If it genuinely cannot be described that way, set \`unshapedReason\` to say why and this warning will stop.`)));}var U=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.rulesByTokenType=new Map;this.ruleIndexCache=null;this.candidateBuffer=[];this.normalizeCalls=0;this.phraseTrie=new w;this.ruleShapesCache=null;this.options={...B,...e};}register(e){D(e),this.rules.push(e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}unregister(e){this.rules=this.rules.filter(r=>r.name!==e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}clear(){this.rules=[],this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null,this.phraseTrie=new w;}getSortedRules(){return this.sortedRulesCache===null&&(this.sortedRulesCache=[...this.rules].sort((e,r)=>r.priority-e.priority)),this.sortedRulesCache}getRuleIndex(){return this.ruleIndexCache===null&&(this.ruleIndexCache=new x(this.getSortedRules())),this.ruleIndexCache}rulesAt(e,r){if(e===null)return this.options.ignoreRuleIndex?this.getSortedRules():this.rulesForTokenType(r);let t=this.candidateBuffer;t.length=0;let s=this.getRuleIndex().rules;for(let n=0;n<e.length;n++){let i=e[n]>>>0,u=n*32;for(;i!==0;)(i&1)!==0&&t.push(s[u]),i>>>=1,u++;}return t}rulesForTokenType(e){let r=this.rulesByTokenType.get(e);return r===void 0&&(r=this.getSortedRules().filter(t=>{let s=v(t)[0];return s?.types===void 0||s.types.includes(e)}),this.rulesByTokenType.set(e,r)),r}get ruleCount(){return this.rules.length}getRuleShapes(){if(this.ruleShapesCache!==null)return this.ruleShapesCache;let e=this.getRuleIndex();return this.ruleShapesCache=this.getSortedRules().map(r=>{let t=v(r);return {name:r.name,priority:r.priority,shape:t,unshapedReason:r.unshapedReason,indexedSlots:Math.min(t.length,e.depth)}}),this.ruleShapesCache}getCandidateCounts(e){let r=this.getRuleIndex(),t=[];for(let s=0;s<e.length;s++){let n=r.candidates(e,s),i=0;for(let u=0;u<n.length;u++){let l=n[u]>>>0;for(;l!==0;)i+=l&1,l>>>=1;}t.push(i);}return t}addPhrase(e,r){this.phraseTrie.addPhrase(e,r);}getPhrases(){return this.phraseTrie.getAllPhrases()}canStartPhrase(e){return this.phraseTrie.canStart(e)}normalize(e,r){if(e.length===0)return e;let t=r??this.options.onFusion,s=this.options.maxPasses,n=this.options.maxTokens,i=this.normalizeCalls>0;i||(this.normalizeCalls=1);let u=i&&!this.options.ignoreRuleIndex,l=u?this.getRuleIndex():null,c=e,f=true,p=0;for(;f&&p<s;){f=false,p++;let h=null,o=0;for(;o<c.length;){let g=false,T=c[o].typeId;if(T>=M.length||M[T]===0){let m=this.phraseTrie.matchAt(c,o);if(m){let d=c.slice(o,o+m.consumed);h===null&&(h=c.slice(0,o));for(let A of m.replacement)h.push(A);m.consumed>1&&m.replacement.length===1&&(z(m.replacement[0],d),t({rule:m.ruleName??"phrase-trie",sourceTokens:d,fusedToken:m.replacement[0]})),o+=m.consumed,f=true;continue}}let I=u?l.candidates(c,o):null;if(I!==null&&S(I)){h!==null&&h.push(c[o]),o++;continue}for(let m of this.rulesAt(I,c[o].type)){let d=m.match(c,o);if(d){let A=c.slice(o,o+d.consumed);h===null&&(h=c.slice(0,o));for(let b of d.replacement)h.push(b);if(d.consumed>1&&d.replacement.length===1)z(d.replacement[0],A),t({rule:m.name,sourceTokens:A,fusedToken:d.replacement[0]});else if(d.consumed>1&&d.replacement.length<d.consumed)for(let b of d.replacement)t({rule:m.name,sourceTokens:A,fusedToken:b});o+=d.consumed,f=true,g=true;break}}g||(h!==null&&h.push(c[o]),o++);}if(h===null)break;let R=h;if(R.length>n)throw chunkSUAGBRQ7_cjs.c.validation("NORMALIZED_TOKEN_LIMIT_EXCEEDED",`Normalized token count (${R.length}) exceeds safety limit (${n})`,{tokenCount:R.length,maxTokens:n});c=R;}return c}};var w=class{constructor(){this.startWords=new Set;this.root=new Map;}addPhrase(e,r){let t=e.toLowerCase().trim().split(/\s+/);if(t.length===0||t[0]==="")return;this.startWords.add(t[0]);let s=t[0],n;if(this.root.has(s)?n=this.root.get(s):(n={children:new Map,terminal:null},this.root.set(s,n)),t.length===1){n.terminal={tokenType:r,phrase:e,consumed:1};return}for(let i=1;i<t.length;i++){let u=t[i];n.children.has(u)||n.children.set(u,{children:new Map,terminal:null}),n=n.children.get(u);}n.terminal={tokenType:r,phrase:e,consumed:t.length};}matchAt(e,r){if(r>=e.length)return null;let t=e[r].type;if(t==="TAG"||t.startsWith("TAG_"))return null;let s=e[r].value.toLowerCase();if(!this.startWords.has(s))return null;let n=this.root.get(s);if(!n)return null;let i=null,u=1;if(n.terminal){let l=e.slice(r,r+1);i={consumed:1,replacement:[C(n.terminal.tokenType,n.terminal.phrase,l)],ruleName:n.terminal.phrase};}for(let l=r+1;l<e.length&&n?.children;l++){let c=e[l].type;if(c==="TAG"||c.startsWith("TAG_"))break;let f=e[l].value.toLowerCase();if(n=n.children.get(f),!n)break;if(u++,n.terminal){let p=e.slice(r,r+u);i={consumed:u,replacement:[C(n.terminal.tokenType,n.terminal.phrase,p)],ruleName:n.terminal.phrase};}}return i}get size(){return this.root.size}getAllPhrases(){let e={},r=(t,s)=>{t.terminal&&(e[s.join(" ")]=t.terminal.tokenType);for(let[n,i]of t.children)r(i,[...s,n]);};for(let[t,s]of this.root)r(s,[t]);return e}canStart(e){return this.startWords.has(e.toLowerCase())}};var F=new Set(["per","a","an","each","every"]),W=new Set(["to","power","increase","decrease","times","multiply","divide","by"]);function H(a=50,e){let r=e??(t=>W.has(t.toLowerCase()));return {name:"implicit:multiply",priority:a,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT","LPAREN","PI","E"]}],match(t,s){if(s+1>=t.length)return null;let n=t[s],i=t[s+1];if(!((n.type==="NUMBER"||n.type==="RPAREN")&&(i.type==="IDENT"||i.type==="LPAREN"||i.type==="PI"||i.type==="E")))return null;let l=i.value.toLowerCase();if(r(l)||F.has(l)&&t[s+2]?.type==="UNIT")return null;let c=new chunkWU7SBKVU_cjs.a("STAR",chunkYBQOQTVL_cjs.c("STAR"),"*","*",i.offset,0,i.line,i.col);return {consumed:1,replacement:[n,c]}}}}function ne(a,e){let r=[];for(let t=0;t<e;t++){let s=a[t];if(s.type==="LBRACKET")r.push(true);else if(s.type==="LPAREN"){let n=a[t-1],i=!!n&&(n.type==="MAP"||n.type==="REDUCE"||n.type==="SUM_FN"||n.type==="PROD_FN"||n.type==="IDENT"&&(n.value.toLowerCase()==="map"||n.value.toLowerCase()==="reduce"||n.value.toLowerCase()==="sum"||n.value.toLowerCase()==="prod"));r.push(i);}else (s.type==="RBRACKET"||s.type==="RPAREN")&&r.pop();}return r.length>0&&r[r.length-1]}function re(){return [H()]}exports.a=w;exports.b=C;exports.c=U;exports.d=H;exports.e=ne;exports.f=re;//# sourceMappingURL=chunk-4DR5RBHQ.cjs.map
2
- //# sourceMappingURL=chunk-4DR5RBHQ.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/normalizer/RuleIndex.ts","../src/normalizer/TokenNormalizer.ts","../src/normalizer/PhraseTrie.ts","../src/normalizer/BuiltinNormalizerRules.ts"],"names":["WORD_BITS","MAX_PLANES","effectiveShape","rule","RuleIndex","sortedRules","n","w","shapes","maxTypeId","shape","slot","t","tokenTypeId","depth","i","planes","k","plane","word","bit","types","values","raw","value","mask","id","tokens","pos","scratch","len","at","token","typeId","base","lowered","hasUpper","named","isEmptyMask","c","DEFAULT_OPTIONS","createFusedToken","type","text","sourceTokens","first","last","LexerToken","recordSourceSpan","fused","NON_WORD_NAMES","NON_WORD_TABLE","ids","table","warnedUnshapedRules","warnIfUnshaped","TokenNormalizer","options","PhraseTrie","ruleName","a","b","buffer","rules","bits","index","list","counts","phrase","tokenType","onFusion","fusionHandler","maxPasses","maxTokens","warmedUp","useIndex","ruleIndex","current","changed","passCount","result","matched","tid","trieMatch","rt","candidates","match","passResult","ErrorFactory","words","firstWord","node","startType","best","contType","collect","path","child","RATE_DENOMINATOR_WORDS","PHRASE_START_WORDS","implicitMultiplyRule","priority","canStart","phraseGuard","next","nextValue","starToken","isInsideRangeContext","safeStack","prev","opensMapReduceCall","createBuiltinNormalizerRules"],"mappings":"uKAiEA,IAAMA,CAAAA,CAAY,EAAA,CAeZC,CAAAA,CAAa,CAAA,CASZ,SAASC,CAAAA,CAAeC,CAAAA,CAA2C,CACzE,OAAIA,CAAAA,CAAK,KAAA,GAAU,MAAA,CAAkBA,EAAK,KAAA,CACtCA,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CAAA,CAAA,KAAA,GACVhG,CAAAA,CAAE,OAAS,QAAA,CAAU,CAC9B,IAAMiG,CAAAA,CAAOlF,CAAAA,CAAOZ,CAAAA,CAAI,CAAC,CAAA,CACnB+F,EAAqB,CAAC,CAACD,CAAAA,GAC3BA,CAAAA,CAAK,IAAA,GAAS,KAAA,EAASA,CAAAA,CAAK,IAAA,GAAS,QAAA,EAAYA,CAAAA,CAAK,IAAA,GAAS,QAAA,EAAYA,CAAAA,CAAK,IAAA,GAAS,SAAA,EACxFA,CAAAA,CAAK,OAAS,OAAA,GAAYA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,KAAA,CAAM,aAAY,GAAM,QAAA,EAAYA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,MAAM,WAAA,EAAY,GAAM,MAAA,CAAA,CAAA,CAE/KD,CAAAA,CAAU,IAAA,CAAKE,CAAkB,EACnC,CAAA,KAAA,CAAWlG,CAAAA,CAAE,IAAA,GAAS,UAAA,EAAcA,CAAAA,CAAE,IAAA,GAAS,QAAA,GAC7CgG,CAAAA,CAAU,GAAA,GAEd,CACA,OAAOA,CAAAA,CAAU,MAAA,CAAS,CAAA,EAAKA,CAAAA,CAAUA,CAAAA,CAAU,MAAA,CAAS,CAAC,CAC/D,CAoBO,SAASG,EAAAA,EAAiD,CAC/D,OAAO,CAELX,CAAAA,EACF,CACF","file":"chunk-4DR5RBHQ.cjs","sourcesContent":["//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * RuleIndex, a conjunctive bitmask prefilter over the normalizer's rules.\n *\n * ## Problem\n * The normalizer tries every rule eligible at a position, at every position.\n * The `startTokenTypes` hint buckets rules by the type of the token they start\n * at, which helps only where that type is selective. It is not: the thirteen\n * call-fusion rules all declare `[\"IDENT\"]`, the commonest token in prose, and\n * the rules firing on a bare `NUMBER` all share that one type too. Measured\n * against the built-in package set, the `IDENT` bucket held 53 of 57 rules and\n * the `NUMBER` bucket 45, because a rule declaring no hint has to be tried\n * everywhere.\n *\n * ## Solution\n * Rules discriminate on different things, so no single axis separates them.\n * A rule declares its leading {@link RuleSlot} shape, and this builds one\n * lookup plane per slot: a flat `Uint32Array` of rule bitmasks indexed by token\n * type id, so a lookup is an array load rather than a hash. A position ANDs the\n * planes together and iterates only the surviving bits, which for most\n * positions is none at all.\n *\n * Rejecting a position therefore costs a few loads and ANDs instead of\n * forty-odd closure calls, and one AND tests 32 rules at once. That the common\n * answer is \"no rule can fire here\" is the point.\n *\n * ## Why planes rather than a fingerprint\n * A superimposed code (OR the hashed types of a window into one word, AND\n * against a per-rule required fingerprint) looks like the cheaper way to reach\n * depth, but it is a per-RULE test with no way to invert it into a lookup, so\n * it stays O(rules) per position. These planes are the same conjunctive test\n * done exactly, at O(rules / 32) and with no false positives. Token types\n * number a couple of hundred, small enough to table, so there is nothing to\n * gain by approximating.\n *\n * ## Ordering\n * Bit `i` is the rule at index `i` of the priority-sorted rule list, so\n * iterating bits from low to high visits rules in exactly the order the\n * unindexed scan did. Ties keep registration order, because the sort is stable.\n * This is what makes the index a pure filter rather than a behaviour change,\n * and `NormalizerIndexFidelity.spec` pins it.\n *\n * ## Safety\n * The contract runs one way: a slot admitting MORE than the rule can match\n * costs a `match()` that returns null, which is what happens today; a slot\n * admitting LESS makes the rule unreachable, a silent bug. So indexing fewer\n * planes than were declared is always safe, which is why {@link MAX_PLANES}\n * can be tuned on evidence rather than being a correctness decision. Only\n * over-narrow declarations are dangerous, and those are what the fidelity spec\n * hunts for.\n *\n * @module RuleIndex\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { NormalizerRule, RuleSlot } from \"./NormalizerRule\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n//#endregion\n//#region ─── Constants ────────────────────────────────────────────────────────\n\n/** Bits per word in the masks below. */\nconst WORD_BITS = 32;\n\n/**\n * How many leading slots are indexed, however many a rule declares.\n *\n * Each plane costs a load and an AND at every position, unconditionally, while\n * only positions surviving the earlier planes can benefit from a later one.\n * After two planes most positions have no candidates left, so a third would tax\n * every token to save a couple of `match()` calls on the few that reach it.\n *\n * Two is a measured default, not a limit of the design: raising it is a\n * one-line change, and lowering it can never break a rule (see this module's\n * Safety note). Rules may declare deeper shapes freely; the extra slots simply\n * go unindexed and are checked by `match()` as before.\n */\nconst MAX_PLANES = 2;\n\n//#endregion\n//#region ─── Shape normalisation ──────────────────────────────────────────────\n\n/**\n * A rule's effective shape, folding the older {@link NormalizerRule.startTokenTypes}\n * into the general form. `shape` wins when both are present.\n */\nexport function effectiveShape(rule: NormalizerRule): readonly RuleSlot[] {\n\tif (rule.shape !== undefined) return rule.shape;\n\tif (rule.startTokenTypes !== undefined) return [{ types: rule.startTokenTypes }];\n\treturn [];\n}\n\n//#endregion\n//#region ─── RuleIndex ────────────────────────────────────────────────────────\n\n/** One indexed slot position: the type plane, plus the value axis for it. */\ninterface Plane {\n\t/** `[typeId * words + w]`, rules whose slot admits `typeId`. */\n\treadonly byType: Uint32Array;\n\t/** Rules constraining no type here, admitted at a type with no row. */\n\treadonly typeAny: Uint32Array;\n\t/**\n\t * Rules constraining no type here, and so the only ones still admissible\n\t * when the stream ends before this slot.\n\t */\n\treadonly atEnd: Uint32Array;\n\t/** `[typeId]`, 1 when a value-constraining rule admits this type here. */\n\treadonly typeHasValues: Uint8Array;\n\t/** Lower-cased word to the rules naming it at this slot. */\n\treadonly byValue: Map<string, Uint32Array>;\n\t/** Rules constraining no value here. */\n\treadonly valueAny: Uint32Array;\n}\n\n/**\n * A conjunctive bitmask prefilter over a priority-sorted rule list.\n *\n * Built once per rule-set mutation (registration time), then read only. See\n * this module's overview for the shape and the ordering guarantee.\n */\nexport class RuleIndex {\n\t/** The priority-sorted rules. Bit `i` of every mask refers to `rules[i]`. */\n\treadonly rules: readonly NormalizerRule[];\n\n\t/** Words per mask, `ceil(rules.length / 32)`. */\n\treadonly words: number;\n\n\t/** Number of token type ids with their own row, exclusive upper bound. */\n\tprivate readonly typeRows: number;\n\n\t/** One per indexed slot, at most {@link MAX_PLANES}. */\n\tprivate readonly planes: readonly Plane[];\n\n\t/** Reused across positions so the hot path allocates nothing. */\n\tprivate readonly scratch: Uint32Array;\n\n\t/**\n\t * Every rule's bit set.\n\t *\n\t * Returned when there are no planes at all, which happens when no rule\n\t * declares a shape. Without it {@link candidates} would hand back an\n\t * unwritten scratch buffer, i.e. \"no rule can fire anywhere\", and every\n\t * rule would silently stop running. The all-admitted answer is the correct\n\t * one: a rule that constrains nothing can match anywhere.\n\t */\n\tprivate readonly allRules: Uint32Array;\n\n\tconstructor(sortedRules: readonly NormalizerRule[]) {\n\t\tthis.rules = sortedRules;\n\t\tconst n = sortedRules.length;\n\t\tconst w = Math.max(1, Math.ceil(n / WORD_BITS));\n\t\tthis.words = w;\n\t\tthis.scratch = new Uint32Array(w);\n\n\t\tconst shapes = sortedRules.map(effectiveShape);\n\n\t\t// Size the type-indexed rows to cover every type any rule names. A token\n\t\t// whose id lands past this (a plugin type minted after the index was\n\t\t// built, say) falls back to the \"constrains nothing\" masks, which is\n\t\t// correct rather than merely safe: a rule naming types cannot match a\n\t\t// type it did not name, and a rule naming none can match anywhere.\n\t\tlet maxTypeId = 0;\n\t\tfor (const shape of shapes) {\n\t\t\tfor (const slot of shape) {\n\t\t\t\tfor (const t of slot.types ?? []) maxTypeId = Math.max(maxTypeId, tokenTypeId(t));\n\t\t\t}\n\t\t}\n\t\tthis.typeRows = maxTypeId + 1;\n\n\t\tlet depth = 0;\n\t\tfor (const shape of shapes) depth = Math.max(depth, shape.length);\n\t\tdepth = Math.min(depth, MAX_PLANES);\n\n\t\tthis.allRules = new Uint32Array(w);\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tthis.allRules[(i / WORD_BITS) | 0] |= 1 << (i % WORD_BITS);\n\t\t}\n\n\t\tconst planes: Plane[] = [];\n\t\tfor (let k = 0; k < depth; k++) {\n\t\t\tplanes.push(this.buildPlane(shapes, k, w));\n\t\t}\n\t\tthis.planes = planes;\n\t}\n\n\t/** Build the lookup plane for slot `k`. */\n\tprivate buildPlane(shapes: readonly (readonly RuleSlot[])[], k: number, w: number): Plane {\n\t\tconst plane: Plane = {\n\t\t\tbyType: new Uint32Array(this.typeRows * w),\n\t\t\ttypeAny: new Uint32Array(w),\n\t\t\tatEnd: new Uint32Array(w),\n\t\t\ttypeHasValues: new Uint8Array(this.typeRows),\n\t\t\tbyValue: new Map<string, Uint32Array>(),\n\t\t\tvalueAny: new Uint32Array(w),\n\t\t};\n\n\t\tfor (let i = 0; i < shapes.length; i++) {\n\t\t\tconst slot: RuleSlot | undefined = shapes[i][k];\n\t\t\tconst word = (i / WORD_BITS) | 0;\n\t\t\tconst bit = 1 << (i % WORD_BITS);\n\n\t\t\t// ── Types ──\n\t\t\tconst types = slot?.types;\n\t\t\tif (types === undefined) {\n\t\t\t\t// Constrains nothing here, so admitted at every type, at a type\n\t\t\t\t// with no row, and past the end of the stream.\n\t\t\t\t//\n\t\t\t\t// Deliberately NOT written into every row of `byType`. Doing that\n\t\t\t\t// made construction O(rules x tokenTypes), tens of thousands of\n\t\t\t\t// writes for a table most of which is the same bit, and the\n\t\t\t\t// engine builds an index per instance: a cold parse of a short\n\t\t\t\t// document paid for it without ever amortising it. The lookup\n\t\t\t\t// ORs `typeAny` in instead, which is one extra operation per word\n\t\t\t\t// on a path that already does several.\n\t\t\t\tplane.typeAny[word] |= bit;\n\t\t\t\tplane.atEnd[word] |= bit;\n\t\t\t} else {\n\t\t\t\tfor (const t of types) plane.byType[tokenTypeId(t) * w + word] |= bit;\n\t\t\t}\n\n\t\t\t// ── Values ──\n\t\t\tconst values = slot?.values;\n\t\t\tif (values === undefined) {\n\t\t\t\tplane.valueAny[word] |= bit;\n\t\t\t} else {\n\t\t\t\tfor (const raw of values) {\n\t\t\t\t\tconst value = raw.toLowerCase();\n\t\t\t\t\tlet mask = plane.byValue.get(value);\n\t\t\t\t\tif (mask === undefined) {\n\t\t\t\t\t\tmask = new Uint32Array(w);\n\t\t\t\t\t\tplane.byValue.set(value, mask);\n\t\t\t\t\t}\n\t\t\t\t\tmask[word] |= bit;\n\t\t\t\t}\n\t\t\t\t// The value axis is only worth a map lookup at a type some\n\t\t\t\t// value-constraining rule admits here.\n\t\t\t\tif (types === undefined) {\n\t\t\t\t\tplane.typeHasValues.fill(1);\n\t\t\t\t} else {\n\t\t\t\t\tfor (const t of types) {\n\t\t\t\t\t\tconst id = tokenTypeId(t);\n\t\t\t\t\t\tif (id < this.typeRows) plane.typeHasValues[id] = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn plane;\n\t}\n\n\t/** Number of indexed rules. */\n\tget size(): number { return this.rules.length; }\n\n\t/** How many slot positions are indexed. */\n\tget depth(): number { return this.planes.length; }\n\n\t/**\n\t * The candidate mask for a position, written into a reused scratch buffer\n\t * and returned. Bits are rule indices, ascending bit order being descending\n\t * priority. The buffer is overwritten by the next call, so read it before\n\t * calling again.\n\t *\n\t * @param tokens - The stream being walked\n\t * @param pos - The position to test\n\t */\n\tcandidates(tokens: readonly { typeId: number; value: string }[], pos: number): Uint32Array {\n\t\tconst w = this.words;\n\t\tconst scratch = this.scratch;\n\t\tconst planes = this.planes;\n\t\tconst len = tokens.length;\n\n\t\tif (planes.length === 0) {\n\t\t\tscratch.set(this.allRules);\n\t\t\treturn scratch;\n\t\t}\n\n\t\tfor (let k = 0; k < planes.length; k++) {\n\t\t\tconst plane = planes[k];\n\t\t\tconst at = pos + k;\n\n\t\t\tif (at >= len) {\n\t\t\t\t// The stream ends before this slot, so only rules that constrain\n\t\t\t\t// nothing here remain admissible.\n\t\t\t\tif (k === 0) { scratch.set(plane.atEnd); }\n\t\t\t\telse { for (let i = 0; i < w; i++) scratch[i] &= plane.atEnd[i]; }\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst token = tokens[at];\n\t\t\tconst typeId = token.typeId;\n\t\t\tconst base = typeId >= 0 && typeId < this.typeRows ? typeId * w : -1;\n\n\t\t\t// `typeAny` holds the rules that constrain no type at this slot, so\n\t\t\t// they are admitted whatever the token is; see the construction note.\n\t\t\tif (k === 0) {\n\t\t\t\tif (base >= 0) { for (let i = 0; i < w; i++) scratch[i] = plane.byType[base + i] | plane.typeAny[i]; }\n\t\t\t\telse { scratch.set(plane.typeAny); }\n\t\t\t} else {\n\t\t\t\tif (base >= 0) { for (let i = 0; i < w; i++) scratch[i] &= plane.byType[base + i] | plane.typeAny[i]; }\n\t\t\t\telse { for (let i = 0; i < w; i++) scratch[i] &= plane.typeAny[i]; }\n\t\t\t}\n\n\t\t\t// The value axis costs a map lookup and possibly a lower-casing, so\n\t\t\t// it is consulted only at a type some value-constraining rule names.\n\t\t\tif (base >= 0 && plane.typeHasValues[typeId] === 1) {\n\t\t\t\tconst value = token.value;\n\t\t\t\tconst lowered = hasUpper(value) ? value.toLowerCase() : value;\n\t\t\t\tconst named = plane.byValue.get(lowered);\n\t\t\t\tfor (let i = 0; i < w; i++) {\n\t\t\t\t\tscratch[i] &= (named === undefined ? 0 : named[i]) | plane.valueAny[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isEmptyMask(scratch)) return scratch;\n\t\t}\n\n\t\treturn scratch;\n\t}\n}\n\n/** Whether every bit of a mask returned by {@link RuleIndex.candidates} is clear. */\nexport function isEmptyMask(mask: Uint32Array): boolean {\n\tfor (let i = 0; i < mask.length; i++) if (mask[i] !== 0) return false;\n\treturn true;\n}\n\n/**\n * Whether a string contains an ASCII upper-case letter.\n *\n * `toLowerCase()` allocates even when it changes nothing, and identifiers in\n * running prose are overwhelmingly already lower case, so this scan pays for\n * itself by skipping the allocation in the common case.\n */\nfunction hasUpper(value: string): boolean {\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst c = value.charCodeAt(i);\n\t\tif (c >= 65 && c <= 90) return true;\n\t}\n\treturn false;\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * TokenNormalizer, post-lexer token normalization pass.\n *\n * ## Purpose\n * Applies domain-specific {@link NormalizerRule | NormalizerRules} to the raw\n * token stream produced by the {@link ExpressionLexer}. This keeps the lexer\n * slim and focused on single-token production, while multi-token pattern\n * matching (phrases, implicit operators, domain merges) lives here.\n *\n * ## What rules can do\n * - **Phrase fusion**: Merge consecutive words into compound tokens\n * (e.g., `IDENT + ... + IDENT` → `CARET`)\n * - **Implicit operator insertion**: Insert missing operators between tokens\n * (e.g., `NUMBER IDENT` → `NUMBER STAR IDENT`)\n * - **Domain-specific transformations**: Coalesce item names, currency pairs,\n * percentage syntax, etc.\n *\n * ## Architecture\n * Providers register NormalizerRules alongside Parselets and OpCode handlers\n * via {@link IEnginePackage.normalizerRules}. The normalizer applies them\n * greedily left-to-right in multiple passes with safety limits.\n *\n * @module TokenNormalizer\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, RuleSlot, TokenFusion } from \"./NormalizerRule\";\nimport { PhraseTrie } from \"./PhraseTrie\";\nimport { RuleIndex, isEmptyMask, effectiveShape } from \"./RuleIndex\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n//#endregion\n//#region ─── NormalizerOptions, Configuration ────────────────────────────────\n\n/**\n * Configuration options for the normalization pass.\n *\n * These control safety limits and diagnostic callbacks. The defaults\n * are chosen to be generous enough for any realistic expression while\n * preventing runaway token expansion from recursive rules.\n */\nexport interface NormalizerOptions {\n /**\n * Maximum number of full passes over the token stream before bailing out.\n * Prevents infinite loops from recursive rule chains.\n * @default 100\n */\n maxPasses?: number;\n\n /**\n * Maximum number of tokens allowed after normalization.\n * If exceeded, an Error is thrown rather than passing a bloated stream\n * to the parser.\n * @default 10000\n */\n maxTokens?: number;\n\n /**\n * Callback invoked for each fusion event during normalization.\n * Used by diagnostic mode to populate {@link NormalizerOutput.fusions}.\n * When `undefined`, fusions are still tracked internally but no callbacks fire.\n */\n onFusion?: (fusion: TokenFusion) => void;\n\n /**\n * Try every registered rule at every position, ignoring both the shape\n * index and the first-token buckets the first call uses.\n *\n * Diagnostic only, and much slower. It exists so the filtered walks can be\n * compared against the exhaustive one over a corpus: each filter is pure,\n * so all of them must agree token for token, and a rule whose declared\n * {@link NormalizerRule.shape} is too narrow shows up as a difference rather\n * than as a feature that quietly stopped working.\n * `NormalizerIndexFidelity.spec` and `RuleHintsMatchGuards.spec` are the\n * consumers.\n *\n * @default false\n */\n ignoreRuleIndex?: boolean;\n}\n\n//#endregion\n//#region ─── Default Options ──────────────────────────────────────────────────\n\n/** Sensible defaults that catch infinite loops without limiting real expressions. */\nconst DEFAULT_OPTIONS: Required<NormalizerOptions> = {\n maxPasses: 100,\n maxTokens: 10000,\n onFusion: () => {},\n ignoreRuleIndex: false,\n};\n\n//#endregion\n//#region ─── createFusedToken, Token Factory ──────────────────────────────────\n\n/**\n * Creates a new normalized token from fused source tokens.\n *\n * The fused token inherits position information (offset, line, column)\n * from the first source token, which preserves source-map accuracy\n * for error messages and diagnostic highlighting.\n *\n * It also records where the source text ENDS, on `sourceEnd`. The start alone\n * is not enough to describe the span a fusion covers, because `text` is the\n * replacement rather than the original: `10 frames` fuses into a FRAME_COUNT\n * whose text is `10`, and a timecode fuses into a token whose text is a\n * comma-separated tuple that appears nowhere in the line. Anything painting the\n * line needs both ends, and only this function is in a position to know them.\n *\n * @param type - The new token type (e.g., \"CARET\", \"TIMES_BY\")\n * @param text - The combined text representation (e.g., \"to the power of\")\n * @param sourceTokens - The original tokens being fused (at least 2)\n * @returns A new {@link LexerToken} with the fused type and combined text\n */\nexport function createFusedToken(\n type: string,\n text: string,\n sourceTokens: Token[]\n): Token {\n const first = sourceTokens[0];\n const last = sourceTokens[sourceTokens.length - 1];\n const token = new LexerToken(\n type,\n tokenTypeId(type),\n text,\n text,\n first.offset,\n first.lineBreaks ?? 0,\n first.line,\n first.col,\n );\n // `text`, not `value`: this is where the SOURCE ended, and the two differ\n // for a string literal, whose value is the payload without its quotes.\n token.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n return token;\n}\n\n/**\n * Record, on a token that replaced several, where its source text ended.\n *\n * Called centrally rather than left to each rule. A rule that builds its\n * replacement by hand rather than through {@link createFusedToken} is doing\n * nothing wrong, and several do: the date-literal rule needs a token whose\n * value is an epoch and whose text is the source, which that factory cannot\n * express. Stamping here means every fusion carries its span, including ones\n * written after this was.\n *\n * Reads `sourceEnd` off the last source token when it has one, so a fusion of\n * a fusion still describes the original text rather than the intermediate.\n *\n * @param fused - The single token the rule produced.\n * @param sourceTokens - The tokens it consumed.\n */\nfunction recordSourceSpan(fused: Token, sourceTokens: Token[]): void {\n const last = sourceTokens[sourceTokens.length - 1];\n if (!last) return;\n fused.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n}\n\n//#endregion\n//#region ─── NON_WORD_TOKEN_TYPES, Type-guard skip set ────────────────────────\n\n/**\n * Token types that can NEVER start a multi-word phrase.\n *\n * Used by {@link normalize} to skip the PhraseTrie walk entirely at\n * positions where the token type makes phrase matching impossible.\n * This avoids even the O(1) {@link PhraseTrie.canStart} check.\n *\n * Types NOT in this set (IDENT, KEYWORD, FUNC, UNIT, and any custom\n * types registered by packages) still pass through to the trie for\n * a full match attempt.\n */\n// ── Non-word type ID lookup table (flat Uint8Array, true O(1) array index) ──\n//\n// Index = token typeId, value = 1 if non-word (skip trie), 0 otherwise.\n// Array indexing avoids ALL hashing: no Set.has(), no Map.get(), no string ops.\n//\n// Custom types from packages get IDs beyond the table length, so the bounds\n// check `tid < TABLE.length` safely passes them through to the trie.\n//\n// Arithmetic operators (PLUS, MINUS, STAR, SLASH, CARET, MOD, PERCENT) are\n// intentionally excluded: in keyword locales the lexer maps \"times\"→STAR,\n// \"divide\"→SLASH etc., and those tokens CAN start phrases like \"times by\".\n/**\n * Token type names that can NEVER start a multi-word phrase.\n *\n * Exported for testing only, consumers should use the type-guard behavior\n * of {@link TokenNormalizer.normalize} rather than this list directly.\n */\nexport const NON_WORD_NAMES = [\n\t\"NUMBER\", \"HEX\", \"BIGINT\", \"FLOAT\",\n\t\"LSHIFT\", \"RSHIFT\", \"BIT_AND\", \"BIT_OR\", \"BIT_XOR\",\n\t\"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\",\n\t\"COMMA\", \"COLON\", \"EQUALS\", \"THEREFORE\", \"PIPE\", \"AMPERSAND\", \"AT\",\n\t\"SEMICOLON\", \"QUESTION\", \"EXCLAMATION\",\n\t\"EOF\", \"WS\", \"NEWLINE\",\n] as const;\n\n/**\n * Flat Uint8Array lookup table: index = token typeId, value = 1 if non-word.\n *\n * Exported for testing only, consumers should not depend on the internal\n * table layout, as the set of non-word types may change.\n */\nexport const NON_WORD_TABLE: Uint8Array = (() => {\n\t// Resolve all non-word type names to their numeric IDs\n\tconst ids = NON_WORD_NAMES.map(n => tokenTypeId(n));\n\t// Size the table to cover the largest ID + 1\n\tconst len = Math.max(...ids) + 1;\n\tconst table = new Uint8Array(len);\n\t// Mark non-word type positions\n\tfor (const id of ids) table[id] = 1;\n\treturn table;\n})();\n\n//#endregion\n//#region ─── TokenNormalizer Class ─────────────────────────────────────────────\n\n/**\n * Rule names already warned about, so a rule registered into many engines\n * says it once rather than once per engine.\n */\nconst warnedUnshapedRules = new Set<string>();\n\n/**\n * Warn when a rule declares neither a shape nor a reason for not having one.\n *\n * An unshaped rule is tried at every position of every line, so its cost is\n * paid by every document rather than only by the feature it implements. The\n * warning names the rule and points at the two ways out, and it fires once per\n * rule name per process: a warning a package author sees on every engine they\n * construct is one they learn to filter out, which would make it worse than\n * useless.\n *\n * Deliberately not an error. A rule without a shape is correct, only slower,\n * and refusing to register it would break every package written before the\n * field existed.\n */\nfunction warnIfUnshaped(rule: NormalizerRule): void {\n if (rule.shape !== undefined && rule.shape.length > 0) return;\n if (rule.startTokenTypes !== undefined) return;\n if (rule.unshapedReason !== undefined) return;\n if (warnedUnshapedRules.has(rule.name)) return;\n warnedUnshapedRules.add(rule.name);\n console.warn(\n `[TokenNormalizer] Rule \"${rule.name}\" declares no \\`shape\\`, so it is tried at every ` +\n `token of every line and slows down documents that never use it. Declare the tokens it ` +\n `can start at, e.g. shape: [{ types: [\"IDENT\"], values: [\"myword\"] }, { types: [\"LPAREN\"] }]. ` +\n `If it genuinely cannot be described that way, set \\`unshapedReason\\` to say why and this ` +\n `warning will stop.`,\n );\n}\n\n/**\n * Token normalizer: applies {@link NormalizerRule | NormalizerRules} to a token stream.\n *\n * ## Lifecycle\n * 1. **Registration**: Rules are added via {@link register} and sorted by priority\n * 2. **Normalization**: {@link normalize} applies rules greedily left-to-right\n * 3. **Cleanup**: {@link clear} or {@link unregister} removes rules\n *\n * ## Normalization algorithm\n * The normalizer uses a greedy left-to-right multi-pass algorithm:\n * - At each token position, rules are tried in priority order (highest first)\n * - When a rule matches, matched tokens are consumed and replaced\n * - Processing continues from the replacement position\n * - Multiple passes handle cascading matches (one rule's output triggers another)\n * - Safety limits ({@link NormalizerOptions.maxPasses}) prevent infinite loops\n *\n * @example\n * ```ts\n * const normalizer = new TokenNormalizer();\n * normalizer.register(phraseRule); // \"to the power of\" → CARET\n * normalizer.register(implicitMultRule); // \"2 x\" → \"2 * x\"\n * const normalized = normalizer.normalize(rawTokens);\n * ```\n */\nexport class TokenNormalizer {\n /** Registered rules, unsorted, the source of truth. */\n private rules: NormalizerRule[] = [];\n\n /**\n * Priority-sorted copy of {@link rules}, rebuilt lazily on the next\n * {@link normalize} call after a mutation. Rules are registered once at\n * engine/package-registration time and essentially never change during a\n * session, but normalize() runs on every keystroke-driven evaluation, an\n * earlier version re-sorted a fresh copy of `rules` on every single call,\n * which meant every keystroke paid for an allocation + sort of a list that\n * had usually not changed since the last one. `null` means \"stale, rebuild\n * on next use\"; {@link register}/{@link unregister}/{@link clear} all\n * invalidate it.\n */\n private sortedRulesCache: NormalizerRule[] | null = null;\n\n /**\n * Per-token-type view of the priority-sorted rules, for the one\n * {@link normalize} call that runs before the index exists: for a token\n * type, the rules whose first declared slot admits it (or constrains no\n * type at all), in the same priority order {@link getSortedRules} produces.\n * See {@link rulesForTokenType}. Built once per distinct type and cached,\n * invalidated alongside {@link sortedRulesCache}.\n */\n private rulesByTokenType = new Map<string, NormalizerRule[]>();\n\n /**\n * Shape index over the priority-sorted rules, rebuilt alongside\n * {@link sortedRulesCache}. `null` means \"stale, rebuild on next use\".\n *\n * This is what turns the per-position scan from \"try every rule that could\n * fire on this token type\" into \"AND a few lookup planes and try what\n * survives\", which is usually nothing. See {@link RuleIndex}.\n */\n private ruleIndexCache: RuleIndex | null = null;\n\n /** Reused by {@link rulesAt} so a position's candidate list costs no allocation. */\n private candidateBuffer: NormalizerRule[] = [];\n\n /**\n * How many times {@link normalize} has run, capped once the index is in use.\n *\n * The index costs a few tens of microseconds to build and pays that back\n * within a line or two, but an engine that normalises exactly once, which is\n * what evaluating a single expression on a fresh engine does, would never\n * reach the payback. Skipping the build on the first call keeps that case at\n * the cost it had before the index existed, and a document reaches line two\n * immediately. The first call is not unfiltered, though: it reads the same\n * first-slot types the index would, through {@link rulesForTokenType}, so a\n * single expression still skips every rule that could not start at its\n * tokens.\n */\n private normalizeCalls = 0;\n\n /**\n * Phrase trie for single-pass multi-word phrase fusion.\n * Tried at each token position BEFORE other rules, the trie walk\n * is O(depth) vs O(R × W) for separate rule matching.\n */\n private phraseTrie = new PhraseTrie();\n\n /** Merged options with defaults applied. */\n private options: Required<NormalizerOptions>;\n\n // ── Constructor ──────────────────────────────────────────────────────────\n\n /**\n * @param options - Configuration overrides for safety limits and diagnostic callbacks\n */\n constructor(options: NormalizerOptions = {}) {\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n // ── Rule Management ──────────────────────────────────────────────────────\n\n /**\n * Register a normalization rule.\n *\n * Rules are sorted by priority (descending) on each {@link normalize} call.\n * Multiple rules can share the same priority, they are tried in registration\n * order when priorities are equal.\n *\n * @param rule - The rule to register\n */\n register(rule: NormalizerRule): void {\n warnIfUnshaped(rule);\n this.rules.push(rule);\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = null;\n }\n\n /**\n * Unregister a normalization rule by its {@link NormalizerRule.name | name}.\n *\n * If multiple rules share the same name, all are removed. This is safe to\n * call with a name that doesn't match any rule, it simply has no effect.\n *\n * @param ruleName - The name of the rule to remove\n */\n unregister(ruleName: string): void {\n this.rules = this.rules.filter(r => r.name !== ruleName);\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = null;\n }\n\n /**\n * Remove all registered rules, resetting the normalizer to its initial state.\n * Also clears the phrase trie.\n */\n clear(): void {\n this.rules = [];\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = null;\n this.phraseTrie = new PhraseTrie();\n }\n\n /**\n * Priority-sorted view of {@link rules} (descending priority; registration\n * order preserved for ties, since {@link Array.prototype.sort} is stable).\n * Cached until the next mutation. See {@link sortedRulesCache}.\n */\n private getSortedRules(): NormalizerRule[] {\n if (this.sortedRulesCache === null) {\n this.sortedRulesCache = [...this.rules].sort((a, b) => b.priority - a.priority);\n }\n return this.sortedRulesCache;\n }\n\n /**\n * The shape index over the priority-sorted rules, built on first use after\n * a mutation and cached. See {@link RuleIndex}.\n */\n private getRuleIndex(): RuleIndex {\n if (this.ruleIndexCache === null) {\n this.ruleIndexCache = new RuleIndex(this.getSortedRules());\n }\n return this.ruleIndexCache;\n }\n\n /**\n * The rules to try at a position, in priority order.\n *\n * With a candidate mask, walks its set bits low to high, which is descending\n * priority because bit `i` is the rule at index `i` of the priority-sorted\n * list.\n *\n * The walk shifts a bit at a time rather than jumping to the next set bit\n * with `Math.clz32(bits & -bits)`, which is the idiomatic form and was 36x\n * SLOWER here: 45us per line against 1.2us, measured over the built-in rule\n * set. `clz32` is specified on uint32 and the masks come out of a\n * `Uint32Array` as doubles above 2^31, so every call pays a conversion that\n * swamps the handful of iterations it saves. A de Bruijn table matched the\n * shift scan to within noise and needs a magic constant, so the plain shift\n * wins on both counts. Worst case is 32 iterations per word of pure integer\n * work.\n *\n * With `null` there is no index to consult, for one of two reasons: this is\n * the first call, which reads the first-token bucket from\n * {@link rulesForTokenType}, or {@link NormalizerOptions.ignoreRuleIndex} is\n * set, which is the exhaustive scan every filter is measured against. Both\n * hand back a cached list directly, since the caller only reads it.\n *\n * With a mask, returns a buffer reused across positions, so the caller must\n * finish with it before calling again. Copying the surviving rules out here\n * rather than yielding them lazily is deliberate twice over: it keeps the\n * mask's own scratch buffer from being read after the next position\n * overwrites it, and it avoids a generator on the hottest loop in the pass.\n */\n private rulesAt(mask: Uint32Array | null, type: string): readonly NormalizerRule[] {\n if (mask === null) {\n return this.options.ignoreRuleIndex ? this.getSortedRules() : this.rulesForTokenType(type);\n }\n\n const buffer = this.candidateBuffer;\n buffer.length = 0;\n const rules = this.getRuleIndex().rules;\n for (let w = 0; w < mask.length; w++) {\n let bits = mask[w] >>> 0;\n let index = w * 32;\n while (bits !== 0) {\n if ((bits & 1) !== 0) buffer.push(rules[index]);\n bits >>>= 1;\n index++;\n }\n }\n return buffer;\n }\n\n /**\n * The priority-sorted rules that could start at a token of `type`, for the\n * first {@link normalize} call, which runs before the index is built.\n *\n * The filter is the first slot of each rule's {@link effectiveShape}: a rule\n * naming types there is bucketed under exactly those, and one naming none is\n * in every bucket. That is the same declaration the index reads at its first\n * plane, only without the value axis, so a rule the bucket omits is one the\n * index would omit too, and one that would have returned null here anyway.\n * An earlier version read only the older `startTokenTypes` hint, which most\n * rules had by then replaced with a `shape`, so the first call tried nearly\n * every rule at every position and a fresh engine evaluating one expression\n * paid several times the rule calls of the second line of a document.\n *\n * Built once per distinct type and cached until the rule set changes.\n */\n private rulesForTokenType(type: string): NormalizerRule[] {\n let list = this.rulesByTokenType.get(type);\n if (list === undefined) {\n list = this.getSortedRules().filter((rule) => {\n const first = effectiveShape(rule)[0];\n return first?.types === undefined || first.types.includes(type);\n });\n this.rulesByTokenType.set(type, list);\n }\n return list;\n }\n\n /**\n * Get the number of currently registered rules (excludes phrase trie entries).\n */\n get ruleCount(): number {\n return this.rules.length;\n }\n\n /**\n * Every registered rule with the shape it declared, for diagnostic display.\n *\n * Exposes what the index is actually working with: a rule that declares a\n * shape is only tried where that shape can match, and one that declares none\n * is tried at every position of every line. Which is which is invisible from\n * the outside otherwise, and it is the difference between a package that\n * costs the documents that use it and one that costs all of them, so the\n * playground draws it.\n *\n * Returned in priority order, highest first, which is the order the\n * normalizer tries them in.\n */\n private ruleShapesCache: Array<{\n name: string;\n priority: number;\n shape: readonly RuleSlot[];\n unshapedReason?: string;\n indexedSlots: number;\n }> | null = null;\n\n getRuleShapes(): Array<{\n name: string;\n priority: number;\n shape: readonly RuleSlot[];\n unshapedReason?: string;\n indexedSlots: number;\n }> {\n // Memoised: the answer depends only on the rule set, but the diagnostic\n // pipeline builds a stage per LINE, so recomputing it there made a\n // 25-line document walk every rule 25 times to produce 25 identical lists.\n if (this.ruleShapesCache !== null) return this.ruleShapesCache;\n const index = this.getRuleIndex();\n this.ruleShapesCache = this.getSortedRules().map((rule) => {\n const shape = effectiveShape(rule);\n return {\n name: rule.name,\n priority: rule.priority,\n shape,\n unshapedReason: rule.unshapedReason,\n indexedSlots: Math.min(shape.length, index.depth),\n };\n });\n return this.ruleShapesCache;\n }\n\n /**\n * How many rules could fire at each position of `tokens`, against the total.\n *\n * The point of the index is that most positions admit no rule at all, and\n * this is what makes that visible rather than asserted.\n */\n getCandidateCounts(tokens: Token[]): number[] {\n const index = this.getRuleIndex();\n const counts: number[] = [];\n for (let pos = 0; pos < tokens.length; pos++) {\n const mask = index.candidates(tokens, pos);\n let n = 0;\n for (let w = 0; w < mask.length; w++) {\n let bits = mask[w] >>> 0;\n while (bits !== 0) { n += bits & 1; bits >>>= 1; }\n }\n counts.push(n);\n }\n return counts;\n }\n\n // ── Phrase Registration ────────────────────────────────────────────────\n\n /**\n * Register a multi-word phrase for fusion into a single compound token.\n *\n * This is the preferred way to add phrase patterns. It inserts into the\n * internal {@link PhraseTrie}, which collapses all phrase rules into a\n * single O(depth) trie walk per position, no separate rule scanning.\n *\n * @param phrase - Multi-word phrase (e.g., \"to the power of\", \"abyssal whip\")\n * @param tokenType - Target token type after fusion (e.g., \"CARET\", \"ITEM\")\n */\n addPhrase(phrase: string, tokenType: string): void {\n this.phraseTrie.addPhrase(phrase, tokenType);\n }\n\n /**\n * Check whether a word can start any registered phrase.\n *\n * Used by {@link implicitMultiplyRule} to suppress `*` insertion\n * before phrase-starting identifiers (e.g., \"2 power of 3\" → `2 ^ 3`,\n * not `2 * power of 3`). Delegates to {@link PhraseTrie.canStart}.\n */\n /**\n * Get all registered phrases and their target token types.\n *\n * Exposes the full phrase trie structure for diagnostic rendering\n * in the playground's NormalizerTab. Returns ALL registered phrases,\n * not just the ones that matched in the last evaluation.\n */\n getPhrases(): Record<string, string> {\n return this.phraseTrie.getAllPhrases();\n }\n\n canStartPhrase(word: string): boolean {\n return this.phraseTrie.canStart(word);\n }\n\n // ── Normalization ────────────────────────────────────────────────────────\n\n /**\n * Normalize a token stream by applying all registered rules.\n *\n * ## Algorithm\n * Applies rules greedily left-to-right in multiple passes:\n * 1. Sort rules by priority (descending)\n * 2. Walk the token stream left to right\n * 3. At each position, try rules in priority order\n * 4. On match: consume matched tokens, insert replacements, restart from insert point\n * 5. On no match: pass token through unchanged\n * 6. Repeat until a full pass produces no changes, or maxPasses is reached\n *\n * ## Fusion tracking\n * When a rule consumes more tokens than it produces, the normalizer calls\n * `onFusion` with a {@link TokenFusion} record for diagnostic collection.\n * This populates {@link NormalizerOutput.fusions} in the playground pipeline view.\n *\n * ## Safety\n * If the normalized token count exceeds {@link NormalizerOptions.maxTokens},\n * an Error is thrown to prevent memory exhaustion from runaway rule expansion.\n *\n * @param tokens - Raw tokens from the lexer\n * @param onFusion - Optional fusion callback (overrides {@link NormalizerOptions.onFusion})\n * @returns Normalized tokens ready for parsing\n * @throws {Error} If the normalized token count exceeds maxTokens\n */\n normalize(tokens: Token[], onFusion?: (fusion: TokenFusion) => void): Token[] {\n // ── Early exit: nothing to normalize ──\n if (tokens.length === 0) return tokens;\n\n // Rules reach a position through one of three filters, resolved once\n // below: the shape index, the first-token buckets on the very first call,\n // or no filter at all under `ignoreRuleIndex`. See rulesAt().\n const fusionHandler = onFusion ?? this.options.onFusion;\n const maxPasses = this.options.maxPasses;\n const maxTokens = this.options.maxTokens;\n\n // Hoisted out of the pass loop: the rule set cannot change mid-normalize,\n // so the index is resolved once rather than per position.\n const warmedUp = this.normalizeCalls > 0;\n if (!warmedUp) this.normalizeCalls = 1;\n const useIndex = warmedUp && !this.options.ignoreRuleIndex;\n const ruleIndex = useIndex ? this.getRuleIndex() : null;\n\n let current = tokens;\n let changed = true;\n let passCount = 0;\n\n // Multi-pass loop: rules may trigger cascading matches across passes\n while (changed && passCount < maxPasses) {\n changed = false;\n passCount++;\n\n // Built lazily: a pass that changes nothing must not allocate an array\n // and copy every token into it only to throw the copy away. `null` means\n // \"nothing has changed yet, `current` is still the answer\"; the first\n // rule to fire calls ensureResult() to materialise it. A document whose\n // lines mostly normalise to themselves is the common case, and it now\n // costs no allocation at all.\n let result: Token[] | null = null;\n let pos = 0;\n\n // Single-pass left-to-right greedy walk\n while (pos < current.length) {\n let matched = false;\n\n // ── Fast path: phrase trie (O(depth) single walk vs O(R × W) per rule) ──\n // O(1) type-guard: skip trie entirely for tokens that can't start phrases.\n // Flat Uint8Array indexed by typeId, no hashing, no Set lookup, true O(1).\n const tid = current[pos].typeId;\n if (tid >= NON_WORD_TABLE.length || NON_WORD_TABLE[tid] === 0) {\n const trieMatch = this.phraseTrie.matchAt(current, pos);\n if (trieMatch) {\n const sourceTokens = current.slice(pos, pos + trieMatch.consumed);\n if (result === null) result = current.slice(0, pos);\n for (const rt of trieMatch.replacement) {\n result.push(rt);\n }\n if (trieMatch.consumed > 1 && trieMatch.replacement.length === 1) {\n recordSourceSpan(trieMatch.replacement[0], sourceTokens);\n fusionHandler({\n rule: trieMatch.ruleName ?? \"phrase-trie\",\n sourceTokens,\n fusedToken: trieMatch.replacement[0],\n });\n }\n pos += trieMatch.consumed;\n changed = true;\n continue; // trie matched — skip other rules at this position (no need to set matched)\n }\n }\n\n // Try, in priority order, only the rules whose declared shape admits\n // this position. The index is a pure filter: bit order is priority\n // order, and a rule it excludes would have returned null here anyway\n // (see RuleIndex). `ignoreRuleIndex` restores the exhaustive scan so\n // the two can be compared.\n const candidates = useIndex\n ? ruleIndex!.candidates(current, pos)\n : null;\n if (candidates !== null && isEmptyMask(candidates)) {\n // Nothing can fire here. This is the common case in running prose,\n // and reaching it costs a few array loads rather than one call per\n // registered rule.\n if (result !== null) result.push(current[pos]);\n pos++;\n continue;\n }\n for (const rule of this.rulesAt(candidates, current[pos].type)) {\n const match = rule.match(current, pos);\n if (match) {\n // Collect source tokens for fusion tracking\n const sourceTokens = current.slice(pos, pos + match.consumed);\n\n // Insert replacement tokens into result\n if (result === null) result = current.slice(0, pos);\n for (const rt of match.replacement) {\n result.push(rt);\n }\n\n // Track fusion events for diagnostics:\n // - Multiple tokens → single token: classic fusion\n // - Multiple tokens → fewer tokens: partial fusion\n if (match.consumed > 1 && match.replacement.length === 1) {\n recordSourceSpan(match.replacement[0], sourceTokens);\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: match.replacement[0],\n });\n } else if (match.consumed > 1 && match.replacement.length < match.consumed) {\n for (const rt of match.replacement) {\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: rt,\n });\n }\n }\n\n // Advance position past consumed tokens\n pos += match.consumed;\n changed = true;\n matched = true;\n break; // Rule matched — restart at new position with highest-priority rules\n }\n }\n\n if (!matched) {\n // No rule matched at this position, pass token through unchanged.\n // Only copied when an earlier position already forced the array.\n if (result !== null) result.push(current[pos]);\n pos++;\n }\n }\n\n // Nothing fired anywhere in this pass, so the stream is already its own\n // normal form and `changed` is false; the loop is about to end.\n if (result === null) break;\n const passResult: Token[] = result;\n\n // Safety: bail if token count explodes (runaway rule expansion)\n if (passResult.length > maxTokens) {\n // A raw Error here would bypass ThreeTierEvaluator's DAG-preservation\n // enrichment on compile failure (it specifically checks for\n // EngineError). Same reasoning as ExpressionEngineSafety.ts's\n // complexity/length checks, which this mirrors.\n throw ErrorFactory.validation(\n \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n `Normalized token count (${passResult.length}) exceeds safety limit (${maxTokens})`,\n { tokenCount: passResult.length, maxTokens }\n );\n }\n\n current = passResult;\n }\n\n return current;\n }\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * PhraseTrie, optimized word-level trie for multi-word phrase fusion.\n *\n * ## Problem\n * The normalizer previously applied N separate `phraseFusionRule` instances,\n * each scanning forward from the current token position. For R phrase rules\n * and W average phrase length, this cost O(N × R × W) per pass.\n *\n * ## Solution\n * A single trie walk per position collapses all phrase rules into O(D)\n * where D ≤ longest phrase depth (typically ≤ 5 words). The trie tracks\n * the deepest terminal node reached, implementing longest-match-wins\n * without priority sorting.\n *\n * ## Optimizations\n * 1. **Set<string> quick-reject**, the `startWords` set contains the first\n * word of every registered phrase. At each position, if the token's\n * lowercase value isn't in the set, we bail in O(1) without touching\n * the trie. ~80% of tokens (numbers, operators) hit this fast path.\n * 2. **Longest-match-wins**, the `matchAt()` walk continues past terminal\n * nodes, tracking the deepest one. Shorter overlapping phrases (e.g.,\n * \"power of\") don't need lower priority, the trie naturally prefers\n * the longer match.\n * 3. **Map-based children**, `Map<string, TrieNode>` gives O(1) amortized\n * child lookup per word, faster than array scanning for sparse branches.\n *\n * ## Package integration\n * Packages add phrases via {@link TokenNormalizer.addPhrase} (public API)\n * or the {@link IEnginePackage.phrases} declarative field. Each call to\n * `addPhrase()` inserts the phrase into this trie and updates `startWords`.\n *\n * @module PhraseTrie\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { NormalizerMatch } from \"./NormalizerRule\";\nimport { createFusedToken } from \"./TokenNormalizer\";\n\n//#endregion\n//#region ─── TrieNode ─────────────────────────────────────────────────────────\n\n/**\n * Internal trie node.\n *\n * Each node represents a matched word in a phrase. The path from root\n * to a node spells out a partial or complete phrase.\n */\ninterface TrieNode {\n\t/** Child nodes keyed by next word (all lowercase). */\n\tchildren: Map<string, TrieNode>;\n\t/**\n\t * If this node completes a phrase, the terminal metadata.\n\t * A node can be both terminal AND have children. This handles\n\t * overlapping phrases like \"power of\" and \"to the power of\".\n\t */\n\tterminal: TrieTerminal | null;\n}\n\n/** Metadata stored at terminal nodes for deferred token creation. */\ninterface TrieTerminal {\n\t/** The target token type after fusion (e.g., \"CARET\", \"TIMES_BY\"). */\n\ttokenType: string;\n\t/** The original phrase string (e.g., \"to the power of\"). */\n\tphrase: string;\n\t/** Number of tokens consumed by this phrase. */\n\tconsumed: number;\n}\n\n//#endregion\n//#region ─── PhraseTrie ─────────────────────────────────────────────────────\n\n/**\n * Word-level trie for single-pass multi-word phrase matching.\n *\n * @example\n * ```ts\n * const trie = new PhraseTrie();\n * trie.addPhrase(\"to the power of\", \"CARET\");\n * trie.addPhrase(\"power of\", \"CARET\");\n * trie.addPhrase(\"abyssal whip\", \"ITEM\");\n *\n * // At position 0 with tokens [\"to\",\"the\",\"power\",\"of\",\"3\"]\n * const match = trie.matchAt(tokens, 0);\n * // → { consumed: 4, replacement: [CARET(\"to the power of\")] }\n * ```\n */\nexport class PhraseTrie {\n\t/**\n\t * First words that can start any registered phrase (all lowercase).\n\t * O(1) quick-reject: if `tokens[pos].value.toLowerCase()` isn't here,\n\t * no phrase can match at this position.\n\t */\n\tprivate startWords = new Set<string>();\n\n\t/**\n\t * Root maps first word → child node.\n\t * Two-level root avoids an unnecessary intermediate TrieNode.\n\t */\n\tprivate root = new Map<string, TrieNode>();\n\n\t// ── Registration ──────────────────────────────────────────────────────\n\n\t/**\n\t * Register a phrase for fusion into a single compound token.\n\t *\n\t * @param phrase - Multi-word phrase (e.g., \"to the power of\")\n\t * @param tokenType - Target token type after fusion (e.g., \"CARET\")\n\t */\n\taddPhrase(phrase: string, tokenType: string): void {\n\t\tconst words = phrase.toLowerCase().trim().split(/\\s+/);\n\t\tif (words.length === 0 || words[0] === \"\") return;\n\n\t\tthis.startWords.add(words[0]);\n\n\t\tconst firstWord = words[0];\n\t\tlet node: TrieNode;\n\n\t\tif (this.root.has(firstWord)) {\n\t\t\tnode = this.root.get(firstWord)!;\n\t\t} else {\n\t\t\tnode = { children: new Map(), terminal: null };\n\t\t\tthis.root.set(firstWord, node);\n\t\t}\n\n\t\t// Single-word phrase: terminal at root's child\n\t\tif (words.length === 1) {\n\t\t\tnode.terminal = { tokenType, phrase, consumed: 1 };\n\t\t\treturn;\n\t\t}\n\n\t\t// Walk/insert remaining words\n\t\tfor (let i = 1; i < words.length; i++) {\n\t\t\tconst word = words[i];\n\t\t\tif (!node.children.has(word)) {\n\t\t\t\tnode.children.set(word, { children: new Map(), terminal: null });\n\t\t\t}\n\t\t\tnode = node.children.get(word)!;\n\t\t}\n\n\t\tnode.terminal = { tokenType, phrase, consumed: words.length };\n\t}\n\n\t// ── Matching ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Attempt to match a phrase starting at `pos` in the token stream.\n\t *\n\t * Walks the trie one token at a time, tracking the deepest terminal\n\t * node reached. Returns the longest match found, or `null` if no\n\t * phrase starts at this position.\n\t *\n\t * @param tokens - The current token stream\n\t * @param pos - Position to attempt matching from\n\t * @returns The longest {@link NormalizerMatch}, or `null` on no match\n\t */\n\tmatchAt(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t// ── Bounds guard ──\n\t\tif (pos >= tokens.length) return null;\n\n\t\t// ── A tag token never takes part in phrase fusion (#197, #213) ──\n\t\t// A `#tag` is a typed token, not a bare word, so it must not start or\n\t\t// complete a phrase. The trie matches on written value alone, so without\n\t\t// this guard a tag whose name equals a phrase or a phrase-continuation\n\t\t// word (`1200 #assuming`, `total of #column`) is fused into that grammar\n\t\t// before the category-tag rules ever run, and the tag is lost.\n\t\t//\n\t\t// The guard also covers the fused aggregate tokens the tags package emits\n\t\t// (`TAG_SUM` / `TAG_COUNT` / `TAG_AVERAGE`), whose value is the tag NAME:\n\t\t// otherwise `total of #assuming` fuses correctly to TAG_SUM(\"assuming\"),\n\t\t// then the trie re-reads that value on the next pass and turns it back\n\t\t// into the finance ASSUMING keyword (#213). The whole `TAG` / `TAG_*`\n\t\t// namespace belongs to the tags package.\n\t\tconst startType = tokens[pos].type;\n\t\tif (startType === \"TAG\" || startType.startsWith(\"TAG_\")) return null;\n\n\t\t// ── O(1) quick-reject: first word not a phrase starter ──\n\t\tconst firstWord = tokens[pos].value.toLowerCase();\n\t\tif (!this.startWords.has(firstWord)) return null;\n\n\t\t// ── Walk trie, tracking deepest terminal ──\n\t\tlet node: TrieNode | undefined = this.root.get(firstWord);\n\t\tif (!node) return null;\n\n\t\tlet best: NormalizerMatch | null = null;\n\t\tlet depth = 1;\n\n\t\t// Check single-word phrase at first node\n\t\tif (node.terminal) {\n\t\t\tconst sourceTokens = tokens.slice(pos, pos + 1);\n\t\t\tbest = {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [createFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens)],\n\t\t\t\truleName: node.terminal.phrase,\n\t\t\t};\n\t\t}\n\n\t\t// Walk deeper for multi-word phrases\n\t\tfor (let i = pos + 1; i < tokens.length && node?.children; i++) {\n\t\t\tconst contType = tokens[i].type;\n\t\t\tif (contType === \"TAG\" || contType.startsWith(\"TAG_\")) break; // a tag token can't continue a phrase (#197, #213)\n\t\t\tconst word = tokens[i].value.toLowerCase();\n\t\t\tnode = node.children.get(word);\n\t\t\tif (!node) break; // dead end\n\t\t\tdepth++;\n\n\t\t\tif (node.terminal) {\n\t\t\t\t// Deferred fused-token creation, only on deepest match found\n\t\t\t\tconst sourceTokens = tokens.slice(pos, pos + depth);\n\t\t\t\tbest = {\n\t\t\t\t\tconsumed: depth,\n\t\t\t\t\treplacement: [\n\t\t\t\t\t\tcreateFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens),\n\t\t\t\t\t],\n\t\t\t\t\truleName: node.terminal.phrase,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\t// ── Introspection ─────────────────────────────────────────────────────\n\n\t/** Number of unique first words (not total phrases). */\n\tget size(): number {\n\t\treturn this.root.size;\n\t}\n\n\t/**\n\t * Return all registered phrases and their target token types.\n\t *\n\t * Used by diagnostic mode to expose the complete trie structure to the\n\t * playground's NormalizerTab for rendering ALL registered phrases\n\t * (not just the ones that matched in this evaluation).\n\t */\n\tgetAllPhrases(): Record<string, string> {\n\t\tconst result: Record<string, string> = {};\n\n\t\tconst collect = (node: TrieNode, path: string[]): void => {\n\t\t\tif (node.terminal) {\n\t\t\t\tresult[path.join(' ')] = node.terminal.tokenType;\n\t\t\t}\n\t\t\tfor (const [word, child] of node.children) {\n\t\t\t\tcollect(child, [...path, word]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [firstWord, node] of this.root) {\n\t\t\tcollect(node, [firstWord]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Check if any phrase starts with this word (case-insensitive). */\n\tcanStart(word: string): boolean {\n\t\treturn this.startWords.has(word.toLowerCase());\n\t}\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * Built-in normalization rules for the {@link TokenNormalizer}.\n *\n * These rules handle common expression patterns that span multiple tokens.\n * Phrase fusion (e.g., \"to the power of\" → CARET) is handled by the\n * internal {@link PhraseTrie}. See {@link TokenNormalizer.addPhrase}.\n * This module only exports non-phrase rules like {@link implicitMultiplyRule}.\n *\n * @module BuiltinNormalizerRules\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport 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 \"./NormalizerRule\";\n\n//#endregion\n//#region ─── PHRASE_START_WORDS, Implicit Multiply Guard ─────────────────────\n\n/**\n * Words that can start multi-word phrases, hardcoded fallback.\n *\n * This is ONLY used as the default fallback in {@link implicitMultiplyRule}\n * when no `canStart` predicate is provided. In the recommended pattern,\n * the {@link PhraseTrie}'s live `canStart()` set is passed instead, keeping\n * the guard in sync with package-registered phrases.\n *\n * @see {@link TokenNormalizer.canStartPhrase}\n */\n/**\n * Words that introduce a rate denominator when a unit follows.\n *\n * Kept next to the implicit-multiplication rule because that is the only\n * thing they change here; the rate itself is built in the uom package.\n */\nconst RATE_DENOMINATOR_WORDS = new Set([\"per\", \"a\", \"an\", \"each\", \"every\"]);\n\nconst PHRASE_START_WORDS = new Set([\n \"to\", \"power\", \"increase\", \"decrease\", \"times\", \"multiply\", \"divide\", \"by\",\n]);\n\n//#endregion\n//#region ─── implicitMultiplyRule, Implicit Operator Insertion ────────────────\n\n/**\n * Creates a normalization rule that inserts an implicit multiplication operator\n * between adjacent tokens where multiplication is implied.\n *\n * ## When it fires\n * Inserts a STAR token between:\n * - `NUMBER IDENT` (e.g., \"2 x\" → \"2 * x\")\n * - `RPAREN IDENT` (e.g., \"(x+1)y\" → \"(x+1) * y\")\n * - `NUMBER LPAREN` (e.g., \"2(x+1)\" → \"2 * (x+1)\")\n * - `NUMBER PI` / `NUMBER E` (e.g., \"2π\" → \"2 * π\")\n *\n * ## When it doesn't fire\n * - When the following identifier starts a multi-word phrase\n * (checked against {@link PHRASE_START_WORDS})\n * - When the following token is not an identifier or parenthesized expression\n *\n * ## Priority\n * Default priority is 50, below phrase fusion so phrases match first.\n *\n * @param priority - Rule priority (default 50)\n * @returns A {@link NormalizerRule} that inserts implicit multiply operators\n */\nexport function implicitMultiplyRule(\n\tpriority: number = 50,\n\tcanStart?: (word: string) => boolean\n): NormalizerRule {\n\tconst phraseGuard = canStart ?? ((word: string) => PHRASE_START_WORDS.has(word.toLowerCase()));\n\n\treturn {\n name: \"implicit:multiply\",\n priority,\n // Both slots are exactly the `triggers` test below, which is the whole\n // condition: a value or closing bracket, then something a multiplication\n // could apply to.\n shape: [\n { types: [\"NUMBER\", \"RPAREN\"] },\n { types: [\"IDENT\", \"LPAREN\", \"PI\", \"E\"] },\n ],\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n // ── Need at least one token after the current position ──\n if (pos + 1 >= tokens.length) return null;\n\n const t = tokens[pos];\n const next = tokens[pos + 1];\n\n // ── Check trigger conditions ──\n // Ordered FIRST deliberately. The two guards below only ever suppress a\n // match, so testing them after the trigger cannot change any result, and\n // the first of them allocates a lower-cased copy of the next token's\n // value. Running that ahead of a pair of type comparisons meant every\n // position in the document paid a string allocation and a set lookup to\n // reach a test that rejects nearly all of them.\n const triggers =\n (t.type === \"NUMBER\" || t.type === \"RPAREN\") &&\n (next.type === \"IDENT\" || next.type === \"LPAREN\" || next.type === \"PI\" || next.type === \"E\");\n\n if (!triggers) return null;\n\n // ── Guard: suppress if the next identifier starts a phrase ──\n // Uses the trie's canStart when available, falls back to hardcoded set.\n // This prevents \"2 power of 3\" from becoming \"2 * power of 3\".\n const nextValue = next.value.toLowerCase();\n if (phraseGuard(nextValue)) return null;\n\n // ── Guard: a rate denominator, not a multiplication ──\n // \"99 per week\" is ninety-nine a week, not ninety-nine times something\n // called per. The trie guard above cannot cover this, because these are\n // not registered phrases; they are recognised by the uom package's\n // bare-denominator rule, which runs after this one and then finds its\n // fused token stranded in operand position. The slash spelling never had\n // the problem, which is what made it hard to see.\n if (RATE_DENOMINATOR_WORDS.has(nextValue) && tokens[pos + 2]?.type === \"UNIT\") return null;\n\n // ── Insert a STAR token at the next token's position ──\n const starToken = new LexerToken(\n \"STAR\", tokenTypeId(\"STAR\"), \"*\", \"*\",\n next.offset, 0, next.line, next.col,\n );\n\n // consumed = 1: only the current token is replaced with [current, STAR]\n // The next token is NOT consumed, it stays for the next iteration\n return { consumed: 1, replacement: [t, starToken] };\n },\n };\n}\n\n//#endregion\n//#region ─── isInsideRangeContext, Bracket/Call-Paren Context Guard ───────────\n\n/**\n * Whether token `pos` sits inside a context where a bare `NUMBER:NUMBER`\n * sequence means a Range, not a clock-time/laptime/video-timecode literal:\n * a matrix literal/index/slice (`[1,2,3]`, `a[0:3]`), OR a `map`/`reduce`/\n * `sum`/`prod` call's own argument-list parens (`map(f, 0:3)`, these\n * accept a bare Range argument directly, per the Calca spec's own\n * example). Scans backward from `pos` over the CURRENT pass's token array,\n * tracking `[`/`(` nesting depth, the same \"positional guard via\n * backward scan\" idiom already used elsewhere in this normalizer layer\n * (e.g. `LineRefNormalizerRule`'s previous-token check), generalized to\n * depth-tracking. An `LBRACKET` is unconditionally a range-safe opener; an\n * `LPAREN` is range-safe ONLY when immediately preceded by MAP/REDUCE/\n * SUM_FN/PROD_FN, an ordinary grouping/function-call paren is NOT, so\n * `(9:00) + 5` still means a clock time, not a range.\n *\n * Needed because the clock-time/laptime/video-timecode rules each match a\n * bare `NUMBER COLON NUMBER...` shape with ZERO context-awareness, a real\n * collision discovered when adding Range support, since e.g. \"0:3\" is\n * valid input to BOTH features. These contexts have no legitimate use for\n * a clock-time/laptime/timecode literal, so the carve-out costs the time\n * features nothing.\n *\n * IMPORTANT cross-pass-timing gotcha (a real bug found and fixed here,\n * not a hypothetical): the `LPAREN`-opener check deliberately tests the\n * RAW word text (`prev.value.toLowerCase()`), not `prev.type ===\n * \"MAP\"/\"REDUCE\"/...`. The normalizer's multi-pass loop hands every rule\n * the SAME frozen `tokens` snapshot for an entire pass, a rule scanning\n * a LATER position in that pass cannot see a fusion `mapReduceCallNormalizerRule`\n * performs at an EARLIER position in that SAME pass (fusion results only\n * become visible to other rules starting the NEXT pass). Checking the\n * fused token type here would miss exactly the case that matters most\n * `map(f, 0:3)` on its very first normalization pass, silently letting\n * `0:3` fuse into a clock time before `map(`'s own fusion ever lands.\n * Testing the raw word is immune to this: it's true from the very first\n * pass, regardless of whether `mapReduceCallNormalizerRule` has run yet.\n * (`LBRACKET` above has no equivalent issue, it's a genuine lexer token\n * from the start, never itself the product of a fusion.)\n */\nexport function isInsideRangeContext(tokens: Token[], pos: number): boolean {\n const safeStack: boolean[] = [];\n for (let i = 0; i < pos; i++) {\n const t = tokens[i];\n if (t.type === \"LBRACKET\") {\n safeStack.push(true);\n } else if (t.type === \"LPAREN\") {\n const prev = tokens[i - 1];\n const opensMapReduceCall = !!prev && (\n prev.type === \"MAP\" || prev.type === \"REDUCE\" || prev.type === \"SUM_FN\" || prev.type === \"PROD_FN\" ||\n (prev.type === \"IDENT\" && (prev.value.toLowerCase() === \"map\" || prev.value.toLowerCase() === \"reduce\" || prev.value.toLowerCase() === \"sum\" || prev.value.toLowerCase() === \"prod\"))\n );\n safeStack.push(opensMapReduceCall);\n } else if (t.type === \"RBRACKET\" || t.type === \"RPAREN\") {\n safeStack.pop();\n }\n }\n return safeStack.length > 0 && safeStack[safeStack.length - 1];\n}\n\n//#endregion\n//#region ─── createBuiltinNormalizerRules, All Built-in Rules ─────────────────\n\n/**\n * Creates built-in non-phrase normalization rules.\n *\n * Returns implicit multiply insertion (priority 50).\n *\n * **Prefer** calling {@link implicitMultiplyRule} directly with a\n * `canStart` predicate wired to the normalizer's phrase trie:\n * ```ts\n * normalizer.register(implicitMultiplyRule(50, (w) => normalizer.canStartPhrase(w)));\n * ```\n * Without the predicate, this function falls back to a hardcoded\n * {@link PHRASE_START_WORDS} set that won't reflect package-registered phrases.\n *\n * @returns An array of {@link NormalizerRule} instances ready for registration\n */\nexport function createBuiltinNormalizerRules(): NormalizerRule[] {\n return [\n // ── Implicit operator insertion (priority 50) ──\n implicitMultiplyRule(),\n ];\n}\n\n/**\n * Built-in phrase → tokenType mappings.\n *\n * These are registered into the engine's {@link PhraseTrie} during\n * construction. Tests that create a standalone {@link TokenNormalizer}\n * should register these via {@link TokenNormalizer.addPhrase}. The table\n * itself lives in `lexer/BuiltinPhrases.ts`, shared with the lexer's token\n * lookup, and is re-exported here so existing imports keep working.\n */\nexport { BUILTIN_PHRASES } from \"@solve-js/lexer/BuiltinPhrases\";\n\n//#endregion\n"]}