solve-engine 2.30.0 → 2.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DateCalendar-B85t6Vk6.d.ts → DateCalendar-CTz538dw.d.ts} +41 -1
- package/dist/{DateCalendar-CUGI1fT4.d.cts → DateCalendar-GFQDX1ng.d.cts} +41 -1
- package/dist/chunk-5EL4WXLF.cjs +3 -0
- package/dist/chunk-5EL4WXLF.cjs.map +1 -0
- package/dist/{chunk-CIC2YO2M.js → chunk-64OGL465.js} +2 -2
- package/dist/chunk-64OGL465.js.map +1 -0
- package/dist/chunk-D4UHCZAW.js +3 -0
- package/dist/chunk-D4UHCZAW.js.map +1 -0
- package/dist/chunk-JPT6L7BG.cjs +5 -0
- package/dist/chunk-JPT6L7BG.cjs.map +1 -0
- package/dist/{chunk-RHRAONDK.cjs → chunk-UHS4HMOQ.cjs} +2 -2
- package/dist/chunk-UHS4HMOQ.cjs.map +1 -0
- package/dist/chunk-VYB44JLS.js +5 -0
- package/dist/chunk-VYB44JLS.js.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +1 -1
- package/dist/engine.d.ts +1 -1
- package/dist/engine.js +1 -1
- package/dist/engine.worker.cjs +2 -0
- package/dist/engine.worker.cjs.map +1 -0
- package/dist/engine.worker.d.cts +2 -0
- package/dist/engine.worker.d.ts +2 -0
- package/dist/engine.worker.js +2 -0
- package/dist/engine.worker.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.js +2 -2
- package/dist/worker.js.map +1 -1
- package/package.json +11 -1
- package/dist/chunk-CIC2YO2M.js.map +0 -1
- package/dist/chunk-FNSQ6O4Y.js +0 -3
- package/dist/chunk-FNSQ6O4Y.js.map +0 -1
- package/dist/chunk-NNRTDLGC.cjs +0 -3
- package/dist/chunk-NNRTDLGC.cjs.map +0 -1
- package/dist/chunk-NOZKHMML.js +0 -5
- package/dist/chunk-NOZKHMML.js.map +0 -1
- package/dist/chunk-PNHTC3FM.cjs +0 -5
- package/dist/chunk-PNHTC3FM.cjs.map +0 -1
- package/dist/chunk-RHRAONDK.cjs.map +0 -1
package/dist/constants.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkUHS4HMOQ_cjs=require('./chunk-UHS4HMOQ.cjs');require('./chunk-SUAGBRQ7.cjs');Object.defineProperty(exports,"ConfigManager",{enumerable:true,get:function(){return chunkUHS4HMOQ_cjs.d}});Object.defineProperty(exports,"DEFAULT_CONFIG",{enumerable:true,get:function(){return chunkUHS4HMOQ_cjs.b}});Object.defineProperty(exports,"ENGINE_VERSION",{enumerable:true,get:function(){return chunkUHS4HMOQ_cjs.a}});//# sourceMappingURL=constants.cjs.map
|
|
2
2
|
//# sourceMappingURL=constants.cjs.map
|
package/dist/constants.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{d as ConfigManager,b as DEFAULT_CONFIG,a as ENGINE_VERSION}from'./chunk-
|
|
1
|
+
export{d as ConfigManager,b as DEFAULT_CONFIG,a as ENGINE_VERSION}from'./chunk-64OGL465.js';import'./chunk-RELMEWY6.js';//# sourceMappingURL=constants.js.map
|
|
2
2
|
//# sourceMappingURL=constants.js.map
|
package/dist/engine.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk5EL4WXLF_cjs=require('./chunk-5EL4WXLF.cjs');require('./chunk-EFJCC6FJ.cjs');var chunkJPT6L7BG_cjs=require('./chunk-JPT6L7BG.cjs');require('./chunk-Q7TBBV62.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-ZVPZQ66D.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-GWV273KZ.cjs'),require('./chunk-HG4NPDN5.cjs'),require('./chunk-P43SV4NJ.cjs'),require('./chunk-R2SZFJTT.cjs'),require('./chunk-WQGHJAW2.cjs'),require('./chunk-5AKT36UK.cjs'),require('./chunk-4DR5RBHQ.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-RAFOQ4T5.cjs'),require('./chunk-CM2WM5CM.cjs'),require('./chunk-DUFEONVN.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-YWF6C2IO.cjs');var chunkA764BY7L_cjs=require('./chunk-A764BY7L.cjs');require('./chunk-E4HAKNBQ.cjs'),require('./chunk-OM7NOHJF.cjs'),require('./chunk-ZKFCKAIX.cjs'),require('./chunk-UHS4HMOQ.cjs'),require('./chunk-AGCNMEP2.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-WU7SBKVU.cjs'),require('./chunk-YBQOQTVL.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs'),require('./chunk-SUAGBRQ7.cjs');Object.defineProperty(exports,"DocumentModel",{enumerable:true,get:function(){return chunk5EL4WXLF_cjs.a}});Object.defineProperty(exports,"EvalTier",{enumerable:true,get:function(){return chunk5EL4WXLF_cjs.b}});Object.defineProperty(exports,"ThreeTierEvaluator",{enumerable:true,get:function(){return chunk5EL4WXLF_cjs.c}});Object.defineProperty(exports,"evaluateDocument",{enumerable:true,get:function(){return chunk5EL4WXLF_cjs.d}});Object.defineProperty(exports,"AsyncResolutionBatcher",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.i}});Object.defineProperty(exports,"ExpressionEngine",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.o}});Object.defineProperty(exports,"SNAPSHOT_FORMAT",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.d}});Object.defineProperty(exports,"SNAPSHOT_VERSION",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.e}});Object.defineProperty(exports,"SnapshotErrorCodes",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.f}});Object.defineProperty(exports,"checkExpressionComplexity",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.k}});Object.defineProperty(exports,"checkExpressionLength",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.j}});Object.defineProperty(exports,"extractReadsAndWrites",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.l}});Object.defineProperty(exports,"findInlineSolvesInLine",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.n}});Object.defineProperty(exports,"isEmptyLine",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.m}});Object.defineProperty(exports,"setEngineWorkerFactory",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.g}});Object.defineProperty(exports,"DATE_CALENDAR",{enumerable:true,get:function(){return chunkA764BY7L_cjs.b}});Object.defineProperty(exports,"DateCalendar",{enumerable:true,get:function(){return chunkA764BY7L_cjs.a}});Object.defineProperty(exports,"calendarOf",{enumerable:true,get:function(){return chunkA764BY7L_cjs.c}});Object.defineProperty(exports,"dateCalendarInZone",{enumerable:true,get:function(){return chunkA764BY7L_cjs.d}});//# sourceMappingURL=engine.cjs.map
|
|
2
2
|
//# sourceMappingURL=engine.cjs.map
|
package/dist/engine.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as DocumentModel, E as ExpressionEngine, V as ViewportRange, u as LineChange, U as UnifiedParsingOptions, P as ParsingResult, v as InlineSolvePosition } from './PackageRegistry-B-C1duZw.cjs';
|
|
2
2
|
export { A as ApplyChangesResult, w as AsyncCachePackageInfo, x as AsyncErrorEvent, y as AsyncResolutionBatcher, z as AsyncResolutionEvent, B as BatcherMetrics, F as BytecodeCacheEntry, G as CacheSnapshot, H as CheckpointSnapshot, D as DateOrderSource, b as DateReading, c as DateReadingPolicy, a as EngineOptions, d as EngineRestoreOptions, e as EngineSnapshot, f as Explanation, g as ExplanationStep, J as LineCacheEntryInfo, K as LineState, M as LinesUpdatedEvent, N as ParsedLine, R as ResolvedDateOrder, S as SNAPSHOT_FORMAT, h as SNAPSHOT_VERSION, i as SerializedAnonymousBody, j as SerializedBytecode, k as SerializedDecimal, l as SerializedLineCacheEntry, m as SerializedNumber, n as SerializedRational, o as SerializedUserFunction, p as SerializedValue, q as SnapshotErrorCodes } from './PackageRegistry-B-C1duZw.cjs';
|
|
3
3
|
export { C as CalendarBackend, a as CalendarFields, Z as ZonedFields } from './CalendarBackend-MdS3Bb4P.cjs';
|
|
4
|
-
export { D as DATE_CALENDAR, a as DateCalendar, c as calendarOf, d as dateCalendarInZone } from './DateCalendar-
|
|
4
|
+
export { D as DATE_CALENDAR, a as DateCalendar, E as EngineWorkerFactory, c as calendarOf, d as dateCalendarInZone, s as setEngineWorkerFactory } from './DateCalendar-GFQDX1ng.cjs';
|
|
5
5
|
import { V as Value } from './Value-BYHw-x7q.cjs';
|
|
6
6
|
import { a as VMCheckpointer } from './VMCheckpoints-WdUQrdc9.cjs';
|
|
7
7
|
import { T as Token } from './Token-D8f7yaz1.cjs';
|
package/dist/engine.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as DocumentModel, E as ExpressionEngine, V as ViewportRange, u as LineChange, U as UnifiedParsingOptions, P as ParsingResult, v as InlineSolvePosition } from './PackageRegistry-C78jVkI9.js';
|
|
2
2
|
export { A as ApplyChangesResult, w as AsyncCachePackageInfo, x as AsyncErrorEvent, y as AsyncResolutionBatcher, z as AsyncResolutionEvent, B as BatcherMetrics, F as BytecodeCacheEntry, G as CacheSnapshot, H as CheckpointSnapshot, D as DateOrderSource, b as DateReading, c as DateReadingPolicy, a as EngineOptions, d as EngineRestoreOptions, e as EngineSnapshot, f as Explanation, g as ExplanationStep, J as LineCacheEntryInfo, K as LineState, M as LinesUpdatedEvent, N as ParsedLine, R as ResolvedDateOrder, S as SNAPSHOT_FORMAT, h as SNAPSHOT_VERSION, i as SerializedAnonymousBody, j as SerializedBytecode, k as SerializedDecimal, l as SerializedLineCacheEntry, m as SerializedNumber, n as SerializedRational, o as SerializedUserFunction, p as SerializedValue, q as SnapshotErrorCodes } from './PackageRegistry-C78jVkI9.js';
|
|
3
3
|
export { C as CalendarBackend, a as CalendarFields, Z as ZonedFields } from './CalendarBackend-MdS3Bb4P.js';
|
|
4
|
-
export { D as DATE_CALENDAR, a as DateCalendar, c as calendarOf, d as dateCalendarInZone } from './DateCalendar-
|
|
4
|
+
export { D as DATE_CALENDAR, a as DateCalendar, E as EngineWorkerFactory, c as calendarOf, d as dateCalendarInZone, s as setEngineWorkerFactory } from './DateCalendar-CTz538dw.js';
|
|
5
5
|
import { V as Value } from './Value-BYHw-x7q.js';
|
|
6
6
|
import { a as VMCheckpointer } from './VMCheckpoints-gvy_yxYh.js';
|
|
7
7
|
import { T as Token } from './Token-D8f7yaz1.js';
|
package/dist/engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as DocumentModel,b as EvalTier,c as ThreeTierEvaluator,d as evaluateDocument}from'./chunk-
|
|
1
|
+
export{a as DocumentModel,b as EvalTier,c as ThreeTierEvaluator,d as evaluateDocument}from'./chunk-D4UHCZAW.js';import'./chunk-RAF57WYO.js';export{i as AsyncResolutionBatcher,o as ExpressionEngine,d as SNAPSHOT_FORMAT,e as SNAPSHOT_VERSION,f as SnapshotErrorCodes,k as checkExpressionComplexity,j as checkExpressionLength,l as extractReadsAndWrites,n as findInlineSolvesInLine,m as isEmptyLine,g as setEngineWorkerFactory}from'./chunk-VYB44JLS.js';import'./chunk-CB3EXUM2.js';import'./chunk-2RWAXT6O.js';import'./chunk-IJHL3LMH.js';import'./chunk-MIQBJGGR.js';import'./chunk-2PGGPFF3.js';import'./chunk-JP4JMQOG.js';import'./chunk-IQVSCL2R.js';import'./chunk-XEIDV5JP.js';import'./chunk-FXB5GCBT.js';import'./chunk-VLX7ZVK4.js';import'./chunk-B2NL65FI.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-YN5H54GM.js';import'./chunk-3ZGFAE3Q.js';import'./chunk-PTXUWGRR.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-KH4QXKLT.js';export{b as DATE_CALENDAR,a as DateCalendar,c as calendarOf,d as dateCalendarInZone}from'./chunk-NQFCXLEF.js';import'./chunk-J4K72CQN.js';import'./chunk-X5K72MBV.js';import'./chunk-4CNYGIND.js';import'./chunk-64OGL465.js';import'./chunk-CDE2ZUGG.js';import'./chunk-JPFCXLJV.js';import'./chunk-LP3JYC3A.js';import'./chunk-FAO6DQ74.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import'./chunk-RELMEWY6.js';//# sourceMappingURL=engine.js.map
|
|
2
2
|
//# sourceMappingURL=engine.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkJPT6L7BG_cjs=require('./chunk-JPT6L7BG.cjs');require('./chunk-Q7TBBV62.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-ZVPZQ66D.cjs'),require('./chunk-TTFO4YDP.cjs');var chunkGWV273KZ_cjs=require('./chunk-GWV273KZ.cjs');require('./chunk-HG4NPDN5.cjs'),require('./chunk-P43SV4NJ.cjs'),require('./chunk-R2SZFJTT.cjs');var chunkW7NN77PH_cjs=require('./chunk-W7NN77PH.cjs');require('./chunk-A755LVPT.cjs'),require('./chunk-WQGHJAW2.cjs'),require('./chunk-5AKT36UK.cjs'),require('./chunk-4DR5RBHQ.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs');var chunkRAFOQ4T5_cjs=require('./chunk-RAFOQ4T5.cjs');require('./chunk-CM2WM5CM.cjs'),require('./chunk-DUFEONVN.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-YWF6C2IO.cjs'),require('./chunk-A764BY7L.cjs'),require('./chunk-E4HAKNBQ.cjs'),require('./chunk-OM7NOHJF.cjs'),require('./chunk-ZKFCKAIX.cjs'),require('./chunk-UHS4HMOQ.cjs'),require('./chunk-AGCNMEP2.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-WU7SBKVU.cjs'),require('./chunk-YBQOQTVL.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs'),require('./chunk-SUAGBRQ7.cjs');var i=null;function E(){return i||(i=new chunkJPT6L7BG_cjs.o({packages:chunkW7NN77PH_cjs.z})),i}var f=null;function h(){return f||(f=chunkGWV273KZ_cjs.c(chunkRAFOQ4T5_cjs.w,200,5e4)),f}function B(e){let r={lineId:e.lineId,expression:e.expression,compiledAgainstHash:e.textHash,strings:[],reads:[],writes:[],isVariableDef:false,error:null};try{let n=E(),{program:u,reads:s,writes:t}=n.compileExpression(e.expression),o=t.length>0,a=u.opcodes,l=u.numbers,y=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);return {...r,opcodesBuffer:y,numbersBuffer:d,opcodesLength:a.length,numbersLength:l.length,strings:[...u.strings],reads:s,writes:t,isVariableDef:o}}catch(n){return {...r,opcodesBuffer:new ArrayBuffer(0),numbersBuffer:new ArrayBuffer(0),opcodesLength:0,numbersLength:0,error:n instanceof Error?n.message:String(n)}}}function L(e){let r=[],n=[];for(let u of e.items){let s=B(u);r.push(s),s.opcodesBuffer.byteLength>0&&n.push(s.opcodesBuffer),s.numbersBuffer.byteLength>0&&n.push(s.numbersBuffer);}self.postMessage({id:e.id,type:"COMPILE_RESULT",results:r},n);}function M(e){let r=h();r.reset();let n=new Uint8Array(e.opcodesBuffer,0,e.opcodesLength),u=new Float64Array(e.numbersBuffer,0,e.numbersLength),s={opcodes:n,numbers:u,strings:e.strings};try{let t=chunkGWV273KZ_cjs.d(s,r);if(t.type==="pending")return {lineNumber:e.lineNumber,valueType:12,value:0,isPending:!0,queryKey:t.queryKey};if(t.type==="error")return {lineNumber:e.lineNumber,valueType:13,value:0,isPending:!1,unit:t.error.message};let o=t.value;return {lineNumber:e.lineNumber,valueType:o.type,value:typeof o.value=="number"?o.value:typeof o.value=="bigint"?Number(o.value):0,unit:o.unit,isPending:!1}}catch{return {lineNumber:e.lineNumber,valueType:13,value:0,isPending:false,unit:"Worker execution failed"}}}function T(e){let r=[];for(let n of e.items)r.push(M(n));self.postMessage({id:e.id,type:"EXECUTE_RESULT",results:r});}var x=typeof self<"u"&&typeof window>"u",C=e=>{if(e.origin&&self.location&&e.origin!==self.location.origin)return;let r=e.data;switch(r.type){case "COMPILE_BATCH":L(r);break;case "EXECUTE_BATCH":T(r);break;case "TERMINATE":{i&&(i.clear(),i=null),f&&(f.reset(),f=null),self.postMessage({id:r.id,type:"COMPILE_RESULT",results:[]});break}default:self.postMessage({id:-1,type:"COMPILE_RESULT",results:[],error:`Unknown message type: ${r.type}`});}};x&&(self.onmessage=C);//# sourceMappingURL=engine.worker.cjs.map
|
|
2
|
+
//# sourceMappingURL=engine.worker.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/workers/engine.worker.ts"],"names":["compileEngine","getCompileEngine","ExpressionEngine","BUILTIN_PACKAGES","executeVm","getExecuteVm","createVM","sharedOpRegistry","compileOne","item","base","eng","program","reads","writes","isVariableDef","opcodes","numbers","opcodesBuffer","numbersBuffer","e","handleCompileBatch","msg","results","transferList","result","executeOne","vmm","bytecode","executeBytecode","val","handleExecuteBatch","inWorkerScope","handleMessage","event"],"mappings":"quCA0GA,IAAIA,CAAAA,CAAyC,IAAA,CAC7C,SAASC,CAAAA,EA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AA2B,WAAA,CAAY,CACvC,EAAA,CAAIkB,CAAAA,CAAI,EAAA,CACR,IAAA,CAAM,gBAAA,CACN,QAAS,EACV,CAAC,CAAA,CACD,KACD,CAEA,QACE,IAAA,CAA2B,WAAA,CAAY,CACvC,EAAA,CAAI,EAAA,CACJ,IAAA,CAAM,gBAAA,CACN,OAAA,CAAS,EAAC,CACV,KAAA,CAAO,CAAA,sBAAA,EAA0BA,CAAAA,CAA0B,IAAI,CAAA,CAChE,CAAC,EAEH,CACD,CAAA,CAKIU,CAAAA,GACH,IAAA,CAAK,SAAA,CAAYC,CAAAA,CAAAA","file":"engine.worker.cjs","sourcesContent":["/**\n * Engine worker, offloads both compilation and VM execution to a\n * background thread (plan L6: worker consolidation).\n *\n * Previously two separate worker files (compilation.worker.ts,\n * execution.worker.ts) duplicated the Transferable ArrayBuffer protocol,\n * postMessage/onmessage boilerplate, and lazy-init pattern. This file\n * merges them behind a single `self.onmessage` dispatching on `msg.type`\n * the message shapes are UNCHANGED from the two original files, so\n * CompilationWorkerManager and ExecutionPool (the main-thread consumers)\n * reach a worker started from this file through the factory a host registers\n * with `setEngineWorkerFactory`, and never import this module themselves.\n *\n * Each Worker instance created from this file is used exclusively by ONE\n * consumer (a CompilationWorkerManager sends only COMPILE_BATCH; an\n * ExecutionPool sends only EXECUTE_BATCH), the module-level `engine` and\n * `vm` singletons below are independent lazy state, so there is no\n * cross-contamination between the two roles even though they share code.\n *\n * Message protocol:\n * Main → Worker:\n * { type: \"COMPILE_BATCH\", id, items: CompileItem[] }\n * { type: \"EXECUTE_BATCH\", id, items: ExecuteItem[] }\n * { type: \"TERMINATE\", id }\n *\n * Worker → Main:\n * { id, type: \"COMPILE_RESULT\", results: CompileResult[] }\n * { id, type: \"EXECUTE_RESULT\", results: ExecuteResult[] }\n *\n * Transferable objects: bytecode opcodes/numbers buffers are transferred\n * (zero-copy) in both directions, same pattern as the original files.\n */\n\nimport { ExpressionEngine } from \"../engine/ExpressionEngine\";\nimport { BUILTIN_PACKAGES } from \"../packages/builtins\";\nimport type { Bytecode } from \"../vm/VM\";\nimport { createVM, executeBytecode } from \"../vm/VM\";\nimport { sharedOpRegistry } from \"../vm/OpRegistry\";\nimport { ValueType } from \"../vm/Value\";\n\n// ── Compile message types ──────────────────────────────────────────────\n\ninterface CompileItem {\n\tlineId: number;\n\texpression: string;\n\ttextHash: number;\n}\n\ninterface CompileBatchMsg {\n\ttype: \"COMPILE_BATCH\";\n\tid: number;\n\titems: CompileItem[];\n}\n\ninterface CompileResult {\n\tlineId: number;\n\texpression: string;\n\tcompiledAgainstHash: number;\n\topcodesBuffer: ArrayBuffer;\n\tnumbersBuffer: ArrayBuffer;\n\topcodesLength: number;\n\tnumbersLength: number;\n\tstrings: string[];\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// ── Execute message types ──────────────────────────────────────────────\n\ninterface ExecuteItem {\n\tlineNumber: number;\n\topcodesBuffer: ArrayBuffer;\n\tnumbersBuffer: ArrayBuffer;\n\topcodesLength: number;\n\tnumbersLength: number;\n\tstrings: string[];\n}\n\ninterface ExecuteBatchMsg {\n\ttype: \"EXECUTE_BATCH\";\n\tid: number;\n\titems: ExecuteItem[];\n}\n\ninterface ExecuteResult {\n\tlineNumber: number;\n\tvalueType: ValueType;\n\tvalue: number;\n\tunit?: string;\n\tisPending: boolean;\n\tqueryKey?: string;\n}\n\ninterface TerminateMsg {\n\ttype: \"TERMINATE\";\n\tid: number;\n}\n\ntype EngineWorkerMessage = CompileBatchMsg | ExecuteBatchMsg | TerminateMsg;\n\n// ── Worker body ───────────────────────────────────────────────────────\n\n// ── Lazy per-role state, independent, only the used one is created ────\n\nlet compileEngine: ExpressionEngine | null = null;\nfunction getCompileEngine(): ExpressionEngine {\n\tif (!compileEngine) {\n\t\t// The full vocabulary, which is the point of this file being its own\n\t\t// bundle: a compile engine with no packages would refuse every line a\n\t\t// package gives meaning to, and the manager would fall back to the main\n\t\t// thread for nearly all of them. Nothing but a host that registers a\n\t\t// factory (see `WorkerFactory.ts`) reaches this module, so a consumer's\n\t\t// main bundle carries neither the packages nor this file.\n\t\tcompileEngine = new ExpressionEngine({ packages: BUILTIN_PACKAGES });\n\t}\n\treturn compileEngine;\n}\n\nlet executeVm: ReturnType<typeof createVM> | null = null;\nfunction getExecuteVm(): ReturnType<typeof createVM> {\n\tif (!executeVm) {\n\t\texecuteVm = createVM(sharedOpRegistry, 200, 50000);\n\t}\n\treturn executeVm;\n}\n\n// ── Compile ──────────────────────────────────────────────────────────\n\n/**\n * Compile a single expression and produce a transfer-ready CompileResult.\n * Extracts ArrayBuffers from the compiled TypedArrays so they can be\n * transferred via postMessage, after this call, the original TypedArrays\n * are detached on the worker side.\n */\nfunction compileOne(item: CompileItem): CompileResult {\n\tconst base: Omit<CompileResult, \"opcodesBuffer\" | \"numbersBuffer\" | \"opcodesLength\" | \"numbersLength\"> = {\n\t\tlineId: item.lineId,\n\t\texpression: item.expression,\n\t\tcompiledAgainstHash: item.textHash,\n\t\tstrings: [],\n\t\treads: [],\n\t\twrites: [],\n\t\tisVariableDef: false,\n\t\terror: null,\n\t};\n\n\ttry {\n\t\tconst eng = getCompileEngine();\n\t\tconst { program, reads, writes } = eng.compileExpression(item.expression);\n\t\tconst isVariableDef = writes.length > 0;\n\n\t\tconst opcodes = program.opcodes;\n\t\tconst numbers = program.numbers;\n\n\t\t// Transfer only the exact used slice of the ArrayBuffer. The engine's\n\t\t// buffer pool is write-only, so detaching the source view is fine.\n\t\t//\n\t\t// The casts narrow ArrayBufferLike to ArrayBuffer. A TypedArray's\n\t\t// `buffer` is typed as the union including SharedArrayBuffer, which\n\t\t// TypeScript 6 enforces where 5.1 did not, and the postMessage\n\t\t// transfer list below accepts only ArrayBuffer. The narrowing is\n\t\t// sound here because these buffers come from the engine's own pool,\n\t\t// which allocates plain ArrayBuffers; a SharedArrayBuffer could not\n\t\t// reach this point, and would not be transferable if it did.\n\t\tconst opcodesBuffer = (opcodes.buffer as ArrayBuffer).slice(\n\t\t\topcodes.byteOffset,\n\t\t\topcodes.byteOffset + opcodes.byteLength\n\t\t);\n\t\tconst numbersBuffer = (numbers.buffer as ArrayBuffer).slice(\n\t\t\tnumbers.byteOffset,\n\t\t\tnumbers.byteOffset + numbers.byteLength\n\t\t);\n\n\t\treturn {\n\t\t\t...base,\n\t\t\topcodesBuffer,\n\t\t\tnumbersBuffer,\n\t\t\topcodesLength: opcodes.length,\n\t\t\tnumbersLength: numbers.length,\n\t\t\tstrings: [...program.strings],\n\t\t\treads,\n\t\t\twrites,\n\t\t\tisVariableDef,\n\t\t};\n\t} catch (e) {\n\t\treturn {\n\t\t\t...base,\n\t\t\topcodesBuffer: new ArrayBuffer(0),\n\t\t\tnumbersBuffer: new ArrayBuffer(0),\n\t\t\topcodesLength: 0,\n\t\t\tnumbersLength: 0,\n\t\t\terror: e instanceof Error ? e.message : String(e),\n\t\t};\n\t}\n}\n\nfunction handleCompileBatch(msg: CompileBatchMsg): void {\n\tconst results: CompileResult[] = [];\n\tconst transferList: ArrayBuffer[] = [];\n\n\tfor (const item of msg.items) {\n\t\tconst result = compileOne(item);\n\t\tresults.push(result);\n\t\tif (result.opcodesBuffer.byteLength > 0) transferList.push(result.opcodesBuffer);\n\t\tif (result.numbersBuffer.byteLength > 0) transferList.push(result.numbersBuffer);\n\t}\n\n\t(self as unknown as Worker).postMessage(\n\t\t{ id: msg.id, type: \"COMPILE_RESULT\", results },\n\t\ttransferList\n\t);\n}\n\n// ── Execute ──────────────────────────────────────────────────────────\n\n/**\n * Execute a single bytecode program and produce a serialized ExecuteResult.\n * Reconstructs TypedArrays from the transferred ArrayBuffers (zero-copy).\n * Resets the worker VM before each execution, no state carries over\n * between lines in a batch.\n */\nfunction executeOne(item: ExecuteItem): ExecuteResult {\n\tconst vmm = getExecuteVm();\n\tvmm.reset();\n\n\tconst opcodes = new Uint8Array(item.opcodesBuffer, 0, item.opcodesLength);\n\tconst numbers = new Float64Array(item.numbersBuffer, 0, item.numbersLength);\n\tconst bytecode: Bytecode = { opcodes, numbers, strings: item.strings };\n\n\ttry {\n\t\tconst result = executeBytecode(bytecode, vmm);\n\n\t\tif (result.type === \"pending\") {\n\t\t\treturn {\n\t\t\t\tlineNumber: item.lineNumber,\n\t\t\t\tvalueType: ValueType.Pending,\n\t\t\t\tvalue: 0,\n\t\t\t\tisPending: true,\n\t\t\t\tqueryKey: result.queryKey,\n\t\t\t};\n\t\t}\n\n\t\tif (result.type === \"error\") {\n\t\t\treturn {\n\t\t\t\tlineNumber: item.lineNumber,\n\t\t\t\tvalueType: ValueType.Error,\n\t\t\t\tvalue: 0,\n\t\t\t\tisPending: false,\n\t\t\t\tunit: result.error.message,\n\t\t\t};\n\t\t}\n\n\t\tconst val = result.value;\n\t\treturn {\n\t\t\tlineNumber: item.lineNumber,\n\t\t\tvalueType: val.type,\n\t\t\tvalue: typeof val.value === \"number\"\n\t\t\t\t? val.value\n\t\t\t\t: typeof val.value === \"bigint\"\n\t\t\t\t\t? Number(val.value)\n\t\t\t\t\t: 0,\n\t\t\tunit: val.unit,\n\t\t\tisPending: false,\n\t\t};\n\t} catch {\n\t\t// Execution error, return error-type value so main thread can\n\t\t// propagate through DAG as errorValue.\n\t\treturn {\n\t\t\tlineNumber: item.lineNumber,\n\t\t\tvalueType: ValueType.Error,\n\t\t\tvalue: 0,\n\t\t\tisPending: false,\n\t\t\tunit: \"Worker execution failed\",\n\t\t};\n\t}\n}\n\nfunction handleExecuteBatch(msg: ExecuteBatchMsg): void {\n\tconst results: ExecuteResult[] = [];\n\tfor (const item of msg.items) {\n\t\tresults.push(executeOne(item));\n\t}\n\t// No transferables needed for the response, results are plain\n\t// objects with numbers and strings (structured-cloned).\n\t(self as unknown as Worker).postMessage({\n\t\tid: msg.id,\n\t\ttype: \"EXECUTE_RESULT\",\n\t\tresults,\n\t});\n}\n\n// ── Message handler ───────────────────────────────────────────────────\n\n/**\n * Whether this module is executing inside a real worker global scope.\n *\n * This file is a bundle entry of its own (`solve-engine/engine-worker`), so a\n * host that starts a worker from it runs the handler below in a worker. It is\n * still an ordinary module to anything that merely imports it, a test harness\n * or a Node script included, and there the handler must not bind.\n *\n * Without this guard, importing it from Node throws `self is not defined`\n * before a single expression can be evaluated. The check distinguishes the\n * three environments: Node defines neither `self` nor `window`, a browser main\n * thread defines both, and a worker defines only `self`.\n */\nconst inWorkerScope = typeof self !== \"undefined\" && typeof window === \"undefined\";\n\nconst handleMessage = (event: MessageEvent) => {\n\t// A real postMessage always carries a browser-populated origin the\n\t// sender cannot spoof, so this only ever rejects a genuine mismatch. It\n\t// is skipped, not enforced, when either side is unset, which covers the\n\t// test harness driving this handler directly with a plain object and\n\t// no location global (see WorkerIntegration.spec.ts), without opening\n\t// anything a real message could exploit.\n\tif (event.origin && self.location && event.origin !== self.location.origin) return;\n\n\tconst msg = event.data as EngineWorkerMessage;\n\n\tswitch (msg.type) {\n\t\tcase \"COMPILE_BATCH\":\n\t\t\thandleCompileBatch(msg);\n\t\t\tbreak;\n\n\t\tcase \"EXECUTE_BATCH\":\n\t\t\thandleExecuteBatch(msg);\n\t\t\tbreak;\n\n\t\tcase \"TERMINATE\": {\n\t\t\t// Not sent by either production manager today, both call the\n\t\t\t// native Worker.terminate() directly instead. Kept for protocol\n\t\t\t// completeness and future consumers. Clears whichever per-role\n\t\t\t// state this instance happened to create.\n\t\t\tif (compileEngine) {\n\t\t\t\tcompileEngine.clear();\n\t\t\t\tcompileEngine = null;\n\t\t\t}\n\t\t\tif (executeVm) {\n\t\t\t\texecuteVm.reset();\n\t\t\t\texecuteVm = null;\n\t\t\t}\n\t\t\t(self as unknown as Worker).postMessage({\n\t\t\t\tid: msg.id,\n\t\t\t\ttype: \"COMPILE_RESULT\",\n\t\t\t\tresults: [],\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault: {\n\t\t\t(self as unknown as Worker).postMessage({\n\t\t\t\tid: -1,\n\t\t\t\ttype: \"COMPILE_RESULT\",\n\t\t\t\tresults: [],\n\t\t\t\terror: `Unknown message type: ${(msg as { type?: string }).type}`,\n\t\t\t});\n\t\t}\n\t}\n};\n\n// Installed only when genuinely running as a worker. Everywhere else this\n// module has been inlined into a host bundle, where binding a handler would at\n// best be inert and at worst intercept the host's own messages.\nif (inWorkerScope) {\n\tself.onmessage = handleMessage;\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {o}from'./chunk-VYB44JLS.js';import'./chunk-CB3EXUM2.js';import'./chunk-2RWAXT6O.js';import'./chunk-IJHL3LMH.js';import'./chunk-MIQBJGGR.js';import {d,c}from'./chunk-2PGGPFF3.js';import'./chunk-JP4JMQOG.js';import'./chunk-IQVSCL2R.js';import'./chunk-XEIDV5JP.js';import {z}from'./chunk-V7LXOTCU.js';import'./chunk-SFM4XFGJ.js';import'./chunk-FXB5GCBT.js';import'./chunk-VLX7ZVK4.js';import'./chunk-B2NL65FI.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import {w}from'./chunk-YN5H54GM.js';import'./chunk-3ZGFAE3Q.js';import'./chunk-PTXUWGRR.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-KH4QXKLT.js';import'./chunk-NQFCXLEF.js';import'./chunk-J4K72CQN.js';import'./chunk-X5K72MBV.js';import'./chunk-4CNYGIND.js';import'./chunk-64OGL465.js';import'./chunk-CDE2ZUGG.js';import'./chunk-JPFCXLJV.js';import'./chunk-LP3JYC3A.js';import'./chunk-FAO6DQ74.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import'./chunk-RELMEWY6.js';var i=null;function E(){return i||(i=new o({packages:z})),i}var f=null;function h(){return f||(f=c(w,200,5e4)),f}function B(e){let r={lineId:e.lineId,expression:e.expression,compiledAgainstHash:e.textHash,strings:[],reads:[],writes:[],isVariableDef:false,error:null};try{let n=E(),{program:u,reads:s,writes:t}=n.compileExpression(e.expression),o=t.length>0,a=u.opcodes,l=u.numbers,y=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);return {...r,opcodesBuffer:y,numbersBuffer:d,opcodesLength:a.length,numbersLength:l.length,strings:[...u.strings],reads:s,writes:t,isVariableDef:o}}catch(n){return {...r,opcodesBuffer:new ArrayBuffer(0),numbersBuffer:new ArrayBuffer(0),opcodesLength:0,numbersLength:0,error:n instanceof Error?n.message:String(n)}}}function L(e){let r=[],n=[];for(let u of e.items){let s=B(u);r.push(s),s.opcodesBuffer.byteLength>0&&n.push(s.opcodesBuffer),s.numbersBuffer.byteLength>0&&n.push(s.numbersBuffer);}self.postMessage({id:e.id,type:"COMPILE_RESULT",results:r},n);}function M(e){let r=h();r.reset();let n=new Uint8Array(e.opcodesBuffer,0,e.opcodesLength),u=new Float64Array(e.numbersBuffer,0,e.numbersLength),s={opcodes:n,numbers:u,strings:e.strings};try{let t=d(s,r);if(t.type==="pending")return {lineNumber:e.lineNumber,valueType:12,value:0,isPending:!0,queryKey:t.queryKey};if(t.type==="error")return {lineNumber:e.lineNumber,valueType:13,value:0,isPending:!1,unit:t.error.message};let o=t.value;return {lineNumber:e.lineNumber,valueType:o.type,value:typeof o.value=="number"?o.value:typeof o.value=="bigint"?Number(o.value):0,unit:o.unit,isPending:!1}}catch{return {lineNumber:e.lineNumber,valueType:13,value:0,isPending:false,unit:"Worker execution failed"}}}function T(e){let r=[];for(let n of e.items)r.push(M(n));self.postMessage({id:e.id,type:"EXECUTE_RESULT",results:r});}var x=typeof self<"u"&&typeof window>"u",C=e=>{if(e.origin&&self.location&&e.origin!==self.location.origin)return;let r=e.data;switch(r.type){case "COMPILE_BATCH":L(r);break;case "EXECUTE_BATCH":T(r);break;case "TERMINATE":{i&&(i.clear(),i=null),f&&(f.reset(),f=null),self.postMessage({id:r.id,type:"COMPILE_RESULT",results:[]});break}default:self.postMessage({id:-1,type:"COMPILE_RESULT",results:[],error:`Unknown message type: ${r.type}`});}};x&&(self.onmessage=C);//# sourceMappingURL=engine.worker.js.map
|
|
2
|
+
//# sourceMappingURL=engine.worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/workers/engine.worker.ts"],"names":["compileEngine","getCompileEngine","ExpressionEngine","BUILTIN_PACKAGES","executeVm","getExecuteVm","createVM","sharedOpRegistry","compileOne","item","base","eng","program","reads","writes","isVariableDef","opcodes","numbers","opcodesBuffer","numbersBuffer","e","handleCompileBatch","msg","results","transferList","result","executeOne","vmm","bytecode","executeBytecode","val","handleExecuteBatch","inWorkerScope","handleMessage","event"],"mappings":"khCA0GA,IAAIA,CAAAA,CAAyC,IAAA,CAC7C,SAASC,CAAAA,EAAqC,CAC7C,OAAKD,CAAAA,GAOJA,CAAAA,CAAgB,IAAIE,CAAAA,CAAiB,CAAE,QAAA,CAAUC,CAAiB,CAAC,CAAA,CAAA,CAE7DH,CACR,CAEA,IAAII,CAAAA,CAAgD,IAAA,CACpD,SAASC,CAAAA,EAA4C,CACpD,OAAKD,CAAAA,GACJA,CAAAA,CAAYE,CAAAA,CAASC,CAAAA,CAAkB,GAAA,CAAK,GAAK,CAAA,CAAA,CAE3CH,CACR,CAUA,SAASI,CAAAA,CAAWC,CAAAA,CAAkC,CACrD,IAAMC,CAAAA,CAAmG,CACxG,MAAA,CAAQD,CAAAA,CAAK,MAAA,CACb,UAAA,CAAYA,CAAAA,CAAK,UAAA,CACjB,mBAAA,CAAqBA,CAAAA,CAAK,QAAA,CAC1B,OAAA,CAAS,EAAC,CACV,KAAA,CAAO,EAAC,CACR,MAAA,CAAQ,EAAC,CACT,aAAA,CAAe,KAAA,CACf,MAAO,IACR,CAAA,CAEA,GAAI,CACH,IAAME,CAAAA,CAAMV,CAAAA,EAAiB,CACvB,CAAE,OAAA,CAAAW,CAAAA,CAAS,KAAA,CAAAC,CAAAA,CAAO,MAAA,CAAAC,CAAO,CAAA,CAAIH,CAAAA,CAAI,iBAAA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,EAAYA,CAAAA,CAAM,MAAA,GAAW,IAAA,CAAK,QAAA,CAAS,MAAA,CAAQ,OAE5E,IAAMZ,CAAAA,CAAMY,CAAAA,CAAM,IAAA,CAElB,OAAQZ,CAAAA,CAAI,IAAA,EACX,KAAK,eAAA,CACJD,CAAAA,CAAmBC,CAAG,EACtB,MAED,KAAK,eAAA,CACJS,CAAAA,CAAmBT,CAAG,CAAA,CACtB,MAED,KAAK,WAAA,CAAa,CAKbtB,CAAAA,GACHA,CAAAA,CAAc,KAAA,EAAM,CACpBA,CAAAA,CAAgB,IAAA,CAAA,CAEbI,CAAAA,GACHA,CAAAA,CAAU,KAAA,EAAM,CAChBA,CAAAA,CAAY,IAAA,CAAA,CAEZ,IAAA,CAA2B,WAAA,CAAY,CACvC,EAAA,CAAIkB,CAAAA,CAAI,EAAA,CACR,IAAA,CAAM,gBAAA,CACN,QAAS,EACV,CAAC,CAAA,CACD,KACD,CAEA,QACE,IAAA,CAA2B,WAAA,CAAY,CACvC,EAAA,CAAI,EAAA,CACJ,IAAA,CAAM,gBAAA,CACN,OAAA,CAAS,EAAC,CACV,KAAA,CAAO,CAAA,sBAAA,EAA0BA,CAAAA,CAA0B,IAAI,CAAA,CAChE,CAAC,EAEH,CACD,CAAA,CAKIU,CAAAA,GACH,IAAA,CAAK,SAAA,CAAYC,CAAAA,CAAAA","file":"engine.worker.js","sourcesContent":["/**\n * Engine worker, offloads both compilation and VM execution to a\n * background thread (plan L6: worker consolidation).\n *\n * Previously two separate worker files (compilation.worker.ts,\n * execution.worker.ts) duplicated the Transferable ArrayBuffer protocol,\n * postMessage/onmessage boilerplate, and lazy-init pattern. This file\n * merges them behind a single `self.onmessage` dispatching on `msg.type`\n * the message shapes are UNCHANGED from the two original files, so\n * CompilationWorkerManager and ExecutionPool (the main-thread consumers)\n * reach a worker started from this file through the factory a host registers\n * with `setEngineWorkerFactory`, and never import this module themselves.\n *\n * Each Worker instance created from this file is used exclusively by ONE\n * consumer (a CompilationWorkerManager sends only COMPILE_BATCH; an\n * ExecutionPool sends only EXECUTE_BATCH), the module-level `engine` and\n * `vm` singletons below are independent lazy state, so there is no\n * cross-contamination between the two roles even though they share code.\n *\n * Message protocol:\n * Main → Worker:\n * { type: \"COMPILE_BATCH\", id, items: CompileItem[] }\n * { type: \"EXECUTE_BATCH\", id, items: ExecuteItem[] }\n * { type: \"TERMINATE\", id }\n *\n * Worker → Main:\n * { id, type: \"COMPILE_RESULT\", results: CompileResult[] }\n * { id, type: \"EXECUTE_RESULT\", results: ExecuteResult[] }\n *\n * Transferable objects: bytecode opcodes/numbers buffers are transferred\n * (zero-copy) in both directions, same pattern as the original files.\n */\n\nimport { ExpressionEngine } from \"../engine/ExpressionEngine\";\nimport { BUILTIN_PACKAGES } from \"../packages/builtins\";\nimport type { Bytecode } from \"../vm/VM\";\nimport { createVM, executeBytecode } from \"../vm/VM\";\nimport { sharedOpRegistry } from \"../vm/OpRegistry\";\nimport { ValueType } from \"../vm/Value\";\n\n// ── Compile message types ──────────────────────────────────────────────\n\ninterface CompileItem {\n\tlineId: number;\n\texpression: string;\n\ttextHash: number;\n}\n\ninterface CompileBatchMsg {\n\ttype: \"COMPILE_BATCH\";\n\tid: number;\n\titems: CompileItem[];\n}\n\ninterface CompileResult {\n\tlineId: number;\n\texpression: string;\n\tcompiledAgainstHash: number;\n\topcodesBuffer: ArrayBuffer;\n\tnumbersBuffer: ArrayBuffer;\n\topcodesLength: number;\n\tnumbersLength: number;\n\tstrings: string[];\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// ── Execute message types ──────────────────────────────────────────────\n\ninterface ExecuteItem {\n\tlineNumber: number;\n\topcodesBuffer: ArrayBuffer;\n\tnumbersBuffer: ArrayBuffer;\n\topcodesLength: number;\n\tnumbersLength: number;\n\tstrings: string[];\n}\n\ninterface ExecuteBatchMsg {\n\ttype: \"EXECUTE_BATCH\";\n\tid: number;\n\titems: ExecuteItem[];\n}\n\ninterface ExecuteResult {\n\tlineNumber: number;\n\tvalueType: ValueType;\n\tvalue: number;\n\tunit?: string;\n\tisPending: boolean;\n\tqueryKey?: string;\n}\n\ninterface TerminateMsg {\n\ttype: \"TERMINATE\";\n\tid: number;\n}\n\ntype EngineWorkerMessage = CompileBatchMsg | ExecuteBatchMsg | TerminateMsg;\n\n// ── Worker body ───────────────────────────────────────────────────────\n\n// ── Lazy per-role state, independent, only the used one is created ────\n\nlet compileEngine: ExpressionEngine | null = null;\nfunction getCompileEngine(): ExpressionEngine {\n\tif (!compileEngine) {\n\t\t// The full vocabulary, which is the point of this file being its own\n\t\t// bundle: a compile engine with no packages would refuse every line a\n\t\t// package gives meaning to, and the manager would fall back to the main\n\t\t// thread for nearly all of them. Nothing but a host that registers a\n\t\t// factory (see `WorkerFactory.ts`) reaches this module, so a consumer's\n\t\t// main bundle carries neither the packages nor this file.\n\t\tcompileEngine = new ExpressionEngine({ packages: BUILTIN_PACKAGES });\n\t}\n\treturn compileEngine;\n}\n\nlet executeVm: ReturnType<typeof createVM> | null = null;\nfunction getExecuteVm(): ReturnType<typeof createVM> {\n\tif (!executeVm) {\n\t\texecuteVm = createVM(sharedOpRegistry, 200, 50000);\n\t}\n\treturn executeVm;\n}\n\n// ── Compile ──────────────────────────────────────────────────────────\n\n/**\n * Compile a single expression and produce a transfer-ready CompileResult.\n * Extracts ArrayBuffers from the compiled TypedArrays so they can be\n * transferred via postMessage, after this call, the original TypedArrays\n * are detached on the worker side.\n */\nfunction compileOne(item: CompileItem): CompileResult {\n\tconst base: Omit<CompileResult, \"opcodesBuffer\" | \"numbersBuffer\" | \"opcodesLength\" | \"numbersLength\"> = {\n\t\tlineId: item.lineId,\n\t\texpression: item.expression,\n\t\tcompiledAgainstHash: item.textHash,\n\t\tstrings: [],\n\t\treads: [],\n\t\twrites: [],\n\t\tisVariableDef: false,\n\t\terror: null,\n\t};\n\n\ttry {\n\t\tconst eng = getCompileEngine();\n\t\tconst { program, reads, writes } = eng.compileExpression(item.expression);\n\t\tconst isVariableDef = writes.length > 0;\n\n\t\tconst opcodes = program.opcodes;\n\t\tconst numbers = program.numbers;\n\n\t\t// Transfer only the exact used slice of the ArrayBuffer. The engine's\n\t\t// buffer pool is write-only, so detaching the source view is fine.\n\t\t//\n\t\t// The casts narrow ArrayBufferLike to ArrayBuffer. A TypedArray's\n\t\t// `buffer` is typed as the union including SharedArrayBuffer, which\n\t\t// TypeScript 6 enforces where 5.1 did not, and the postMessage\n\t\t// transfer list below accepts only ArrayBuffer. The narrowing is\n\t\t// sound here because these buffers come from the engine's own pool,\n\t\t// which allocates plain ArrayBuffers; a SharedArrayBuffer could not\n\t\t// reach this point, and would not be transferable if it did.\n\t\tconst opcodesBuffer = (opcodes.buffer as ArrayBuffer).slice(\n\t\t\topcodes.byteOffset,\n\t\t\topcodes.byteOffset + opcodes.byteLength\n\t\t);\n\t\tconst numbersBuffer = (numbers.buffer as ArrayBuffer).slice(\n\t\t\tnumbers.byteOffset,\n\t\t\tnumbers.byteOffset + numbers.byteLength\n\t\t);\n\n\t\treturn {\n\t\t\t...base,\n\t\t\topcodesBuffer,\n\t\t\tnumbersBuffer,\n\t\t\topcodesLength: opcodes.length,\n\t\t\tnumbersLength: numbers.length,\n\t\t\tstrings: [...program.strings],\n\t\t\treads,\n\t\t\twrites,\n\t\t\tisVariableDef,\n\t\t};\n\t} catch (e) {\n\t\treturn {\n\t\t\t...base,\n\t\t\topcodesBuffer: new ArrayBuffer(0),\n\t\t\tnumbersBuffer: new ArrayBuffer(0),\n\t\t\topcodesLength: 0,\n\t\t\tnumbersLength: 0,\n\t\t\terror: e instanceof Error ? e.message : String(e),\n\t\t};\n\t}\n}\n\nfunction handleCompileBatch(msg: CompileBatchMsg): void {\n\tconst results: CompileResult[] = [];\n\tconst transferList: ArrayBuffer[] = [];\n\n\tfor (const item of msg.items) {\n\t\tconst result = compileOne(item);\n\t\tresults.push(result);\n\t\tif (result.opcodesBuffer.byteLength > 0) transferList.push(result.opcodesBuffer);\n\t\tif (result.numbersBuffer.byteLength > 0) transferList.push(result.numbersBuffer);\n\t}\n\n\t(self as unknown as Worker).postMessage(\n\t\t{ id: msg.id, type: \"COMPILE_RESULT\", results },\n\t\ttransferList\n\t);\n}\n\n// ── Execute ──────────────────────────────────────────────────────────\n\n/**\n * Execute a single bytecode program and produce a serialized ExecuteResult.\n * Reconstructs TypedArrays from the transferred ArrayBuffers (zero-copy).\n * Resets the worker VM before each execution, no state carries over\n * between lines in a batch.\n */\nfunction executeOne(item: ExecuteItem): ExecuteResult {\n\tconst vmm = getExecuteVm();\n\tvmm.reset();\n\n\tconst opcodes = new Uint8Array(item.opcodesBuffer, 0, item.opcodesLength);\n\tconst numbers = new Float64Array(item.numbersBuffer, 0, item.numbersLength);\n\tconst bytecode: Bytecode = { opcodes, numbers, strings: item.strings };\n\n\ttry {\n\t\tconst result = executeBytecode(bytecode, vmm);\n\n\t\tif (result.type === \"pending\") {\n\t\t\treturn {\n\t\t\t\tlineNumber: item.lineNumber,\n\t\t\t\tvalueType: ValueType.Pending,\n\t\t\t\tvalue: 0,\n\t\t\t\tisPending: true,\n\t\t\t\tqueryKey: result.queryKey,\n\t\t\t};\n\t\t}\n\n\t\tif (result.type === \"error\") {\n\t\t\treturn {\n\t\t\t\tlineNumber: item.lineNumber,\n\t\t\t\tvalueType: ValueType.Error,\n\t\t\t\tvalue: 0,\n\t\t\t\tisPending: false,\n\t\t\t\tunit: result.error.message,\n\t\t\t};\n\t\t}\n\n\t\tconst val = result.value;\n\t\treturn {\n\t\t\tlineNumber: item.lineNumber,\n\t\t\tvalueType: val.type,\n\t\t\tvalue: typeof val.value === \"number\"\n\t\t\t\t? val.value\n\t\t\t\t: typeof val.value === \"bigint\"\n\t\t\t\t\t? Number(val.value)\n\t\t\t\t\t: 0,\n\t\t\tunit: val.unit,\n\t\t\tisPending: false,\n\t\t};\n\t} catch {\n\t\t// Execution error, return error-type value so main thread can\n\t\t// propagate through DAG as errorValue.\n\t\treturn {\n\t\t\tlineNumber: item.lineNumber,\n\t\t\tvalueType: ValueType.Error,\n\t\t\tvalue: 0,\n\t\t\tisPending: false,\n\t\t\tunit: \"Worker execution failed\",\n\t\t};\n\t}\n}\n\nfunction handleExecuteBatch(msg: ExecuteBatchMsg): void {\n\tconst results: ExecuteResult[] = [];\n\tfor (const item of msg.items) {\n\t\tresults.push(executeOne(item));\n\t}\n\t// No transferables needed for the response, results are plain\n\t// objects with numbers and strings (structured-cloned).\n\t(self as unknown as Worker).postMessage({\n\t\tid: msg.id,\n\t\ttype: \"EXECUTE_RESULT\",\n\t\tresults,\n\t});\n}\n\n// ── Message handler ───────────────────────────────────────────────────\n\n/**\n * Whether this module is executing inside a real worker global scope.\n *\n * This file is a bundle entry of its own (`solve-engine/engine-worker`), so a\n * host that starts a worker from it runs the handler below in a worker. It is\n * still an ordinary module to anything that merely imports it, a test harness\n * or a Node script included, and there the handler must not bind.\n *\n * Without this guard, importing it from Node throws `self is not defined`\n * before a single expression can be evaluated. The check distinguishes the\n * three environments: Node defines neither `self` nor `window`, a browser main\n * thread defines both, and a worker defines only `self`.\n */\nconst inWorkerScope = typeof self !== \"undefined\" && typeof window === \"undefined\";\n\nconst handleMessage = (event: MessageEvent) => {\n\t// A real postMessage always carries a browser-populated origin the\n\t// sender cannot spoof, so this only ever rejects a genuine mismatch. It\n\t// is skipped, not enforced, when either side is unset, which covers the\n\t// test harness driving this handler directly with a plain object and\n\t// no location global (see WorkerIntegration.spec.ts), without opening\n\t// anything a real message could exploit.\n\tif (event.origin && self.location && event.origin !== self.location.origin) return;\n\n\tconst msg = event.data as EngineWorkerMessage;\n\n\tswitch (msg.type) {\n\t\tcase \"COMPILE_BATCH\":\n\t\t\thandleCompileBatch(msg);\n\t\t\tbreak;\n\n\t\tcase \"EXECUTE_BATCH\":\n\t\t\thandleExecuteBatch(msg);\n\t\t\tbreak;\n\n\t\tcase \"TERMINATE\": {\n\t\t\t// Not sent by either production manager today, both call the\n\t\t\t// native Worker.terminate() directly instead. Kept for protocol\n\t\t\t// completeness and future consumers. Clears whichever per-role\n\t\t\t// state this instance happened to create.\n\t\t\tif (compileEngine) {\n\t\t\t\tcompileEngine.clear();\n\t\t\t\tcompileEngine = null;\n\t\t\t}\n\t\t\tif (executeVm) {\n\t\t\t\texecuteVm.reset();\n\t\t\t\texecuteVm = null;\n\t\t\t}\n\t\t\t(self as unknown as Worker).postMessage({\n\t\t\t\tid: msg.id,\n\t\t\t\ttype: \"COMPILE_RESULT\",\n\t\t\t\tresults: [],\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault: {\n\t\t\t(self as unknown as Worker).postMessage({\n\t\t\t\tid: -1,\n\t\t\t\ttype: \"COMPILE_RESULT\",\n\t\t\t\tresults: [],\n\t\t\t\terror: `Unknown message type: ${(msg as { type?: string }).type}`,\n\t\t\t});\n\t\t}\n\t}\n};\n\n// Installed only when genuinely running as a worker. Everywhere else this\n// module has been inlined into a host bundle, where binding a handler would at\n// best be inert and at worst intercept the host's own messages.\nif (inWorkerScope) {\n\tself.onmessage = handleMessage;\n}\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';require('./chunk-
|
|
1
|
+
'use strict';require('./chunk-5EL4WXLF.cjs'),require('./chunk-EFJCC6FJ.cjs');var chunkJPT6L7BG_cjs=require('./chunk-JPT6L7BG.cjs');require('./chunk-Q7TBBV62.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-ZVPZQ66D.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-GWV273KZ.cjs'),require('./chunk-HG4NPDN5.cjs');var chunkP43SV4NJ_cjs=require('./chunk-P43SV4NJ.cjs');require('./chunk-R2SZFJTT.cjs');var chunkW7NN77PH_cjs=require('./chunk-W7NN77PH.cjs');require('./chunk-A755LVPT.cjs'),require('./chunk-WQGHJAW2.cjs');var chunk5AKT36UK_cjs=require('./chunk-5AKT36UK.cjs');require('./chunk-4DR5RBHQ.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-RAFOQ4T5.cjs'),require('./chunk-CM2WM5CM.cjs'),require('./chunk-DUFEONVN.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-YWF6C2IO.cjs');var chunkA764BY7L_cjs=require('./chunk-A764BY7L.cjs');require('./chunk-E4HAKNBQ.cjs');var chunkOM7NOHJF_cjs=require('./chunk-OM7NOHJF.cjs');require('./chunk-ZKFCKAIX.cjs');var chunkUHS4HMOQ_cjs=require('./chunk-UHS4HMOQ.cjs');require('./chunk-AGCNMEP2.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-WU7SBKVU.cjs'),require('./chunk-YBQOQTVL.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs');var chunkSUAGBRQ7_cjs=require('./chunk-SUAGBRQ7.cjs');var r={DEFINE_FUNCTION_INVALID_NAME:"DEFINE_FUNCTION_INVALID_NAME",DEFINE_FUNCTION_INVALID_SPEC:"DEFINE_FUNCTION_INVALID_SPEC",DEFINE_FUNCTION_ARITY_MISMATCH:"DEFINE_FUNCTION_ARITY_MISMATCH",DEFINE_FUNCTION_ARGUMENT_TYPE:"DEFINE_FUNCTION_ARGUMENT_TYPE",DEFINE_FUNCTION_RETURN_TYPE:"DEFINE_FUNCTION_RETURN_TYPE"},O=/^[a-z_][a-z0-9_]*$/i,N=new Set(["number","string","boolean"]);function u(e){return e===1?"1 argument":`${e} arguments`}function d(e){switch(e.type){case 0:case 1:return "a number";case 3:return "a string";case 10:return "a boolean";case 2:return "a big integer";case 5:return "a percentage";case 6:return "a value with a unit";case 4:return "a date";case 7:return "a matrix";case 8:return "a range";case 9:return "a symbolic expression";default:return "an unsupported value"}}function k(e,n,t){switch(n.type){case "number":if(e.type===0||e.type===1)return e.toNumber();break;case "string":if(e.type===3)return e.value;break;case "boolean":if(e.type===10)return e.value;break}throw chunkSUAGBRQ7_cjs.c.execution({code:r.DEFINE_FUNCTION_ARGUMENT_TYPE,message:`${t}() expects "${n.name}" to be a ${n.type}, but was given ${d(e)}`,expected:`a ${n.type}`,found:d(e),context:{functionName:t,argName:n.name,expectedType:n.type}})}function R(e,n,t){switch(n){case "number":if(typeof e=="number")return chunkOM7NOHJF_cjs.n(e);break;case "string":if(typeof e=="string")return chunkOM7NOHJF_cjs.t(e);break;case "boolean":if(typeof e=="boolean")return chunkOM7NOHJF_cjs.L(e);break}throw chunkSUAGBRQ7_cjs.c.internal({code:r.DEFINE_FUNCTION_RETURN_TYPE,message:`${t}() is declared to return a ${n}, but its implementation returned ${typeof e}`,expected:`a ${n}`,found:typeof e,context:{functionName:t,expectedType:n}})}var p=class{constructor(n){this.fnName=n;this.category="Function";}parse(n,t,a){n.consume("LPAREN");let i=0;if(n.peek()?.type!=="RPAREN")for(n.parseExpression(chunk5AKT36UK_cjs.a.Lowest,a),i++;n.match("COMMA");)n.parseExpression(chunk5AKT36UK_cjs.a.Lowest,a),i++;n.consume("RPAREN"),a.emitPluginCall(this.fnName,i);}};function D(e){let n=e.args.length;return t=>{if(t.length!==n)throw chunkSUAGBRQ7_cjs.c.execution({code:r.DEFINE_FUNCTION_ARITY_MISMATCH,message:`${e.name}() takes ${u(n)}, but was given ${t.length===0?"none":u(t.length)}`,expected:u(n),found:t.length===0?"none":u(t.length),context:{functionName:e.name,expected:n,actual:t.length}});let a=new Array(n);for(let s=0;s<n;s++)a[s]=k(t[s],e.args[s],e.name);let i=e.call(...a);return R(i,e.returns,e.name)}}function h(e){if(typeof e?.name!="string"||!O.test(e.name))throw chunkSUAGBRQ7_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_NAME,message:`defineFunction: name must be a single identifier, got ${JSON.stringify(e?.name)}`,suggestion:'e.g. "vat" or "net_price"',context:{name:e?.name}});if(!Array.isArray(e.args))throw chunkSUAGBRQ7_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" args must be an array`,context:{name:e.name}});for(let n of e.args){if(typeof n?.name!="string"||n.name.length===0)throw chunkSUAGBRQ7_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has an argument with no name`,context:{name:e.name}});if(!N.has(n.type))throw chunkSUAGBRQ7_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" argument "${n.name}" has unsupported type ${JSON.stringify(n.type)}`,suggestion:"supported argument types are number, string, boolean",context:{name:e.name,argName:n.name,type:n.type}})}if(!N.has(e.returns))throw chunkSUAGBRQ7_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has unsupported return type ${JSON.stringify(e.returns)}`,suggestion:"supported return types are number, string, boolean",context:{name:e.name,returns:e.returns}});if(typeof e.call!="function")throw chunkSUAGBRQ7_cjs.c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" is missing a call implementation`,context:{name:e.name}})}function w(e){h(e);let n=e.name,t=`DEFINE_FN_${n.toUpperCase()}`;return {name:`solve-fn-${n}`,lexerVocabulary:{keywords:{[n.toLowerCase()]:t}},prefixParselets:{[t]:new p(n)},pluginFunctions:{[n]:D(e)}}}function U(e={}){let{extraPackages:n=[],...t}=e;return new chunkJPT6L7BG_cjs.o({...t,packages:n.length>0?[...chunkW7NN77PH_cjs.z,...n]:chunkW7NN77PH_cjs.z})}Object.defineProperty(exports,"ExpressionEngine",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.o}});Object.defineProperty(exports,"SNAPSHOT_FORMAT",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.d}});Object.defineProperty(exports,"SNAPSHOT_VERSION",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.e}});Object.defineProperty(exports,"SnapshotErrorCodes",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.f}});Object.defineProperty(exports,"assertEngineVersionCompatible",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.c}});Object.defineProperty(exports,"checkEngineVersionCompatibility",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.b}});Object.defineProperty(exports,"checkPackageCompatibility",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.a}});Object.defineProperty(exports,"setEngineWorkerFactory",{enumerable:true,get:function(){return chunkJPT6L7BG_cjs.g}});Object.defineProperty(exports,"formatValue",{enumerable:true,get:function(){return chunkP43SV4NJ_cjs.c}});Object.defineProperty(exports,"dateCalendarInZone",{enumerable:true,get:function(){return chunkA764BY7L_cjs.d}});Object.defineProperty(exports,"Value",{enumerable:true,get:function(){return chunkOM7NOHJF_cjs.m}});Object.defineProperty(exports,"ValueType",{enumerable:true,get:function(){return chunkOM7NOHJF_cjs.g}});Object.defineProperty(exports,"ENGINE_VERSION",{enumerable:true,get:function(){return chunkUHS4HMOQ_cjs.a}});exports.DefineFunctionErrorCodes=r;exports.createEngine=U;exports.defineFunction=w;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { I as IEnginePackage, a as EngineOptions, E as ExpressionEngine } from './PackageRegistry-B-C1duZw.cjs';
|
|
2
2
|
export { D as DateOrderSource, b as DateReading, c as DateReadingPolicy, d as EngineRestoreOptions, e as EngineSnapshot, f as Explanation, g as ExplanationStep, R as ResolvedDateOrder, S as SNAPSHOT_FORMAT, h as SNAPSHOT_VERSION, i as SerializedAnonymousBody, j as SerializedBytecode, k as SerializedDecimal, l as SerializedLineCacheEntry, m as SerializedNumber, n as SerializedRational, o as SerializedUserFunction, p as SerializedValue, q as SnapshotErrorCodes } from './PackageRegistry-B-C1duZw.cjs';
|
|
3
3
|
export { a as CompatibilityConflict, b as CompatibilityConflictKind, C as CompatibilityReport, c as CompatibilitySeverity, d as checkPackageCompatibility } from './PackageCompatibility-Bn-T_xKW.cjs';
|
|
4
|
+
export { E as EngineWorkerFactory, d as dateCalendarInZone, s as setEngineWorkerFactory } from './DateCalendar-GFQDX1ng.cjs';
|
|
4
5
|
export { E as EngineConfigOverride } from './Configuration-BxriK9Kw.cjs';
|
|
5
6
|
export { D as DatetimeGrain, V as Value, b as ValueType } from './Value-BYHw-x7q.cjs';
|
|
6
7
|
export { formatValue } from './format.cjs';
|
|
7
8
|
export { F as FormattingSettings } from './FormattingSettings-ByO-4wiM.cjs';
|
|
8
9
|
export { C as CalendarBackend, a as CalendarFields, Z as ZonedFields } from './CalendarBackend-MdS3Bb4P.cjs';
|
|
9
|
-
export { d as dateCalendarInZone } from './DateCalendar-CUGI1fT4.cjs';
|
|
10
10
|
export { ENGINE_VERSION } from './constants.cjs';
|
|
11
11
|
import './Parselet-DF3864la.cjs';
|
|
12
12
|
import './BytecodeBuilder-DSWKZi4f.cjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { I as IEnginePackage, a as EngineOptions, E as ExpressionEngine } from './PackageRegistry-C78jVkI9.js';
|
|
2
2
|
export { D as DateOrderSource, b as DateReading, c as DateReadingPolicy, d as EngineRestoreOptions, e as EngineSnapshot, f as Explanation, g as ExplanationStep, R as ResolvedDateOrder, S as SNAPSHOT_FORMAT, h as SNAPSHOT_VERSION, i as SerializedAnonymousBody, j as SerializedBytecode, k as SerializedDecimal, l as SerializedLineCacheEntry, m as SerializedNumber, n as SerializedRational, o as SerializedUserFunction, p as SerializedValue, q as SnapshotErrorCodes } from './PackageRegistry-C78jVkI9.js';
|
|
3
3
|
export { a as CompatibilityConflict, b as CompatibilityConflictKind, C as CompatibilityReport, c as CompatibilitySeverity, d as checkPackageCompatibility } from './PackageCompatibility-phvSFP4f.js';
|
|
4
|
+
export { E as EngineWorkerFactory, d as dateCalendarInZone, s as setEngineWorkerFactory } from './DateCalendar-CTz538dw.js';
|
|
4
5
|
export { E as EngineConfigOverride } from './Configuration-BxriK9Kw.js';
|
|
5
6
|
export { D as DatetimeGrain, V as Value, b as ValueType } from './Value-BYHw-x7q.js';
|
|
6
7
|
export { formatValue } from './format.js';
|
|
7
8
|
export { F as FormattingSettings } from './FormattingSettings-CvCzAfsz.js';
|
|
8
9
|
export { C as CalendarBackend, a as CalendarFields, Z as ZonedFields } from './CalendarBackend-MdS3Bb4P.js';
|
|
9
|
-
export { d as dateCalendarInZone } from './DateCalendar-B85t6Vk6.js';
|
|
10
10
|
export { ENGINE_VERSION } from './constants.js';
|
|
11
11
|
import './Parselet-Dgymjxzd.js';
|
|
12
12
|
import './BytecodeBuilder-DSWKZi4f.js';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import'./chunk-
|
|
1
|
+
import'./chunk-D4UHCZAW.js';import'./chunk-RAF57WYO.js';import {o}from'./chunk-VYB44JLS.js';export{o as ExpressionEngine,d as SNAPSHOT_FORMAT,e as SNAPSHOT_VERSION,f as SnapshotErrorCodes,c as assertEngineVersionCompatible,b as checkEngineVersionCompatibility,a as checkPackageCompatibility,g as setEngineWorkerFactory}from'./chunk-VYB44JLS.js';import'./chunk-CB3EXUM2.js';import'./chunk-2RWAXT6O.js';import'./chunk-IJHL3LMH.js';import'./chunk-MIQBJGGR.js';import'./chunk-2PGGPFF3.js';import'./chunk-JP4JMQOG.js';export{c as formatValue}from'./chunk-IQVSCL2R.js';import'./chunk-XEIDV5JP.js';import {z}from'./chunk-V7LXOTCU.js';import'./chunk-SFM4XFGJ.js';import'./chunk-FXB5GCBT.js';import {a}from'./chunk-VLX7ZVK4.js';import'./chunk-B2NL65FI.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-YN5H54GM.js';import'./chunk-3ZGFAE3Q.js';import'./chunk-PTXUWGRR.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-KH4QXKLT.js';export{d as dateCalendarInZone}from'./chunk-NQFCXLEF.js';import'./chunk-J4K72CQN.js';import {L,t,n}from'./chunk-X5K72MBV.js';export{m as Value,g as ValueType}from'./chunk-X5K72MBV.js';import'./chunk-4CNYGIND.js';export{a as ENGINE_VERSION}from'./chunk-64OGL465.js';import'./chunk-CDE2ZUGG.js';import'./chunk-JPFCXLJV.js';import'./chunk-LP3JYC3A.js';import'./chunk-FAO6DQ74.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import {c}from'./chunk-RELMEWY6.js';var r={DEFINE_FUNCTION_INVALID_NAME:"DEFINE_FUNCTION_INVALID_NAME",DEFINE_FUNCTION_INVALID_SPEC:"DEFINE_FUNCTION_INVALID_SPEC",DEFINE_FUNCTION_ARITY_MISMATCH:"DEFINE_FUNCTION_ARITY_MISMATCH",DEFINE_FUNCTION_ARGUMENT_TYPE:"DEFINE_FUNCTION_ARGUMENT_TYPE",DEFINE_FUNCTION_RETURN_TYPE:"DEFINE_FUNCTION_RETURN_TYPE"},O=/^[a-z_][a-z0-9_]*$/i,N=new Set(["number","string","boolean"]);function u(e){return e===1?"1 argument":`${e} arguments`}function d(e){switch(e.type){case 0:case 1:return "a number";case 3:return "a string";case 10:return "a boolean";case 2:return "a big integer";case 5:return "a percentage";case 6:return "a value with a unit";case 4:return "a date";case 7:return "a matrix";case 8:return "a range";case 9:return "a symbolic expression";default:return "an unsupported value"}}function k(e,n,t){switch(n.type){case "number":if(e.type===0||e.type===1)return e.toNumber();break;case "string":if(e.type===3)return e.value;break;case "boolean":if(e.type===10)return e.value;break}throw c.execution({code:r.DEFINE_FUNCTION_ARGUMENT_TYPE,message:`${t}() expects "${n.name}" to be a ${n.type}, but was given ${d(e)}`,expected:`a ${n.type}`,found:d(e),context:{functionName:t,argName:n.name,expectedType:n.type}})}function R(e,n$1,t$1){switch(n$1){case "number":if(typeof e=="number")return n(e);break;case "string":if(typeof e=="string")return t(e);break;case "boolean":if(typeof e=="boolean")return L(e);break}throw c.internal({code:r.DEFINE_FUNCTION_RETURN_TYPE,message:`${t$1}() is declared to return a ${n$1}, but its implementation returned ${typeof e}`,expected:`a ${n$1}`,found:typeof e,context:{functionName:t$1,expectedType:n$1}})}var p=class{constructor(n){this.fnName=n;this.category="Function";}parse(n,t,a$1){n.consume("LPAREN");let i=0;if(n.peek()?.type!=="RPAREN")for(n.parseExpression(a.Lowest,a$1),i++;n.match("COMMA");)n.parseExpression(a.Lowest,a$1),i++;n.consume("RPAREN"),a$1.emitPluginCall(this.fnName,i);}};function D(e){let n=e.args.length;return t=>{if(t.length!==n)throw c.execution({code:r.DEFINE_FUNCTION_ARITY_MISMATCH,message:`${e.name}() takes ${u(n)}, but was given ${t.length===0?"none":u(t.length)}`,expected:u(n),found:t.length===0?"none":u(t.length),context:{functionName:e.name,expected:n,actual:t.length}});let a=new Array(n);for(let s=0;s<n;s++)a[s]=k(t[s],e.args[s],e.name);let i=e.call(...a);return R(i,e.returns,e.name)}}function h(e){if(typeof e?.name!="string"||!O.test(e.name))throw c.config({code:r.DEFINE_FUNCTION_INVALID_NAME,message:`defineFunction: name must be a single identifier, got ${JSON.stringify(e?.name)}`,suggestion:'e.g. "vat" or "net_price"',context:{name:e?.name}});if(!Array.isArray(e.args))throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" args must be an array`,context:{name:e.name}});for(let n of e.args){if(typeof n?.name!="string"||n.name.length===0)throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has an argument with no name`,context:{name:e.name}});if(!N.has(n.type))throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" argument "${n.name}" has unsupported type ${JSON.stringify(n.type)}`,suggestion:"supported argument types are number, string, boolean",context:{name:e.name,argName:n.name,type:n.type}})}if(!N.has(e.returns))throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" has unsupported return type ${JSON.stringify(e.returns)}`,suggestion:"supported return types are number, string, boolean",context:{name:e.name,returns:e.returns}});if(typeof e.call!="function")throw c.config({code:r.DEFINE_FUNCTION_INVALID_SPEC,message:`defineFunction: "${e.name}" is missing a call implementation`,context:{name:e.name}})}function w(e){h(e);let n=e.name,t=`DEFINE_FN_${n.toUpperCase()}`;return {name:`solve-fn-${n}`,lexerVocabulary:{keywords:{[n.toLowerCase()]:t}},prefixParselets:{[t]:new p(n)},pluginFunctions:{[n]:D(e)}}}function U(e={}){let{extraPackages:n=[],...t}=e;return new o({...t,packages:n.length>0?[...z,...n]:z})}export{r as DefineFunctionErrorCodes,U as createEngine,w as defineFunction};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api/defineFunction.ts","../src/api/createEngine.ts"],"names":["DefineFunctionErrorCodes","NAME_PATTERN","SUPPORTED_TYPES","plural","count","describeValueType","v","coerceArgument","value","arg","fnName","ErrorFactory","wrapReturn","result","returns","numberValue","stringValue","boolValue","DefinedFunctionParselet","parser","_token","builder","argCount","BindingPower","makeHandler","spec","arity","args","jsArgs","i","validateSpec","defineFunction","name","tokenType","createEngine","options","extraPackages","engineOptions","ExpressionEngine","BUILTIN_PACKAGES"],"mappings":"m8CAkFO,IAAMA,EAA2B,CAEtC,4BAAA,CAA8B,+BAE9B,4BAAA,CAA8B,8BAAA,CAE9B,+BAAgC,gCAAA,CAEhC,6BAAA,CAA+B,+BAAA,CAE/B,2BAAA,CAA6B,6BAC/B,CAAA,CAGMC,CAAAA,CAAe,sBAEfC,CAAAA,CAAuC,IAAI,IAAI,CAAC,QAAA,CAAU,QAAA,CAAU,SAAS,CAAC,EAGpF,SAASC,EAAOC,CAAAA,CAAuB,CACrC,OAAOA,CAAAA,GAAU,CAAA,CAAI,aAAe,CAAA,EAAGA,CAAK,YAC9C,CAQA,SAASC,EAAkBC,CAAAA,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IAAIf,CAAAA,CAAwBc,CAAI,CAC/C,CAAA,CACA,eAAA,CAAiB,CACf,CAACA,CAAI,EAAGR,CAAAA,CAAYC,CAAoB,CAC1C,CACF,CACF,CCrWO,SAASS,EAAaC,CAAAA,CAA+B,GAAsB,CACjF,GAAM,CAAE,aAAA,CAAAC,GAAAA,CAAgB,EAAC,CAAG,GAAGC,CAAc,CAAA,CAAIF,EACjD,OAAO,IAAIG,EAAiB,CAC3B,GAAGD,EACH,QAAA,CAAUD,GAAAA,CAAc,OAAS,CAAA,CAAI,CAAC,GAAGG,CAAAA,CAAkB,GAAGH,GAAa,CAAA,CAAIG,CAChF,CAAC,CACF","file":"index.js","sourcesContent":["import type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport type { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport type { Parser } from \"@solve-js/parser/Parser\";\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport {\n Value,\n ValueType,\n numberValue,\n stringValue,\n boolValue,\n} from \"@solve-js/vm/Value\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A higher-level, declarative way to contribute a single `name(args)`\n * function, sitting ON TOP OF the package contract rather than replacing it.\n *\n * The low-level contract (allocate a plugin function index, write a parselet,\n * emit `CALL_PLUGIN`) stays exactly as it was and remains the way to add\n * anything that needs custom parsing. This module derives that same wiring\n * from a declaration for the common case, a function called with parenthesised\n * arguments, so adding `vat(x)` costs a spec object rather than an\n * understanding of the parser and the VM. See `defineFunction`.\n */\n\n/** The value types a declared argument or return may take. */\nexport type FunctionValueType = \"number\" | \"string\" | \"boolean\";\n\n/** The JavaScript type a {@link FunctionValueType} maps to at the `call` boundary. */\ntype JsValue<T extends FunctionValueType> = T extends \"number\"\n ? number\n : T extends \"string\"\n ? string\n : boolean;\n\n/** One declared parameter: a name (for error messages) and a value type. */\nexport interface FunctionArg {\n /** Parameter name, used only in the generated type-mismatch messages. */\n name: string;\n /** The value type this parameter accepts. */\n type: FunctionValueType;\n}\n\n/** Map a tuple of {@link FunctionArg} specs to the tuple of JS values `call` receives. */\ntype CallArgs<A extends readonly FunctionArg[]> = {\n [K in keyof A]: JsValue<A[K][\"type\"]>;\n};\n\n/**\n * A declarative function definition.\n *\n * `A` and `R` are inferred from the literal `args`/`returns` (via\n * `defineFunction`'s `const` type parameter), so `call`'s parameters and\n * return are typed from the declaration with no annotations: an\n * `{ type: \"number\" }` argument arrives as a `number`, and a `returns:\n * \"string\"` demands a `string` back.\n */\nexport interface FunctionSpec<\n A extends readonly FunctionArg[] = readonly FunctionArg[],\n R extends FunctionValueType = FunctionValueType,\n> {\n /**\n * The call name, a single identifier (`/^[a-z_][a-z0-9_]*$/i`). Registered\n * as a lexer keyword, so it is matched case-insensitively and cannot collide\n * with a built-in keyword (that collision throws at registration time).\n */\n name: string;\n /** The parameters, in order. A fixed-length list: variadic and optional args are out of scope (see {@link defineFunction}). */\n args: A;\n /** The value type the function returns. */\n returns: R;\n /** The implementation, receiving plain JS values and returning one. Must be synchronous (see {@link defineFunction}). */\n call: (...args: CallArgs<A>) => JsValue<R>;\n}\n\n/**\n * Error codes the declarative function API raises. Kept as a co-located const\n * (the convention `errors/ErrorCode.ts` documents for a domain's own codes) so\n * the strings have one source of truth.\n */\nexport const DefineFunctionErrorCodes = {\n /** The spec's `name` is not a single identifier. Thrown by `defineFunction`, before any engine sees it. */\n DEFINE_FUNCTION_INVALID_NAME: \"DEFINE_FUNCTION_INVALID_NAME\",\n /** The spec is otherwise malformed (bad `args`, unsupported type, missing `call`). Thrown by `defineFunction`. */\n DEFINE_FUNCTION_INVALID_SPEC: \"DEFINE_FUNCTION_INVALID_SPEC\",\n /** The call site passed the wrong number of arguments. Raised at evaluation time. */\n DEFINE_FUNCTION_ARITY_MISMATCH: \"DEFINE_FUNCTION_ARITY_MISMATCH\",\n /** An argument was the wrong value type. Raised at evaluation time. */\n DEFINE_FUNCTION_ARGUMENT_TYPE: \"DEFINE_FUNCTION_ARGUMENT_TYPE\",\n /** The `call` implementation returned a value that did not match `returns`. Raised at evaluation time, an authoring bug rather than a user one. */\n DEFINE_FUNCTION_RETURN_TYPE: \"DEFINE_FUNCTION_RETURN_TYPE\",\n} as const;\n\n/** A single identifier: a letter or underscore, then letters, digits, or underscores. */\nconst NAME_PATTERN = /^[a-z_][a-z0-9_]*$/i;\n\nconst SUPPORTED_TYPES: ReadonlySet<string> = new Set([\"number\", \"string\", \"boolean\"]);\n\n/** \"1 argument\" / \"2 arguments\", so a count reads as English either way. Mirrors `VMBuiltinArity.ts`. */\nfunction plural(count: number): string {\n return count === 1 ? \"1 argument\" : `${count} arguments`;\n}\n\n/**\n * A human noun for the type a Value actually carries, for the \"was given ...\"\n * half of a mismatch message. Covers the three declarable types by their own\n * names and everything else by a readable category, so the message never reads\n * \"given a 6\".\n */\nfunction describeValueType(v: Value): string {\n switch (v.type) {\n case ValueType.Number:\n case ValueType.Hex:\n return \"a number\";\n case ValueType.String:\n return \"a string\";\n case ValueType.Boolean:\n return \"a boolean\";\n case ValueType.BigInt:\n return \"a big integer\";\n case ValueType.Percentage:\n return \"a percentage\";\n case ValueType.Uom:\n return \"a value with a unit\";\n case ValueType.Datetime:\n return \"a date\";\n case ValueType.Matrix:\n return \"a matrix\";\n case ValueType.Range:\n return \"a range\";\n case ValueType.Symbolic:\n return \"a symbolic expression\";\n default:\n return \"an unsupported value\";\n }\n}\n\n/**\n * Read one runtime Value as the JS primitive its declared type promises, or\n * raise the engine's structured type error.\n *\n * A \"number\" accepts a plain number or a based literal (`0xFF`), both of which\n * ARE numbers written differently, and reads it with `toNumber()`. Nothing\n * else is coerced: a percentage, a unit-bearing value or a string is a\n * genuinely different kind of value, and silently reinterpreting it is the\n * class of wrong-answer this API exists to avoid.\n */\nfunction coerceArgument(\n value: Value,\n arg: FunctionArg,\n fnName: string,\n): number | string | boolean {\n switch (arg.type) {\n case \"number\":\n // Hex is a number in another base (see `hexValue`), so it reads as one here.\n if (value.type === ValueType.Number || value.type === ValueType.Hex) {\n return value.toNumber();\n }\n break;\n case \"string\":\n if (value.type === ValueType.String) return value.value as string;\n break;\n case \"boolean\":\n if (value.type === ValueType.Boolean) return value.value as boolean;\n break;\n }\n throw ErrorFactory.execution({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_ARGUMENT_TYPE,\n message: `${fnName}() expects \"${arg.name}\" to be a ${arg.type}, but was given ${describeValueType(value)}`,\n expected: `a ${arg.type}`,\n found: describeValueType(value),\n context: { functionName: fnName, argName: arg.name, expectedType: arg.type },\n });\n}\n\n/**\n * Wrap the `call` result back into a Value of the declared return type, or\n * raise a structured error if the implementation handed back something else.\n *\n * The type check here catches an authoring mistake (a function declared to\n * return a number that returns `undefined`, or a Promise from an accidental\n * `async`), turning it into a named error rather than a Value that lies about\n * its own type downstream.\n */\nfunction wrapReturn(result: unknown, returns: FunctionValueType, fnName: string): Value {\n switch (returns) {\n case \"number\":\n if (typeof result === \"number\") return numberValue(result);\n break;\n case \"string\":\n if (typeof result === \"string\") return stringValue(result);\n break;\n case \"boolean\":\n if (typeof result === \"boolean\") return boolValue(result);\n break;\n }\n throw ErrorFactory.internal({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_RETURN_TYPE,\n message: `${fnName}() is declared to return a ${returns}, but its implementation returned ${typeof result}`,\n expected: `a ${returns}`,\n found: typeof result,\n context: { functionName: fnName, expectedType: returns },\n });\n}\n\n/**\n * The call-syntax parselet generated for one declared function.\n *\n * Identical in shape to the built-in `FunctionCallParselet`: consume the open\n * paren, parse a comma-separated argument list, then emit `CALL_PLUGIN` with\n * the function's index and the argument count. The count is whatever was\n * written, arity is checked at the dispatch point (see {@link makeHandler}),\n * the same place the built-in arity check lives.\n */\nclass DefinedFunctionParselet implements PrefixParselet {\n readonly category = \"Function\";\n\n constructor(\n private readonly fnName: string,\n ) {}\n\n parse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n parser.consume(\"LPAREN\");\n\n let argCount = 0;\n if (parser.peek()?.type !== \"RPAREN\") {\n parser.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (parser.match(\"COMMA\")) {\n parser.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n\n parser.consume(\"RPAREN\");\n\n builder.emitPluginCall(this.fnName, argCount);\n }\n}\n\n/**\n * Build the plugin function that checks arity and argument types, calls the\n * host implementation, and wraps the result.\n *\n * The VM has already screened out faulted arguments (an errored or still\n * pending operand short-circuits before the handler runs, see\n * `VM.ts`'s `CALL_PLUGIN` case), so every Value reaching here carries a real\n * result. Arity is checked first, before any argument is read, so a wrong\n * count is reported as a wrong count rather than as a type error on a missing\n * argument.\n */\nfunction makeHandler(spec: FunctionSpec): (args: Value[]) => Value {\n const arity = spec.args.length;\n return (args: Value[]): Value => {\n if (args.length !== arity) {\n throw ErrorFactory.execution({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_ARITY_MISMATCH,\n message: `${spec.name}() takes ${plural(arity)}, but was given ${args.length === 0 ? \"none\" : plural(args.length)}`,\n expected: plural(arity),\n found: args.length === 0 ? \"none\" : plural(args.length),\n context: { functionName: spec.name, expected: arity, actual: args.length },\n });\n }\n\n const jsArgs: (number | string | boolean)[] = new Array(arity);\n for (let i = 0; i < arity; i++) {\n jsArgs[i] = coerceArgument(args[i], spec.args[i], spec.name);\n }\n\n const result = (spec.call as (...a: (number | string | boolean)[]) => unknown)(...jsArgs);\n return wrapReturn(result, spec.returns, spec.name);\n };\n}\n\n/** Reject a spec that could not produce a working function, before any engine sees it. */\nfunction validateSpec(spec: FunctionSpec): void {\n if (typeof spec?.name !== \"string\" || !NAME_PATTERN.test(spec.name)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_NAME,\n message: `defineFunction: name must be a single identifier, got ${JSON.stringify(spec?.name)}`,\n suggestion: 'e.g. \"vat\" or \"net_price\"',\n context: { name: spec?.name },\n });\n }\n if (!Array.isArray(spec.args)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" args must be an array`,\n context: { name: spec.name },\n });\n }\n for (const arg of spec.args) {\n if (typeof arg?.name !== \"string\" || arg.name.length === 0) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" has an argument with no name`,\n context: { name: spec.name },\n });\n }\n if (!SUPPORTED_TYPES.has(arg.type)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" argument \"${arg.name}\" has unsupported type ${JSON.stringify(arg.type)}`,\n suggestion: \"supported argument types are number, string, boolean\",\n context: { name: spec.name, argName: arg.name, type: arg.type },\n });\n }\n }\n if (!SUPPORTED_TYPES.has(spec.returns)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" has unsupported return type ${JSON.stringify(spec.returns)}`,\n suggestion: \"supported return types are number, string, boolean\",\n context: { name: spec.name, returns: spec.returns },\n });\n }\n if (typeof spec.call !== \"function\") {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" is missing a call implementation`,\n context: { name: spec.name },\n });\n }\n}\n\n/**\n * Turn a declarative {@link FunctionSpec} into a ready-to-register\n * {@link IEnginePackage}.\n *\n * This is the higher-level API from issue #102. It derives, from the\n * declaration alone, everything the low-level contract asks an author to write\n * by hand: a named plugin function (the engine assigns its `CALL_PLUGIN`\n * index), a lexer keyword so the name tokenises, a call-syntax parselet emitting\n * that call by name, and a handler that checks arity and argument types (yielding\n * the engine's own structured errors) before invoking `call` and wrapping its\n * result. Anything needing custom parsing keeps writing a raw parselet exactly\n * as before, this sits on top of that contract and does not change it.\n *\n * @example\n * ```ts\n * const engine = new ExpressionEngine({ packages: [\n * ...BUILTIN_PACKAGES,\n * defineFunction({\n * name: \"vat\",\n * args: [{ name: \"amount\", type: \"number\" }],\n * returns: \"number\",\n * call: (amount) => amount * 1.2,\n * }),\n * ] });\n * engine.evaluateExpression(\"vat(100)\"); // 120\n * ```\n *\n * The returned package is self-contained and composes with any others through\n * the engine's `packages` array; register several functions by passing several\n * packages. Its name is `solve-fn-<name>`.\n *\n * Scope: arguments are a fixed-length list of `number`/`string`/`boolean`, and\n * `call` is synchronous. Variadic and optional arguments, other value types\n * (units, percentages, dates, matrices), and async work are deliberately out\n * of scope, a function needing any of those keeps using the low-level\n * contract, whose parselets and async resolvers are unchanged.\n *\n * @throws {EngineError} (category CONFIG) if the spec is malformed, at the\n * point `defineFunction` is called, before the package reaches an engine.\n */\nexport function defineFunction<\n const A extends readonly FunctionArg[],\n R extends FunctionValueType,\n>(spec: FunctionSpec<A, R>): IEnginePackage {\n validateSpec(spec as FunctionSpec);\n\n const name = spec.name;\n // Uppercased so the generated type is a valid, collision-resistant token\n // type; the name pattern guarantees it forms one. Distinct from the\n // built-in FUNC type, so this never routes through the builtin name map.\n const tokenType = `DEFINE_FN_${name.toUpperCase()}`;\n\n return {\n name: `solve-fn-${name}`,\n lexerVocabulary: {\n // Lowercased because the lexer lowercases input before lookup, so the\n // call is matched case-insensitively.\n keywords: { [name.toLowerCase()]: tokenType },\n },\n prefixParselets: {\n [tokenType]: new DefinedFunctionParselet(name),\n },\n pluginFunctions: {\n [name]: makeHandler(spec as FunctionSpec),\n },\n };\n}\n","import { ExpressionEngine, type EngineOptions } from \"@solve-js/engine/ExpressionEngine\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\n\n/** Options for {@link createEngine}: the engine options, minus `packages` (the\n * built-in set is always registered), plus `extraPackages` to add your own. */\nexport interface CreateEngineOptions extends Omit<EngineOptions, \"packages\"> {\n\t/** Packages to register ON TOP of the built-in set (e.g. an OSRS or stocks package). */\n\textraPackages?: IEnginePackage[];\n}\n\n/**\n * A batteries-included {@link ExpressionEngine} with every built-in package\n * registered.\n *\n * The constructor registers only the packages it is given, so a consumer's\n * bundler can tree-shake away the built-ins they never use: an engine built\n * with `new ExpressionEngine({ packages: [ARITHMETIC_PACKAGE] })` carries no\n * finance, colour or weather code. This convenience is the opposite trade: it\n * pulls the FULL built-in set (`BUILTIN_PACKAGES`) for the common \"I want\n * everything\" case, so importing it defeats that tree-shaking. Reach for the\n * constructor with an explicit package list when bundle size matters, and for\n * `createEngine` when it does not.\n *\n * @param options - Engine options ({@link EngineOptions}) minus `packages`, plus\n * an optional `extraPackages` to register alongside the built-in set.\n * @returns An engine with the built-in packages (and any extras) registered.\n *\n * @example\n * ```typescript\n * import { createEngine } from \"solve-engine\";\n * const engine = createEngine();\n * const value = engine.evaluateExpression(\"2 + 2 * 10\");\n * console.log(value.toNumber()); // 22\n * ```\n */\nexport function createEngine(options: CreateEngineOptions = {}): ExpressionEngine {\n\tconst { extraPackages = [], ...engineOptions } = options;\n\treturn new ExpressionEngine({\n\t\t...engineOptions,\n\t\tpackages: extraPackages.length > 0 ? [...BUILTIN_PACKAGES, ...extraPackages] : BUILTIN_PACKAGES,\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/api/defineFunction.ts","../src/api/createEngine.ts"],"names":["DefineFunctionErrorCodes","NAME_PATTERN","SUPPORTED_TYPES","plural","count","describeValueType","v","coerceArgument","value","arg","fnName","ErrorFactory","wrapReturn","result","returns","numberValue","stringValue","boolValue","DefinedFunctionParselet","parser","_token","builder","argCount","BindingPower","makeHandler","spec","arity","args","jsArgs","i","validateSpec","defineFunction","name","tokenType","createEngine","options","extraPackages","engineOptions","ExpressionEngine","BUILTIN_PACKAGES"],"mappings":"w9CAkFO,IAAMA,EAA2B,CAEtC,4BAAA,C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AASM,CAAAA,CAGdN,CAAAA,CAA0C,CAC1CK,CAAAA,CAAaL,CAAoB,EAEjC,IAAMO,CAAAA,CAAOP,EAAK,IAAA,CAIZQ,CAAAA,CAAY,CAAA,UAAA,EAAaD,CAAAA,CAAK,aAAa,CAAA,CAAA,CAEjD,OAAO,CACL,IAAA,CAAM,YAAYA,CAAI,CAAA,CAAA,CACtB,eAAA,CAAiB,CAGf,SAAU,CAAE,CAACA,EAAK,WAAA,EAAa,EAAGC,CAAU,CAC9C,EACA,eAAA,CAAiB,CACf,CAACA,CAAS,EAAG,IAAIf,CAAAA,CAAwBc,CAAI,CAC/C,CAAA,CACA,eAAA,CAAiB,CACf,CAACA,CAAI,EAAGR,CAAAA,CAAYC,CAAoB,CAC1C,CACF,CACF,CCrWO,SAASS,EAAaC,CAAAA,CAA+B,GAAsB,CACjF,GAAM,CAAE,aAAA,CAAAC,CAAAA,CAAgB,EAAC,CAAG,GAAGC,CAAc,CAAA,CAAIF,EACjD,OAAO,IAAIG,EAAiB,CAC3B,GAAGD,EACH,QAAA,CAAUD,CAAAA,CAAc,OAAS,CAAA,CAAI,CAAC,GAAGG,CAAAA,CAAkB,GAAGH,CAAa,CAAA,CAAIG,CAChF,CAAC,CACF","file":"index.js","sourcesContent":["import type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport type { PrefixParselet } from \"@solve-js/parser/Parselet\";\nimport type { Parser } from \"@solve-js/parser/Parser\";\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\nimport {\n Value,\n ValueType,\n numberValue,\n stringValue,\n boolValue,\n} from \"@solve-js/vm/Value\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A higher-level, declarative way to contribute a single `name(args)`\n * function, sitting ON TOP OF the package contract rather than replacing it.\n *\n * The low-level contract (allocate a plugin function index, write a parselet,\n * emit `CALL_PLUGIN`) stays exactly as it was and remains the way to add\n * anything that needs custom parsing. This module derives that same wiring\n * from a declaration for the common case, a function called with parenthesised\n * arguments, so adding `vat(x)` costs a spec object rather than an\n * understanding of the parser and the VM. See `defineFunction`.\n */\n\n/** The value types a declared argument or return may take. */\nexport type FunctionValueType = \"number\" | \"string\" | \"boolean\";\n\n/** The JavaScript type a {@link FunctionValueType} maps to at the `call` boundary. */\ntype JsValue<T extends FunctionValueType> = T extends \"number\"\n ? number\n : T extends \"string\"\n ? string\n : boolean;\n\n/** One declared parameter: a name (for error messages) and a value type. */\nexport interface FunctionArg {\n /** Parameter name, used only in the generated type-mismatch messages. */\n name: string;\n /** The value type this parameter accepts. */\n type: FunctionValueType;\n}\n\n/** Map a tuple of {@link FunctionArg} specs to the tuple of JS values `call` receives. */\ntype CallArgs<A extends readonly FunctionArg[]> = {\n [K in keyof A]: JsValue<A[K][\"type\"]>;\n};\n\n/**\n * A declarative function definition.\n *\n * `A` and `R` are inferred from the literal `args`/`returns` (via\n * `defineFunction`'s `const` type parameter), so `call`'s parameters and\n * return are typed from the declaration with no annotations: an\n * `{ type: \"number\" }` argument arrives as a `number`, and a `returns:\n * \"string\"` demands a `string` back.\n */\nexport interface FunctionSpec<\n A extends readonly FunctionArg[] = readonly FunctionArg[],\n R extends FunctionValueType = FunctionValueType,\n> {\n /**\n * The call name, a single identifier (`/^[a-z_][a-z0-9_]*$/i`). Registered\n * as a lexer keyword, so it is matched case-insensitively and cannot collide\n * with a built-in keyword (that collision throws at registration time).\n */\n name: string;\n /** The parameters, in order. A fixed-length list: variadic and optional args are out of scope (see {@link defineFunction}). */\n args: A;\n /** The value type the function returns. */\n returns: R;\n /** The implementation, receiving plain JS values and returning one. Must be synchronous (see {@link defineFunction}). */\n call: (...args: CallArgs<A>) => JsValue<R>;\n}\n\n/**\n * Error codes the declarative function API raises. Kept as a co-located const\n * (the convention `errors/ErrorCode.ts` documents for a domain's own codes) so\n * the strings have one source of truth.\n */\nexport const DefineFunctionErrorCodes = {\n /** The spec's `name` is not a single identifier. Thrown by `defineFunction`, before any engine sees it. */\n DEFINE_FUNCTION_INVALID_NAME: \"DEFINE_FUNCTION_INVALID_NAME\",\n /** The spec is otherwise malformed (bad `args`, unsupported type, missing `call`). Thrown by `defineFunction`. */\n DEFINE_FUNCTION_INVALID_SPEC: \"DEFINE_FUNCTION_INVALID_SPEC\",\n /** The call site passed the wrong number of arguments. Raised at evaluation time. */\n DEFINE_FUNCTION_ARITY_MISMATCH: \"DEFINE_FUNCTION_ARITY_MISMATCH\",\n /** An argument was the wrong value type. Raised at evaluation time. */\n DEFINE_FUNCTION_ARGUMENT_TYPE: \"DEFINE_FUNCTION_ARGUMENT_TYPE\",\n /** The `call` implementation returned a value that did not match `returns`. Raised at evaluation time, an authoring bug rather than a user one. */\n DEFINE_FUNCTION_RETURN_TYPE: \"DEFINE_FUNCTION_RETURN_TYPE\",\n} as const;\n\n/** A single identifier: a letter or underscore, then letters, digits, or underscores. */\nconst NAME_PATTERN = /^[a-z_][a-z0-9_]*$/i;\n\nconst SUPPORTED_TYPES: ReadonlySet<string> = new Set([\"number\", \"string\", \"boolean\"]);\n\n/** \"1 argument\" / \"2 arguments\", so a count reads as English either way. Mirrors `VMBuiltinArity.ts`. */\nfunction plural(count: number): string {\n return count === 1 ? \"1 argument\" : `${count} arguments`;\n}\n\n/**\n * A human noun for the type a Value actually carries, for the \"was given ...\"\n * half of a mismatch message. Covers the three declarable types by their own\n * names and everything else by a readable category, so the message never reads\n * \"given a 6\".\n */\nfunction describeValueType(v: Value): string {\n switch (v.type) {\n case ValueType.Number:\n case ValueType.Hex:\n return \"a number\";\n case ValueType.String:\n return \"a string\";\n case ValueType.Boolean:\n return \"a boolean\";\n case ValueType.BigInt:\n return \"a big integer\";\n case ValueType.Percentage:\n return \"a percentage\";\n case ValueType.Uom:\n return \"a value with a unit\";\n case ValueType.Datetime:\n return \"a date\";\n case ValueType.Matrix:\n return \"a matrix\";\n case ValueType.Range:\n return \"a range\";\n case ValueType.Symbolic:\n return \"a symbolic expression\";\n default:\n return \"an unsupported value\";\n }\n}\n\n/**\n * Read one runtime Value as the JS primitive its declared type promises, or\n * raise the engine's structured type error.\n *\n * A \"number\" accepts a plain number or a based literal (`0xFF`), both of which\n * ARE numbers written differently, and reads it with `toNumber()`. Nothing\n * else is coerced: a percentage, a unit-bearing value or a string is a\n * genuinely different kind of value, and silently reinterpreting it is the\n * class of wrong-answer this API exists to avoid.\n */\nfunction coerceArgument(\n value: Value,\n arg: FunctionArg,\n fnName: string,\n): number | string | boolean {\n switch (arg.type) {\n case \"number\":\n // Hex is a number in another base (see `hexValue`), so it reads as one here.\n if (value.type === ValueType.Number || value.type === ValueType.Hex) {\n return value.toNumber();\n }\n break;\n case \"string\":\n if (value.type === ValueType.String) return value.value as string;\n break;\n case \"boolean\":\n if (value.type === ValueType.Boolean) return value.value as boolean;\n break;\n }\n throw ErrorFactory.execution({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_ARGUMENT_TYPE,\n message: `${fnName}() expects \"${arg.name}\" to be a ${arg.type}, but was given ${describeValueType(value)}`,\n expected: `a ${arg.type}`,\n found: describeValueType(value),\n context: { functionName: fnName, argName: arg.name, expectedType: arg.type },\n });\n}\n\n/**\n * Wrap the `call` result back into a Value of the declared return type, or\n * raise a structured error if the implementation handed back something else.\n *\n * The type check here catches an authoring mistake (a function declared to\n * return a number that returns `undefined`, or a Promise from an accidental\n * `async`), turning it into a named error rather than a Value that lies about\n * its own type downstream.\n */\nfunction wrapReturn(result: unknown, returns: FunctionValueType, fnName: string): Value {\n switch (returns) {\n case \"number\":\n if (typeof result === \"number\") return numberValue(result);\n break;\n case \"string\":\n if (typeof result === \"string\") return stringValue(result);\n break;\n case \"boolean\":\n if (typeof result === \"boolean\") return boolValue(result);\n break;\n }\n throw ErrorFactory.internal({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_RETURN_TYPE,\n message: `${fnName}() is declared to return a ${returns}, but its implementation returned ${typeof result}`,\n expected: `a ${returns}`,\n found: typeof result,\n context: { functionName: fnName, expectedType: returns },\n });\n}\n\n/**\n * The call-syntax parselet generated for one declared function.\n *\n * Identical in shape to the built-in `FunctionCallParselet`: consume the open\n * paren, parse a comma-separated argument list, then emit `CALL_PLUGIN` with\n * the function's index and the argument count. The count is whatever was\n * written, arity is checked at the dispatch point (see {@link makeHandler}),\n * the same place the built-in arity check lives.\n */\nclass DefinedFunctionParselet implements PrefixParselet {\n readonly category = \"Function\";\n\n constructor(\n private readonly fnName: string,\n ) {}\n\n parse(parser: Parser, _token: Token, builder: BytecodeBuilder): void {\n parser.consume(\"LPAREN\");\n\n let argCount = 0;\n if (parser.peek()?.type !== \"RPAREN\") {\n parser.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (parser.match(\"COMMA\")) {\n parser.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n\n parser.consume(\"RPAREN\");\n\n builder.emitPluginCall(this.fnName, argCount);\n }\n}\n\n/**\n * Build the plugin function that checks arity and argument types, calls the\n * host implementation, and wraps the result.\n *\n * The VM has already screened out faulted arguments (an errored or still\n * pending operand short-circuits before the handler runs, see\n * `VM.ts`'s `CALL_PLUGIN` case), so every Value reaching here carries a real\n * result. Arity is checked first, before any argument is read, so a wrong\n * count is reported as a wrong count rather than as a type error on a missing\n * argument.\n */\nfunction makeHandler(spec: FunctionSpec): (args: Value[]) => Value {\n const arity = spec.args.length;\n return (args: Value[]): Value => {\n if (args.length !== arity) {\n throw ErrorFactory.execution({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_ARITY_MISMATCH,\n message: `${spec.name}() takes ${plural(arity)}, but was given ${args.length === 0 ? \"none\" : plural(args.length)}`,\n expected: plural(arity),\n found: args.length === 0 ? \"none\" : plural(args.length),\n context: { functionName: spec.name, expected: arity, actual: args.length },\n });\n }\n\n const jsArgs: (number | string | boolean)[] = new Array(arity);\n for (let i = 0; i < arity; i++) {\n jsArgs[i] = coerceArgument(args[i], spec.args[i], spec.name);\n }\n\n const result = (spec.call as (...a: (number | string | boolean)[]) => unknown)(...jsArgs);\n return wrapReturn(result, spec.returns, spec.name);\n };\n}\n\n/** Reject a spec that could not produce a working function, before any engine sees it. */\nfunction validateSpec(spec: FunctionSpec): void {\n if (typeof spec?.name !== \"string\" || !NAME_PATTERN.test(spec.name)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_NAME,\n message: `defineFunction: name must be a single identifier, got ${JSON.stringify(spec?.name)}`,\n suggestion: 'e.g. \"vat\" or \"net_price\"',\n context: { name: spec?.name },\n });\n }\n if (!Array.isArray(spec.args)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" args must be an array`,\n context: { name: spec.name },\n });\n }\n for (const arg of spec.args) {\n if (typeof arg?.name !== \"string\" || arg.name.length === 0) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" has an argument with no name`,\n context: { name: spec.name },\n });\n }\n if (!SUPPORTED_TYPES.has(arg.type)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" argument \"${arg.name}\" has unsupported type ${JSON.stringify(arg.type)}`,\n suggestion: \"supported argument types are number, string, boolean\",\n context: { name: spec.name, argName: arg.name, type: arg.type },\n });\n }\n }\n if (!SUPPORTED_TYPES.has(spec.returns)) {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" has unsupported return type ${JSON.stringify(spec.returns)}`,\n suggestion: \"supported return types are number, string, boolean\",\n context: { name: spec.name, returns: spec.returns },\n });\n }\n if (typeof spec.call !== \"function\") {\n throw ErrorFactory.config({\n code: DefineFunctionErrorCodes.DEFINE_FUNCTION_INVALID_SPEC,\n message: `defineFunction: \"${spec.name}\" is missing a call implementation`,\n context: { name: spec.name },\n });\n }\n}\n\n/**\n * Turn a declarative {@link FunctionSpec} into a ready-to-register\n * {@link IEnginePackage}.\n *\n * This is the higher-level API from issue #102. It derives, from the\n * declaration alone, everything the low-level contract asks an author to write\n * by hand: a named plugin function (the engine assigns its `CALL_PLUGIN`\n * index), a lexer keyword so the name tokenises, a call-syntax parselet emitting\n * that call by name, and a handler that checks arity and argument types (yielding\n * the engine's own structured errors) before invoking `call` and wrapping its\n * result. Anything needing custom parsing keeps writing a raw parselet exactly\n * as before, this sits on top of that contract and does not change it.\n *\n * @example\n * ```ts\n * const engine = new ExpressionEngine({ packages: [\n * ...BUILTIN_PACKAGES,\n * defineFunction({\n * name: \"vat\",\n * args: [{ name: \"amount\", type: \"number\" }],\n * returns: \"number\",\n * call: (amount) => amount * 1.2,\n * }),\n * ] });\n * engine.evaluateExpression(\"vat(100)\"); // 120\n * ```\n *\n * The returned package is self-contained and composes with any others through\n * the engine's `packages` array; register several functions by passing several\n * packages. Its name is `solve-fn-<name>`.\n *\n * Scope: arguments are a fixed-length list of `number`/`string`/`boolean`, and\n * `call` is synchronous. Variadic and optional arguments, other value types\n * (units, percentages, dates, matrices), and async work are deliberately out\n * of scope, a function needing any of those keeps using the low-level\n * contract, whose parselets and async resolvers are unchanged.\n *\n * @throws {EngineError} (category CONFIG) if the spec is malformed, at the\n * point `defineFunction` is called, before the package reaches an engine.\n */\nexport function defineFunction<\n const A extends readonly FunctionArg[],\n R extends FunctionValueType,\n>(spec: FunctionSpec<A, R>): IEnginePackage {\n validateSpec(spec as FunctionSpec);\n\n const name = spec.name;\n // Uppercased so the generated type is a valid, collision-resistant token\n // type; the name pattern guarantees it forms one. Distinct from the\n // built-in FUNC type, so this never routes through the builtin name map.\n const tokenType = `DEFINE_FN_${name.toUpperCase()}`;\n\n return {\n name: `solve-fn-${name}`,\n lexerVocabulary: {\n // Lowercased because the lexer lowercases input before lookup, so the\n // call is matched case-insensitively.\n keywords: { [name.toLowerCase()]: tokenType },\n },\n prefixParselets: {\n [tokenType]: new DefinedFunctionParselet(name),\n },\n pluginFunctions: {\n [name]: makeHandler(spec as FunctionSpec),\n },\n };\n}\n","import { ExpressionEngine, type EngineOptions } from \"@solve-js/engine/ExpressionEngine\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\n\n/** Options for {@link createEngine}: the engine options, minus `packages` (the\n * built-in set is always registered), plus `extraPackages` to add your own. */\nexport interface CreateEngineOptions extends Omit<EngineOptions, \"packages\"> {\n\t/** Packages to register ON TOP of the built-in set (e.g. an OSRS or stocks package). */\n\textraPackages?: IEnginePackage[];\n}\n\n/**\n * A batteries-included {@link ExpressionEngine} with every built-in package\n * registered.\n *\n * The constructor registers only the packages it is given, so a consumer's\n * bundler can tree-shake away the built-ins they never use: an engine built\n * with `new ExpressionEngine({ packages: [ARITHMETIC_PACKAGE] })` carries no\n * finance, colour or weather code. This convenience is the opposite trade: it\n * pulls the FULL built-in set (`BUILTIN_PACKAGES`) for the common \"I want\n * everything\" case, so importing it defeats that tree-shaking. Reach for the\n * constructor with an explicit package list when bundle size matters, and for\n * `createEngine` when it does not.\n *\n * @param options - Engine options ({@link EngineOptions}) minus `packages`, plus\n * an optional `extraPackages` to register alongside the built-in set.\n * @returns An engine with the built-in packages (and any extras) registered.\n *\n * @example\n * ```typescript\n * import { createEngine } from \"solve-engine\";\n * const engine = createEngine();\n * const value = engine.evaluateExpression(\"2 + 2 * 10\");\n * console.log(value.toNumber()); // 22\n * ```\n */\nexport function createEngine(options: CreateEngineOptions = {}): ExpressionEngine {\n\tconst { extraPackages = [], ...engineOptions } = options;\n\treturn new ExpressionEngine({\n\t\t...engineOptions,\n\t\tpackages: extraPackages.length > 0 ? [...BUILTIN_PACKAGES, ...extraPackages] : BUILTIN_PACKAGES,\n\t});\n}\n"]}
|
package/dist/testing.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkJPT6L7BG_cjs=require('./chunk-JPT6L7BG.cjs');require('./chunk-Q7TBBV62.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-ZVPZQ66D.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-GWV273KZ.cjs'),require('./chunk-HG4NPDN5.cjs'),require('./chunk-P43SV4NJ.cjs'),require('./chunk-R2SZFJTT.cjs');var chunkW7NN77PH_cjs=require('./chunk-W7NN77PH.cjs');require('./chunk-A755LVPT.cjs'),require('./chunk-WQGHJAW2.cjs'),require('./chunk-5AKT36UK.cjs'),require('./chunk-4DR5RBHQ.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-RAFOQ4T5.cjs'),require('./chunk-CM2WM5CM.cjs'),require('./chunk-DUFEONVN.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5TVI2UPZ.cjs'),require('./chunk-YWF6C2IO.cjs'),require('./chunk-A764BY7L.cjs'),require('./chunk-E4HAKNBQ.cjs');var chunkOM7NOHJF_cjs=require('./chunk-OM7NOHJF.cjs');require('./chunk-ZKFCKAIX.cjs');var chunkUHS4HMOQ_cjs=require('./chunk-UHS4HMOQ.cjs');require('./chunk-AGCNMEP2.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-WU7SBKVU.cjs'),require('./chunk-YBQOQTVL.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs');var chunkSUAGBRQ7_cjs=require('./chunk-SUAGBRQ7.cjs');var i=class o extends Error{constructor(t){super(t.message),this.name="ExpectationError",this.code=t.code,this.expected=t.expected,this.actual=t.actual,Object.setPrototypeOf(this,o.prototype);}};function V(o=[],t={}){let{locale:e="en",includeBuiltins:r=true}=t,s=new chunkJPT6L7BG_cjs.o({locale:e,packages:r?chunkW7NN77PH_cjs.z:[]});for(let a of o)s.registerPackage(a);return s}function v(o,t){try{let e=o.evaluateExpression(t);return e.isError()?{status:"error",code:e.errorCode??"",message:e.errorMessage??"",source:e}:e.isPending()?{status:"pending",value:e}:{status:"value",value:e}}catch(e){if(e instanceof chunkSUAGBRQ7_cjs.b)return {status:"error",code:e.code,message:e.message,source:e};let r=e instanceof Error?e.message:String(e);return {status:"error",code:"UNKNOWN_ERROR",message:r,source:new chunkOM7NOHJF_cjs.m(13,"UNKNOWN_ERROR",r)}}}function x(o,t){if(Object.is(o,t))return true;if(!Number.isFinite(o)||!Number.isFinite(t))return false;let e=1e-9*Math.max(1,Math.abs(o),Math.abs(t));return Math.abs(o-t)<=e}function l(o){return o.type===3?JSON.stringify(o.value):o.type===6&&typeof o.unit=="string"?`${String(o.value)} ${o.unit}`:String(o.value)}function n(o){switch(o.status){case "value":return l(o.value);case "pending":return "a pending async value";case "error":return `an error (${o.code}: ${o.message})`}}var d=class{constructor(t,e){this.expression=t;this.outcome=e;}get value(){if(this.outcome.status==="error")throw new i({code:"EXPECTED_VALUE",message:`Expected "${this.expression}" to evaluate, but it failed with ${n(this.outcome)}.`,expected:"a resolved value",actual:n(this.outcome)});return this.outcome.value}toEvaluate(){if(this.outcome.status!=="value")throw new i({code:"EXPECTED_EVALUATE",message:`Expected "${this.expression}" to evaluate to a value, but got ${n(this.outcome)}.`,expected:"a resolved value",actual:n(this.outcome)});return this}toEqual(t,e){if(this.outcome.status!=="value")throw new i({code:"EXPECTED_EQUAL",message:`Expected "${this.expression}" to equal ${c(t,e)}, but got ${n(this.outcome)}.`,expected:c(t,e),actual:n(this.outcome)});let r=this.outcome.value,s;if(typeof t=="number"?s=x(r.toNumber(),t):typeof t=="boolean"?s=r.type===10&&r.value===t:s=C(r)===t,!s)throw new i({code:"EXPECTED_EQUAL",message:`Expected "${this.expression}" to equal ${c(t,e)}, but it was ${l(r)}.`,expected:c(t,e),actual:l(r)});if(e!==void 0&&r.unit!==e)throw new i({code:"EXPECTED_UNIT",message:`Expected "${this.expression}" to carry the unit "${e}", but it was ${r.unit===void 0?"unitless":`"${r.unit}"`}.`,expected:`unit "${e}"`,actual:r.unit===void 0?"no unit":`unit "${r.unit}"`});return this}toBeError(){if(this.outcome.status!=="error")throw new i({code:"EXPECTED_ERROR",message:`Expected "${this.expression}" to fail, but it produced ${n(this.outcome)}.`,expected:"an error",actual:n(this.outcome)});return this}toFailWith(t){if(this.outcome.status!=="error")throw new i({code:"EXPECTED_FAIL_WITH",message:`Expected "${this.expression}" to fail with "${t}", but it produced ${n(this.outcome)}.`,expected:`error code "${t}"`,actual:n(this.outcome)});if(this.outcome.code!==t)throw new i({code:"EXPECTED_FAIL_WITH",message:`Expected "${this.expression}" to fail with "${t}", but it failed with "${this.outcome.code}" (${this.outcome.message}).`,expected:`error code "${t}"`,actual:`error code "${this.outcome.code}"`});return this}toBePending(){if(this.outcome.status!=="pending")throw new i({code:"EXPECTED_PENDING",message:`Expected "${this.expression}" to be pending, but got ${n(this.outcome)}.`,expected:"a pending async value",actual:n(this.outcome)});return this}};function c(o,t){let e=typeof o=="string"?JSON.stringify(o):String(o);return t===void 0?e:`${e} ${t}`}function C(o){return String(o.value)}function D(o,t){return new d(t,v(o,t))}var O=["a","an","and","or","but","if","then","the","this","that","these","those","in","on","at","to","of","for","from","with","by","as","per","into","over","is","are","was","were","be","been","being","do","does","did","have","has","had","will","would","can","could","should","may","might","must","price","cost","value","total","sum","count","rate","amount","number","time","date","day","week","month","year","hour","minute","second","add","buy","sell","hold","make","take","give","get","set","run","up","down","out","off","all","some","any","no","not","more","less","one","two","three","first","last","next","each","every","here","there"],$=["error","warning","info"];function k(o){let t=[],e=o.lexerVocabulary;if(e?.keywords)for(let[r,s]of Object.entries(e.keywords))t.push({word:r,via:"keyword",tokenType:s});if(e?.units)for(let r of e.units)t.push({word:r,via:"unit"});if(e?.operators)for(let[r,s]of Object.entries(e.operators))t.push({word:r,via:"operator",tokenType:s});if(o.phrases)for(let[r,s]of Object.entries(o.phrases))r.includes(" ")||t.push({word:r,via:"phrase",tokenType:s});return t}var p=class{constructor(t){this.pkg=t;}notToShadow(t=O){let e=new Set(t.map(s=>s.toLowerCase())),r=k(this.pkg).filter(s=>e.has(s.word.toLowerCase()));if(r.length>0){let s=r.map(a=>`"${a.word}" (${a.via})`).join(", ");throw new i({code:"PACKAGE_SHADOWS_PROSE",message:`Package "${this.pkg.name}" claims prose word(s) as syntax: ${s}. A word that is also ordinary English turns prose into arithmetic; prefer a multi-word phrase or a form that requires a parenthesis.`,expected:"no prose words claimed as syntax",actual:s})}return r}notToCollideWith(t,e="error"){let r=chunkJPT6L7BG_cjs.a(this.pkg,t),s=$.indexOf(e),a=r.conflicts.filter(u=>$.indexOf(u.severity)<=s);if(a.length>0){let u=a.map(g=>`[${g.severity}] ${g.detail}`).join(`
|
|
2
2
|
`);throw new i({code:"PACKAGE_VOCABULARY_COLLISION",message:`Package "${this.pkg.name}" collides with another package:
|
|
3
|
-
${u}`,expected:`no conflicts at or above "${e}" severity`,actual:`${a.length} conflict(s)`})}return r}toDeclareCompatibleEngineVersion(t=
|
|
3
|
+
${u}`,expected:`no conflicts at or above "${e}" severity`,actual:`${a.length} conflict(s)`})}return r}toDeclareCompatibleEngineVersion(t=chunkUHS4HMOQ_cjs.a){let e=chunkJPT6L7BG_cjs.b(this.pkg,t);if(!e.compatible){let r=e.reason==="invalid-range"?`its range "${e.declaredRange}" is not valid semver`:`its range "${e.declaredRange}" is not satisfied by engine version "${e.engineVersion}"`;throw new i({code:"PACKAGE_ENGINE_VERSION_INCOMPATIBLE",message:`Package "${this.pkg.name}" declares an engineVersion that will be rejected at registration: ${r}.`,expected:`an engineVersion satisfied by "${t}"`,actual:`"${e.declaredRange}"`})}return this}};function L(o){return new p(o)}exports.COMMON_PROSE_WORDS=O;exports.ExpectationError=i;exports.ExpressionAssertion=d;exports.PackageAssertion=p;exports.createTestEngine=V;exports.expectExpression=D;exports.expectPackage=L;//# sourceMappingURL=testing.cjs.map
|
|
4
4
|
//# sourceMappingURL=testing.cjs.map
|
package/dist/testing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {o,a,b}from'./chunk-VYB44JLS.js';import'./chunk-CB3EXUM2.js';import'./chunk-2RWAXT6O.js';import'./chunk-IJHL3LMH.js';import'./chunk-MIQBJGGR.js';import'./chunk-2PGGPFF3.js';import'./chunk-JP4JMQOG.js';import'./chunk-IQVSCL2R.js';import'./chunk-XEIDV5JP.js';import {z}from'./chunk-V7LXOTCU.js';import'./chunk-SFM4XFGJ.js';import'./chunk-FXB5GCBT.js';import'./chunk-VLX7ZVK4.js';import'./chunk-B2NL65FI.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-YN5H54GM.js';import'./chunk-3ZGFAE3Q.js';import'./chunk-PTXUWGRR.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-KH4QXKLT.js';import'./chunk-NQFCXLEF.js';import'./chunk-J4K72CQN.js';import {m}from'./chunk-X5K72MBV.js';import'./chunk-4CNYGIND.js';import {a as a$1}from'./chunk-64OGL465.js';import'./chunk-CDE2ZUGG.js';import'./chunk-JPFCXLJV.js';import'./chunk-LP3JYC3A.js';import'./chunk-FAO6DQ74.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import {b as b$1}from'./chunk-RELMEWY6.js';var i=class o extends Error{constructor(t){super(t.message),this.name="ExpectationError",this.code=t.code,this.expected=t.expected,this.actual=t.actual,Object.setPrototypeOf(this,o.prototype);}};function V(o$1=[],t={}){let{locale:e="en",includeBuiltins:r=true}=t,s=new o({locale:e,packages:r?z:[]});for(let a of o$1)s.registerPackage(a);return s}function v(o,t){try{let e=o.evaluateExpression(t);return e.isError()?{status:"error",code:e.errorCode??"",message:e.errorMessage??"",source:e}:e.isPending()?{status:"pending",value:e}:{status:"value",value:e}}catch(e){if(e instanceof b$1)return {status:"error",code:e.code,message:e.message,source:e};let r=e instanceof Error?e.message:String(e);return {status:"error",code:"UNKNOWN_ERROR",message:r,source:new m(13,"UNKNOWN_ERROR",r)}}}function x(o,t){if(Object.is(o,t))return true;if(!Number.isFinite(o)||!Number.isFinite(t))return false;let e=1e-9*Math.max(1,Math.abs(o),Math.abs(t));return Math.abs(o-t)<=e}function l(o){return o.type===3?JSON.stringify(o.value):o.type===6&&typeof o.unit=="string"?`${String(o.value)} ${o.unit}`:String(o.value)}function n(o){switch(o.status){case "value":return l(o.value);case "pending":return "a pending async value";case "error":return `an error (${o.code}: ${o.message})`}}var d=class{constructor(t,e){this.expression=t;this.outcome=e;}get value(){if(this.outcome.status==="error")throw new i({code:"EXPECTED_VALUE",message:`Expected "${this.expression}" to evaluate, but it failed with ${n(this.outcome)}.`,expected:"a resolved value",actual:n(this.outcome)});return this.outcome.value}toEvaluate(){if(this.outcome.status!=="value")throw new i({code:"EXPECTED_EVALUATE",message:`Expected "${this.expression}" to evaluate to a value, but got ${n(this.outcome)}.`,expected:"a resolved value",actual:n(this.outcome)});return this}toEqual(t,e){if(this.outcome.status!=="value")throw new i({code:"EXPECTED_EQUAL",message:`Expected "${this.expression}" to equal ${c(t,e)}, but got ${n(this.outcome)}.`,expected:c(t,e),actual:n(this.outcome)});let r=this.outcome.value,s;if(typeof t=="number"?s=x(r.toNumber(),t):typeof t=="boolean"?s=r.type===10&&r.value===t:s=C(r)===t,!s)throw new i({code:"EXPECTED_EQUAL",message:`Expected "${this.expression}" to equal ${c(t,e)}, but it was ${l(r)}.`,expected:c(t,e),actual:l(r)});if(e!==void 0&&r.unit!==e)throw new i({code:"EXPECTED_UNIT",message:`Expected "${this.expression}" to carry the unit "${e}", but it was ${r.unit===void 0?"unitless":`"${r.unit}"`}.`,expected:`unit "${e}"`,actual:r.unit===void 0?"no unit":`unit "${r.unit}"`});return this}toBeError(){if(this.outcome.status!=="error")throw new i({code:"EXPECTED_ERROR",message:`Expected "${this.expression}" to fail, but it produced ${n(this.outcome)}.`,expected:"an error",actual:n(this.outcome)});return this}toFailWith(t){if(this.outcome.status!=="error")throw new i({code:"EXPECTED_FAIL_WITH",message:`Expected "${this.expression}" to fail with "${t}", but it produced ${n(this.outcome)}.`,expected:`error code "${t}"`,actual:n(this.outcome)});if(this.outcome.code!==t)throw new i({code:"EXPECTED_FAIL_WITH",message:`Expected "${this.expression}" to fail with "${t}", but it failed with "${this.outcome.code}" (${this.outcome.message}).`,expected:`error code "${t}"`,actual:`error code "${this.outcome.code}"`});return this}toBePending(){if(this.outcome.status!=="pending")throw new i({code:"EXPECTED_PENDING",message:`Expected "${this.expression}" to be pending, but got ${n(this.outcome)}.`,expected:"a pending async value",actual:n(this.outcome)});return this}};function c(o,t){let e=typeof o=="string"?JSON.stringify(o):String(o);return t===void 0?e:`${e} ${t}`}function C(o){return String(o.value)}function D(o,t){return new d(t,v(o,t))}var O=["a","an","and","or","but","if","then","the","this","that","these","those","in","on","at","to","of","for","from","with","by","as","per","into","over","is","are","was","were","be","been","being","do","does","did","have","has","had","will","would","can","could","should","may","might","must","price","cost","value","total","sum","count","rate","amount","number","time","date","day","week","month","year","hour","minute","second","add","buy","sell","hold","make","take","give","get","set","run","up","down","out","off","all","some","any","no","not","more","less","one","two","three","first","last","next","each","every","here","there"],$=["error","warning","info"];function k(o){let t=[],e=o.lexerVocabulary;if(e?.keywords)for(let[r,s]of Object.entries(e.keywords))t.push({word:r,via:"keyword",tokenType:s});if(e?.units)for(let r of e.units)t.push({word:r,via:"unit"});if(e?.operators)for(let[r,s]of Object.entries(e.operators))t.push({word:r,via:"operator",tokenType:s});if(o.phrases)for(let[r,s]of Object.entries(o.phrases))r.includes(" ")||t.push({word:r,via:"phrase",tokenType:s});return t}var p=class{constructor(t){this.pkg=t;}notToShadow(t=O){let e=new Set(t.map(s=>s.toLowerCase())),r=k(this.pkg).filter(s=>e.has(s.word.toLowerCase()));if(r.length>0){let s=r.map(a=>`"${a.word}" (${a.via})`).join(", ");throw new i({code:"PACKAGE_SHADOWS_PROSE",message:`Package "${this.pkg.name}" claims prose word(s) as syntax: ${s}. A word that is also ordinary English turns prose into arithmetic; prefer a multi-word phrase or a form that requires a parenthesis.`,expected:"no prose words claimed as syntax",actual:s})}return r}notToCollideWith(t,e="error"){let r=a(this.pkg,t),s=$.indexOf(e),a$1=r.conflicts.filter(u=>$.indexOf(u.severity)<=s);if(a$1.length>0){let u=a$1.map(g=>`[${g.severity}] ${g.detail}`).join(`
|
|
2
2
|
`);throw new i({code:"PACKAGE_VOCABULARY_COLLISION",message:`Package "${this.pkg.name}" collides with another package:
|
|
3
3
|
${u}`,expected:`no conflicts at or above "${e}" severity`,actual:`${a$1.length} conflict(s)`})}return r}toDeclareCompatibleEngineVersion(t=a$1){let e=b(this.pkg,t);if(!e.compatible){let r=e.reason==="invalid-range"?`its range "${e.declaredRange}" is not valid semver`:`its range "${e.declaredRange}" is not satisfied by engine version "${e.engineVersion}"`;throw new i({code:"PACKAGE_ENGINE_VERSION_INCOMPATIBLE",message:`Package "${this.pkg.name}" declares an engineVersion that will be rejected at registration: ${r}.`,expected:`an engineVersion satisfied by "${t}"`,actual:`"${e.declaredRange}"`})}return this}};function L(o){return new p(o)}export{O as COMMON_PROSE_WORDS,i as ExpectationError,d as ExpressionAssertion,p as PackageAssertion,V as createTestEngine,D as expectExpression,L as expectPackage};//# sourceMappingURL=testing.js.map
|
|
4
4
|
//# sourceMappingURL=testing.js.map
|