@opengrid-ui/engine-wasm 0.0.0-stage → 0.1.25
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/LICENSE +21 -0
- package/dist/LICENSE +21 -0
- package/dist/engine/evaluate.d.ts +11 -0
- package/dist/engine/formula.test.d.ts +1 -0
- package/dist/engine/parser.d.ts +34 -0
- package/dist/engine/sheet.d.ts +7 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +7 -0
- package/dist/llms.txt +144 -0
- package/dist/opengrid.wasm +0 -0
- package/dist/skills/opengrid/SKILL.md +24 -0
- package/dist/wasm.d.ts +17 -0
- package/dist/worker/formula-protocol.d.ts +26 -0
- package/dist/worker/formula-session.d.ts +9 -0
- package/dist/worker/formula-session.test.d.ts +1 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.js +2 -0
- package/dist/worker.js.map +7 -0
- package/package.json +1 -6
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Han-wangyu and OpenGrid contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Han-wangyu and OpenGrid contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { CellValue } from '@opengrid-ui/core/engine';
|
|
2
|
+
import type { Ast } from './parser.js';
|
|
3
|
+
export type FormulaErrorCode = '#PARSE!' | '#REF!' | '#CYCLE!' | '#DIV/0!' | '#VALUE!' | '#N/A' | '#NAME?' | '#NUM!';
|
|
4
|
+
export declare class FormulaError extends Error {
|
|
5
|
+
readonly code: FormulaErrorCode;
|
|
6
|
+
constructor(code: FormulaErrorCode);
|
|
7
|
+
}
|
|
8
|
+
export type FormulaValue = CellValue | FormulaError;
|
|
9
|
+
type Read = (id: string) => FormulaValue;
|
|
10
|
+
export declare function evaluateFormula(ast: Ast, read: Read): FormulaValue;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { CellValue } from '@opengrid-ui/core/engine';
|
|
2
|
+
export type Ast = {
|
|
3
|
+
kind: 'literal';
|
|
4
|
+
value: CellValue;
|
|
5
|
+
} | {
|
|
6
|
+
kind: 'ref';
|
|
7
|
+
id: string;
|
|
8
|
+
} | {
|
|
9
|
+
kind: 'range';
|
|
10
|
+
start: string;
|
|
11
|
+
end: string;
|
|
12
|
+
} | {
|
|
13
|
+
kind: 'unary';
|
|
14
|
+
operator: '+' | '-';
|
|
15
|
+
node: Ast;
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'binary';
|
|
18
|
+
operator: string;
|
|
19
|
+
left: Ast;
|
|
20
|
+
right: Ast;
|
|
21
|
+
} | {
|
|
22
|
+
kind: 'call';
|
|
23
|
+
name: string;
|
|
24
|
+
args: Ast[];
|
|
25
|
+
};
|
|
26
|
+
export declare function normalizeCell(id: string): string;
|
|
27
|
+
export declare function cellCoordinates(id: string): {
|
|
28
|
+
column: number;
|
|
29
|
+
row: number;
|
|
30
|
+
};
|
|
31
|
+
export declare function cellNameAt(column: number, row: number): string;
|
|
32
|
+
export declare function rangeCells(start: string, end: string): string[][];
|
|
33
|
+
export declare function parseFormula(formula: string): Ast;
|
|
34
|
+
export declare function formulaDependencies(ast: Ast): Set<string>;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { CellValue } from '@opengrid-ui/core/engine';
|
|
2
|
+
import type { FormulaValue } from './evaluate.js';
|
|
3
|
+
export declare function createFormulaSheet(initial?: Readonly<Record<string, CellValue>>): {
|
|
4
|
+
get: (id: string) => FormulaValue;
|
|
5
|
+
apply: (changes: Readonly<Record<string, CellValue>>) => ReadonlyMap<string, FormulaValue>;
|
|
6
|
+
raw: (id: string) => string | number | boolean | null;
|
|
7
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createWasmEngine, createWasmSorter } from './wasm.js';
|
|
2
|
+
export type { WasmOptions } from './wasm.js';
|
|
3
|
+
export { createFormulaSheet } from './engine/sheet.js';
|
|
4
|
+
export { createFormulaSession } from './worker/formula-session.js';
|
|
5
|
+
export { FormulaError, evaluateFormula } from './engine/evaluate.js';
|
|
6
|
+
export type { FormulaErrorCode, FormulaValue } from './engine/evaluate.js';
|
|
7
|
+
export { parseFormula, formulaDependencies } from './engine/parser.js';
|
|
8
|
+
export type { Ast } from './engine/parser.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
async function L(e={}){let a=e.locateFile?.("opengrid.wasm")??new URL("./opengrid.wasm",import.meta.url);async function t(){let i=await fetch(a);if(!i.ok)throw new Error(`Could not load the OpenGrid WASM engine (${i.status})`);return i.arrayBuffer()}let n=(await WebAssembly.instantiate(e.bytes??await t())).instance.exports,o=new WeakMap,m=[],c={pointer:0,words:0};function u(i){return{pointer:n.og_allocate(i),words:i}}function f(i,y){let g=o.get(i);if(g===void 0){let A=u(i.length);g=A.pointer,o.set(i,g),m.push(A),new Float64Array(n.memory.buffer,g,i.length).set(i)}if(y?.size){let A=new Float64Array(n.memory.buffer,g,i.length);for(let[E,C]of y)A[E]=C}return g}function h(i){let y=Math.ceil(i.length/2);return c.words<y&&(c.words&&n.og_release(c.pointer,c.words),c=u(y)),new Uint32Array(n.memory.buffer,c.pointer,i.length).set(i),c.pointer}let l=(i,y,g,A)=>{if(!i.length)return i;let E=f(y,A);return n.og_sort_numeric(E,y.length,h(i),i.length,Number(g)),new Uint32Array(n.memory.buffer,c.pointer,i.length).slice()},d=(i,y,g,A)=>{if(!i.length||!g.length)return new Uint32Array;let E=f(y,A),C=u(g.length);try{new Float64Array(n.memory.buffer,C.pointer,g.length).set(g);let W=n.og_filter_numeric(E,y.length,h(i),i.length,C.pointer,g.length);return new Uint32Array(n.memory.buffer,c.pointer,W).slice()}finally{n.og_release(C.pointer,C.words)}};function s(i,y,g){if(i.length!==y.length||!Number.isInteger(g)||g<0||y.some(C=>C>=g))throw new Error("Invalid numeric group slots");if(!g||!i.length)return Array.from({length:g},()=>({count:0,sum:0,min:null,max:null}));let A=f(i),E=u(g*4);try{n.og_aggregate_numeric(A,h(y),i.length,E.pointer,g);let C=new Float64Array(n.memory.buffer,E.pointer,g*4);return Array.from({length:g},(W,I)=>{let[k,T,B,j]=C.subarray(I*4,I*4+4);return{count:k,sum:T,min:k?B:null,max:k?j:null}})}finally{n.og_release(E.pointer,E.words)}}function p(){for(let{pointer:i,words:y}of m)n.og_release(i,y);m.length=0,o=new WeakMap,c.words&&n.og_release(c.pointer,c.words),c={pointer:0,words:0}}return{sort:l,filter:d,aggregate:s,clear:p}}async function q(e,a){let t=await L(a),r=e(t.sort,t.filter);return{...r,async reset(n){await r.reset(n),t.clear()},dispose(){r.dispose(),t.clear()}}}var G=/^\$?[a-z]+\$?[1-9][0-9]*$/i,O={"=":1,"<>":1,"<":1,">":1,"<=":1,">=":1,"&":2,"+":3,"-":3,"*":4,"/":4,"^":6};function x(e){if(!G.test(e))throw new Error(`Invalid cell reference ${e}`);return e.replace(/\$/g,"").toUpperCase()}function V(e){let a=x(e),t=/^([A-Z]+)([0-9]+)$/.exec(a),r=0;for(let o of t[1])r=r*26+o.charCodeAt(0)-64;let n=Number(t[2]);if(n>1048576||r>16384)throw new Error(`Cell reference out of range ${e}`);return{column:r,row:n}}function Z(e,a){let t="";for(let r=e;r>0;r=Math.floor((r-1)/26))t=String.fromCharCode(65+(r-1)%26)+t;return t+String(a)}function S(e,a){let t=V(e),r=V(a),n=Math.min(t.column,r.column),o=Math.max(t.column,r.column),m=Math.min(t.row,r.row),c=Math.max(t.row,r.row);if((c-m+1)*(o-n+1)>1e6)throw new Error("Formula range exceeds one million cells");return Array.from({length:c-m+1},(u,f)=>Array.from({length:o-n+1},(h,l)=>Z(l+n,f+m)))}function R(e){let a=e.startsWith("=")?e.slice(1):e,t=/\s*(?:(\d+(?:\.\d*)?|\.\d+)([eE][+-]?\d+)?|("(?:[^"]|"")*")|(\$?[a-z][a-z0-9_.$]*)|(<=|>=|<>|[-+*/^&=<>:,()]))/iy,r=[];for(let l=0;l<a.length&&a.slice(l).trim()!=="";){t.lastIndex=l;let d=t.exec(a);if(!d)throw new Error(`Invalid formula token at ${l+1}`);let[,s,p,i,y,g]=d;r.push(s?s+(p??""):i??y??g),l=t.lastIndex}let n=0,o=()=>r[n],m=()=>r[n++];function c(l){if(m()!==l)throw new Error(`Expected ${l}`)}function u(){let l=m();if(!l)throw new Error("Expected an expression");if(l==="+"||l==="-")return{kind:"unary",operator:l,node:f(5)};if(l==="("){let p=f(0);return c(")"),p}if(l.startsWith('"'))return{kind:"literal",value:l.slice(1,-1).replace(/""/g,'"')};if(/^[\d.]/.test(l))return{kind:"literal",value:Number(l)};let d=l.toUpperCase();if(d==="TRUE"||d==="FALSE")return{kind:"literal",value:d==="TRUE"};if(o()==="("&&/^[A-Z_][A-Z0-9_.]*$/.test(d)){m();let p=[];if(o()!==")")do{if(p.push(f(0)),o()!==",")break;m()}while(!0);return c(")"),{kind:"call",name:d,args:p}}let s=x(d);return o()===":"?(m(),{kind:"range",start:s,end:x(m()??"")}):{kind:"ref",id:s}}function f(l){let d=u();for(;o()&&(O[o()]??-1)>=l;){let s=m(),p=O[s];d={kind:"binary",operator:s,left:d,right:f(p+(s==="^"?0:1))}}return d}let h=f(0);if(n!==r.length)throw new Error(`Unexpected token ${o()}`);return h}function v(e){let a=new Set;function t(r){switch(r.kind){case"ref":a.add(r.id);return;case"range":S(r.start,r.end).forEach(n=>n.forEach(o=>a.add(o)));return;case"unary":t(r.node);return;case"binary":t(r.left),t(r.right);return;case"call":r.args.forEach(t);return;case"literal":return}}return t(e),a}var w=class extends Error{constructor(t){super(t);this.code=t}},F=e=>{throw new w(e)},b=e=>{if(e instanceof w)throw e;return Array.isArray(e)?F("#VALUE!"):e},M=e=>{let a=Number(b(e));return Number.isFinite(a)?a:F("#VALUE!")},$=e=>String(b(e)??"");function X(e,a,t){if(e==="&")return $(a)+$(t);if(e==="="||e==="<>")return b(a)===b(t)==(e==="=");if(["<","<=",">",">="].includes(e)){let m=b(a),c=b(t),u=typeof m=="number"&&typeof c=="number"?m-c:String(m??"").localeCompare(String(c??""));return e==="<"?u<0:e==="<="?u<=0:e===">"?u>0:u>=0}let r=M(a),n=M(t),o;switch(e){case"+":o=r+n;break;case"-":o=r-n;break;case"*":o=r*n;break;case"/":if(n===0)return F("#DIV/0!");o=r/n;break;case"^":o=r**n;break;default:return F("#PARSE!")}return Number.isFinite(o)?o:F("#NUM!")}function P(e){return e.flatMap(a=>Array.isArray(a)?a.flat().map(b):[b(a)])}function Y(e,a){if(e==="CONCAT")return P(a).map(n=>n??"").join("");if(e==="ROUND"){let[n=null,o=0]=a,m=M(n),c=Math.trunc(M(o));if(c<-15||c>15)return F("#NUM!");let u=10**c;return Math.sign(m)*Math.round(Math.abs(m)*u)/u}if(e==="VLOOKUP"){let[n=null,o,m=1,c=!1]=a;if(!Array.isArray(o)||b(c))return F("#VALUE!");let u=M(m)-1;if(!Number.isInteger(u)||u<0||u>=(o[0]?.length??0))return F("#REF!");let f=o.find(h=>b(h[0]??null)===b(n));return f?b(f[u]??null):F("#N/A")}if(!["SUM","AVG","AVERAGE","MIN","MAX","COUNT"].includes(e))return F("#NAME?");let t=P(a).filter(n=>typeof n=="number");if(e==="COUNT")return t.length;if(e==="MIN")return t.length?t.reduce((n,o)=>Math.min(n,o)):0;if(e==="MAX")return t.length?t.reduce((n,o)=>Math.max(n,o)):0;let r=t.reduce((n,o)=>n+o,0);return e==="SUM"?r:t.length?r/t.length:F("#DIV/0!")}function _(e,a){function t(r){switch(r.kind){case"literal":return r.value;case"ref":return a(r.id);case"range":return S(r.start,r.end).map(n=>n.map(a));case"unary":return(r.operator==="-"?-1:1)*M(t(r.node));case"binary":return X(r.operator,t(r.left),t(r.right));case"call":{if(r.name==="IF"){let[n,o,m]=r.args;return!n||!o?F("#VALUE!"):b(t(n))?t(o):m?t(m):!1}return Y(r.name,r.args.map(t))}}}try{return b(t(e))}catch(r){return r instanceof w?r:new w("#REF!")}}function N(e){let a=new Map,t=new Map,r=new Map;function n(u){if(typeof u!="string"||!u.startsWith("="))return{value:u,dependencies:new Set};try{let f=R(u),h=v(f);return h.forEach(V),{value:u,formula:f,dependencies:h}}catch{return{value:u,error:new w("#PARSE!"),dependencies:new Set}}}function o(u,f){if(f.has(u))return new w("#CYCLE!");let h=r.get(u);if(h!==void 0)return h;let l=a.get(u);if(!l)return null;f.add(u);let d=l.error??(l.formula?_(l.formula,s=>o(s,f)):l.value);return f.delete(u),r.set(u,d),d}function m(u){let f=x(u);return V(f),o(f,new Set)}function c(u){let f=Object.entries(u).map(([l,d])=>{let s=x(l);return V(s),{id:s,entry:n(d)}});for(let{id:l,entry:d}of f){for(let s of a.get(l)?.dependencies??[]){let p=t.get(s);p?.delete(l),p?.size===0&&t.delete(s)}for(let s of d.dependencies){let p=t.get(s);p||t.set(s,p=new Set),p.add(l)}a.set(l,d)}let h=new Set(f.map(l=>l.id));for(let l of h)r.delete(l),t.get(l)?.forEach(d=>h.add(d));return new Map([...h].map(l=>[l,o(l,new Set)]))}return e&&c(e),{get:m,apply:c,raw:u=>a.get(x(u))?.value??null}}function z(e){return e instanceof w?{error:e.code}:e}function U(e){return e!==null&&typeof e=="object"?new w(e.error):e}function D(e,{changes:a,read:t}){let r=a?[...e.apply(a)].map(([o,m])=>[o,z(m)]):[],n=t?z(t.raw?e.raw(t.id):e.get(t.id)):null;return{ok:!0,changed:r,value:n}}function K(e,a,t){return new Promise((r,n)=>{function o(){e.removeEventListener("message",m),e.removeEventListener("error",c),e.removeEventListener("messageerror",c),t.removeEventListener("abort",u)}function m({data:f}){o(),r(f)}function c(f){o(),n(f)}function u(){o(),n(t.reason)}e.addEventListener("message",m),e.addEventListener("error",c),e.addEventListener("messageerror",c),t.addEventListener("abort",u,{once:!0});try{e.postMessage(a)}catch(f){o(),n(f)}})}function H(e){let a={...e},t=new Map,r=new AbortController,n,o,m=typeof Worker>"u",c=!1,u=Promise.resolve();function f(){n?.terminate(),n=void 0,m=!0}function h(){let s=new Worker(new URL("./worker.js",import.meta.url),{type:"module",name:"opengrid-formulas"});function p(){queueMicrotask(()=>{n===s&&f()})}return s.addEventListener("error",p),s.addEventListener("messageerror",p),s}async function l(s){let p;if(!m)try{n??(n=h()),p=await K(n,c?s:{...s,initial:a},r.signal),p.ok&&(c=!0)}catch(i){if(r.signal.aborted)throw i;f()}if(p||(o||(o=N(a),t.size&&o.apply(Object.fromEntries(t)),t.clear()),p=D(o,s)),!p.ok)throw new Error(p.message);if(!o&&s.changes)for(let[i,y]of Object.entries(s.changes))t.set(x(i),y);return p}function d(s){let p=u.then(()=>{if(r.signal.aborted)throw r.signal.reason;return l(s)});return u=p.then(()=>{},()=>{}),p}return{async apply(s){let{changed:p}=await d({changes:{...s}});return new Map(p.map(([i,y])=>[i,U(y)]))},async get(s){return U((await d({read:{id:s,raw:!1}})).value)},async raw(s){return(await d({read:{id:s,raw:!0}})).value},dispose(){r.abort(),n?.terminate(),n=void 0}}}export{w as FormulaError,H as createFormulaSession,N as createFormulaSheet,q as createWasmEngine,L as createWasmSorter,_ as evaluateFormula,v as formulaDependencies,R as parseFormula};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/wasm.ts", "../src/engine/parser.ts", "../src/engine/evaluate.ts", "../src/engine/sheet.ts", "../src/worker/formula-protocol.ts", "../src/worker/formula-session.ts"],
|
|
4
|
+
"sourcesContent": ["import type { ComputeEngine, NumericFilter, NumericSort } from '@opengrid-ui/core/engine';\n\ninterface WasmExports extends WebAssembly.Exports {\n memory: WebAssembly.Memory;\n og_allocate(words: number): number;\n og_release(pointer: number, words: number): void;\n og_sort_numeric(values: number, size: number, indices: number, count: number, desc: number): void;\n og_filter_numeric(values: number, size: number, indices: number, count: number, accepted: number, acceptedCount: number): number;\n og_aggregate_numeric(values: number, keys: number, length: number, output: number, groups: number): void;\n}\n\nexport interface WasmOptions {\n locateFile?: (name: string) => URL | string;\n bytes?: ArrayBuffer;\n}\n\nexport async function createWasmSorter(options: WasmOptions = {}) {\n const url = options.locateFile?.('opengrid.wasm') ?? new URL('./opengrid.wasm', import.meta.url);\n async function load(): Promise<ArrayBuffer> {\n const response = await fetch(url);\n if (!response.ok) throw new Error(`Could not load the OpenGrid WASM engine (${response.status})`);\n return response.arrayBuffer();\n }\n const module = await WebAssembly.instantiate(options.bytes ?? await load());\n const api = module.instance.exports as WasmExports;\n let columns = new WeakMap<Float64Array | Int32Array, number>();\n const allocations: { pointer: number; words: number }[] = [];\n let scratch = { pointer: 0, words: 0 };\n\n function allocate(words: number) {\n return { pointer: api.og_allocate(words), words };\n }\n\n function columnPointer(values: Float64Array | Int32Array, edits?: ReadonlyMap<number, number>) {\n let pointer = columns.get(values);\n if (pointer === undefined) {\n const buffer = allocate(values.length);\n pointer = buffer.pointer;\n columns.set(values, pointer);\n allocations.push(buffer);\n new Float64Array(api.memory.buffer, pointer, values.length).set(values);\n }\n if (edits?.size) {\n const column = new Float64Array(api.memory.buffer, pointer, values.length);\n for (const [slot, value] of edits) column[slot] = value;\n }\n return pointer;\n }\n\n function orderPointer(indices: Uint32Array) {\n const words = Math.ceil(indices.length / 2);\n if (scratch.words < words) {\n if (scratch.words) api.og_release(scratch.pointer, scratch.words);\n scratch = allocate(words);\n }\n new Uint32Array(api.memory.buffer, scratch.pointer, indices.length).set(indices);\n return scratch.pointer;\n }\n\n const sort: NumericSort = (indices, values, desc, edits) => {\n if (!indices.length) return indices;\n const pointer = columnPointer(values, edits);\n api.og_sort_numeric(pointer, values.length, orderPointer(indices), indices.length, Number(desc));\n return new Uint32Array(api.memory.buffer, scratch.pointer, indices.length).slice();\n };\n\n const filter: NumericFilter = (indices, values, accepted, edits) => {\n if (!indices.length || !accepted.length) return new Uint32Array();\n const pointer = columnPointer(values, edits);\n const targets = allocate(accepted.length);\n try {\n new Float64Array(api.memory.buffer, targets.pointer, accepted.length).set(accepted);\n const count = api.og_filter_numeric(pointer, values.length, orderPointer(indices), indices.length, targets.pointer, accepted.length);\n return new Uint32Array(api.memory.buffer, scratch.pointer, count).slice();\n } finally { api.og_release(targets.pointer, targets.words); }\n };\n\n function aggregate(values: Float64Array | Int32Array, keys: Uint32Array, groups: number) {\n if (values.length !== keys.length || !Number.isInteger(groups) || groups < 0 || keys.some(key => key >= groups)) {\n throw new Error('Invalid numeric group slots');\n }\n if (!groups || !values.length) return Array.from({ length: groups }, () => ({ count: 0, sum: 0, min: null, max: null }));\n const pointer = columnPointer(values);\n const output = allocate(groups * 4);\n try {\n api.og_aggregate_numeric(pointer, orderPointer(keys), values.length, output.pointer, groups);\n const results = new Float64Array(api.memory.buffer, output.pointer, groups * 4);\n return Array.from({ length: groups }, (_, index) => {\n const [count, sum, min, max] = results.subarray(index * 4, index * 4 + 4);\n return { count: count!, sum: sum!, min: count ? min! : null, max: count ? max! : null };\n });\n } finally { api.og_release(output.pointer, output.words); }\n }\n\n function clear() {\n for (const { pointer, words } of allocations) api.og_release(pointer, words);\n allocations.length = 0;\n columns = new WeakMap();\n if (scratch.words) api.og_release(scratch.pointer, scratch.words);\n scratch = { pointer: 0, words: 0 };\n }\n return { sort, filter, aggregate, clear };\n}\n\nexport async function createWasmEngine(\n createEngine: (sort: NumericSort, filter: NumericFilter) => ComputeEngine,\n options?: WasmOptions,\n): Promise<ComputeEngine> {\n const wasm = await createWasmSorter(options);\n const engine = createEngine(wasm.sort, wasm.filter);\n return {\n ...engine,\n async reset(dataset) { await engine.reset(dataset); wasm.clear(); },\n dispose() { engine.dispose(); wasm.clear(); },\n };\n}\n", "import type { CellValue } from '@opengrid-ui/core/engine';\n\nexport type Ast =\n | { kind: 'literal'; value: CellValue }\n | { kind: 'ref'; id: string }\n | { kind: 'range'; start: string; end: string }\n | { kind: 'unary'; operator: '+' | '-'; node: Ast }\n | { kind: 'binary'; operator: string; left: Ast; right: Ast }\n | { kind: 'call'; name: string; args: Ast[] };\n\nconst cellName = /^\\$?[a-z]+\\$?[1-9][0-9]*$/i;\nconst operatorPrecedence: Readonly<Record<string, number>> = {\n '=': 1, '<>': 1, '<': 1, '>': 1, '<=': 1, '>=': 1,\n '&': 2, '+': 3, '-': 3, '*': 4, '/': 4, '^': 6,\n};\n\nexport function normalizeCell(id: string) {\n if (!cellName.test(id)) throw new Error(`Invalid cell reference ${id}`);\n return id.replace(/\\$/g, '').toUpperCase();\n}\n\nexport function cellCoordinates(id: string) {\n const name = normalizeCell(id);\n const parts = /^([A-Z]+)([0-9]+)$/.exec(name)!;\n let column = 0;\n for (const letter of parts[1]!) column = column * 26 + letter.charCodeAt(0) - 64;\n const row = Number(parts[2]);\n if (row > 1_048_576 || column > 16_384) throw new Error(`Cell reference out of range ${id}`);\n return { column, row };\n}\n\nexport function cellNameAt(column: number, row: number) {\n let name = '';\n for (let rest = column; rest > 0; rest = Math.floor((rest - 1) / 26)) {\n name = String.fromCharCode(65 + (rest - 1) % 26) + name;\n }\n return name + String(row);\n}\n\nexport function rangeCells(start: string, end: string): string[][] {\n const a = cellCoordinates(start);\n const b = cellCoordinates(end);\n const left = Math.min(a.column, b.column);\n const right = Math.max(a.column, b.column);\n const top = Math.min(a.row, b.row);\n const bottom = Math.max(a.row, b.row);\n if ((bottom - top + 1) * (right - left + 1) > 1_000_000) throw new Error('Formula range exceeds one million cells');\n return Array.from({ length: bottom - top + 1 }, (_, row) =>\n Array.from({ length: right - left + 1 }, (_, column) => cellNameAt(column + left, row + top)),\n );\n}\n\nexport function parseFormula(formula: string): Ast {\n const text = formula.startsWith('=') ? formula.slice(1) : formula;\n const tokens = /\\s*(?:(\\d+(?:\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?|(\"(?:[^\"]|\"\")*\")|(\\$?[a-z][a-z0-9_.$]*)|(<=|>=|<>|[-+*/^&=<>:,()]))/iy;\n const parts: string[] = [];\n for (let cursor = 0; cursor < text.length;) {\n if (text.slice(cursor).trim() === '') break;\n tokens.lastIndex = cursor;\n const match = tokens.exec(text);\n if (!match) throw new Error(`Invalid formula token at ${cursor + 1}`);\n const [, integer, exponent, quoted, name, symbol] = match;\n parts.push(integer ? integer + (exponent ?? '') : quoted ?? name ?? symbol!);\n cursor = tokens.lastIndex;\n }\n let index = 0;\n const current = () => parts[index];\n const take = () => parts[index++];\n function consume(expected: string) {\n if (take() !== expected) throw new Error(`Expected ${expected}`);\n }\n function prefix(): Ast {\n const token = take();\n if (!token) throw new Error('Expected an expression');\n if (token === '+' || token === '-') return { kind: 'unary', operator: token, node: expression(5) };\n if (token === '(') {\n const value = expression(0);\n consume(')');\n return value;\n }\n if (token.startsWith('\"')) return { kind: 'literal', value: token.slice(1, -1).replace(/\"\"/g, '\"') };\n if (/^[\\d.]/.test(token)) return { kind: 'literal', value: Number(token) };\n const name = token.toUpperCase();\n if (name === 'TRUE' || name === 'FALSE') return { kind: 'literal', value: name === 'TRUE' };\n if (current() === '(' && /^[A-Z_][A-Z0-9_.]*$/.test(name)) {\n take();\n const args: Ast[] = [];\n if (current() !== ')') {\n do {\n args.push(expression(0));\n if (current() !== ',') break;\n take();\n } while (true);\n }\n consume(')');\n return { kind: 'call', name, args };\n }\n const id = normalizeCell(name);\n if (current() === ':') {\n take();\n return { kind: 'range', start: id, end: normalizeCell(take() ?? '') };\n }\n return { kind: 'ref', id };\n }\n function expression(min: number): Ast {\n let node = prefix();\n while (current() && (operatorPrecedence[current()!] ?? -1) >= min) {\n const operator = take()!;\n const precedence = operatorPrecedence[operator]!;\n node = { kind: 'binary', operator, left: node, right: expression(precedence + (operator === '^' ? 0 : 1)) };\n }\n return node;\n }\n const root = expression(0);\n if (index !== parts.length) throw new Error(`Unexpected token ${current()}`);\n return root;\n}\n\nexport function formulaDependencies(ast: Ast): Set<string> {\n const result = new Set<string>();\n function visit(node: Ast) {\n switch (node.kind) {\n case 'ref': result.add(node.id); return;\n case 'range': rangeCells(node.start, node.end).forEach(row => row.forEach(id => result.add(id))); return;\n case 'unary': visit(node.node); return;\n case 'binary': visit(node.left); visit(node.right); return;\n case 'call': node.args.forEach(visit); return;\n case 'literal': return;\n }\n }\n visit(ast);\n return result;\n}\n", "import type { CellValue } from '@opengrid-ui/core/engine';\nimport { rangeCells } from './parser';\nimport type { Ast } from './parser';\n\nexport type FormulaErrorCode = '#PARSE!' | '#REF!' | '#CYCLE!' | '#DIV/0!' | '#VALUE!' | '#N/A' | '#NAME?' | '#NUM!';\nexport class FormulaError extends Error {\n constructor(readonly code: FormulaErrorCode) { super(code); }\n}\n\nexport type FormulaValue = CellValue | FormulaError;\ntype FormulaInput = FormulaValue | FormulaValue[][];\ntype Read = (id: string) => FormulaValue;\nconst fault = (code: FormulaErrorCode): never => { throw new FormulaError(code); };\nconst scalar = (value: FormulaInput): CellValue => {\n if (value instanceof FormulaError) throw value;\n if (Array.isArray(value)) return fault('#VALUE!');\n return value;\n};\nconst numeric = (value: FormulaInput): number => {\n const result = Number(scalar(value));\n if (!Number.isFinite(result)) return fault('#VALUE!');\n return result;\n};\nconst render = (value: FormulaInput): string => String(scalar(value) ?? '');\n\nfunction calculation(operator: string, left: FormulaInput, right: FormulaInput): CellValue {\n if (operator === '&') return render(left) + render(right);\n if (operator === '=' || operator === '<>') return (scalar(left) === scalar(right)) === (operator === '=');\n if (['<', '<=', '>', '>='].includes(operator)) {\n const a = scalar(left);\n const b = scalar(right);\n const diff = typeof a === 'number' && typeof b === 'number' ? a - b : String(a ?? '').localeCompare(String(b ?? ''));\n if (operator === '<') return diff < 0;\n if (operator === '<=') return diff <= 0;\n if (operator === '>') return diff > 0;\n return diff >= 0;\n }\n const a = numeric(left);\n const b = numeric(right);\n let result: number;\n switch (operator) {\n case '+': result = a + b; break;\n case '-': result = a - b; break;\n case '*': result = a * b; break;\n case '/': if (b === 0) return fault('#DIV/0!'); result = a / b; break;\n case '^': result = a ** b; break;\n default: return fault('#PARSE!');\n }\n return Number.isFinite(result) ? result : fault('#NUM!');\n}\n\nfunction flat(args: FormulaInput[]): CellValue[] {\n return args.flatMap(arg => Array.isArray(arg) ? arg.flat().map(scalar) : [scalar(arg)]);\n}\n\nfunction call(name: string, args: FormulaInput[]): FormulaValue {\n if (name === 'CONCAT') return flat(args).map(value => value ?? '').join('');\n if (name === 'ROUND') {\n const [value = null, digits = 0] = args;\n const number = numeric(value);\n const precision = Math.trunc(numeric(digits));\n if (precision < -15 || precision > 15) return fault('#NUM!');\n const multiplier = 10 ** precision;\n return Math.sign(number) * Math.round(Math.abs(number) * multiplier) / multiplier;\n }\n if (name === 'VLOOKUP') {\n const [needle = null, table, column = 1, approximate = false] = args;\n if (!Array.isArray(table) || scalar(approximate)) return fault('#VALUE!');\n const index = numeric(column) - 1;\n if (!Number.isInteger(index) || index < 0 || index >= (table[0]?.length ?? 0)) return fault('#REF!');\n const match = table.find(row => scalar(row[0] ?? null) === scalar(needle));\n return match ? scalar(match[index] ?? null) : fault('#N/A');\n }\n if (!['SUM', 'AVG', 'AVERAGE', 'MIN', 'MAX', 'COUNT'].includes(name)) return fault('#NAME?');\n const values = flat(args).filter((value): value is number => typeof value === 'number');\n if (name === 'COUNT') return values.length;\n if (name === 'MIN') return values.length ? values.reduce((a, b) => Math.min(a, b)) : 0;\n if (name === 'MAX') return values.length ? values.reduce((a, b) => Math.max(a, b)) : 0;\n const sum = values.reduce((total, value) => total + value, 0);\n if (name === 'SUM') return sum;\n return values.length ? sum / values.length : fault('#DIV/0!');\n}\n\nexport function evaluateFormula(ast: Ast, read: Read): FormulaValue {\n function evaluate(node: Ast): FormulaInput {\n switch (node.kind) {\n case 'literal': return node.value;\n case 'ref': return read(node.id);\n case 'range': return rangeCells(node.start, node.end).map(row => row.map(read));\n case 'unary': return (node.operator === '-' ? -1 : 1) * numeric(evaluate(node.node));\n case 'binary': return calculation(node.operator, evaluate(node.left), evaluate(node.right));\n case 'call': {\n if (node.name === 'IF') {\n const [condition, yes, no] = node.args;\n if (!condition || !yes) return fault('#VALUE!');\n return scalar(evaluate(condition)) ? evaluate(yes) : no ? evaluate(no) : false;\n }\n return call(node.name, node.args.map(evaluate));\n }\n }\n }\n try { return scalar(evaluate(ast)); }\n catch (error) { return error instanceof FormulaError ? error : new FormulaError('#REF!'); }\n}\n", "import type { CellValue } from '@opengrid-ui/core/engine';\nimport { evaluateFormula, FormulaError } from './evaluate';\nimport type { FormulaValue } from './evaluate';\nimport { cellCoordinates, formulaDependencies, normalizeCell, parseFormula } from './parser';\nimport type { Ast } from './parser';\n\ninterface Entry { value: CellValue; formula?: Ast; error?: FormulaError; dependencies: Set<string> }\n\nexport function createFormulaSheet(initial?: Readonly<Record<string, CellValue>>) {\n const entries = new Map<string, Entry>();\n const reverse = new Map<string, Set<string>>();\n const results = new Map<string, FormulaValue>();\n\n function compile(value: CellValue): Entry {\n if (typeof value !== 'string' || !value.startsWith('=')) return { value, dependencies: new Set() };\n try {\n const formula = parseFormula(value);\n const dependencies = formulaDependencies(formula);\n dependencies.forEach(cellCoordinates);\n return { value, formula, dependencies };\n } catch {\n return { value, error: new FormulaError('#PARSE!'), dependencies: new Set() };\n }\n }\n\n function evaluate(id: string, visited: Set<string>): FormulaValue {\n if (visited.has(id)) return new FormulaError('#CYCLE!');\n const cached = results.get(id);\n if (cached !== undefined) return cached;\n const entry = entries.get(id);\n if (!entry) return null;\n visited.add(id);\n const value = entry.error ?? (entry.formula ? evaluateFormula(entry.formula, dependency => evaluate(dependency, visited)) : entry.value);\n visited.delete(id);\n results.set(id, value);\n return value;\n }\n\n function get(id: string): FormulaValue {\n const value = normalizeCell(id);\n cellCoordinates(value);\n return evaluate(value, new Set());\n }\n\n function apply(changes: Readonly<Record<string, CellValue>>): ReadonlyMap<string, FormulaValue> {\n const additions = Object.entries(changes).map(([key, value]) => {\n const id = normalizeCell(key);\n cellCoordinates(id);\n return { id, entry: compile(value) };\n });\n for (const { id, entry } of additions) {\n for (const dependency of entries.get(id)?.dependencies ?? []) {\n const consumedBy = reverse.get(dependency);\n consumedBy?.delete(id);\n if (consumedBy?.size === 0) reverse.delete(dependency);\n }\n for (const dependency of entry.dependencies) {\n let consumedBy = reverse.get(dependency);\n if (!consumedBy) reverse.set(dependency, consumedBy = new Set());\n consumedBy.add(id);\n }\n entries.set(id, entry);\n }\n const dirty = new Set(additions.map(change => change.id));\n for (const id of dirty) {\n results.delete(id);\n reverse.get(id)?.forEach(dependent => dirty.add(dependent));\n }\n return new Map([...dirty].map(id => [id, evaluate(id, new Set())]));\n }\n\n if (initial) apply(initial);\n return { get, apply, raw: (id: string) => entries.get(normalizeCell(id))?.value ?? null };\n}\n", "import type { CellValue } from '@opengrid-ui/core/engine';\nimport { FormulaError } from '../engine/evaluate';\nimport type { FormulaErrorCode, FormulaValue } from '../engine/evaluate';\nimport type { createFormulaSheet } from '../engine/sheet';\n\nexport type FormulaCells = Readonly<Record<string, CellValue>>;\ntype WireValue = CellValue | { error: FormulaErrorCode };\n\nexport interface FormulaCommand {\n initial?: FormulaCells;\n changes?: FormulaCells;\n read?: { id: string; raw: boolean };\n}\n\nexport type FormulaReply = {\n ok: true;\n changed: readonly (readonly [string, WireValue])[];\n value: WireValue;\n} | { ok: false; message: string };\n\nfunction encode(value: FormulaValue): WireValue {\n return value instanceof FormulaError ? { error: value.code } : value;\n}\n\nexport function decodeFormulaValue(value: WireValue): FormulaValue {\n return value !== null && typeof value === 'object' ? new FormulaError(value.error) : value;\n}\n\nexport function executeFormula(sheet: ReturnType<typeof createFormulaSheet>, { changes, read }: FormulaCommand): FormulaReply {\n const changed = changes ? [...sheet.apply(changes)].map(([id, value]) => [id, encode(value)] as const) : [];\n const value = read ? encode(read.raw ? sheet.raw(read.id) : sheet.get(read.id)) : null;\n return { ok: true, changed, value };\n}\n", "import type { CellValue } from '@opengrid-ui/core/engine';\nimport { normalizeCell } from '../engine/parser';\nimport type { FormulaValue } from '../engine/evaluate';\nimport { createFormulaSheet } from '../engine/sheet';\nimport { decodeFormulaValue, executeFormula } from './formula-protocol';\nimport type { FormulaCells, FormulaCommand, FormulaReply } from './formula-protocol';\n\nfunction exchange(worker: Worker, command: FormulaCommand, signal: AbortSignal): Promise<FormulaReply> {\n return new Promise((resolve, reject) => {\n function cleanup() {\n worker.removeEventListener('message', receive);\n worker.removeEventListener('error', fail);\n worker.removeEventListener('messageerror', fail);\n signal.removeEventListener('abort', abort);\n }\n function receive({ data }: MessageEvent<FormulaReply>) {\n cleanup();\n resolve(data);\n }\n function fail(error: Event) {\n cleanup();\n reject(error);\n }\n function abort() {\n cleanup();\n reject(signal.reason);\n }\n worker.addEventListener('message', receive);\n worker.addEventListener('error', fail);\n worker.addEventListener('messageerror', fail);\n signal.addEventListener('abort', abort, { once: true });\n try {\n worker.postMessage(command);\n } catch (error) {\n cleanup();\n reject(error);\n }\n });\n}\n\nexport function createFormulaSession(initial?: FormulaCells) {\n const seed = { ...initial };\n const confirmed = new Map<string, CellValue>();\n const lifetime = new AbortController();\n let worker: Worker | undefined;\n let local: ReturnType<typeof createFormulaSheet> | undefined;\n let fallback = typeof Worker === 'undefined';\n let started = false;\n let tail = Promise.resolve();\n\n function useLocal() {\n worker?.terminate();\n worker = undefined;\n fallback = true;\n }\n\n function launch() {\n const next = new Worker(new URL('./worker.js', import.meta.url), { type: 'module', name: 'opengrid-formulas' });\n function failed() {\n queueMicrotask(() => { if (worker === next) useLocal(); });\n }\n next.addEventListener('error', failed);\n next.addEventListener('messageerror', failed);\n return next;\n }\n\n async function run(command: FormulaCommand) {\n let reply: FormulaReply | undefined;\n if (!fallback) {\n try {\n worker ??= launch();\n reply = await exchange(worker, started ? command : { ...command, initial: seed }, lifetime.signal);\n if (reply.ok) started = true;\n } catch (error) {\n if (lifetime.signal.aborted) throw error;\n useLocal();\n }\n }\n if (!reply) {\n if (!local) {\n local = createFormulaSheet(seed);\n if (confirmed.size) local.apply(Object.fromEntries(confirmed));\n confirmed.clear();\n }\n reply = executeFormula(local, command);\n }\n if (!reply.ok) throw new Error(reply.message);\n if (!local && command.changes) {\n for (const [id, value] of Object.entries(command.changes)) confirmed.set(normalizeCell(id), value);\n }\n return reply;\n }\n\n function enqueue(command: FormulaCommand) {\n const result = tail.then(() => {\n if (lifetime.signal.aborted) throw lifetime.signal.reason;\n return run(command);\n });\n tail = result.then(() => {}, () => {});\n return result;\n }\n\n return {\n async apply(changes: FormulaCells): Promise<ReadonlyMap<string, FormulaValue>> {\n const { changed } = await enqueue({ changes: { ...changes } });\n return new Map(changed.map(([id, value]) => [id, decodeFormulaValue(value)]));\n },\n async get(id: string) {\n return decodeFormulaValue((await enqueue({ read: { id, raw: false } })).value);\n },\n async raw(id: string) {\n return (await enqueue({ read: { id, raw: true } })).value as CellValue;\n },\n dispose() {\n lifetime.abort();\n worker?.terminate();\n worker = undefined;\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AAgBA,eAAsBA,EAAiBC,EAAuB,CAAC,EAAG,CAChE,IAAMC,EAAMD,EAAQ,aAAa,eAAe,GAAK,IAAI,IAAI,kBAAmB,YAAY,GAAG,EAC/F,eAAeE,GAA6B,CAC1C,IAAMC,EAAW,MAAM,MAAMF,CAAG,EAChC,GAAI,CAACE,EAAS,GAAI,MAAM,IAAI,MAAM,4CAA4CA,EAAS,MAAM,GAAG,EAChG,OAAOA,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,CAAE,QAAS,CAAE,GAAGE,CAAQ,CAAE,CAAC,EAC7D,OAAO,IAAI,IAAIC,EAAQ,IAAI,CAAC,CAACN,EAAIC,CAAK,IAAM,CAACD,EAAIO,EAAmBN,CAAK,CAAC,CAAC,CAAC,CAC9E,EACA,MAAM,IAAID,EAAY,CACpB,OAAOO,GAAoB,MAAMJ,EAAQ,CAAE,KAAM,CAAE,GAAAH,EAAI,IAAK,EAAM,CAAE,CAAC,GAAG,KAAK,CAC/E,EACA,MAAM,IAAIA,EAAY,CACpB,OAAQ,MAAMG,EAAQ,CAAE,KAAM,CAAE,GAAAH,EAAI,IAAK,EAAK,CAAE,CAAC,GAAG,KACtD,EACA,SAAU,CACRb,EAAS,MAAM,EACff,GAAQ,UAAU,EAClBA,EAAS,MACX,CACF,CACF",
|
|
6
|
+
"names": ["createWasmSorter", "options", "url", "load", "response", "api", "columns", "allocations", "scratch", "allocate", "words", "columnPointer", "values", "edits", "pointer", "buffer", "column", "slot", "value", "orderPointer", "indices", "sort", "desc", "filter", "accepted", "targets", "count", "aggregate", "keys", "groups", "key", "output", "results", "_", "index", "sum", "min", "max", "clear", "createWasmEngine", "createEngine", "wasm", "engine", "dataset", "cellName", "operatorPrecedence", "normalizeCell", "id", "cellCoordinates", "name", "parts", "column", "letter", "row", "cellNameAt", "rest", "rangeCells", "start", "end", "a", "b", "left", "right", "top", "bottom", "_", "parseFormula", "formula", "text", "tokens", "cursor", "match", "integer", "exponent", "quoted", "symbol", "index", "current", "take", "consume", "expected", "prefix", "token", "expression", "value", "args", "min", "node", "operator", "precedence", "root", "formulaDependencies", "ast", "result", "visit", "FormulaError", "code", "fault", "scalar", "value", "numeric", "result", "render", "calculation", "operator", "left", "right", "a", "b", "diff", "flat", "args", "arg", "call", "name", "digits", "number", "precision", "multiplier", "needle", "table", "column", "approximate", "index", "match", "row", "values", "sum", "total", "evaluateFormula", "ast", "read", "evaluate", "node", "rangeCells", "condition", "yes", "no", "error", "createFormulaSheet", "initial", "entries", "reverse", "results", "compile", "value", "formula", "parseFormula", "dependencies", "formulaDependencies", "cellCoordinates", "FormulaError", "evaluate", "id", "visited", "cached", "entry", "evaluateFormula", "dependency", "get", "normalizeCell", "apply", "changes", "additions", "key", "consumedBy", "dirty", "change", "dependent", "encode", "value", "FormulaError", "decodeFormulaValue", "executeFormula", "sheet", "changes", "read", "changed", "id", "exchange", "worker", "command", "signal", "resolve", "reject", "cleanup", "receive", "fail", "abort", "data", "error", "createFormulaSession", "initial", "seed", "confirmed", "lifetime", "local", "fallback", "started", "tail", "useLocal", "launch", "next", "failed", "run", "reply", "createFormulaSheet", "executeFormula", "id", "value", "normalizeCell", "enqueue", "result", "changes", "changed", "decodeFormulaValue"]
|
|
7
|
+
}
|
package/dist/llms.txt
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# OpenGrid
|
|
2
|
+
|
|
3
|
+
OpenGrid is an MIT-licensed React data grid for CRUD, large local datasets, and spreadsheet editing. Use it with Arco Design, Ant Design, or the host-neutral ProGrid.
|
|
4
|
+
|
|
5
|
+
[Live documentation and sandbox](https://han-wangyu.github.io/opengrid-ui/) · [GitHub releases](https://github.com/Han-wangyu/opengrid-ui/releases) · [简体中文](https://han-wangyu.github.io/opengrid-ui/?lang=zh)
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Releases are distributed as npm-compatible tarballs on GitHub. Install Core and Pro together so the package manager can resolve both packages from the same release.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
release=https://github.com/Han-wangyu/opengrid-ui/releases/download/v0.1.25
|
|
13
|
+
npm install "$release/opengrid-ui-core-0.1.25.tgz" "$release/opengrid-ui-pro-0.1.25.tgz"
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```tsx
|
|
17
|
+
import { ProGrid } from '@opengrid-ui/pro';
|
|
18
|
+
import '@opengrid-ui/core/styles.css';
|
|
19
|
+
import '@opengrid-ui/pro/styles.css';
|
|
20
|
+
|
|
21
|
+
const rows = [{ id: 'A-104', name: 'Lumen', amount: 230 }];
|
|
22
|
+
|
|
23
|
+
export function Invoices() {
|
|
24
|
+
return (
|
|
25
|
+
<ProGrid
|
|
26
|
+
label="Invoices"
|
|
27
|
+
rows={rows}
|
|
28
|
+
getRowId={row => row.id}
|
|
29
|
+
columns={[
|
|
30
|
+
{ id: 'name', title: 'Account', query: true },
|
|
31
|
+
{ id: 'amount', title: 'Amount', valueType: 'money', sortable: true },
|
|
32
|
+
]}
|
|
33
|
+
/>
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
For native tokens and scoped tooltips, add the Arco or Ant Design adapter tarball and import its `ProGrid`. Check the [packed React and TypeScript compatibility matrix](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/compat-matrix.spec.md) for peer versions and React 19 setup.
|
|
39
|
+
|
|
40
|
+
ProGrid automatically sorts and filters local datasets above 5,000 rows in a Worker. Plain pages slice the supplied data directly. The [local query contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/pro-crud.spec.md#local-datasets) describes refresh and data ownership.
|
|
41
|
+
|
|
42
|
+
Pass `pageData` for a page already fetched by the host. Send the current rows and full result count, and use `pager={false}` to keep the host's pagination controls. [Host-owned pages](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/pro-crud.spec.md#host-owned-pages)
|
|
43
|
+
|
|
44
|
+
Enable cell editing by passing a `spreadsheet.commit` handler. Pro uses each column's value type for the editor and respects column-level edit permissions during inline edits and pastes. The [Pro contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/pro-crud.spec.md#spreadsheet-editors) describes value adapters and custom editors.
|
|
45
|
+
|
|
46
|
+
Enable Core header reordering with `<Grid columnReordering />`. Drag the grip, activate two grips, or focus a grip and press an arrow key. The [Core contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/core-engine.spec.md#column-reordering) covers grouped headers and storing column order.
|
|
47
|
+
|
|
48
|
+
Use `useServerTree` with Core to expand remote groups in place. The [server-side row model contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/ssrm.spec.md) describes block requests, projections and retries.
|
|
49
|
+
|
|
50
|
+
Configure a pivot report with `PivotSidebar`. The sidebar controls result columns, filters and grouping, and applies filters through the existing pivot Worker. [Pivot sidebar](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/analytics.spec.md#pivot-sidebar)
|
|
51
|
+
|
|
52
|
+
The installed packages include `dist/llms.txt` and `dist/skills/opengrid/SKILL.md`. Coding agents can read the guide and migration instructions from the same version as the installed package.
|
|
53
|
+
|
|
54
|
+
## Packages
|
|
55
|
+
|
|
56
|
+
| Package | Provides |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| `core` | Real DOM virtualization, column pinning and reordering, keyboard selection, TSV, edit transactions and Worker data windows |
|
|
59
|
+
| `pro` | Query schema, tabs, controlled state, URL history, preferences and paged selection |
|
|
60
|
+
| `arco`, `antd` | Scoped tokens, locale and column migration |
|
|
61
|
+
| `engine-wasm` | Numeric sort, filter and aggregation, plus [incremental formula sessions](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/analytics.spec.md#formulas) |
|
|
62
|
+
| `plugin-pivot` | Grouping, [Worker and WASM pivot views](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/analytics.spec.md#pivot), advanced filters and [lazy server groups](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/ssrm.spec.md) |
|
|
63
|
+
| `plugin-excel` | Styled multi-sheet XLSX and streaming CSV/XLSX IO ([workbook text contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/excel.spec.md)) |
|
|
64
|
+
| `plugin-charts` | Sparklines, conditional formatting and [charts from a spreadsheet selection](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/charts.spec.md) |
|
|
65
|
+
|
|
66
|
+
## Verify
|
|
67
|
+
|
|
68
|
+
Use Node.js 22, Corepack, and stable Rust with the WebAssembly target for repository builds. Consumers install the already-built packages.
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
corepack enable
|
|
72
|
+
rustup target add wasm32-unknown-unknown --toolchain stable
|
|
73
|
+
pnpm install --frozen-lockfile
|
|
74
|
+
pnpm exec playwright install chromium
|
|
75
|
+
pnpm verify:m4
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The [live comparison](https://han-wangyu.github.io/opengrid-ui/benchmark/?engine=compare) sends the same navigation and sort commands to the JS and Rust/WASM workers on 50,000 or 500,000 rows. The [reference benchmarks](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/benchmarks/m5-reference.json) measure each engine independently. Read [AGENTS.md](https://github.com/Han-wangyu/opengrid-ui/blob/main/AGENTS.md), the [contribution guide](https://github.com/Han-wangyu/opengrid-ui/blob/main/CONTRIBUTING.md), or the [agent skill](https://github.com/Han-wangyu/opengrid-ui/blob/main/skills/opengrid/SKILL.md) before changing the public contract.
|
|
79
|
+
|
|
80
|
+
# OpenGrid architecture
|
|
81
|
+
|
|
82
|
+
OpenGrid is a client-side React toolkit for CRUD pages, large datasets, and spreadsheet editing. It is independently maintained and MIT licensed.
|
|
83
|
+
|
|
84
|
+
| Layer | Ownership |
|
|
85
|
+
| --- | --- |
|
|
86
|
+
| Arco and AntD adapters | Host tokens, scoped overlays and locale, migration converters |
|
|
87
|
+
| Pro | Column schema, form and tabs, query store, column preferences, toolbar, and paged selection |
|
|
88
|
+
| Core | TanStack column model, React external-store bridge, DOM viewport, and spreadsheet interactions |
|
|
89
|
+
| Compute and optional plugins | JavaScript worker, Rust WebAssembly, pivot, Excel, and charts |
|
|
90
|
+
|
|
91
|
+
The data plane accepts a columnar dataset, materializes sorted or filtered views, returns only the requested viewport, and applies versioned edit transactions. A dataset epoch and query generation help callers discard late responses. Paged CRUD renders supplied rows directly. Its query state has one commit point with cancellation, stale response rejection, URL synchronization and separate tab counts.
|
|
92
|
+
|
|
93
|
+
React 17 and TypeScript 4 are supported targets alongside React 18 and 19. All packages are tested from packed artifacts in isolated applications. The [compatibility matrix](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/compat-matrix.spec.md) checks published declarations with legacy Node, Node16, NodeNext, and Bundler resolution as supported by each compiler. Core emits scoped styles. Adapters map host visual tokens into each instance and attach overlays within the instance. When a React 17 Ant Design host enables CSS variables, an explicit light or dark grid theme gets a stable key for that mounted instance.
|
|
94
|
+
|
|
95
|
+
The [milestones](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/ROADMAP.md) define observable launch criteria. [Package contracts](https://github.com/Han-wangyu/opengrid-ui/tree/main/docs/specs/) and [decision records](https://github.com/Han-wangyu/opengrid-ui/tree/main/docs/adr/) define behavior and document changes.
|
|
96
|
+
|
|
97
|
+
The first virtualizer uses an eight-million-pixel physical scroll track and arithmetic row coordinates. It measures its live viewport and keeps an overscanned window plus a prefetched worker chunk. The reference benchmark runs one engine at a time in Chromium against the production build. The 500,000-row scroll gate captures the sampled renderer JavaScript heap peak in the same trace window as the frame measurements. The public comparison starts both engines on identical datasets and displays each panel's ingestion, paint and sort timings while the two engines share the browser.
|
|
98
|
+
|
|
99
|
+
Core's opt-in column reordering applies sibling preferences to the definitions passed to TanStack. A pointer drag resolves the destination against logical column boxes and holds capture on the header while center columns virtualize. The same sibling rules serve keyboard moves and successive grip activation.
|
|
100
|
+
|
|
101
|
+
The horizontal virtualizer stores column offsets and pin boundaries with the layout. A binary search locates the first visible center column. The mounted leaves identify the grouped headers using a per-pane ancestry index, so horizontal scroll work follows the visible columns, pinned columns and header depth.
|
|
102
|
+
|
|
103
|
+
Pro's committed query is distinct from form drafts and asynchronously restored column preferences. An opt-in saved query read waits up to its configured deadline. The first commit combines the resulting fields with the current URL and controlled props, replaces the history entry, and starts rows and category counts. A single query slot tracks active requests by normalized key, aborts superseded work and checks each generation. A separate slot handles category counts. A pending query intent can receive controlled acknowledgements across renders. The controller keeps its staged fields out of the accepted query until they are all confirmed. Export consumers receive the query corresponding to the last accepted batch of rows. For full-query Excel export, Pro opens a host-provided revision and passes ordered, validated blocks to the workbook handler. The Excel plugin owns file encoding. Migration converters preserve native field paths and emit diagnostics for callbacks with different semantics.
|
|
104
|
+
|
|
105
|
+
Category tabs track keyboard focus within each visible list. The committed query supplies the selected path and labels the shared grid panel. Host changes to the query view and a Pro-owned page reset use a single query commit.
|
|
106
|
+
|
|
107
|
+
The query form and the header filter dialog share schema inputs. Header filter edits stay local until an explicit column change. The accepted column value is copied into the query form while its other drafts are preserved. The header dialog mounts in the owning theme container.
|
|
108
|
+
|
|
109
|
+
Pro feeds Core header moves into the same column preference as the toolbar. It reconciles the visible heading tree with the schema's hidden leaves and uses the current visible pin panes for export order.
|
|
110
|
+
|
|
111
|
+
For large local Pro queries, the browser Worker caches sort and filter columns and returns a page of original row positions. Core's compute protocol serves applications that supply full columnar datasets and edit transactions. Both paths avoid feeding the complete row model through TanStack.
|
|
112
|
+
|
|
113
|
+
When an application supplies [host-owned pages](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/pro-crud.spec.md#host-owned-pages), Pro keeps the same query intent handling and renders the page supplied by the host. The host controls page loading, retry and the authoritative result metadata.
|
|
114
|
+
|
|
115
|
+
Spreadsheet mode adds a coordinate selection model and an on-demand cell editor. Core sends scalar values through validation and the edit interface, which accepts an authoritative transaction ACK and inverse patches. Pro selects editors and edit permissions through the same column schema used for display, search and filters. A recovering Worker client captures submitted inputs, replays confirmed batches against its owned dataset checkpoint, rebuilds active views and then resumes queued work.
|
|
116
|
+
|
|
117
|
+
The [compute protocol](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/wasm-protocol.spec.md) reuses the row order when a view's definition and dependencies remain current. Spreadsheet actions bridge to one edit transaction, and recovery retries an interrupted edit with its original transaction ID.
|
|
118
|
+
|
|
119
|
+
[Selection summaries](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/core-engine.spec.md#selection-summaries) run against Worker views when the spreadsheet uses raw source values. Sheets with custom value projections read bounded blocks and yield between batches of main-thread work.
|
|
120
|
+
|
|
121
|
+
Enterprise features are explicit imports. Core supports pinned rows, dynamic heights, local cell spans, row drag, trees and nested details. The pivot plugin owns grouping, aggregation, filters and server-side blocks. The Excel plugin owns streamed file IO. The Charts plugin maps a Core spreadsheet selection to a chart adapter's series and categories. The Rust worker shares the JS transaction and viewport contract while providing native numeric sorting, filters and aggregates.
|
|
122
|
+
|
|
123
|
+
The [server-side tree](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/ssrm.spec.md) keeps a sparse list of spans for the expanded hierarchy. Core reads the requested window through its tree source capability and renders loaded siblings while child blocks resolve. New windows release abandoned requests and reuse in-flight blocks where both windows overlap.
|
|
124
|
+
|
|
125
|
+
[Pivot and formula sessions](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/analytics.spec.md) use dedicated Workers when their workflows become active. Large pivot views batch numeric reducers through a lazily loaded Rust kernel. JavaScript retains the layout and source-order semantics, the Worker reuses projected columns, and the host applies custom reducers. Formula sessions keep the dependency graph off the main thread and use acknowledged raw values for recovery.
|
|
126
|
+
|
|
127
|
+
The pivot session applies filters against its cached projections before aggregation. Sidebar filter drafts stay in the UI until the host applies them. Report-column visibility and order change the rendered columns without a pivot computation.
|
|
128
|
+
|
|
129
|
+
# Roadmap
|
|
130
|
+
|
|
131
|
+
| Milestone | Deliverables | Exit criteria |
|
|
132
|
+
| --- | --- | --- |
|
|
133
|
+
| M0 | Workspace, published contracts, fixtures, structured verification | React 17/TS4, 18 and 19 packed hosts typecheck, build and run |
|
|
134
|
+
| M1 | Two-dimensional virtual grid, pinned columns, grouped headers, resizing, reordering, worker sorting, native themes, benchmark | 500,000 rows reach the final row and meet agreed paint, scroll, sort and size budgets. Column moves work across the virtual window, and four theme snapshots and dual-locale isolation pass |
|
|
135
|
+
| M2 | Pro schema, value types, tabs, forms, toolbar, persistence, URL, selection, migration adapters | Migrated Arco and AntD examples pass request-race, StrictMode, history and persistence cases |
|
|
136
|
+
| M3 | Range selection, fill handle, TSV, keyboard, editing, undo/redo, aggregates, context menu | Cross-window edit and undo after worker recovery pass on 500,000 rows. IME editing passes in browser |
|
|
137
|
+
| M4 | Grouping, pivot, SSRM with inline expansion, filters, detail, dynamic rows, merging, row drag, tree, Excel, charts, Rust/WASM formulas | Shared engine contract passes in both engines. WASM sort and size budgets pass. The server tree reaches the end of a large group with bounded block reads |
|
|
138
|
+
| M5 | Bilingual documentation, sandbox, benchmark, agent skill, published packages and React 17 adoption pilot | All verification layers pass. Docs and npm packages are reachable. The pilot passes on the agreed real list page |
|
|
139
|
+
|
|
140
|
+
The two first-release scenarios are a production-style Pro migration and a 500,000-row virtual grid. Performance claims require a recorded Chromium run and reference machine.
|
|
141
|
+
|
|
142
|
+
## First delivery
|
|
143
|
+
|
|
144
|
+
The published GitHub release supplies the nine installable tarballs and public documentation. The registry publish and an internal rollout are follow-up activities. The [status board](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/progress/STATUS.md) records the evidence for the GitHub gate and the current rollout boundary.
|
|
Binary file
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: opengrid
|
|
3
|
+
description: Build and migrate OpenGrid React tables, CRUD pages, virtual grids, and spreadsheet interactions with Arco Design or Ant Design.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# OpenGrid
|
|
7
|
+
|
|
8
|
+
Use this skill when adding an OpenGrid table or migrating native Arco or Ant Design columns.
|
|
9
|
+
|
|
10
|
+
1. Match the host's React, TypeScript, and design-system versions against the compatibility matrix. Use the public tarballs from the tagged GitHub release.
|
|
11
|
+
2. Import `@opengrid-ui/core/styles.css` and also `@opengrid-ui/pro/styles.css` when rendering ProGrid.
|
|
12
|
+
3. Pick `@opengrid-ui/pro` for a host-neutral CRUD UI or the `arco` and `antd` adapter package for native tokens, locale, and overlays. Set a stable row ID.
|
|
13
|
+
4. Declare fields, labels, search controls, and renderers in one column schema. Native converters return diagnostics. Resolve any diagnostic relevant to the current page.
|
|
14
|
+
5. Use the single request callback for remote CRUD. Pass AbortSignal to the API and keep pagination and controls in the supplied dual-mode contract. Keep URL ownership with one layer.
|
|
15
|
+
6. ProGrid sorts and filters local `rows` above 5,000 records in a Worker. For a large columnar dataset and explicit viewport control, initialize an engine, create a view, and pass `computedSource(engine, view)` to Core. Only enable spreadsheet writes when an authoritative transaction handler is available.
|
|
16
|
+
7. Pass `columnReordering` to Core to expose drag, tap and keyboard moves. Use `columnReordering={{ order, onOrderChange }}` for a persisted order of group and leaf IDs. Each gesture stays within the original group and pin pane.
|
|
17
|
+
8. For inline server groups, use `useServerTree` from the pivot plugin and pass its source to Core. Keep the provider and accessors stable, and return each path's total with its requested block. Include group and row identity fields in every projection.
|
|
18
|
+
9. When a host request hook returns an already paginated result, pass `pageData={{ rows, total, loading }}`. Keep the host request and URL wiring through the existing query callbacks. Use `pager={false}` to keep the host's pager.
|
|
19
|
+
10. For a configurable pivot report, use `PivotSidebar` with `columnSettings` and `filters`. Send the applied expression to `usePivot` and render `visiblePivotColumns` from the report. Import the pivot sidebar stylesheet once in the host.
|
|
20
|
+
7. For chart actions, use the Charts plugin's `chartMenuItem` in `spreadsheet.contextMenu` and render the `ChartRange` delivered to your app. The selection reader works with local rows and computed viewports.
|
|
21
|
+
8. Use `usePivot` to tie a pivot Worker to a React view. Use `createFormulaSession` for background formula recalculation and dispose it when leaving the workflow.
|
|
22
|
+
9. Validate via an isolated consumer install and its actual host build. Exercise deep links, focus, overlays, edit/undo and representative scrolling with Chromium.
|
|
23
|
+
|
|
24
|
+
See [API contracts](https://github.com/Han-wangyu/opengrid-ui/tree/main/docs/specs), the [live sandbox](https://han-wangyu.github.io/opengrid-ui/) and the [benchmark methodology](https://github.com/Han-wangyu/opengrid-ui/tree/main/docs/benchmarks).
|
package/dist/wasm.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ComputeEngine, NumericFilter, NumericSort } from '@opengrid-ui/core/engine';
|
|
2
|
+
export interface WasmOptions {
|
|
3
|
+
locateFile?: (name: string) => URL | string;
|
|
4
|
+
bytes?: ArrayBuffer;
|
|
5
|
+
}
|
|
6
|
+
export declare function createWasmSorter(options?: WasmOptions): Promise<{
|
|
7
|
+
sort: NumericSort;
|
|
8
|
+
filter: NumericFilter;
|
|
9
|
+
aggregate: (values: Float64Array | Int32Array, keys: Uint32Array, groups: number) => {
|
|
10
|
+
count: number;
|
|
11
|
+
sum: number;
|
|
12
|
+
min: number | null;
|
|
13
|
+
max: number | null;
|
|
14
|
+
}[];
|
|
15
|
+
clear: () => void;
|
|
16
|
+
}>;
|
|
17
|
+
export declare function createWasmEngine(createEngine: (sort: NumericSort, filter: NumericFilter) => ComputeEngine, options?: WasmOptions): Promise<ComputeEngine>;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { CellValue } from '@opengrid-ui/core/engine';
|
|
2
|
+
import type { FormulaErrorCode, FormulaValue } from '../engine/evaluate.js';
|
|
3
|
+
import type { createFormulaSheet } from '../engine/sheet.js';
|
|
4
|
+
export type FormulaCells = Readonly<Record<string, CellValue>>;
|
|
5
|
+
type WireValue = CellValue | {
|
|
6
|
+
error: FormulaErrorCode;
|
|
7
|
+
};
|
|
8
|
+
export interface FormulaCommand {
|
|
9
|
+
initial?: FormulaCells;
|
|
10
|
+
changes?: FormulaCells;
|
|
11
|
+
read?: {
|
|
12
|
+
id: string;
|
|
13
|
+
raw: boolean;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export type FormulaReply = {
|
|
17
|
+
ok: true;
|
|
18
|
+
changed: readonly (readonly [string, WireValue])[];
|
|
19
|
+
value: WireValue;
|
|
20
|
+
} | {
|
|
21
|
+
ok: false;
|
|
22
|
+
message: string;
|
|
23
|
+
};
|
|
24
|
+
export declare function decodeFormulaValue(value: WireValue): FormulaValue;
|
|
25
|
+
export declare function executeFormula(sheet: ReturnType<typeof createFormulaSheet>, { changes, read }: FormulaCommand): FormulaReply;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CellValue } from '@opengrid-ui/core/engine';
|
|
2
|
+
import type { FormulaValue } from '../engine/evaluate.js';
|
|
3
|
+
import type { FormulaCells } from './formula-protocol.js';
|
|
4
|
+
export declare function createFormulaSession(initial?: FormulaCells): {
|
|
5
|
+
apply(changes: FormulaCells): Promise<ReadonlyMap<string, FormulaValue>>;
|
|
6
|
+
get(id: string): Promise<FormulaValue>;
|
|
7
|
+
raw(id: string): Promise<CellValue>;
|
|
8
|
+
dispose(): void;
|
|
9
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/worker.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/worker.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var L=/^\$?[a-z]+\$?[1-9][0-9]*$/i,w={"=":1,"<>":1,"<":1,">":1,"<=":1,">=":1,"&":2,"+":3,"-":3,"*":4,"/":4,"^":6};function F(e){if(!L.test(e))throw new Error(`Invalid cell reference ${e}`);return e.replace(/\$/g,"").toUpperCase()}function E(e){let n=F(e),r=/^([A-Z]+)([0-9]+)$/.exec(n),t=0;for(let a of r[1])t=t*26+a.charCodeAt(0)-64;let l=Number(r[2]);if(l>1048576||t>16384)throw new Error(`Cell reference out of range ${e}`);return{column:t,row:l}}function _(e,n){let r="";for(let t=e;t>0;t=Math.floor((t-1)/26))r=String.fromCharCode(65+(t-1)%26)+r;return r+String(n)}function C(e,n){let r=E(e),t=E(n),l=Math.min(r.column,t.column),a=Math.max(r.column,t.column),i=Math.min(r.row,t.row),f=Math.max(r.row,t.row);if((f-i+1)*(a-l+1)>1e6)throw new Error("Formula range exceeds one million cells");return Array.from({length:f-i+1},(u,s)=>Array.from({length:a-l+1},(d,o)=>_(o+l,s+i)))}function V(e){let n=e.startsWith("=")?e.slice(1):e,r=/\s*(?:(\d+(?:\.\d*)?|\.\d+)([eE][+-]?\d+)?|("(?:[^"]|"")*")|(\$?[a-z][a-z0-9_.$]*)|(<=|>=|<>|[-+*/^&=<>:,()]))/iy,t=[];for(let o=0;o<n.length&&n.slice(o).trim()!=="";){r.lastIndex=o;let c=r.exec(n);if(!c)throw new Error(`Invalid formula token at ${o+1}`);let[,m,p,U,v,$]=c;t.push(m?m+(p??""):U??v??$),o=r.lastIndex}let l=0,a=()=>t[l],i=()=>t[l++];function f(o){if(i()!==o)throw new Error(`Expected ${o}`)}function u(){let o=i();if(!o)throw new Error("Expected an expression");if(o==="+"||o==="-")return{kind:"unary",operator:o,node:s(5)};if(o==="("){let p=s(0);return f(")"),p}if(o.startsWith('"'))return{kind:"literal",value:o.slice(1,-1).replace(/""/g,'"')};if(/^[\d.]/.test(o))return{kind:"literal",value:Number(o)};let c=o.toUpperCase();if(c==="TRUE"||c==="FALSE")return{kind:"literal",value:c==="TRUE"};if(a()==="("&&/^[A-Z_][A-Z0-9_.]*$/.test(c)){i();let p=[];if(a()!==")")do{if(p.push(s(0)),a()!==",")break;i()}while(!0);return f(")"),{kind:"call",name:c,args:p}}let m=F(c);return a()===":"?(i(),{kind:"range",start:m,end:F(i()??"")}):{kind:"ref",id:m}}function s(o){let c=u();for(;a()&&(w[a()]??-1)>=o;){let m=i(),p=w[m];c={kind:"binary",operator:m,left:c,right:s(p+(m==="^"?0:1))}}return c}let d=s(0);if(l!==t.length)throw new Error(`Unexpected token ${a()}`);return d}function b(e){let n=new Set;function r(t){switch(t.kind){case"ref":n.add(t.id);return;case"range":C(t.start,t.end).forEach(l=>l.forEach(a=>n.add(a)));return;case"unary":r(t.node);return;case"binary":r(t.left),r(t.right);return;case"call":t.args.forEach(r);return;case"literal":return}}return r(e),n}var h=class extends Error{constructor(r){super(r);this.code=r}},y=e=>{throw new h(e)},g=e=>{if(e instanceof h)throw e;return Array.isArray(e)?y("#VALUE!"):e},A=e=>{let n=Number(g(e));return Number.isFinite(n)?n:y("#VALUE!")},x=e=>String(g(e)??"");function W(e,n,r){if(e==="&")return x(n)+x(r);if(e==="="||e==="<>")return g(n)===g(r)==(e==="=");if(["<","<=",">",">="].includes(e)){let i=g(n),f=g(r),u=typeof i=="number"&&typeof f=="number"?i-f:String(i??"").localeCompare(String(f??""));return e==="<"?u<0:e==="<="?u<=0:e===">"?u>0:u>=0}let t=A(n),l=A(r),a;switch(e){case"+":a=t+l;break;case"-":a=t-l;break;case"*":a=t*l;break;case"/":if(l===0)return y("#DIV/0!");a=t/l;break;case"^":a=t**l;break;default:return y("#PARSE!")}return Number.isFinite(a)?a:y("#NUM!")}function k(e){return e.flatMap(n=>Array.isArray(n)?n.flat().map(g):[g(n)])}function O(e,n){if(e==="CONCAT")return k(n).map(l=>l??"").join("");if(e==="ROUND"){let[l=null,a=0]=n,i=A(l),f=Math.trunc(A(a));if(f<-15||f>15)return y("#NUM!");let u=10**f;return Math.sign(i)*Math.round(Math.abs(i)*u)/u}if(e==="VLOOKUP"){let[l=null,a,i=1,f=!1]=n;if(!Array.isArray(a)||g(f))return y("#VALUE!");let u=A(i)-1;if(!Number.isInteger(u)||u<0||u>=(a[0]?.length??0))return y("#REF!");let s=a.find(d=>g(d[0]??null)===g(l));return s?g(s[u]??null):y("#N/A")}if(!["SUM","AVG","AVERAGE","MIN","MAX","COUNT"].includes(e))return y("#NAME?");let r=k(n).filter(l=>typeof l=="number");if(e==="COUNT")return r.length;if(e==="MIN")return r.length?r.reduce((l,a)=>Math.min(l,a)):0;if(e==="MAX")return r.length?r.reduce((l,a)=>Math.max(l,a)):0;let t=r.reduce((l,a)=>l+a,0);return e==="SUM"?t:r.length?t/r.length:y("#DIV/0!")}function M(e,n){function r(t){switch(t.kind){case"literal":return t.value;case"ref":return n(t.id);case"range":return C(t.start,t.end).map(l=>l.map(n));case"unary":return(t.operator==="-"?-1:1)*A(r(t.node));case"binary":return W(t.operator,r(t.left),r(t.right));case"call":{if(t.name==="IF"){let[l,a,i]=t.args;return!l||!a?y("#VALUE!"):g(r(l))?r(a):i?r(i):!1}return O(t.name,t.args.map(r))}}}try{return g(r(e))}catch(t){return t instanceof h?t:new h("#REF!")}}function S(e){let n=new Map,r=new Map,t=new Map;function l(u){if(typeof u!="string"||!u.startsWith("="))return{value:u,dependencies:new Set};try{let s=V(u),d=b(s);return d.forEach(E),{value:u,formula:s,dependencies:d}}catch{return{value:u,error:new h("#PARSE!"),dependencies:new Set}}}function a(u,s){if(s.has(u))return new h("#CYCLE!");let d=t.get(u);if(d!==void 0)return d;let o=n.get(u);if(!o)return null;s.add(u);let c=o.error??(o.formula?M(o.formula,m=>a(m,s)):o.value);return s.delete(u),t.set(u,c),c}function i(u){let s=F(u);return E(s),a(s,new Set)}function f(u){let s=Object.entries(u).map(([o,c])=>{let m=F(o);return E(m),{id:m,entry:l(c)}});for(let{id:o,entry:c}of s){for(let m of n.get(o)?.dependencies??[]){let p=r.get(m);p?.delete(o),p?.size===0&&r.delete(m)}for(let m of c.dependencies){let p=r.get(m);p||r.set(m,p=new Set),p.add(o)}n.set(o,c)}let d=new Set(s.map(o=>o.id));for(let o of d)t.delete(o),r.get(o)?.forEach(c=>d.add(c));return new Map([...d].map(o=>[o,a(o,new Set)]))}return e&&f(e),{get:i,apply:f,raw:u=>n.get(F(u))?.value??null}}function R(e){return e instanceof h?{error:e.code}:e}function N(e,{changes:n,read:r}){let t=n?[...e.apply(n)].map(([a,i])=>[a,R(i)]):[],l=r?R(r.raw?e.raw(r.id):e.get(r.id)):null;return{ok:!0,changed:t,value:l}}var I;self.addEventListener("message",({data:e})=>{let n;try{I??(I=S(e.initial)),n=N(I,e)}catch(r){n={ok:!1,message:r instanceof Error?r.message:String(r)}}self.postMessage(n)});
|
|
2
|
+
//# sourceMappingURL=worker.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/engine/parser.ts", "../src/engine/evaluate.ts", "../src/engine/sheet.ts", "../src/worker/formula-protocol.ts", "../src/worker.ts"],
|
|
4
|
+
"sourcesContent": ["import type { CellValue } from '@opengrid-ui/core/engine';\n\nexport type Ast =\n | { kind: 'literal'; value: CellValue }\n | { kind: 'ref'; id: string }\n | { kind: 'range'; start: string; end: string }\n | { kind: 'unary'; operator: '+' | '-'; node: Ast }\n | { kind: 'binary'; operator: string; left: Ast; right: Ast }\n | { kind: 'call'; name: string; args: Ast[] };\n\nconst cellName = /^\\$?[a-z]+\\$?[1-9][0-9]*$/i;\nconst operatorPrecedence: Readonly<Record<string, number>> = {\n '=': 1, '<>': 1, '<': 1, '>': 1, '<=': 1, '>=': 1,\n '&': 2, '+': 3, '-': 3, '*': 4, '/': 4, '^': 6,\n};\n\nexport function normalizeCell(id: string) {\n if (!cellName.test(id)) throw new Error(`Invalid cell reference ${id}`);\n return id.replace(/\\$/g, '').toUpperCase();\n}\n\nexport function cellCoordinates(id: string) {\n const name = normalizeCell(id);\n const parts = /^([A-Z]+)([0-9]+)$/.exec(name)!;\n let column = 0;\n for (const letter of parts[1]!) column = column * 26 + letter.charCodeAt(0) - 64;\n const row = Number(parts[2]);\n if (row > 1_048_576 || column > 16_384) throw new Error(`Cell reference out of range ${id}`);\n return { column, row };\n}\n\nexport function cellNameAt(column: number, row: number) {\n let name = '';\n for (let rest = column; rest > 0; rest = Math.floor((rest - 1) / 26)) {\n name = String.fromCharCode(65 + (rest - 1) % 26) + name;\n }\n return name + String(row);\n}\n\nexport function rangeCells(start: string, end: string): string[][] {\n const a = cellCoordinates(start);\n const b = cellCoordinates(end);\n const left = Math.min(a.column, b.column);\n const right = Math.max(a.column, b.column);\n const top = Math.min(a.row, b.row);\n const bottom = Math.max(a.row, b.row);\n if ((bottom - top + 1) * (right - left + 1) > 1_000_000) throw new Error('Formula range exceeds one million cells');\n return Array.from({ length: bottom - top + 1 }, (_, row) =>\n Array.from({ length: right - left + 1 }, (_, column) => cellNameAt(column + left, row + top)),\n );\n}\n\nexport function parseFormula(formula: string): Ast {\n const text = formula.startsWith('=') ? formula.slice(1) : formula;\n const tokens = /\\s*(?:(\\d+(?:\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?|(\"(?:[^\"]|\"\")*\")|(\\$?[a-z][a-z0-9_.$]*)|(<=|>=|<>|[-+*/^&=<>:,()]))/iy;\n const parts: string[] = [];\n for (let cursor = 0; cursor < text.length;) {\n if (text.slice(cursor).trim() === '') break;\n tokens.lastIndex = cursor;\n const match = tokens.exec(text);\n if (!match) throw new Error(`Invalid formula token at ${cursor + 1}`);\n const [, integer, exponent, quoted, name, symbol] = match;\n parts.push(integer ? integer + (exponent ?? '') : quoted ?? name ?? symbol!);\n cursor = tokens.lastIndex;\n }\n let index = 0;\n const current = () => parts[index];\n const take = () => parts[index++];\n function consume(expected: string) {\n if (take() !== expected) throw new Error(`Expected ${expected}`);\n }\n function prefix(): Ast {\n const token = take();\n if (!token) throw new Error('Expected an expression');\n if (token === '+' || token === '-') return { kind: 'unary', operator: token, node: expression(5) };\n if (token === '(') {\n const value = expression(0);\n consume(')');\n return value;\n }\n if (token.startsWith('\"')) return { kind: 'literal', value: token.slice(1, -1).replace(/\"\"/g, '\"') };\n if (/^[\\d.]/.test(token)) return { kind: 'literal', value: Number(token) };\n const name = token.toUpperCase();\n if (name === 'TRUE' || name === 'FALSE') return { kind: 'literal', value: name === 'TRUE' };\n if (current() === '(' && /^[A-Z_][A-Z0-9_.]*$/.test(name)) {\n take();\n const args: Ast[] = [];\n if (current() !== ')') {\n do {\n args.push(expression(0));\n if (current() !== ',') break;\n take();\n } while (true);\n }\n consume(')');\n return { kind: 'call', name, args };\n }\n const id = normalizeCell(name);\n if (current() === ':') {\n take();\n return { kind: 'range', start: id, end: normalizeCell(take() ?? '') };\n }\n return { kind: 'ref', id };\n }\n function expression(min: number): Ast {\n let node = prefix();\n while (current() && (operatorPrecedence[current()!] ?? -1) >= min) {\n const operator = take()!;\n const precedence = operatorPrecedence[operator]!;\n node = { kind: 'binary', operator, left: node, right: expression(precedence + (operator === '^' ? 0 : 1)) };\n }\n return node;\n }\n const root = expression(0);\n if (index !== parts.length) throw new Error(`Unexpected token ${current()}`);\n return root;\n}\n\nexport function formulaDependencies(ast: Ast): Set<string> {\n const result = new Set<string>();\n function visit(node: Ast) {\n switch (node.kind) {\n case 'ref': result.add(node.id); return;\n case 'range': rangeCells(node.start, node.end).forEach(row => row.forEach(id => result.add(id))); return;\n case 'unary': visit(node.node); return;\n case 'binary': visit(node.left); visit(node.right); return;\n case 'call': node.args.forEach(visit); return;\n case 'literal': return;\n }\n }\n visit(ast);\n return result;\n}\n", "import type { CellValue } from '@opengrid-ui/core/engine';\nimport { rangeCells } from './parser';\nimport type { Ast } from './parser';\n\nexport type FormulaErrorCode = '#PARSE!' | '#REF!' | '#CYCLE!' | '#DIV/0!' | '#VALUE!' | '#N/A' | '#NAME?' | '#NUM!';\nexport class FormulaError extends Error {\n constructor(readonly code: FormulaErrorCode) { super(code); }\n}\n\nexport type FormulaValue = CellValue | FormulaError;\ntype FormulaInput = FormulaValue | FormulaValue[][];\ntype Read = (id: string) => FormulaValue;\nconst fault = (code: FormulaErrorCode): never => { throw new FormulaError(code); };\nconst scalar = (value: FormulaInput): CellValue => {\n if (value instanceof FormulaError) throw value;\n if (Array.isArray(value)) return fault('#VALUE!');\n return value;\n};\nconst numeric = (value: FormulaInput): number => {\n const result = Number(scalar(value));\n if (!Number.isFinite(result)) return fault('#VALUE!');\n return result;\n};\nconst render = (value: FormulaInput): string => String(scalar(value) ?? '');\n\nfunction calculation(operator: string, left: FormulaInput, right: FormulaInput): CellValue {\n if (operator === '&') return render(left) + render(right);\n if (operator === '=' || operator === '<>') return (scalar(left) === scalar(right)) === (operator === '=');\n if (['<', '<=', '>', '>='].includes(operator)) {\n const a = scalar(left);\n const b = scalar(right);\n const diff = typeof a === 'number' && typeof b === 'number' ? a - b : String(a ?? '').localeCompare(String(b ?? ''));\n if (operator === '<') return diff < 0;\n if (operator === '<=') return diff <= 0;\n if (operator === '>') return diff > 0;\n return diff >= 0;\n }\n const a = numeric(left);\n const b = numeric(right);\n let result: number;\n switch (operator) {\n case '+': result = a + b; break;\n case '-': result = a - b; break;\n case '*': result = a * b; break;\n case '/': if (b === 0) return fault('#DIV/0!'); result = a / b; break;\n case '^': result = a ** b; break;\n default: return fault('#PARSE!');\n }\n return Number.isFinite(result) ? result : fault('#NUM!');\n}\n\nfunction flat(args: FormulaInput[]): CellValue[] {\n return args.flatMap(arg => Array.isArray(arg) ? arg.flat().map(scalar) : [scalar(arg)]);\n}\n\nfunction call(name: string, args: FormulaInput[]): FormulaValue {\n if (name === 'CONCAT') return flat(args).map(value => value ?? '').join('');\n if (name === 'ROUND') {\n const [value = null, digits = 0] = args;\n const number = numeric(value);\n const precision = Math.trunc(numeric(digits));\n if (precision < -15 || precision > 15) return fault('#NUM!');\n const multiplier = 10 ** precision;\n return Math.sign(number) * Math.round(Math.abs(number) * multiplier) / multiplier;\n }\n if (name === 'VLOOKUP') {\n const [needle = null, table, column = 1, approximate = false] = args;\n if (!Array.isArray(table) || scalar(approximate)) return fault('#VALUE!');\n const index = numeric(column) - 1;\n if (!Number.isInteger(index) || index < 0 || index >= (table[0]?.length ?? 0)) return fault('#REF!');\n const match = table.find(row => scalar(row[0] ?? null) === scalar(needle));\n return match ? scalar(match[index] ?? null) : fault('#N/A');\n }\n if (!['SUM', 'AVG', 'AVERAGE', 'MIN', 'MAX', 'COUNT'].includes(name)) return fault('#NAME?');\n const values = flat(args).filter((value): value is number => typeof value === 'number');\n if (name === 'COUNT') return values.length;\n if (name === 'MIN') return values.length ? values.reduce((a, b) => Math.min(a, b)) : 0;\n if (name === 'MAX') return values.length ? values.reduce((a, b) => Math.max(a, b)) : 0;\n const sum = values.reduce((total, value) => total + value, 0);\n if (name === 'SUM') return sum;\n return values.length ? sum / values.length : fault('#DIV/0!');\n}\n\nexport function evaluateFormula(ast: Ast, read: Read): FormulaValue {\n function evaluate(node: Ast): FormulaInput {\n switch (node.kind) {\n case 'literal': return node.value;\n case 'ref': return read(node.id);\n case 'range': return rangeCells(node.start, node.end).map(row => row.map(read));\n case 'unary': return (node.operator === '-' ? -1 : 1) * numeric(evaluate(node.node));\n case 'binary': return calculation(node.operator, evaluate(node.left), evaluate(node.right));\n case 'call': {\n if (node.name === 'IF') {\n const [condition, yes, no] = node.args;\n if (!condition || !yes) return fault('#VALUE!');\n return scalar(evaluate(condition)) ? evaluate(yes) : no ? evaluate(no) : false;\n }\n return call(node.name, node.args.map(evaluate));\n }\n }\n }\n try { return scalar(evaluate(ast)); }\n catch (error) { return error instanceof FormulaError ? error : new FormulaError('#REF!'); }\n}\n", "import type { CellValue } from '@opengrid-ui/core/engine';\nimport { evaluateFormula, FormulaError } from './evaluate';\nimport type { FormulaValue } from './evaluate';\nimport { cellCoordinates, formulaDependencies, normalizeCell, parseFormula } from './parser';\nimport type { Ast } from './parser';\n\ninterface Entry { value: CellValue; formula?: Ast; error?: FormulaError; dependencies: Set<string> }\n\nexport function createFormulaSheet(initial?: Readonly<Record<string, CellValue>>) {\n const entries = new Map<string, Entry>();\n const reverse = new Map<string, Set<string>>();\n const results = new Map<string, FormulaValue>();\n\n function compile(value: CellValue): Entry {\n if (typeof value !== 'string' || !value.startsWith('=')) return { value, dependencies: new Set() };\n try {\n const formula = parseFormula(value);\n const dependencies = formulaDependencies(formula);\n dependencies.forEach(cellCoordinates);\n return { value, formula, dependencies };\n } catch {\n return { value, error: new FormulaError('#PARSE!'), dependencies: new Set() };\n }\n }\n\n function evaluate(id: string, visited: Set<string>): FormulaValue {\n if (visited.has(id)) return new FormulaError('#CYCLE!');\n const cached = results.get(id);\n if (cached !== undefined) return cached;\n const entry = entries.get(id);\n if (!entry) return null;\n visited.add(id);\n const value = entry.error ?? (entry.formula ? evaluateFormula(entry.formula, dependency => evaluate(dependency, visited)) : entry.value);\n visited.delete(id);\n results.set(id, value);\n return value;\n }\n\n function get(id: string): FormulaValue {\n const value = normalizeCell(id);\n cellCoordinates(value);\n return evaluate(value, new Set());\n }\n\n function apply(changes: Readonly<Record<string, CellValue>>): ReadonlyMap<string, FormulaValue> {\n const additions = Object.entries(changes).map(([key, value]) => {\n const id = normalizeCell(key);\n cellCoordinates(id);\n return { id, entry: compile(value) };\n });\n for (const { id, entry } of additions) {\n for (const dependency of entries.get(id)?.dependencies ?? []) {\n const consumedBy = reverse.get(dependency);\n consumedBy?.delete(id);\n if (consumedBy?.size === 0) reverse.delete(dependency);\n }\n for (const dependency of entry.dependencies) {\n let consumedBy = reverse.get(dependency);\n if (!consumedBy) reverse.set(dependency, consumedBy = new Set());\n consumedBy.add(id);\n }\n entries.set(id, entry);\n }\n const dirty = new Set(additions.map(change => change.id));\n for (const id of dirty) {\n results.delete(id);\n reverse.get(id)?.forEach(dependent => dirty.add(dependent));\n }\n return new Map([...dirty].map(id => [id, evaluate(id, new Set())]));\n }\n\n if (initial) apply(initial);\n return { get, apply, raw: (id: string) => entries.get(normalizeCell(id))?.value ?? null };\n}\n", "import type { CellValue } from '@opengrid-ui/core/engine';\nimport { FormulaError } from '../engine/evaluate';\nimport type { FormulaErrorCode, FormulaValue } from '../engine/evaluate';\nimport type { createFormulaSheet } from '../engine/sheet';\n\nexport type FormulaCells = Readonly<Record<string, CellValue>>;\ntype WireValue = CellValue | { error: FormulaErrorCode };\n\nexport interface FormulaCommand {\n initial?: FormulaCells;\n changes?: FormulaCells;\n read?: { id: string; raw: boolean };\n}\n\nexport type FormulaReply = {\n ok: true;\n changed: readonly (readonly [string, WireValue])[];\n value: WireValue;\n} | { ok: false; message: string };\n\nfunction encode(value: FormulaValue): WireValue {\n return value instanceof FormulaError ? { error: value.code } : value;\n}\n\nexport function decodeFormulaValue(value: WireValue): FormulaValue {\n return value !== null && typeof value === 'object' ? new FormulaError(value.error) : value;\n}\n\nexport function executeFormula(sheet: ReturnType<typeof createFormulaSheet>, { changes, read }: FormulaCommand): FormulaReply {\n const changed = changes ? [...sheet.apply(changes)].map(([id, value]) => [id, encode(value)] as const) : [];\n const value = read ? encode(read.raw ? sheet.raw(read.id) : sheet.get(read.id)) : null;\n return { ok: true, changed, value };\n}\n", "import { createFormulaSheet } from './engine/sheet';\nimport { executeFormula } from './worker/formula-protocol';\nimport type { FormulaCommand, FormulaReply } from './worker/formula-protocol';\n\nlet sheet: ReturnType<typeof createFormulaSheet> | undefined;\nself.addEventListener('message', ({ data }: MessageEvent<FormulaCommand>) => {\n let reply: FormulaReply;\n try {\n sheet ??= createFormulaSheet(data.initial);\n reply = executeFormula(sheet, data);\n } catch (error) {\n reply = { ok: false, message: error instanceof Error ? error.message : String(error) };\n }\n self.postMessage(reply);\n});\n"],
|
|
5
|
+
"mappings": "AAUA,IAAMA,EAAW,6BACXC,EAAuD,CAC3D,IAAK,EAAG,KAAM,EAAG,IAAK,EAAG,IAAK,EAAG,KAAM,EAAG,KAAM,EAChD,IAAK,EAAG,IAAK,EAAG,IAAK,EAAG,IAAK,EAAG,IAAK,EAAG,IAAK,CAC/C,EAEO,SAASC,EAAcC,EAAY,CACxC,GAAI,CAACH,EAAS,KAAKG,CAAE,EAAG,MAAM,IAAI,MAAM,0BAA0BA,CAAE,EAAE,EACtE,OAAOA,EAAG,QAAQ,MAAO,EAAE,EAAE,YAAY,CAC3C,CAEO,SAASC,EAAgBD,EAAY,CAC1C,IAAME,EAAOH,EAAcC,CAAE,EACvBG,EAAQ,qBAAqB,KAAKD,CAAI,EACxCE,EAAS,EACb,QAAWC,KAAUF,EAAM,CAAC,EAAIC,EAASA,EAAS,GAAKC,EAAO,WAAW,CAAC,EAAI,GAC9E,IAAMC,EAAM,OAAOH,EAAM,CAAC,CAAC,EAC3B,GAAIG,EAAM,SAAaF,EAAS,MAAQ,MAAM,IAAI,MAAM,+BAA+BJ,CAAE,EAAE,EAC3F,MAAO,CAAE,OAAAI,EAAQ,IAAAE,CAAI,CACvB,CAEO,SAASC,EAAWH,EAAgBE,EAAa,CACtD,IAAIJ,EAAO,GACX,QAASM,EAAOJ,EAAQI,EAAO,EAAGA,EAAO,KAAK,OAAOA,EAAO,GAAK,EAAE,EACjEN,EAAO,OAAO,aAAa,IAAMM,EAAO,GAAK,EA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cP,CAAE,CAAC,GAAG,OAAS,IAAK,CAC1F,CCrDA,SAASgB,EAAOC,EAAgC,CAC9C,OAAOA,aAAiBC,EAAe,CAAE,MAAOD,EAAM,IAAK,EAAIA,CACjE,CAMO,SAASE,EAAeC,EAA8C,CAAE,QAAAC,EAAS,KAAAC,CAAK,EAAiC,CAC5H,IAAMC,EAAUF,EAAU,CAAC,GAAGD,EAAM,MAAMC,CAAO,CAAC,EAAE,IAAI,CAAC,CAACG,EAAIC,CAAK,IAAM,CAACD,EAAIE,EAAOD,CAAK,CAAC,CAAU,EAAI,CAAC,EACpGA,EAAQH,EAAOI,EAAOJ,EAAK,IAAMF,EAAM,IAAIE,EAAK,EAAE,EAAIF,EAAM,IAAIE,EAAK,EAAE,CAAC,EAAI,KAClF,MAAO,CAAE,GAAI,GAAM,QAAAC,EAAS,MAAAE,CAAM,CACpC,CC5BA,IAAIE,EACJ,KAAK,iBAAiB,UAAW,CAAC,CAAE,KAAAC,CAAK,IAAoC,CAC3E,IAAIC,EACJ,GAAI,CACFF,MAAUG,EAAmBF,EAAK,OAAO,GACzCC,EAAQE,EAAeJ,EAAOC,CAAI,CACpC,OAASI,EAAO,CACdH,EAAQ,CAAE,GAAI,GAAO,QAASG,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAE,CACvF,CACA,KAAK,YAAYH,CAAK,CACxB,CAAC",
|
|
6
|
+
"names": ["cellName", "operatorPrecedence", "normalizeCell", "id", "cellCoordinates", "name", "parts", "column", "letter", "row", "cellNameAt", "rest", "rangeCells", "start", "end", "a", "b", "left", "right", "top", "bottom", "_", "parseFormula", "formula", "text", "tokens", "cursor", "match", "integer", "exponent", "quoted", "symbol", "index", "current", "take", "consume", "expected", "prefix", "token", "expression", "value", "args", "min", "node", "operator", "precedence", "root", "formulaDependencies", "ast", "result", "visit", "FormulaError", "code", "fault", "scalar", "value", "numeric", "result", "render", "calculation", "operator", "left", "right", "a", "b", "diff", "flat", "args", "arg", "call", "name", "digits", "number", "precision", "multiplier", "needle", "table", "column", "approximate", "index", "match", "row", "values", "sum", "total", "evaluateFormula", "ast", "read", "evaluate", "node", "rangeCells", "condition", "yes", "no", "error", "createFormulaSheet", "initial", "entries", "reverse", "results", "compile", "value", "formula", "parseFormula", "dependencies", "formulaDependencies", "cellCoordinates", "FormulaError", "evaluate", "id", "visited", "cached", "entry", "evaluateFormula", "dependency", "get", "normalizeCell", "apply", "changes", "additions", "key", "consumedBy", "dirty", "change", "dependent", "encode", "value", "FormulaError", "executeFormula", "sheet", "changes", "read", "changed", "id", "value", "encode", "sheet", "data", "reply", "createFormulaSheet", "executeFormula", "error"]
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@opengrid-ui/engine-wasm",
|
|
3
|
-
"version": "0.0.0-stage",
|
|
4
|
-
"stub": true,
|
|
5
|
-
"description": "Temporary package placeholder for staged publishing"
|
|
6
|
-
}
|
|
1
|
+
{"name":"@opengrid-ui/engine-wasm","version":"0.1.25","license":"MIT","type":"module","repository":{"type":"git","url":"git+https://github.com/Han-wangyu/opengrid-ui.git","directory":"packages/engine-wasm"},"files":["dist","LICENSE"],"main":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","default":"./dist/index.js"}},"sideEffects":false,"publishConfig":{"access":"public"},"scripts":{"build":"node ../../scripts/build-package.mjs"},"devDependencies":{"@opengrid-ui/core":"workspace:^"}}
|
package/README.md
DELETED