@betteroffice/xlsx 0.0.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,11 +4,6 @@ Framework-free core for the BetterOffice XLSX editor — the Rust engine (parse,
4
4
  calc, render) compiled to WebAssembly, plus display-list, viewport, hit-test,
5
5
  and accessibility helpers.
6
6
 
7
- > **Early (`0.0.x`).** The core surfaces — opening/saving documents, the editor
8
- > components, collaboration — are settling and unlikely to change shape. Smaller
9
- > APIs may still move between releases; breaking changes are always listed in
10
- > the changelog.
11
-
12
7
  ```bash
13
8
  bun add @betteroffice/xlsx
14
9
  ```
@@ -48,6 +43,20 @@ handle itself covers styling (`patchRangeStyle`, `setNumberFormat`), undo/redo,
48
43
  and PNG export (`renderPng` / `renderRangePng`; guard with
49
44
  `isPngExportAvailable`).
50
45
 
46
+ ## Print a range
47
+
48
+ `workbook.printDisplayList(sheet, range, metrics, gridlines)` renders a range
49
+ without changing workbook data, the active sheet, or screen geometry. Pass
50
+ `PrintMetrics` measured from the workbook's normal font: `dpi`, `maxDigitWidth`,
51
+ `fontAscent`, and `fontDescent` use the layout device's pixels; `fontSizePt` and
52
+ `defaultRowHeightPt` use points. `fontFamily` supplies the default face, and
53
+ optional `defaultColumnWidth` uses the stored OOXML character width.
54
+
55
+ The result uses 96-DPI logical coordinates. Paint it with `paintDisplayList(ctx,
56
+ frame, scale, { x, y })`; the optional origin uses backing-store pixels, so page
57
+ margins need no intermediate image. Cell ranges, paper size, and pagination are
58
+ chosen by the caller. See the [Office comparison harness](../../scripts/office-quality).
59
+
51
60
  ## AI agents / human-in-the-loop
52
61
 
53
62
  An agent stages edits as a proposal instead of applying them; a human reviews
@@ -112,7 +121,9 @@ they have stable axis identities and a Yrs-aware undo manager.
112
121
  ## Development
113
122
 
114
123
  The generated `.wasm` binary is intentionally not committed. From the repository
115
- root, install `wasm-pack` 0.15.0 and run `bun run build:xlsx-wasm`. Package builds,
116
- tests, demo startup, and CI run this step automatically.
124
+ root, install `wasm-pack` 0.15.0 and `binaryen`, then run
125
+ `bun run build:xlsx-wasm`. Package builds, tests, demo startup, and CI run this
126
+ step automatically.
117
127
 
118
- Docs: https://betteroffice.dev · Apache-2.0.
128
+ [JavaScript guide](https://docs.betteroffice.dev/docs/javascript) ·
129
+ [Changelog](https://github.com/openooxml/betteroffice/blob/main/packages/xlsx/CHANGELOG.md) · Apache-2.0.
@@ -0,0 +1,4 @@
1
+ function I(e){return Math.max(0,e.length-1)}function E(e){return e.length>0?e[e.length-1]:0}function C(e,t,n){return Math.max(t,Math.min(n,e))}function T(e,t,n,r){let o=n,l=r;for(;o<l;){let c=o+l+1>>1;e[c]<=t?o=c:l=c-1;}return o}function M(e,t,n,r){let o=I(e);if(o===0)return {first:0,last:-1};let l=C(Math.trunc(t),0,o);if(l>=o)return {first:0,last:-1};let c=e[l]-e[0],i=e[l]+Math.max(0,n),s=Math.max(0,r-c),f=i+s,a=T(e,i,l,o-1);if(e[a+1]<=i||s===0)return {first:0,last:-1};let x=T(e,f,a,o-1);return {first:a,last:x}}function z(e,t,n){return {cols:M(t,e.frozenCols,e.scrollX,e.width),rows:M(n,e.frozenRows,e.scrollY,e.height)}}function D(e,t,n){let r=I(e),o=C(Math.trunc(t),0,r),l=E(e)-e[o],c=Math.max(0,n-(e[o]-e[0]));return Math.max(0,l-c)}function _(e,t,n){let r=C(e.scrollX,0,D(t,e.frozenCols,e.width)),o=C(e.scrollY,0,D(n,e.frozenRows,e.height));return r===e.scrollX&&o===e.scrollY?e:{...e,scrollX:r,scrollY:o}}function $(e,t){let n=new Array(e+1);for(let r=0;r<=e;r++)n[r]=r*t;return n}function A(e,t,n){return Math.max(t,Math.min(n,e))}function p(e){return {anchor:{...e},focus:{...e}}}function y(e){return {top:Math.min(e.anchor.row,e.focus.row),bottom:Math.max(e.anchor.row,e.focus.row),left:Math.min(e.anchor.col,e.focus.col),right:Math.max(e.anchor.col,e.focus.col)}}function N(e,t){let n=y(e);return t.row>=n.top&&t.row<=n.bottom&&t.col>=n.left&&t.col<=n.right}function U(e){let t=y(e);return (t.bottom-t.top+1)*(t.right-t.left+1)}function S(e,t,n){let r=n?{row:A(t.row,0,n.rows-1),col:A(t.col,0,n.cols-1)}:{...t};return {anchor:{...e.anchor},focus:r}}function W(e,t){switch(e){case "up":return {row:-t,col:0};case "down":return {row:t,col:0};case "left":return {row:0,col:-t};case "right":return {row:0,col:t}}}function w(e,t,n){let{limits:r}=n,o=n.step??1,l=W(t,o),c={row:A(e.focus.row+l.row,0,r.rows-1),col:A(e.focus.col+l.col,0,r.cols-1)};return n.extend?S(e,c):p(c)}var B={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right"};function R(e){return !!(e.metaKey||e.ctrlKey)}function X(e,t,n){switch(t){case "up":return {row:0,col:e.col};case "down":return {row:n.rows-1,col:e.col};case "left":return {row:e.row,col:0};case "right":return {row:e.row,col:n.cols-1}}}function m(e){return {type:"move",selection:e}}function Y(e,t,n){let{row:r,col:o}=e.focus;return !t&&o>=n.cols-1?p({row:Math.min(r+1,n.rows-1),col:0}):t&&o<=0?p({row:Math.max(r-1,0),col:n.cols-1}):p({row:r,col:o+(t?-1:1)})}function j(e){return e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey}function q(e,t,n){let r=B[t.key];if(r){if(R(t)){let o=X(e.focus,r,n);return m(t.shiftKey?S(e,o,n):p(o))}return m(w(e,r,{extend:t.shiftKey,limits:n}))}switch(t.key){case "Tab":return m(Y(e,!!t.shiftKey,n));case "Enter":return m(w(e,t.shiftKey?"up":"down",{extend:false,limits:n}));case "Home":return m(R(t)?p({row:0,col:0}):p({row:e.focus.row,col:0}));case "End":return m(R(t)?p({row:n.rows-1,col:n.cols-1}):p({row:e.focus.row,col:n.cols-1}));case "PageDown":return m(w(e,"down",{extend:t.shiftKey,step:n.rowsPerPage,limits:n}));case "PageUp":return m(w(e,"up",{extend:t.shiftKey,step:n.rowsPerPage,limits:n}));case "F2":return {type:"startEdit"};case "Delete":case "Backspace":return {type:"clear"}}return (t.key==="a"||t.key==="A")&&R(t)?m({anchor:{row:0,col:0},focus:{row:n.rows-1,col:n.cols-1}}):j(t)?{type:"startEdit",initialInput:t.key}:{type:"none"}}function we(e,t,n){if(!e)return null;let r=Math.fround(t),o=Math.fround(n);if(!Number.isFinite(r)||!Number.isFinite(o))return null;for(let l=e.length-1;l>=0;l--){let c=e[l].clip,i=Math.fround(c.x),s=Math.fround(c.y),f=Math.fround(i+Math.fround(c.w)),a=Math.fround(s+Math.fround(c.h));if(r>=i&&r<f&&o>=s&&o<a)return e[l]}return null}function v(e,t){let n=e.length-1;if(n<=0||t<e[0]||t>=e[n])return -1;let r=0,o=n-1;for(;r<o;){let l=r+o+1>>1;e[l]<=t?r=l:o=l-1;}return r}function de(e,t,n){if(!e)return null;let r=v(e.colOffsets,t),o=v(e.rowOffsets,n);return r<0||o<0?null:{row:e.rowIndices?.[o]??e.startRow+o,col:e.colIndices?.[r]??e.startCol+r}}function K(e,t,n,r){if(t){let l=0,c=t.length-1;for(;l<=c;){let i=l+c>>1,s=t[i];if(s===r)return i;s<r?l=i+1:c=i-1;}return -1}let o=r-e;return o>=0&&o<n.length-1?o:-1}function be(e,t,n){if(!e)return null;let r=K(e.startCol,e.colIndices,e.colOffsets,n),o=K(e.startRow,e.rowIndices,e.rowOffsets,t);return r<0||o<0?null:{x:e.colOffsets[r],y:e.rowOffsets[o],w:e.colOffsets[r+1]-e.colOffsets[r],h:e.rowOffsets[o+1]-e.rowOffsets[o]}}function J(e,t,n){return t?.[n]??e+n}function H(e,t,n,r,o){let l=-1,c=-1;for(let i=0;i<n;i++){let s=J(e,t,i);if(!(s<r)){if(s>o)break;l<0&&(l=i),c=i;}}return l<0?null:[l,c]}function ye(e,t){if(!e)return null;let n=e.colOffsets.length-1,r=e.rowOffsets.length-1;if(n<=0||r<=0)return null;let o=H(e.startCol,e.colIndices,n,t.left,t.right),l=H(e.startRow,e.rowIndices,r,t.top,t.bottom);if(!o||!l)return null;let[c,i]=o,[s,f]=l;return {x:e.colOffsets[c],y:e.rowOffsets[s],w:e.colOffsets[i+1]-e.colOffsets[c],h:e.rowOffsets[f+1]-e.rowOffsets[s]}}function xe(e,t,n){return e.hyperlinks?.find(r=>t>=r.top&&t<=r.bottom&&n>=r.left&&n<=r.right)??null}function Ce(e){if(!e.externalTarget)return null;let t;try{t=new URL(e.externalTarget);}catch{return null}return ["http:","https:","mailto:","tel:"].includes(t.protocol)?(e.location&&!t.hash&&(t.hash=e.location.replace(/^#/,"")),t.href):null}function Ae(e,t){let n=e.replace(/^#/,""),r=n.lastIndexOf("!"),o=r<0?t:n.slice(0,r),l=(r<0?n:n.slice(r+1)).split(":",1)[0],c=/^\$?([A-Za-z]{1,3})\$?([1-9]\d*)$/.exec(l);if(!c)return null;let i=0;for(let a of c[1].toUpperCase())i=i*26+a.charCodeAt(0)-64;let s=Number(c[2]);if(i<1||i>16384||s<1||s>1048576)return null;let f=o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1).replace(/''/g,"'"):o;return f?{sheetName:f,row:s-1,col:i-1}:null}var Z=new Set(["=","+","-","@"]);function Q(e){let t=e.charCodeAt(0);return Z.has(e[0])||t===9||t===13||t===10}function ee(e){return /[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function te(e){let t=!e.isFormula&&e.input.length>0&&Q(e.input);return ee(t?`'${e.input}`:e.input)}function Re(e){return e.map(t=>t.map(te).join(" ")).join(`\r
2
+ `)}function Oe(e){let t=[],n=[],r="",o=false,l=0,c=()=>{n.push(r),r="";},i=()=>{c(),t.push(n),n=[];};for(;l<e.length;){let s=e[l];if(o){if(s==='"'){if(e[l+1]==='"'){r+='"',l+=2;continue}o=false,l+=1;continue}r+=s,l+=1;continue}if(s==='"'){o=true,l+=1;continue}if(s===" "){c(),l+=1;continue}if(s==="\r"){i(),e[l+1]===`
3
+ `&&(l+=1),l+=1;continue}if(s===`
4
+ `){i(),l+=1;continue}r+=s,l+=1;}return (r.length>0||n.length>0)&&i(),t}function P(e){let t=e,n="";do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return n}function ne(e,t){return `${P(t)}${e+1}`}function O(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>String(t[r]??""))}function F(e,t){return `${Math.round(e*1e3)},${Math.round(t*1e3)}`}function re(e){let t=new Map;for(let n of e.commands)n.op==="text"&&n.clip&&!n.ghost&&!n.chart&&t.set(F(n.clip.x,n.clip.y),n.text);return t}function oe(e,t,n){return e?t>=e.top&&t<=e.bottom&&n>=e.left&&n<=e.right:false}function g(e,t,n){return t?.[n]??e+n}function le(e,t,n,r,o,l){let c=g(e.startRow,e.rowIndices,t),i=g(e.startCol,e.colIndices,n),s=ne(c,i),a=r.length===0?o?l.emptyCellLabelSelected:l.emptyCellLabel:o?l.cellLabelSelected:l.cellLabel;return {row:c,col:i,address:s,text:r,selected:o,label:O(a,{address:s,value:r})}}function Le(e,t,n,r){let o=e.grid,l=O(r.gridLabel,{sheet:n}),c=(e.charts??[]).map(u=>({label:u.label,placeholder:u.placeholder??false}));if(!o)return {label:l,sheetName:n,columnHeaders:[],rows:[],charts:c};let i=o.colOffsets.length-1,s=o.rowOffsets.length-1,f=t?y(t):null,a=re(e),x=[];for(let u=0;u<i;u++){let h=g(o.startCol,o.colIndices,u),d=P(h);x.push({col:h,text:d,label:O(r.columnHeaderLabel,{column:d})});}let L=[];for(let u=0;u<s;u++){let h=g(o.startRow,o.rowIndices,u),d=[];for(let b=0;b<i;b++){let k=F(o.colOffsets[b],o.rowOffsets[u]),G=a.get(k)??"",V=g(o.startCol,o.colIndices,b);d.push(le(o,u,b,G,oe(f,h,V),r));}L.push({row:h,header:O(r.rowHeaderLabel,{row:h+1}),cells:d});}return {label:l,sheetName:n,columnHeaders:x,rows:L,charts:c}}export{I as a,E as b,M as c,z as d,_ as e,$ as f,p as g,y as h,N as i,U as j,S as k,w as l,q as m,we as n,de as o,be as p,ye as q,xe as r,Ce as s,Ae as t,Re as u,Oe as v,Le as w};
@@ -1 +1 @@
1
- import {a}from'./chunk-O2XFH626.js';var v=80,U=2e4,_=45e3,oe=3e3,ie=1048576,ce=16384;var x=1024,T=["#0B57D0","#B3261E","#146C2E","#6B4EFF","#8E24AA","#00639B","#8E4E00","#7D5260"];function X(r){return r?{sheet:r.sheet,anchor:{...r.anchor},head:{...r.head}}:null}function le(r){return {user:{...r.user},cursor:X(r.cursor)}}function V(r,e){return !r||!e?r===e:r.sheet===e.sheet&&r.anchor.row===e.anchor.row&&r.anchor.col===e.anchor.col&&r.head.row===e.head.row&&r.head.col===e.head.col}function ue(r,e){return !r||!e?r===e:r.user.name===e.user.name&&r.user.color===e.user.color&&V(r.cursor,e.cursor)}function $(r){return T[r%T.length]}function E(r,e){if(typeof r!="string"||!/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(r))return $(e);let t=r.slice(1).toUpperCase();return t.length===6?`#${t}`:`#${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`}function P(r,e){return {name:r?.name.trim().slice(0,128)||"Anonymous",color:E(r?.color,e)}}function R(r,e,t,s,n={}){let a=n.maxPeers??1024;if(!Number.isSafeInteger(a)||a<1)throw new RangeError("Awareness peer limit must be a positive integer");let c=false,l=0;for(let p of e){if(p.clientId===t)continue;let d=r.get(p.clientId);if(d&&p.clock<d.clock)continue;if(d&&p.clock===d.clock){d.lastSeen=s;continue}if(!d&&r.size>=a){l+=1;continue}let m=p.state?.cursor!=null&&(!d?.state||!V(d.state.cursor,p.state.cursor)),f=p.state?le(p.state):null;c||(c=!ue(d?.state??null,f)),r.set(p.clientId,{clock:p.clock,state:f,lastSeen:s,cursorMovedAt:m?s:d?.cursorMovedAt??0});}return l>0&&n.onPeersDiscarded?.(l),c}function L(r,e,t=45e3){let s=false;for(let[n,a]of r)e-a.lastSeen<t||(s||(s=a.state!==null),r.delete(n));return s}function M(r){let e=[];for(let[t,s]of r)s.state&&e.push({clientId:t,clock:s.clock,user:{...s.state.user},cursor:X(s.state.cursor),lastSeen:s.lastSeen,cursorMovedAt:s.cursorMovedAt});return e.sort((t,s)=>t.clientId-s.clientId),e}function pe(r,e,t=1048576,s=16384){let n=e.indexOf(r.sheet);return n<0||t<1||s<1||[r.anchor,r.head].some(({row:c,col:l})=>!Number.isSafeInteger(c)||!Number.isSafeInteger(l)||c<0||l<0||c>=t||l>=s)?null:{sheetIndex:n,range:{top:Math.min(r.anchor.row,r.head.row),left:Math.min(r.anchor.col,r.head.col),bottom:Math.max(r.anchor.row,r.head.row),right:Math.max(r.anchor.col,r.head.col)}}}var w=16777216,F=4096,b=1024,H=0,G=1,de=2,Y=3,z=0,K=1,j=2,fe=0,Ae=Number.MAX_SAFE_INTEGER,i=class extends Error{constructor(e){super(e),this.name="ProtocolError";}},C=class{constructor(e){a(this,"bytes",e);a(this,"offset",0);}get done(){return this.offset===this.bytes.byteLength}readVarUint(){let e=0,t=1,s=0;for(;;){if(this.offset>=this.bytes.byteLength)throw new i("Truncated varUint");let n=this.bytes[this.offset++],a=n&127;if(a>Math.floor((Ae-e)/t))throw new i("varUint exceeds Number.MAX_SAFE_INTEGER");if(e+=a*t,s+=1,(n&128)===0){if(s>1&&a===0)throw new i("Non-canonical varUint");return e}if(s>=8)throw new i("varUint exceeds Number.MAX_SAFE_INTEGER");t*=128;}}readVarUint8Array(){let e=this.readVarUint(),t=this.bytes.byteLength-this.offset;if(e>t)throw new i("Truncated varUint8Array");let s=this.bytes.slice(this.offset,this.offset+e);return this.offset+=e,s}readVarString(){let e=this.readVarUint8Array();try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(t){throw new i(`Invalid UTF-8 string${t instanceof Error?`: ${t.message}`:""}`)}}};function A(r){if(!Number.isSafeInteger(r)||r<0)throw new i("varUint value must be a non-negative safe integer");let e=[],t=r;for(;t>=128;)e.push(t%128|128),t=Math.floor(t/128);return e.push(t),Uint8Array.from(e)}function g(r,e){let t=0;for(let a of r)if(t+=a.byteLength,t>e)throw new i(`Frame exceeds ${e} bytes`);let s=new Uint8Array(t),n=0;for(let a of r)s.set(a,n),n+=a.byteLength;return s}function we(r){let e=new TextEncoder().encode(r);return [A(e.byteLength),e]}function S(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function q(r){if(!S(r))throw new i("Awareness cell must be an object");let{row:e,col:t}=r;if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0)throw new i("Awareness cell coordinates must be non-negative safe integers");return {row:e,col:t}}function J(r,e){if(r===null)return null;if(!S(r)||!S(r.user))throw new i("Awareness state must contain a user");let{name:t,color:s}=r.user;if(typeof t!="string"||t.length===0||t.length>128)throw new i(`Awareness user name must contain 1 to ${128} characters`);let n=E(s,e),a=r.cursor;if(a==null)return {user:{name:t,color:n},cursor:null};if(!S(a)||typeof a.sheet!="string")throw new i("Awareness cursor must contain a sheet identifier");if(a.sheet.length===0||a.sheet.length>256)throw new i(`Awareness sheet identifier must contain 1 to ${256} characters`);return {user:{name:t,color:n},cursor:{sheet:a.sheet,anchor:q(a.anchor),head:q(a.head)}}}function N(r,e,t){return g([A(H),A(r),A(e.byteLength),e],t)}function Q(r,e=w){return N(z,r,e)}function Z(r,e=w){return N(K,r,e)}function ee(r,e=w){return N(j,r,e)}function te(r,e=w){if(r.length>b)throw new i(`Awareness update exceeds ${b} states`);let t=[A(r.length)];for(let n of r){if(!Number.isSafeInteger(n.clientId)||n.clientId<=0)throw new i("Awareness clientId must be a positive safe integer");if(!Number.isSafeInteger(n.clock)||n.clock<0)throw new i("Awareness clock must be a non-negative safe integer");let a=J(n.state,n.clientId);t.push(A(n.clientId),A(n.clock),...we(JSON.stringify(a)));}let s=g(t,e);return g([A(G),A(s.byteLength),s],e)}function re(r=w){return g([A(Y)],r)}function se(r,e=b,t){if(!(r instanceof Uint8Array))throw new i("Awareness update must be a Uint8Array");if(!Number.isSafeInteger(e)||e<1)throw new i("Awareness state limit must be a positive integer");let s=new C(r),n=s.readVarUint();if(n>e){let l=new i(`Awareness update exceeds ${e} states`);if(!t)throw l;t(l);}let a=[],c=Math.min(n,e);for(let l=0;l<c;l++){let p,d,m;try{p=s.readVarUint(),d=s.readVarUint(),m=s.readVarString();}catch(f){if(!t)throw f;return t(new i(`Awareness entry ${l+1} could not be decoded: ${f instanceof Error?f.message:"Unknown error"}`)),a}try{if(p<=0)throw new i("Awareness clientId must be a positive safe integer");let f=JSON.parse(m);a.push({clientId:p,clock:d,state:J(f,p)});}catch(f){let D=f instanceof i?f:new i(`Invalid awareness JSON${f instanceof Error?`: ${f.message}`:""}`);if(!t)throw D;t(new i(`Awareness entry ${l+1} discarded: ${D.message}`));}}if(n<=e&&!s.done){let l=new i("Trailing awareness update data");if(!t)throw l;t(l);}return a}function ne(r,e=w,t=F){if(!(r instanceof Uint8Array))throw new i("Frame must be a Uint8Array");if(r.byteLength===0)throw new i("Frame is empty");if(r.byteLength>e)throw new i(`Frame exceeds ${e} bytes`);if(!Number.isSafeInteger(t)||t<1)throw new i("Message limit must be a positive integer");let s=new C(r),n=[];for(;!s.done;){if(n.length>=t)throw new i(`Frame exceeds ${t} messages`);let a=s.readVarUint();switch(a){case H:{let c=s.readVarUint(),l=s.readVarUint8Array();if(c===z)n.push({type:"sync-step-1",stateVector:l});else if(c===K)n.push({type:"sync-step-2",update:l});else if(c===j)n.push({type:"update",update:l});else throw new i(`Unknown sync message type ${c}`);break}case G:n.push({type:"awareness",update:s.readVarUint8Array()});break;case de:{let c=s.readVarUint();if(c!==fe)throw new i(`Unknown auth message type ${c}`);n.push({type:"auth",reason:s.readVarString()});break}case Y:n.push({type:"query-awareness"});break;default:throw new i(`Unknown top-level message type ${a}`)}}return n}var h=class extends Error{constructor(t,s,n){super(s);a(this,"code");a(this,"cause");this.name="CollaborationError",this.code=t,this.cause=n;}};var ye=w,be=1e3;function O(r,e,t){if(!Number.isSafeInteger(e)||e<(t?0:1))throw new RangeError(`${r} must be ${t?"a non-negative":"a positive"} integer`);return e}function me(r){return r instanceof Error&&r.message?r.message:typeof r=="string"&&r?r:"Unknown error"}function u(r,e,t){return t instanceof h?t:new h(r,`${e}: ${me(t)}`,t)}function I(r,e){if(!(r instanceof Uint8Array))throw new TypeError(`${e} must return a Uint8Array`);return r.slice()}function B(r){r.unref?.();}function ae(r){return !!r&&Number.isSafeInteger(r.row)&&r.row>=0&&Number.isSafeInteger(r.col)&&r.col>=0}function Ee(r){return typeof r.sheet=="string"&&r.sheet.length>0&&r.sheet.length<=256&&ae(r.anchor)&&ae(r.head)}var k=class{constructor(e,t,s={}){a(this,"replica");a(this,"transport");a(this,"maxFrameBytes");a(this,"maxMessagesPerFrame");a(this,"maxPendingBytes");a(this,"statusListeners",new Map);a(this,"errorListeners",new Map);a(this,"awarenessListeners",new Map);a(this,"awarenessStore",new Map);a(this,"awarenessUser");a(this,"pendingFrames",[]);a(this,"unsubscribeReplica");a(this,"unsubscribeTransport",()=>{});a(this,"hasTransportSubscription",false);a(this,"connectionStatus","disconnected");a(this,"isSynced",false);a(this,"wantsConnection",false);a(this,"isOpen",false);a(this,"isDestroyed",false);a(this,"epoch",0);a(this,"connectAttempt",0);a(this,"nextListenerId",0);a(this,"queuedBytes",0);a(this,"isFlushing",false);a(this,"transportCleanup");a(this,"statusRevision",0);a(this,"awarenessClock",0);a(this,"reportedClockExhaustion",false);a(this,"awarenessCursor",null);a(this,"lastAwarenessSentAt",Number.NEGATIVE_INFINITY);a(this,"awarenessBroadcastTimer");a(this,"awarenessHeartbeatTimer");a(this,"awarenessExpiryTimer");a(this,"hasPublishedAwarenessForOpen",false);this.replica=e,this.transport=t,this.maxFrameBytes=O("maxFrameBytes",s.maxFrameBytes??w,false),this.maxMessagesPerFrame=O("maxMessagesPerFrame",s.maxMessagesPerFrame??F,false),this.maxPendingBytes=O("maxPendingBytes",s.maxPendingBytes??ye,true),this.awarenessUser=P(s.user,e.clientId);try{this.unsubscribeReplica=e.onUpdate((n,a)=>{a==="local"&&this.forwardLocalUpdate(n);});}catch(n){throw u("replica","Failed to observe replica updates",n)}}get status(){return this.connectionStatus}get synced(){return this.isSynced}get pendingBytes(){return this.queuedBytes}get peers(){return M(this.awarenessStore)}connect(){this.isDestroyed||this.isOpen||this.connectionStatus==="connecting"||(this.wantsConnection=true,this.setStatus("connecting",false),!(this.transportCleanup||this.isDestroyed||!this.wantsConnection)&&this.startConnection());}startConnection(){if(this.isDestroyed||!this.wantsConnection||this.isOpen||this.transportCleanup)return;let e=this.hasTransportSubscription?this.epoch:++this.epoch,t=++this.connectAttempt;if(this.setStatus("connecting",false),!!this.isCurrent(e)){if(!this.hasTransportSubscription){let s;try{if(s=this.transport.onEvent(n=>this.handleTransportEvent(e,n)),typeof s!="function")throw new TypeError("Transport event subscription must return a function")}catch(n){this.failConnection(e,u("transport","Failed to subscribe to transport events",n));return}if(!this.isCurrent(e)){try{s();}catch(n){this.isDestroyed||this.report(u("transport","Failed to unsubscribe from stale transport events",n));}return}this.unsubscribeTransport=s,this.hasTransportSubscription=true;}try{let s=this.transport.connect();s&&s.catch(n=>{this.isCurrent(e)&&this.connectAttempt===t&&this.failConnection(e,u("transport","Transport connect failed",n));});}catch(s){this.failConnection(e,u("transport","Transport connect failed",s));}}}disconnect(){if(this.isDestroyed||!(this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus!=="disconnected"))return;this.clearPending(),this.publishAwareness(null,"best-effort"),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription(),s=this.cleanupTransport(t,true);this.setStatus("disconnected",false);for(let n of s)this.report(n);}destroy(){if(this.isDestroyed)return;let e=this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus==="connecting"||this.connectionStatus==="connected";this.clearPending(),this.publishAwareness(null,"best-effort"),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.isDestroyed=true,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription(),s=this.cleanupTransport(t,e);this.setStatus("destroyed",false);for(let n of s)this.report(n);try{this.unsubscribeReplica();}catch(n){this.report(u("replica","Failed to unsubscribe from replica updates",n));}this.unsubscribeReplica=()=>{},this.statusListeners.clear(),this.errorListeners.clear(),this.awarenessListeners.clear();}onStatus(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("status listener must be a function");let t=this.nextListenerId++;return this.statusListeners.set(t,e),()=>this.statusListeners.delete(t)}onError(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("error listener must be a function");let t=this.nextListenerId++;return this.errorListeners.set(t,e),()=>this.errorListeners.delete(t)}onAwareness(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("awareness listener must be a function");let t=this.nextListenerId++;this.awarenessListeners.set(t,e);try{e(this.peers);}catch{}return ()=>this.awarenessListeners.delete(t)}setCursor(e){if(this.isDestroyed)return;let t=e?Ee(e):false;if(this.awarenessCursor=e&&t?{sheet:e.sheet,anchor:{...e.anchor},head:{...e.head}}:null,e&&!t&&this.report(new h("protocol",`Awareness cursor needs a sheet identifier of 1 to ${256} characters and non-negative cell coordinates; cursor dropped`)),!this.isOpen||!this.wantsConnection)return;let s=80-(Date.now()-this.lastAwarenessSentAt);if(s<=0){this.publishAwareness();return}this.awarenessBroadcastTimer||(this.awarenessBroadcastTimer=setTimeout(()=>{this.awarenessBroadcastTimer=void 0,this.publishAwareness();},s),B(this.awarenessBroadcastTimer));}isCurrent(e){return !this.isDestroyed&&this.wantsConnection&&e===this.epoch}failConnection(e,t){if(!this.isCurrent(e))return;this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let s=this.takeTransportSubscription();this.clearPending();let n=this.cleanupTransport(s,true);this.setStatus("disconnected",false),this.report(t);for(let a of n)this.report(a);}takeTransportSubscription(){let e=this.unsubscribeTransport;return this.unsubscribeTransport=()=>{},this.hasTransportSubscription=false,e}cleanupTransport(e,t){let s=[];try{e();}catch(n){s.push(u("transport","Failed to unsubscribe from transport events",n));}if(!t||this.transportCleanup)return s;try{let n=this.transport.disconnect();if(n){let a=!1,c=Promise.resolve(n).catch(l=>{a=!0,this.isDestroyed||this.report(u("transport","Transport disconnect failed",l));}).finally(()=>{this.transportCleanup===c&&(this.transportCleanup=void 0,!this.isDestroyed&&(a?(this.wantsConnection=!1,this.setStatus("disconnected",!1)):this.wantsConnection&&this.startConnection()));});this.transportCleanup=c;}}catch(n){s.push(u("transport","Transport disconnect failed",n));}return s}handleTransportEvent(e,t){if(this.isCurrent(e))switch(t.type){case "open":this.handleOpen(e);break;case "message":this.isOpen&&this.handleMessage(e,t.data);break;case "close":this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.isOpen=false,this.connectAttempt+=1,this.clearPending(),this.setStatus("disconnected",false);break;case "error":this.failConnection(e,u("transport","Transport error",t.error));break;case "drain":this.isOpen&&this.flushPending();break;default:this.failConnection(e,new h("transport","Unknown transport event"));}}handleOpen(e){if(this.isOpen||(this.isOpen=true,this.hasPublishedAwarenessForOpen=false,this.clearPending(),this.setStatus("connected",false),!this.isCurrent(e)||!this.isOpen))return;let t;try{t=I(this.replica.encodeStateVector(),"encodeStateVector");}catch(s){this.failConnection(e,u("replica","Failed to encode replica state vector",s));return}try{this.sendFrame(Q(t,this.maxFrameBytes));}catch(s){this.failConnection(e,u("protocol","Failed to encode collaboration handshake",s));return}if(!(!this.isCurrent(e)||!this.isOpen)){try{this.sendFrame(re(this.maxFrameBytes));}catch(s){this.report(u("protocol","Failed to encode awareness query",s));}!this.isCurrent(e)||!this.isOpen||(this.hasPublishedAwarenessForOpen||this.publishAwareness(),!(!this.isCurrent(e)||!this.isOpen)&&this.startAwarenessTimers());}}handleMessage(e,t){let s;try{if(!(t instanceof Uint8Array))throw new TypeError("Frame must be a Uint8Array");if(t.byteLength>this.maxFrameBytes)throw new RangeError(`Frame exceeds ${this.maxFrameBytes} bytes`);s=ne(t,this.maxFrameBytes,this.maxMessagesPerFrame);}catch(n){this.failConnection(e,u("protocol","Invalid collaboration frame",n));return}for(let n of s){if(!this.isCurrent(e)||!this.isOpen)return;switch(n.type){case "sync-step-1":this.respondToSyncStep1(e,n.stateVector);break;case "sync-step-2":this.applyRemoteUpdate(e,n.update)&&this.isCurrent(e)&&this.setStatus("connected",true);break;case "update":this.applyRemoteUpdate(e,n.update);break;case "awareness":try{let a=[],c=0,l=R(this.awarenessStore,se(n.update,b,p=>a.push(p)),this.replica.clientId,Date.now(),{onPeersDiscarded:p=>{c=p;}});for(let p of a)this.report(u("protocol","Invalid awareness update",p));if(c>0&&this.report(new h("protocol",`${c} awareness ${c===1?"entry was":"entries were"} discarded because the tracked peer limit of ${1024} was reached`)),!this.isCurrent(e)||!this.isOpen)return;l&&this.emitAwareness();}catch(a){this.report(u("protocol","Invalid awareness update",a));}break;case "auth":this.failConnection(e,new h("protocol",n.reason?`Authentication denied: ${n.reason}`:"Authentication denied"));return;case "query-awareness":this.publishAwareness();break}}}respondToSyncStep1(e,t){let s;try{s=I(this.replica.encodeStateAsUpdate(t.slice()),"encodeStateAsUpdate");}catch(n){this.failConnection(e,u("replica","Failed to encode replica update",n));return}try{this.sendFrame(Z(s,this.maxFrameBytes));}catch(n){this.failConnection(e,u("protocol","Failed to encode SyncStep2",n));}}applyRemoteUpdate(e,t){try{return this.replica.applyUpdate(t.slice()),!0}catch(s){return this.failConnection(e,u("replica","Failed to apply remote update",s)),false}}forwardLocalUpdate(e){if(this.isDestroyed||!this.isOpen||!this.wantsConnection)return;let t=this.epoch,s;try{s=I(e,"Replica update");}catch(n){this.failConnection(t,u("replica","Invalid replica update",n));return}try{this.sendFrame(ee(s,this.maxFrameBytes));}catch(n){this.failConnection(t,u("protocol","Failed to encode update",n));}}publishAwareness(e="current",t="queued"){if(!(!this.isOpen||this.isDestroyed||!this.wantsConnection)){if(this.awarenessBroadcastTimer&&(clearTimeout(this.awarenessBroadcastTimer),this.awarenessBroadcastTimer=void 0),this.awarenessClock>=Number.MAX_SAFE_INTEGER){t==="queued"&&!this.reportedClockExhaustion&&(this.reportedClockExhaustion=true,this.report(new h("protocol","Awareness clock exhausted")));return}this.awarenessClock+=1;try{this.hasPublishedAwarenessForOpen=!0;let s=te([{clientId:this.replica.clientId,clock:this.awarenessClock,state:e===null?null:{user:this.awarenessUser,cursor:this.awarenessCursor}}],this.maxFrameBytes);t==="best-effort"?this.sendBestEffort(s):this.sendFrame(s),this.lastAwarenessSentAt=Date.now();}catch(s){t==="queued"&&this.report(u("protocol","Failed to encode awareness update",s));}}}startAwarenessTimers(){this.stopAwarenessTimers(),this.awarenessHeartbeatTimer=setInterval(()=>{this.publishAwareness();},2e4),this.awarenessExpiryTimer=setInterval(()=>{L(this.awarenessStore,Date.now(),45e3)&&this.emitAwareness();},be),B(this.awarenessHeartbeatTimer),B(this.awarenessExpiryTimer);}stopAwarenessTimers(){this.awarenessBroadcastTimer&&clearTimeout(this.awarenessBroadcastTimer),this.awarenessHeartbeatTimer&&clearInterval(this.awarenessHeartbeatTimer),this.awarenessExpiryTimer&&clearInterval(this.awarenessExpiryTimer),this.awarenessBroadcastTimer=void 0,this.awarenessHeartbeatTimer=void 0,this.awarenessExpiryTimer=void 0;}clearAwarenessPeers(){if(this.awarenessStore.size===0)return;let e=this.peers.length>0;this.awarenessStore.clear(),e&&this.emitAwareness();}emitAwareness(){let e=this.peers;for(let[t,s]of [...this.awarenessListeners])if(this.awarenessListeners.get(t)===s)try{s(e);}catch{}}sendFrame(e){if(!this.isOpen||this.isDestroyed||!this.wantsConnection)return;let t=this.epoch;if(this.pendingFrames.length>0){this.queueFrame(t,e);return}let s;try{s=this.transport.send(e.slice());}catch(n){this.failConnection(t,u("transport","Transport send failed",n));return}if(typeof s!="boolean"){this.failConnection(t,new h("transport","Transport send must return a boolean"));return}!s&&this.isCurrent(t)&&this.isOpen&&this.queueFrame(t,e);}sendBestEffort(e){try{this.transport.send(e.slice());}catch{}}queueFrame(e,t){if(t.byteLength>this.maxPendingBytes-this.queuedBytes){this.failConnection(e,new h("backpressure",`Pending collaboration data exceeds ${this.maxPendingBytes} bytes`));return}let s=t.slice();this.pendingFrames.push(s),this.queuedBytes+=s.byteLength;}flushPending(){if(!this.isFlushing){this.isFlushing=true;try{for(;this.isOpen&&!this.isDestroyed&&this.pendingFrames.length>0;){let e=this.epoch,t=this.pendingFrames[0],s;try{s=this.transport.send(t.slice());}catch(n){this.failConnection(e,u("transport","Transport send failed",n));return}if(typeof s!="boolean"){this.failConnection(e,new h("transport","Transport send must return a boolean"));return}if(!s||!this.isOpen||this.pendingFrames[0]!==t)return;this.pendingFrames.shift(),this.queuedBytes-=t.byteLength;}}finally{this.isFlushing=false;}}}clearPending(){this.pendingFrames.length=0,this.queuedBytes=0;}setStatus(e,t){if(this.connectionStatus===e&&this.isSynced===t)return;this.connectionStatus=e,this.isSynced=t;let s=++this.statusRevision,n={status:e,synced:t};for(let[a,c]of [...this.statusListeners]){if(this.statusRevision!==s)return;if(this.statusListeners.get(a)===c)try{c(n);}catch{}}}report(e){for(let[t,s]of [...this.errorListeners])if(this.errorListeners.get(t)===s)try{s(e);}catch{}}};export{v as AWARENESS_BROADCAST_INTERVAL_MS,T as AWARENESS_COLORS,U as AWARENESS_HEARTBEAT_INTERVAL_MS,oe as AWARENESS_LABEL_DURATION_MS,_ as AWARENESS_PEER_TIMEOUT_MS,h as CollaborationError,k as CollaborationProvider,x as MAX_TRACKED_AWARENESS_PEERS,ce as XLSX_MAX_COLUMNS,ie as XLSX_MAX_ROWS,R as applyAwarenessUpdates,M as awarenessPeers,$ as colorForClientId,L as expireAwarenessPeers,E as normalizeAwarenessColor,P as normalizeCollaborationUser,pe as resolveAwarenessCursor};
1
+ import {a}from'./chunk-O2XFH626.js';var v=80,U=2e4,_=45e3,ce=3e3,le=1048576,ue=16384;var x=1024,T=["#0B57D0","#B3261E","#146C2E","#6B4EFF","#8E24AA","#00639B","#8E4E00","#7D5260"];function V(r){return r?{sheet:r.sheet,anchor:{...r.anchor},head:{...r.head}}:null}function pe(r){return {user:{...r.user},cursor:V(r.cursor)}}function $(r,e){return !r||!e?r===e:r.sheet===e.sheet&&r.anchor.row===e.anchor.row&&r.anchor.col===e.anchor.col&&r.head.row===e.head.row&&r.head.col===e.head.col}function he(r,e){return !r||!e?r===e:r.user.name===e.user.name&&r.user.color===e.user.color&&$(r.cursor,e.cursor)}function W(r){return T[r%T.length]}function E(r,e){if(typeof r!="string"||!/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(r))return W(e);let t=r.slice(1).toUpperCase();return t.length===6?`#${t}`:`#${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`}function P(r,e){return {name:r?.name.trim().slice(0,128)||"Anonymous",color:E(r?.color,e)}}function R(r,e,t,s,n={}){let a=n.maxPeers??1024;if(!Number.isSafeInteger(a)||a<1)throw new RangeError("Awareness peer limit must be a positive integer");let c=false,l=0;for(let p of e){if(p.clientId===t)continue;let d=r.get(p.clientId);if(d&&p.clock<d.clock)continue;if(d&&p.clock===d.clock){d.lastSeen=s;continue}if(!d&&r.size>=a){l+=1;continue}let m=p.state?.cursor!=null&&(!d?.state||!$(d.state.cursor,p.state.cursor)),f=p.state?pe(p.state):null;c||(c=!he(d?.state??null,f)),r.set(p.clientId,{clock:p.clock,state:f,lastSeen:s,cursorMovedAt:m?s:d?.cursorMovedAt??0});}return l>0&&n.onPeersDiscarded?.(l),c}function L(r,e,t=45e3){let s=false;for(let[n,a]of r)e-a.lastSeen<t||(s||(s=a.state!==null),r.delete(n));return s}function M(r){let e=[];for(let[t,s]of r)s.state&&e.push({clientId:t,clock:s.clock,user:{...s.state.user},cursor:V(s.state.cursor),lastSeen:s.lastSeen,cursorMovedAt:s.cursorMovedAt});return e.sort((t,s)=>t.clientId-s.clientId),e}function de(r,e,t=1048576,s=16384){let n=e.indexOf(r.sheet);return n<0||t<1||s<1||[r.anchor,r.head].some(({row:c,col:l})=>!Number.isSafeInteger(c)||!Number.isSafeInteger(l)||c<0||l<0||c>=t||l>=s)?null:{sheetIndex:n,range:{top:Math.min(r.anchor.row,r.head.row),left:Math.min(r.anchor.col,r.head.col),bottom:Math.max(r.anchor.row,r.head.row),right:Math.max(r.anchor.col,r.head.col)}}}var w=16777216,N=4096,b=1024,G=0,Y=1,Ae=2,z=3,K=0,j=1,J=2,we=0,ye=Number.MAX_SAFE_INTEGER,i=class extends Error{constructor(e){super(e),this.name="ProtocolError";}},C=class{constructor(e){a(this,"bytes",e);a(this,"offset",0);}get done(){return this.offset===this.bytes.byteLength}readVarUint(){let e=0,t=1,s=0;for(;;){if(this.offset>=this.bytes.byteLength)throw new i("Truncated varUint");let n=this.bytes[this.offset++],a=n&127;if(a>Math.floor((ye-e)/t))throw new i("varUint exceeds Number.MAX_SAFE_INTEGER");if(e+=a*t,s+=1,(n&128)===0){if(s>1&&a===0)throw new i("Non-canonical varUint");return e}if(s>=8)throw new i("varUint exceeds Number.MAX_SAFE_INTEGER");t*=128;}}readVarUint8Array(){let e=this.readVarUint(),t=this.bytes.byteLength-this.offset;if(e>t)throw new i("Truncated varUint8Array");let s=this.bytes.slice(this.offset,this.offset+e);return this.offset+=e,s}readVarString(){let e=this.readVarUint8Array();try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(t){throw new i(`Invalid UTF-8 string${t instanceof Error?`: ${t.message}`:""}`)}}};function A(r){if(!Number.isSafeInteger(r)||r<0)throw new i("varUint value must be a non-negative safe integer");let e=[],t=r;for(;t>=128;)e.push(t%128|128),t=Math.floor(t/128);return e.push(t),Uint8Array.from(e)}function g(r,e){let t=0;for(let a of r)if(t+=a.byteLength,t>e)throw new i(`Frame exceeds ${e} bytes`);let s=new Uint8Array(t),n=0;for(let a of r)s.set(a,n),n+=a.byteLength;return s}function be(r){let e=new TextEncoder().encode(r);return [A(e.byteLength),e]}function S(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function H(r){if(!S(r))throw new i("Awareness cell must be an object");let{row:e,col:t}=r;if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0)throw new i("Awareness cell coordinates must be non-negative safe integers");return {row:e,col:t}}function Q(r,e){if(r===null)return null;if(!S(r)||!S(r.user))throw new i("Awareness state must contain a user");let{name:t,color:s}=r.user;if(typeof t!="string"||t.length===0||t.length>128)throw new i(`Awareness user name must contain 1 to ${128} characters`);let n=E(s,e),a=r.cursor;if(a==null)return {user:{name:t,color:n},cursor:null};if(!S(a)||typeof a.sheet!="string")throw new i("Awareness cursor must contain a sheet identifier");if(a.sheet.length===0||a.sheet.length>256)throw new i(`Awareness sheet identifier must contain 1 to ${256} characters`);return {user:{name:t,color:n},cursor:{sheet:a.sheet,anchor:H(a.anchor),head:H(a.head)}}}function F(r,e,t){return g([A(G),A(r),A(e.byteLength),e],t)}function Z(r,e=w){return F(K,r,e)}function ee(r,e=w){return F(j,r,e)}function te(r,e=w){return F(J,r,e)}function re(r,e=w){if(r.length>b)throw new i(`Awareness update exceeds ${b} states`);let t=[A(r.length)];for(let n of r){if(!Number.isSafeInteger(n.clientId)||n.clientId<=0)throw new i("Awareness clientId must be a positive safe integer");if(!Number.isSafeInteger(n.clock)||n.clock<0)throw new i("Awareness clock must be a non-negative safe integer");let a=Q(n.state,n.clientId);t.push(A(n.clientId),A(n.clock),...be(JSON.stringify(a)));}let s=g(t,e);return g([A(Y),A(s.byteLength),s],e)}function se(r=w){return g([A(z)],r)}function ne(r,e=b,t){if(!(r instanceof Uint8Array))throw new i("Awareness update must be a Uint8Array");if(!Number.isSafeInteger(e)||e<1)throw new i("Awareness state limit must be a positive integer");let s=new C(r),n=s.readVarUint();if(n>e){let l=new i(`Awareness update exceeds ${e} states`);if(!t)throw l;t(l);}let a=[],c=Math.min(n,e);for(let l=0;l<c;l++){let p,d,m;try{p=s.readVarUint(),d=s.readVarUint(),m=s.readVarString();}catch(f){if(!t)throw f;return t(new i(`Awareness entry ${l+1} could not be decoded: ${f instanceof Error?f.message:"Unknown error"}`)),a}try{if(p<=0)throw new i("Awareness clientId must be a positive safe integer");let f=JSON.parse(m);a.push({clientId:p,clock:d,state:Q(f,p)});}catch(f){let X=f instanceof i?f:new i(`Invalid awareness JSON${f instanceof Error?`: ${f.message}`:""}`);if(!t)throw X;t(new i(`Awareness entry ${l+1} discarded: ${X.message}`));}}if(n<=e&&!s.done){let l=new i("Trailing awareness update data");if(!t)throw l;t(l);}return a}function ae(r,e=w,t=N){if(!(r instanceof Uint8Array))throw new i("Frame must be a Uint8Array");if(r.byteLength===0)throw new i("Frame is empty");if(r.byteLength>e)throw new i(`Frame exceeds ${e} bytes`);if(!Number.isSafeInteger(t)||t<1)throw new i("Message limit must be a positive integer");let s=new C(r),n=[];for(;!s.done;){if(n.length>=t)throw new i(`Frame exceeds ${t} messages`);let a=s.readVarUint();switch(a){case G:{let c=s.readVarUint(),l=s.readVarUint8Array();if(c===K)n.push({type:"sync-step-1",stateVector:l});else if(c===j)n.push({type:"sync-step-2",update:l});else if(c===J)n.push({type:"update",update:l});else throw new i(`Unknown sync message type ${c}`);break}case Y:n.push({type:"awareness",update:s.readVarUint8Array()});break;case Ae:{let c=s.readVarUint();if(c!==we)throw new i(`Unknown auth message type ${c}`);n.push({type:"auth",reason:s.readVarString()});break}case z:n.push({type:"query-awareness"});break;default:throw new i(`Unknown top-level message type ${a}`)}}return n}var h=class extends Error{constructor(t,s,n){super(s);a(this,"code");a(this,"cause");this.name="CollaborationError",this.code=t,this.cause=n;}};var me=w,Ee=1e3,O=new TextEncoder().encode("\0betteroffice-document-fingerprint-v1\0");function I(r,e,t){if(!Number.isSafeInteger(e)||e<(t?0:1))throw new RangeError(`${r} must be ${t?"a non-negative":"a positive"} integer`);return e}function Se(r){return r instanceof Error&&r.message?r.message:typeof r=="string"&&r?r:"Unknown error"}function u(r,e,t){return t instanceof h?t:new h(r,`${e}: ${Se(t)}`,t)}function B(r,e){if(!(r instanceof Uint8Array))throw new TypeError(`${e} must return a Uint8Array`);return r.slice()}function oe(r){let e=O.byteLength+32,t=r.byteLength-e;if(t<0)return r;for(let s=0;s<O.byteLength;s+=1)if(r[t+s]!==O[s])return r;return r.subarray(0,t)}function k(r){r.unref?.();}function ie(r){return !!r&&Number.isSafeInteger(r.row)&&r.row>=0&&Number.isSafeInteger(r.col)&&r.col>=0}function Ce(r){return typeof r.sheet=="string"&&r.sheet.length>0&&r.sheet.length<=256&&ie(r.anchor)&&ie(r.head)}var D=class{constructor(e,t,s={}){a(this,"replica");a(this,"transport");a(this,"maxFrameBytes");a(this,"maxMessagesPerFrame");a(this,"maxPendingBytes");a(this,"statusListeners",new Map);a(this,"errorListeners",new Map);a(this,"awarenessListeners",new Map);a(this,"awarenessStore",new Map);a(this,"awarenessUser");a(this,"pendingFrames",[]);a(this,"unsubscribeReplica");a(this,"unsubscribeTransport",()=>{});a(this,"hasTransportSubscription",false);a(this,"connectionStatus","disconnected");a(this,"isSynced",false);a(this,"wantsConnection",false);a(this,"isOpen",false);a(this,"isDestroyed",false);a(this,"epoch",0);a(this,"connectAttempt",0);a(this,"nextListenerId",0);a(this,"queuedBytes",0);a(this,"isFlushing",false);a(this,"transportCleanup");a(this,"statusRevision",0);a(this,"awarenessClock",0);a(this,"reportedClockExhaustion",false);a(this,"awarenessCursor",null);a(this,"lastAwarenessSentAt",Number.NEGATIVE_INFINITY);a(this,"awarenessBroadcastTimer");a(this,"awarenessHeartbeatTimer");a(this,"awarenessExpiryTimer");a(this,"hasPublishedAwarenessForOpen",false);this.replica=e,this.transport=t,this.maxFrameBytes=I("maxFrameBytes",s.maxFrameBytes??w,false),this.maxMessagesPerFrame=I("maxMessagesPerFrame",s.maxMessagesPerFrame??N,false),this.maxPendingBytes=I("maxPendingBytes",s.maxPendingBytes??me,true),this.awarenessUser=P(s.user,e.clientId);try{this.unsubscribeReplica=e.onUpdate((n,a)=>{a==="local"&&this.forwardLocalUpdate(n);});}catch(n){throw u("replica","Failed to observe replica updates",n)}}get status(){return this.connectionStatus}get synced(){return this.isSynced}get pendingBytes(){return this.queuedBytes}get peers(){return M(this.awarenessStore)}connect(){this.isDestroyed||this.isOpen||this.connectionStatus==="connecting"||(this.wantsConnection=true,this.setStatus("connecting",false),!(this.transportCleanup||this.isDestroyed||!this.wantsConnection)&&this.startConnection());}startConnection(){if(this.isDestroyed||!this.wantsConnection||this.isOpen||this.transportCleanup)return;let e=this.hasTransportSubscription?this.epoch:++this.epoch,t=++this.connectAttempt;if(this.setStatus("connecting",false),!!this.isCurrent(e)){if(!this.hasTransportSubscription){let s;try{if(s=this.transport.onEvent(n=>this.handleTransportEvent(e,n)),typeof s!="function")throw new TypeError("Transport event subscription must return a function")}catch(n){this.failConnection(e,u("transport","Failed to subscribe to transport events",n));return}if(!this.isCurrent(e)){try{s();}catch(n){this.isDestroyed||this.report(u("transport","Failed to unsubscribe from stale transport events",n));}return}this.unsubscribeTransport=s,this.hasTransportSubscription=true;}try{let s=this.transport.connect();s&&s.catch(n=>{this.isCurrent(e)&&this.connectAttempt===t&&this.failConnection(e,u("transport","Transport connect failed",n));});}catch(s){this.failConnection(e,u("transport","Transport connect failed",s));}}}disconnect(){if(this.isDestroyed||!(this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus!=="disconnected"))return;this.clearPending(),this.publishAwareness(null,"best-effort"),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription(),s=this.cleanupTransport(t,true);this.setStatus("disconnected",false);for(let n of s)this.report(n);}destroy(){if(this.isDestroyed)return;let e=this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus==="connecting"||this.connectionStatus==="connected";this.clearPending(),this.publishAwareness(null,"best-effort"),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.isDestroyed=true,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription(),s=this.cleanupTransport(t,e);this.setStatus("destroyed",false);for(let n of s)this.report(n);try{this.unsubscribeReplica();}catch(n){this.report(u("replica","Failed to unsubscribe from replica updates",n));}this.unsubscribeReplica=()=>{},this.statusListeners.clear(),this.errorListeners.clear(),this.awarenessListeners.clear();}onStatus(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("status listener must be a function");let t=this.nextListenerId++;return this.statusListeners.set(t,e),()=>this.statusListeners.delete(t)}onError(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("error listener must be a function");let t=this.nextListenerId++;return this.errorListeners.set(t,e),()=>this.errorListeners.delete(t)}onAwareness(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("awareness listener must be a function");let t=this.nextListenerId++;this.awarenessListeners.set(t,e);try{e(this.peers);}catch{}return ()=>this.awarenessListeners.delete(t)}setCursor(e){if(this.isDestroyed)return;let t=e?Ce(e):false;if(this.awarenessCursor=e&&t?{sheet:e.sheet,anchor:{...e.anchor},head:{...e.head}}:null,e&&!t&&this.report(new h("protocol",`Awareness cursor needs a sheet identifier of 1 to ${256} characters and non-negative cell coordinates; cursor dropped`)),!this.isOpen||!this.wantsConnection)return;let s=80-(Date.now()-this.lastAwarenessSentAt);if(s<=0){this.publishAwareness();return}this.awarenessBroadcastTimer||(this.awarenessBroadcastTimer=setTimeout(()=>{this.awarenessBroadcastTimer=void 0,this.publishAwareness();},s),k(this.awarenessBroadcastTimer));}isCurrent(e){return !this.isDestroyed&&this.wantsConnection&&e===this.epoch}failConnection(e,t){if(!this.isCurrent(e))return;this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let s=this.takeTransportSubscription();this.clearPending();let n=this.cleanupTransport(s,true);this.setStatus("disconnected",false),this.report(t);for(let a of n)this.report(a);}takeTransportSubscription(){let e=this.unsubscribeTransport;return this.unsubscribeTransport=()=>{},this.hasTransportSubscription=false,e}cleanupTransport(e,t){let s=[];try{e();}catch(n){s.push(u("transport","Failed to unsubscribe from transport events",n));}if(!t||this.transportCleanup)return s;try{let n=this.transport.disconnect();if(n){let a=!1,c=Promise.resolve(n).catch(l=>{a=!0,this.isDestroyed||this.report(u("transport","Transport disconnect failed",l));}).finally(()=>{this.transportCleanup===c&&(this.transportCleanup=void 0,!this.isDestroyed&&(a?(this.wantsConnection=!1,this.setStatus("disconnected",!1)):this.wantsConnection&&this.startConnection()));});this.transportCleanup=c;}}catch(n){s.push(u("transport","Transport disconnect failed",n));}return s}handleTransportEvent(e,t){if(this.isCurrent(e))switch(t.type){case "open":this.handleOpen(e);break;case "message":this.isOpen&&this.handleMessage(e,t.data);break;case "close":this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.isOpen=false,this.connectAttempt+=1,this.clearPending(),this.setStatus("disconnected",false);break;case "error":this.failConnection(e,u("transport","Transport error",t.error));break;case "drain":this.isOpen&&this.flushPending();break;default:this.failConnection(e,new h("transport","Unknown transport event"));}}handleOpen(e){if(this.isOpen||(this.isOpen=true,this.hasPublishedAwarenessForOpen=false,this.clearPending(),this.setStatus("connected",false),!this.isCurrent(e)||!this.isOpen))return;let t;try{t=B(this.replica.encodeStateVector(),"encodeStateVector");}catch(s){this.failConnection(e,u("replica","Failed to encode replica state vector",s));return}try{this.sendFrame(Z(t,this.maxFrameBytes));}catch(s){this.failConnection(e,u("protocol","Failed to encode collaboration handshake",s));return}if(!(!this.isCurrent(e)||!this.isOpen)){try{this.sendFrame(se(this.maxFrameBytes));}catch(s){this.report(u("protocol","Failed to encode awareness query",s));}!this.isCurrent(e)||!this.isOpen||(this.hasPublishedAwarenessForOpen||this.publishAwareness(),!(!this.isCurrent(e)||!this.isOpen)&&this.startAwarenessTimers());}}handleMessage(e,t){let s;try{if(!(t instanceof Uint8Array))throw new TypeError("Frame must be a Uint8Array");if(t.byteLength>this.maxFrameBytes)throw new RangeError(`Frame exceeds ${this.maxFrameBytes} bytes`);s=ae(t,this.maxFrameBytes,this.maxMessagesPerFrame);}catch(n){this.failConnection(e,u("protocol","Invalid collaboration frame",n));return}for(let n of s){if(!this.isCurrent(e)||!this.isOpen)return;switch(n.type){case "sync-step-1":this.respondToSyncStep1(e,n.stateVector);break;case "sync-step-2":this.applyRemoteUpdate(e,n.update)&&this.isCurrent(e)&&this.setStatus("connected",true);break;case "update":this.applyRemoteUpdate(e,n.update);break;case "awareness":try{let a=[],c=0,l=R(this.awarenessStore,ne(n.update,b,p=>a.push(p)),this.replica.clientId,Date.now(),{onPeersDiscarded:p=>{c=p;}});for(let p of a)this.report(u("protocol","Invalid awareness update",p));if(c>0&&this.report(new h("protocol",`${c} awareness ${c===1?"entry was":"entries were"} discarded because the tracked peer limit of ${1024} was reached`)),!this.isCurrent(e)||!this.isOpen)return;l&&this.emitAwareness();}catch(a){this.report(u("protocol","Invalid awareness update",a));}break;case "auth":this.failConnection(e,new h("protocol",n.reason?`Authentication denied: ${n.reason}`:"Authentication denied"));return;case "query-awareness":this.publishAwareness();break}}}respondToSyncStep1(e,t){let s;try{s=B(this.replica.encodeStateAsUpdate(oe(t).slice()),"encodeStateAsUpdate");}catch(n){this.failConnection(e,u("replica","Failed to encode replica update",n));return}try{this.sendFrame(ee(s,this.maxFrameBytes));}catch(n){this.failConnection(e,u("protocol","Failed to encode SyncStep2",n));}}applyRemoteUpdate(e,t){try{return this.replica.applyUpdate(oe(t).slice()),!0}catch(s){return this.failConnection(e,u("replica","Failed to apply remote update",s)),false}}forwardLocalUpdate(e){if(this.isDestroyed||!this.isOpen||!this.wantsConnection)return;let t=this.epoch,s;try{s=B(e,"Replica update");}catch(n){this.failConnection(t,u("replica","Invalid replica update",n));return}try{this.sendFrame(te(s,this.maxFrameBytes));}catch(n){this.failConnection(t,u("protocol","Failed to encode update",n));}}publishAwareness(e="current",t="queued"){if(!(!this.isOpen||this.isDestroyed||!this.wantsConnection)){if(this.awarenessBroadcastTimer&&(clearTimeout(this.awarenessBroadcastTimer),this.awarenessBroadcastTimer=void 0),this.awarenessClock>=Number.MAX_SAFE_INTEGER){t==="queued"&&!this.reportedClockExhaustion&&(this.reportedClockExhaustion=true,this.report(new h("protocol","Awareness clock exhausted")));return}this.awarenessClock+=1;try{this.hasPublishedAwarenessForOpen=!0;let s=re([{clientId:this.replica.clientId,clock:this.awarenessClock,state:e===null?null:{user:this.awarenessUser,cursor:this.awarenessCursor}}],this.maxFrameBytes);t==="best-effort"?this.sendBestEffort(s):this.sendFrame(s),this.lastAwarenessSentAt=Date.now();}catch(s){t==="queued"&&this.report(u("protocol","Failed to encode awareness update",s));}}}startAwarenessTimers(){this.stopAwarenessTimers(),this.awarenessHeartbeatTimer=setInterval(()=>{this.publishAwareness();},2e4),this.awarenessExpiryTimer=setInterval(()=>{L(this.awarenessStore,Date.now(),45e3)&&this.emitAwareness();},Ee),k(this.awarenessHeartbeatTimer),k(this.awarenessExpiryTimer);}stopAwarenessTimers(){this.awarenessBroadcastTimer&&clearTimeout(this.awarenessBroadcastTimer),this.awarenessHeartbeatTimer&&clearInterval(this.awarenessHeartbeatTimer),this.awarenessExpiryTimer&&clearInterval(this.awarenessExpiryTimer),this.awarenessBroadcastTimer=void 0,this.awarenessHeartbeatTimer=void 0,this.awarenessExpiryTimer=void 0;}clearAwarenessPeers(){if(this.awarenessStore.size===0)return;let e=this.peers.length>0;this.awarenessStore.clear(),e&&this.emitAwareness();}emitAwareness(){let e=this.peers;for(let[t,s]of [...this.awarenessListeners])if(this.awarenessListeners.get(t)===s)try{s(e);}catch{}}sendFrame(e){if(!this.isOpen||this.isDestroyed||!this.wantsConnection)return;let t=this.epoch;if(this.pendingFrames.length>0){this.queueFrame(t,e);return}let s;try{s=this.transport.send(e.slice());}catch(n){this.failConnection(t,u("transport","Transport send failed",n));return}if(typeof s!="boolean"){this.failConnection(t,new h("transport","Transport send must return a boolean"));return}!s&&this.isCurrent(t)&&this.isOpen&&this.queueFrame(t,e);}sendBestEffort(e){try{this.transport.send(e.slice());}catch{}}queueFrame(e,t){if(t.byteLength>this.maxPendingBytes-this.queuedBytes){this.failConnection(e,new h("backpressure",`Pending collaboration data exceeds ${this.maxPendingBytes} bytes`));return}let s=t.slice();this.pendingFrames.push(s),this.queuedBytes+=s.byteLength;}flushPending(){if(!this.isFlushing){this.isFlushing=true;try{for(;this.isOpen&&!this.isDestroyed&&this.pendingFrames.length>0;){let e=this.epoch,t=this.pendingFrames[0],s;try{s=this.transport.send(t.slice());}catch(n){this.failConnection(e,u("transport","Transport send failed",n));return}if(typeof s!="boolean"){this.failConnection(e,new h("transport","Transport send must return a boolean"));return}if(!s||!this.isOpen||this.pendingFrames[0]!==t)return;this.pendingFrames.shift(),this.queuedBytes-=t.byteLength;}}finally{this.isFlushing=false;}}}clearPending(){this.pendingFrames.length=0,this.queuedBytes=0;}setStatus(e,t){if(this.connectionStatus===e&&this.isSynced===t)return;this.connectionStatus=e,this.isSynced=t;let s=++this.statusRevision,n={status:e,synced:t};for(let[a,c]of [...this.statusListeners]){if(this.statusRevision!==s)return;if(this.statusListeners.get(a)===c)try{c(n);}catch{}}}report(e){for(let[t,s]of [...this.errorListeners])if(this.errorListeners.get(t)===s)try{s(e);}catch{}}};export{v as AWARENESS_BROADCAST_INTERVAL_MS,T as AWARENESS_COLORS,U as AWARENESS_HEARTBEAT_INTERVAL_MS,ce as AWARENESS_LABEL_DURATION_MS,_ as AWARENESS_PEER_TIMEOUT_MS,h as CollaborationError,D as CollaborationProvider,x as MAX_TRACKED_AWARENESS_PEERS,ue as XLSX_MAX_COLUMNS,le as XLSX_MAX_ROWS,R as applyAwarenessUpdates,M as awarenessPeers,W as colorForClientId,L as expireAwarenessPeers,E as normalizeAwarenessColor,P as normalizeCollaborationUser,de as resolveAwarenessCursor};
Binary file
@@ -32,6 +32,7 @@ interface FillRectCmd {
32
32
  h: number;
33
33
  /** css color string (`#rrggbb`, `rgba(...)`), resolved from theme + tint in Rust. */
34
34
  color: string;
35
+ clip?: Rect;
35
36
  }
36
37
  /**
37
38
  * Stroke a straight line — gridlines, cell borders, frozen-pane dividers.
@@ -50,6 +51,43 @@ interface LineCmd {
50
51
  * serialized at its default in Rust, so a solid line omits the field.
51
52
  */
52
53
  style?: 'dashed' | 'dotted' | 'double';
54
+ clip?: Rect;
55
+ }
56
+ type GeometryPathCommand = {
57
+ type: 'move';
58
+ x: number;
59
+ y: number;
60
+ } | {
61
+ type: 'line';
62
+ x: number;
63
+ y: number;
64
+ } | {
65
+ type: 'quad';
66
+ cpx: number;
67
+ cpy: number;
68
+ x: number;
69
+ y: number;
70
+ } | {
71
+ type: 'cubic';
72
+ cp1x: number;
73
+ cp1y: number;
74
+ cp2x: number;
75
+ cp2y: number;
76
+ x: number;
77
+ y: number;
78
+ } | {
79
+ type: 'close';
80
+ };
81
+ interface PathStroke {
82
+ color: string;
83
+ width: number;
84
+ }
85
+ interface PathCmd {
86
+ op: 'path';
87
+ commands: GeometryPathCommand[];
88
+ fill: string;
89
+ stroke?: PathStroke;
90
+ clip?: Rect;
53
91
  }
54
92
  /**
55
93
  * Paint a single-line text run. Spreadsheet cell text is single-line and
@@ -61,6 +99,7 @@ interface TextCmd {
61
99
  x: number;
62
100
  y: number;
63
101
  text: string;
102
+ /** Font size in points. */
64
103
  fontSize: number;
65
104
  /** resolved font color (`#rrggbb`); a number-format color prefix wins upstream. */
66
105
  color: string;
@@ -84,11 +123,12 @@ interface TextCmd {
84
123
  * `new` text). Painted normally, but excluded from a11y text recovery.
85
124
  */
86
125
  ghost?: boolean;
126
+ chart?: boolean;
87
127
  }
88
128
  /**
89
129
  * One draw command; discriminated on `op`.
90
130
  */
91
- type DrawCmd = FillRectCmd | LineCmd | TextCmd;
131
+ type DrawCmd = FillRectCmd | LineCmd | PathCmd | TextCmd;
92
132
  /**
93
133
  * Grid metadata for the frame: which sheet cells the visible tracks map to and
94
134
  * their viewport-local pixel boundaries. `rowOffsets[i]`/`colOffsets[i]` is the
@@ -117,6 +157,35 @@ interface HyperlinkRegion {
117
157
  location?: string;
118
158
  tooltip?: string;
119
159
  }
160
+ /**
161
+ * A chart's placement in the frame: the id that addresses it across the wasm
162
+ * boundary, what a screen reader reads, whether the renderer managed to draw
163
+ * it, its full viewport-local rect and the visible part after pane clipping. A
164
+ * chart that degraded to a placeholder still gets a region, so it stays an
165
+ * addressable object on the sheet.
166
+ *
167
+ * Hand-mirrored from crates/xlsx-render/src/display_list.rs — keep in sync.
168
+ */
169
+ interface ChartRegion {
170
+ /**
171
+ * the drawing part and the anchor in it, unique within a sheet. Opaque —
172
+ * never the chart part's path, which two anchors may share.
173
+ */
174
+ id: string;
175
+ label: string;
176
+ /**
177
+ * the chart could not be drawn; a neutral box occupies its rect instead.
178
+ * skip-serialized at `false` in Rust, so treat absent as `false`.
179
+ */
180
+ placeholder?: boolean;
181
+ rect: Rect;
182
+ /** `rect` intersected with the pane band it paints in — the hit area. */
183
+ clip: Rect;
184
+ /** whether the anchor can be repinned; an absolute one cannot. */
185
+ movable: boolean;
186
+ }
187
+ /** Former name of {@link ChartRegion}, when it carried the label alone. */
188
+ type ChartA11yAttrs = ChartRegion;
120
189
  /**
121
190
  * A full frame to paint: logical size plus the ordered command stream. `grid`
122
191
  * is optional so a synthetic or pre-grid-metadata frame still type-checks; the
@@ -128,11 +197,11 @@ interface DisplayList {
128
197
  commands: DrawCmd[];
129
198
  grid?: GridMeta;
130
199
  hyperlinks?: HyperlinkRegion[];
200
+ charts?: ChartRegion[];
131
201
  }
132
202
 
133
203
  /**
134
- * Pure viewport types. No DOM — this is the compute seam the a11y grid, the
135
- * canvas painter, and a future Rust port all read from.
204
+ * Pure viewport types shared by the accessibility grid and canvas painter.
136
205
  */
137
206
  /**
138
207
  * Cumulative pixel offsets for a track axis (columns or rows). `offsets[i]` is
@@ -175,8 +244,7 @@ interface VisibleCells {
175
244
  /**
176
245
  * Pure viewport math: visible-range computation against cumulative track
177
246
  * offsets, and scroll clamping. No DOM, no side effects — every function is a
178
- * deterministic transform of plain numbers so it is golden-testable and can be
179
- * mirrored in Rust.
247
+ * deterministic transform of plain numbers so it is golden-testable.
180
248
  */
181
249
 
182
250
  /**
@@ -209,7 +277,7 @@ declare function uniformOffsets(count: number, size: number): TrackOffsets;
209
277
 
210
278
  /**
211
279
  * Pure selection types. Plain data only — no DOM, no framework — so the model
212
- * is golden-testable and mirrorable in Rust. The chrome layer interprets the
280
+ * is golden-testable. The chrome layer interprets the
213
281
  * declarative {@link SelectionAction}s the reducer emits.
214
282
  */
215
283
  /**
@@ -347,6 +415,17 @@ declare function selectionKeyReducer(state: Selection, key: KeyInput, limits: Se
347
415
  * handling and the selection overlay share one geometry source with the painter.
348
416
  */
349
417
 
418
+ /**
419
+ * The topmost chart whose visible region contains a viewport-local point, or
420
+ * `null`. Mirrors `chart_at_point` in crates/xlsx-render/src/hit.rs: regions are
421
+ * in paint order so the last match wins, and the clipped region bounds the hit,
422
+ * so a chart scrolled under a frozen pane is not hit where it is hidden.
423
+ *
424
+ * Every coordinate is rounded to f32 first. The regions arrive as f32 off the
425
+ * wire, and the engine compares against `clip.x + clip.w` computed in f32; the
426
+ * same sum in f64 lands on the other side of the edge at reachable coordinates.
427
+ */
428
+ declare function chartRegionAtPoint(charts: readonly ChartRegion[] | undefined, x: number, y: number): ChartRegion | null;
350
429
  /**
351
430
  * The cell under a viewport-local point, or `null` when the point is outside the
352
431
  * visible grid (or the frame carries no grid metadata).
@@ -458,6 +537,11 @@ interface A11yRow {
458
537
  header: string;
459
538
  cells: A11yCell[];
460
539
  }
540
+ interface A11yChart {
541
+ label: string;
542
+ /** the chart could not be drawn; a neutral box occupies its rect instead. */
543
+ placeholder: boolean;
544
+ }
461
545
  /**
462
546
  * The full offscreen grid mirror for the current frame.
463
547
  */
@@ -466,6 +550,7 @@ interface A11yGrid {
466
550
  sheetName: string;
467
551
  columnHeaders: A11yColumnHeader[];
468
552
  rows: A11yRow[];
553
+ charts: A11yChart[];
469
554
  }
470
555
 
471
556
  /**
@@ -483,4 +568,4 @@ interface A11yGrid {
483
568
  */
484
569
  declare function buildA11yGrid(displayList: DisplayList, selection: Selection | null, sheetName: string, t: A11yStrings): A11yGrid;
485
570
 
486
- export { type A11yCell, type A11yColumnHeader, type A11yGrid, type A11yRow, type A11yStrings, type CellAddr, type CellInput, type CellRange, type Direction, type DisplayList, type DrawCmd, type FillRectCmd, type GridMeta, type HyperlinkDestination, type HyperlinkRegion, type KeyInput, type LineCmd, type MoveOpts, type Rect, type Selection, type SelectionAction, type SelectionLimits, type TextAlign, type TextCmd, type TrackOffsets, type ViewportState, type VisibleCells, type VisibleRange, buildA11yGrid, cellAtPoint, cellCount, cellRect, clampScroll, extendTo, fromTsv, hyperlinkAtCell, moveFocus, normalizeRange, parseHyperlinkLocation, rangeContains, rangeRect, safeExternalHyperlink, selectionAt, selectionKeyReducer, toTsv, totalExtent, trackCount, uniformOffsets, visibleCells, visibleRange };
571
+ export { type A11yCell, type A11yChart, type A11yColumnHeader, type A11yGrid, type A11yRow, type A11yStrings, type CellAddr, type CellInput, type CellRange, type ChartA11yAttrs, type ChartRegion, type Direction, type DisplayList, type DrawCmd, type FillRectCmd, type GeometryPathCommand, type GridMeta, type HyperlinkDestination, type HyperlinkRegion, type KeyInput, type LineCmd, type MoveOpts, type PathCmd, type PathStroke, type Rect, type Selection, type SelectionAction, type SelectionLimits, type TextAlign, type TextCmd, type TrackOffsets, type ViewportState, type VisibleCells, type VisibleRange, buildA11yGrid, cellAtPoint, cellCount, cellRect, chartRegionAtPoint, clampScroll, extendTo, fromTsv, hyperlinkAtCell, moveFocus, normalizeRange, parseHyperlinkLocation, rangeContains, rangeRect, safeExternalHyperlink, selectionAt, selectionKeyReducer, toTsv, totalExtent, trackCount, uniformOffsets, visibleCells, visibleRange };
package/dist/headless.js CHANGED
@@ -1 +1 @@
1
- export{v as buildA11yGrid,n as cellAtPoint,j as cellCount,o as cellRect,e as clampScroll,k as extendTo,u as fromTsv,q as hyperlinkAtCell,l as moveFocus,h as normalizeRange,s as parseHyperlinkLocation,i as rangeContains,p as rangeRect,r as safeExternalHyperlink,g as selectionAt,m as selectionKeyReducer,t as toTsv,b as totalExtent,a as trackCount,f as uniformOffsets,d as visibleCells,c as visibleRange}from'./chunk-4LMGHPXC.js';import'./chunk-O2XFH626.js';
1
+ export{w as buildA11yGrid,o as cellAtPoint,j as cellCount,p as cellRect,n as chartRegionAtPoint,e as clampScroll,k as extendTo,v as fromTsv,r as hyperlinkAtCell,l as moveFocus,h as normalizeRange,t as parseHyperlinkLocation,i as rangeContains,q as rangeRect,s as safeExternalHyperlink,g as selectionAt,m as selectionKeyReducer,u as toTsv,b as totalExtent,a as trackCount,f as uniformOffsets,d as visibleCells,c as visibleRange}from'./chunk-E6PJOEEH.js';import'./chunk-O2XFH626.js';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { DisplayList } from './headless.js';
2
- export { A11yCell, A11yColumnHeader, A11yGrid, A11yRow, A11yStrings, CellAddr, CellInput, CellRange, Direction, DrawCmd, FillRectCmd, GridMeta, HyperlinkDestination, HyperlinkRegion, KeyInput, LineCmd, MoveOpts, Rect, Selection, SelectionAction, SelectionLimits, TextAlign, TextCmd, TrackOffsets, ViewportState, VisibleCells, VisibleRange, buildA11yGrid, cellAtPoint, cellCount, cellRect, clampScroll, extendTo, fromTsv, hyperlinkAtCell, moveFocus, normalizeRange, parseHyperlinkLocation, rangeContains, rangeRect, safeExternalHyperlink, selectionAt, selectionKeyReducer, toTsv, totalExtent, trackCount, uniformOffsets, visibleCells, visibleRange } from './headless.js';
1
+ import { DisplayList, ChartRegion } from './headless.js';
2
+ export { A11yCell, A11yChart, A11yColumnHeader, A11yGrid, A11yRow, A11yStrings, CellAddr, CellInput, CellRange, ChartA11yAttrs, Direction, DrawCmd, FillRectCmd, GeometryPathCommand, GridMeta, HyperlinkDestination, HyperlinkRegion, KeyInput, LineCmd, MoveOpts, PathCmd, PathStroke, Rect, Selection, SelectionAction, SelectionLimits, TextAlign, TextCmd, TrackOffsets, ViewportState, VisibleCells, VisibleRange, buildA11yGrid, cellAtPoint, cellCount, cellRect, chartRegionAtPoint, clampScroll, extendTo, fromTsv, hyperlinkAtCell, moveFocus, normalizeRange, parseHyperlinkLocation, rangeContains, rangeRect, safeExternalHyperlink, selectionAt, selectionKeyReducer, toTsv, totalExtent, trackCount, uniformOffsets, visibleCells, visibleRange } from './headless.js';
3
3
  import { C as CollaborationReplica, s as CollaborationUpdateOrigin } from './types-C24EBcAP.js';
4
4
 
5
5
  /**
@@ -14,9 +14,12 @@ import { C as CollaborationReplica, s as CollaborationUpdateOrigin } from './typ
14
14
  /**
15
15
  * Paint a display list into a 2D context. `dpr` maps device-independent list
16
16
  * coordinates onto the backing store, so callers size the canvas at
17
- * `width * dpr` × `height * dpr` and this sets the matching transform.
17
+ * `width * dpr` × `height * dpr`. `origin` is in backing-store pixels.
18
18
  */
19
- declare function paintDisplayList(ctx: CanvasRenderingContext2D, dl: DisplayList, dpr: number): void;
19
+ declare function paintDisplayList(ctx: CanvasRenderingContext2D, dl: DisplayList, dpr: number, origin?: {
20
+ x: number;
21
+ y: number;
22
+ }): void;
20
23
 
21
24
  type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
22
25
 
@@ -38,6 +41,16 @@ interface Viewport {
38
41
  width: number;
39
42
  height: number;
40
43
  }
44
+ interface PrintMetrics {
45
+ dpi: number;
46
+ maxDigitWidth: number;
47
+ defaultRowHeightPt: number;
48
+ defaultColumnWidth?: number;
49
+ fontSizePt: number;
50
+ fontFamily: string;
51
+ fontAscent: number;
52
+ fontDescent: number;
53
+ }
41
54
  /**
42
55
  * Chrome-facing sheet metadata: stable IDs, tab names, active index, and the
43
56
  * scrollable content extent of the active sheet. Mirrors the Rust `SheetInfo`.
@@ -226,6 +239,25 @@ interface WorkbookHandle extends CollaborationReplica {
226
239
  sheetInfo(): SheetInfo;
227
240
  calculationStatus(): CalculationStatus;
228
241
  displayList(viewport: Viewport): DisplayList;
242
+ printDisplayList(sheet: number, range: string, metrics: PrintMetrics, gridlines: boolean): DisplayList;
243
+ /**
244
+ * the chart under a viewport-local point on the active sheet, or `null`,
245
+ * resolved against the current model from the same anchor geometry the
246
+ * display list is built from. the returned `label` is always empty: a hit
247
+ * test resolves anchors only and never reads a chart part.
248
+ *
249
+ * this answers for the model as it is now. chrome painting a frame should
250
+ * hit-test that frame's own `charts` with `chartRegionAtPoint` instead, or a
251
+ * mutation the canvas has not drawn yet will move the answer off the pixels.
252
+ */
253
+ chartAtPoint(viewport: Viewport, x: number, y: number): ChartRegion | null;
254
+ /**
255
+ * slide the chart frame `chart` names — a {@link ChartRegion} id — by a
256
+ * content-pixel delta, clamped to the grid, as one undo step. the new anchor
257
+ * is written back on save. throws for a chart pinned to the sheet by an
258
+ * absolute anchor.
259
+ */
260
+ moveChart(sheet: number, chart: string, dx: number, dy: number): EditResult;
229
261
  setActiveSheet(index: number): void;
230
262
  /**
231
263
  * apply one user input to a cell (parses number/bool/formula/text) and
@@ -322,4 +354,4 @@ declare function openWorkbook(bytes: Uint8Array, options?: OpenWorkbookOptions):
322
354
  */
323
355
  declare function wasmVersion(): string;
324
356
 
325
- export { type BorderPatch, type BorderPreset, type BorderStyle, type CalculationStatus, type CapturedFormat, type CellEdit, type CellInputEdit, type CellPoint, type CellPosition, DisplayList, type EditResult, type HistoryState, type HorizontalAlignment, type MergedRange, type NumberFormat, type NumberFormatMutation, type OpenWorkbookOptions, type Proposal, type ProposalCell, type ProposalEdit, type RangeStylePatch, type SelectionFormatting, type SheetInfo, StaleProposalError, type StyleProperty, type TextWrapping, type VerticalAlignment, type Viewport, type WasmInitInput, type WorkbookHandle, type WorkbookUpdateListener, type WorkbookUpdateOrigin, initWasm, isPngExportAvailable, isProposalsAvailable, isWasmAvailable, openWorkbook, paintDisplayList, wasmVersion };
357
+ export { type BorderPatch, type BorderPreset, type BorderStyle, type CalculationStatus, type CapturedFormat, type CellEdit, type CellInputEdit, type CellPoint, type CellPosition, ChartRegion, DisplayList, type EditResult, type HistoryState, type HorizontalAlignment, type MergedRange, type NumberFormat, type NumberFormatMutation, type OpenWorkbookOptions, type PrintMetrics, type Proposal, type ProposalCell, type ProposalEdit, type RangeStylePatch, type SelectionFormatting, type SheetInfo, StaleProposalError, type StyleProperty, type TextWrapping, type VerticalAlignment, type Viewport, type WasmInitInput, type WorkbookHandle, type WorkbookUpdateListener, type WorkbookUpdateOrigin, initWasm, isPngExportAvailable, isProposalsAvailable, isWasmAvailable, openWorkbook, paintDisplayList, wasmVersion };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export{v as buildA11yGrid,n as cellAtPoint,j as cellCount,o as cellRect,e as clampScroll,k as extendTo,u as fromTsv,q as hyperlinkAtCell,l as moveFocus,h as normalizeRange,s as parseHyperlinkLocation,i as rangeContains,p as rangeRect,r as safeExternalHyperlink,g as selectionAt,m as selectionKeyReducer,t as toTsv,b as totalExtent,a as trackCount,f as uniformOffsets,d as visibleCells,c as visibleRange}from'./chunk-4LMGHPXC.js';import {a}from'./chunk-O2XFH626.js';var he={left:"left",center:"center",right:"right"},xe={dashed:[4,2],dotted:[1,2]};function ve(o,e,n){o.save(),o.setTransform(n,0,0,n,0,0),o.clearRect(0,0,e.width,e.height);for(let t of e.commands)Se(o,t);o.restore();}function Se(o,e){switch(e.op){case "fillRect":o.fillStyle=e.color,o.fillRect(e.x,e.y,e.w,e.h);return;case "line":Ce(o,e);return;case "text":Re(o,e);return}}function Ce(o,e){if(o.strokeStyle=e.color,e.style==="double"){let n=Math.max(e.width*.8,.8),t=Math.abs(e.y1-e.y2)<=Math.abs(e.x1-e.x2),[r,i]=t?[0,n]:[n,0];o.lineWidth=Math.max(e.width*.6,.5),U(o,e.x1-r,e.y1-i,e.x2-r,e.y2-i),U(o,e.x1+r,e.y1+i,e.x2+r,e.y2+i);return}o.lineWidth=e.width,o.save(),o.setLineDash(e.style?xe[e.style]:[]),U(o,e.x1,e.y1,e.x2,e.y2),o.restore();}function U(o,e,n,t,r){o.beginPath(),o.moveTo(e,n),o.lineTo(t,r),o.stroke();}function Re(o,e){o.save(),e.clip&&(o.beginPath(),o.rect(e.clip.x,e.clip.y,e.clip.w,e.clip.h),o.clip()),o.fillStyle=e.color,o.font=Je(e),o.textAlign=he[e.align??"left"],o.textBaseline="alphabetic",e.highlight&&Pe(o,e),o.fillStyle=e.color,o.fillText(e.text,e.x,e.y),(e.underline||e.strike||e.dashedUnderline)&&Ae(o,e),o.restore();}function Je(o){let e=o.italic?"italic ":"",n=o.bold?"bold ":"",t=o.fontFamily?`"${o.fontFamily}", sans-serif`:"sans-serif";return `${e}${n}${o.fontSize}px ${t}`}function Ae(o,e){let n=o.measureText(e.text).width,t=e.align??"left",r=t==="right"?e.x-n:t==="center"?e.x-n/2:e.x,i=Math.max(e.fontSize*.05,.5);o.fillStyle=e.color,e.underline&&o.fillRect(r,e.y+e.fontSize*.1,n,i),e.strike&&o.fillRect(r,e.y-e.fontSize*.26,n,i),e.dashedUnderline&&(o.save(),o.strokeStyle=e.color,o.lineWidth=i,o.setLineDash([3,2]),U(o,r,e.y+e.fontSize*.1,r+n,e.y+e.fontSize*.1),o.restore());}function Pe(o,e){let n=o.measureText(e.text),t=n.width,r=e.align??"left",i=r==="right"?e.x-t:r==="center"?e.x-t/2:e.x,d=n.actualBoundingBoxAscent||e.fontSize*.8,c=n.actualBoundingBoxDescent||e.fontSize*.2;o.fillStyle=e.highlight,o.fillRect(i-2,e.y-d-1,t+4,d+c+2);}var x=class o{static __wrap(e){let n=Object.create(o.prototype);return n.__wbg_ptr=e,V.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,V.unregister(this),e}free(){let e=this.__destroy_into_raw();s.__wbg_xlsxdocument_free(e,0);}acceptProposalJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_acceptProposalJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}applyFormatJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_applyFormatJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}applyOpsJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_applyOpsJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}applyUpdateJson(e){let n,t;try{let d=I(e,s.__wbindgen_malloc),c=g,a=s.xlsxdocument_applyUpdateJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}calculationStatusJson(){let e,n;try{let i=s.xlsxdocument_calculationStatusJson(this.__wbg_ptr);var t=i[0],r=i[1];if(i[3])throw t=0,r=0,_(i[2]);return e=t,n=r,p(t,r)}finally{s.__wbindgen_free(e,n,1);}}captureFormatJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_captureFormatJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}cellJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_cellJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}cellPositionJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_cellPositionJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}clearUpdateObservation(){s.xlsxdocument_clearUpdateObservation(this.__wbg_ptr);}get clientId(){return s.xlsxdocument_clientId(this.__wbg_ptr)}displayListJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_displayListJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}drainUpdateEvent(){let e=s.xlsxdocument_drainUpdateEvent(this.__wbg_ptr);if(e[3])throw _(e[2]);var n=h(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),n}editCellJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_editCellJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}editCellsJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_editCellsJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}encodeDiff(e){let n=I(e,s.__wbindgen_malloc),t=g,r=s.xlsxdocument_encodeDiff(this.__wbg_ptr,n,t);if(r[3])throw _(r[2]);var i=h(r[0],r[1]).slice();return s.__wbindgen_free(r[0],r[1]*1,1),i}encodeStateAsUpdate(){let e=s.xlsxdocument_encodeStateAsUpdate(this.__wbg_ptr);var n=h(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),n}encodeStateVector(){let e=s.xlsxdocument_encodeStateVector(this.__wbg_ptr);var n=h(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),n}historyStateJson(){let e,n;try{let i=s.xlsxdocument_historyStateJson(this.__wbg_ptr);var t=i[0],r=i[1];if(i[3])throw t=0,r=0,_(i[2]);return e=t,n=r,p(t,r)}finally{s.__wbindgen_free(e,n,1);}}listProposalsJson(){let e,n;try{let i=s.xlsxdocument_listProposalsJson(this.__wbg_ptr);var t=i[0],r=i[1];if(i[3])throw t=0,r=0,_(i[2]);return e=t,n=r,p(t,r)}finally{s.__wbindgen_free(e,n,1);}}mergedRangesJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_mergedRangesJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}static open(e){let n=I(e,s.__wbindgen_malloc),t=g,r=s.xlsxdocument_open(n,t);if(r[2])throw _(r[1]);return o.__wrap(r[0])}static openCollaborative(e,n){let t=I(e,s.__wbindgen_malloc),r=g,i=s.xlsxdocument_openCollaborative(t,r,n);if(i[2])throw _(i[1]);return o.__wrap(i[0])}patchRangeStyleJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_patchRangeStyleJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}proposeJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_proposeJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}rangeCellsJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_rangeCellsJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}redoJson(){let e,n;try{let i=s.xlsxdocument_redoJson(this.__wbg_ptr);var t=i[0],r=i[1];if(i[3])throw t=0,r=0,_(i[2]);return e=t,n=r,p(t,r)}finally{s.__wbindgen_free(e,n,1);}}rejectProposalJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_rejectProposalJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}renderPng(e){let n=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),t=g,r=s.xlsxdocument_renderPng(this.__wbg_ptr,n,t);if(r[3])throw _(r[2]);var i=h(r[0],r[1]).slice();return s.__wbindgen_free(r[0],r[1]*1,1),i}renderRangePng(e){let n=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),t=g,r=s.xlsxdocument_renderRangePng(this.__wbg_ptr,n,t);if(r[3])throw _(r[2]);var i=h(r[0],r[1]).slice();return s.__wbindgen_free(r[0],r[1]*1,1),i}saveBytes(){let e=s.xlsxdocument_saveBytes(this.__wbg_ptr);if(e[3])throw _(e[2]);var n=h(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),n}selectionFormattingJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_selectionFormattingJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}setActiveSheet(e){let n=s.xlsxdocument_setActiveSheet(this.__wbg_ptr,e);if(n[1])throw _(n[0])}setRangeNumberFormatJson(e){let n,t;try{let d=b(e,s.__wbindgen_malloc,s.__wbindgen_realloc),c=g,a=s.xlsxdocument_setRangeNumberFormatJson(this.__wbg_ptr,d,c);var r=a[0],i=a[1];if(a[3])throw r=0,i=0,_(a[2]);return n=r,t=i,p(r,i)}finally{s.__wbindgen_free(n,t,1);}}sheetInfoJson(){let e,n;try{let i=s.xlsxdocument_sheetInfoJson(this.__wbg_ptr);var t=i[0],r=i[1];if(i[3])throw t=0,r=0,_(i[2]);return e=t,n=r,p(t,r)}finally{s.__wbindgen_free(e,n,1);}}startUpdateObservation(){let e=s.xlsxdocument_startUpdateObservation(this.__wbg_ptr);if(e[1])throw _(e[0])}undoJson(){let e,n;try{let i=s.xlsxdocument_undoJson(this.__wbg_ptr);var t=i[0],r=i[1];if(i[3])throw t=0,r=0,_(i[2]);return e=t,n=r,p(t,r)}finally{s.__wbindgen_free(e,n,1);}}static version(){let e,n;try{let t=s.xlsxdocument_version();return e=t[0],n=t[1],p(t[0],t[1])}finally{s.__wbindgen_free(e,n,1);}}};Symbol.dispose&&(x.prototype[Symbol.dispose]=x.prototype.free);function Ee(){return {__proto__:null,"./xlsx_wasm_bg.js":{__proto__:null,__wbg___wbindgen_string_get_b0ca35b86a603356:function(e,n){let t=n,r=typeof t=="string"?t:void 0;var i=Oe(r)?0:b(r,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g;B().setInt32(e+4,d,true),B().setInt32(e+0,i,true);},__wbg___wbindgen_throw_344f42d3211c4765:function(e,n){throw new Error(p(e,n))},__wbg_getRandomValues_3f44b700395062e5:function(){return N(function(e,n){globalThis.crypto.getRandomValues(h(e,n));},arguments)},__wbg_get_78f252d074a84d0b:function(){return N(function(e,n){return Reflect.get(e,n)},arguments)},__wbg_get_unchecked_6e0ad6d2a41b06f6:function(e,n){return e[n>>>0]},__wbg_instanceof_Object_33f20e6f12439f3e:function(e){let n;try{n=e instanceof Object;}catch{n=false;}return n},__wbg_keys_58421f8f96795607:function(e){return Object.keys(e)},__wbg_length_1f0964f4a5e2c6d8:function(e){return e.length},__wbg_length_370319915dc99107:function(e){return e.length},__wbg_new_cd45aabdf6073e84:function(e){return new Uint8Array(e)},__wbg_new_da52cf8fe3429cb2:function(){return new Object},__wbg_new_from_slice_77cdfb7977362f3c:function(e,n){return new Uint8Array(h(e,n))},__wbg_now_86c0d4ba3fa605b8:function(){return Date.now()},__wbg_prototypesetcall_4770620bbe4688a0:function(e,n,t){Uint8Array.prototype.set.call(h(e,n),t);},__wbg_set_8535240470bf2500:function(){return N(function(e,n,t){return Reflect.set(e,n,t)},arguments)},__wbindgen_cast_0000000000000001:function(e,n){return p(e,n)},__wbindgen_init_externref_table:function(){let e=s.__wbindgen_externrefs,n=e.grow(4);e.set(0,void 0),e.set(n+0,void 0),e.set(n+1,null),e.set(n+2,true),e.set(n+3,false);}}}}var V=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(o=>s.__wbg_xlsxdocument_free(o,1));function ke(o){let e=s.__externref_table_alloc();return s.__wbindgen_externrefs.set(e,o),e}function h(o,e){return o=o>>>0,R().subarray(o/1,o/1+e)}var S=null;function B(){return (S===null||S.buffer.detached===true||S.buffer.detached===void 0&&S.buffer!==s.memory.buffer)&&(S=new DataView(s.memory.buffer)),S}function p(o,e){return Ie(o>>>0,e)}var J=null;function R(){return (J===null||J.byteLength===0)&&(J=new Uint8Array(s.memory.buffer)),J}function N(o,e){try{return o.apply(this,e)}catch(n){let t=ke(n);s.__wbindgen_exn_store(t);}}function Oe(o){return o==null}function I(o,e){let n=e(o.length*1,1)>>>0;return R().set(o,n/1),g=o.length,n}function b(o,e,n){if(n===void 0){let c=A.encode(o),a=e(c.length,1)>>>0;return R().subarray(a,a+c.length).set(c),g=c.length,a}let t=o.length,r=e(t,1)>>>0,i=R(),d=0;for(;d<t;d++){let c=o.charCodeAt(d);if(c>127)break;i[r+d]=c;}if(d!==t){d!==0&&(o=o.slice(d)),r=n(r,t,t=d+o.length*3,1)>>>0;let c=R().subarray(r+d,r+t),a=A.encodeInto(o,c);d+=a.written,r=n(r,t,d,1)>>>0;}return g=d,r}function _(o){let e=s.__wbindgen_externrefs.get(o);return s.__externref_table_dealloc(o),e}var T=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});T.decode();var Ue=2146435072,D=0;function Ie(o,e){return D+=e,D>=Ue&&(T=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true}),T.decode(),D=e),T.decode(R().subarray(o,o+e))}var A=new TextEncoder;"encodeInto"in A||(A.encodeInto=function(o,e){let n=A.encode(o);return e.set(n),{read:o.length,written:n.length}});var g=0,s;function We(o,e){return s=o.exports,S=null,J=null,s.__wbindgen_start(),s}async function Ne(o,e){if(typeof Response=="function"&&o instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(o,e)}catch(r){if(o.ok&&n(o.type)&&o.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}let t=await o.arrayBuffer();return await WebAssembly.instantiate(t,e)}else {let t=await WebAssembly.instantiate(o,e);return t instanceof WebAssembly.Instance?{instance:t,module:o}:t}function n(t){switch(t){case "basic":case "cors":case "default":return true}return false}}async function j(o){if(s!==void 0)return s;if(o!==void 0&&(Object.getPrototypeOf(o)===Object.prototype?{module_or_path:o}=o:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),o===void 0)throw new Error("xlsx-wasm requires an explicit module or URL");let e=Ee();(typeof o=="string"||typeof Request=="function"&&o instanceof Request||typeof URL=="function"&&o instanceof URL)&&(o=fetch(o));let{instance:n,module:t}=await Ne(await o,e);return We(n)}var F=class extends Error{constructor(n){super(`stale: ${n.join(", ")}`);a(this,"cells");this.name="StaleProposalError",this.cells=n;}},H="stale: ";function De(o){let e=o.slice(H.length).split(",").map(n=>n.trim()).filter(n=>n.length>0);return new F(e)}var z=false,P;function ze(o=new URL("./generated/xlsx_wasm_bg.wasm",import.meta.url)){return z?Promise.resolve():P||(P=j({module_or_path:o}).then(()=>{z=true;},e=>{throw P=void 0,E(e)}),P)}function X(){if(!z)throw new Error("xlsx wasm is not initialized; call initWasm() first")}function E(o){return o instanceof Error?o:new Error(typeof o=="string"?o:String(o))}function Le(){return typeof WebAssembly=="object"}function Me(){return typeof x.prototype.renderPng=="function"}function Ve(){return typeof x.prototype.proposeJson=="function"}function Be(o,e={}){X();let n=je(e),t;try{t=n===void 0?x.open(o):x.openCollaborative(o,n);}catch(l){throw E(l)}let r=new Map,i=[],d=0,c=false,a=false,k=0,W=false;function L(){if(c)throw new Error("workbook handle is disposed")}function $(){if(!(c||W||k!==0)){W=true;try{for(;!c&&i.length>0;){let l=i.shift();if(!l)break;for(let[u,f]of [...r]){if(c)return;if(r.get(u)===f)try{f(l.update.slice(),l.origin);}catch{}}}}finally{W=false,c&&(i.length=0);}}}function q(){if(!(!a||c))for(;;){let l=t.drainUpdateEvent();if(l.byteLength===0)return;let u=l[0];if(u!==0&&u!==1)throw new Error(`xlsx wasm returned unknown update origin ${u}`);i.push({update:l.slice(1),origin:u===0?"local":"remote"});}}function m(l,u=false){L(),k+=1;try{let f,w,C=!1;try{f=l();}catch(v){w=v,C=!0;}if(u)try{q();}catch(v){C||(w=v,C=!0);}if(C)throw E(w);return f}finally{k-=1,k===0&&$();}}function O(l){return m(l,true)}function y(l,u=false){return m(()=>JSON.parse(l()),u)}function G(){a||(m(()=>t.startUpdateObservation()),a=true);}function K(){!a||r.size>0||c||(i.length=0,m(()=>t.clearUpdateObservation()),a=false);}return {get clientId(){return m(()=>t.clientId)},encodeStateVector(){return m(()=>t.encodeStateVector().slice())},encodeStateAsUpdate(l){return m(()=>l===void 0?t.encodeStateAsUpdate().slice():t.encodeDiff(l.slice()).slice())},applyUpdate(l){return y(()=>t.applyUpdateJson(l.slice()),true)},onUpdate(l){if(L(),typeof l!="function")throw new TypeError("update listener must be a function");let u=d++;r.set(u,l);try{G();}catch(w){throw r.delete(u),w}let f=true;return ()=>{f&&(f=false,r.delete(u),K());}},sheetInfo(){return y(()=>t.sheetInfoJson())},calculationStatus(){return m(()=>{let l=t.calculationStatusJson;return typeof l!="function"?{limitedCells:[]}:JSON.parse(l.call(t))})},displayList(l){return y(()=>t.displayListJson(JSON.stringify(l)))},setActiveSheet(l){O(()=>t.setActiveSheet(l));},editCell(l,u,f,w){return y(()=>t.editCellJson(JSON.stringify({sheet:l,row:u,col:f,input:w})),true)},editCells(l,u){return y(()=>t.editCellsJson(JSON.stringify({sheet:l,edits:u})),true)},applyOps(l){return y(()=>t.applyOpsJson(JSON.stringify({ops:l})),true)},undo(){return y(()=>t.undoJson(),true)},redo(){return y(()=>t.redoJson(),true)},cell(l,u,f){return y(()=>t.cellJson(JSON.stringify({sheet:l,row:u,col:f})))},cellPosition(l,u,f){return y(()=>t.cellPositionJson(JSON.stringify({sheet:l,row:u,col:f})))},rangeCells(l,u){return y(()=>t.rangeCellsJson(JSON.stringify({sheet:l,range:u}))).cells},patchRangeStyle(l,u,f){return y(()=>t.patchRangeStyleJson(JSON.stringify({sheet:l,range:u,patch:f})),true)},setNumberFormat(l,u,f){let w=typeof f=="string"?{type:f}:f;return y(()=>t.setRangeNumberFormatJson(JSON.stringify({sheet:l,range:u,format:w})),true)},selectionFormatting(l,u){return y(()=>t.selectionFormattingJson(JSON.stringify({sheet:l,range:u})))},captureFormat(l,u){return y(()=>t.captureFormatJson(JSON.stringify({sheet:l,range:u})))},applyFormat(l,u,f){return y(()=>t.applyFormatJson(JSON.stringify({sheet:l,range:u,format:f})),true)},mergedRanges(l,u){return y(()=>t.mergedRangesJson(JSON.stringify({sheet:l,range:u}))).ranges},historyState(){return y(()=>t.historyStateJson())},renderPng(l){return m(()=>{let u=t.renderPng;if(typeof u!="function")throw new Error("png export not in this build");return u.call(t,JSON.stringify(l)).slice()})},renderRangePng(l){return m(()=>{let u=t.renderRangePng;if(typeof u!="function")throw new Error("png export not in this build");return u.call(t,JSON.stringify(l??{})).slice()})},save(){return m(()=>t.saveBytes().slice())},propose(l,u,f){return O(()=>{let w=t.proposeJson;if(typeof w!="function")throw new Error("proposals not in this build");let C=f.map(({numberFormat:v,...Y})=>({...Y,...v===void 0?{}:{numberFormat:typeof v=="string"?{type:v}:v}}));return JSON.parse(w.call(t,JSON.stringify({agentId:l,note:u,edits:C})))})},listProposals(){return m(()=>{let l=t.listProposalsJson;return typeof l!="function"?[]:JSON.parse(l.call(t)).proposals})},acceptProposal(l,u){try{return O(()=>{let f=t.acceptProposalJson;if(typeof f!="function")throw new Error("proposals not in this build");return JSON.parse(f.call(t,JSON.stringify({id:l,force:u?.force??!1})))})}catch(f){let w=f instanceof Error?f.message:typeof f=="string"?f:String(f);throw w.startsWith(H)?De(w):E(f)}},rejectProposal(l){return O(()=>{let u=t.rejectProposalJson;return typeof u!="function"?false:JSON.parse(u.call(t,JSON.stringify({id:l}))).removed})},isProposalsAvailable(){return m(()=>typeof t.proposeJson=="function")},dispose(){if(c)return;c=true,r.clear(),i.length=0;let l;if(a){try{t.clearUpdateObservation();}catch(u){l=u;}a=false;}try{t.free();}catch(u){l??(l=u);}if(l!==void 0)throw E(l)}}}function je(o){if(!o.collaborative){if(o.clientId!==void 0)throw new TypeError("clientId requires collaborative mode");return}if(o.clientId!==void 0){if(!Number.isSafeInteger(o.clientId)||o.clientId<=0||o.clientId>Number.MAX_SAFE_INTEGER)throw new RangeError("clientId must be a nonzero safe integer");return o.clientId}let e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw new Error("crypto.getRandomValues is required to generate a collaboration client ID");let n=new Uint32Array(2),t;do e.getRandomValues(n),t=(n[0]&2097151)*4294967296+n[1];while(t===0);return t}function He(){return X(),x.version()}export{F as StaleProposalError,ze as initWasm,Me as isPngExportAvailable,Ve as isProposalsAvailable,Le as isWasmAvailable,Be as openWorkbook,ve as paintDisplayList,He as wasmVersion};
1
+ export{w as buildA11yGrid,o as cellAtPoint,j as cellCount,p as cellRect,n as chartRegionAtPoint,e as clampScroll,k as extendTo,v as fromTsv,r as hyperlinkAtCell,l as moveFocus,h as normalizeRange,t as parseHyperlinkLocation,i as rangeContains,q as rangeRect,s as safeExternalHyperlink,g as selectionAt,m as selectionKeyReducer,u as toTsv,b as totalExtent,a as trackCount,f as uniformOffsets,d as visibleCells,c as visibleRange}from'./chunk-E6PJOEEH.js';import {a}from'./chunk-O2XFH626.js';var he=1.3333333333333333,xe={left:"left",center:"center",right:"right"},ve={dashed:[4,2],dotted:[1,2]};function Ce(r,e,n,t={x:0,y:0}){r.save(),r.setTransform(n,0,0,n,t.x,t.y),r.beginPath(),r.rect(0,0,e.width,e.height),r.clip(),r.clearRect(0,0,e.width,e.height);for(let o of e.commands)Se(r,o);r.restore();}function Se(r,e){switch(e.op){case "fillRect":W(r,e.clip,()=>{r.fillStyle=e.color,r.fillRect(e.x,e.y,e.w,e.h);});return;case "line":W(r,e.clip,()=>Re(r,e));return;case "path":W(r,e.clip,()=>Pe(r,e));return;case "text":Je(r,e);return}}function W(r,e,n){if(!e){n();return}r.save(),r.beginPath(),r.rect(e.x,e.y,e.w,e.h),r.clip(),n(),r.restore();}function Pe(r,e){r.beginPath();for(let n of e.commands)switch(n.type){case "move":r.moveTo(n.x,n.y);break;case "line":r.lineTo(n.x,n.y);break;case "quad":r.quadraticCurveTo(n.cpx,n.cpy,n.x,n.y);break;case "cubic":r.bezierCurveTo(n.cp1x,n.cp1y,n.cp2x,n.cp2y,n.x,n.y);break;case "close":r.closePath();break}r.fillStyle=e.fill,r.fill(),e.stroke&&(r.strokeStyle=e.stroke.color,r.lineWidth=e.stroke.width,r.setLineDash([]),r.stroke());}function Re(r,e){if(r.strokeStyle=e.color,e.style==="double"){let n=Math.max(e.width*.8,.8),t=Math.abs(e.y1-e.y2)<=Math.abs(e.x1-e.x2),[o,i]=t?[0,n]:[n,0];r.lineWidth=Math.max(e.width*.6,.5),O(r,e.x1-o,e.y1-i,e.x2-o,e.y2-i),O(r,e.x1+o,e.y1+i,e.x2+o,e.y2+i);return}r.lineWidth=e.width,r.save(),r.setLineDash(e.style?ve[e.style]:[]),O(r,e.x1,e.y1,e.x2,e.y2),r.restore();}function O(r,e,n,t,o){r.beginPath(),r.moveTo(e,n),r.lineTo(t,o),r.stroke();}function Je(r,e){r.save(),e.clip&&(r.beginPath(),r.rect(e.clip.x,e.clip.y,e.clip.w,e.clip.h),r.clip()),r.fillStyle=e.color,r.font=Ae(e),r.textAlign=xe[e.align??"left"],r.textBaseline="alphabetic",e.highlight&&ke(r,e),r.fillStyle=e.color,r.fillText(e.text,e.x,e.y),(e.underline||e.strike||e.dashedUnderline)&&Ee(r,e),r.restore();}function Ae(r){let e=r.italic?"italic ":"",n=r.bold?"bold ":"",t=r.fontFamily?r.chart?r.fontFamily:`"${r.fontFamily.replace(/"/g,'\\"')}", sans-serif`:"sans-serif";return `${e}${n}${D(r)}px ${t}`}function D(r){return r.fontSize*he}function Ee(r,e){let n=r.measureText(e.text).width,t=e.align??"left",o=t==="right"?e.x-n:t==="center"?e.x-n/2:e.x,i=D(e),c=Math.max(i*.05,.5);r.fillStyle=e.color,e.underline&&r.fillRect(o,e.y+i*.1,n,c),e.strike&&r.fillRect(o,e.y-i*.26,n,c),e.dashedUnderline&&(r.save(),r.strokeStyle=e.color,r.lineWidth=c,r.setLineDash([3,2]),O(r,o,e.y+i*.1,o+n,e.y+i*.1),r.restore());}function ke(r,e){let n=r.measureText(e.text),t=n.width,o=e.align??"left",i=o==="right"?e.x-t:o==="center"?e.x-t/2:e.x,c=D(e),d=n.actualBoundingBoxAscent||c*.8,a=n.actualBoundingBoxDescent||c*.2;r.fillStyle=e.highlight,r.fillRect(i-2,e.y-d-1,t+4,d+a+2);}var h=class r{static __wrap(e){let n=Object.create(r.prototype);return n.__wbg_ptr=e,V.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,V.unregister(this),e}free(){let e=this.__destroy_into_raw();s.__wbg_xlsxdocument_free(e,0);}acceptProposalJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_acceptProposalJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}applyFormatJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_applyFormatJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}applyOpsJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_applyOpsJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}applyUpdateJson(e){let n,t;try{let c=U(e,s.__wbindgen_malloc),d=g,a=s.xlsxdocument_applyUpdateJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}calculationStatusJson(){let e,n;try{let i=s.xlsxdocument_calculationStatusJson(this.__wbg_ptr);var t=i[0],o=i[1];if(i[3])throw t=0,o=0,_(i[2]);return e=t,n=o,p(t,o)}finally{s.__wbindgen_free(e,n,1);}}captureFormatJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_captureFormatJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}cellJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_cellJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}cellPositionJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_cellPositionJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}chartAtPointJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_chartAtPointJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}clearUpdateObservation(){s.xlsxdocument_clearUpdateObservation(this.__wbg_ptr);}get clientId(){return s.xlsxdocument_clientId(this.__wbg_ptr)}displayListJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_displayListJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}drainUpdateEvent(){let e=s.xlsxdocument_drainUpdateEvent(this.__wbg_ptr);if(e[3])throw _(e[2]);var n=v(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),n}editCellJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_editCellJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}editCellsJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_editCellsJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}encodeDiff(e){let n=U(e,s.__wbindgen_malloc),t=g,o=s.xlsxdocument_encodeDiff(this.__wbg_ptr,n,t);if(o[3])throw _(o[2]);var i=v(o[0],o[1]).slice();return s.__wbindgen_free(o[0],o[1]*1,1),i}encodeStateAsUpdate(){let e=s.xlsxdocument_encodeStateAsUpdate(this.__wbg_ptr);var n=v(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),n}encodeStateVector(){let e=s.xlsxdocument_encodeStateVector(this.__wbg_ptr);var n=v(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),n}historyStateJson(){let e,n;try{let i=s.xlsxdocument_historyStateJson(this.__wbg_ptr);var t=i[0],o=i[1];if(i[3])throw t=0,o=0,_(i[2]);return e=t,n=o,p(t,o)}finally{s.__wbindgen_free(e,n,1);}}listProposalsJson(){let e,n;try{let i=s.xlsxdocument_listProposalsJson(this.__wbg_ptr);var t=i[0],o=i[1];if(i[3])throw t=0,o=0,_(i[2]);return e=t,n=o,p(t,o)}finally{s.__wbindgen_free(e,n,1);}}mergedRangesJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_mergedRangesJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}moveChartJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_moveChartJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}static open(e){let n=U(e,s.__wbindgen_malloc),t=g,o=s.xlsxdocument_open(n,t);if(o[2])throw _(o[1]);return r.__wrap(o[0])}static openCollaborative(e,n){let t=U(e,s.__wbindgen_malloc),o=g,i=s.xlsxdocument_openCollaborative(t,o,n);if(i[2])throw _(i[1]);return r.__wrap(i[0])}patchRangeStyleJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_patchRangeStyleJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}printDisplayListJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_printDisplayListJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}proposeJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_proposeJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}rangeCellsJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_rangeCellsJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}redoJson(){let e,n;try{let i=s.xlsxdocument_redoJson(this.__wbg_ptr);var t=i[0],o=i[1];if(i[3])throw t=0,o=0,_(i[2]);return e=t,n=o,p(t,o)}finally{s.__wbindgen_free(e,n,1);}}rejectProposalJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_rejectProposalJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}renderPng(e){let n=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),t=g,o=s.xlsxdocument_renderPng(this.__wbg_ptr,n,t);if(o[3])throw _(o[2]);var i=v(o[0],o[1]).slice();return s.__wbindgen_free(o[0],o[1]*1,1),i}renderRangePng(e){let n=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),t=g,o=s.xlsxdocument_renderRangePng(this.__wbg_ptr,n,t);if(o[3])throw _(o[2]);var i=v(o[0],o[1]).slice();return s.__wbindgen_free(o[0],o[1]*1,1),i}saveBytes(){let e=s.xlsxdocument_saveBytes(this.__wbg_ptr);if(e[3])throw _(e[2]);var n=v(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),n}selectionFormattingJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_selectionFormattingJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}setActiveSheet(e){let n=s.xlsxdocument_setActiveSheet(this.__wbg_ptr,e);if(n[1])throw _(n[0])}setRangeNumberFormatJson(e){let n,t;try{let c=y(e,s.__wbindgen_malloc,s.__wbindgen_realloc),d=g,a=s.xlsxdocument_setRangeNumberFormatJson(this.__wbg_ptr,c,d);var o=a[0],i=a[1];if(a[3])throw o=0,i=0,_(a[2]);return n=o,t=i,p(o,i)}finally{s.__wbindgen_free(n,t,1);}}sheetInfoJson(){let e,n;try{let i=s.xlsxdocument_sheetInfoJson(this.__wbg_ptr);var t=i[0],o=i[1];if(i[3])throw t=0,o=0,_(i[2]);return e=t,n=o,p(t,o)}finally{s.__wbindgen_free(e,n,1);}}startUpdateObservation(){let e=s.xlsxdocument_startUpdateObservation(this.__wbg_ptr);if(e[1])throw _(e[0])}undoJson(){let e,n;try{let i=s.xlsxdocument_undoJson(this.__wbg_ptr);var t=i[0],o=i[1];if(i[3])throw t=0,o=0,_(i[2]);return e=t,n=o,p(t,o)}finally{s.__wbindgen_free(e,n,1);}}static version(){let e,n;try{let t=s.xlsxdocument_version();return e=t[0],n=t[1],p(t[0],t[1])}finally{s.__wbindgen_free(e,n,1);}}};Symbol.dispose&&(h.prototype[Symbol.dispose]=h.prototype.free);function Oe(){return {__proto__:null,"./xlsx_wasm_bg.js":{__proto__:null,__wbg___wbindgen_throw_344f42d3211c4765:function(e,n){throw new Error(p(e,n))},__wbg_getRandomValues_3f44b700395062e5:function(){return Ie(function(e,n){globalThis.crypto.getRandomValues(v(e,n));},arguments)},__wbg_now_86c0d4ba3fa605b8:function(){return Date.now()},__wbindgen_cast_0000000000000001:function(e,n){return p(e,n)},__wbindgen_init_externref_table:function(){let e=s.__wbindgen_externrefs,n=e.grow(4);e.set(0,void 0),e.set(n+0,void 0),e.set(n+1,null),e.set(n+2,true),e.set(n+3,false);}}}}var V=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(r=>s.__wbg_xlsxdocument_free(r,1));function Ue(r){let e=s.__externref_table_alloc();return s.__wbindgen_externrefs.set(e,r),e}function v(r,e){return r=r>>>0,S().subarray(r/1,r/1+e)}function p(r,e){return Fe(r>>>0,e)}var P=null;function S(){return (P===null||P.byteLength===0)&&(P=new Uint8Array(s.memory.buffer)),P}function Ie(r,e){try{return r.apply(this,e)}catch(n){let t=Ue(n);s.__wbindgen_exn_store(t);}}function U(r,e){let n=e(r.length*1,1)>>>0;return S().set(r,n/1),g=r.length,n}function y(r,e,n){if(n===void 0){let d=R.encode(r),a=e(d.length,1)>>>0;return S().subarray(a,a+d.length).set(d),g=d.length,a}let t=r.length,o=e(t,1)>>>0,i=S(),c=0;for(;c<t;c++){let d=r.charCodeAt(c);if(d>127)break;i[o+c]=d;}if(c!==t){c!==0&&(r=r.slice(c)),o=n(o,t,t=c+r.length*3,1)>>>0;let d=S().subarray(o+c,o+t),a=R.encodeInto(r,d);c+=a.written,o=n(o,t,c,1)>>>0;}return g=c,o}function _(r){let e=s.__wbindgen_externrefs.get(r);return s.__externref_table_dealloc(r),e}var I=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});I.decode();var Te=2146435072,N=0;function Fe(r,e){return N+=e,N>=Te&&(I=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true}),I.decode(),N=e),I.decode(S().subarray(r,r+e))}var R=new TextEncoder;"encodeInto"in R||(R.encodeInto=function(r,e){let n=R.encode(r);return e.set(n),{read:r.length,written:n.length}});var g=0,s;function Ne(r,e){return s=r.exports,P=null,s.__wbindgen_start(),s}async function Le(r,e){if(typeof Response=="function"&&r instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(r,e)}catch(o){if(r.ok&&n(r.type)&&r.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}let t=await r.arrayBuffer();return await WebAssembly.instantiate(t,e)}else {let t=await WebAssembly.instantiate(r,e);return t instanceof WebAssembly.Instance?{instance:t,module:r}:t}function n(t){switch(t){case "basic":case "cors":case "default":return true}return false}}async function B(r){if(s!==void 0)return s;if(r!==void 0&&(Object.getPrototypeOf(r)===Object.prototype?{module_or_path:r}=r:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),r===void 0)throw new Error("xlsx-wasm requires an explicit module or URL");let e=Oe();(typeof r=="string"||typeof Request=="function"&&r instanceof Request||typeof URL=="function"&&r instanceof URL)&&(r=fetch(r));let{instance:n,module:t}=await Le(await r,e);return Ne(n)}var T=class extends Error{constructor(n){super(`stale: ${n.join(", ")}`);a(this,"cells");this.name="StaleProposalError",this.cells=n;}},H="stale: ";function Me(r){let e=r.slice(H.length).split(",").map(n=>n.trim()).filter(n=>n.length>0);return new T(e)}var L=false,J;function ze(r=new URL("./generated/xlsx_wasm_bg.wasm",import.meta.url)){return L?Promise.resolve():J||(J=B({module_or_path:r}).then(()=>{L=true;},e=>{throw J=void 0,A(e)}),J)}function j(){if(!L)throw new Error("xlsx wasm is not initialized; call initWasm() first")}function A(r){return r instanceof Error?r:new Error(typeof r=="string"?r:String(r))}function Ve(){return typeof WebAssembly=="object"}function Be(){return typeof h.prototype.renderPng=="function"}function He(){return typeof h.prototype.proposeJson=="function"}function je(r,e={}){j();let n=qe(e),t;try{t=n===void 0?h.open(r):h.openCollaborative(r,n);}catch(l){throw A(l)}let o=new Map,i=[],c=0,d=false,a=false,E=0,F=false;function M(){if(d)throw new Error("workbook handle is disposed")}function q(){if(!(d||F||E!==0)){F=true;try{for(;!d&&i.length>0;){let l=i.shift();if(!l)break;for(let[u,f]of [...o]){if(d)return;if(o.get(u)===f)try{f(l.update.slice(),l.origin);}catch{}}}}finally{F=false,d&&(i.length=0);}}}function X(){if(!(!a||d))for(;;){let l=t.drainUpdateEvent();if(l.byteLength===0)return;let u=l[0];if(u!==0&&u!==1)throw new Error(`xlsx wasm returned unknown update origin ${u}`);i.push({update:l.subarray(1),origin:u===0?"local":"remote"});}}function w(l,u=false){M(),E+=1;try{let f,m,C=!1;try{f=l();}catch(x){m=x,C=!0;}if(u)try{X();}catch(x){C||(m=x,C=!0);}if(C)throw A(m);return f}finally{E-=1,E===0&&q();}}function k(l){return w(l,true)}function b(l,u=false){return w(()=>JSON.parse(l()),u)}function G(){a||(w(()=>t.startUpdateObservation()),a=true);}function $(){!a||o.size>0||d||(i.length=0,w(()=>t.clearUpdateObservation()),a=false);}return {get clientId(){return w(()=>t.clientId)},encodeStateVector(){return w(()=>t.encodeStateVector())},encodeStateAsUpdate(l){return w(()=>l===void 0?t.encodeStateAsUpdate():t.encodeDiff(l))},applyUpdate(l){return b(()=>t.applyUpdateJson(l),true)},onUpdate(l){if(M(),typeof l!="function")throw new TypeError("update listener must be a function");let u=c++;o.set(u,l);try{G();}catch(m){throw o.delete(u),m}let f=true;return ()=>{f&&(f=false,o.delete(u),$());}},sheetInfo(){return b(()=>t.sheetInfoJson())},calculationStatus(){return w(()=>{let l=t.calculationStatusJson;return typeof l!="function"?{limitedCells:[]}:JSON.parse(l.call(t))})},displayList(l){return b(()=>t.displayListJson(JSON.stringify(l)))},printDisplayList(l,u,f,m){return b(()=>t.printDisplayListJson(JSON.stringify({sheet:l,range:u,metrics:f,gridlines:m})))},chartAtPoint(l,u,f){return b(()=>t.chartAtPointJson(JSON.stringify({viewport:l,x:u,y:f})))},moveChart(l,u,f,m){return b(()=>t.moveChartJson(JSON.stringify({sheet:l,chart:u,dx:f,dy:m})),true)},setActiveSheet(l){k(()=>t.setActiveSheet(l));},editCell(l,u,f,m){return b(()=>t.editCellJson(JSON.stringify({sheet:l,row:u,col:f,input:m})),true)},editCells(l,u){return b(()=>t.editCellsJson(JSON.stringify({sheet:l,edits:u})),true)},applyOps(l){return b(()=>t.applyOpsJson(JSON.stringify({ops:l})),true)},undo(){return b(()=>t.undoJson(),true)},redo(){return b(()=>t.redoJson(),true)},cell(l,u,f){return b(()=>t.cellJson(JSON.stringify({sheet:l,row:u,col:f})))},cellPosition(l,u,f){return b(()=>t.cellPositionJson(JSON.stringify({sheet:l,row:u,col:f})))},rangeCells(l,u){return b(()=>t.rangeCellsJson(JSON.stringify({sheet:l,range:u}))).cells},patchRangeStyle(l,u,f){return b(()=>t.patchRangeStyleJson(JSON.stringify({sheet:l,range:u,patch:f})),true)},setNumberFormat(l,u,f){let m=typeof f=="string"?{type:f}:f;return b(()=>t.setRangeNumberFormatJson(JSON.stringify({sheet:l,range:u,format:m})),true)},selectionFormatting(l,u){return b(()=>t.selectionFormattingJson(JSON.stringify({sheet:l,range:u})))},captureFormat(l,u){return b(()=>t.captureFormatJson(JSON.stringify({sheet:l,range:u})))},applyFormat(l,u,f){return b(()=>t.applyFormatJson(JSON.stringify({sheet:l,range:u,format:f})),true)},mergedRanges(l,u){return b(()=>t.mergedRangesJson(JSON.stringify({sheet:l,range:u}))).ranges},historyState(){return b(()=>t.historyStateJson())},renderPng(l){return w(()=>{let u=t.renderPng;if(typeof u!="function")throw new Error("png export not in this build");return u.call(t,JSON.stringify(l)).slice()})},renderRangePng(l){return w(()=>{let u=t.renderRangePng;if(typeof u!="function")throw new Error("png export not in this build");return u.call(t,JSON.stringify(l??{})).slice()})},save(){return w(()=>t.saveBytes())},propose(l,u,f){return k(()=>{let m=t.proposeJson;if(typeof m!="function")throw new Error("proposals not in this build");let C=f.map(({numberFormat:x,...K})=>({...K,...x===void 0?{}:{numberFormat:typeof x=="string"?{type:x}:x}}));return JSON.parse(m.call(t,JSON.stringify({agentId:l,note:u,edits:C})))})},listProposals(){return w(()=>{let l=t.listProposalsJson;return typeof l!="function"?[]:JSON.parse(l.call(t)).proposals})},acceptProposal(l,u){try{return k(()=>{let f=t.acceptProposalJson;if(typeof f!="function")throw new Error("proposals not in this build");return JSON.parse(f.call(t,JSON.stringify({id:l,force:u?.force??!1})))})}catch(f){let m=f instanceof Error?f.message:typeof f=="string"?f:String(f);throw m.startsWith(H)?Me(m):A(f)}},rejectProposal(l){return k(()=>{let u=t.rejectProposalJson;return typeof u!="function"?false:JSON.parse(u.call(t,JSON.stringify({id:l}))).removed})},isProposalsAvailable(){return w(()=>typeof t.proposeJson=="function")},dispose(){if(d)return;d=true,o.clear(),i.length=0;let l;if(a){try{t.clearUpdateObservation();}catch(u){l=u;}a=false;}try{t.free();}catch(u){l??(l=u);}if(l!==void 0)throw A(l)}}}function qe(r){if(!r.collaborative){if(r.clientId!==void 0)throw new TypeError("clientId requires collaborative mode");return}if(r.clientId!==void 0){if(!Number.isSafeInteger(r.clientId)||r.clientId<=0||r.clientId>Number.MAX_SAFE_INTEGER)throw new RangeError("clientId must be a nonzero safe integer");return r.clientId}let e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw new Error("crypto.getRandomValues is required to generate a collaboration client ID");let n=new Uint32Array(2),t;do e.getRandomValues(n),t=(n[0]&2097151)*4294967296+n[1];while(t===0);return t}function Xe(){return j(),h.version()}export{T as StaleProposalError,ze as initWasm,Be as isPngExportAvailable,He as isProposalsAvailable,Ve as isWasmAvailable,je as openWorkbook,Ce as paintDisplayList,Xe as wasmVersion};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@betteroffice/xlsx",
3
- "version": "0.0.8",
3
+ "version": "0.2.0",
4
4
  "description": "Excel-faithful XLSX spreadsheet editor and viewer core — full OOXML fidelity, real-time human + AI agent collaboration. Framework-free (Rust/Wasm).",
5
5
  "keywords": [
6
6
  "xlsx",
@@ -10,10 +10,19 @@
10
10
  "office",
11
11
  "editor",
12
12
  "viewer",
13
+ "xlsx-editor",
14
+ "xlsx-viewer",
15
+ "xlsx-parser",
16
+ "spreadsheet-editor",
17
+ "formula",
13
18
  "collaborative",
14
19
  "real-time",
20
+ "crdt",
21
+ "yjs",
15
22
  "ai-agent",
16
- "wasm"
23
+ "headless",
24
+ "wasm",
25
+ "rust"
17
26
  ],
18
27
  "type": "module",
19
28
  "sideEffects": false,
@@ -1,4 +0,0 @@
1
- function I(e){return Math.max(0,e.length-1)}function D(e){return e.length>0?e[e.length-1]:0}function C(e,t,n){return Math.max(t,Math.min(n,e))}function L(e,t,n,r){let o=n,l=r;for(;o<l;){let c=o+l+1>>1;e[c]<=t?o=c:l=c-1;}return o}function M(e,t,n,r){let o=I(e);if(o===0)return {first:0,last:-1};let l=C(Math.trunc(t),0,o);if(l>=o)return {first:0,last:-1};let c=e[l]-e[0],i=e[l]+Math.max(0,n),s=Math.max(0,r-c),a=i+s,f=L(e,i,l,o-1);if(e[f+1]<=i||s===0)return {first:0,last:-1};let x=L(e,a,f,o-1);return {first:f,last:x}}function V(e,t,n){return {cols:M(t,e.frozenCols,e.scrollX,e.width),rows:M(n,e.frozenRows,e.scrollY,e.height)}}function T(e,t,n){let r=I(e),o=C(Math.trunc(t),0,r),l=D(e)-e[o],c=Math.max(0,n-(e[o]-e[0]));return Math.max(0,l-c)}function z(e,t,n){let r=C(e.scrollX,0,T(t,e.frozenCols,e.width)),o=C(e.scrollY,0,T(n,e.frozenRows,e.height));return r===e.scrollX&&o===e.scrollY?e:{...e,scrollX:r,scrollY:o}}function _(e,t){let n=new Array(e+1);for(let r=0;r<=e;r++)n[r]=r*t;return n}function A(e,t,n){return Math.max(t,Math.min(n,e))}function u(e){return {anchor:{...e},focus:{...e}}}function y(e){return {top:Math.min(e.anchor.row,e.focus.row),bottom:Math.max(e.anchor.row,e.focus.row),left:Math.min(e.anchor.col,e.focus.col),right:Math.max(e.anchor.col,e.focus.col)}}function $(e,t){let n=y(e);return t.row>=n.top&&t.row<=n.bottom&&t.col>=n.left&&t.col<=n.right}function U(e){let t=y(e);return (t.bottom-t.top+1)*(t.right-t.left+1)}function S(e,t,n){let r=n?{row:A(t.row,0,n.rows-1),col:A(t.col,0,n.cols-1)}:{...t};return {anchor:{...e.anchor},focus:r}}function W(e,t){switch(e){case "up":return {row:-t,col:0};case "down":return {row:t,col:0};case "left":return {row:0,col:-t};case "right":return {row:0,col:t}}}function h(e,t,n){let{limits:r}=n,o=n.step??1,l=W(t,o),c={row:A(e.focus.row+l.row,0,r.rows-1),col:A(e.focus.col+l.col,0,r.cols-1)};return n.extend?S(e,c):u(c)}var B={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right"};function R(e){return !!(e.metaKey||e.ctrlKey)}function X(e,t,n){switch(t){case "up":return {row:0,col:e.col};case "down":return {row:n.rows-1,col:e.col};case "left":return {row:e.row,col:0};case "right":return {row:e.row,col:n.cols-1}}}function m(e){return {type:"move",selection:e}}function Y(e,t,n){let{row:r,col:o}=e.focus;return !t&&o>=n.cols-1?u({row:Math.min(r+1,n.rows-1),col:0}):t&&o<=0?u({row:Math.max(r-1,0),col:n.cols-1}):u({row:r,col:o+(t?-1:1)})}function N(e){return e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey}function j(e,t,n){let r=B[t.key];if(r){if(R(t)){let o=X(e.focus,r,n);return m(t.shiftKey?S(e,o,n):u(o))}return m(h(e,r,{extend:t.shiftKey,limits:n}))}switch(t.key){case "Tab":return m(Y(e,!!t.shiftKey,n));case "Enter":return m(h(e,t.shiftKey?"up":"down",{extend:false,limits:n}));case "Home":return m(R(t)?u({row:0,col:0}):u({row:e.focus.row,col:0}));case "End":return m(R(t)?u({row:n.rows-1,col:n.cols-1}):u({row:e.focus.row,col:n.cols-1}));case "PageDown":return m(h(e,"down",{extend:t.shiftKey,step:n.rowsPerPage,limits:n}));case "PageUp":return m(h(e,"up",{extend:t.shiftKey,step:n.rowsPerPage,limits:n}));case "F2":return {type:"startEdit"};case "Delete":case "Backspace":return {type:"clear"}}return (t.key==="a"||t.key==="A")&&R(t)?m({anchor:{row:0,col:0},focus:{row:n.rows-1,col:n.cols-1}}):N(t)?{type:"startEdit",initialInput:t.key}:{type:"none"}}function E(e,t){let n=e.length-1;if(n<=0||t<e[0]||t>=e[n])return -1;let r=0,o=n-1;for(;r<o;){let l=r+o+1>>1;e[l]<=t?r=l:o=l-1;}return r}function we(e,t,n){if(!e)return null;let r=E(e.colOffsets,t),o=E(e.rowOffsets,n);return r<0||o<0?null:{row:e.rowIndices?.[o]??e.startRow+o,col:e.colIndices?.[r]??e.startCol+r}}function v(e,t,n,r){if(t){let l=0,c=t.length-1;for(;l<=c;){let i=l+c>>1,s=t[i];if(s===r)return i;s<r?l=i+1:c=i-1;}return -1}let o=r-e;return o>=0&&o<n.length-1?o:-1}function he(e,t,n){if(!e)return null;let r=v(e.startCol,e.colIndices,e.colOffsets,n),o=v(e.startRow,e.rowIndices,e.rowOffsets,t);return r<0||o<0?null:{x:e.colOffsets[r],y:e.rowOffsets[o],w:e.colOffsets[r+1]-e.colOffsets[r],h:e.rowOffsets[o+1]-e.rowOffsets[o]}}function q(e,t,n){return t?.[n]??e+n}function K(e,t,n,r,o){let l=-1,c=-1;for(let i=0;i<n;i++){let s=q(e,t,i);if(!(s<r)){if(s>o)break;l<0&&(l=i),c=i;}}return l<0?null:[l,c]}function be(e,t){if(!e)return null;let n=e.colOffsets.length-1,r=e.rowOffsets.length-1;if(n<=0||r<=0)return null;let o=K(e.startCol,e.colIndices,n,t.left,t.right),l=K(e.startRow,e.rowIndices,r,t.top,t.bottom);if(!o||!l)return null;let[c,i]=o,[s,a]=l;return {x:e.colOffsets[c],y:e.rowOffsets[s],w:e.colOffsets[i+1]-e.colOffsets[c],h:e.rowOffsets[a+1]-e.rowOffsets[s]}}function ye(e,t,n){return e.hyperlinks?.find(r=>t>=r.top&&t<=r.bottom&&n>=r.left&&n<=r.right)??null}function ge(e){if(!e.externalTarget)return null;let t;try{t=new URL(e.externalTarget);}catch{return null}return ["http:","https:","mailto:","tel:"].includes(t.protocol)?(e.location&&!t.hash&&(t.hash=e.location.replace(/^#/,"")),t.href):null}function xe(e,t){let n=e.replace(/^#/,""),r=n.lastIndexOf("!"),o=r<0?t:n.slice(0,r),l=(r<0?n:n.slice(r+1)).split(":",1)[0],c=/^\$?([A-Za-z]{1,3})\$?([1-9]\d*)$/.exec(l);if(!c)return null;let i=0;for(let f of c[1].toUpperCase())i=i*26+f.charCodeAt(0)-64;let s=Number(c[2]);if(i<1||i>16384||s<1||s>1048576)return null;let a=o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1).replace(/''/g,"'"):o;return a?{sheetName:a,row:s-1,col:i-1}:null}var J=new Set(["=","+","-","@"]);function Z(e){let t=e.charCodeAt(0);return J.has(e[0])||t===9||t===13||t===10}function Q(e){return /[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function ee(e){let t=!e.isFormula&&e.input.length>0&&Z(e.input);return Q(t?`'${e.input}`:e.input)}function Ae(e){return e.map(t=>t.map(ee).join(" ")).join(`\r
2
- `)}function Se(e){let t=[],n=[],r="",o=false,l=0,c=()=>{n.push(r),r="";},i=()=>{c(),t.push(n),n=[];};for(;l<e.length;){let s=e[l];if(o){if(s==='"'){if(e[l+1]==='"'){r+='"',l+=2;continue}o=false,l+=1;continue}r+=s,l+=1;continue}if(s==='"'){o=true,l+=1;continue}if(s===" "){c(),l+=1;continue}if(s==="\r"){i(),e[l+1]===`
3
- `&&(l+=1),l+=1;continue}if(s===`
4
- `){i(),l+=1;continue}r+=s,l+=1;}return (r.length>0||n.length>0)&&i(),t}function H(e){let t=e,n="";do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return n}function te(e,t){return `${H(t)}${e+1}`}function O(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>String(t[r]??""))}function P(e,t){return `${Math.round(e*1e3)},${Math.round(t*1e3)}`}function ne(e){let t=new Map;for(let n of e.commands)n.op==="text"&&n.clip&&!n.ghost&&t.set(P(n.clip.x,n.clip.y),n.text);return t}function re(e,t,n){return e?t>=e.top&&t<=e.bottom&&n>=e.left&&n<=e.right:false}function g(e,t,n){return t?.[n]??e+n}function oe(e,t,n,r,o,l){let c=g(e.startRow,e.rowIndices,t),i=g(e.startCol,e.colIndices,n),s=te(c,i),f=r.length===0?o?l.emptyCellLabelSelected:l.emptyCellLabel:o?l.cellLabelSelected:l.cellLabel;return {row:c,col:i,address:s,text:r,selected:o,label:O(f,{address:s,value:r})}}function Me(e,t,n,r){let o=e.grid,l=O(r.gridLabel,{sheet:n});if(!o)return {label:l,sheetName:n,columnHeaders:[],rows:[]};let c=o.colOffsets.length-1,i=o.rowOffsets.length-1,s=t?y(t):null,a=ne(e),f=[];for(let p=0;p<c;p++){let w=g(o.startCol,o.colIndices,p),b=H(w);f.push({col:w,text:b,label:O(r.columnHeaderLabel,{column:b})});}let x=[];for(let p=0;p<i;p++){let w=g(o.startRow,o.rowIndices,p),b=[];for(let d=0;d<c;d++){let k=P(o.colOffsets[d],o.rowOffsets[p]),F=a.get(k)??"",G=g(o.startCol,o.colIndices,d);b.push(oe(o,p,d,F,re(s,w,G),r));}x.push({row:w,header:O(r.rowHeaderLabel,{row:w+1}),cells:b});}return {label:l,sheetName:n,columnHeaders:f,rows:x}}export{I as a,D as b,M as c,V as d,z as e,_ as f,u as g,y as h,$ as i,U as j,S as k,h as l,j as m,we as n,he as o,be as p,ye as q,ge as r,xe as s,Ae as t,Se as u,Me as v};