solve-engine 2.38.13 → 2.38.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PackageCompatibility-Cu_bHpwY.d.cts → PackageCompatibility-C-3vPMKp.d.cts} +1 -1
- package/dist/{PackageCompatibility-BILTZSHP.d.ts → PackageCompatibility-zdsKvwQI.d.ts} +1 -1
- package/dist/{PackageRegistry-DMKDsYiA.d.ts → PackageRegistry-CStmqgw_.d.ts} +36 -1
- package/dist/{PackageRegistry-wZgm2zzk.d.cts → PackageRegistry-DiHxyxrn.d.cts} +36 -1
- package/dist/{VMBuiltins-D3rXBm2k.d.cts → VMBuiltins-BwqFO2TY.d.cts} +215 -1
- package/dist/{VMBuiltins-Dd0KZR4G.d.ts → VMBuiltins-h09nijID.d.ts} +215 -1
- package/dist/chunk-44BWHZ5V.js +2 -0
- package/dist/chunk-44BWHZ5V.js.map +1 -0
- package/dist/chunk-6UW4JJZV.cjs +3 -0
- package/dist/chunk-6UW4JJZV.cjs.map +1 -0
- package/dist/{chunk-CW623SJ7.cjs → chunk-A3CNNRFM.cjs} +2 -2
- package/dist/{chunk-CW623SJ7.cjs.map → chunk-A3CNNRFM.cjs.map} +1 -1
- package/dist/{chunk-PN6S4SW3.js → chunk-BIV4K7B2.js} +2 -2
- package/dist/{chunk-PN6S4SW3.js.map → chunk-BIV4K7B2.js.map} +1 -1
- package/dist/chunk-ENLFOXF3.js +5 -0
- package/dist/chunk-ENLFOXF3.js.map +1 -0
- package/dist/chunk-HFES6BF5.cjs +2 -0
- package/dist/chunk-HFES6BF5.cjs.map +1 -0
- package/dist/chunk-ZGA7X625.cjs +5 -0
- package/dist/chunk-ZGA7X625.cjs.map +1 -0
- package/dist/chunk-ZYXFJ4X2.js +3 -0
- package/dist/chunk-ZYXFJ4X2.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 +4 -4
- package/dist/engine.d.ts +4 -4
- package/dist/engine.js +1 -1
- package/dist/engine.worker.cjs +1 -1
- package/dist/engine.worker.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/language.d.cts +3 -3
- package/dist/language.d.ts +3 -3
- package/dist/packages.d.cts +2 -2
- package/dist/packages.d.ts +2 -2
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.cjs.map +1 -1
- package/dist/vm.d.cts +1 -2
- package/dist/vm.d.ts +1 -2
- package/dist/vm.js +1 -1
- package/dist/vm.js.map +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.d.cts +2 -2
- package/dist/worker.d.ts +2 -2
- package/dist/worker.js +1 -1
- package/package.json +1 -1
- package/dist/VMCheckpoints-BXavssWa.d.ts +0 -176
- package/dist/VMCheckpoints-BwLCnV8C.d.cts +0 -176
- package/dist/chunk-3X2DR2QH.js +0 -5
- package/dist/chunk-3X2DR2QH.js.map +0 -1
- package/dist/chunk-QCH4JXSZ.cjs +0 -5
- package/dist/chunk-QCH4JXSZ.cjs.map +0 -1
- package/dist/chunk-SWONJJK3.js +0 -3
- package/dist/chunk-SWONJJK3.js.map +0 -1
- package/dist/chunk-WLY2OSWU.cjs +0 -3
- package/dist/chunk-WLY2OSWU.cjs.map +0 -1
package/dist/testing.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { I as IEnginePackage, E as ExpressionEngine } from './PackageRegistry-
|
|
1
|
+
import { I as IEnginePackage, E as ExpressionEngine } from './PackageRegistry-CStmqgw_.js';
|
|
2
2
|
import { V as Value } from './Value-B55Hvn3e.js';
|
|
3
3
|
import { E as EngineError } from './EngineError-Bm4OYmw8.js';
|
|
4
|
-
import { C as CompatibilityReport } from './PackageCompatibility-
|
|
4
|
+
import { C as CompatibilityReport } from './PackageCompatibility-zdsKvwQI.js';
|
|
5
5
|
import './Parselet-Br1tHash.js';
|
|
6
6
|
import './BytecodeBuilder-DSWKZi4f.js';
|
|
7
7
|
import './Token-D8f7yaz1.js';
|
|
@@ -11,7 +11,7 @@ import './Lexer-DPn5dfCH.js';
|
|
|
11
11
|
import './resolvers.js';
|
|
12
12
|
import '@tanstack/query-core';
|
|
13
13
|
import './TokenNormalizer-DAzPp-j1.js';
|
|
14
|
-
import './VMBuiltins-
|
|
14
|
+
import './VMBuiltins-h09nijID.js';
|
|
15
15
|
import './Configuration-BxriK9Kw.js';
|
|
16
16
|
|
|
17
17
|
/**
|
package/dist/testing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {o,a,b}from'./chunk-
|
|
1
|
+
import {o,a,b}from'./chunk-ENLFOXF3.js';import'./chunk-RU3KGJRA.js';import'./chunk-2RWAXT6O.js';import'./chunk-RMDCGYZM.js';import'./chunk-MIQBJGGR.js';import'./chunk-ZXNM355C.js';import'./chunk-JP4JMQOG.js';import'./chunk-SSS3ZMKX.js';import'./chunk-HLZRNZEU.js';import {z}from'./chunk-4LMPCB2V.js';import'./chunk-AWGSR2GZ.js';import'./chunk-IUCUBHFW.js';import'./chunk-U5MESNRT.js';import'./chunk-DB5ISONG.js';import'./chunk-76F3LCIL.js';import'./chunk-EOKHRS2T.js';import'./chunk-TCZSPH4A.js';import'./chunk-AFNK2LUO.js';import'./chunk-X2GQAKL2.js';import'./chunk-PICFFFJV.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-5TCSFTZD.js';import'./chunk-IHPYXJIY.js';import'./chunk-EOO6M65F.js';import'./chunk-J4K72CQN.js';import {m}from'./chunk-A34R65WT.js';import'./chunk-BWTVJD5L.js';import {a as a$1}from'./chunk-BIV4K7B2.js';import'./chunk-6NL7RBAG.js';import'./chunk-JPFCXLJV.js';import'./chunk-APYRNAU2.js';import'./chunk-FAO6DQ74.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import {b as b$1}from'./chunk-6G2NES2I.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
|
package/dist/vm.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkDTOSRC6E_cjs=require('./chunk-DTOSRC6E.cjs');require('./chunk-HG4NPDN5.cjs');var chunk6ADFAXTZ_cjs=require('./chunk-6ADFAXTZ.cjs');require('./chunk-OBZJKZ2F.cjs'),require('./chunk-SF5QVUEI.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5N4XDULO.cjs'),require('./chunk-EQNKDTMX.cjs'),require('./chunk-E4HAKNBQ.cjs');var chunkNH74IT7B_cjs=require('./chunk-NH74IT7B.cjs');require('./chunk-PHWIO4P3.cjs'),require('./chunk-EZKR44MA.cjs'),require('./chunk-6SYU4MH7.cjs');
|
|
1
|
+
'use strict';var chunkHFES6BF5_cjs=require('./chunk-HFES6BF5.cjs'),chunkDTOSRC6E_cjs=require('./chunk-DTOSRC6E.cjs');require('./chunk-HG4NPDN5.cjs');var chunk6ADFAXTZ_cjs=require('./chunk-6ADFAXTZ.cjs');require('./chunk-OBZJKZ2F.cjs'),require('./chunk-SF5QVUEI.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs'),require('./chunk-5N4XDULO.cjs'),require('./chunk-EQNKDTMX.cjs'),require('./chunk-E4HAKNBQ.cjs');var chunkNH74IT7B_cjs=require('./chunk-NH74IT7B.cjs');require('./chunk-PHWIO4P3.cjs'),require('./chunk-EZKR44MA.cjs'),require('./chunk-6SYU4MH7.cjs');Object.defineProperty(exports,"VMCheckpointer",{enumerable:true,get:function(){return chunkHFES6BF5_cjs.a}});Object.defineProperty(exports,"ScopeManager",{enumerable:true,get:function(){return chunkDTOSRC6E_cjs.a}});Object.defineProperty(exports,"createVM",{enumerable:true,get:function(){return chunkDTOSRC6E_cjs.b}});Object.defineProperty(exports,"executeBytecode",{enumerable:true,get:function(){return chunkDTOSRC6E_cjs.c}});Object.defineProperty(exports,"DependencyGraph",{enumerable:true,get:function(){return chunk6ADFAXTZ_cjs.b}});Object.defineProperty(exports,"OpRegistry",{enumerable:true,get:function(){return chunk6ADFAXTZ_cjs.y}});Object.defineProperty(exports,"allocatePluginFunctionIndex",{enumerable:true,get:function(){return chunk6ADFAXTZ_cjs.H}});Object.defineProperty(exports,"binaryOp",{enumerable:true,get:function(){return chunk6ADFAXTZ_cjs.x}});Object.defineProperty(exports,"builtinFunctions",{enumerable:true,get:function(){return chunk6ADFAXTZ_cjs.F}});Object.defineProperty(exports,"pluginFunctionIndexFor",{enumerable:true,get:function(){return chunk6ADFAXTZ_cjs.I}});Object.defineProperty(exports,"pluginFunctionRegistry",{enumerable:true,get:function(){return chunk6ADFAXTZ_cjs.G}});Object.defineProperty(exports,"sharedOpRegistry",{enumerable:true,get:function(){return chunk6ADFAXTZ_cjs.z}});Object.defineProperty(exports,"unifyUom",{enumerable:true,get:function(){return chunk6ADFAXTZ_cjs.l}});Object.defineProperty(exports,"Value",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.m}});Object.defineProperty(exports,"ValueType",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.g}});Object.defineProperty(exports,"bigIntValue",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.s}});Object.defineProperty(exports,"chargeAllocation",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.c}});Object.defineProperty(exports,"checkAllocation",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.d}});Object.defineProperty(exports,"checkedArray",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.e}});Object.defineProperty(exports,"colVectorValue",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.E}});Object.defineProperty(exports,"hexValue",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.r}});Object.defineProperty(exports,"matrixValue",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.C}});Object.defineProperty(exports,"numberValue",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.n}});Object.defineProperty(exports,"rangeValue",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.F}});Object.defineProperty(exports,"rowVectorValue",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.D}});Object.defineProperty(exports,"stringValue",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.t}});Object.defineProperty(exports,"uomValue",{enumerable:true,get:function(){return chunkNH74IT7B_cjs.u}});//# sourceMappingURL=vm.cjs.map
|
|
2
2
|
//# sourceMappingURL=vm.cjs.map
|
package/dist/vm.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","keep","parent","variables","functions","name","fn","val","checkpoint","target","chain","current","cp","key","result","scope"],"mappings":"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","file":"vm.cjs","sourcesContent":["import { Value } from \"@solve-js/vm/Value\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\nimport type { UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\n\n// ── VMCheckpoint ────────────────────────────────────────────────────────\n\n/**\n * A point-in-time snapshot of VM variable state.\n *\n * Uses **prototypal inheritance** for memory efficiency: each checkpoint's\n * `variables` object has its parent checkpoint's `variables` as its\n * `__proto__`. This means a `getVar(\"x\")` lookup walks the prototype chain\n * until it finds `x`, and only variables that CHANGED at this checkpoint\n * consume heap space. Unchanged variables are inherited from the parent.\n *\n * ```text\n * Checkpoint 0 (root): {} // empty scope\n * Checkpoint 1 (:x=5): { x: 5 } __proto__ → 0\n * Checkpoint 2 (:y=8): { y: 8 } __proto__ → 1\n * Checkpoint 3 (:x=3): { x: 3 } __proto__ → 2 // shadows x=5\n * ```\n *\n * To look up `x` at checkpoint 3: find own `x=3` → done.\n * To look up `y` at checkpoint 3: not own → walk proto to checkpoint 2 → `y=8`.\n * To look up `z` at checkpoint 3: not found anywhere → undefined.\n *\n * **Memory:** O(number of variable definitions) heap, independent of\n * document length. Typical Obsidian documents have < 100 variable defs,\n * so total checkpoint heap is < 10 KB.\n */\nexport interface VMCheckpoint {\n\t/** 1-based line number where this checkpoint was created. */\n\tlineNumber: number;\n\t/** Persistent line ID from DocumentModel. */\n\tlineId: number;\n\t/**\n\t * Variable name → Value at this checkpoint.\n\t * Own properties are variables set/updated at this line.\n\t * The prototype chain provides inherited variables from parent checkpoints.\n\t */\n\tvariables: Record<string, Value>;\n\t/**\n\t * User-defined-function name → definition at this checkpoint. SEPARATE\n\t * from `variables` above (not prototypally chained the same way\n\t * `restoreTo()` replays every checkpoint in the chain in order, so a\n\t * later redefinition of the same function name naturally overwrites an\n\t * earlier one during replay, without needing its own prototype walk).\n\t *\n\t * Without this field, a function definition's checkpoint entry would be\n\t * SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every\n\t * written name, which returns `undefined` for a function name (function\n\t * defs live in `vm.userFunctions`, not the flat variable store), and a\n\t * `val !== undefined` guard silently skipped it. A scroll-triggered\n\t * `restoreTo()` would then reset the VM and replay only `variables`,\n\t * making a function defined above the new viewport vanish (calling it\n\t * would throw `UNDEFINED_FUNCTION`) even though the document still\n\t * shows its definition line as clean/cached.\n\t */\n\tfunctions: Record<string, UserFunctionDef>;\n\t/** Parent checkpoint (closer to document start), or null for root. */\n\tparent: VMCheckpoint | null;\n}\n\n// ── VMCheckpointer ──────────────────────────────────────────────────────\n\n/**\n * Manages VM state checkpoints for the three-tier evaluation strategy.\n *\n * **Checkpoint creation:** After a variable-definition line executes\n * (Tier 1 or Tier 3), `snapshot()` records the current values of the\n * written variables. The checkpoint is linked via prototypal inheritance\n * to the previous checkpoint, so only changed variables consume memory.\n *\n * **Checkpoint restoration:** Before evaluating a viewport whose start line\n * is not line 1, `restoreTo(lineNumber)` resets the VM and replays all\n * variable definitions up to and including that line. This avoids\n * re-evaluating the entire document from line 1 on every scroll.\n *\n * **Thread safety:** Checkpoints are created synchronously on the main\n * thread during evaluation. They are immutable after creation (Value is\n * an immutable type), so no synchronization is needed.\n *\n * **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`\n * to find the checkpoint just before the new viewport start, then call\n * `restoreTo()` to set up the VM before evaluating only the visible lines.\n * This is the key to O(visible lines) scrolling instead of O(document).\n */\nexport class VMCheckpointer {\n\t/** Ordered array of checkpoints (ascending lineNumber). */\n\tprivate checkpoints: VMCheckpoint[] = [];\n\t/** The VM instance whose variables are snapshotted/restored. */\n\tprivate vm: VM;\n\n\tconstructor(vm: VM) {\n\t\tthis.vm = vm;\n\t}\n\n\t// ── Snapshot ─────────────────────────────────────────────────────\n\n\t/**\n\t * Create a checkpoint at the current line, recording the VM values of\n\t * the specified variables.\n\t *\n\t * Uses prototypal inheritance: `Object.create(parent.variables)` so\n\t * that inherited variable lookups fall through to previous checkpoints\n\t * without copying all variables into each checkpoint.\n\t *\n\t * A line that is snapshotted again drops every checkpoint at or after it\n\t * first, so the list stays in document order and the new checkpoint\n\t * inherits from the line before it rather than from one after it. See the\n\t * body for what went wrong without that.\n\t *\n\t * @param lineNumber 1-based line position.\n\t * @param lineId Persistent line ID from DocumentModel.\n\t * @param variableNames Names of variables that were written at this line.\n\t * @returns The new checkpoint, or null if no variable names provided.\n\t */\n\tsnapshot(\n\t\tlineNumber: number,\n\t\tlineId: number,\n\t\tvariableNames: string[]\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\t// Everything at or after this line goes before the new checkpoint is\n\t\t// taken.\n\t\t//\n\t\t// The list is a sequence of document positions and `restoreTo` reads it\n\t\t// as one, so appending on a re-run broke both halves of that. Editing\n\t\t// line 2 of a document whose lines 1, 2 and 3 each define something\n\t\t// left the list as [1, 2, 3, 2]: `getNearestCheckpoint(2)` stops at the\n\t\t// first entry past its target, so it found the stale line 2 and\n\t\t// restored the old value, and the new line 2 inherited from line 3, a\n\t\t// chain running backwards through the document that would have defined\n\t\t// a variable from a line that had not run yet.\n\t\t//\n\t\t// Nothing is lost by dropping them. A pass runs in document order and\n\t\t// every line that writes takes a checkpoint, so the ones removed here\n\t\t// are re-taken by this same pass as it continues past this line.\n\t\tlet keep = this.checkpoints.length;\n\t\twhile (keep > 0 && this.checkpoints[keep - 1].lineNumber >= lineNumber) keep--;\n\t\tif (keep !== this.checkpoints.length) this.checkpoints.length = keep;\n\n\t\tconst parent = keep > 0 ? this.checkpoints[keep - 1] : null;\n\n\t\t// Create prototypal chain: new checkpoint inherits from parent\n\t\tconst variables: Record<string, Value> = Object.create(\n\t\t\tparent?.variables ?? null\n\t\t) as Record<string, Value>;\n\t\tconst functions: Record<string, UserFunctionDef> = Object.create(\n\t\t\tparent?.functions ?? null\n\t\t) as Record<string, UserFunctionDef>;\n\n\t\t// Record current VM values for the written names, routing each into\n\t\t// the right bag (a name is either a variable or a user-defined\n\t\t// function, never both; see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional).\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst val = this.vm.getVar(name);\n\t\t\tif (val !== undefined) {\n\t\t\t\tvariables[name] = val;\n\t\t\t}\n\t\t}\n\n\t\tconst checkpoint: VMCheckpoint = {\n\t\t\tlineNumber,\n\t\t\tlineId,\n\t\t\tvariables,\n\t\t\tfunctions,\n\t\t\tparent,\n\t\t};\n\t\tthis.checkpoints.push(checkpoint);\n\t\treturn checkpoint;\n\t}\n\n\t// ── Restore ──────────────────────────────────────────────────────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,\n\t * then replays all variable definitions from root → that checkpoint\n\t * into the VM via `setVar()`. The VM's stack is also reset.\n\t *\n\t * If no checkpoint exists at or before the target line, the VM is\n\t * fully reset (empty scope, empty stack).\n\t *\n\t * **Performance:** O(number of checkpoints × variables per checkpoint).\n\t * With prototypal inheritance, `Object.keys()` on each checkpoint\n\t * returns only the variables that were set at that checkpoint (not\n\t * inherited ones), so the total work is O(total variable definitions\n\t * in the document), which is < 100 for typical Obsidian documents.\n\t *\n\t * @param lineNumber Target 1-based line number. The VM will have the\n\t * state that existed AFTER evaluating lines up to `lineNumber`.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tconst target = this.getNearestCheckpoint(lineNumber);\n\t\tif (!target) {\n\t\t\tthis.vm.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Collect the checkpoint chain from root to target.\n\t\t// Walk parent links and reverse so root is first.\n\t\tconst chain: VMCheckpoint[] = [];\n\t\tlet current: VMCheckpoint | null = target;\n\t\twhile (current) {\n\t\t\tchain.unshift(current);\n\t\t\tcurrent = current.parent;\n\t\t}\n\n\t\tthis.vm.reset();\n\t\tfor (const cp of chain) {\n\t\t\t// Object.keys() returns only OWN enumerable properties\n\t\t\t// it does NOT include inherited properties from the prototype chain.\n\t\t\t// This means we only set variables that were defined/updated at this\n\t\t\t// specific checkpoint, not all variables from parent checkpoints.\n\t\t\tfor (const key of Object.keys(cp.variables)) {\n\t\t\t\tthis.vm.setVar(key, cp.variables[key]);\n\t\t\t}\n\t\t\t// Replay function definitions the same way, a later checkpoint's\n\t\t\t// redefinition of the same name naturally overwrites an earlier\n\t\t\t// one since the chain replays in root-to-target order.\n\t\t\tfor (const key of Object.keys(cp.functions)) {\n\t\t\t\tconst fn = cp.functions[key];\n\t\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Queries ──────────────────────────────────────────────────────\n\n\t/**\n\t * Find the nearest checkpoint at or before the given line number.\n\t *\n\t * Uses linear scan (checkpoints are sorted by lineNumber and the list\n\t * is short, typically < 20 for Obsidian documents). Can be upgraded\n\t * to binary search if needed for documents with 1000+ variable defs.\n\t *\n\t * @returns The nearest checkpoint, or null if none exists before the line.\n\t */\n\tgetNearestCheckpoint(lineNumber: number): VMCheckpoint | null {\n\t\tlet result: VMCheckpoint | null = null;\n\t\tfor (const cp of this.checkpoints) {\n\t\t\tif (cp.lineNumber <= lineNumber) {\n\t\t\t\tresult = cp;\n\t\t\t} else {\n\t\t\t\tbreak; // checkpoints are sorted ascending\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get a specific checkpoint by its line number.\n\t * @returns The checkpoint, or undefined if not found.\n\t */\n\tgetCheckpointAt(lineNumber: number): VMCheckpoint | undefined {\n\t\treturn this.checkpoints.find((cp) => cp.lineNumber === lineNumber);\n\t}\n\n\t/**\n\t * Get the entire checkpoint chain from root to the last checkpoint.\n\t * Useful for debugging and serialization.\n\t */\n\tgetAllCheckpoints(): readonly VMCheckpoint[] {\n\t\treturn this.checkpoints;\n\t}\n\n\t/**\n\t * Look up a variable's value through the checkpoint chain.\n\t *\n\t * Walks the prototype chain starting from the most recent checkpoint,\n\t * looking for the variable name as an own property. This is O(depth)\n\t * where depth is the number of checkpoints since the variable was\n\t * last set.\n\t *\n\t * **Note:** This queries the checkpointer's snapshot, not the VM.\n\t * The VM may have been modified since the last snapshot (e.g., by\n\t * Tier 2 execution of non-variable-def lines that don't create checkpoints).\n\t *\n\t * @returns The Value, or undefined if the variable was never set.\n\t */\n\tlookupVariable(name: string): Value | undefined {\n\t\tif (this.checkpoints.length === 0) return undefined;\n\n\t\tconst latest = this.checkpoints[this.checkpoints.length - 1];\n\t\tlet scope: Record<string, Value> | null = latest.variables;\n\t\twhile (scope) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(scope, name)) {\n\t\t\t\treturn scope[name];\n\t\t\t}\n\t\t\tscope = Object.getPrototypeOf(scope) as Record<string, Value> | null;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────\n\n\t/**\n\t * Clear all checkpoints. The underlying VM is NOT reset, call\n\t * `vm.reset()` separately if needed.\n\t */\n\tclear(): void {\n\t\tthis.checkpoints = [];\n\t}\n\n\t/** Number of checkpoints stored. */\n\tget count(): number {\n\t\treturn this.checkpoints.length;\n\t}\n\n\t/** Returns true if no checkpoints have been created. */\n\tget isEmpty(): boolean {\n\t\treturn this.checkpoints.length === 0;\n\t}\n\n\t/** The associated VM instance. */\n\tget vmInstance(): VM {\n\t\treturn this.vm;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"vm.cjs"}
|
package/dist/vm.d.cts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, L as LineExecutionContext, O as OpRegistry, S as ScopeManager, V as VM, a as
|
|
1
|
+
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, L as LineExecutionContext, O as OpRegistry, S as ScopeManager, V as VM, a as VMCheckpoint, b as VMCheckpointer, c as allocatePluginFunctionIndex, d as builtinFunctions, e as createVM, f as executeBytecode, p as pluginFunctionIndexFor, g as pluginFunctionRegistry, s as sharedOpRegistry } from './VMBuiltins-BwqFO2TY.cjs';
|
|
2
2
|
import { V as Value } from './Value-B55Hvn3e.cjs';
|
|
3
3
|
export { M as MatrixData, a as MatrixEntry, R as RangeData, b as ValueType, c as bigIntValue, d as colVectorValue, h as hexValue, m as matrixValue, n as numberValue, r as rangeValue, e as rowVectorValue, s as stringValue, u as uomValue } from './Value-B55Hvn3e.cjs';
|
|
4
|
-
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-BwLCnV8C.cjs';
|
|
5
4
|
import './BytecodeBuilder-DSWKZi4f.cjs';
|
|
6
5
|
import './CalendarBackend-MdS3Bb4P.cjs';
|
|
7
6
|
import './EngineError-Bm4OYmw8.cjs';
|
package/dist/vm.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, L as LineExecutionContext, O as OpRegistry, S as ScopeManager, V as VM, a as
|
|
1
|
+
export { B as Bytecode, D as DependencyGraph, E as ExpressionRecord, L as LineExecutionContext, O as OpRegistry, S as ScopeManager, V as VM, a as VMCheckpoint, b as VMCheckpointer, c as allocatePluginFunctionIndex, d as builtinFunctions, e as createVM, f as executeBytecode, p as pluginFunctionIndexFor, g as pluginFunctionRegistry, s as sharedOpRegistry } from './VMBuiltins-h09nijID.js';
|
|
2
2
|
import { V as Value } from './Value-B55Hvn3e.js';
|
|
3
3
|
export { M as MatrixData, a as MatrixEntry, R as RangeData, b as ValueType, c as bigIntValue, d as colVectorValue, h as hexValue, m as matrixValue, n as numberValue, r as rangeValue, e as rowVectorValue, s as stringValue, u as uomValue } from './Value-B55Hvn3e.js';
|
|
4
|
-
export { V as VMCheckpoint, a as VMCheckpointer } from './VMCheckpoints-BXavssWa.js';
|
|
5
4
|
import './BytecodeBuilder-DSWKZi4f.js';
|
|
6
5
|
import './CalendarBackend-MdS3Bb4P.js';
|
|
7
6
|
import './EngineError-Bm4OYmw8.js';
|
package/dist/vm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as ScopeManager,b as createVM,c as executeBytecode}from'./chunk-ZXNM355C.js';import'./chunk-JP4JMQOG.js';export{b as DependencyGraph,y as OpRegistry,H as allocatePluginFunctionIndex,x as binaryOp,F as builtinFunctions,I as pluginFunctionIndexFor,G as pluginFunctionRegistry,z as sharedOpRegistry,l as unifyUom}from'./chunk-AFNK2LUO.js';import'./chunk-X2GQAKL2.js';import'./chunk-PICFFFJV.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-IHPYXJIY.js';import'./chunk-EOO6M65F.js';import'./chunk-J4K72CQN.js';export{m as Value,g as ValueType,s as bigIntValue,c as chargeAllocation,d as checkAllocation,e as checkedArray,E as colVectorValue,r as hexValue,C as matrixValue,n as numberValue,F as rangeValue,D as rowVectorValue,t as stringValue,u as uomValue}from'./chunk-A34R65WT.js';import'./chunk-BWTVJD5L.js';import'./chunk-PRSXXDTA.js';import'./chunk-6G2NES2I.js'
|
|
1
|
+
export{a as VMCheckpointer}from'./chunk-44BWHZ5V.js';export{a as ScopeManager,b as createVM,c as executeBytecode}from'./chunk-ZXNM355C.js';import'./chunk-JP4JMQOG.js';export{b as DependencyGraph,y as OpRegistry,H as allocatePluginFunctionIndex,x as binaryOp,F as builtinFunctions,I as pluginFunctionIndexFor,G as pluginFunctionRegistry,z as sharedOpRegistry,l as unifyUom}from'./chunk-AFNK2LUO.js';import'./chunk-X2GQAKL2.js';import'./chunk-PICFFFJV.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import'./chunk-IHPYXJIY.js';import'./chunk-EOO6M65F.js';import'./chunk-J4K72CQN.js';export{m as Value,g as ValueType,s as bigIntValue,c as chargeAllocation,d as checkAllocation,e as checkedArray,E as colVectorValue,r as hexValue,C as matrixValue,n as numberValue,F as rangeValue,D as rowVectorValue,t as stringValue,u as uomValue}from'./chunk-A34R65WT.js';import'./chunk-BWTVJD5L.js';import'./chunk-PRSXXDTA.js';import'./chunk-6G2NES2I.js';//# sourceMappingURL=vm.js.map
|
|
2
2
|
//# sourceMappingURL=vm.js.map
|
package/dist/vm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","keep","parent","variables","functions","name","fn","val","checkpoint","target","chain","current","cp","key","result","scope"],"mappings":"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","file":"vm.js","sourcesContent":["import { Value } from \"@solve-js/vm/Value\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\nimport type { UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\n\n// ── VMCheckpoint ────────────────────────────────────────────────────────\n\n/**\n * A point-in-time snapshot of VM variable state.\n *\n * Uses **prototypal inheritance** for memory efficiency: each checkpoint's\n * `variables` object has its parent checkpoint's `variables` as its\n * `__proto__`. This means a `getVar(\"x\")` lookup walks the prototype chain\n * until it finds `x`, and only variables that CHANGED at this checkpoint\n * consume heap space. Unchanged variables are inherited from the parent.\n *\n * ```text\n * Checkpoint 0 (root): {} // empty scope\n * Checkpoint 1 (:x=5): { x: 5 } __proto__ → 0\n * Checkpoint 2 (:y=8): { y: 8 } __proto__ → 1\n * Checkpoint 3 (:x=3): { x: 3 } __proto__ → 2 // shadows x=5\n * ```\n *\n * To look up `x` at checkpoint 3: find own `x=3` → done.\n * To look up `y` at checkpoint 3: not own → walk proto to checkpoint 2 → `y=8`.\n * To look up `z` at checkpoint 3: not found anywhere → undefined.\n *\n * **Memory:** O(number of variable definitions) heap, independent of\n * document length. Typical Obsidian documents have < 100 variable defs,\n * so total checkpoint heap is < 10 KB.\n */\nexport interface VMCheckpoint {\n\t/** 1-based line number where this checkpoint was created. */\n\tlineNumber: number;\n\t/** Persistent line ID from DocumentModel. */\n\tlineId: number;\n\t/**\n\t * Variable name → Value at this checkpoint.\n\t * Own properties are variables set/updated at this line.\n\t * The prototype chain provides inherited variables from parent checkpoints.\n\t */\n\tvariables: Record<string, Value>;\n\t/**\n\t * User-defined-function name → definition at this checkpoint. SEPARATE\n\t * from `variables` above (not prototypally chained the same way\n\t * `restoreTo()` replays every checkpoint in the chain in order, so a\n\t * later redefinition of the same function name naturally overwrites an\n\t * earlier one during replay, without needing its own prototype walk).\n\t *\n\t * Without this field, a function definition's checkpoint entry would be\n\t * SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every\n\t * written name, which returns `undefined` for a function name (function\n\t * defs live in `vm.userFunctions`, not the flat variable store), and a\n\t * `val !== undefined` guard silently skipped it. A scroll-triggered\n\t * `restoreTo()` would then reset the VM and replay only `variables`,\n\t * making a function defined above the new viewport vanish (calling it\n\t * would throw `UNDEFINED_FUNCTION`) even though the document still\n\t * shows its definition line as clean/cached.\n\t */\n\tfunctions: Record<string, UserFunctionDef>;\n\t/** Parent checkpoint (closer to document start), or null for root. */\n\tparent: VMCheckpoint | null;\n}\n\n// ── VMCheckpointer ──────────────────────────────────────────────────────\n\n/**\n * Manages VM state checkpoints for the three-tier evaluation strategy.\n *\n * **Checkpoint creation:** After a variable-definition line executes\n * (Tier 1 or Tier 3), `snapshot()` records the current values of the\n * written variables. The checkpoint is linked via prototypal inheritance\n * to the previous checkpoint, so only changed variables consume memory.\n *\n * **Checkpoint restoration:** Before evaluating a viewport whose start line\n * is not line 1, `restoreTo(lineNumber)` resets the VM and replays all\n * variable definitions up to and including that line. This avoids\n * re-evaluating the entire document from line 1 on every scroll.\n *\n * **Thread safety:** Checkpoints are created synchronously on the main\n * thread during evaluation. They are immutable after creation (Value is\n * an immutable type), so no synchronization is needed.\n *\n * **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`\n * to find the checkpoint just before the new viewport start, then call\n * `restoreTo()` to set up the VM before evaluating only the visible lines.\n * This is the key to O(visible lines) scrolling instead of O(document).\n */\nexport class VMCheckpointer {\n\t/** Ordered array of checkpoints (ascending lineNumber). */\n\tprivate checkpoints: VMCheckpoint[] = [];\n\t/** The VM instance whose variables are snapshotted/restored. */\n\tprivate vm: VM;\n\n\tconstructor(vm: VM) {\n\t\tthis.vm = vm;\n\t}\n\n\t// ── Snapshot ─────────────────────────────────────────────────────\n\n\t/**\n\t * Create a checkpoint at the current line, recording the VM values of\n\t * the specified variables.\n\t *\n\t * Uses prototypal inheritance: `Object.create(parent.variables)` so\n\t * that inherited variable lookups fall through to previous checkpoints\n\t * without copying all variables into each checkpoint.\n\t *\n\t * A line that is snapshotted again drops every checkpoint at or after it\n\t * first, so the list stays in document order and the new checkpoint\n\t * inherits from the line before it rather than from one after it. See the\n\t * body for what went wrong without that.\n\t *\n\t * @param lineNumber 1-based line position.\n\t * @param lineId Persistent line ID from DocumentModel.\n\t * @param variableNames Names of variables that were written at this line.\n\t * @returns The new checkpoint, or null if no variable names provided.\n\t */\n\tsnapshot(\n\t\tlineNumber: number,\n\t\tlineId: number,\n\t\tvariableNames: string[]\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\t// Everything at or after this line goes before the new checkpoint is\n\t\t// taken.\n\t\t//\n\t\t// The list is a sequence of document positions and `restoreTo` reads it\n\t\t// as one, so appending on a re-run broke both halves of that. Editing\n\t\t// line 2 of a document whose lines 1, 2 and 3 each define something\n\t\t// left the list as [1, 2, 3, 2]: `getNearestCheckpoint(2)` stops at the\n\t\t// first entry past its target, so it found the stale line 2 and\n\t\t// restored the old value, and the new line 2 inherited from line 3, a\n\t\t// chain running backwards through the document that would have defined\n\t\t// a variable from a line that had not run yet.\n\t\t//\n\t\t// Nothing is lost by dropping them. A pass runs in document order and\n\t\t// every line that writes takes a checkpoint, so the ones removed here\n\t\t// are re-taken by this same pass as it continues past this line.\n\t\tlet keep = this.checkpoints.length;\n\t\twhile (keep > 0 && this.checkpoints[keep - 1].lineNumber >= lineNumber) keep--;\n\t\tif (keep !== this.checkpoints.length) this.checkpoints.length = keep;\n\n\t\tconst parent = keep > 0 ? this.checkpoints[keep - 1] : null;\n\n\t\t// Create prototypal chain: new checkpoint inherits from parent\n\t\tconst variables: Record<string, Value> = Object.create(\n\t\t\tparent?.variables ?? null\n\t\t) as Record<string, Value>;\n\t\tconst functions: Record<string, UserFunctionDef> = Object.create(\n\t\t\tparent?.functions ?? null\n\t\t) as Record<string, UserFunctionDef>;\n\n\t\t// Record current VM values for the written names, routing each into\n\t\t// the right bag (a name is either a variable or a user-defined\n\t\t// function, never both; see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional).\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst val = this.vm.getVar(name);\n\t\t\tif (val !== undefined) {\n\t\t\t\tvariables[name] = val;\n\t\t\t}\n\t\t}\n\n\t\tconst checkpoint: VMCheckpoint = {\n\t\t\tlineNumber,\n\t\t\tlineId,\n\t\t\tvariables,\n\t\t\tfunctions,\n\t\t\tparent,\n\t\t};\n\t\tthis.checkpoints.push(checkpoint);\n\t\treturn checkpoint;\n\t}\n\n\t// ── Restore ──────────────────────────────────────────────────────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,\n\t * then replays all variable definitions from root → that checkpoint\n\t * into the VM via `setVar()`. The VM's stack is also reset.\n\t *\n\t * If no checkpoint exists at or before the target line, the VM is\n\t * fully reset (empty scope, empty stack).\n\t *\n\t * **Performance:** O(number of checkpoints × variables per checkpoint).\n\t * With prototypal inheritance, `Object.keys()` on each checkpoint\n\t * returns only the variables that were set at that checkpoint (not\n\t * inherited ones), so the total work is O(total variable definitions\n\t * in the document), which is < 100 for typical Obsidian documents.\n\t *\n\t * @param lineNumber Target 1-based line number. The VM will have the\n\t * state that existed AFTER evaluating lines up to `lineNumber`.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tconst target = this.getNearestCheckpoint(lineNumber);\n\t\tif (!target) {\n\t\t\tthis.vm.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Collect the checkpoint chain from root to target.\n\t\t// Walk parent links and reverse so root is first.\n\t\tconst chain: VMCheckpoint[] = [];\n\t\tlet current: VMCheckpoint | null = target;\n\t\twhile (current) {\n\t\t\tchain.unshift(current);\n\t\t\tcurrent = current.parent;\n\t\t}\n\n\t\tthis.vm.reset();\n\t\tfor (const cp of chain) {\n\t\t\t// Object.keys() returns only OWN enumerable properties\n\t\t\t// it does NOT include inherited properties from the prototype chain.\n\t\t\t// This means we only set variables that were defined/updated at this\n\t\t\t// specific checkpoint, not all variables from parent checkpoints.\n\t\t\tfor (const key of Object.keys(cp.variables)) {\n\t\t\t\tthis.vm.setVar(key, cp.variables[key]);\n\t\t\t}\n\t\t\t// Replay function definitions the same way, a later checkpoint's\n\t\t\t// redefinition of the same name naturally overwrites an earlier\n\t\t\t// one since the chain replays in root-to-target order.\n\t\t\tfor (const key of Object.keys(cp.functions)) {\n\t\t\t\tconst fn = cp.functions[key];\n\t\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Queries ──────────────────────────────────────────────────────\n\n\t/**\n\t * Find the nearest checkpoint at or before the given line number.\n\t *\n\t * Uses linear scan (checkpoints are sorted by lineNumber and the list\n\t * is short, typically < 20 for Obsidian documents). Can be upgraded\n\t * to binary search if needed for documents with 1000+ variable defs.\n\t *\n\t * @returns The nearest checkpoint, or null if none exists before the line.\n\t */\n\tgetNearestCheckpoint(lineNumber: number): VMCheckpoint | null {\n\t\tlet result: VMCheckpoint | null = null;\n\t\tfor (const cp of this.checkpoints) {\n\t\t\tif (cp.lineNumber <= lineNumber) {\n\t\t\t\tresult = cp;\n\t\t\t} else {\n\t\t\t\tbreak; // checkpoints are sorted ascending\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get a specific checkpoint by its line number.\n\t * @returns The checkpoint, or undefined if not found.\n\t */\n\tgetCheckpointAt(lineNumber: number): VMCheckpoint | undefined {\n\t\treturn this.checkpoints.find((cp) => cp.lineNumber === lineNumber);\n\t}\n\n\t/**\n\t * Get the entire checkpoint chain from root to the last checkpoint.\n\t * Useful for debugging and serialization.\n\t */\n\tgetAllCheckpoints(): readonly VMCheckpoint[] {\n\t\treturn this.checkpoints;\n\t}\n\n\t/**\n\t * Look up a variable's value through the checkpoint chain.\n\t *\n\t * Walks the prototype chain starting from the most recent checkpoint,\n\t * looking for the variable name as an own property. This is O(depth)\n\t * where depth is the number of checkpoints since the variable was\n\t * last set.\n\t *\n\t * **Note:** This queries the checkpointer's snapshot, not the VM.\n\t * The VM may have been modified since the last snapshot (e.g., by\n\t * Tier 2 execution of non-variable-def lines that don't create checkpoints).\n\t *\n\t * @returns The Value, or undefined if the variable was never set.\n\t */\n\tlookupVariable(name: string): Value | undefined {\n\t\tif (this.checkpoints.length === 0) return undefined;\n\n\t\tconst latest = this.checkpoints[this.checkpoints.length - 1];\n\t\tlet scope: Record<string, Value> | null = latest.variables;\n\t\twhile (scope) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(scope, name)) {\n\t\t\t\treturn scope[name];\n\t\t\t}\n\t\t\tscope = Object.getPrototypeOf(scope) as Record<string, Value> | null;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────\n\n\t/**\n\t * Clear all checkpoints. The underlying VM is NOT reset, call\n\t * `vm.reset()` separately if needed.\n\t */\n\tclear(): void {\n\t\tthis.checkpoints = [];\n\t}\n\n\t/** Number of checkpoints stored. */\n\tget count(): number {\n\t\treturn this.checkpoints.length;\n\t}\n\n\t/** Returns true if no checkpoints have been created. */\n\tget isEmpty(): boolean {\n\t\treturn this.checkpoints.length === 0;\n\t}\n\n\t/** The associated VM instance. */\n\tget vmInstance(): VM {\n\t\treturn this.vm;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"vm.js"}
|
package/dist/worker.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var chunkHSTGWWU2_cjs=require('./chunk-HSTGWWU2.cjs'),
|
|
2
|
-
`).forEach((u,d)=>a.set(d+1,u)):o.method==="evaluateLines"?o.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,o.args[0]),a},V=(o,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:chunkHSTGWWU2_cjs.b(chunk6SYU4MH7_cjs.d(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let T=o.evaluateLine(d,f);T&&u.push({lineNumber:d,value:m(T,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},U=o=>{p?.();let a=o.getEventStream().getReader();p=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;V(o,d);}}catch{}})();},j=o=>{try{let a=$(n,o.packages);t=new
|
|
1
|
+
'use strict';var chunkHSTGWWU2_cjs=require('./chunk-HSTGWWU2.cjs'),chunkZGA7X625_cjs=require('./chunk-ZGA7X625.cjs');require('./chunk-P5YWBIIU.cjs'),require('./chunk-NGBBNL4K.cjs'),require('./chunk-R3W53ZMP.cjs'),require('./chunk-TTFO4YDP.cjs'),require('./chunk-DTOSRC6E.cjs'),require('./chunk-HG4NPDN5.cjs');var chunkJUIHUG4M_cjs=require('./chunk-JUIHUG4M.cjs');require('./chunk-W4XLVZ6R.cjs');var chunkKVONXXPJ_cjs=require('./chunk-KVONXXPJ.cjs');require('./chunk-NMZRAJLJ.cjs');var chunkU54BIYXO_cjs=require('./chunk-U54BIYXO.cjs');require('./chunk-K3PZ66XR.cjs'),require('./chunk-YV4GDW5A.cjs'),require('./chunk-UURM7P3P.cjs'),require('./chunk-GDLYXRMA.cjs'),require('./chunk-ZLRJ7TDP.cjs'),require('./chunk-6ADFAXTZ.cjs'),require('./chunk-OBZJKZ2F.cjs'),require('./chunk-SF5QVUEI.cjs'),require('./chunk-ABVDKMNF.cjs'),require('./chunk-TLG7VZRX.cjs');var chunk5TVI2UPZ_cjs=require('./chunk-5TVI2UPZ.cjs'),chunk5N4XDULO_cjs=require('./chunk-5N4XDULO.cjs');require('./chunk-EQNKDTMX.cjs'),require('./chunk-E4HAKNBQ.cjs'),require('./chunk-NH74IT7B.cjs'),require('./chunk-PHWIO4P3.cjs');var chunkA3CNNRFM_cjs=require('./chunk-A3CNNRFM.cjs');require('./chunk-3MG7VIPL.cjs'),require('./chunk-Y7O4D3BJ.cjs'),require('./chunk-72J5V7SN.cjs'),require('./chunk-YBQOQTVL.cjs'),require('./chunk-S3DFU33X.cjs'),require('./chunk-J4LSAHCY.cjs'),require('./chunk-EZKR44MA.cjs');var chunk6SYU4MH7_cjs=require('./chunk-6SYU4MH7.cjs');function B(e){if(e?.date?.inputOrder!=="locale")return e;let r={...e.date,inputOrder:chunkU54BIYXO_cjs.k({...chunkA3CNNRFM_cjs.b.date,...e.date}).order};return delete r.inputLocale,{...e,date:r}}var x=class{constructor(r){this.nextId=1;this.pending=new Map;this.resolvedListeners=new Set;this.asyncErrorListeners=new Set;this.terminated=false;this.transport=r,this.transport.onMessage(n=>this.onMessage(n));}init(r){let n=this.nextId++;return new Promise((t,s)=>{this.pending.set(n,{resolve:()=>t(),reject:s}),this.transport.postMessage({kind:"init",id:n,localeCode:r.localeCode,diagnostics:r.diagnostics,config:B(r.config),packages:r.packages,formatting:r.formatting});})}parseDocument(r,n){let{signal:t,...s}=n??{},i=Object.keys(s).length>0?s:void 0;return this.call("parseDocument",[r,i],t)}evaluateLines(r,n){return this.call("evaluateLines",[r],n?.signal)}evaluateExpression(r,n){return this.call("evaluateExpression",[r],n?.signal)}onResolved(r){return this.resolvedListeners.add(r),()=>this.resolvedListeners.delete(r)}onAsyncError(r){return this.asyncErrorListeners.add(r),()=>this.asyncErrorListeners.delete(r)}terminate(){if(this.terminated)return;this.terminated=true;let r=chunkHSTGWWU2_cjs.e();for(let n of this.pending.values())this.unhook(n),n.reject(r);this.pending.clear(),this.resolvedListeners.clear(),this.asyncErrorListeners.clear(),this.transport.terminate();}call(r,n,t){if(this.terminated)return Promise.reject(chunkHSTGWWU2_cjs.e());if(t?.aborted)return Promise.reject(chunkHSTGWWU2_cjs.d(r));let s=this.nextId++;return new Promise((i,l)=>{let c={resolve:i,reject:l};if(t){let p=()=>{this.pending.has(s)&&(this.pending.delete(s),this.transport.postMessage({kind:"cancel",id:s}),l(chunkHSTGWWU2_cjs.d(r)));};c.signal=t,c.onAbort=p,t.addEventListener("abort",p,{once:true});}this.pending.set(s,c),this.transport.postMessage({kind:"request",id:s,method:r,args:n});})}onMessage(r){let n=r;switch(n.kind){case "ready":case "result":{let t=n.kind==="result"?n.value:void 0;this.settle(n.id,s=>s.resolve(t));break}case "error":this.settle(n.id,t=>t.reject(chunkHSTGWWU2_cjs.c(n.error)));break;case "async-update":for(let t of [...this.resolvedListeners])t(n.lines);break;case "async-error":for(let t of [...this.asyncErrorListeners])t({queryKey:n.queryKey,packageId:n.packageId,error:chunkHSTGWWU2_cjs.c(n.error)});break}}settle(r,n){let t=this.pending.get(r);t&&(this.pending.delete(r),this.unhook(t),n(t));}unhook(r){r.signal&&r.onAbort&&r.signal.removeEventListener("abort",r.onAbort);}};async function G(e){let r=new x(e.transport);return await r.init(e),r}function F(e){return e>0?"Infinity":e<0?"-Infinity":"NaN"}function H(e){let r=e.data.map(n=>typeof n=="object"&&n!==null?chunk5N4XDULO_cjs.R(n):typeof n=="number"&&!Number.isFinite(n)?F(n):n);return {rows:e.rows,cols:e.cols,cells:r,hasSymbolic:e.hasSymbolic}}function m(e,r){let n=e.toNumber(),t={type:e.type,text:chunkJUIHUG4M_cjs.c(e,r),number:Number.isFinite(n)?n:0};Number.isFinite(n)||(t.nonFinite=F(n)),e.unit!==void 0&&(t.unit=e.unit),e.timedOut!==void 0&&(t.timedOut=e.timedOut),e.grain!==void 0&&(t.grain=e.grain),e.zone!==void 0&&(t.zone=e.zone);let s=e.value;if(typeof s=="bigint")t.bigint=s.toString();else if(e.type===7)t.matrix=H(s);else if(e.type===8){let i=s;t.range={min:i.min,max:i.max};}else if(e.type===14){let i=s;t.colour={hex:chunk5TVI2UPZ_cjs.f(i),r:i.r,g:i.g,b:i.b,a:i.a,format:i.format,css:chunk5TVI2UPZ_cjs.g(i)};}else if(e.type===16){let i=s;t.chart={kind:i.kind,points:i.points.map(l=>[l[0],l[1]]),label:i.label,domain:[i.domain[0],i.domain[1]],range:[i.range[0],i.range[1]],...i.expr!==void 0?{expr:i.expr}:{}};}else if(e.type===17){let i=s;t.ipCidr={...i.addr!==void 0?{addr:i.addr}:{},...i.prefix!==void 0?{prefix:i.prefix}:{},text:chunkJUIHUG4M_cjs.c(e).replace(/^=\s*/,"")};}return t}function q(e,r){return e?m(e,r):null}function J(e,r){return {start:e.start,end:e.end,expression:e.expression,lineNumber:e.lineNumber,columnNumber:e.columnNumber,result:q(e.result,r),error:e.error??null}}function y(e,r){return {lineNumber:e.lineNumber,text:e.text,startPosition:e.startPosition,endPosition:e.endPosition,isEmpty:e.isEmpty,hasInlineSolves:e.hasInlineSolves,inlineSolves:e.inlineSolves.map(n=>J(n,r)),expression:e.expression,result:q(e.result,r),error:e.error}}function R(e,r){let n={lines:e.lines.map(t=>y(t,r)),totalLines:e.totalLines,errors:[...e.errors]};return e.diagnostics!==void 0&&(n.diagnostics=e.diagnostics),n}function $(e,r){if(r===void 0)return e;let n=new Map(e.map(s=>[s.name,s])),t=[];for(let s of r){let i=n.get(s);if(!i)throw chunk6SYU4MH7_cjs.c.config(chunkHSTGWWU2_cjs.a.WORKER_UNKNOWN_PACKAGE,`No package named "${s}" is available in this worker runtime`,{name:s,available:[...n.keys()]});t.push(i);}return t}function Q(e,r={}){let n=r.packages??chunkKVONXXPJ_cjs.z,t=null,s,i=new Map,l=new Map,c=null,p=null,g=o=>e.postMessage(o),E=(o,a)=>{g({kind:"error",id:o,error:chunkHSTGWWU2_cjs.b(chunk6SYU4MH7_cjs.d(a))});},D=o=>{let a=new Map;return o.method==="parseDocument"?o.args[0].split(`
|
|
2
|
+
`).forEach((u,d)=>a.set(d+1,u)):o.method==="evaluateLines"?o.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,o.args[0]),a},V=(o,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:chunkHSTGWWU2_cjs.b(chunk6SYU4MH7_cjs.d(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let T=o.evaluateLine(d,f);T&&u.push({lineNumber:d,value:m(T,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},U=o=>{p?.();let a=o.getEventStream().getReader();p=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;V(o,d);}}catch{}})();},j=o=>{try{let a=$(n,o.packages);t=new chunkZGA7X625_cjs.o({locale:o.localeCode??"en",diagnostics:o.diagnostics??!1,config:o.config,packages:a,calendar:r.calendar}),s=r.calendar?{...o.formatting??chunkJUIHUG4M_cjs.a,calendar:r.calendar}:o.formatting,U(t),g({kind:"ready",id:o.id});}catch(a){E(o.id,a);}},K=(o,a)=>{let{method:u,args:d}=a;switch(u){case "parseDocument":return R(o.parseDocument(d[0],d[1]),s);case "evaluateLines":return o.evaluateLines(d[0]).map(f=>y(f,s));case "evaluateExpression":return m(o.evaluateExpression(d[0]),s);default:throw chunk6SYU4MH7_cjs.c.execution(chunkHSTGWWU2_cjs.a.WORKER_UNKNOWN_METHOD,`The worker runtime has no method named "${String(u)}"`,{method:u})}},_=o=>{let a=t;if(!a){E(o.id,chunk6SYU4MH7_cjs.c.execution(chunkHSTGWWU2_cjs.a.WORKER_NOT_INITIALISED,"The worker received a request before its engine finished initialising"));return}c?.abort();let u=new AbortController;c=u,l=D(o),i.set(o.id,u),a.setKeystrokeSignal(u.signal);try{let d=K(a,o);g({kind:"result",id:o.id,value:d});}catch(d){E(o.id,d);}finally{i.delete(o.id),a.setKeystrokeSignal(null);}};return e.onMessage(o=>{let a=o;switch(a.kind){case "init":j(a);break;case "request":_(a);break;case "cancel":i.get(a.id)?.abort();break}}),()=>{p?.(),p=null,c?.abort(),c=null,l=new Map;for(let o of i.values())o.abort();i.clear(),t?.clear(),t=null,e.terminate();}}function X(e){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e))}function Y(){let e=null,r=null,n=true,t=(l,c)=>{let p=X(c);queueMicrotask(()=>{n&&l()?.(p);});};return {client:{postMessage:l=>t(()=>r,l),onMessage:l=>{e=l;},terminate:()=>{n=false;}},host:{postMessage:l=>t(()=>e,l),onMessage:l=>{r=l;},terminate:()=>{n=false;}}}}function Z(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{let n=t=>r(t.data);typeof e.addEventListener=="function"?e.addEventListener("message",n):e.onmessage=n,e.start?.();},terminate:()=>{e.terminate?.(),e.close?.();}}}function ee(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{e.on("message",n=>r(n));},terminate:()=>{e.terminate?.(),e.close?.();}}}exports.createLinkedTransports=Y;exports.createWorkerEngine=G;exports.eventTargetTransport=Z;exports.messagePortTransport=ee;exports.serializeParsedLine=y;exports.serializeParsingResult=R;exports.serializeValue=m;exports.startWorkerRuntime=Q;//# sourceMappingURL=worker.cjs.map
|
|
3
3
|
//# sourceMappingURL=worker.cjs.map
|
package/dist/worker.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as EngineConfigOverride } from './Configuration-BxriK9Kw.cjs';
|
|
2
|
-
import { U as UnifiedParsingOptions, I as IEnginePackage, N as ParsedLine, P as ParsingResult } from './PackageRegistry-
|
|
2
|
+
import { U as UnifiedParsingOptions, I as IEnginePackage, N as ParsedLine, P as ParsingResult } from './PackageRegistry-DiHxyxrn.cjs';
|
|
3
3
|
import { F as FormattingSettings } from './FormattingSettings-ByO-4wiM.cjs';
|
|
4
4
|
import { E as EngineError } from './EngineError-Bm4OYmw8.cjs';
|
|
5
5
|
import { b as ValueType, i as ColourFormat, D as DatetimeGrain, V as Value } from './Value-B55Hvn3e.cjs';
|
|
@@ -13,7 +13,7 @@ import './Lexer-DaWkCu84.cjs';
|
|
|
13
13
|
import './resolvers.cjs';
|
|
14
14
|
import '@tanstack/query-core';
|
|
15
15
|
import './TokenNormalizer-D382VSYh.cjs';
|
|
16
|
-
import './VMBuiltins-
|
|
16
|
+
import './VMBuiltins-BwqFO2TY.cjs';
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
19
|
* The seam between the harness and whatever actually carries messages.
|
package/dist/worker.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as EngineConfigOverride } from './Configuration-BxriK9Kw.js';
|
|
2
|
-
import { U as UnifiedParsingOptions, I as IEnginePackage, N as ParsedLine, P as ParsingResult } from './PackageRegistry-
|
|
2
|
+
import { U as UnifiedParsingOptions, I as IEnginePackage, N as ParsedLine, P as ParsingResult } from './PackageRegistry-CStmqgw_.js';
|
|
3
3
|
import { F as FormattingSettings } from './FormattingSettings-CvCzAfsz.js';
|
|
4
4
|
import { E as EngineError } from './EngineError-Bm4OYmw8.js';
|
|
5
5
|
import { b as ValueType, i as ColourFormat, D as DatetimeGrain, V as Value } from './Value-B55Hvn3e.js';
|
|
@@ -13,7 +13,7 @@ import './Lexer-DPn5dfCH.js';
|
|
|
13
13
|
import './resolvers.js';
|
|
14
14
|
import '@tanstack/query-core';
|
|
15
15
|
import './TokenNormalizer-DAzPp-j1.js';
|
|
16
|
-
import './VMBuiltins-
|
|
16
|
+
import './VMBuiltins-h09nijID.js';
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
19
|
* The seam between the harness and whatever actually carries messages.
|
package/dist/worker.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {a as a$1,e,d,c as c$2,b}from'./chunk-YID47OPR.js';import {o}from'./chunk-
|
|
1
|
+
import {a as a$1,e,d,c as c$2,b}from'./chunk-YID47OPR.js';import {o}from'./chunk-ENLFOXF3.js';import'./chunk-RU3KGJRA.js';import'./chunk-2RWAXT6O.js';import'./chunk-RMDCGYZM.js';import'./chunk-MIQBJGGR.js';import'./chunk-ZXNM355C.js';import'./chunk-JP4JMQOG.js';import {c,a}from'./chunk-SSS3ZMKX.js';import'./chunk-HLZRNZEU.js';import {z}from'./chunk-4LMPCB2V.js';import'./chunk-AWGSR2GZ.js';import {k}from'./chunk-IUCUBHFW.js';import'./chunk-U5MESNRT.js';import'./chunk-DB5ISONG.js';import'./chunk-76F3LCIL.js';import'./chunk-EOKHRS2T.js';import'./chunk-TCZSPH4A.js';import'./chunk-AFNK2LUO.js';import'./chunk-X2GQAKL2.js';import'./chunk-PICFFFJV.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import {g,f}from'./chunk-5TCSFTZD.js';import {R as R$1}from'./chunk-IHPYXJIY.js';import'./chunk-EOO6M65F.js';import'./chunk-J4K72CQN.js';import'./chunk-A34R65WT.js';import'./chunk-BWTVJD5L.js';import {b as b$1}from'./chunk-BIV4K7B2.js';import'./chunk-6NL7RBAG.js';import'./chunk-JPFCXLJV.js';import'./chunk-APYRNAU2.js';import'./chunk-FAO6DQ74.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import {c as c$1,d as d$1}from'./chunk-6G2NES2I.js';function B(e){if(e?.date?.inputOrder!=="locale")return e;let r={...e.date,inputOrder:k({...b$1.date,...e.date}).order};return delete r.inputLocale,{...e,date:r}}var x=class{constructor(r){this.nextId=1;this.pending=new Map;this.resolvedListeners=new Set;this.asyncErrorListeners=new Set;this.terminated=false;this.transport=r,this.transport.onMessage(n=>this.onMessage(n));}init(r){let n=this.nextId++;return new Promise((t,s)=>{this.pending.set(n,{resolve:()=>t(),reject:s}),this.transport.postMessage({kind:"init",id:n,localeCode:r.localeCode,diagnostics:r.diagnostics,config:B(r.config),packages:r.packages,formatting:r.formatting});})}parseDocument(r,n){let{signal:t,...s}=n??{},i=Object.keys(s).length>0?s:void 0;return this.call("parseDocument",[r,i],t)}evaluateLines(r,n){return this.call("evaluateLines",[r],n?.signal)}evaluateExpression(r,n){return this.call("evaluateExpression",[r],n?.signal)}onResolved(r){return this.resolvedListeners.add(r),()=>this.resolvedListeners.delete(r)}onAsyncError(r){return this.asyncErrorListeners.add(r),()=>this.asyncErrorListeners.delete(r)}terminate(){if(this.terminated)return;this.terminated=true;let r=e();for(let n of this.pending.values())this.unhook(n),n.reject(r);this.pending.clear(),this.resolvedListeners.clear(),this.asyncErrorListeners.clear(),this.transport.terminate();}call(r,n,t){if(this.terminated)return Promise.reject(e());if(t?.aborted)return Promise.reject(d(r));let s=this.nextId++;return new Promise((i,l)=>{let c={resolve:i,reject:l};if(t){let p=()=>{this.pending.has(s)&&(this.pending.delete(s),this.transport.postMessage({kind:"cancel",id:s}),l(d(r)));};c.signal=t,c.onAbort=p,t.addEventListener("abort",p,{once:true});}this.pending.set(s,c),this.transport.postMessage({kind:"request",id:s,method:r,args:n});})}onMessage(r){let n=r;switch(n.kind){case "ready":case "result":{let t=n.kind==="result"?n.value:void 0;this.settle(n.id,s=>s.resolve(t));break}case "error":this.settle(n.id,t=>t.reject(c$2(n.error)));break;case "async-update":for(let t of [...this.resolvedListeners])t(n.lines);break;case "async-error":for(let t of [...this.asyncErrorListeners])t({queryKey:n.queryKey,packageId:n.packageId,error:c$2(n.error)});break}}settle(r,n){let t=this.pending.get(r);t&&(this.pending.delete(r),this.unhook(t),n(t));}unhook(r){r.signal&&r.onAbort&&r.signal.removeEventListener("abort",r.onAbort);}};async function G(e){let r=new x(e.transport);return await r.init(e),r}function F(e){return e>0?"Infinity":e<0?"-Infinity":"NaN"}function H(e){let r=e.data.map(n=>typeof n=="object"&&n!==null?R$1(n):typeof n=="number"&&!Number.isFinite(n)?F(n):n);return {rows:e.rows,cols:e.cols,cells:r,hasSymbolic:e.hasSymbolic}}function m(e,r){let n=e.toNumber(),t={type:e.type,text:c(e,r),number:Number.isFinite(n)?n:0};Number.isFinite(n)||(t.nonFinite=F(n)),e.unit!==void 0&&(t.unit=e.unit),e.timedOut!==void 0&&(t.timedOut=e.timedOut),e.grain!==void 0&&(t.grain=e.grain),e.zone!==void 0&&(t.zone=e.zone);let s=e.value;if(typeof s=="bigint")t.bigint=s.toString();else if(e.type===7)t.matrix=H(s);else if(e.type===8){let i=s;t.range={min:i.min,max:i.max};}else if(e.type===14){let i=s;t.colour={hex:f(i),r:i.r,g:i.g,b:i.b,a:i.a,format:i.format,css:g(i)};}else if(e.type===16){let i=s;t.chart={kind:i.kind,points:i.points.map(l=>[l[0],l[1]]),label:i.label,domain:[i.domain[0],i.domain[1]],range:[i.range[0],i.range[1]],...i.expr!==void 0?{expr:i.expr}:{}};}else if(e.type===17){let i=s;t.ipCidr={...i.addr!==void 0?{addr:i.addr}:{},...i.prefix!==void 0?{prefix:i.prefix}:{},text:c(e).replace(/^=\s*/,"")};}return t}function q(e,r){return e?m(e,r):null}function J(e,r){return {start:e.start,end:e.end,expression:e.expression,lineNumber:e.lineNumber,columnNumber:e.columnNumber,result:q(e.result,r),error:e.error??null}}function y(e,r){return {lineNumber:e.lineNumber,text:e.text,startPosition:e.startPosition,endPosition:e.endPosition,isEmpty:e.isEmpty,hasInlineSolves:e.hasInlineSolves,inlineSolves:e.inlineSolves.map(n=>J(n,r)),expression:e.expression,result:q(e.result,r),error:e.error}}function R(e,r){let n={lines:e.lines.map(t=>y(t,r)),totalLines:e.totalLines,errors:[...e.errors]};return e.diagnostics!==void 0&&(n.diagnostics=e.diagnostics),n}function $(e,r){if(r===void 0)return e;let n=new Map(e.map(s=>[s.name,s])),t=[];for(let s of r){let i=n.get(s);if(!i)throw c$1.config(a$1.WORKER_UNKNOWN_PACKAGE,`No package named "${s}" is available in this worker runtime`,{name:s,available:[...n.keys()]});t.push(i);}return t}function Q(e,r={}){let n=r.packages??z,t=null,s,i=new Map,l=new Map,c=null,p=null,g=o=>e.postMessage(o),E=(o,a)=>{g({kind:"error",id:o,error:b(d$1(a))});},D=o=>{let a=new Map;return o.method==="parseDocument"?o.args[0].split(`
|
|
2
2
|
`).forEach((u,d)=>a.set(d+1,u)):o.method==="evaluateLines"?o.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,o.args[0]),a},V=(o,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:b(d$1(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let T=o.evaluateLine(d,f);T&&u.push({lineNumber:d,value:m(T,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},U=o=>{p?.();let a=o.getEventStream().getReader();p=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;V(o,d);}}catch{}})();},j=o$1=>{try{let a$1=$(n,o$1.packages);t=new o({locale:o$1.localeCode??"en",diagnostics:o$1.diagnostics??!1,config:o$1.config,packages:a$1,calendar:r.calendar}),s=r.calendar?{...o$1.formatting??a,calendar:r.calendar}:o$1.formatting,U(t),g({kind:"ready",id:o$1.id});}catch(a){E(o$1.id,a);}},K=(o,a)=>{let{method:u,args:d}=a;switch(u){case "parseDocument":return R(o.parseDocument(d[0],d[1]),s);case "evaluateLines":return o.evaluateLines(d[0]).map(f=>y(f,s));case "evaluateExpression":return m(o.evaluateExpression(d[0]),s);default:throw c$1.execution(a$1.WORKER_UNKNOWN_METHOD,`The worker runtime has no method named "${String(u)}"`,{method:u})}},_=o=>{let a=t;if(!a){E(o.id,c$1.execution(a$1.WORKER_NOT_INITIALISED,"The worker received a request before its engine finished initialising"));return}c?.abort();let u=new AbortController;c=u,l=D(o),i.set(o.id,u),a.setKeystrokeSignal(u.signal);try{let d=K(a,o);g({kind:"result",id:o.id,value:d});}catch(d){E(o.id,d);}finally{i.delete(o.id),a.setKeystrokeSignal(null);}};return e.onMessage(o=>{let a=o;switch(a.kind){case "init":j(a);break;case "request":_(a);break;case "cancel":i.get(a.id)?.abort();break}}),()=>{p?.(),p=null,c?.abort(),c=null,l=new Map;for(let o of i.values())o.abort();i.clear(),t?.clear(),t=null,e.terminate();}}function X(e){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e))}function Y(){let e=null,r=null,n=true,t=(l,c)=>{let p=X(c);queueMicrotask(()=>{n&&l()?.(p);});};return {client:{postMessage:l=>t(()=>r,l),onMessage:l=>{e=l;},terminate:()=>{n=false;}},host:{postMessage:l=>t(()=>e,l),onMessage:l=>{r=l;},terminate:()=>{n=false;}}}}function Z(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{let n=t=>r(t.data);typeof e.addEventListener=="function"?e.addEventListener("message",n):e.onmessage=n,e.start?.();},terminate:()=>{e.terminate?.(),e.close?.();}}}function ee(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{e.on("message",n=>r(n));},terminate:()=>{e.terminate?.(),e.close?.();}}}export{Y as createLinkedTransports,G as createWorkerEngine,Z as eventTargetTransport,ee as messagePortTransport,y as serializeParsedLine,R as serializeParsingResult,m as serializeValue,Q as startWorkerRuntime};//# sourceMappingURL=worker.js.map
|
|
3
3
|
//# sourceMappingURL=worker.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "solve-engine",
|
|
3
|
-
"version": "2.38.
|
|
3
|
+
"version": "2.38.15",
|
|
4
4
|
"description": "An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"expression-evaluator",
|
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
import { V as Value } from './Value-B55Hvn3e.js';
|
|
2
|
-
import { V as VM } from './VMBuiltins-Dd0KZR4G.js';
|
|
3
|
-
import { U as UserFunctionDef } from './BytecodeBuilder-DSWKZi4f.js';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* A point-in-time snapshot of VM variable state.
|
|
7
|
-
*
|
|
8
|
-
* Uses **prototypal inheritance** for memory efficiency: each checkpoint's
|
|
9
|
-
* `variables` object has its parent checkpoint's `variables` as its
|
|
10
|
-
* `__proto__`. This means a `getVar("x")` lookup walks the prototype chain
|
|
11
|
-
* until it finds `x`, and only variables that CHANGED at this checkpoint
|
|
12
|
-
* consume heap space. Unchanged variables are inherited from the parent.
|
|
13
|
-
*
|
|
14
|
-
* ```text
|
|
15
|
-
* Checkpoint 0 (root): {} // empty scope
|
|
16
|
-
* Checkpoint 1 (:x=5): { x: 5 } __proto__ → 0
|
|
17
|
-
* Checkpoint 2 (:y=8): { y: 8 } __proto__ → 1
|
|
18
|
-
* Checkpoint 3 (:x=3): { x: 3 } __proto__ → 2 // shadows x=5
|
|
19
|
-
* ```
|
|
20
|
-
*
|
|
21
|
-
* To look up `x` at checkpoint 3: find own `x=3` → done.
|
|
22
|
-
* To look up `y` at checkpoint 3: not own → walk proto to checkpoint 2 → `y=8`.
|
|
23
|
-
* To look up `z` at checkpoint 3: not found anywhere → undefined.
|
|
24
|
-
*
|
|
25
|
-
* **Memory:** O(number of variable definitions) heap, independent of
|
|
26
|
-
* document length. Typical Obsidian documents have < 100 variable defs,
|
|
27
|
-
* so total checkpoint heap is < 10 KB.
|
|
28
|
-
*/
|
|
29
|
-
interface VMCheckpoint {
|
|
30
|
-
/** 1-based line number where this checkpoint was created. */
|
|
31
|
-
lineNumber: number;
|
|
32
|
-
/** Persistent line ID from DocumentModel. */
|
|
33
|
-
lineId: number;
|
|
34
|
-
/**
|
|
35
|
-
* Variable name → Value at this checkpoint.
|
|
36
|
-
* Own properties are variables set/updated at this line.
|
|
37
|
-
* The prototype chain provides inherited variables from parent checkpoints.
|
|
38
|
-
*/
|
|
39
|
-
variables: Record<string, Value>;
|
|
40
|
-
/**
|
|
41
|
-
* User-defined-function name → definition at this checkpoint. SEPARATE
|
|
42
|
-
* from `variables` above (not prototypally chained the same way
|
|
43
|
-
* `restoreTo()` replays every checkpoint in the chain in order, so a
|
|
44
|
-
* later redefinition of the same function name naturally overwrites an
|
|
45
|
-
* earlier one during replay, without needing its own prototype walk).
|
|
46
|
-
*
|
|
47
|
-
* Without this field, a function definition's checkpoint entry would be
|
|
48
|
-
* SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every
|
|
49
|
-
* written name, which returns `undefined` for a function name (function
|
|
50
|
-
* defs live in `vm.userFunctions`, not the flat variable store), and a
|
|
51
|
-
* `val !== undefined` guard silently skipped it. A scroll-triggered
|
|
52
|
-
* `restoreTo()` would then reset the VM and replay only `variables`,
|
|
53
|
-
* making a function defined above the new viewport vanish (calling it
|
|
54
|
-
* would throw `UNDEFINED_FUNCTION`) even though the document still
|
|
55
|
-
* shows its definition line as clean/cached.
|
|
56
|
-
*/
|
|
57
|
-
functions: Record<string, UserFunctionDef>;
|
|
58
|
-
/** Parent checkpoint (closer to document start), or null for root. */
|
|
59
|
-
parent: VMCheckpoint | null;
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Manages VM state checkpoints for the three-tier evaluation strategy.
|
|
63
|
-
*
|
|
64
|
-
* **Checkpoint creation:** After a variable-definition line executes
|
|
65
|
-
* (Tier 1 or Tier 3), `snapshot()` records the current values of the
|
|
66
|
-
* written variables. The checkpoint is linked via prototypal inheritance
|
|
67
|
-
* to the previous checkpoint, so only changed variables consume memory.
|
|
68
|
-
*
|
|
69
|
-
* **Checkpoint restoration:** Before evaluating a viewport whose start line
|
|
70
|
-
* is not line 1, `restoreTo(lineNumber)` resets the VM and replays all
|
|
71
|
-
* variable definitions up to and including that line. This avoids
|
|
72
|
-
* re-evaluating the entire document from line 1 on every scroll.
|
|
73
|
-
*
|
|
74
|
-
* **Thread safety:** Checkpoints are created synchronously on the main
|
|
75
|
-
* thread during evaluation. They are immutable after creation (Value is
|
|
76
|
-
* an immutable type), so no synchronization is needed.
|
|
77
|
-
*
|
|
78
|
-
* **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`
|
|
79
|
-
* to find the checkpoint just before the new viewport start, then call
|
|
80
|
-
* `restoreTo()` to set up the VM before evaluating only the visible lines.
|
|
81
|
-
* This is the key to O(visible lines) scrolling instead of O(document).
|
|
82
|
-
*/
|
|
83
|
-
declare class VMCheckpointer {
|
|
84
|
-
/** Ordered array of checkpoints (ascending lineNumber). */
|
|
85
|
-
private checkpoints;
|
|
86
|
-
/** The VM instance whose variables are snapshotted/restored. */
|
|
87
|
-
private vm;
|
|
88
|
-
constructor(vm: VM);
|
|
89
|
-
/**
|
|
90
|
-
* Create a checkpoint at the current line, recording the VM values of
|
|
91
|
-
* the specified variables.
|
|
92
|
-
*
|
|
93
|
-
* Uses prototypal inheritance: `Object.create(parent.variables)` so
|
|
94
|
-
* that inherited variable lookups fall through to previous checkpoints
|
|
95
|
-
* without copying all variables into each checkpoint.
|
|
96
|
-
*
|
|
97
|
-
* A line that is snapshotted again drops every checkpoint at or after it
|
|
98
|
-
* first, so the list stays in document order and the new checkpoint
|
|
99
|
-
* inherits from the line before it rather than from one after it. See the
|
|
100
|
-
* body for what went wrong without that.
|
|
101
|
-
*
|
|
102
|
-
* @param lineNumber 1-based line position.
|
|
103
|
-
* @param lineId Persistent line ID from DocumentModel.
|
|
104
|
-
* @param variableNames Names of variables that were written at this line.
|
|
105
|
-
* @returns The new checkpoint, or null if no variable names provided.
|
|
106
|
-
*/
|
|
107
|
-
snapshot(lineNumber: number, lineId: number, variableNames: string[]): VMCheckpoint | null;
|
|
108
|
-
/**
|
|
109
|
-
* Restore the VM to the state at or just after the given line number.
|
|
110
|
-
*
|
|
111
|
-
* Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,
|
|
112
|
-
* then replays all variable definitions from root → that checkpoint
|
|
113
|
-
* into the VM via `setVar()`. The VM's stack is also reset.
|
|
114
|
-
*
|
|
115
|
-
* If no checkpoint exists at or before the target line, the VM is
|
|
116
|
-
* fully reset (empty scope, empty stack).
|
|
117
|
-
*
|
|
118
|
-
* **Performance:** O(number of checkpoints × variables per checkpoint).
|
|
119
|
-
* With prototypal inheritance, `Object.keys()` on each checkpoint
|
|
120
|
-
* returns only the variables that were set at that checkpoint (not
|
|
121
|
-
* inherited ones), so the total work is O(total variable definitions
|
|
122
|
-
* in the document), which is < 100 for typical Obsidian documents.
|
|
123
|
-
*
|
|
124
|
-
* @param lineNumber Target 1-based line number. The VM will have the
|
|
125
|
-
* state that existed AFTER evaluating lines up to `lineNumber`.
|
|
126
|
-
*/
|
|
127
|
-
restoreTo(lineNumber: number): void;
|
|
128
|
-
/**
|
|
129
|
-
* Find the nearest checkpoint at or before the given line number.
|
|
130
|
-
*
|
|
131
|
-
* Uses linear scan (checkpoints are sorted by lineNumber and the list
|
|
132
|
-
* is short, typically < 20 for Obsidian documents). Can be upgraded
|
|
133
|
-
* to binary search if needed for documents with 1000+ variable defs.
|
|
134
|
-
*
|
|
135
|
-
* @returns The nearest checkpoint, or null if none exists before the line.
|
|
136
|
-
*/
|
|
137
|
-
getNearestCheckpoint(lineNumber: number): VMCheckpoint | null;
|
|
138
|
-
/**
|
|
139
|
-
* Get a specific checkpoint by its line number.
|
|
140
|
-
* @returns The checkpoint, or undefined if not found.
|
|
141
|
-
*/
|
|
142
|
-
getCheckpointAt(lineNumber: number): VMCheckpoint | undefined;
|
|
143
|
-
/**
|
|
144
|
-
* Get the entire checkpoint chain from root to the last checkpoint.
|
|
145
|
-
* Useful for debugging and serialization.
|
|
146
|
-
*/
|
|
147
|
-
getAllCheckpoints(): readonly VMCheckpoint[];
|
|
148
|
-
/**
|
|
149
|
-
* Look up a variable's value through the checkpoint chain.
|
|
150
|
-
*
|
|
151
|
-
* Walks the prototype chain starting from the most recent checkpoint,
|
|
152
|
-
* looking for the variable name as an own property. This is O(depth)
|
|
153
|
-
* where depth is the number of checkpoints since the variable was
|
|
154
|
-
* last set.
|
|
155
|
-
*
|
|
156
|
-
* **Note:** This queries the checkpointer's snapshot, not the VM.
|
|
157
|
-
* The VM may have been modified since the last snapshot (e.g., by
|
|
158
|
-
* Tier 2 execution of non-variable-def lines that don't create checkpoints).
|
|
159
|
-
*
|
|
160
|
-
* @returns The Value, or undefined if the variable was never set.
|
|
161
|
-
*/
|
|
162
|
-
lookupVariable(name: string): Value | undefined;
|
|
163
|
-
/**
|
|
164
|
-
* Clear all checkpoints. The underlying VM is NOT reset, call
|
|
165
|
-
* `vm.reset()` separately if needed.
|
|
166
|
-
*/
|
|
167
|
-
clear(): void;
|
|
168
|
-
/** Number of checkpoints stored. */
|
|
169
|
-
get count(): number;
|
|
170
|
-
/** Returns true if no checkpoints have been created. */
|
|
171
|
-
get isEmpty(): boolean;
|
|
172
|
-
/** The associated VM instance. */
|
|
173
|
-
get vmInstance(): VM;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export { type VMCheckpoint as V, VMCheckpointer as a };
|