@origints/xlsx 0.1.0 → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Franco Ponticelli
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,314 @@
1
+ # @origints/xlsx
2
+
3
+ > XLSX parsing for Origins with full traceability to sheets, ranges, and cells.
4
+
5
+ ---
6
+
7
+ ## Features
8
+
9
+ - Parse XLSX files from streams, buffers, or file paths
10
+ - Navigate workbooks, sheets, ranges, and cells
11
+ - Cursor-based iteration for sequential processing
12
+ - Cell predicates for conditional extraction
13
+ - Convert ranges to JSON, arrays, or objects
14
+ - Export to CSV format
15
+ - Full source location tracking for every cell
16
+
17
+ ---
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install @origints/xlsx @origints/core
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Usage with Planner
28
+
29
+ ### Extract cell values from a spreadsheet
30
+
31
+ ```ts
32
+ import { Planner, loadFile, run } from '@origints/core'
33
+ import { parseXlsx } from '@origints/xlsx'
34
+
35
+ const plan = new Planner()
36
+ .in(loadFile('data.xlsx'))
37
+ .mapIn(parseXlsx())
38
+ .emit((out, $) =>
39
+ out
40
+ .add('title', $.firstSheet().cell('A1').string())
41
+ .add('revenue', $.firstSheet().cell('B2').number())
42
+ )
43
+ .compile()
44
+
45
+ const result = await run(plan, { readFile, registry })
46
+ // result.value: { title: 'Q4 Report', revenue: 150000 }
47
+ ```
48
+
49
+ ### Extract from specific sheets
50
+
51
+ ```ts
52
+ const plan = new Planner()
53
+ .in(loadFile('report.xlsx'))
54
+ .mapIn(parseXlsx())
55
+ .emit((out, $) =>
56
+ out
57
+ .add('totalSales', $.sheet('Sales').cell('B10').number())
58
+ .add('totalExpenses', $.sheet('Expenses').cell('B10').number())
59
+ )
60
+ .compile()
61
+ ```
62
+
63
+ ### Extract rows from a range
64
+
65
+ Use `range().rows()` to iterate over rows in a range and extract structured data:
66
+
67
+ ```ts
68
+ // Spreadsheet has headers in row 1: Name | Age | Department
69
+ // Data rows in A2:C10
70
+
71
+ const plan = new Planner()
72
+ .in(loadFile('employees.xlsx'))
73
+ .mapIn(parseXlsx())
74
+ .emit((out, $) =>
75
+ out.add(
76
+ 'employees',
77
+ $.firstSheet()
78
+ .range('A2:C4')
79
+ .rows(row => ({
80
+ kind: 'object',
81
+ properties: {
82
+ name: row.col(1).string(),
83
+ age: row.col(2).number(),
84
+ dept: row.col(3).string(),
85
+ },
86
+ }))
87
+ )
88
+ )
89
+ .compile()
90
+
91
+ const result = await run(plan, { readFile, registry })
92
+ // result.value: {
93
+ // employees: [
94
+ // { name: 'Alice', age: 30, dept: 'Engineering' },
95
+ // { name: 'Bob', age: 25, dept: 'Marketing' },
96
+ // ...
97
+ // ]
98
+ // }
99
+ ```
100
+
101
+ ### Range from two corners
102
+
103
+ `range()` accepts two addresses or two dynamic cell builders:
104
+
105
+ ```ts
106
+ // Two string addresses — equivalent to range("A2:C10")
107
+ $.firstSheet().range("A2", "C10").rows(...)
108
+
109
+ // Dynamic corners — cells resolved at runtime
110
+ const topLeft = $.firstSheet().find(cell.equals("Name"));
111
+ const bottomRight = $.firstSheet().find(cell.equals("Total")).left();
112
+ $.firstSheet().range(topLeft, bottomRight).rows((row) => ({
113
+ kind: "object",
114
+ properties: {
115
+ name: row.col(1).string(),
116
+ value: row.col(2).number(),
117
+ },
118
+ }));
119
+ ```
120
+
121
+ ### Collect rows with predicates
122
+
123
+ Use `eachSlice()` to iterate rows from a starting cell while a predicate holds, with header-relative column access:
124
+
125
+ ```ts
126
+ import { cell, rowCol } from '@origints/xlsx'
127
+
128
+ const hasData = rowCol(0, cell.isNotEmpty()).and(
129
+ rowCol(0, cell.startsWith('Total').not())
130
+ )
131
+
132
+ const plan = new Planner()
133
+ .in(loadFile('report.xlsx'))
134
+ .mapIn(parseXlsx())
135
+ .emit((out, $) => {
136
+ const header = $.firstSheet().find(cell.equals('Name'))
137
+
138
+ return out.add(
139
+ 'people',
140
+ header.down().eachSlice('down', hasData, row => ({
141
+ kind: 'object',
142
+ properties: {
143
+ name: row.colWhere(header, cell.equals('Name')).string(),
144
+ role: row.colWhere(header, cell.equals('Role')).string(),
145
+ },
146
+ }))
147
+ )
148
+ })
149
+ .compile()
150
+ ```
151
+
152
+ ### Collect cell values in a direction
153
+
154
+ Use `eachCell()` to gather cells in a direction while a predicate matches:
155
+
156
+ ```ts
157
+ import { cell } from '@origints/xlsx'
158
+
159
+ const plan = new Planner()
160
+ .in(loadFile('data.xlsx'))
161
+ .mapIn(parseXlsx())
162
+ .emit((out, $) =>
163
+ out.add(
164
+ 'values',
165
+ $.firstSheet()
166
+ .cell('B2')
167
+ .eachCell('down', cell.isNotEmpty(), c => c.number())
168
+ )
169
+ )
170
+ .compile()
171
+
172
+ const result = await run(plan, { readFile, registry })
173
+ // result.value: { values: [100, 200, 300, 400] }
174
+ ```
175
+
176
+ ### Optional and fallback extraction
177
+
178
+ Handle missing or invalid cell values using `optional()`, `tryExtract()`, `mapSpec()`, and `guard()`:
179
+
180
+ ```ts
181
+ import { literal, optional, tryExtract, mapSpec, guard } from '@origints/core'
182
+ import { cell, rowCol } from '@origints/xlsx'
183
+
184
+ const plan = new Planner()
185
+ .in(loadFile('portfolio.xlsx'))
186
+ .mapIn(parseXlsx())
187
+ .emit((out, $) => {
188
+ const header = $.firstSheet().find(cell.equals('Company'))
189
+ const hasData = rowCol(0, cell.isNotEmpty()).and(
190
+ rowCol(0, cell.startsWith('Total').not())
191
+ )
192
+
193
+ return out.add(
194
+ 'companies',
195
+ header.down().eachSlice('down', hasData, row => ({
196
+ kind: 'object',
197
+ properties: {
198
+ // Required field
199
+ name: row.colWhere(header, cell.equals('Company')).string(),
200
+ // Optional: returns null when cell is empty or has wrong type
201
+ ownership: optional(
202
+ row.colWhere(header, cell.equals('Ownership %')).number(),
203
+ null
204
+ ),
205
+ // Fallback: try number first, then parse string, then null
206
+ revenue: tryExtract(
207
+ row.colWhere(header, cell.equals('Revenue')).number(),
208
+ mapSpec(
209
+ row.colWhere(header, cell.equals('Revenue')).string(),
210
+ v => parseFloat((v as string).replace(/[,$]/g, '')),
211
+ 'parseFloat'
212
+ ),
213
+ literal(null)
214
+ ),
215
+ // Guard: ensure investment amount is positive
216
+ investment: guard(
217
+ row.colWhere(header, cell.equals('Investment')).number(),
218
+ v => (v as number) > 0,
219
+ 'Investment must be positive'
220
+ ),
221
+ },
222
+ }))
223
+ )
224
+ })
225
+ .compile()
226
+ ```
227
+
228
+ ### Combine with other data sources
229
+
230
+ ```ts
231
+ const plan = new Planner()
232
+ .in(loadFile('budget.xlsx'))
233
+ .mapIn(parseXlsx())
234
+ .emit((out, $) => out.add('budget', $.firstSheet().cell('B2').number()))
235
+ .in(loadFile('config.json'))
236
+ .mapIn(parseJson())
237
+ .emit((out, $) => out.add('department', $.get('department').string()))
238
+ .compile()
239
+ ```
240
+
241
+ ### Standalone usage (without Planner)
242
+
243
+ For direct workbook navigation:
244
+
245
+ ```ts
246
+ import { parseXlsxAsyncImpl, XlsxWorkbook } from '@origints/xlsx'
247
+
248
+ const workbook = (await parseXlsxAsyncImpl.execute(buffer)) as XlsxWorkbook
249
+
250
+ // Navigate sheets
251
+ const sheetResult = workbook.sheet('Sheet1')
252
+ if (sheetResult.ok) {
253
+ const sheet = sheetResult.value
254
+
255
+ // Read a cell
256
+ const cellResult = sheet.cell('A1')
257
+ if (cellResult.ok) {
258
+ console.log(cellResult.value.string().value)
259
+ }
260
+
261
+ // Work with ranges
262
+ const rangeResult = sheet.range('A1:D10')
263
+ if (rangeResult.ok) {
264
+ const range = rangeResult.value
265
+ // Convert to array of arrays
266
+ const rows = range.toArray()
267
+ // Convert to objects using first row as headers
268
+ const records = range.toObjects()
269
+ }
270
+ }
271
+ ```
272
+
273
+ ### Cursor-based iteration
274
+
275
+ ```ts
276
+ import { XlsxCursor } from '@origints/xlsx'
277
+
278
+ const sheetResult = workbook.sheet('Data')
279
+ if (sheetResult.ok) {
280
+ const cursor = new XlsxCursor(sheetResult.value, 'A1')
281
+
282
+ // Move and grab values
283
+ cursor.move('right', 2)
284
+ const value = cursor.grab()
285
+
286
+ // Iterate rows
287
+ while (cursor.hasMore('down')) {
288
+ const row = cursor.grabRow(4)
289
+ cursor.move('down')
290
+ }
291
+ }
292
+ ```
293
+
294
+ ---
295
+
296
+ ## API
297
+
298
+ | Export | Description |
299
+ | ---------------------------------- | ----------------------------------------------------- |
300
+ | `parseXlsx(options?)` | Create a transform AST for use with `Planner.mapIn()` |
301
+ | `parseXlsxImpl` | Sync transform implementation |
302
+ | `parseXlsxAsyncImpl` | Async transform implementation (stream/buffer) |
303
+ | `registerXlsxTransforms(registry)` | Register all XLSX transforms with a registry |
304
+ | `XlsxWorkbook` | Workbook navigation |
305
+ | `XlsxSheet` | Sheet navigation with cell/range access |
306
+ | `XlsxRange` | Range operations and conversion |
307
+ | `XlsxCell` | Cell value extraction |
308
+ | `XlsxCursor` | Sequential cursor-based iteration |
309
+
310
+ ---
311
+
312
+ ## License
313
+
314
+ MIT
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("exceljs");function i(s,t){return{ok:!0,value:s,path:t}}function a(s,t,e,r){return{ok:!1,failure:{kind:s,message:t,path:e,sourceLocation:r}}}function F(s){const t=[];return s.file&&t.push(s.file),s.sheet&&t.push(`[${s.sheet}]`),s.range?t.push(`!${s.range}`):s.cell&&t.push(`!${s.cell}`),t.join("")||"workbook"}function z(s){if(s.sheet)return{kind:"excel",file:s.file??"",sheet:s.sheet,range:s.range??s.cell??""}}function b(s){return typeof s=="object"&&s!==null&&!(s instanceof Date)&&"formula"in s}function R(s){return typeof s=="object"&&s!==null&&!(s instanceof Date)&&"error"in s}async function I(s){const t=s.getReader(),e=[];try{for(;;){const{done:r,value:n}=await t.read();if(r)break;e.push(n)}return Buffer.concat(e)}finally{t.releaseLock()}}function S(s){let t=0;for(let e=0;e<s.length;e++)t=t*26+(s.charCodeAt(e)-64);return t}function V(s){let t="";for(;s>0;){const e=(s-1)%26;t=String.fromCharCode(65+e)+t,s=Math.floor((s-1)/26)}return t}function w(s){const t=s.match(/^([A-Z]+)(\d+)$/i);if(!t)throw new Error(`Invalid cell address: ${s}`);const e=t[1].toUpperCase();return{row:parseInt(t[2],10),col:S(e),colLetter:e}}function C(s,t){return`${V(t)}${s}`}function y(s){const t=s.split(":");if(t.length===1){const n=w(t[0]);return{start:{row:n.row,col:n.col},end:{row:n.row,col:n.col}}}if(t.length!==2)throw new Error(`Invalid range: ${s}`);const e=w(t[0]),r=w(t[1]);return{start:{row:e.row,col:e.col},end:{row:r.row,col:r.col}}}function $(s,t,e,r){const n=C(s,t),o=C(e,r);return n===o?n:`${n}:${o}`}function O(s,t,e){return s>=e.start.row&&s<=e.end.row&&t>=e.start.col&&t<=e.end.col}class p{constructor(t,e,r){this.cell=t,this._path=e,this._sheetName=r}static fromExcelJS(t,e,r){const n={file:r,sheet:e,cell:t.address};return new p(t,n,e)}get address(){return this.cell.address}get row(){return typeof this.cell.row=="number"?this.cell.row:parseInt(String(this.cell.row),10)}get col(){return typeof this.cell.col=="number"?this.cell.col:parseInt(String(this.cell.col),10)}get colLetter(){return this.address.replace(/\d+$/,"")}get path(){return this._path}get sheetName(){return this._sheetName}value(){const t=this.getRawValue();return b(t)?i(t.result??null,this._path):R(t)?a("formula",`Cell contains error: ${t.error}`,this._path):i(t,this._path)}extendedValue(){return i(this.getRawValue(),this._path)}string(){const t=this.getResolvedValue();return t==null?a("type","Expected string, got null",this._path):typeof t=="string"?i(t,this._path):typeof t=="number"||typeof t=="boolean"?i(String(t),this._path):t instanceof Date?i(t.toISOString(),this._path):a("type",`Expected string, got ${typeof t}`,this._path)}number(){const t=this.getResolvedValue();if(typeof t=="number")return i(t,this._path);if(typeof t=="string"){const e=parseFloat(t);if(!isNaN(e))return i(e,this._path)}return a("type",`Expected number, got ${E(t)}`,this._path)}boolean(){const t=this.getResolvedValue();return typeof t=="boolean"?i(t,this._path):a("type",`Expected boolean, got ${E(t)}`,this._path)}date(){const t=this.getResolvedValue();if(t instanceof Date)return i(t,this._path);if(typeof t=="number"){const e=this.excelDateToJS(t);return i(e,this._path)}if(typeof t=="string"){const e=new Date(t);if(!isNaN(e.getTime()))return i(e,this._path)}return a("type",`Expected date, got ${E(t)}`,this._path)}formula(){const t=this.getRawValue();return b(t)?i(t.formula,this._path):a("type","Cell does not contain a formula",this._path)}richText(){const t=this.cell.value,e=this.cell.hyperlink;if(t&&typeof t=="object"&&"richText"in t){const u=t.richText.map(c=>({text:c.text,bold:c.font?.bold,italic:c.font?.italic,underline:c.font?.underline===!0||c.font?.underline==="single",strikethrough:c.font?.strike,color:c.font?.color?.argb,size:c.font?.size,font:c.font?.name}));return i({segments:u,hyperlink:e},this._path)}if(t&&typeof t=="object"&&"text"in t&&"hyperlink"in t){const h=t,u=this.style(),c={text:h.text,bold:u.font?.bold,italic:u.font?.italic,underline:u.font?.underline,strikethrough:u.font?.strikethrough,color:u.font?.color,size:u.font?.size,font:u.font?.name};return i({segments:[c],hyperlink:h.hyperlink},this._path)}const r=this.getResolvedValue(),n=r!==null?String(r):"",o=this.style(),l={text:n,bold:o.font?.bold,italic:o.font?.italic,underline:o.font?.underline,strikethrough:o.font?.strikethrough,color:o.font?.color,size:o.font?.size,font:o.font?.name};return i({segments:[l],hyperlink:e},this._path)}markdown(){const t=this.richText();if(!t.ok)return t;const{segments:e,hyperlink:r}=t.value;let n="";for(const o of e){let l=o.text;o.strikethrough&&(l=`~~${l}~~`),o.bold&&(l=`**${l}**`),o.italic&&(l=`*${l}*`),n+=l}return r&&(n=`[${n}](${r})`),i(n,this._path)}isRichText(){const t=this.cell.value;return t!==null&&typeof t=="object"&&"richText"in t}isEmpty(){const t=this.cell.value;return t==null||t===""}isFormula(){return b(this.getRawValue())}isMerged(){return this.cell.isMerged}isMergedMaster(){return this.cell.isMerged?this.cell.master.address===this.cell.address:!1}isString(){return typeof this.getResolvedValue()=="string"}isNumber(){return typeof this.getResolvedValue()=="number"}isBoolean(){return typeof this.getResolvedValue()=="boolean"}isDate(){return this.getResolvedValue()instanceof Date}isError(){return R(this.getRawValue())}style(){const t=this.cell.font,e=this.cell.fill,r=this.cell.border,n=this.cell.alignment;return{font:t?{name:t.name,size:t.size,bold:t.bold,italic:t.italic,underline:t.underline===!0||t.underline==="single",strikethrough:t.strike,color:t.color?.argb??(t.color?.theme!==void 0?`theme:${t.color.theme}`:void 0)}:void 0,fill:e&&e.type==="pattern"?{type:e.pattern,color:e.fgColor?.argb}:void 0,border:r?{top:!!r.top,bottom:!!r.bottom,left:!!r.left,right:!!r.right}:void 0,alignment:n?{horizontal:n.horizontal,vertical:n.vertical,wrapText:n.wrapText}:void 0,numFmt:this.cell.numFmt}}hyperlink(){const t=this.cell.hyperlink;return t?i(t,this._path):a("missing","Cell does not contain a hyperlink",this._path)}comment(){const t=this.cell.note;return t?typeof t=="string"?i(t,this._path):t.texts?i(t.texts.map(e=>e.text).join(""),this._path):a("format","Unable to extract comment text",this._path):a("missing","Cell does not contain a comment",this._path)}getOffsetCell(t,e,r){const n=this.row+t,o=this.col+e;if(n<1||o<1)return a("bounds",`Cell offset (${t}, ${e}) from ${this.address} is out of bounds`,this._path);const l=r(n,o);return l?i(l,l.path):a("missing",`Cell at ${C(n,o)} not found`,this._path)}getRawValue(){const t=this.cell.value;if(t==null)return null;if(typeof t=="object"){if("error"in t)return{error:String(t.error)};if("formula"in t){const e=t;return{formula:e.formula,result:this.normalizeResult(e.result)}}if("sharedFormula"in t){const e=t;return{formula:e.sharedFormula,result:this.normalizeResult(e.result)}}if("richText"in t)return t.richText.map(r=>r.text).join("");if(t instanceof Date)return t}return typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:null}getResolvedValue(){const t=this.getRawValue();return b(t)?t.result??null:R(t)?null:t}normalizeResult(t){return t==null?null:typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Date?t:null}excelDateToJS(t){const e=t>60?-1:0,r=t+e-1,n=new Date(1900,0,1);return new Date(n.getTime()+r*24*60*60*1e3)}}function E(s){return s===null?"null":s===void 0?"undefined":s instanceof Date?"date":Array.isArray(s)?"array":typeof s}class m{constructor(t,e,r,n,o,l,h,u){this.worksheet=t,this._startRow=e,this._startCol=r,this._endRow=n,this._endCol=o,this._path=l,this._sheetName=h,this._file=u}static fromCoords(t,e,r,n,o,l,h){const u=$(e,r,n,o),c={file:h,sheet:l,range:u};return new m(t,e,r,n,o,c,l,h)}static fromAddress(t,e,r,n){try{const{start:o,end:l}=y(e);return i(m.fromCoords(t,o.row,o.col,l.row,l.col,r,n),{file:n,sheet:r,range:e})}catch{return a("range",`Invalid range address: ${e}`,{file:n,sheet:r})}}get address(){return $(this._startRow,this._startCol,this._endRow,this._endCol)}get startRow(){return this._startRow}get startCol(){return this._startCol}get endRow(){return this._endRow}get endCol(){return this._endCol}get path(){return this._path}get rowCount(){return this._endRow-this._startRow+1}get colCount(){return this._endCol-this._startCol+1}get cellCount(){return this.rowCount*this.colCount}cellAt(t,e){const r=this._startRow+t,n=this._startCol+e;if(r<this._startRow||r>this._endRow||n<this._startCol||n>this._endCol)return a("bounds",`Offset (${t}, ${e}) is outside range ${this.address}`,this._path);const o=this.worksheet.getCell(r,n);return i(p.fromExcelJS(o,this._sheetName,this._file),{...this._path,cell:o.address,range:void 0})}cell(t){try{const{start:e}=y(t);if(e.row<this._startRow||e.row>this._endRow||e.col<this._startCol||e.col>this._endCol)return a("bounds",`Cell ${t} is outside range ${this.address}`,this._path);const r=this.worksheet.getCell(t);return i(p.fromExcelJS(r,this._sheetName,this._file),{...this._path,cell:t,range:void 0})}catch{return a("range",`Invalid cell address: ${t}`,this._path)}}*cells(){for(let t=this._startRow;t<=this._endRow;t++)for(let e=this._startCol;e<=this._endCol;e++){const r=this.worksheet.getCell(t,e);yield p.fromExcelJS(r,this._sheetName,this._file)}}*rows(){for(let t=this._startRow;t<=this._endRow;t++){const e=[];for(let r=this._startCol;r<=this._endCol;r++){const n=this.worksheet.getCell(t,r);e.push(p.fromExcelJS(n,this._sheetName,this._file))}yield e}}*cols(){for(let t=this._startCol;t<=this._endCol;t++){const e=[];for(let r=this._startRow;r<=this._endRow;r++){const n=this.worksheet.getCell(r,t);e.push(p.fromExcelJS(n,this._sheetName,this._file))}yield e}}values(){const t=[];for(const e of this.rows()){const r=[];for(const n of e){const o=n.value();r.push(o.ok?o.value:null)}t.push(r)}return t}cellsArray(){return[...this.cells()]}subRange(t){try{const{start:e,end:r}=y(t);return e.row<this._startRow||r.row>this._endRow||e.col<this._startCol||r.col>this._endCol?a("bounds",`Subrange ${t} extends outside range ${this.address}`,this._path):i(m.fromCoords(this.worksheet,e.row,e.col,r.row,r.col,this._sheetName,this._file),{...this._path,range:t})}catch{return a("range",`Invalid range address: ${t}`,this._path)}}firstRow(){return m.fromCoords(this.worksheet,this._startRow,this._startCol,this._startRow,this._endCol,this._sheetName,this._file)}lastRow(){return m.fromCoords(this.worksheet,this._endRow,this._startCol,this._endRow,this._endCol,this._sheetName,this._file)}firstCol(){return m.fromCoords(this.worksheet,this._startRow,this._startCol,this._endRow,this._startCol,this._sheetName,this._file)}lastCol(){return m.fromCoords(this.worksheet,this._startRow,this._endCol,this._endRow,this._endCol,this._sheetName,this._file)}rowAt(t){const e=this._startRow+t;return e<this._startRow||e>this._endRow?a("bounds",`Row offset ${t} is outside range ${this.address}`,this._path):i(m.fromCoords(this.worksheet,e,this._startCol,e,this._endCol,this._sheetName,this._file),this._path)}colAt(t){const e=this._startCol+t;return e<this._startCol||e>this._endCol?a("bounds",`Column offset ${t} is outside range ${this.address}`,this._path):i(m.fromCoords(this.worksheet,this._startRow,e,this._endRow,e,this._sheetName,this._file),this._path)}find(t){for(const e of this.cells())if(t(e))return i(e,e.path);return a("missing",`No cell matching predicate found in range ${this.address}`,this._path)}findAll(t){const e=[];for(const r of this.cells())t(r)&&e.push(r);return e}findValue(t){for(const e of this.cells()){const r=e.value();if(r.ok&&r.value===t)return i(e,e.path)}return a("missing",`Value "${t}" not found in range ${this.address}`,this._path)}some(t){for(const e of this.cells())if(t(e))return!0;return!1}every(t){for(const e of this.cells())if(!t(e))return!1;return!0}count(t){let e=0;for(const r of this.cells())t(r)&&e++;return e}toArray(){return this.values()}toObjects(t=0,e=1){const r=[...this.rows()];if(r.length===0)return[];const n=r[t];if(!n)return[];const o=n.map(h=>{const u=h.value();return u.ok&&u.value!==null?String(u.value):""}),l=[];for(let h=e;h<r.length;h++){const u=r[h],c={};for(let f=0;f<o.length;f++){const k=o[f];if(k){const v=u[f]?.value();c[k]=v?.ok?v.value:null}}l.push(c)}return l}toJson(){return{address:this.address,rows:this.values()}}}class d{constructor(t,e,r,n="right"){this.sheet=t,this._row=e,this._col=r,this._direction=n}static create(t,e){const{row:r,col:n}=w(e);return new d(t,r,n)}static createAt(t,e,r){return new d(t,Math.max(1,e),Math.max(1,r))}get row(){return this._row}get col(){return this._col}get address(){return C(this._row,this._col)}get colLetter(){return V(this._col)}get direction(){return this._direction}get path(){return{...this.sheet.path,cell:this.address}}move(t,e){return new d(this.sheet,Math.max(1,this._row+t),Math.max(1,this._col+e),this._direction)}moveTo(t){const{row:e,col:r}=w(t);return new d(this.sheet,e,r,this._direction)}moveToRow(t){return new d(this.sheet,Math.max(1,t),this._col,this._direction)}moveToCol(t){const e=typeof t=="string"?S(t.toUpperCase()):t;return new d(this.sheet,this._row,Math.max(1,e),this._direction)}left(t=1){return new d(this.sheet,this._row,Math.max(1,this._col-t),"left")}right(t=1){return new d(this.sheet,this._row,this._col+t,"right")}up(t=1){return new d(this.sheet,Math.max(1,this._row-t),this._col,"up")}down(t=1){return new d(this.sheet,this._row+t,this._col,"down")}setDirection(t){return new d(this.sheet,this._row,this._col,t)}forward(t=1){switch(this._direction){case"right":return this.right(t);case"left":return this.left(t);case"down":return this.down(t);case"up":return this.up(t)}}startOfRow(){return new d(this.sheet,this._row,1,this._direction)}startOfCol(){return new d(this.sheet,1,this._col,this._direction)}skipEmpty(){return this.skipWhile(t=>t.isEmpty())}skipWhile(t){let e=this;const r=this.sheet.dimensions(),n=Math.max(r.rowCount,r.colCount)*2;for(let o=0;o<n;o++){const l=e.cell();if(!l.ok||!t(l.value))break;e=e.forward()}return e}skipUntil(t){return this.skipWhile(e=>!t(e))}skipToValue(t){return this.skipUntil(e=>{const r=e.value();return r.ok&&r.value===t})}skip(t){return this.forward(t)}grab(){const t=this.cell();return t.ok?i({cell:t.value,cursor:this.forward()},this.path):t}grabN(t){const e=[];let r=this;for(let n=0;n<t;n++){const o=r.cell();if(!o.ok)break;e.push(o.value),r=r.forward()}return e.length===0?a("bounds","No cells to grab",this.path):i({cells:e,cursor:r},this.path)}grabWhile(t){const e=[];let r=this;const n=this.sheet.dimensions(),o=Math.max(n.rowCount,n.colCount)*2;for(let l=0;l<o;l++){const h=r.cell();if(!h.ok||!t(h.value))break;e.push(h.value),r=r.forward()}return i({cells:e,cursor:r},this.path)}grabUntil(t){return this.grabWhile(e=>!t(e))}grabRow(){const t=[],e=this.sheet.dimensions();let r=this.setDirection("right");for(let n=this._col;n<=e.endCol;n++){const o=r.cell();if(!o.ok)break;t.push(o.value),r=r.forward()}return i({cells:t,cursor:r},this.path)}grabCol(){const t=[],e=this.sheet.dimensions();let r=this.setDirection("down");for(let n=this._row;n<=e.endRow;n++){const o=r.cell();if(!o.ok)break;t.push(o.value),r=r.forward()}return i({cells:t,cursor:r},this.path)}grabNonEmpty(){return this.grabWhile(t=>!t.isEmpty())}peek(){return this.cell()}peekAhead(t){const e=[];let r=this;for(let n=0;n<t;n++){const o=r.cell();if(!o.ok)break;e.push(o.value),r=r.forward()}return i(e,this.path)}peekAt(t,e){return this.move(t,e).cell()}cell(){return this.sheet.cellAt(this._row,this._col)}value(){const t=this.cell();return t.ok?t.value.value():t}isValid(){return this.cell().ok}isEmpty(){const t=this.cell();return t.ok&&t.value.isEmpty()}isNotEmpty(){const t=this.cell();return t.ok&&!t.value.isEmpty()}clone(){return new d(this.sheet,this._row,this._col,this._direction)}}class g{constructor(t,e,r){this.worksheet=t,this._path=e,this._file=r}static fromExcelJS(t,e){const r={file:e,sheet:t.name};return new g(t,r,e)}get name(){return this.worksheet.name}get index(){return this.worksheet.id}get path(){return this._path}cell(t){try{w(t);const e=this.worksheet.getCell(t);return i(p.fromExcelJS(e,this.name,this._file),{...this._path,cell:t})}catch{return a("range",`Invalid cell address: ${t}`,this._path)}}cellAt(t,e){if(t<1||e<1)return a("bounds",`Invalid cell coordinates: row=${t}, col=${e}`,this._path);const r=this.worksheet.getCell(t,e);return i(p.fromExcelJS(r,this.name,this._file),{...this._path,cell:r.address})}getValue(t){const e=this.cell(t);return e.ok?e.value.value():e}range(t){return m.fromAddress(this.worksheet,t,this.name,this._file)}rangeFrom(t,e){return this.range(`${t}:${e}`)}rangeAt(t,e,r,n){return t<1||e<1||r<1||n<1?a("bounds","Invalid range coordinates",this._path):i(m.fromCoords(this.worksheet,t,e,r,n,this.name,this._file),this._path)}usedRange(){const t=this.dimensions();return t.rowCount===0||t.colCount===0?a("missing","Sheet has no used cells",this._path):i(m.fromCoords(this.worksheet,t.startRow,t.startCol,t.endRow,t.endCol,this.name,this._file),this._path)}row(t){const e=this.dimensions();if(t<1)return a("bounds",`Invalid row number: ${t}`,this._path);const r=Math.max(e.endCol,1);return i(m.fromCoords(this.worksheet,t,1,t,r,this.name,this._file),this._path)}col(t){const e=typeof t=="string"?S(t.toUpperCase()):t;if(e<1)return a("bounds",`Invalid column: ${t}`,this._path);const r=this.dimensions(),n=Math.max(r.endRow,1);return i(m.fromCoords(this.worksheet,1,e,n,e,this.name,this._file),this._path)}*rows(){const t=this.dimensions();for(let e=t.startRow;e<=t.endRow;e++)yield m.fromCoords(this.worksheet,e,t.startCol,e,t.endCol,this.name,this._file)}*cols(){const t=this.dimensions();for(let e=t.startCol;e<=t.endCol;e++)yield m.fromCoords(this.worksheet,t.startRow,e,t.endRow,e,this.name,this._file)}cursor(t){const e=t??"A1";return d.create(this,e)}cursorAt(t,e){return d.createAt(this,t,e)}find(t){const e=this.usedRange();return e.ok?e.value.find(t):e}findAll(t){const e=this.usedRange();return e.ok?e.value.findAll(t):[]}findValue(t){const e=this.usedRange();return e.ok?e.value.findValue(t):e}findInRange(t,e){const r=this.range(t);return r.ok?r.value.find(e):r}findAllInRange(t,e){const r=this.range(t);return r.ok?r.value.findAll(e):[]}dimensions(){const t=this.worksheet.rowCount,e=this.worksheet.columnCount;let r=1,n=t,o=1,l=e;if(this.worksheet.dimensions){const h=this.worksheet.dimensions;if(typeof h=="string")try{const u=y(h);r=u.start.row,o=u.start.col,n=u.end.row,l=u.end.col}catch{}}return{startRow:r,endRow:n,startCol:o,endCol:l,rowCount:n-r+1,colCount:l-o+1}}rowCount(){return this.dimensions().rowCount}colCount(){return this.dimensions().colCount}mergedRanges(){const t=this.worksheet._merges;return t?Object.keys(t):[]}isMerged(t){const e=this.cell(t);return e.ok?e.value.isMerged():!1}getWorksheet(){return this.worksheet}getCellInternal(t,e){if(t<1||e<1)return;const r=this.worksheet.getCell(t,e);return p.fromExcelJS(r,this.name,this._file)}}class _{constructor(t,e){this.workbook=t,this._path=e,this.sheetsCache=new Map}static fromExcelJS(t,e){const r={file:e};return new _(t,r)}get path(){return this._path}get file(){return this._path.file}sheet(t){const e=this.sheetsCache.get(t);if(e)return i(e,{...this._path,sheet:t});const r=this.workbook.getWorksheet(t);if(!r)return a("missing",`Sheet "${t}" not found`,this._path);const n=g.fromExcelJS(r,this._path.file);return this.sheetsCache.set(t,n),i(n,n.path)}sheetAt(t){if(t<1)return a("bounds",`Sheet index must be >= 1, got ${t}`,this._path);const e=this.workbook.getWorksheet(t);if(!e)return a("missing",`Sheet at index ${t} not found`,this._path);const r=this.sheetsCache.get(e.name);if(r)return i(r,r.path);const n=g.fromExcelJS(e,this._path.file);return this.sheetsCache.set(e.name,n),i(n,n.path)}sheets(){const t=[];return this.workbook.eachSheet(e=>{const r=this.sheetsCache.get(e.name);if(r)t.push(r);else{const n=g.fromExcelJS(e,this._path.file);this.sheetsCache.set(e.name,n),t.push(n)}}),t}sheetNames(){const t=[];return this.workbook.eachSheet(e=>{t.push(e.name)}),t}sheetCount(){return this.workbook.worksheets.length}firstSheet(){return this.sheetAt(1)}lastSheet(){const t=this.sheetCount();return t===0?a("missing","Workbook has no sheets",this._path):this.sheetAt(t)}hasSheet(t){return this.workbook.getWorksheet(t)!==void 0}findSheet(t){for(const e of this.sheets())if(t(e))return i(e,e.path);return a("missing","No sheet matching predicate found",this._path)}filterSheets(t){return this.sheets().filter(t)}findSheetByPattern(t){return this.findSheet(e=>t.test(e.name))}filterSheetsByPattern(t){return this.filterSheets(e=>t.test(e.name))}properties(){return{title:this.workbook.title,subject:this.workbook.subject,creator:this.workbook.creator,lastModifiedBy:this.workbook.lastModifiedBy,created:this.workbook.created,modified:this.workbook.modified}}creator(){return this.workbook.creator}created(){return this.workbook.created}modified(){return this.workbook.modified}definedNames(){return[]}*[Symbol.iterator](){for(const t of this.sheets())yield t}forEach(t){this.sheets().forEach(t)}map(t){return this.sheets().map(t)}getWorkbook(){return this.workbook}}const U={equals:s=>t=>{const e=t.value();return e.ok?s===null?e.value===null:e.value===null?!1:s instanceof Date&&e.value instanceof Date?s.getTime()===e.value.getTime():e.value===s:!1},contains:(s,t=!1)=>e=>{const r=e.string();return r.ok?t?r.value.includes(s):r.value.toLowerCase().includes(s.toLowerCase()):!1},matches:s=>t=>{const e=t.string();return e.ok?s.test(e.value):!1},startsWith:(s,t=!1)=>e=>{const r=e.string();return r.ok?t?r.value.startsWith(s):r.value.toLowerCase().startsWith(s.toLowerCase()):!1},endsWith:(s,t=!1)=>e=>{const r=e.string();return r.ok?t?r.value.endsWith(s):r.value.toLowerCase().endsWith(s.toLowerCase()):!1},isString:()=>s=>s.isString(),isNumber:()=>s=>s.isNumber(),isBoolean:()=>s=>s.isBoolean(),isDate:()=>s=>s.isDate(),isEmpty:()=>s=>s.isEmpty(),isNotEmpty:()=>s=>!s.isEmpty(),isFormula:()=>s=>s.isFormula(),isError:()=>s=>s.isError(),isMerged:()=>s=>s.isMerged(),greaterThan:s=>t=>{const e=t.number();return e.ok&&e.value>s},greaterThanOrEqual:s=>t=>{const e=t.number();return e.ok&&e.value>=s},lessThan:s=>t=>{const e=t.number();return e.ok&&e.value<s},lessThanOrEqual:s=>t=>{const e=t.number();return e.ok&&e.value<=s},between:(s,t)=>e=>{const r=e.number();return r.ok&&r.value>=s&&r.value<=t},dateBefore:s=>t=>{const e=t.date();return e.ok&&e.value.getTime()<s.getTime()},dateAfter:s=>t=>{const e=t.date();return e.ok&&e.value.getTime()>s.getTime()},dateBetween:(s,t)=>e=>{const r=e.date();if(!r.ok)return!1;const n=r.value.getTime();return n>=s.getTime()&&n<=t.getTime()},inRow:s=>t=>t.row===s,inCol:s=>t=>t.col===s,inColLetter:s=>t=>t.colLetter.toUpperCase()===s.toUpperCase(),and:(...s)=>t=>s.every(e=>e(t)),or:(...s)=>t=>s.some(e=>e(t)),not:s=>t=>!s(t),isBold:()=>s=>s.style().font?.bold===!0,isItalic:()=>s=>s.style().font?.italic===!0,hasHyperlink:()=>s=>s.hyperlink().ok,hasComment:()=>s=>s.comment().ok,always:()=>()=>!0,never:()=>()=>!1,custom:s=>s};function q(s){return{kind:"transform",namespace:"@origints/xlsx",name:"parseXlsx",args:s}}const P={namespace:"@origints/xlsx",name:"parseXlsx",execute(s,t){throw new Error("parseXlsx requires async execution. Use parseXlsxAsyncImpl instead.")}};function x(s){return new Uint8Array(s).buffer}const M={namespace:"@origints/xlsx",name:"parseXlsx",async execute(s,t){const e=t??{};let r;if(s instanceof ReadableStream){const o=await I(s);r=x(o)}else if(Buffer.isBuffer(s))r=x(s);else if(s instanceof ArrayBuffer)r=s;else if(s instanceof Uint8Array)r=x(s);else throw new Error(`parseXlsx expects stream or buffer input, got ${typeof s}`);const n=new N.Workbook;return await n.xlsx.load(r),_.fromExcelJS(n,e.fileName)}};async function X(s,t){const e=new N.Workbook;let r;return s instanceof ArrayBuffer?r=s:r=x(s),await e.xlsx.load(r),_.fromExcelJS(e,t?.fileName)}async function H(s,t){const e=new N.Workbook;return await e.xlsx.readFile(s),_.fromExcelJS(e,t?.fileName??s)}function j(s,t){return s==null?null:s instanceof Date?t?.dateAsIsoString!==!1?s.toISOString():s.getTime():typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:null}function J(s,t){const e=s.value(),r=e.ok?j(e.value,t):null;return t?.includeCellAddresses?{address:s.address,value:r}:r}function D(s,t){return t?.firstRowAsHeaders?B(s,t):W(s,t)}function W(s,t){const e=[];for(const r of s.rows()){const n=[];for(const o of r){const l=J(o,t);l!==null||t?.includeEmpty?n.push(l):(n.length>0||t?.includeEmpty)&&n.push(null)}(n.length>0||t?.includeEmpty)&&e.push(n)}return e}function B(s,t){const e=[...s.rows()];if(e.length===0)return[];const n=e[0].map(l=>{const h=l.value();return h.ok&&h.value!==null?String(h.value):`col_${l.col}`}),o=[];for(let l=1;l<e.length;l++){const h=e[l],u={};let c=!1;for(let f=0;f<n.length;f++){const k=n[f],T=h[f];if(T){const v=J(T,t);v!==null&&(c=!0),u[k]=v}else u[k]=null}(c||t?.includeEmpty)&&o.push(u)}return o}function A(s,t){const e=s.usedRange();return e.ok?D(e.value,t):t?.firstRowAsHeaders?[]:[[]]}function Z(s,t){const e=s.sheets();if(t?.includeSheetNames!==!1){const r={};for(const n of e)r[n.name]=A(n,t);return r}return e.map(r=>A(r,t))}function L(s,t){const e=t?.delimiter??",",r=t?.lineEnding??`
2
- `,n=t?.quoteStrings??!0,o=[];for(const l of s.rows()){const h=[];for(const u of l){const c=u.value();let f;!c.ok||c.value===null?f="":c.value instanceof Date?f=c.value.toISOString():f=String(c.value),n&&(f.includes(e)||f.includes(`
3
- `)||f.includes("\r")||f.includes('"'))&&(f='"'+f.replace(/"/g,'""')+'"'),h.push(f)}o.push(h.join(e))}return o.join(r)}function G(s,t){const e=s.usedRange();return e.ok?L(e.value,t):""}function K(s){s.register(M)}exports.XlsxCell=p;exports.XlsxCursor=d;exports.XlsxRange=m;exports.XlsxSheet=g;exports.XlsxWorkbook=_;exports.cellToJson=J;exports.cellValueToJson=j;exports.columnLetterToNumber=S;exports.columnNumberToLetter=V;exports.fail=a;exports.formatAddress=C;exports.formatRange=$;exports.formatXlsxPath=F;exports.isError=R;exports.isFormula=b;exports.isInRange=O;exports.ok=i;exports.parseAddress=w;exports.parseRange=y;exports.parseXlsx=q;exports.parseXlsxAsyncImpl=M;exports.parseXlsxBuffer=X;exports.parseXlsxFile=H;exports.parseXlsxImpl=P;exports.predicates=U;exports.rangeToArray=W;exports.rangeToCsv=L;exports.rangeToJson=D;exports.rangeToObjects=B;exports.registerXlsxTransforms=K;exports.sheetToCsv=G;exports.sheetToJson=A;exports.streamToBuffer=I;exports.toExcelLocation=z;exports.workbookToJson=Z;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("@origints/core"),le=require("exceljs");function f(r,e){return{ok:!0,value:r,path:e}}function w(r,e,t,s){return{ok:!1,failure:{kind:r,message:e,path:t,sourceLocation:s}}}function Ae(r){const e=[];return r.file&&e.push(r.file),r.sheet&&e.push(`[${r.sheet}]`),r.range?e.push(`!${r.range}`):r.cell&&e.push(`!${r.cell}`),e.join("")||"workbook"}function Te(r){if(r.sheet)return{kind:"excel",file:r.file??"",sheet:r.sheet,range:r.range??r.cell??""}}function X(r){return typeof r=="object"&&r!==null&&!(r instanceof Date)&&"formula"in r}function Y(r){return typeof r=="object"&&r!==null&&!(r instanceof Date)&&"error"in r}async function ke(r){const e=r.getReader(),t=[];try{for(;;){const{done:s,value:n}=await e.read();if(s)break;t.push(n)}return Buffer.concat(t)}finally{e.releaseLock()}}function Q(r){let e=0;for(let t=0;t<r.length;t++)e=e*26+(r.charCodeAt(t)-64);return e}function ie(r){let e="";for(;r>0;){const t=(r-1)%26;e=String.fromCharCode(65+t)+e,r=Math.floor((r-1)/26)}return e}function F(r){const e=r.match(/^([A-Z]+)(\d+)$/i);if(!e)throw new Error(`Invalid cell address: ${r}`);const t=e[1].toUpperCase();return{row:parseInt(e[2],10),col:Q(t),colLetter:t}}function H(r,e){return`${ie(e)}${r}`}function U(r){const e=r.split(":");if(e.length===1){const n=F(e[0]);return{start:{row:n.row,col:n.col},end:{row:n.row,col:n.col}}}if(e.length!==2)throw new Error(`Invalid range: ${r}`);const t=F(e[0]),s=F(e[1]);return{start:{row:t.row,col:t.col},end:{row:s.row,col:s.col}}}function ne(r,e,t,s){const n=H(r,e),l=H(t,s);return n===l?n:`${n}:${l}`}function We(r,e,t){return r>=t.start.row&&r<=t.end.row&&e>=t.start.col&&e<=t.end.col}class T{constructor(e,t,s){this.cell=e,this._path=t,this._sheetName=s}get[I.TYPE_LABEL](){return`XlsxCell(${this.address})`}static fromExcelJS(e,t,s){const n={file:s,sheet:t,cell:e.address};return new T(e,n,t)}get address(){return this.cell.address}get row(){return typeof this.cell.row=="number"?this.cell.row:parseInt(String(this.cell.row),10)}get col(){return typeof this.cell.col=="number"?this.cell.col:parseInt(String(this.cell.col),10)}get colLetter(){return this.address.replace(/\d+$/,"")}get path(){return this._path}get sheetName(){return this._sheetName}value(){const e=this.getRawValue();return X(e)?f(e.result??null,this._path):Y(e)?w("formula",`Cell contains error: ${e.error}`,this._path):f(e,this._path)}extendedValue(){return f(this.getRawValue(),this._path)}string(){const e=this.getResolvedValue();return e==null?w("type","Expected string, got null",this._path):typeof e=="string"?f(e,this._path):typeof e=="number"||typeof e=="boolean"?f(String(e),this._path):e instanceof Date?f(e.toISOString(),this._path):w("type",`Expected string, got ${typeof e}`,this._path)}number(){const e=this.getResolvedValue();if(typeof e=="number")return f(e,this._path);if(typeof e=="string"){const t=parseFloat(e);if(!isNaN(t))return f(t,this._path)}return w("type",`Expected number, got ${se(e)}`,this._path)}boolean(){const e=this.getResolvedValue();return typeof e=="boolean"?f(e,this._path):w("type",`Expected boolean, got ${se(e)}`,this._path)}date(){const e=this.getResolvedValue();if(e instanceof Date)return f(e,this._path);if(typeof e=="number"){const t=this.excelDateToJS(e);return f(t,this._path)}if(typeof e=="string"){const t=new Date(e);if(!isNaN(t.getTime()))return f(t,this._path)}return w("type",`Expected date, got ${se(e)}`,this._path)}formula(){const e=this.getRawValue();return X(e)?f(e.formula,this._path):w("type","Cell does not contain a formula",this._path)}richText(){const e=this.cell.value,t=this.cell.hyperlink;if(e&&typeof e=="object"&&"richText"in e){const a=e.richText.map(i=>({text:i.text,bold:i.font?.bold,italic:i.font?.italic,underline:i.font?.underline===!0||i.font?.underline==="single",strikethrough:i.font?.strike,color:i.font?.color?.argb,size:i.font?.size,font:i.font?.name}));return f({segments:a,hyperlink:t},this._path)}if(e&&typeof e=="object"&&"text"in e&&"hyperlink"in e){const o=e,a=this.style(),i={text:o.text,bold:a.font?.bold,italic:a.font?.italic,underline:a.font?.underline,strikethrough:a.font?.strikethrough,color:a.font?.color,size:a.font?.size,font:a.font?.name};return f({segments:[i],hyperlink:o.hyperlink},this._path)}const s=this.getResolvedValue(),n=s!==null?String(s):"",l=this.style(),u={text:n,bold:l.font?.bold,italic:l.font?.italic,underline:l.font?.underline,strikethrough:l.font?.strikethrough,color:l.font?.color,size:l.font?.size,font:l.font?.name};return f({segments:[u],hyperlink:t},this._path)}markdown(){const e=this.richText();if(!e.ok)return e;const{segments:t,hyperlink:s}=e.value;let n="";for(const l of t){let u=l.text;l.strikethrough&&(u=`~~${u}~~`),l.bold&&(u=`**${u}**`),l.italic&&(u=`*${u}*`),n+=u}return s&&(n=`[${n}](${s})`),f(n,this._path)}isRichText(){const e=this.cell.value;return e!==null&&typeof e=="object"&&"richText"in e}isEmpty(){const e=this.cell.value;return e==null||e===""}isFormula(){return X(this.getRawValue())}isMerged(){return this.cell.isMerged}isMergedMaster(){return this.cell.isMerged?this.cell.master.address===this.cell.address:!1}isString(){return typeof this.getResolvedValue()=="string"}isNumber(){return typeof this.getResolvedValue()=="number"}isBoolean(){return typeof this.getResolvedValue()=="boolean"}isDate(){return this.getResolvedValue()instanceof Date}isError(){return Y(this.getRawValue())}style(){const e=this.cell.font,t=this.cell.fill,s=this.cell.border,n=this.cell.alignment;return{font:e?{name:e.name,size:e.size,bold:e.bold,italic:e.italic,underline:e.underline===!0||e.underline==="single",strikethrough:e.strike,color:e.color?.argb??(e.color?.theme!==void 0?`theme:${e.color.theme}`:void 0)}:void 0,fill:t&&t.type==="pattern"?{type:t.pattern,color:t.fgColor?.argb}:void 0,border:s?{top:!!s.top,bottom:!!s.bottom,left:!!s.left,right:!!s.right}:void 0,alignment:n?{horizontal:n.horizontal,vertical:n.vertical,wrapText:n.wrapText}:void 0,numFmt:this.cell.numFmt}}hyperlink(){const e=this.cell.hyperlink;return e?f(e,this._path):w("missing","Cell does not contain a hyperlink",this._path)}comment(){const e=this.cell.note;return e?typeof e=="string"?f(e,this._path):e.texts?f(e.texts.map(t=>t.text).join(""),this._path):w("format","Unable to extract comment text",this._path):w("missing","Cell does not contain a comment",this._path)}getOffsetCell(e,t,s){const n=this.row+e,l=this.col+t;if(n<1||l<1)return w("bounds",`Cell offset (${e}, ${t}) from ${this.address} is out of bounds`,this._path);const u=s(n,l);return u?f(u,u.path):w("missing",`Cell at ${H(n,l)} not found`,this._path)}getRawValue(){const e=this.cell.value;if(e==null)return null;if(typeof e=="object"){if("error"in e)return{error:String(e.error)};if("formula"in e){const t=e;return{formula:t.formula,result:this.normalizeResult(t.result)}}if("sharedFormula"in e){const t=e;return{formula:t.sharedFormula,result:this.normalizeResult(t.result)}}if("richText"in e)return e.richText.map(s=>s.text).join("");if(e instanceof Date)return e}return typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:null}getResolvedValue(){const e=this.getRawValue();return X(e)?e.result??null:Y(e)?null:e}normalizeResult(e){return e==null?null:typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e instanceof Date?e:null}excelDateToJS(e){const t=e>60?-1:0,s=e+t-1,n=new Date(1900,0,1);return new Date(n.getTime()+s*24*60*60*1e3)}}function se(r){return r===null?"null":r===void 0?"undefined":r instanceof Date?"date":Array.isArray(r)?"array":typeof r}class x{constructor(e,t,s,n,l,u,o,a){this.worksheet=e,this._startRow=t,this._startCol=s,this._endRow=n,this._endCol=l,this._path=u,this._sheetName=o,this._file=a}get[I.TYPE_LABEL](){return`XlsxRange(${this.address})`}static fromCoords(e,t,s,n,l,u,o){const a=ne(t,s,n,l),i={file:o,sheet:u,range:a};return new x(e,t,s,n,l,i,u,o)}static fromAddress(e,t,s,n){try{const{start:l,end:u}=U(t);return f(x.fromCoords(e,l.row,l.col,u.row,u.col,s,n),{file:n,sheet:s,range:t})}catch{return w("range",`Invalid range address: ${t}`,{file:n,sheet:s})}}get address(){return ne(this._startRow,this._startCol,this._endRow,this._endCol)}get startRow(){return this._startRow}get startCol(){return this._startCol}get endRow(){return this._endRow}get endCol(){return this._endCol}get path(){return this._path}get rowCount(){return this._endRow-this._startRow+1}get colCount(){return this._endCol-this._startCol+1}get cellCount(){return this.rowCount*this.colCount}cellAt(e,t){const s=this._startRow+e,n=this._startCol+t;if(s<this._startRow||s>this._endRow||n<this._startCol||n>this._endCol)return w("bounds",`Offset (${e}, ${t}) is outside range ${this.address}`,this._path);const l=this.worksheet.getCell(s,n);return f(T.fromExcelJS(l,this._sheetName,this._file),{...this._path,cell:l.address,range:void 0})}cell(e){try{const{start:t}=U(e);if(t.row<this._startRow||t.row>this._endRow||t.col<this._startCol||t.col>this._endCol)return w("bounds",`Cell ${e} is outside range ${this.address}`,this._path);const s=this.worksheet.getCell(e);return f(T.fromExcelJS(s,this._sheetName,this._file),{...this._path,cell:e,range:void 0})}catch{return w("range",`Invalid cell address: ${e}`,this._path)}}*cells(){for(let e=this._startRow;e<=this._endRow;e++)for(let t=this._startCol;t<=this._endCol;t++){const s=this.worksheet.getCell(e,t);yield T.fromExcelJS(s,this._sheetName,this._file)}}*rows(){for(let e=this._startRow;e<=this._endRow;e++){const t=[];for(let s=this._startCol;s<=this._endCol;s++){const n=this.worksheet.getCell(e,s);t.push(T.fromExcelJS(n,this._sheetName,this._file))}yield t}}*cols(){for(let e=this._startCol;e<=this._endCol;e++){const t=[];for(let s=this._startRow;s<=this._endRow;s++){const n=this.worksheet.getCell(s,e);t.push(T.fromExcelJS(n,this._sheetName,this._file))}yield t}}values(){const e=[];for(const t of this.rows()){const s=[];for(const n of t){const l=n.value();s.push(l.ok?l.value:null)}e.push(s)}return e}cellsArray(){return[...this.cells()]}subRange(e){try{const{start:t,end:s}=U(e);return t.row<this._startRow||s.row>this._endRow||t.col<this._startCol||s.col>this._endCol?w("bounds",`Subrange ${e} extends outside range ${this.address}`,this._path):f(x.fromCoords(this.worksheet,t.row,t.col,s.row,s.col,this._sheetName,this._file),{...this._path,range:e})}catch{return w("range",`Invalid range address: ${e}`,this._path)}}firstRow(){return x.fromCoords(this.worksheet,this._startRow,this._startCol,this._startRow,this._endCol,this._sheetName,this._file)}lastRow(){return x.fromCoords(this.worksheet,this._endRow,this._startCol,this._endRow,this._endCol,this._sheetName,this._file)}firstCol(){return x.fromCoords(this.worksheet,this._startRow,this._startCol,this._endRow,this._startCol,this._sheetName,this._file)}lastCol(){return x.fromCoords(this.worksheet,this._startRow,this._endCol,this._endRow,this._endCol,this._sheetName,this._file)}rowAt(e){const t=this._startRow+e;return t<this._startRow||t>this._endRow?w("bounds",`Row offset ${e} is outside range ${this.address}`,this._path):f(x.fromCoords(this.worksheet,t,this._startCol,t,this._endCol,this._sheetName,this._file),this._path)}colAt(e){const t=this._startCol+e;return t<this._startCol||t>this._endCol?w("bounds",`Column offset ${e} is outside range ${this.address}`,this._path):f(x.fromCoords(this.worksheet,this._startRow,t,this._endRow,t,this._sheetName,this._file),this._path)}find(e){for(const t of this.cells())if(e(t))return f(t,t.path);return w("missing",`No cell matching predicate found in range ${this.address}`,this._path)}findAll(e){const t=[];for(const s of this.cells())e(s)&&t.push(s);return t}findValue(e){for(const t of this.cells()){const s=t.value();if(s.ok&&s.value===e)return f(t,t.path)}return w("missing",`Value "${e}" not found in range ${this.address}`,this._path)}some(e){for(const t of this.cells())if(e(t))return!0;return!1}every(e){for(const t of this.cells())if(!e(t))return!1;return!0}count(e){let t=0;for(const s of this.cells())e(s)&&t++;return t}toArray(){return this.values()}toObjects(e=0,t=1){const s=[...this.rows()];if(s.length===0)return[];const n=s[e];if(!n)return[];const l=n.map(o=>{const a=o.value();return a.ok&&a.value!==null?String(a.value):""}),u=[];for(let o=t;o<s.length;o++){const a=s[o],i={};for(let c=0;c<l.length;c++){const h=l[c];if(h){const k=a[c]?.value();i[h]=k?.ok?k.value:null}}u.push(i)}return u}toJson(){return{address:this.address,rows:this.values()}}}class y{constructor(e,t,s,n="right"){this.sheet=e,this._row=t,this._col=s,this._direction=n}get[I.TYPE_LABEL](){return`XlsxCursor(${this.address} ${this._direction})`}static create(e,t){const{row:s,col:n}=F(t);return new y(e,s,n)}static createAt(e,t,s){return new y(e,Math.max(1,t),Math.max(1,s))}get row(){return this._row}get col(){return this._col}get address(){return H(this._row,this._col)}get colLetter(){return ie(this._col)}get direction(){return this._direction}get path(){return{...this.sheet.path,cell:this.address}}move(e,t){return new y(this.sheet,Math.max(1,this._row+e),Math.max(1,this._col+t),this._direction)}moveTo(e){const{row:t,col:s}=F(e);return new y(this.sheet,t,s,this._direction)}moveToRow(e){return new y(this.sheet,Math.max(1,e),this._col,this._direction)}moveToCol(e){const t=typeof e=="string"?Q(e.toUpperCase()):e;return new y(this.sheet,this._row,Math.max(1,t),this._direction)}left(e=1){return new y(this.sheet,this._row,Math.max(1,this._col-e),"left")}right(e=1){return new y(this.sheet,this._row,this._col+e,"right")}up(e=1){return new y(this.sheet,Math.max(1,this._row-e),this._col,"up")}down(e=1){return new y(this.sheet,this._row+e,this._col,"down")}setDirection(e){return new y(this.sheet,this._row,this._col,e)}forward(e=1){switch(this._direction){case"right":return this.right(e);case"left":return this.left(e);case"down":return this.down(e);case"up":return this.up(e)}}startOfRow(){return new y(this.sheet,this._row,1,this._direction)}startOfCol(){return new y(this.sheet,1,this._col,this._direction)}skipEmpty(){return this.skipWhile(e=>e.isEmpty())}skipWhile(e){let t=this;const s=this.sheet.dimensions(),n=Math.max(s.rowCount,s.colCount)*2;for(let l=0;l<n;l++){const u=t.cell();if(!u.ok||!e(u.value))break;t=t.forward()}return t}skipUntil(e){return this.skipWhile(t=>!e(t))}skipToValue(e){return this.skipUntil(t=>{const s=t.value();return s.ok&&s.value===e})}skip(e){return this.forward(e)}grab(){const e=this.cell();return e.ok?f({cell:e.value,cursor:this.forward()},this.path):e}grabN(e){const t=[];let s=this;for(let n=0;n<e;n++){const l=s.cell();if(!l.ok)break;t.push(l.value),s=s.forward()}return t.length===0?w("bounds","No cells to grab",this.path):f({cells:t,cursor:s},this.path)}grabWhile(e){const t=[];let s=this;const n=this.sheet.dimensions(),l=Math.max(n.rowCount,n.colCount)*2;for(let u=0;u<l;u++){const o=s.cell();if(!o.ok||!e(o.value))break;t.push(o.value),s=s.forward()}return f({cells:t,cursor:s},this.path)}grabUntil(e){return this.grabWhile(t=>!e(t))}grabRow(){const e=[],t=this.sheet.dimensions();let s=this.setDirection("right");for(let n=this._col;n<=t.endCol;n++){const l=s.cell();if(!l.ok)break;e.push(l.value),s=s.forward()}return f({cells:e,cursor:s},this.path)}grabCol(){const e=[],t=this.sheet.dimensions();let s=this.setDirection("down");for(let n=this._row;n<=t.endRow;n++){const l=s.cell();if(!l.ok)break;e.push(l.value),s=s.forward()}return f({cells:e,cursor:s},this.path)}grabNonEmpty(){return this.grabWhile(e=>!e.isEmpty())}peek(){return this.cell()}peekAhead(e){const t=[];let s=this;for(let n=0;n<e;n++){const l=s.cell();if(!l.ok)break;t.push(l.value),s=s.forward()}return f(t,this.path)}peekAt(e,t){return this.move(e,t).cell()}cell(){return this.sheet.cellAt(this._row,this._col)}value(){const e=this.cell();return e.ok?e.value.value():e}isValid(){return this.cell().ok}isEmpty(){const e=this.cell();return e.ok&&e.value.isEmpty()}isNotEmpty(){const e=this.cell();return e.ok&&!e.value.isEmpty()}clone(){return new y(this.sheet,this._row,this._col,this._direction)}}class q{constructor(e,t,s){this.worksheet=e,this._path=t,this._file=s}get[I.TYPE_LABEL](){return`XlsxSheet(${this.name})`}static fromExcelJS(e,t){const s={file:t,sheet:e.name};return new q(e,s,t)}get name(){return this.worksheet.name}get index(){return this.worksheet.id}get path(){return this._path}cell(e){try{F(e);const t=this.worksheet.getCell(e);return f(T.fromExcelJS(t,this.name,this._file),{...this._path,cell:e})}catch{return w("range",`Invalid cell address: ${e}`,this._path)}}cellAt(e,t){if(e<1||t<1)return w("bounds",`Invalid cell coordinates: row=${e}, col=${t}`,this._path);const s=this.worksheet.getCell(e,t);return f(T.fromExcelJS(s,this.name,this._file),{...this._path,cell:s.address})}getValue(e){const t=this.cell(e);return t.ok?t.value.value():t}range(e){return x.fromAddress(this.worksheet,e,this.name,this._file)}rangeFrom(e,t){return this.range(`${e}:${t}`)}rangeAt(e,t,s,n){return e<1||t<1||s<1||n<1?w("bounds","Invalid range coordinates",this._path):f(x.fromCoords(this.worksheet,e,t,s,n,this.name,this._file),this._path)}usedRange(){const e=this.dimensions();return e.rowCount===0||e.colCount===0?w("missing","Sheet has no used cells",this._path):f(x.fromCoords(this.worksheet,e.startRow,e.startCol,e.endRow,e.endCol,this.name,this._file),this._path)}row(e){const t=this.dimensions();if(e<1)return w("bounds",`Invalid row number: ${e}`,this._path);const s=Math.max(t.endCol,1);return f(x.fromCoords(this.worksheet,e,1,e,s,this.name,this._file),this._path)}col(e){const t=typeof e=="string"?Q(e.toUpperCase()):e;if(t<1)return w("bounds",`Invalid column: ${e}`,this._path);const s=this.dimensions(),n=Math.max(s.endRow,1);return f(x.fromCoords(this.worksheet,1,t,n,t,this.name,this._file),this._path)}*rows(){const e=this.dimensions();for(let t=e.startRow;t<=e.endRow;t++)yield x.fromCoords(this.worksheet,t,e.startCol,t,e.endCol,this.name,this._file)}*cols(){const e=this.dimensions();for(let t=e.startCol;t<=e.endCol;t++)yield x.fromCoords(this.worksheet,e.startRow,t,e.endRow,t,this.name,this._file)}cursor(e){const t=e??"A1";return y.create(this,t)}cursorAt(e,t){return y.createAt(this,e,t)}find(e){const t=this.usedRange();return t.ok?t.value.find(e):t}findAll(e){const t=this.usedRange();return t.ok?t.value.findAll(e):[]}findValue(e){const t=this.usedRange();return t.ok?t.value.findValue(e):t}findInRange(e,t){const s=this.range(e);return s.ok?s.value.find(t):s}findAllInRange(e,t){const s=this.range(e);return s.ok?s.value.findAll(t):[]}dimensions(){const e=this.worksheet.rowCount,t=this.worksheet.columnCount;let s=1,n=e,l=1,u=t;if(this.worksheet.dimensions){const o=this.worksheet.dimensions;if(typeof o=="string")try{const a=U(o);s=a.start.row,l=a.start.col,n=a.end.row,u=a.end.col}catch{}}return{startRow:s,endRow:n,startCol:l,endCol:u,rowCount:n-s+1,colCount:u-l+1}}rowCount(){return this.dimensions().rowCount}colCount(){return this.dimensions().colCount}mergedRanges(){const e=this.worksheet._merges;return e?Object.keys(e):[]}isMerged(e){const t=this.cell(e);return t.ok?t.value.isMerged():!1}getWorksheet(){return this.worksheet}getCellInternal(e,t){if(e<1||t<1)return;const s=this.worksheet.getCell(e,t);return T.fromExcelJS(s,this.name,this._file)}}class V{constructor(e,t){this.workbook=e,this._path=t,this.sheetsCache=new Map}get[I.TYPE_LABEL](){return`XlsxWorkbook(${this.sheetCount()} sheets)`}static fromExcelJS(e,t){const s={file:t};return new V(e,s)}get path(){return this._path}get file(){return this._path.file}sheet(e){const t=this.sheetsCache.get(e);if(t)return f(t,{...this._path,sheet:e});const s=this.workbook.getWorksheet(e);if(!s)return w("missing",`Sheet "${e}" not found`,this._path);const n=q.fromExcelJS(s,this._path.file);return this.sheetsCache.set(e,n),f(n,n.path)}sheetAt(e){if(e<1)return w("bounds",`Sheet index must be >= 1, got ${e}`,this._path);const t=this.workbook.getWorksheet(e);if(!t)return w("missing",`Sheet at index ${e} not found`,this._path);const s=this.sheetsCache.get(t.name);if(s)return f(s,s.path);const n=q.fromExcelJS(t,this._path.file);return this.sheetsCache.set(t.name,n),f(n,n.path)}sheets(){const e=[];return this.workbook.eachSheet(t=>{const s=this.sheetsCache.get(t.name);if(s)e.push(s);else{const n=q.fromExcelJS(t,this._path.file);this.sheetsCache.set(t.name,n),e.push(n)}}),e}sheetNames(){const e=[];return this.workbook.eachSheet(t=>{e.push(t.name)}),e}sheetCount(){return this.workbook.worksheets.length}firstSheet(){return this.sheetAt(1)}lastSheet(){const e=this.sheetCount();return e===0?w("missing","Workbook has no sheets",this._path):this.sheetAt(e)}hasSheet(e){return this.workbook.getWorksheet(e)!==void 0}findSheet(e){for(const t of this.sheets())if(e(t))return f(t,t.path);return w("missing","No sheet matching predicate found",this._path)}filterSheets(e){return this.sheets().filter(e)}findSheetByPattern(e){return this.findSheet(t=>e.test(t.name))}filterSheetsByPattern(e){return this.filterSheets(t=>e.test(t.name))}properties(){return{title:this.workbook.title,subject:this.workbook.subject,creator:this.workbook.creator,lastModifiedBy:this.workbook.lastModifiedBy,created:this.workbook.created,modified:this.workbook.modified}}creator(){return this.workbook.creator}created(){return this.workbook.created}modified(){return this.workbook.modified}definedNames(){return[]}*[Symbol.iterator](){for(const e of this.sheets())yield e}forEach(e){this.sheets().forEach(e)}map(e){return this.sheets().map(e)}getWorkbook(){return this.workbook}}const Ie={equals:r=>e=>{const t=e.value();return t.ok?r===null?t.value===null:t.value===null?!1:r instanceof Date&&t.value instanceof Date?r.getTime()===t.value.getTime():t.value===r:!1},contains:(r,e=!1)=>t=>{const s=t.string();return s.ok?e?s.value.includes(r):s.value.toLowerCase().includes(r.toLowerCase()):!1},matches:r=>e=>{const t=e.string();return t.ok?r.test(t.value):!1},startsWith:(r,e=!1)=>t=>{const s=t.string();return s.ok?e?s.value.startsWith(r):s.value.toLowerCase().startsWith(r.toLowerCase()):!1},endsWith:(r,e=!1)=>t=>{const s=t.string();return s.ok?e?s.value.endsWith(r):s.value.toLowerCase().endsWith(r.toLowerCase()):!1},isString:()=>r=>r.isString(),isNumber:()=>r=>r.isNumber(),isBoolean:()=>r=>r.isBoolean(),isDate:()=>r=>r.isDate(),isEmpty:()=>r=>r.isEmpty(),isNotEmpty:()=>r=>!r.isEmpty(),isFormula:()=>r=>r.isFormula(),isError:()=>r=>r.isError(),isMerged:()=>r=>r.isMerged(),greaterThan:r=>e=>{const t=e.number();return t.ok&&t.value>r},greaterThanOrEqual:r=>e=>{const t=e.number();return t.ok&&t.value>=r},lessThan:r=>e=>{const t=e.number();return t.ok&&t.value<r},lessThanOrEqual:r=>e=>{const t=e.number();return t.ok&&t.value<=r},between:(r,e)=>t=>{const s=t.number();return s.ok&&s.value>=r&&s.value<=e},dateBefore:r=>e=>{const t=e.date();return t.ok&&t.value.getTime()<r.getTime()},dateAfter:r=>e=>{const t=e.date();return t.ok&&t.value.getTime()>r.getTime()},dateBetween:(r,e)=>t=>{const s=t.date();if(!s.ok)return!1;const n=s.value.getTime();return n>=r.getTime()&&n<=e.getTime()},inRow:r=>e=>e.row===r,inCol:r=>e=>e.col===r,inColLetter:r=>e=>e.colLetter.toUpperCase()===r.toUpperCase(),and:(...r)=>e=>r.every(t=>t(e)),or:(...r)=>e=>r.some(t=>t(e)),not:r=>e=>!r(e),isBold:()=>r=>r.style().font?.bold===!0,isItalic:()=>r=>r.style().font?.italic===!0,hasHyperlink:()=>r=>r.hyperlink().ok,hasComment:()=>r=>r.comment().ok,always:()=>()=>!0,never:()=>()=>!1,custom:r=>r};function S(r,e){return{kind:"extract",format:"xlsx",steps:r,extract:e}}class g{constructor(e){this.steps=e}get _steps(){return this.steps}string(){return S(this.steps,"string")}number(){return S(this.steps,"number")}boolean(){return S(this.steps,"boolean")}date(){return S(this.steps,"date")}value(){return S(this.steps,"value")}formula(){return S(this.steps,"formula")}right(e=1){return new g([...this.steps,{kind:"right",count:e}])}left(e=1){return new g([...this.steps,{kind:"left",count:e}])}up(e=1){return new g([...this.steps,{kind:"up",count:e}])}down(e=1){return new g([...this.steps,{kind:"down",count:e}])}offset(e,t){return new g([...this.steps,{kind:"offset",rowDelta:e,colDelta:t}])}scanTo(e,t){return new g([...this.steps,{kind:"scanTo",direction:e,predicate:t._spec}])}skipWhile(e,t){return new g([...this.steps,{kind:"skipWhile",direction:e,predicate:t._spec}])}eachCell(e,t,s){const n=s(new g([])),l={kind:"eachCell",direction:e,while:t._spec};return{kind:"array",source:S(this.steps,l),items:n}}eachSlice(e,t,s){const n=s(new we([])),l={kind:"eachSlice",direction:e,while:t._spec};return{kind:"array",source:S(this.steps,l),items:n}}}class we{constructor(e){this.steps=e}colWhere(e,t){const s=S(e._steps,"value");return new g([...this.steps,{kind:"colWhere",headerRef:s,predicate:t._spec}])}rowWhere(e,t){const s=S(e._steps,"value");return new g([...this.steps,{kind:"rowWhere",headerRef:s,predicate:t._spec}])}col(e){return new g([...this.steps,{kind:"offset",rowDelta:0,colDelta:e}])}row(e){return new g([...this.steps,{kind:"offset",rowDelta:e,colDelta:0}])}}class me{constructor(e){this.steps=e}col(e){return new g([...this.steps,{kind:"col",index:e}])}cell(e){return new g([...this.steps,{kind:"cell",ref:e}])}}class K{constructor(e){this.steps=e}cell(e){return new g([...this.steps,{kind:"cell",ref:e}])}cellAt(e,t){return new g([...this.steps,{kind:"cellAt",row:e,col:t}])}rows(e){const t=e(new me([]));return{kind:"array",source:S(this.steps,"rows"),items:t}}cells(e){const t=e(new g([]));return{kind:"array",source:S(this.steps,"cells"),items:t}}}class ge{constructor(e){this.steps=e}cell(e){return new g([...this.steps,{kind:"cell",ref:e}])}cellAt(e,t){return new g([...this.steps,{kind:"cellAt",row:e,col:t}])}}class pe{constructor(e){this.steps=e}cell(e){return new g([...this.steps,{kind:"cell",ref:e}])}cellAt(e,t){return new g([...this.steps,{kind:"cellAt",row:e,col:t}])}}class P{constructor(e){this.steps=e}cell(e){return new g([...this.steps,{kind:"cell",ref:e}])}cellAt(e,t){return new g([...this.steps,{kind:"cellAt",row:e,col:t}])}find(e){return new g([...this.steps,{kind:"find",predicate:e._spec}])}findInRow(e,t){return new g([...this.steps,{kind:"findInRow",rowIndex:e,predicate:t._spec}])}findInCol(e,t){return new g([...this.steps,{kind:"findInCol",colIndex:e,predicate:t._spec}])}findInRange(e,t){return new g([...this.steps,{kind:"findInRange",rangeRef:e,predicate:t._spec}])}range(e,t){if(t===void 0)return new K([...this.steps,{kind:"range",ref:e}]);if(typeof e=="string"&&typeof t=="string")return new K([...this.steps,{kind:"range",ref:`${e}:${t}`}]);const s=S(e._steps,"value"),n=S(t._steps,"value");return new K([...this.steps,{kind:"rangeFromCells",from:s,to:n}])}row(e){return new ge([...this.steps,{kind:"row",index:e}])}col(e){return new pe([...this.steps,{kind:"col",index:e}])}}class ee{constructor(e){this.steps=e}static root(){return new ee([])}sheet(e){return new P([...this.steps,{kind:"sheet",name:e}])}sheetAt(e){return new P([...this.steps,{kind:"sheetAt",index:e}])}firstSheet(){return new P([...this.steps,{kind:"firstSheet"}])}findSheet(e){return new P([...this.steps,{kind:"findSheet",predicate:e._spec}])}}function De(r){return{kind:"transform",namespace:"@origints/xlsx",name:"parseXlsx",args:r,specBuilderFactory:()=>ee.root()}}const Ne={namespace:"@origints/xlsx",name:"parseXlsx",execute(r,e){throw new Error("parseXlsx requires async execution. Use parseXlsxAsyncImpl instead.")}};function Z(r){return new Uint8Array(r).buffer}const ve={namespace:"@origints/xlsx",name:"parseXlsx",async execute(r,e){const t=e??{};let s;if(r instanceof ReadableStream){const l=await ke(r);s=Z(l)}else if(Buffer.isBuffer(r))s=Z(r);else if(r instanceof ArrayBuffer)s=r;else if(r instanceof Uint8Array)s=Z(r);else throw new Error(`parseXlsx expects stream or buffer input, got ${typeof r}`);const n=new le.Workbook;return await n.xlsx.load(s),V.fromExcelJS(n,t.fileName)}};async function Be(r,e){const t=new le.Workbook;let s;return r instanceof ArrayBuffer?s=r:s=Z(r),await t.xlsx.load(s),V.fromExcelJS(t,e?.fileName)}async function Me(r,e){const t=new le.Workbook;return await t.xlsx.readFile(r),V.fromExcelJS(t,e?.fileName??r)}function R(r){switch(r.kind){case"equals":return e=>{const t=e.value();return t.ok?r.value===null?t.value===null:t.value===null?!1:r.value instanceof Date&&t.value instanceof Date?r.value.getTime()===t.value.getTime():t.value===r.value:!1};case"contains":return e=>{const t=e.string();return t.ok?r.caseSensitive?t.value.includes(r.text):t.value.toLowerCase().includes(r.text.toLowerCase()):!1};case"matches":return e=>{const t=e.string();return t.ok?new RegExp(r.pattern,r.flags).test(t.value):!1};case"startsWith":return e=>{const t=e.string();return t.ok?r.caseSensitive?t.value.startsWith(r.prefix):t.value.toLowerCase().startsWith(r.prefix.toLowerCase()):!1};case"endsWith":return e=>{const t=e.string();return t.ok?r.caseSensitive?t.value.endsWith(r.suffix):t.value.toLowerCase().endsWith(r.suffix.toLowerCase()):!1};case"isString":return e=>e.isString();case"isNumber":return e=>e.isNumber();case"isBoolean":return e=>e.isBoolean();case"isDate":return e=>e.isDate();case"isEmpty":return e=>e.isEmpty();case"isNotEmpty":return e=>!e.isEmpty();case"isFormula":return e=>e.isFormula();case"isError":return e=>e.isError();case"isMerged":return e=>e.isMerged();case"gt":return e=>{const t=e.number();return t.ok&&t.value>r.value};case"gte":return e=>{const t=e.number();return t.ok&&t.value>=r.value};case"lt":return e=>{const t=e.number();return t.ok&&t.value<r.value};case"lte":return e=>{const t=e.number();return t.ok&&t.value<=r.value};case"between":return e=>{const t=e.number();return t.ok&&t.value>=r.min&&t.value<=r.max};case"isBold":return e=>e.style().font?.bold===!0;case"isItalic":return e=>e.style().font?.italic===!0;case"hasHyperlink":return e=>e.hyperlink().ok;case"hasComment":return e=>e.comment().ok;case"and":{const e=R(r.left),t=R(r.right);return s=>e(s)&&t(s)}case"or":{const e=R(r.left),t=R(r.right);return s=>e(s)||t(s)}case"not":{const e=R(r.operand);return t=>!e(t)}}}function B(r){switch(r.kind){case"nameEquals":return e=>e.name===r.name;case"nameContains":return e=>e.name.includes(r.text);case"nameStartsWith":return e=>e.name.startsWith(r.prefix);case"nameEndsWith":return e=>e.name.endsWith(r.suffix);case"nameMatches":{const e=new RegExp(r.pattern,r.flags);return t=>e.test(t.name)}case"and":{const e=B(r.left),t=B(r.right);return s=>e(s)&&t(s)}case"or":{const e=B(r.left),t=B(r.right);return s=>e(s)||t(s)}case"not":{const e=B(r.operand);return t=>!e(t)}}}function M(r){switch(r.kind){case"rowCol":{const e=R(r.predicate);return(t,s,n)=>{const l=n+r.offset;if(l<1)return!1;const u=t.cellAt(s,l);return u.ok?e(u.value):!1}}case"and":{const e=M(r.left),t=M(r.right);return(s,n,l)=>e(s,n,l)&&t(s,n,l)}case"or":{const e=M(r.left),t=M(r.right);return(s,n,l)=>e(s,n,l)||t(s,n,l)}case"not":{const e=M(r.operand);return(t,s,n)=>!e(t,s,n)}}}function v(r){return{_spec:r,and(e){return v({kind:"and",left:r,right:e._spec})},or(e){return v({kind:"or",left:r,right:e._spec})},not(){return v({kind:"not",operand:r})},describe(){return C(r)}}}function D(r){return{_spec:r,and(e){return D({kind:"and",left:r,right:e._spec})},or(e){return D({kind:"or",left:r,right:e._spec})},not(){return D({kind:"not",operand:r})},describe(){return N(r)}}}function Le(r){return r===null?"null":r instanceof Date?`Date(${r.toISOString()})`:typeof r=="string"?`'${r}'`:String(r)}const Fe=Object.freeze({equals:r=>v({kind:"equals",value:r}),contains:(r,e=!1)=>v({kind:"contains",text:r,caseSensitive:e}),matches:r=>v({kind:"matches",pattern:r.source,flags:r.flags}),startsWith:(r,e=!1)=>v({kind:"startsWith",prefix:r,caseSensitive:e}),endsWith:(r,e=!1)=>v({kind:"endsWith",suffix:r,caseSensitive:e}),isString:()=>v({kind:"isString"}),isNumber:()=>v({kind:"isNumber"}),isBoolean:()=>v({kind:"isBoolean"}),isDate:()=>v({kind:"isDate"}),isEmpty:()=>v({kind:"isEmpty"}),isNotEmpty:()=>v({kind:"isNotEmpty"}),isFormula:()=>v({kind:"isFormula"}),isError:()=>v({kind:"isError"}),isMerged:()=>v({kind:"isMerged"}),gt:r=>v({kind:"gt",value:r}),gte:r=>v({kind:"gte",value:r}),lt:r=>v({kind:"lt",value:r}),lte:r=>v({kind:"lte",value:r}),between:(r,e)=>v({kind:"between",min:r,max:e}),isBold:()=>v({kind:"isBold"}),isItalic:()=>v({kind:"isItalic"}),hasHyperlink:()=>v({kind:"hasHyperlink"}),hasComment:()=>v({kind:"hasComment"})}),qe=Object.freeze({nameEquals:r=>D({kind:"nameEquals",name:r}),nameContains:r=>D({kind:"nameContains",text:r}),nameStartsWith:r=>D({kind:"nameStartsWith",prefix:r}),nameEndsWith:r=>D({kind:"nameEndsWith",suffix:r}),nameMatches:r=>D({kind:"nameMatches",pattern:r.source,flags:r.flags})});function C(r){switch(r.kind){case"equals":return`equals(${Le(r.value)})`;case"contains":return`contains('${r.text}')`;case"matches":return`matches(/${r.pattern}/${r.flags})`;case"startsWith":return`startsWith('${r.prefix}')`;case"endsWith":return`endsWith('${r.suffix}')`;case"isString":return"isString()";case"isNumber":return"isNumber()";case"isBoolean":return"isBoolean()";case"isDate":return"isDate()";case"isEmpty":return"isEmpty()";case"isNotEmpty":return"isNotEmpty()";case"isFormula":return"isFormula()";case"isError":return"isError()";case"isMerged":return"isMerged()";case"gt":return`gt(${r.value})`;case"gte":return`gte(${r.value})`;case"lt":return`lt(${r.value})`;case"lte":return`lte(${r.value})`;case"between":return`between(${r.min}, ${r.max})`;case"isBold":return"isBold()";case"isItalic":return"isItalic()";case"hasHyperlink":return"hasHyperlink()";case"hasComment":return"hasComment()";case"and":return`${C(r.left)} AND ${C(r.right)}`;case"or":return`${C(r.left)} OR ${C(r.right)}`;case"not":return`NOT(${C(r.operand)})`}}function G(r){return{_spec:r,and(e){return G({kind:"and",left:r,right:e._spec})},or(e){return G({kind:"or",left:r,right:e._spec})},not(){return G({kind:"not",operand:r})},describe(){return L(r)}}}function Ve(r,e){return G({kind:"rowCol",offset:r,predicate:e._spec})}function L(r){switch(r.kind){case"rowCol":return`rowCol(${r.offset}, ${C(r.predicate)})`;case"and":return`${L(r.left)} AND ${L(r.right)}`;case"or":return`${L(r.left)} OR ${L(r.right)}`;case"not":return`NOT(${L(r.operand)})`}}function N(r){switch(r.kind){case"nameEquals":return`nameEquals('${r.name}')`;case"nameContains":return`nameContains('${r.text}')`;case"nameStartsWith":return`nameStartsWith('${r.prefix}')`;case"nameEndsWith":return`nameEndsWith('${r.suffix}')`;case"nameMatches":return`nameMatches(/${r.pattern}/${r.flags})`;case"and":return`${N(r.left)} AND ${N(r.right)}`;case"or":return`${N(r.left)} OR ${N(r.right)}`;case"not":return`NOT(${N(r.operand)})`}}const ue=new WeakMap,he=new WeakMap;function W(r){return{ok:!0,value:r,path:[]}}function E(r){return{ok:!1,kind:"format",message:r,path:[]}}function O(r,e){return{ok:!1,kind:"format",message:r,path:[...e]}}function _(r,e){return r.ok?r.value:E(`XLSX navigation failed at ${e}: ${r.failure.message}`)}function fe(r){switch(r.kind){case"sheet":return`sheet("${r.name}")`;case"sheetAt":return`sheetAt(${r.index})`;case"firstSheet":return"firstSheet()";case"findSheet":return`findSheet(${N(r.predicate)})`;case"cell":return`cell("${r.ref}")`;case"cellAt":return`cellAt(${r.row}, ${r.col})`;case"find":return`find(${C(r.predicate)})`;case"findInRow":return`findInRow(${r.rowIndex}, ${C(r.predicate)})`;case"findInCol":return`findInCol(${r.colIndex}, ${C(r.predicate)})`;case"findInRange":return`findInRange("${r.rangeRef}", ${C(r.predicate)})`;case"right":return`right(${r.count})`;case"left":return`left(${r.count})`;case"up":return`up(${r.count})`;case"down":return`down(${r.count})`;case"offset":return`offset(${r.rowDelta}, ${r.colDelta})`;case"scanTo":return`scanTo(${r.direction}, ${C(r.predicate)})`;case"skipWhile":return`skipWhile(${r.direction}, ${C(r.predicate)})`;case"colWhere":return`colWhere(${C(r.predicate)})`;case"rowWhere":return`rowWhere(${C(r.predicate)})`;case"range":return`range("${r.ref}")`;case"rangeFromCells":return"rangeFromCells()";case"row":return`row(${r.index})`;case"col":return`col(${r.index})`}}function m(r){return typeof r=="object"&&r!==null&&"ok"in r&&!r.ok}class be{constructor(e,t,s){this.workbook=e,this.sheet=t,this.anchorCell=s}get[I.TYPE_LABEL](){return"XlsxSliceContext"}}function Je(r){if(r==null||typeof r!="object")return null;const e=r[I.TYPE_LABEL];if(typeof e=="string"){if(e==="XlsxSliceContext")return"sliceContext";if(e.startsWith("XlsxWorkbook"))return"workbook";if(e.startsWith("XlsxRange"))return"range";if(e.startsWith("XlsxCell"))return"cell"}return r instanceof x?"range":r instanceof T?"cell":"workbook"}function ae(r){switch(r){case"right":return{rowDelta:0,colDelta:1};case"left":return{rowDelta:0,colDelta:-1};case"down":return{rowDelta:1,colDelta:0};case"up":return{rowDelta:-1,colDelta:0}}}function de(r,e,t,s,n,l){const u=R(n),{rowDelta:o,colDelta:a}=ae(s),i=r.dimensions(),c=Math.max(i.rowCount,i.colCount)*2;let h=e+o,d=t+a;for(let b=0;b<c&&!(h<1||d<1||h>i.endRow+1||d>i.endCol+1);b++){const p=r.cellAt(h,d);if(!p.ok)break;const $=p.value;if(l==="scanTo"){if(u($))return $}else if(!u($))return $;h+=o,d+=a}const k=C(n);return E(l==="scanTo"?`scanTo(${s}): no cell matching ${k} found`:`skipWhile(${s}): predicate ${k} never stopped matching`)}function je(r,e,t,s,n){const l=R(n),{rowDelta:u,colDelta:o}=ae(s),a=r.dimensions(),i=Math.max(a.rowCount,a.colCount)*2,c=[];let h=e,d=t;for(let k=0;k<i&&!(h<1||d<1||h>a.endRow+1||d>a.endCol+1);k++){const b=r.cellAt(h,d);if(!b.ok)break;const p=b.value;if(!l(p))break;c.push(p),h+=u,d+=o}return c}function Xe(r,e,t,s,n,l){const u=M(l),{rowDelta:o,colDelta:a}=ae(n),i=e.dimensions(),c=Math.max(i.rowCount,i.colCount)*2,h=[];let d=t,k=s;for(let b=0;b<c&&!(d<1||k<1||d>i.endRow+1||k>i.endCol+1||!u(e,d,k));b++){const p=e.cellAt(d,k);if(!p.ok)break;h.push(new be(r,e,p.value)),d+=o,k+=a}return h}function z(r,e){let t=r;const s=[];function n(o,a){a.level==="cell"?s.push(`${o}@${a.cell.address}`):s.push(o)}function l(o,a){const i=[...s];return a&&i.push(fe(a)),O(o,i)}function u(o){return o.message}for(const o of e){const a=fe(o);switch(o.kind){case"sheet":{const i=_(t.workbook.sheet(o.name),a);if(m(i))return l(u(i),o);t={level:"sheet",workbook:t.workbook,sheet:i},n(a,t);break}case"sheetAt":{const i=_(t.workbook.sheetAt(o.index),a);if(m(i))return l(u(i),o);t={level:"sheet",workbook:t.workbook,sheet:i},n(a,t);break}case"firstSheet":{const i=_(t.workbook.firstSheet(),a);if(m(i))return l(u(i),o);t={level:"sheet",workbook:t.workbook,sheet:i},n(a,t);break}case"findSheet":{const i=B(o.predicate),c=_(t.workbook.findSheet(i),a);if(m(c))return l(u(c),o);t={level:"sheet",workbook:t.workbook,sheet:c},n(a,t);break}case"cell":{if(t.level==="workbook")return l("cell() called without a sheet navigation step",o);if(t.level==="range"){const h=_(t.range.cell(o.ref),a);if(m(h))return l(u(h),o);t={level:"cell",workbook:t.workbook,sheet:t.sheet,cell:h},n(a,t);break}const i=t.sheet,c=_(i.cell(o.ref),a);if(m(c))return l(u(c),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:c},n(a,t);break}case"cellAt":{if(t.level==="workbook")return l("cellAt() called without a sheet navigation step",o);if(t.level==="range"){const h=_(t.range.cellAt(o.row,o.col),a);if(m(h))return l(u(h),o);t={level:"cell",workbook:t.workbook,sheet:t.sheet,cell:h},n(a,t);break}const i=t.sheet,c=_(i.cellAt(o.row,o.col),a);if(m(c))return l(u(c),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:c},n(a,t);break}case"find":{if(t.level!=="sheet")return l("find() requires sheet-level navigation state",o);const i=t.sheet,c=R(o.predicate),h=_(i.find(c),a);if(m(h))return l(u(h),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:h},n(a,t);break}case"findInRow":{if(t.level!=="sheet")return l("findInRow() requires sheet-level navigation state",o);const i=t.sheet,c=R(o.predicate),h=i.dimensions(),d=Math.max(h.endCol,1);let k=null;for(let b=1;b<=d;b++){const p=i.cellAt(o.rowIndex,b);if(p.ok&&c(p.value)){k=p.value;break}}if(!k)return l(`findInRow(${o.rowIndex}): no cell matching ${C(o.predicate)} found`,o);t={level:"cell",workbook:t.workbook,sheet:i,cell:k},n(a,t);break}case"findInCol":{if(t.level!=="sheet")return l("findInCol() requires sheet-level navigation state",o);const i=t.sheet,c=R(o.predicate),h=i.dimensions(),d=Math.max(h.endRow,1);let k=null;for(let b=1;b<=d;b++){const p=i.cellAt(b,o.colIndex);if(p.ok&&c(p.value)){k=p.value;break}}if(!k)return l(`findInCol(${o.colIndex}): no cell matching ${C(o.predicate)} found`,o);t={level:"cell",workbook:t.workbook,sheet:i,cell:k},n(a,t);break}case"findInRange":{if(t.level!=="sheet")return l("findInRange() requires sheet-level navigation state",o);const i=t.sheet,c=R(o.predicate),h=_(i.findInRange(o.rangeRef,c),a);if(m(h))return l(u(h),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:h},n(a,t);break}case"right":{if(t.level!=="cell")return l("right() requires cell-level navigation state",o);const i=t.sheet,c=_(i.cellAt(t.cell.row,t.cell.col+o.count),a);if(m(c))return l(u(c),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:c},n(a,t);break}case"left":{if(t.level!=="cell")return l("left() requires cell-level navigation state",o);const i=t.sheet,c=t.cell.col-o.count;if(c<1)return l(`left(${o.count}) from column ${t.cell.col} goes out of bounds`,o);const h=_(i.cellAt(t.cell.row,c),a);if(m(h))return l(u(h),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:h},n(a,t);break}case"up":{if(t.level!=="cell")return l("up() requires cell-level navigation state",o);const i=t.sheet,c=t.cell.row-o.count;if(c<1)return l(`up(${o.count}) from row ${t.cell.row} goes out of bounds`,o);const h=_(i.cellAt(c,t.cell.col),a);if(m(h))return l(u(h),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:h},n(a,t);break}case"down":{if(t.level!=="cell")return l("down() requires cell-level navigation state",o);const i=t.sheet,c=_(i.cellAt(t.cell.row+o.count,t.cell.col),a);if(m(c))return l(u(c),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:c},n(a,t);break}case"offset":{if(t.level!=="cell")return l("offset() requires cell-level navigation state",o);const i=t.sheet,c=t.cell.row+o.rowDelta,h=t.cell.col+o.colDelta;if(c<1||h<1)return l(`offset(${o.rowDelta}, ${o.colDelta}) from ${t.cell.address} goes out of bounds`,o);const d=_(i.cellAt(c,h),a);if(m(d))return l(u(d),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:d},n(a,t);break}case"scanTo":{if(t.level!=="cell")return l("scanTo() requires cell-level navigation state",o);const i=t.sheet,c=de(i,t.cell.row,t.cell.col,o.direction,o.predicate,"scanTo");if(m(c))return l(u(c),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:c},n(a,t);break}case"skipWhile":{if(t.level!=="cell")return l("skipWhile() requires cell-level navigation state",o);const i=t.sheet,c=de(i,t.cell.row,t.cell.col,o.direction,o.predicate,"skipWhile");if(m(c))return l(u(c),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:c},n(a,t);break}case"range":{if(t.level!=="sheet")return l("range() requires sheet-level navigation state",o);const i=t.sheet,c=_(i.range(o.ref),a);if(m(c))return l(u(c),o);t={level:"range",workbook:t.workbook,sheet:i,range:c},n(a,t);break}case"rangeFromCells":{if(t.level!=="sheet")return l("rangeFromCells requires sheet-level navigation state",o);const i=t.sheet,c=z({level:"workbook",workbook:t.workbook},o.from.steps);if(m(c))return l(u(c),o);const h=c;if(h.state.level!=="cell")return l('rangeFromCells: "from" did not resolve to a cell',o);const d=h.state.cell,k=z({level:"workbook",workbook:t.workbook},o.to.steps);if(m(k))return l(u(k),o);const b=k;if(b.state.level!=="cell")return l('rangeFromCells: "to" did not resolve to a cell',o);const p=b.state.cell,$=_(i.rangeAt(d.row,d.col,p.row,p.col),a);if(m($))return l(u($),o);t={level:"range",workbook:t.workbook,sheet:i,range:$},n(a,t);break}case"row":{if(t.level!=="sheet")return l("row() requires sheet-level navigation state",o);const i=t.sheet,c=_(i.row(o.index),a);if(m(c))return l(u(c),o);t={level:"range",workbook:t.workbook,sheet:i,range:c},n(a,t);break}case"col":{if(t.level==="range"){const h=_(t.range.cellAt(0,o.index-1),a);if(m(h))return l(u(h),o);t={level:"cell",workbook:t.workbook,sheet:t.sheet,cell:h},n(a,t);break}if(t.level!=="sheet")return l("col() requires sheet-level or range-level navigation state",o);const i=t.sheet,c=_(i.col(o.index),a);if(m(c))return l(u(c),o);t={level:"range",workbook:t.workbook,sheet:i,range:c},n(a,t);break}case"colWhere":{if(t.level!=="cell")return l("colWhere() requires cell-level navigation state",o);const i=t.sheet,c=JSON.stringify(o);let h=ue.get(i),d=h?.get(c)??null;if(d===null){const b=o.headerRef,p=z({level:"workbook",workbook:t.workbook},b.steps);if(m(p))return l(u(p),o);const $=p;if($.state.level!=="cell")return l("colWhere: headerRef did not resolve to a cell",o);const J=$.state.cell.row,te=i.dimensions(),re=R(o.predicate);for(let A=1;A<=te.endCol;A++){const j=i.cellAt(J,A);if(j.ok&&re(j.value)){d=A;break}}if(d===null){const A=C(o.predicate);return l(`colWhere: no column matching ${A} found in header row ${J}`,o)}h||(h=new Map,ue.set(i,h)),h.set(c,d)}const k=_(i.cellAt(t.cell.row,d),a);if(m(k))return l(u(k),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:k},n(a,t);break}case"rowWhere":{if(t.level!=="cell")return l("rowWhere() requires cell-level navigation state",o);const i=t.sheet,c=JSON.stringify(o);let h=he.get(i),d=h?.get(c)??null;if(d===null){const b=o.headerRef,p=z({level:"workbook",workbook:t.workbook},b.steps);if(m(p))return l(u(p),o);const $=p;if($.state.level!=="cell")return l("rowWhere: headerRef did not resolve to a cell",o);const J=$.state.cell.col,te=i.dimensions(),re=R(o.predicate);for(let A=1;A<=te.endRow;A++){const j=i.cellAt(A,J);if(j.ok&&re(j.value)){d=A;break}}if(d===null){const A=C(o.predicate);return l(`rowWhere: no row matching ${A} found in header column ${J}`,o)}h||(h=new Map,he.set(i,h)),h.set(c,d)}const k=_(i.cellAt(d,t.cell.col),a);if(m(k))return l(u(k),o);t={level:"cell",workbook:t.workbook,sheet:i,cell:k},n(a,t);break}}}return{state:t,breadcrumbs:s}}function Pe(r,e){if(typeof e!="string")return E(`Unexpected extract type on cell: ${JSON.stringify(e)}`);switch(e){case"string":{const t=r.string();return t.ok?W(t.value):E(`Failed to extract string: ${t.failure.message}`)}case"number":{const t=r.number();return t.ok?W(t.value):E(`Failed to extract number: ${t.failure.message}`)}case"boolean":{const t=r.boolean();return t.ok?W(t.value):E(`Failed to extract boolean: ${t.failure.message}`)}case"date":{const t=r.date();return t.ok?W(t.value):E(`Failed to extract date: ${t.failure.message}`)}case"value":{const t=r.value();return t.ok?W(t.value):E(`Failed to extract value: ${t.failure.message}`)}case"formula":{const t=r.formula();return t.ok?W(t.value):E(`Failed to extract formula: ${t.failure.message}`)}default:return E(`Unknown cell extract type: ${e}`)}}function Oe(r,e){if(e==="rows"){const t=[];for(let s=0;s<r.rowCount;s++){const n=r.rowAt(s);if(!n.ok)return E(`Failed to get row at offset ${s}: ${n.failure.message}`);t.push(n.value)}return W(t)}return e==="cells"?W(r.cellsArray()):E(`Extract type "${typeof e=="string"?e:JSON.stringify(e)}" is not valid at range level`)}function ze(r,e,t){const s=je(r,e.row,e.col,t.direction,t.while);return W(s)}function _e(r,e){if(r.kind!=="extract"||r.format!=="xlsx")return E(`Expected extract spec with format "xlsx", got kind="${r.kind}" format="${r.format}"`);const t=Je(e);let s;switch(t){case"range":{s={level:"range",workbook:null,sheet:null,range:e};break}case"cell":{s={level:"cell",workbook:null,sheet:null,cell:e};break}case"sliceContext":{const i=e;s={level:"cell",workbook:i.workbook,sheet:i.sheet,cell:i.anchorCell};break}default:{s={level:"workbook",workbook:e};break}}const n=z(s,r.steps);if(m(n))return n;const{state:l,breadcrumbs:u}=n,o=r.extract;function a(i){return i.ok?{...i,path:[...u]}:{...i,path:[...u,...i.path]}}return typeof o=="object"&&o.kind==="eachCell"?l.level!=="cell"?O("eachCell extract requires cell-level navigation state",u):a(ze(l.sheet,l.cell,o)):typeof o=="object"&&o.kind==="eachSlice"?l.level!=="cell"?O("eachSlice extract requires cell-level navigation state",u):{ok:!0,value:Xe(l.workbook,l.sheet,l.cell.row,l.cell.col,o.direction,o.while),path:[...u]}:o==="rows"||o==="cells"?l.level!=="range"?O(`"${o}" extract requires range-level navigation state`,u):a(Oe(l.range,o)):l.level!=="cell"?O("XLSX spec navigation did not reach a cell",u):a(Pe(l.cell,o))}function Ce(r,e){return r==null?null:r instanceof Date?e?.dateAsIsoString!==!1?r.toISOString():r.getTime():typeof r=="string"||typeof r=="number"||typeof r=="boolean"?r:null}function ce(r,e){const t=r.value(),s=t.ok?Ce(t.value,e):null;return e?.includeCellAddresses?{address:r.address,value:s}:s}function xe(r,e){return e?.firstRowAsHeaders?Re(r,e):ye(r,e)}function ye(r,e){const t=[];for(const s of r.rows()){const n=[];for(const l of s){const u=ce(l,e);u!==null||e?.includeEmpty?n.push(u):(n.length>0||e?.includeEmpty)&&n.push(null)}(n.length>0||e?.includeEmpty)&&t.push(n)}return t}function Re(r,e){const t=[...r.rows()];if(t.length===0)return[];const n=t[0].map(u=>{const o=u.value();return o.ok&&o.value!==null?String(o.value):`col_${u.col}`}),l=[];for(let u=1;u<t.length;u++){const o=t[u],a={};let i=!1;for(let c=0;c<n.length;c++){const h=n[c],d=o[c];if(d){const k=ce(d,e);k!==null&&(i=!0),a[h]=k}else a[h]=null}(i||e?.includeEmpty)&&l.push(a)}return l}function oe(r,e){const t=r.usedRange();return t.ok?xe(t.value,e):e?.firstRowAsHeaders?[]:[[]]}function Ue(r,e){const t=r.sheets();if(e?.includeSheetNames!==!1){const s={};for(const n of t)s[n.name]=oe(n,e);return s}return t.map(s=>oe(s,e))}function $e(r,e){const t=e?.delimiter??",",s=e?.lineEnding??`
2
+ `,n=e?.quoteStrings??!0,l=[];for(const u of r.rows()){const o=[];for(const a of u){const i=a.value();let c;!i.ok||i.value===null?c="":i.value instanceof Date?c=i.value.toISOString():c=String(i.value),n&&(c.includes(t)||c.includes(`
3
+ `)||c.includes("\r")||c.includes('"'))&&(c='"'+c.replace(/"/g,'""')+'"'),o.push(c)}l.push(o.join(t))}return l.join(s)}function He(r,e){const t=r.usedRange();return t.ok?$e(t.value,e):""}function Se(r){r.register(ve)}Se(I.globalRegistry);I.registerSpecExecutor("xlsx",(r,e)=>_e(r,e));exports.XlsxCell=T;exports.XlsxCellSB=g;exports.XlsxColSB=pe;exports.XlsxCursor=y;exports.XlsxRange=x;exports.XlsxRangeSB=K;exports.XlsxRowItemSB=me;exports.XlsxRowSB=ge;exports.XlsxSheet=q;exports.XlsxSheetSB=P;exports.XlsxSliceContext=be;exports.XlsxSliceSB=we;exports.XlsxSpecBuilder=ee;exports.XlsxWorkbook=V;exports.cell=Fe;exports.cellToJson=ce;exports.cellValueToJson=Ce;exports.columnLetterToNumber=Q;exports.columnNumberToLetter=ie;exports.compileCellPredicate=R;exports.compileRowPredicate=M;exports.compileSheetPredicate=B;exports.describeCellPredicate=C;exports.describeRowPredicate=L;exports.describeSheetPredicate=N;exports.executeXlsxSpec=_e;exports.fail=w;exports.formatAddress=H;exports.formatRange=ne;exports.formatXlsxPath=Ae;exports.isError=Y;exports.isFormula=X;exports.isInRange=We;exports.ok=f;exports.parseAddress=F;exports.parseRange=U;exports.parseXlsx=De;exports.parseXlsxAsyncImpl=ve;exports.parseXlsxBuffer=Be;exports.parseXlsxFile=Me;exports.parseXlsxImpl=Ne;exports.predicates=Ie;exports.rangeToArray=ye;exports.rangeToCsv=$e;exports.rangeToJson=xe;exports.rangeToObjects=Re;exports.registerXlsxTransforms=Se;exports.rowCol=Ve;exports.sheet=qe;exports.sheetToCsv=He;exports.sheetToJson=oe;exports.streamToBuffer=ke;exports.toExcelLocation=Te;exports.workbookToJson=Ue;
4
4
  //# sourceMappingURL=index.cjs.map