solve-engine 2.6.0 → 2.7.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 (130) hide show
  1. package/dist/{PackageCompatibility-CCdud__Q.d.cts → PackageCompatibility-BG0iur4I.d.cts} +1 -1
  2. package/dist/{PackageCompatibility-4QtIErfx.d.ts → PackageCompatibility-BlIcQg5v.d.ts} +1 -1
  3. package/dist/{PackageRegistry-B7wkfSrY.d.ts → PackageRegistry-BJ0QQd3k.d.ts} +4 -4
  4. package/dist/{PackageRegistry-Hx85XD01.d.cts → PackageRegistry-DeGDZkNt.d.cts} +4 -4
  5. package/dist/{Parselet-CTNpfuEB.d.cts → Parselet-BSndkWEY.d.cts} +1 -1
  6. package/dist/{Parselet-DONNUpur.d.ts → Parselet-Blq8B0Gj.d.ts} +1 -1
  7. package/dist/{ScopeManager-BkbDXK_R.d.ts → ScopeManager-CF3cZUqW.d.ts} +2 -2
  8. package/dist/{ScopeManager-Cvgypcu4.d.cts → ScopeManager-D8nLv--u.d.cts} +2 -2
  9. package/dist/{VMCheckpoints-9zBQnTsN.d.ts → VMCheckpoints-BsR5_auF.d.ts} +2 -2
  10. package/dist/{VMCheckpoints-CBMGiSqw.d.cts → VMCheckpoints-Dy39SVHa.d.cts} +2 -2
  11. package/dist/{Value-D1XlMwe2.d.cts → Value-DCTqTSeP.d.cts} +22 -5
  12. package/dist/{Value-D1XlMwe2.d.ts → Value-DCTqTSeP.d.ts} +22 -5
  13. package/dist/chunk-5AMJNF7J.js +3 -0
  14. package/dist/chunk-5AMJNF7J.js.map +1 -0
  15. package/dist/chunk-5TCSFTZD.js +2 -0
  16. package/dist/chunk-5TCSFTZD.js.map +1 -0
  17. package/dist/chunk-5TVI2UPZ.cjs +2 -0
  18. package/dist/chunk-5TVI2UPZ.cjs.map +1 -0
  19. package/dist/{chunk-ZOOVGXMK.cjs → chunk-75XDS65A.cjs} +2 -2
  20. package/dist/{chunk-ZOOVGXMK.cjs.map → chunk-75XDS65A.cjs.map} +1 -1
  21. package/dist/chunk-A33K7NY4.js +2 -0
  22. package/dist/chunk-A33K7NY4.js.map +1 -0
  23. package/dist/chunk-AQWNEO7M.cjs +2 -0
  24. package/dist/{chunk-Z5KBBQOJ.cjs.map → chunk-AQWNEO7M.cjs.map} +1 -1
  25. package/dist/{chunk-OVQ3V4CG.cjs → chunk-B7J24Q5T.cjs} +2 -2
  26. package/dist/{chunk-OVQ3V4CG.cjs.map → chunk-B7J24Q5T.cjs.map} +1 -1
  27. package/dist/{chunk-HMEZJXLX.js → chunk-CVY2A3TP.js} +2 -2
  28. package/dist/{chunk-HMEZJXLX.js.map → chunk-CVY2A3TP.js.map} +1 -1
  29. package/dist/{chunk-HOQU47MF.cjs → chunk-FNNIAJNY.cjs} +2 -2
  30. package/dist/{chunk-HOQU47MF.cjs.map → chunk-FNNIAJNY.cjs.map} +1 -1
  31. package/dist/{chunk-3AVWA5IZ.cjs → chunk-FUDVKPB7.cjs} +2 -2
  32. package/dist/{chunk-3AVWA5IZ.cjs.map → chunk-FUDVKPB7.cjs.map} +1 -1
  33. package/dist/chunk-GYX6S6OS.cjs +3 -0
  34. package/dist/chunk-GYX6S6OS.cjs.map +1 -0
  35. package/dist/{chunk-GKDZ7TSX.cjs → chunk-HAEOMJE3.cjs} +2 -2
  36. package/dist/{chunk-GKDZ7TSX.cjs.map → chunk-HAEOMJE3.cjs.map} +1 -1
  37. package/dist/{chunk-T52Y5G24.js → chunk-HF4H7LYA.js} +4 -4
  38. package/dist/{chunk-T52Y5G24.js.map → chunk-HF4H7LYA.js.map} +1 -1
  39. package/dist/chunk-HTJPV42D.js +2 -0
  40. package/dist/{chunk-XTM4HTRB.js.map → chunk-HTJPV42D.js.map} +1 -1
  41. package/dist/chunk-IHZBKT7L.cjs +3 -0
  42. package/dist/chunk-IHZBKT7L.cjs.map +1 -0
  43. package/dist/{chunk-SWKYVSMP.js → chunk-JEFMG6CV.js} +2 -2
  44. package/dist/{chunk-SWKYVSMP.js.map → chunk-JEFMG6CV.js.map} +1 -1
  45. package/dist/{chunk-P6BLASAA.js → chunk-JQBG3LX4.js} +2 -2
  46. package/dist/{chunk-P6BLASAA.js.map → chunk-JQBG3LX4.js.map} +1 -1
  47. package/dist/{chunk-GHW2X7PS.js → chunk-KHCNMNZZ.js} +2 -2
  48. package/dist/{chunk-GHW2X7PS.js.map → chunk-KHCNMNZZ.js.map} +1 -1
  49. package/dist/{chunk-4XTD4B77.js → chunk-KXM7EY27.js} +3 -3
  50. package/dist/{chunk-4XTD4B77.js.map → chunk-KXM7EY27.js.map} +1 -1
  51. package/dist/{chunk-R7T3NGUE.cjs → chunk-MVP2YD4X.cjs} +2 -2
  52. package/dist/{chunk-R7T3NGUE.cjs.map → chunk-MVP2YD4X.cjs.map} +1 -1
  53. package/dist/chunk-N4HJTHZR.js +2 -0
  54. package/dist/{chunk-ZJPAPBP3.js.map → chunk-N4HJTHZR.js.map} +1 -1
  55. package/dist/chunk-P5EMTVMJ.js +3 -0
  56. package/dist/chunk-P5EMTVMJ.js.map +1 -0
  57. package/dist/chunk-PNDQRCRQ.cjs +2 -0
  58. package/dist/chunk-PNDQRCRQ.cjs.map +1 -0
  59. package/dist/{chunk-B4P4M4ZW.cjs → chunk-W7VOTR2J.cjs} +3 -3
  60. package/dist/{chunk-B4P4M4ZW.cjs.map → chunk-W7VOTR2J.cjs.map} +1 -1
  61. package/dist/{chunk-VYWGUMFW.js → chunk-WTEXBPBR.js} +2 -2
  62. package/dist/{chunk-VYWGUMFW.js.map → chunk-WTEXBPBR.js.map} +1 -1
  63. package/dist/{chunk-KSDTVFXA.cjs → chunk-ZRFUD2LX.cjs} +4 -4
  64. package/dist/{chunk-KSDTVFXA.cjs.map → chunk-ZRFUD2LX.cjs.map} +1 -1
  65. package/dist/constants.cjs +1 -1
  66. package/dist/constants.js +1 -1
  67. package/dist/engine.cjs +1 -1
  68. package/dist/engine.d.cts +7 -7
  69. package/dist/engine.d.ts +7 -7
  70. package/dist/engine.js +1 -1
  71. package/dist/format.cjs +1 -1
  72. package/dist/format.d.cts +1 -1
  73. package/dist/format.d.ts +1 -1
  74. package/dist/format.js +1 -1
  75. package/dist/index.cjs +1 -1
  76. package/dist/index.d.cts +7 -7
  77. package/dist/index.d.ts +7 -7
  78. package/dist/index.js +1 -1
  79. package/dist/language.d.cts +6 -6
  80. package/dist/language.d.ts +6 -6
  81. package/dist/packages.cjs +1 -1
  82. package/dist/packages.d.cts +6 -6
  83. package/dist/packages.d.ts +6 -6
  84. package/dist/packages.js +1 -1
  85. package/dist/parser.cjs +1 -1
  86. package/dist/parser.d.cts +3 -3
  87. package/dist/parser.d.ts +3 -3
  88. package/dist/parser.js +1 -1
  89. package/dist/{pipeline-DY0rhgQG.d.cts → pipeline-BM8xc0CZ.d.cts} +3 -3
  90. package/dist/{pipeline-BH7BFOTJ.d.ts → pipeline-J2ehIm7t.d.ts} +3 -3
  91. package/dist/resolvers.d.cts +1 -1
  92. package/dist/resolvers.d.ts +1 -1
  93. package/dist/testing.cjs +2 -2
  94. package/dist/testing.d.cts +6 -6
  95. package/dist/testing.d.ts +6 -6
  96. package/dist/testing.js +1 -1
  97. package/dist/uom.cjs +1 -1
  98. package/dist/uom.d.cts +1 -1
  99. package/dist/uom.d.ts +1 -1
  100. package/dist/uom.js +1 -1
  101. package/dist/vm.cjs +1 -1
  102. package/dist/vm.d.cts +6 -6
  103. package/dist/vm.d.ts +6 -6
  104. package/dist/vm.js +1 -1
  105. package/dist/worker.cjs +2 -2
  106. package/dist/worker.cjs.map +1 -1
  107. package/dist/worker.d.cts +15 -5
  108. package/dist/worker.d.ts +15 -5
  109. package/dist/worker.js +2 -2
  110. package/dist/worker.js.map +1 -1
  111. package/package.json +1 -1
  112. package/dist/chunk-3DD2RVBI.cjs +0 -3
  113. package/dist/chunk-3DD2RVBI.cjs.map +0 -1
  114. package/dist/chunk-5FGOIDLS.cjs +0 -2
  115. package/dist/chunk-5FGOIDLS.cjs.map +0 -1
  116. package/dist/chunk-5OIXCVB2.js +0 -3
  117. package/dist/chunk-5OIXCVB2.js.map +0 -1
  118. package/dist/chunk-ESUN2THE.cjs +0 -2
  119. package/dist/chunk-ESUN2THE.cjs.map +0 -1
  120. package/dist/chunk-IO374J6Z.js +0 -2
  121. package/dist/chunk-IO374J6Z.js.map +0 -1
  122. package/dist/chunk-R2ENWQ76.js +0 -2
  123. package/dist/chunk-R2ENWQ76.js.map +0 -1
  124. package/dist/chunk-SOSUS2SK.cjs +0 -3
  125. package/dist/chunk-SOSUS2SK.cjs.map +0 -1
  126. package/dist/chunk-T4Y5XOT2.js +0 -3
  127. package/dist/chunk-T4Y5XOT2.js.map +0 -1
  128. package/dist/chunk-XTM4HTRB.js +0 -2
  129. package/dist/chunk-Z5KBBQOJ.cjs +0 -2
  130. package/dist/chunk-ZJPAPBP3.js +0 -2
package/dist/worker.d.ts CHANGED
@@ -1,18 +1,18 @@
1
1
  import { E as EngineConfigOverride } from './Configuration-BGQn-cJ8.js';
2
- import { U as UnifiedParsingOptions, I as IEnginePackage, J as ParsedLine, P as ParsingResult } from './PackageRegistry-B7wkfSrY.js';
2
+ import { U as UnifiedParsingOptions, I as IEnginePackage, J as ParsedLine, P as ParsingResult } from './PackageRegistry-BJ0QQd3k.js';
3
3
  import { F as FormattingSettings } from './FormattingSettings-bRKjU7wI.js';
4
4
  import { E as EngineError } from './EngineError-Ce1lPkjZ.js';
5
- import { b as ValueType, i as ColourFormat, V as Value } from './Value-D1XlMwe2.js';
6
- import { a as DiagnosticReportJSON } from './pipeline-BH7BFOTJ.js';
5
+ import { b as ValueType, i as ColourFormat, V as Value } from './Value-DCTqTSeP.js';
6
+ import { a as DiagnosticReportJSON } from './pipeline-J2ehIm7t.js';
7
7
  import { S as SerializedEngineError } from './WorkerError-Dhj9BQ_A.js';
8
- import './Parselet-DONNUpur.js';
8
+ import './Parselet-Blq8B0Gj.js';
9
9
  import './BytecodeBuilder-BGq9ZiO3.js';
10
10
  import './Token-CbP_OutD.js';
11
11
  import './Lexer-DKMlj7Sy.js';
12
12
  import './resolvers.js';
13
13
  import '@tanstack/query-core';
14
14
  import './TokenNormalizer-DCWdZjGz.js';
15
- import './ScopeManager-BkbDXK_R.js';
15
+ import './ScopeManager-CF3cZUqW.js';
16
16
 
17
17
  /**
18
18
  * The seam between the harness and whatever actually carries messages.
@@ -199,6 +199,16 @@ interface SerializedValue {
199
199
  range: [number, number];
200
200
  expr?: string;
201
201
  };
202
+ /**
203
+ * IP/CIDR payload, present only for {@link ValueType.IpCidr}: the 32-bit
204
+ * `addr` and/or CIDR `prefix`, plus `text` (the dotted-quad form the answer
205
+ * shows). See issue #189.
206
+ */
207
+ ipCidr?: {
208
+ addr?: number;
209
+ prefix?: number;
210
+ text: string;
211
+ };
202
212
  /** Whether an async fallback timed out, carried through when the engine set it. */
203
213
  timedOut?: boolean;
204
214
  }
package/dist/worker.js CHANGED
@@ -1,3 +1,3 @@
1
- import {a,e,d,c as c$2,b}from'./chunk-MVZUTETT.js';import {n}from'./chunk-T52Y5G24.js';import'./chunk-P6BLASAA.js';import'./chunk-2RWAXT6O.js';import'./chunk-7E7NXKQ5.js';import'./chunk-MIQBJGGR.js';import'./chunk-ZJPAPBP3.js';import'./chunk-GHW2X7PS.js';import {c}from'./chunk-5OIXCVB2.js';import'./chunk-XEIDV5JP.js';import {y as y$1}from'./chunk-T4Y5XOT2.js';import'./chunk-SWKYVSMP.js';import'./chunk-AR7L5OJ2.js';import'./chunk-YVKHEAFT.js';import'./chunk-5FO4PDIG.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-XTM4HTRB.js';import'./chunk-YAYBVVG2.js';import'./chunk-YNMMRH44.js';import'./chunk-HFKDWQUL.js';import {g,f}from'./chunk-R2ENWQ76.js';import {R}from'./chunk-VYWGUMFW.js';import'./chunk-IO374J6Z.js';import'./chunk-WGZ3FNHI.js';import'./chunk-HMEZJXLX.js';import'./chunk-YAHGSBMC.js';import'./chunk-JPFCXLJV.js';import'./chunk-G7TBEQRQ.js';import'./chunk-IJMNVBIS.js';import'./chunk-62LMTO4F.js';import'./chunk-TRBXW6HW.js';import'./chunk-2JMFUQZH.js';import {c as c$1,d as d$1}from'./chunk-MPB7KUN5.js';var x=class{constructor(r){this.nextId=1;this.pending=new Map;this.resolvedListeners=new Set;this.asyncErrorListeners=new Set;this.terminated=false;this.transport=r,this.transport.onMessage(n=>this.onMessage(n));}init(r){let n=this.nextId++;return new Promise((t,s)=>{this.pending.set(n,{resolve:()=>t(),reject:s}),this.transport.postMessage({kind:"init",id:n,localeCode:r.localeCode,diagnostics:r.diagnostics,config:r.config,packages:r.packages,formatting:r.formatting});})}parseDocument(r,n){let{signal:t,...s}=n??{},o=Object.keys(s).length>0?s:void 0;return this.call("parseDocument",[r,o],t)}evaluateLines(r,n){return this.call("evaluateLines",[r],n?.signal)}evaluateExpression(r,n){return this.call("evaluateExpression",[r],n?.signal)}onResolved(r){return this.resolvedListeners.add(r),()=>this.resolvedListeners.delete(r)}onAsyncError(r){return this.asyncErrorListeners.add(r),()=>this.asyncErrorListeners.delete(r)}terminate(){if(this.terminated)return;this.terminated=true;let r=e();for(let n of this.pending.values())this.unhook(n),n.reject(r);this.pending.clear(),this.resolvedListeners.clear(),this.asyncErrorListeners.clear(),this.transport.terminate();}call(r,n,t){if(this.terminated)return Promise.reject(e());if(t?.aborted)return Promise.reject(d(r));let s=this.nextId++;return new Promise((o,l)=>{let c={resolve:o,reject:l};if(t){let p=()=>{this.pending.has(s)&&(this.pending.delete(s),this.transport.postMessage({kind:"cancel",id:s}),l(d(r)));};c.signal=t,c.onAbort=p,t.addEventListener("abort",p,{once:true});}this.pending.set(s,c),this.transport.postMessage({kind:"request",id:s,method:r,args:n});})}onMessage(r){let n=r;switch(n.kind){case "ready":case "result":{let t=n.kind==="result"?n.value:void 0;this.settle(n.id,s=>s.resolve(t));break}case "error":this.settle(n.id,t=>t.reject(c$2(n.error)));break;case "async-update":for(let t of [...this.resolvedListeners])t(n.lines);break;case "async-error":for(let t of [...this.asyncErrorListeners])t({queryKey:n.queryKey,packageId:n.packageId,error:c$2(n.error)});break}}settle(r,n){let t=this.pending.get(r);t&&(this.pending.delete(r),this.unhook(t),n(t));}unhook(r){r.signal&&r.onAbort&&r.signal.removeEventListener("abort",r.onAbort);}};async function K(e){let r=new x(e.transport);return await r.init(e),r}function O(e){return e>0?"Infinity":e<0?"-Infinity":"NaN"}function U(e){let r=e.data.map(n=>typeof n=="object"&&n!==null?R(n):typeof n=="number"&&!Number.isFinite(n)?O(n):n);return {rows:e.rows,cols:e.cols,cells:r,hasSymbolic:e.hasSymbolic}}function m(e,r){let n=e.toNumber(),t={type:e.type,text:c(e,r),number:Number.isFinite(n)?n:0};Number.isFinite(n)||(t.nonFinite=O(n)),e.unit!==void 0&&(t.unit=e.unit),e.timedOut!==void 0&&(t.timedOut=e.timedOut);let s=e.value;if(typeof s=="bigint")t.bigint=s.toString();else if(e.type===7)t.matrix=U(s);else if(e.type===8){let o=s;t.range={min:o.min,max:o.max};}else if(e.type===14){let o=s;t.colour={hex:f(o),r:o.r,g:o.g,b:o.b,a:o.a,format:o.format,css:g(o)};}else if(e.type===16){let o=s;t.chart={kind:o.kind,points:o.points.map(l=>[l[0],l[1]]),label:o.label,domain:[o.domain[0],o.domain[1]],range:[o.range[0],o.range[1]],...o.expr!==void 0?{expr:o.expr}:{}};}return t}function C(e,r){return e?m(e,r):null}function _(e,r){return {start:e.start,end:e.end,expression:e.expression,lineNumber:e.lineNumber,columnNumber:e.columnNumber,result:C(e.result,r),error:e.error??null}}function y(e,r){return {lineNumber:e.lineNumber,text:e.text,startPosition:e.startPosition,endPosition:e.endPosition,isEmpty:e.isEmpty,hasInlineSolves:e.hasInlineSolves,inlineSolves:e.inlineSolves.map(n=>_(n,r)),expression:e.expression,result:C(e.result,r),error:e.error}}function W(e,r){let n={lines:e.lines.map(t=>y(t,r)),totalLines:e.totalLines,errors:[...e.errors]};return e.diagnostics!==void 0&&(n.diagnostics=e.diagnostics),n}function H(e,r){if(r===void 0)return e;let n=new Map(e.map(s=>[s.name,s])),t=[];for(let s of r){let o=n.get(s);if(!o)throw c$1.config(a.WORKER_UNKNOWN_PACKAGE,`No package named "${s}" is available in this worker runtime`,{name:s,available:[...n.keys()]});t.push(o);}return t}function B(e,r={}){let n$1=r.packages??y$1,t=null,s,o=new Map,l=new Map,c=null,p=null,g=i=>e.postMessage(i),h=(i,a)=>{g({kind:"error",id:i,error:b(d$1(a))});},N=i=>{let a=new Map;return i.method==="parseDocument"?i.args[0].split(`
2
- `).forEach((u,d)=>a.set(d+1,u)):i.method==="evaluateLines"?i.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,i.args[0]),a},q=(i,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:b(d$1(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let R=i.evaluateLine(d,f);R&&u.push({lineNumber:d,value:m(R,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},F=i=>{p?.();let a=i.getEventStream().getReader();p=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;q(i,d);}}catch{}})();},V=i=>{try{let a=H(n$1,i.packages);t=new n({locale:i.localeCode??"en",diagnostics:i.diagnostics??!1,config:i.config,packages:a}),s=i.formatting,F(t),g({kind:"ready",id:i.id});}catch(a){h(i.id,a);}},D=(i,a$1)=>{let{method:u,args:d}=a$1;switch(u){case "parseDocument":return W(i.parseDocument(d[0],d[1]),s);case "evaluateLines":return i.evaluateLines(d[0]).map(f=>y(f,s));case "evaluateExpression":return m(i.evaluateExpression(d[0]),s);default:throw c$1.execution(a.WORKER_UNKNOWN_METHOD,`The worker runtime has no method named "${String(u)}"`,{method:u})}},j=i=>{let a$1=t;if(!a$1){h(i.id,c$1.execution(a.WORKER_NOT_INITIALISED,"The worker received a request before its engine finished initialising"));return}c?.abort();let u=new AbortController;c=u,l=N(i),o.set(i.id,u),a$1.setKeystrokeSignal(u.signal);try{let d=D(a$1,i);g({kind:"result",id:i.id,value:d});}catch(d){h(i.id,d);}finally{o.delete(i.id),a$1.setKeystrokeSignal(null);}};return e.onMessage(i=>{let a=i;switch(a.kind){case "init":V(a);break;case "request":j(a);break;case "cancel":o.get(a.id)?.abort();break}}),()=>{p?.(),p=null,c?.abort(),c=null,l=new Map;for(let i of o.values())i.abort();o.clear(),t?.clear(),t=null,e.terminate();}}function G(e){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e))}function J(){let e=null,r=null,n=true,t=(l,c)=>{let p=G(c);queueMicrotask(()=>{n&&l()?.(p);});};return {client:{postMessage:l=>t(()=>r,l),onMessage:l=>{e=l;},terminate:()=>{n=false;}},host:{postMessage:l=>t(()=>e,l),onMessage:l=>{r=l;},terminate:()=>{n=false;}}}}function $(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{let n=t=>r(t.data);typeof e.addEventListener=="function"?e.addEventListener("message",n):e.onmessage=n,e.start?.();},terminate:()=>{e.terminate?.(),e.close?.();}}}function Q(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{e.on("message",n=>r(n));},terminate:()=>{e.terminate?.(),e.close?.();}}}export{J as createLinkedTransports,K as createWorkerEngine,$ as eventTargetTransport,Q as messagePortTransport,y as serializeParsedLine,W as serializeParsingResult,m as serializeValue,B as startWorkerRuntime};//# sourceMappingURL=worker.js.map
1
+ import {a,e,d,c as c$2,b}from'./chunk-MVZUTETT.js';import {n}from'./chunk-HF4H7LYA.js';import'./chunk-JQBG3LX4.js';import'./chunk-2RWAXT6O.js';import'./chunk-7E7NXKQ5.js';import'./chunk-MIQBJGGR.js';import'./chunk-N4HJTHZR.js';import'./chunk-KHCNMNZZ.js';import {c}from'./chunk-5AMJNF7J.js';import'./chunk-XEIDV5JP.js';import {y as y$1}from'./chunk-P5EMTVMJ.js';import'./chunk-JEFMG6CV.js';import'./chunk-AR7L5OJ2.js';import'./chunk-YVKHEAFT.js';import'./chunk-5FO4PDIG.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-HTJPV42D.js';import'./chunk-YAYBVVG2.js';import'./chunk-YNMMRH44.js';import'./chunk-HFKDWQUL.js';import {g,f}from'./chunk-5TCSFTZD.js';import {R as R$1}from'./chunk-WTEXBPBR.js';import'./chunk-A33K7NY4.js';import'./chunk-WGZ3FNHI.js';import'./chunk-CVY2A3TP.js';import'./chunk-YAHGSBMC.js';import'./chunk-JPFCXLJV.js';import'./chunk-G7TBEQRQ.js';import'./chunk-IJMNVBIS.js';import'./chunk-62LMTO4F.js';import'./chunk-TRBXW6HW.js';import'./chunk-2JMFUQZH.js';import {c as c$1,d as d$1}from'./chunk-MPB7KUN5.js';var W=class{constructor(r){this.nextId=1;this.pending=new Map;this.resolvedListeners=new Set;this.asyncErrorListeners=new Set;this.terminated=false;this.transport=r,this.transport.onMessage(n=>this.onMessage(n));}init(r){let n=this.nextId++;return new Promise((t,s)=>{this.pending.set(n,{resolve:()=>t(),reject:s}),this.transport.postMessage({kind:"init",id:n,localeCode:r.localeCode,diagnostics:r.diagnostics,config:r.config,packages:r.packages,formatting:r.formatting});})}parseDocument(r,n){let{signal:t,...s}=n??{},i=Object.keys(s).length>0?s:void 0;return this.call("parseDocument",[r,i],t)}evaluateLines(r,n){return this.call("evaluateLines",[r],n?.signal)}evaluateExpression(r,n){return this.call("evaluateExpression",[r],n?.signal)}onResolved(r){return this.resolvedListeners.add(r),()=>this.resolvedListeners.delete(r)}onAsyncError(r){return this.asyncErrorListeners.add(r),()=>this.asyncErrorListeners.delete(r)}terminate(){if(this.terminated)return;this.terminated=true;let r=e();for(let n of this.pending.values())this.unhook(n),n.reject(r);this.pending.clear(),this.resolvedListeners.clear(),this.asyncErrorListeners.clear(),this.transport.terminate();}call(r,n,t){if(this.terminated)return Promise.reject(e());if(t?.aborted)return Promise.reject(d(r));let s=this.nextId++;return new Promise((i,l)=>{let p={resolve:i,reject:l};if(t){let c=()=>{this.pending.has(s)&&(this.pending.delete(s),this.transport.postMessage({kind:"cancel",id:s}),l(d(r)));};p.signal=t,p.onAbort=c,t.addEventListener("abort",c,{once:true});}this.pending.set(s,p),this.transport.postMessage({kind:"request",id:s,method:r,args:n});})}onMessage(r){let n=r;switch(n.kind){case "ready":case "result":{let t=n.kind==="result"?n.value:void 0;this.settle(n.id,s=>s.resolve(t));break}case "error":this.settle(n.id,t=>t.reject(c$2(n.error)));break;case "async-update":for(let t of [...this.resolvedListeners])t(n.lines);break;case "async-error":for(let t of [...this.asyncErrorListeners])t({queryKey:n.queryKey,packageId:n.packageId,error:c$2(n.error)});break}}settle(r,n){let t=this.pending.get(r);t&&(this.pending.delete(r),this.unhook(t),n(t));}unhook(r){r.signal&&r.onAbort&&r.signal.removeEventListener("abort",r.onAbort);}};async function K(e){let r=new W(e.transport);return await r.init(e),r}function C(e){return e>0?"Infinity":e<0?"-Infinity":"NaN"}function U(e){let r=e.data.map(n=>typeof n=="object"&&n!==null?R$1(n):typeof n=="number"&&!Number.isFinite(n)?C(n):n);return {rows:e.rows,cols:e.cols,cells:r,hasSymbolic:e.hasSymbolic}}function m(e,r){let n=e.toNumber(),t={type:e.type,text:c(e,r),number:Number.isFinite(n)?n:0};Number.isFinite(n)||(t.nonFinite=C(n)),e.unit!==void 0&&(t.unit=e.unit),e.timedOut!==void 0&&(t.timedOut=e.timedOut);let s=e.value;if(typeof s=="bigint")t.bigint=s.toString();else if(e.type===7)t.matrix=U(s);else if(e.type===8){let i=s;t.range={min:i.min,max:i.max};}else if(e.type===14){let i=s;t.colour={hex:f(i),r:i.r,g:i.g,b:i.b,a:i.a,format:i.format,css:g(i)};}else if(e.type===16){let i=s;t.chart={kind:i.kind,points:i.points.map(l=>[l[0],l[1]]),label:i.label,domain:[i.domain[0],i.domain[1]],range:[i.range[0],i.range[1]],...i.expr!==void 0?{expr:i.expr}:{}};}else if(e.type===17){let i=s;t.ipCidr={...i.addr!==void 0?{addr:i.addr}:{},...i.prefix!==void 0?{prefix:i.prefix}:{},text:c(e).replace(/^=\s*/,"")};}return t}function O(e,r){return e?m(e,r):null}function _(e,r){return {start:e.start,end:e.end,expression:e.expression,lineNumber:e.lineNumber,columnNumber:e.columnNumber,result:O(e.result,r),error:e.error??null}}function y(e,r){return {lineNumber:e.lineNumber,text:e.text,startPosition:e.startPosition,endPosition:e.endPosition,isEmpty:e.isEmpty,hasInlineSolves:e.hasInlineSolves,inlineSolves:e.inlineSolves.map(n=>_(n,r)),expression:e.expression,result:O(e.result,r),error:e.error}}function R(e,r){let n={lines:e.lines.map(t=>y(t,r)),totalLines:e.totalLines,errors:[...e.errors]};return e.diagnostics!==void 0&&(n.diagnostics=e.diagnostics),n}function H(e,r){if(r===void 0)return e;let n=new Map(e.map(s=>[s.name,s])),t=[];for(let s of r){let i=n.get(s);if(!i)throw c$1.config(a.WORKER_UNKNOWN_PACKAGE,`No package named "${s}" is available in this worker runtime`,{name:s,available:[...n.keys()]});t.push(i);}return t}function B(e,r={}){let n$1=r.packages??y$1,t=null,s,i=new Map,l=new Map,p=null,c=null,g=o=>e.postMessage(o),h=(o,a)=>{g({kind:"error",id:o,error:b(d$1(a))});},N=o=>{let a=new Map;return o.method==="parseDocument"?o.args[0].split(`
2
+ `).forEach((u,d)=>a.set(d+1,u)):o.method==="evaluateLines"?o.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,o.args[0]),a},q=(o,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:b(d$1(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let L=o.evaluateLine(d,f);L&&u.push({lineNumber:d,value:m(L,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},F=o=>{c?.();let a=o.getEventStream().getReader();c=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;q(o,d);}}catch{}})();},D=o=>{try{let a=H(n$1,o.packages);t=new n({locale:o.localeCode??"en",diagnostics:o.diagnostics??!1,config:o.config,packages:a}),s=o.formatting,F(t),g({kind:"ready",id:o.id});}catch(a){h(o.id,a);}},V=(o,a$1)=>{let{method:u,args:d}=a$1;switch(u){case "parseDocument":return R(o.parseDocument(d[0],d[1]),s);case "evaluateLines":return o.evaluateLines(d[0]).map(f=>y(f,s));case "evaluateExpression":return m(o.evaluateExpression(d[0]),s);default:throw c$1.execution(a.WORKER_UNKNOWN_METHOD,`The worker runtime has no method named "${String(u)}"`,{method:u})}},j=o=>{let a$1=t;if(!a$1){h(o.id,c$1.execution(a.WORKER_NOT_INITIALISED,"The worker received a request before its engine finished initialising"));return}p?.abort();let u=new AbortController;p=u,l=N(o),i.set(o.id,u),a$1.setKeystrokeSignal(u.signal);try{let d=V(a$1,o);g({kind:"result",id:o.id,value:d});}catch(d){h(o.id,d);}finally{i.delete(o.id),a$1.setKeystrokeSignal(null);}};return e.onMessage(o=>{let a=o;switch(a.kind){case "init":D(a);break;case "request":j(a);break;case "cancel":i.get(a.id)?.abort();break}}),()=>{c?.(),c=null,p?.abort(),p=null,l=new Map;for(let o of i.values())o.abort();i.clear(),t?.clear(),t=null,e.terminate();}}function G(e){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e))}function J(){let e=null,r=null,n=true,t=(l,p)=>{let c=G(p);queueMicrotask(()=>{n&&l()?.(c);});};return {client:{postMessage:l=>t(()=>r,l),onMessage:l=>{e=l;},terminate:()=>{n=false;}},host:{postMessage:l=>t(()=>e,l),onMessage:l=>{r=l;},terminate:()=>{n=false;}}}}function $(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{let n=t=>r(t.data);typeof e.addEventListener=="function"?e.addEventListener("message",n):e.onmessage=n,e.start?.();},terminate:()=>{e.terminate?.(),e.close?.();}}}function Q(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{e.on("message",n=>r(n));},terminate:()=>{e.terminate?.(),e.close?.();}}}export{J as createLinkedTransports,K as createWorkerEngine,$ as eventTargetTransport,Q as messagePortTransport,y as serializeParsedLine,R as serializeParsingResult,m as serializeValue,B as startWorkerRuntime};//# sourceMappingURL=worker.js.map
3
3
  //# sourceMappingURL=worker.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/worker/client.ts","../src/worker/serialize.ts","../src/worker/runtime.ts","../src/worker/transport.ts"],"names":["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","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","runMethod","handleRequest","controller","cloneMessage","createLinkedTransports","clientHandler","hostHandler","alive","deliver","target","cloned","handler","eventTargetTransport","messagePortTransport","port"],"mappings":"whCA8HA,IAAMA,CAAAA,CAAN,KAAiD,CAWhD,WAAA,CAAYC,CAAAA,CAA4B,CATxC,IAAA,CAAQ,MAAA,CAAS,CAAA,CACjB,IAAA,CAAiB,OAAA,CAAU,IAAI,GAAA,CAI/B,IAAA,CAAiB,iBAAA,CAAoB,IAAI,GAAA,CACzC,IAAA,CAAiB,mBAAA,CAAsB,IAAI,GAAA,CAC3C,IAAA,CAAQ,UAAA,CAAa,KAAA,CAGpB,IAAA,CAAK,SAAA,CAAYA,CAAAA,CACjB,IAAA,CAAK,SAAA,CAAU,SAAA,CAAWC,CAAAA,EAAQ,IAAA,CAAK,SAAA,CAA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AAK,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 type { EngineConfigOverride } from \"@solve-js/constants/Configuration\";\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\tSerializedValue,\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 SerializedValue}. 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: SerializedValue;\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<SerializedValue>;\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\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: 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<SerializedValue> {\n\t\treturn this.call<SerializedValue>(\"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 } 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\tSerializedValue,\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 SerializedValue}.\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): SerializedValue {\n\tconst reading = value.toNumber();\n\tconst dto: SerializedValue = {\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\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}\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): SerializedValue | 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 type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\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, chiefly its custom packages. */\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}\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});\n\t\t\tformatting = 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":["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","runMethod","handleRequest","controller","cloneMessage","createLinkedTransports","clientHandler","hostHandler","alive","deliver","target","cloned","handler","eventTargetTransport","messagePortTransport","port"],"mappings":"+hCA8HA,IAAMA,CAAAA,CAAN,KAAiD,CAWhD,WAAA,CAAYC,CAAAA,CAA4B,CATxC,IAAA,CAAQ,MAAA,CAAS,CAAA,CACjB,IAAA,CAAiB,OAAA,CAAU,IAAI,GAAA,CAI/B,IAAA,CAAiB,iBAAA,CAAoB,IAAI,GAAA,CACzC,IAAA,CAAiB,mBAAA,CAAsB,IAAI,GAAA,CAC3C,IAAA,CAAQ,UAAA,CAAa,KAAA,CAGpB,IAAA,CAAK,SAAA,CAAYA,CAAAA,CACjB,IAAA,CAAK,UAAU,SAAA,CAAWC,CAAAA,EAAQ,IAAA,CAAK,SAAA,CAAUA,CAAG,CAAC,EACtD,CAGA,IAAA,CAAKC,CAAAA,CAA6C,CACjD,IAAMC,CAAAA,CAAK,IAAA,CAAK,MAAA,EAAA,CAChB,OAAO,IAAI,OAAA,CAAc,CAACC,CAAAA,CAASC,CAAAA,GAAW,CAC7C,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAIF,CAAAA,CAAI,CAAE,OAAA,CAAS,IAAMC,CAAAA,EAAQ,CAAG,MAAA,CAAAC,CAAO,CAAC,CAAA,CACzD,IAAA,CAAK,SAAA,CAAU,WAAA,CAAY,CAC1B,IAAA,CAAM,MAAA,CACN,EAAA,CAAAF,CAAAA,CACA,UAAA,CAAYD,CAAAA,CAAQ,UAAA,CACpB,WAAA,CAAaA,CAAAA,CAAQ,WAAA,CACr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B,CAAA,CACA,SAAA,CAAW,IAAM,CAChBJ,CAAAA,CAAQ,MACT,CACD,EAYiB,IAAA,CAVa,CAC7B,WAAA,CAAczE,CAAAA,EAAY0E,EAAQ,IAAMH,CAAAA,CAAevE,CAAO,CAAA,CAC9D,UAAY6E,CAAAA,EAAY,CACvBL,CAAAA,CAAcK,EACf,EACA,SAAA,CAAW,IAAM,CAChBJ,CAAAA,CAAQ,MACT,CACD,CAEsB,CACvB,CAqBO,SAASK,EAAqBH,CAAAA,CAA0C,CAC9E,OAAO,CACN,YAAc3E,CAAAA,EAAY2E,CAAAA,CAAO,WAAA,CAAY3E,CAAO,EACpD,SAAA,CAAY6E,CAAAA,EAAY,CACvB,IAAMrF,EAAYkE,CAAAA,EAAmCmB,CAAAA,CAAQnB,CAAAA,CAAM,IAAI,EACnE,OAAOiB,CAAAA,CAAO,gBAAA,EAAqB,UAAA,CACtCA,EAAO,gBAAA,CAAiB,SAAA,CAAWnF,CAAQ,CAAA,CAE3CmF,EAAO,SAAA,CAAYnF,CAAAA,CAEpBmF,CAAAA,CAAO,KAAA,KACR,CAAA,CAGA,SAAA,CAAW,IAAM,CAChBA,CAAAA,CAAO,aAAY,CACnBA,CAAAA,CAAO,KAAA,KACR,CACD,CACD,CAmBO,SAASI,CAAAA,CAAqBC,EAAwC,CAC5E,OAAO,CACN,WAAA,CAAchF,GAAYgF,CAAAA,CAAK,WAAA,CAAYhF,CAAO,CAAA,CAClD,UAAY6E,CAAAA,EAAY,CACvBG,CAAAA,CAAK,EAAA,CAAG,UAAYhF,CAAAA,EAAY6E,CAAAA,CAAQ7E,CAAO,CAAC,EACjD,CAAA,CACA,SAAA,CAAW,IAAM,CAChBgF,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 type { EngineConfigOverride } from \"@solve-js/constants/Configuration\";\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\tSerializedValue,\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 SerializedValue}. 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: SerializedValue;\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<SerializedValue>;\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\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: 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<SerializedValue> {\n\t\treturn this.call<SerializedValue>(\"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\tSerializedValue,\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 SerializedValue}.\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): SerializedValue {\n\tconst reading = value.toNumber();\n\tconst dto: SerializedValue = {\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\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): SerializedValue | 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 type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\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, chiefly its custom packages. */\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}\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});\n\t\t\tformatting = 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.6.0",
3
+ "version": "2.7.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,3 +0,0 @@
1
- 'use strict';var chunkR2SZFJTT_cjs=require('./chunk-R2SZFJTT.cjs'),chunkESUN2THE_cjs=require('./chunk-ESUN2THE.cjs'),chunkZOOVGXMK_cjs=require('./chunk-ZOOVGXMK.cjs'),chunk5FGOIDLS_cjs=require('./chunk-5FGOIDLS.cjs'),chunkMSYX32PF_cjs=require('./chunk-MSYX32PF.cjs');var b={floatResult:{decimalPlaces:2,enableSeperator:true},numberResult:{decimalSeparatorLocale:"en-US"},hexResult:{enablePadding:false,paddingZeros:0},unitOfMeasurementResult:{decimalPlaces:2},percentageResult:{decimalPlaces:2},dateResult:{format:"long"}};function D(t,r,o,n){let e=o.floatResult.enableSeperator,i=o.numberResult.decimalSeparatorLocale;if(n!==void 0&&Number.isFinite(t)){let c=t.toLocaleString(i||"en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:e});return `${r.display.resultPrefix}${c}`}let a=o.floatResult.decimalPlaces,s=chunkR2SZFJTT_cjs.a(t,a,e,i);return `${r.display.resultPrefix}${s}`}function F(t,r,o,n){let e=n.floatResult.decimalPlaces,i=n.floatResult.enableSeperator,a=n.numberResult.decimalSeparatorLocale||"en-US",s=Math.max(e,1),c=t.toLocaleString(a,{useGrouping:i,minimumFractionDigits:0,maximumFractionDigits:e}),u=Math.abs(r).toLocaleString(a,{useGrouping:i,minimumFractionDigits:1,maximumFractionDigits:s});return `${o.display.resultPrefix}${c} \xB1 ${u}`}function R(t,r,o){if(typeof t=="number"&&!Number.isFinite(t))return `= ${t}`;let n=typeof t=="bigint"?t<0n:t<0,e=n?"-":"",i=c=>typeof t=="bigint"?(n?-t:t).toString(c):Math.abs(Math.trunc(t)).toString(c);if(o==="bin")return `= ${e}0b${i(2)}`;if(o==="oct")return `= ${e}0o${i(8)}`;let a=r.hexResult.enablePadding?r.hexResult.paddingZeros:0,s=i(16).toUpperCase().padStart(a,"0");return `= ${e}0x${s}`}var L=2e4;function P(t){let r=t<0n?-t:t;if(Number.isFinite(Number(r)))return `= ${t}`;let o=r.toString(16).length*4;if(o*Math.LN2/Math.LN10<=L)return `= ${t}`;let n=o*Math.LN2/Math.LN10,e=Math.floor(n),i=Math.pow(10,n-e);return `= ${t<0n?"-":""}~${i.toFixed(3)}e+${e} (an exact integer of about ${(e+1).toLocaleString("en-US")} digits, too large to print)`}function T(t){return `= ${t}`}function I(t){return `= ${t}`}function w(t,r,o){let n=new Date(t),e=o.dateResult?.format??"long",i=n.getHours()===0&&n.getMinutes()===0&&n.getSeconds()===0&&n.getMilliseconds()===0;if(e==="long"){let g=n.toLocaleDateString(r.code,{weekday:"long",year:"numeric",month:"long",day:"numeric"});return i?`= ${g}`:`= ${g}, ${n.toLocaleTimeString(r.code)}`}let a=g=>String(g).padStart(2,"0"),s=n.getFullYear(),c=a(n.getMonth()+1),u=a(n.getDate()),m;if(e==="iso"?m=`${s}-${c}-${u}`:e==="dmy"?m=`${u}/${c}/${s}`:m=`${c}/${u}/${s}`,i)return `= ${m}`;let l=`${a(n.getHours())}:${a(n.getMinutes())}:${a(n.getSeconds())}`;return e==="iso"?`= ${m}T${l}`:`= ${m} ${l}`}function N(t){let r=t<0?"-":"",o=Math.round(Math.abs(t)/1e3),n=Math.floor(o/3600),e=Math.floor(o%3600/60),i=o%60,a=String(e).padStart(2,"0");if(i===0)return `${r}${n}:${a}`;let s=String(i).padStart(2,"0");return `${r}${n}:${a}:${s}`}function U(t,r,o,n,e){if(r==="ms")return `= ${N(t)}`;let i=n.unitOfMeasurementResult.decimalPlaces,s=r&&["days","weeks","months","years","hours","minutes","seconds","day","week","month","year","hour","minute","second"].includes(r),c;s&&t===Math.floor(t)?c=t.toString():c=t.toFixed(i);let u=r?chunkZOOVGXMK_cjs.ua[r.toUpperCase()]:void 0;if(u){let l=e?chunkZOOVGXMK_cjs.sa(e,i):c,g=u.spaced?" ":"";return `= ${u.position==="prefix"?`${u.symbol}${g}${l}`:`${l}${g}${u.symbol}`}`}return `= ${e?chunkZOOVGXMK_cjs.sa(e,i):c} ${r||""}`.trim()}function M(t,r){if(typeof t=="boolean")return t?"true":"false";if(typeof t=="object"&&t!==null)return chunkZOOVGXMK_cjs.R(t);let o=r.floatResult.decimalPlaces,n=r.floatResult.enableSeperator,e=r.numberResult.decimalSeparatorLocale;return chunkR2SZFJTT_cjs.a(t,o,n,e)}function C(t,r,o){let n=chunkZOOVGXMK_cjs.Z(t),e=[];for(let i=0;i<t.rows;i++){let a=[];for(let s=0;s<t.cols;s++)a.push(M(n[i*t.cols+s],o));e.push(a.join(", "));}return `${r.display.resultPrefix}[${e.join("; ")}]`}function Q(t,r){let o=r||b,n=chunkZOOVGXMK_cjs.Z(t),e=[];for(let a=0;a<t.rows;a++){let s=[];for(let c=0;c<t.cols;c++)s.push(M(n[a*t.cols+c],o));e.push(s);}let i=[];for(let a=0;a<t.cols;a++){let s=0;for(let c=0;c<t.rows;c++)s=Math.max(s,e[c][a].length);i.push(s);}return e.map(a=>`[ ${a.map((s,c)=>s.padStart(i[c])).join(" ")} ]`).join(`
2
- `)}function E(t,r,o){return `${o.display.resultPrefix}${t}:${r}`}function j(t,r,o){let n=o.percentageResult.decimalPlaces;return `= ${(t*100).toFixed(n)}${r.display.percentageSuffix}`}function A(t,r){return `= ${t} ${r||""}`.trim()}function G(t,r,o){let n=r.display.resultPrefix,e=u=>{let m=t.unit!==void 0?new chunk5FGOIDLS_cjs.m(6,u.value,t.unit):new chunk5FGOIDLS_cjs.m(0,u.value);m.exact=u.exact;let l=O(m,o);return l.startsWith(n)?l.slice(n.length):l},[i,a]=t.shares,s=`${e(i)} each`;if(a===void 0)return `${n}${s}`;let c=a.count===1?"share":"shares";return `${n}${s}, with ${a.count} ${c} paying ${e(a)}`}function O(t,r){let o=r||b,n=o.numberResult.decimalSeparatorLocale||"en",e=chunkMSYX32PF_cjs.a(n);switch(t.type){case 0:return t.uncertainty!==void 0?F(t.value,t.uncertainty,e,o):D(t.value,e,o,t.decimalPlaces);case 1:return R(t.value,o,t.unit);case 2:return P(t.value);case 3:return T(t.value);case 10:return I(t.value);case 4:return w(t.value,e,o);case 6:return U(t.value,t.unit,e,o,t.exact);case 7:return C(t.value,e,o);case 8:{let i=t.value;return E(i.min,i.max,e)}case 14:return `${e.display.resultPrefix}${chunkESUN2THE_cjs.g(t.value)}`;case 15:return G(t.value,e,o);case 16:return `${e.display.resultPrefix}${t.value.label}`;case 9:return chunkZOOVGXMK_cjs.R(t.value);case 5:return j(t.value,e,o);case 11:return A(t.value,t.unit);case 13:return t.unit??String(t.value);default:return `= ${String(t.value)}`}}exports.a=b;exports.b=Q;exports.c=O;//# sourceMappingURL=chunk-3DD2RVBI.cjs.map
3
- //# sourceMappingURL=chunk-3DD2RVBI.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/format/FormattingSettings.ts","../src/format/FormatEngine.ts"],"names":["DEFAULT_FORMATTING_SETTINGS","formatNumber","value","locale","settings","decimalPlaces","sep","loc","formatted","dp","autoFormatIntegerOrFloat","formatUncertain","center","uncertainty","useGrouping","spreadMax","centerText","spreadText","formatHex","base","negative","sign","digits","radix","padding","hex","MAX_DISPLAYED_BIGINT_DIGITS","formatBigInt","magnitude","bits","log10","exponent","mantissa","formatString","formatBoolean","formatDatetime","d","format","isMidnight","dateStr","p2","n","year","month","day","datePart","time","formatMsDuration","ms","totalSeconds","hours","minutes","seconds","mm","ss","formatUom","unit","exact","isTimeSpan","currencyDisplay","CURRENCY_DISPLAY","moneyText","decimalToFixed","formatMatrixEntry","entry","formatSymbolic","formatMatrix","m","rowMajor","columnMajorToRowMajor","rows","r","cells","c","formatMatrixAligned","us","row","colWidth","width","cell","formatRange","min","max","formatPercentage","formatUnit","formatSplit","data","prefix","render","share","v","Value","text","formatValue","high","each","shareWord","localeCode","getLocale","formatColour"],"mappings":"2QA8CO,IAAMA,CAAAA,CAAkD,CAC7D,WAAA,CAAa,CACX,aAAA,CAAe,CAAA,CACf,eAAA,CAAiB,IACnB,CAAA,CACA,YAAA,CAAc,CACZ,sBAAA,CAAwB,OAC1B,EACA,SAAA,CAAW,CACT,aAAA,CAA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C,CACA,QACE,OAAO,CAAA,EAAGA,EAAO,OAAA,CAAQ,YAAY,CAAA,EAAGgG,mBAAAA,CAAajG,EAAM,KAAmB,CAAC,GACjF,KAAA,EAAA,CACE,OAAOmF,EAAYnF,CAAAA,CAAM,KAAA,CAAoBC,CAAAA,CAAQwE,CAAE,EACzD,KAAA,EAAA,CAGE,OAAO,GAAGxE,CAAAA,CAAO,OAAA,CAAQ,YAAY,CAAA,EAAID,CAAAA,CAAM,KAAA,CAAoB,KAAK,GAC1E,KAAA,CAAA,CACE,OAAO+D,mBAAAA,CAAe/D,CAAAA,CAAM,KAAqB,CAAA,CACnD,KAAA,CAAA,CACE,OAAOiF,CAAAA,CAAiBjF,EAAM,KAAA,CAAiBC,CAAAA,CAAQwE,CAAE,CAAA,CAC3D,KAAA,EAAA,CACE,OAAOS,CAAAA,CAAWlF,CAAAA,CAAM,KAAA,CAAiBA,CAAAA,CAAM,IAAI,CAAA,CACrD,KAAA,EAAA,CAKE,OAAOA,CAAAA,CAAM,IAAA,EAAQ,OAAOA,CAAAA,CAAM,KAAK,CAAA,CACzC,QACE,OAAO,CAAA,EAAA,EAAK,MAAA,CAAOA,EAAM,KAAK,CAAC,EACnC,CACF","file":"chunk-3DD2RVBI.cjs","sourcesContent":["/**\n * How a Datetime value is rendered.\n *\n * - `'long'`: the spelled-out form, \"Tuesday, March 10, 2026\" (the default).\n * - `'iso'`: \"2026-03-10\" (ISO 8601, with a `T`-separated time when present).\n * - `'dmy'`: \"10/03/2026\" (day first).\n * - `'mdy'`: \"03/10/2026\" (month first).\n *\n * The weekday and long month name in `'long'` are localised through the same\n * locale the number separators come from; the numeric forms are locale-neutral.\n */\nexport type DateOutputFormat = \"long\" | \"iso\" | \"dmy\" | \"mdy\";\n\n/**\n * Minimal formatting settings interface for the engine\n * This allows the engine to format values without depending on app-specific settings\n */\nexport interface FormattingSettings {\n floatResult: {\n decimalPlaces: number;\n enableSeperator: boolean;\n };\n numberResult: {\n decimalSeparatorLocale: string;\n };\n hexResult: {\n enablePadding: boolean;\n paddingZeros: number;\n };\n unitOfMeasurementResult: {\n decimalPlaces: number;\n };\n percentageResult: {\n decimalPlaces: number;\n };\n /**\n * Optional so a host that built a `FormattingSettings` before this field\n * existed still compiles; a missing `dateResult` reads as `'long'`, the\n * historic output.\n */\n dateResult?: {\n format: DateOutputFormat;\n };\n}\n\n/** Formatting used when a host supplies none. */\nexport const DEFAULT_FORMATTING_SETTINGS: FormattingSettings = {\n floatResult: {\n decimalPlaces: 2,\n enableSeperator: true,\n },\n numberResult: {\n decimalSeparatorLocale: \"en-US\",\n },\n hexResult: {\n enablePadding: false,\n paddingZeros: 0,\n },\n unitOfMeasurementResult: {\n decimalPlaces: 2,\n },\n percentageResult: {\n decimalPlaces: 2,\n },\n dateResult: {\n format: \"long\",\n },\n};\n","import { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type SplitData, type SplitShare, type ChartData } from \"@solve-js/vm/Value\";\nimport { formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport { decimalToFixed, type DecimalData } from \"@solve-js/decimal\";\nimport { getLocale, type ILocale } from \"@solve-js/constants/locales\";\nimport { autoFormatIntegerOrFloat } from \"@solve-js/utilities/Number\";\nimport { FormattingSettings, DEFAULT_FORMATTING_SETTINGS } from \"./FormattingSettings\";\nimport { CURRENCY_DISPLAY } from \"@solve-js/uom/CurrencyAliases\";\nimport { columnMajorToRowMajor } from \"@solve-js/vm/MatrixOps\";\nimport { formatSymbolic, type SymbolicNode } from \"@solve-js/symbolic\";\n\nfunction formatNumber(value: number, locale: ILocale, settings: FormattingSettings, decimalPlaces?: number): string {\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n // An explicit precision (`3.14159 to 4 dp`, `round(1.5, 2)`) shows EXACTLY that\n // many places with trailing zeros kept, where the default trims them and shows\n // an integer with none. The value was already rounded to this precision when\n // it was set (see VMBuiltins' roundToPlaces, exact where an exact decimal was\n // there), so rendering it to the same place count reproduces that rounding.\n if (decimalPlaces !== undefined && Number.isFinite(value)) {\n const formatted = value.toLocaleString(loc || \"en-US\", {\n minimumFractionDigits: decimalPlaces,\n maximumFractionDigits: decimalPlaces,\n useGrouping: sep,\n });\n return `${locale.display.resultPrefix}${formatted}`;\n }\n const dp = settings.floatResult.decimalPlaces;\n const formatted = autoFormatIntegerOrFloat(value, dp, sep, loc);\n return `${locale.display.resultPrefix}${formatted}`;\n}\n\n/**\n * Renders a measurement that carries a one-sigma uncertainty as\n * `center ± spread`, e.g. `49.2 ± 2.0`.\n *\n * The center is shown the way any number is, whole numbers as integers and\n * trailing zeros trimmed, so a tolerance-free-looking center still reads\n * cleanly (\"30 ± 2.24\", not \"30.00 ± 2.24\"). The spread is shown to the same\n * decimal-place budget but always keeps at least one fractional digit, which is\n * what distinguishes it as a tolerance and gives \"± 2.0\" rather than \"± 2\".\n * Both use `Intl` with `maximumFractionDigits`, so the trailing-zero trimming is\n * locale-correct (a comma-decimal locale is not string-sliced on \".\").\n *\n * The symbol is always the `±` glyph on output, even when the input was the\n * ASCII `+/-`, since the glyph is the conventional notation and unambiguous to\n * read back.\n */\nfunction formatUncertain(center: number, uncertainty: number, locale: ILocale, settings: FormattingSettings): string {\n const dp = settings.floatResult.decimalPlaces;\n const useGrouping = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale || \"en-US\";\n // The spread needs room for at least one fractional digit, so a zero-decimal\n // budget cannot leave minimumFractionDigits above maximumFractionDigits.\n const spreadMax = Math.max(dp, 1);\n const centerText = center.toLocaleString(loc, { useGrouping, minimumFractionDigits: 0, maximumFractionDigits: dp });\n const spreadText = Math.abs(uncertainty).toLocaleString(loc, { useGrouping, minimumFractionDigits: 1, maximumFractionDigits: spreadMax });\n return `${locale.display.resultPrefix}${centerText} ± ${spreadText}`;\n}\n\n/**\n * Renders a number in whichever base it is tagged with.\n *\n * The zero padding is a hexadecimal setting and stays one. Applying it to a\n * binary rendering would pad `0b101` out to the same digit count as a hex\n * value, which is a different quantity of zeros and not what the setting asks\n * for.\n */\nfunction formatHex(value: number | bigint, settings: FormattingSettings, base?: string): string {\n // An infinity or a NaN has no digits in any base, and asking for them\n // produced `0xINFINITY`, a literal that reads back as nothing at all. Render\n // the value itself, which is what every other non-finite result shows.\n if (typeof value === \"number\" && !Number.isFinite(value)) return `= ${value}`;\n\n // Truncate and take the sign off before converting. `Number.toString(radix)`\n // does neither: it renders -255 as \"-ff\", which lands the minus inside the\n // literal as `0x-FF`, and it renders 255.7 as \"ff.b3333333333\", inventing\n // fractional hex digits for a notation that has no use for them. Both were\n // visible on `as hex` until the builtins started sharing this path.\n //\n // A bigint needs neither truncation nor a Math call, and must not be routed\n // through one: passing it to Math.trunc() throws, and converting it to a\n // double first is exactly the precision loss it is carried as a bigint to\n // avoid.\n const negative = typeof value === \"bigint\" ? value < 0n : value < 0;\n const sign = negative ? \"-\" : \"\";\n const digits = (radix: number): string =>\n typeof value === \"bigint\"\n ? (negative ? -value : value).toString(radix)\n : Math.abs(Math.trunc(value)).toString(radix);\n\n if (base === \"bin\") return `= ${sign}0b${digits(2)}`;\n if (base === \"oct\") return `= ${sign}0o${digits(8)}`;\n const padding = settings.hexResult.enablePadding ? settings.hexResult.paddingZeros : 0;\n const hex = digits(16).toUpperCase().padStart(padding, \"0\");\n return `= ${sign}0x${hex}`;\n}\n\n/**\n * How many decimal digits of an exact integer this will render in full.\n *\n * A little above the ~19,729 digits of the largest bigint the VM will build\n * (`vm/VM.ts`'s MAX_EXACT_POW_BITS / MAX_EXACT_SHIFT_BITS, 65,536 bits), so\n * every value the engine can produce through `^` or `<<` still prints exactly\n * and this ceiling only ever meets a value that came from somewhere else.\n */\nconst MAX_DISPLAYED_BIGINT_DIGITS = 20000;\n\n/**\n * Renders an exact integer, or describes it when writing it out is itself the\n * expensive operation.\n *\n * This used to be a bare `= ${value}` template, which renders whatever it is\n * handed: `1n << 100000000` took 8.5 seconds here turning a 12.5MB integer\n * into a thirty-million-character string, and a host has no way to opt out,\n * since displaying the answer is what it asked the engine for. The VM's own\n * ceiling on `<<` and `^` now stops that value existing, so this is the\n * backstop for every other way a large bigint can arrive (repeated `x * x`,\n * a Value a host built itself), and it costs one comparison for every value\n * that is not absurd.\n *\n * The digit count is estimated from the bit length rather than measured, since\n * measuring means doing the conversion this exists to avoid. Bit length comes\n * off the hexadecimal form, which is linear in the size of the value where the\n * decimal form is not.\n */\nfunction formatBigInt(value: bigint): string {\n const magnitude = value < 0n ? -value : value;\n // Every bigint a person actually reads takes this line and nothing else:\n // anything a double can hold is at most 309 digits, so it is printable\n // without measuring it at all.\n if (Number.isFinite(Number(magnitude))) return `= ${value}`;\n const bits = magnitude.toString(16).length * 4;\n if (bits * Math.LN2 / Math.LN10 <= MAX_DISPLAYED_BIGINT_DIGITS) return `= ${value}`;\n const log10 = bits * Math.LN2 / Math.LN10;\n const exponent = Math.floor(log10);\n const mantissa = Math.pow(10, log10 - exponent);\n const sign = value < 0n ? \"-\" : \"\";\n return `= ${sign}~${mantissa.toFixed(3)}e+${exponent} (an exact integer of about ${(exponent + 1).toLocaleString(\"en-US\")} digits, too large to print)`;\n}\n\nfunction formatString(value: string): string {\n return `= ${value}`;\n}\n\nfunction formatBoolean(value: boolean): string {\n return `= ${value}`;\n}\n\n/**\n * Renders a Datetime value locale-aware, the previous implementation\n * called `d.toLocaleString()` with no arguments, which always uses the JS\n * runtime's own default locale and never actually consulted `locale.code`\n * despite receiving it as a parameter (both branches of its old\n * `dateFormat === \"default\"` check were byte-for-byte identical, dead\n * groundwork for a distinction that was never implemented). Concretely,\n * this meant every configured locale (including the shipped German one)\n * always displayed weekday/month names in English. See GitHub issue #77.\n *\n * Uses `weekday`/`month`: \"long\" for a spelled-out date (\"Monday,\n * November 17, 2025\" / \"lundi 17 novembre 2025\") since that's what a\n * literal weekday name is for; a bare numeric date doesn't need\n * localizing beyond the decimal/thousands separators `formatNumber()`\n * already handles. The time-of-day portion is only appended when it's\n * not exactly local midnight, bare date literals (\"today\", \"17/11/2025\")\n * always anchor to local midnight, and showing \"00:00:00\" on every one of\n * those would be noise, not information.\n */\nfunction formatDatetime(value: number, locale: ILocale, settings: FormattingSettings): string {\n const d = new Date(value);\n const format = settings.dateResult?.format ?? \"long\";\n const isMidnight = d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0 && d.getMilliseconds() === 0;\n\n // The spelled-out default, localised through the locale's own names.\n if (format === \"long\") {\n const dateStr = d.toLocaleDateString(locale.code, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" });\n if (isMidnight) return `= ${dateStr}`;\n return `= ${dateStr}, ${d.toLocaleTimeString(locale.code)}`;\n }\n\n // The numeric forms, built from the local calendar fields so they read the\n // same regardless of the JS runtime's own default locale.\n const p2 = (n: number) => String(n).padStart(2, \"0\");\n const year = d.getFullYear();\n const month = p2(d.getMonth() + 1);\n const day = p2(d.getDate());\n let datePart: string;\n if (format === \"iso\") datePart = `${year}-${month}-${day}`;\n else if (format === \"dmy\") datePart = `${day}/${month}/${year}`;\n else datePart = `${month}/${day}/${year}`; // mdy\n\n if (isMidnight) return `= ${datePart}`;\n const time = `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`;\n // ISO joins date and time with `T`; the slash forms with a space.\n return format === \"iso\" ? `= ${datePart}T${time}` : `= ${datePart} ${time}`;\n}\n\n/**\n * Renders a millisecond duration as clock-style `H:MM` (or `H:MM:SS` when\n * there's a non-zero seconds component). `ms` is never a user-typeable\n * unit (confirmed: it appears nowhere in `lexer/units.ts`), it's only\n * ever produced by subtracting two clock times/datetimes (`9:30 - 8:30`,\n * `VM.ts`'s Datetime SUB case), so this is a safe, narrow special case,\n * not a general change to how durations display.\n */\nfunction formatMsDuration(ms: number): string {\n const sign = ms < 0 ? \"-\" : \"\";\n const totalSeconds = Math.round(Math.abs(ms) / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const mm = String(minutes).padStart(2, \"0\");\n if (seconds === 0) return `${sign}${hours}:${mm}`;\n const ss = String(seconds).padStart(2, \"0\");\n return `${sign}${hours}:${mm}:${ss}`;\n}\n\nfunction formatUom(value: number, unit: string | undefined, locale: ILocale, settings: FormattingSettings, exact?: DecimalData): string {\n if (unit === \"ms\") return `= ${formatMsDuration(value)}`;\n\n const dp = settings.unitOfMeasurementResult.decimalPlaces;\n\n // For TimeSpan values (days, weeks, hours, etc.), format as integer if the value is a whole number\n const timeSpanUnits = [\"days\", \"weeks\", \"months\", \"years\", \"hours\", \"minutes\", \"seconds\", \"day\", \"week\", \"month\", \"year\", \"hour\", \"minute\", \"second\"];\n const isTimeSpan = unit && timeSpanUnits.includes(unit);\n\n let formatted: string;\n if (isTimeSpan && value === Math.floor(value)) {\n // For whole number TimeSpan values, format as integer\n formatted = value.toString();\n } else {\n // For other values, use the configured decimal places\n formatted = value.toFixed(dp);\n }\n\n // Currency display: symbol + culturally-conventional placement (e.g.\n // \"$100.00\" prefix vs \"100.00 kr\" suffix) instead of the generic\n // \"amount CODE\" fallback below. See uom/CurrencyAliases.ts's\n // CURRENCY_DISPLAY table for the exact set covered and the reasoning\n // behind each placement choice. Any currency code NOT in that table\n // (most of the ~150 `CurrencyExchange.isCurrency()` recognizes) falls\n // through to the unchanged \"amount CODE\" format below.\n const currencyDisplay = unit ? CURRENCY_DISPLAY[unit.toUpperCase()] : undefined;\n if (currencyDisplay) {\n // An exact money amount rounds from its decimal, not from the double: a\n // half-cent like \"$1.005\" reads as \"$1.01\" here, where \"(1.005).toFixed(2)\"\n // answers \"1.00\" because the double it is handed already sits below the\n // value the user typed. Amounts with no exact decimal (a currency\n // conversion, whose rate is a double) keep the toFixed rendering above.\n const moneyText = exact ? decimalToFixed(exact, dp) : formatted;\n const sep = currencyDisplay.spaced ? \" \" : \"\";\n const withSymbol = currencyDisplay.position === \"prefix\"\n ? `${currencyDisplay.symbol}${sep}${moneyText}`\n : `${moneyText}${sep}${currencyDisplay.symbol}`;\n return `= ${withSymbol}`;\n }\n\n // The unit is written as the symbol the value carries. There used to be a\n // `unitOfMeasurementResult.unitNames` setting here whose two branches were\n // the same expression, so it never changed anything, and it was removed\n // rather than implemented: the engine has no unit-name data to render from.\n // The generated unit table maps a spelling to [measure, ratio] only, and\n // names cannot be recovered from it, because units that differ by an OFFSET\n // share a ratio, so \"20 C\" would come back as \"20 kelvins\". A real\n // implementation needs a hand-authored name per unit plus pluralization and\n // per-locale spelling (metre against meter), which is a feature rather than\n // the repair of a dead ternary.\n //\n // An exact currency with no symbol in the display table above (one of the\n // less common ISO codes) still rounds from its decimal here, so \"1.005 UYW\"\n // reads the same way \"$1.005\" does. Non-currency Uoms never carry an exact,\n // so this leaves \"1.50 kg\" exactly as it was.\n const genericText = exact ? decimalToFixed(exact, dp) : formatted;\n return `= ${genericText} ${unit || \"\"}`.trim();\n}\n\nfunction formatMatrixEntry(entry: MatrixEntry, settings: FormattingSettings): string {\n if (typeof entry === \"boolean\") return entry ? \"true\" : \"false\";\n if (typeof entry === \"object\" && entry !== null) return formatSymbolic(entry);\n const dp = settings.floatResult.decimalPlaces;\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n return autoFormatIntegerOrFloat(entry, dp, sep, loc);\n}\n\n/**\n * Renders a Matrix matching its own literal syntax: a single row (1xN,\n * including plain vectors) as `[a, b, c]`, a single column (Nx1) as\n * `[a; b; c]`, and a general shape as `[r0c0, r0c1; r1c0, r1c1]`, row-major\n * textual output read back out of the column-major storage\n * (`columnMajorToRowMajor()`), matching how `[1,2;3,4]` is written.\n */\nfunction formatMatrix(m: MatrixData, locale: ILocale, settings: FormattingSettings): string {\n const rowMajor = columnMajorToRowMajor(m);\n const rows: string[] = [];\n for (let r = 0; r < m.rows; r++) {\n const cells: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n cells.push(formatMatrixEntry(rowMajor[r * m.cols + c], settings));\n }\n rows.push(cells.join(\", \"));\n }\n return `${locale.display.resultPrefix}[${rows.join(\"; \")}]`;\n}\n\n/**\n * Render a matrix as a multi-line, column-aligned block: one row per line (the\n * newline is where {@link formatValue}'s compact form writes `;`), each column\n * right-padded to its widest cell, and every row wrapped in `[ ... ]`. For\n * display where a grid reads better than a line, e.g. a docs notepad or a REPL:\n *\n * ```text\n * [ 1 2 ]\n * [ 30 4 ]\n * ```\n *\n * This is deliberately separate from {@link formatValue}, whose single-line\n * matrix form stays the stable, assertable text the API and the worker DTO use.\n * A 1xN row vector is one line; an Nx1 column vector is N lines.\n */\nexport function formatMatrixAligned(m: MatrixData, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const rowMajor = columnMajorToRowMajor(m);\n const cells: string[][] = [];\n for (let r = 0; r < m.rows; r++) {\n const row: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n row.push(formatMatrixEntry(rowMajor[r * m.cols + c], us));\n }\n cells.push(row);\n }\n const colWidth: number[] = [];\n for (let c = 0; c < m.cols; c++) {\n let width = 0;\n for (let r = 0; r < m.rows; r++) width = Math.max(width, cells[r][c].length);\n colWidth.push(width);\n }\n return cells\n .map((row) => `[ ${row.map((cell, c) => cell.padStart(colWidth[c])).join(\" \")} ]`)\n .join(\"\\n\");\n}\n\nfunction formatRange(min: number, max: number, locale: ILocale): string {\n return `${locale.display.resultPrefix}${min}:${max}`;\n}\n\nfunction formatPercentage(value: number, locale: ILocale, settings: FormattingSettings): string {\n // ValueType.Percentage stores a fraction (0.25 for 25%). See Value.ts's\n // documented contract and the sole producer, VM.ts's TO_PERCENTAGE opcode\n // (`right/left - 1`, e.g. 0.25 for \"800 to 1000\"). Multiply by 100 before\n // formatting; without this every percentage-change result displayed as\n // e.g. \"0.25%\" instead of \"25.00%\".\n const dp = settings.percentageResult.decimalPlaces;\n const formatted = (value * 100).toFixed(dp);\n return `= ${formatted}${locale.display.percentageSuffix}`;\n}\n\nfunction formatUnit(value: number, unit: string | undefined): string {\n return `= ${value} ${unit || \"\"}`.trim();\n}\n\n/**\n * Renders a per-person bill split: \"= $45.00 each\", or, when the division is\n * uneven, \"= $33.33 each, with 1 share paying $33.34\". Each share's amount is\n * rendered through the ordinary value formatter (a throwaway {@link Value}), so\n * a currency share honours the same symbol placement, decimal places and locale\n * as any other money and a bare share trims trailing zeros the way a plain\n * number does; the \"= \" prefix is added once, around the whole sentence, not\n * per share.\n */\nfunction formatSplit(data: SplitData, locale: ILocale, settings: FormattingSettings): string {\n const prefix = locale.display.resultPrefix;\n const render = (share: SplitShare): string => {\n const v = data.unit !== undefined\n ? new Value(ValueType.Uom, share.value, data.unit)\n : new Value(ValueType.Number, share.value);\n v.exact = share.exact;\n const text = formatValue(v, settings);\n return text.startsWith(prefix) ? text.slice(prefix.length) : text;\n };\n\n const [base, high] = data.shares;\n const each = `${render(base)} each`;\n if (high === undefined) return `${prefix}${each}`;\n const shareWord = high.count === 1 ? \"share\" : \"shares\";\n return `${prefix}${each}, with ${high.count} ${shareWord} paying ${render(high)}`;\n}\n\n/**\n * Render an evaluated {@link Value} as a display string, dispatching on\n * `value.type` to the type-specific formatter (number, hex, datetime, unit\n * of measurement, matrix, range, percentage, ...).\n *\n * Most branches produce a `\"= \"`-prefixed result string (matching the\n * plugin's inline-result convention); `ValueType.Error` is the one\n * exception, it returns the human-readable error message directly\n * (stored in `value.unit`), not an `\"= \"`-prefixed string.\n *\n * @param value - The evaluated value to format.\n * @param settings - Locale/precision/separator options; defaults to\n * {@link DEFAULT_FORMATTING_SETTINGS} when omitted.\n * @example\n * ```typescript\n * const value = engine.evaluateExpression(\"10 USD to GBP\");\n * formatValue(value); // \"= £7.85\" (exact output depends on live exchange rates)\n * ```\n */\nexport function formatValue(value: Value, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const localeCode = us.numberResult.decimalSeparatorLocale || \"en\";\n const locale = getLocale(localeCode);\n\n switch (value.type) {\n case ValueType.Number:\n // A measurement with a tolerance renders as \"center ± spread\"; every\n // other number is unchanged, so a plain value is byte-for-byte what it was.\n if (value.uncertainty !== undefined) {\n return formatUncertain(value.value as number, value.uncertainty, locale, us);\n }\n return formatNumber(value.value as number, locale, us, value.decimalPlaces);\n case ValueType.Hex:\n return formatHex(value.value as number | bigint, us, value.unit);\n case ValueType.BigInt:\n return formatBigInt(value.value as bigint);\n case ValueType.String:\n return formatString(value.value as string);\n case ValueType.Boolean:\n return formatBoolean(value.value as boolean);\n case ValueType.Datetime:\n return formatDatetime(value.value as number, locale, us);\n case ValueType.Uom:\n return formatUom(value.value as number, value.unit, locale, us, value.exact);\n case ValueType.Matrix:\n return formatMatrix(value.value as MatrixData, locale, us);\n case ValueType.Range: {\n const r = value.value as RangeData;\n return formatRange(r.min, r.max, locale);\n }\n case ValueType.Colour:\n return `${locale.display.resultPrefix}${formatColour(value.value as ColourData)}`;\n case ValueType.Split:\n return formatSplit(value.value as SplitData, locale, us);\n case ValueType.Chart:\n // A chart is drawn from its data by the host; the text answer is its label\n // (`sin(x) over [0, 6.28]`, or the series a sparkline came from).\n return `${locale.display.resultPrefix}${(value.value as ChartData).label}`;\n case ValueType.Symbolic:\n return formatSymbolic(value.value as SymbolicNode);\n case ValueType.Percentage:\n return formatPercentage(value.value as number, locale, us);\n case ValueType.Unit:\n return formatUnit(value.value as number, value.unit);\n case ValueType.Error:\n // errorValue(code, message) stores the human-readable message in\n // `.unit` (code goes in `.value`), falling through to the default\n // case here previously displayed the raw code (e.g.\n // \"CURRENCY_RATE_UNAVAILABLE\") instead of the actual message.\n return value.unit ?? String(value.value);\n default:\n return `= ${String(value.value)}`;\n }\n}\n"]}
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkSOMGSIO4_cjs=require('./chunk-SOMGSIO4.cjs');var m=0,l=0,p=Number.POSITIVE_INFINITY,d=0,h=Number.POSITIVE_INFINITY;function b(e,t,r){return chunkSOMGSIO4_cjs.c.execution({code:"ALLOCATION_LIMIT_EXCEEDED",message:`Evaluating this expression would materialise ${e.toLocaleString("en-US")} ${t}, past the limit of ${p.toLocaleString("en-US")} elements for one evaluation`,expected:`at most ${p.toLocaleString("en-US")} elements materialised while evaluating one expression`,found:`a request for ${e.toLocaleString("en-US")} more ${t}, on top of ${r.toLocaleString("en-US")} already materialised`,suggestion:"use a smaller collection or matrix, or raise the engine's vm.maxAllocatedElements setting",context:{requested:e,what:t,used:r,limit:p}})}function w(e){m++===0&&(l=0,p=e.getMaxAllocatedElements(),d=0,h=e.getMaxFunctionCalls());}function _(){m>0&&m--;}function T(e,t){if(m!==0){if(!(e>=0))throw b(e,t,l);if(l+=e,l>p)throw b(e,t,l-e)}}function N(e,t){if(m!==0&&(!(e>=0)||l+e>p))throw b(e,t,l)}function R(e,t){return N(e,t),new Array(e)}function P(){if(m!==0&&++d>h)throw chunkSOMGSIO4_cjs.c.execution({code:"FUNCTION_CALL_LIMIT_EXCEEDED",message:`Evaluating this expression would make more than ${h.toLocaleString("en-US")} user-defined-function calls, which is the limit for one evaluation`,expected:`at most ${h.toLocaleString("en-US")} function calls while evaluating one expression`,found:"a call past that limit, from a chain of functions that each call others more than once",suggestion:"check for a function that calls itself (or a chain of them) more times than intended, or raise the engine's vm.maxFunctionCalls setting",context:{calls:d,callLimit:h}})}var E=(n=>(n[n.Number=0]="Number",n[n.Hex=1]="Hex",n[n.BigInt=2]="BigInt",n[n.String=3]="String",n[n.Datetime=4]="Datetime",n[n.Percentage=5]="Percentage",n[n.Uom=6]="Uom",n[n.Matrix=7]="Matrix",n[n.Range=8]="Range",n[n.Symbolic=9]="Symbolic",n[n.Boolean=10]="Boolean",n[n.Unit=11]="Unit",n[n.Pending=12]="Pending",n[n.Error=13]="Error",n[n.Colour=14]="Colour",n[n.Split=15]="Split",n[n.Chart=16]="Chart",n))(E||{}),f=class f{constructor(t=512){this.arena=[];this.index=0;this.initialSize=t;for(let r=0;r<t;r++)this.arena.push(new a(0,0));}acquire(t,r,o){if(this.index<this.arena.length){let s=this.arena[this.index++];return s.recycle(t,r,o),s}let y=new a(t,r,o);return this.arena.push(y),this.index++,y}reset(){let t=this.index;this.index=0,!(this.arena.length<=this.initialSize)&&(this.arena.length<=t*f.SHRINK_WHEN_HOLDING_TIMES||(this.arena.length=Math.max(this.initialSize,t*f.KEEP_TIMES)));}get usage(){return this.index}get capacity(){return this.arena.length}};f.SHRINK_WHEN_HOLDING_TIMES=4,f.KEEP_TIMES=2;var g=f,i=null,u=false;function A(e){return i||(i=new g(e)),i.reset(),u=true,i}function O(){u=false;}function v(){return u}function $(e){let t=new a(e.type,e.value,e.unit);return e.exact!==void 0&&(t.exact=e.exact),e.rational!==void 0&&(t.rational=e.rational),e.uncertainty!==void 0&&(t.uncertainty=e.uncertainty),t}var I=process.env.NODE_ENV==="development";function q(e){return I&&!v()&&(e.toNumber(),Object.freeze(e)),e}var a=class{constructor(t,r,o){this.type=t,this.value=r,this.unit=o,typeof r=="number"&&(this._cachedNumber=r);}recycle(t,r,o){this.type=t,this.value=r,this.unit=o,this._cachedNumber=typeof r=="number"?r:void 0,this.timedOut=void 0,this.exact=void 0,this.rational=void 0,this.uncertainty=void 0,this.decimalPlaces=void 0;}isNumber(){return this.type===0}isHex(){return this.type===1}isBigInt(){return this.type===2}isString(){return this.type===3}isMatrix(){return this.type===7}isVectorShape(){if(this.type!==7)return false;let t=this.value;return t.rows===1||t.cols===1}isRange(){return this.type===8}isColour(){return this.type===14}isChart(){return this.type===16}isSymbolic(){return this.type===9}isError(){return this.type===13}isPending(){return this.type===12}isFault(){return this.type===13||this.type===12}get errorCode(){return this.type===13?this.value:void 0}get errorMessage(){return this.type===13?this.unit:void 0}toNumber(){if(this.type===12||this.type===13)return 0;if(this.type===7){let r=this.value;return r.rows===1&&r.cols===1&&typeof r.data[0]=="number"?r.data[0]:0}if(this.type===8||this.type===14||this.type===16)return 0;if(this.type===15)return this.value.shares[0].value;if(this.type===9)return 0;if(this.type===10)return this.value===true?1:0;if(this._cachedNumber!==void 0)return this._cachedNumber;if(typeof this.value=="bigint")return this._cachedNumber=Number(this.value),this._cachedNumber;let t=parseFloat(this.value);return this._cachedNumber=isNaN(t)?0:t,this._cachedNumber}isNaN(){if(this.type===12||this.type===13)return false;if(this.type===7){let t=this.value;return t.rows===1&&t.cols===1&&typeof t.data[0]=="number"?isNaN(t.data[0]):false}return this.type===8||this.type===14||this.type===15||this.type===16||this.type===9||this.type===10?false:typeof this.value=="number"?isNaN(this.value):typeof this.value=="bigint"?false:isNaN(parseFloat(this.value))}};function x(e){return u&&i?i.acquire(0,e):new a(0,e)}function B(e,t){let r=x(e);return r.exact=t,r}function H(e,t){let r=x(e);return r.rational=t,r}function k(e,t){let r=x(e);return r.uncertainty=t,r}function j(e,t="hex"){let r=t==="hex"?void 0:t;return u&&i?i.acquire(1,e,r):new a(1,e,r)}function K(e){return u&&i?i.acquire(2,e):new a(2,e)}function z(e){return u&&i?i.acquire(3,e):new a(3,e)}function D(e,t){return u&&i?i.acquire(6,e,t):new a(6,e,t)}function Y(e,t,r){let o=D(e,t);return o.exact=r,o}function W(e,t,r){return D(e,`${t}/${r}`)}function X(e){return typeof e=="string"&&e.includes("/")}function G(e){let t=e.indexOf("/");if(t<0)throw chunkSOMGSIO4_cjs.c.internal("INVALID_RATE_UNIT",`splitRateUnit: "${e}" is not a rate unit (expected "numerator/denominator")`,{unit:e});return {numerator:e.slice(0,t),denominator:e.slice(t+1)}}var V="timecode@";function J(e){return `${V}${e}`}function C(e){return typeof e=="string"&&e.startsWith(V)}function Q(e){if(!C(e))throw chunkSOMGSIO4_cjs.c.internal("INVALID_TIMECODE_UNIT",`timecodeFps: "${e}" is not a timecode unit (expected "timecode@<fps>")`,{unit:e});return parseFloat(e.slice(V.length))}function S(e,t,r){T(r.length,"matrix cells");let o=r.some(s=>typeof s=="object"&&s!==null&&"kind"in s),y={rows:e,cols:t,data:r,hasSymbolic:o};return u&&i?i.acquire(7,y):new a(7,y)}function Z(e){return S(1,e.length,e)}function ee(e){return S(e.length,1,e)}function te(e,t){let r={min:e,max:t};return u&&i?i.acquire(8,r):new a(8,r)}function re(e){return u&&i?i.acquire(14,e):new a(14,e)}function ne(e){return u&&i?i.acquire(15,e):new a(15,e)}function ie(e){return u&&i?i.acquire(16,e):new a(16,e)}function ae(e){return u&&i?i.acquire(9,e):new a(9,e)}function ue(e){return u&&i?i.acquire(10,e):new a(10,e)}function oe(e){return u&&i?i.acquire(4,e):new a(4,e)}function le(e){return u&&i?i.acquire(5,e):new a(5,e)}function se(e){return new a(12,e)}function ce(e,t){return new a(13,e,t)}function pe(e,t,r){return e.type===13||e.type===12?e:t!==void 0&&(t.type===13||t.type===12)?t:r!==void 0&&(r.type===13||r.type===12)?r:null}function me(e){for(let t=0;t<e.length;t++){let r=e[t];if(r.type===13||r.type===12)return r}return null}exports.A=C;exports.B=Q;exports.C=S;exports.D=Z;exports.E=ee;exports.F=te;exports.G=re;exports.H=ne;exports.I=ie;exports.J=ae;exports.K=ue;exports.L=oe;exports.M=le;exports.N=se;exports.O=ce;exports.P=pe;exports.Q=me;exports.a=w;exports.b=_;exports.c=T;exports.d=N;exports.e=R;exports.f=P;exports.g=E;exports.h=A;exports.i=O;exports.j=v;exports.k=$;exports.l=q;exports.m=a;exports.n=x;exports.o=B;exports.p=H;exports.q=k;exports.r=j;exports.s=K;exports.t=z;exports.u=D;exports.v=Y;exports.w=W;exports.x=X;exports.y=G;exports.z=J;//# sourceMappingURL=chunk-5FGOIDLS.cjs.map
2
- //# sourceMappingURL=chunk-5FGOIDLS.cjs.map