saurus-excel 0.1.0 → 0.1.2

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
@@ -1,82 +1,120 @@
1
- # 🦖 ExcelSaurus
1
+ # 🦖 Saurus-Excel
2
2
 
3
3
  > Blazingly fast Excel parser for the web - powered by Rust & WebAssembly
4
4
 
5
- [![npm version](https://img.shields.io/npm/v/excelsaurus.svg)](https://www.npmjs.com/package/excelsaurus)
5
+ [![npm version](https://img.shields.io/npm/v/saurus-excel.svg)](https://www.npmjs.com/package/saurus-excel)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
7
 
8
- ExcelSaurus is a high-performance Excel file parser designed for handling **large datasets** in the browser. Built with Rust and compiled to WebAssembly, it processes millions of rows without crashing your browser.
8
+ Saurus-Excel is a high-performance Excel file parser designed for handling **large datasets** in the browser. Built with Rust and compiled to WebAssembly, it processes millions of rows without crashing your browser.
9
9
 
10
10
  ## ✨ Features
11
11
 
12
12
  - 🚀 **Blazingly Fast** - 10x faster than SheetJS for large files
13
- - 💾 **Memory Efficient** - Streaming parser uses minimal RAM
13
+ - 💾 **Memory Efficient** - Minimal RAM usage
14
14
  - 📊 **Multiple Formats** - XLSX, XLS, XLSM, XLSB, ODS
15
- - **Schema Validation** - Built-in validators for email, phone, URL
16
- - ⚛️ **Framework Support** - React hooks & Astro components included
15
+ - ⚛️ **Framework Support** - React hooks included
17
16
  - 🔧 **TypeScript First** - Full type definitions
18
17
 
19
18
  ## 📦 Installation
20
19
 
21
20
  ```bash
22
- npm install excelsaurus
21
+ npm install saurus-excel
23
22
  ```
24
23
 
25
- ## 🚀 Quick Start
26
-
27
- ### Basic Usage
28
-
29
- ```typescript
30
- import { parseExcel } from "excelsaurus";
31
-
32
- // Parse from file input
33
- const file = event.target.files[0];
34
- const result = await parseExcel(file);
24
+ ---
35
25
 
36
- console.log(result.headers); // ["Name", "Email", "Age"]
37
- console.log(result.rows); // [["John", "john@example.com", 30], ...]
38
- console.log(result.rowCount); // 100000
26
+ ## 🚀 Usage
27
+
28
+ ### Vanilla JavaScript (Browser)
29
+
30
+ ```html
31
+ <!DOCTYPE html>
32
+ <html>
33
+ <head>
34
+ <title>Excel Parser</title>
35
+ </head>
36
+ <body>
37
+ <input type="file" id="fileInput" accept=".xlsx,.xls" />
38
+ <pre id="output"></pre>
39
+
40
+ <script type="module">
41
+ // Import from pkg folder for direct Wasm access
42
+ import init, { parseExcel } from "saurus-excel/pkg/excelsaurus.js";
43
+
44
+ // Initialize Wasm module (required once)
45
+ await init();
46
+
47
+ document
48
+ .getElementById("fileInput")
49
+ .addEventListener("change", async (e) => {
50
+ const file = e.target.files[0];
51
+ if (!file) return;
52
+
53
+ // Read file as bytes
54
+ const arrayBuffer = await file.arrayBuffer();
55
+ const bytes = new Uint8Array(arrayBuffer);
56
+
57
+ // Parse Excel
58
+ const result = parseExcel(bytes, { hasHeaders: true });
59
+
60
+ console.log(result.headers); // ["Name", "Email", "Age"]
61
+ console.log(result.rows); // [["John", "john@example.com", 30], ...]
62
+
63
+ document.getElementById("output").textContent = JSON.stringify(
64
+ result,
65
+ null,
66
+ 2,
67
+ );
68
+ });
69
+ </script>
70
+ </body>
71
+ </html>
39
72
  ```
40
73
 
41
- ### With Schema Validation
74
+ ### With Bundler (Vite, Webpack, etc.)
42
75
 
43
76
  ```typescript
44
- import { parseExcelWithSchema } from "excelsaurus";
45
-
46
- const result = await parseExcelWithSchema(file, {
47
- fields: [
48
- { name: "name", column: 0, type: "string", required: true },
49
- { name: "email", column: 1, type: "string", validate: "email" },
50
- { name: "age", column: 2, type: "number" },
51
- ],
52
- });
53
-
54
- console.log(result.data);
55
- // [{ name: "John", email: "john@example.com", age: 30 }, ...]
56
- ```
57
-
58
- ### Streaming Large Files
77
+ // Note: Wasm needs special bundler config (see below)
78
+ import init, {
79
+ parseExcel,
80
+ getSheetNames,
81
+ } from "saurus-excel/pkg/excelsaurus.js";
82
+
83
+ // Initialize once at app startup
84
+ let initialized = false;
85
+ async function ensureInit() {
86
+ if (!initialized) {
87
+ await init();
88
+ initialized = true;
89
+ }
90
+ }
59
91
 
60
- ```typescript
61
- import { createExcelStream } from "excelsaurus";
92
+ export async function parseExcelFile(file: File) {
93
+ await ensureInit();
62
94
 
63
- const stream = await createExcelStream(file, {
64
- chunkSize: 1000,
65
- onProgress: (p) => console.log(`${p.percent}%`),
66
- });
95
+ const arrayBuffer = await file.arrayBuffer();
96
+ const bytes = new Uint8Array(arrayBuffer);
67
97
 
68
- for await (const chunk of stream) {
69
- await saveToDatabase(chunk.rows);
98
+ return parseExcel(bytes, {
99
+ hasHeaders: true,
100
+ limit: 1000, // Optional: limit rows
101
+ });
70
102
  }
71
103
  ```
72
104
 
73
- ### React Integration
105
+ ---
106
+
107
+ ## ⚛️ React 19 / Next.js (Plug & Play)
108
+
109
+ ### Quick Start
74
110
 
75
111
  ```tsx
76
- import { useExcelParser } from "excelsaurus/react";
112
+ import { useExcelParser } from "saurus-excel/react";
77
113
 
78
- function ImportComponent() {
79
- const { parse, data, isLoading, progress, error } = useExcelParser();
114
+ function ImportPage() {
115
+ const { parse, data, loading, error, ready } = useExcelParser();
116
+
117
+ if (!ready) return <p>Loading parser...</p>;
80
118
 
81
119
  return (
82
120
  <div>
@@ -85,98 +123,200 @@ function ImportComponent() {
85
123
  accept=".xlsx,.xls"
86
124
  onChange={(e) => e.target.files?.[0] && parse(e.target.files[0])}
87
125
  />
88
- {isLoading && <ProgressBar value={progress} />}
89
- {data && <DataTable rows={data} />}
90
- {error && <Alert>{error.message}</Alert>}
126
+
127
+ {loading && <p>Parsing...</p>}
128
+ {error && <p style={{ color: "red" }}>{error.message}</p>}
129
+
130
+ {data && (
131
+ <table>
132
+ <thead>
133
+ <tr>
134
+ {data.headers.map((h, i) => (
135
+ <th key={i}>{h}</th>
136
+ ))}
137
+ </tr>
138
+ </thead>
139
+ <tbody>
140
+ {data.rows.map((row, i) => (
141
+ <tr key={i}>
142
+ {row.map((cell, j) => (
143
+ <td key={j}>{cell}</td>
144
+ ))}
145
+ </tr>
146
+ ))}
147
+ </tbody>
148
+ </table>
149
+ )}
91
150
  </div>
92
151
  );
93
152
  }
94
153
  ```
95
154
 
96
- ### Astro Integration
155
+ ### With Provider (Recommended for Next.js App Router)
97
156
 
98
- ```astro
99
- ---
100
- // src/pages/import.astro
101
- ---
102
- <excel-importer on-complete="handleData"></excel-importer>
157
+ ```tsx
158
+ // app/providers.tsx
159
+ "use client";
160
+ import { ExcelProvider } from "saurus-excel/react";
161
+
162
+ export function Providers({ children }: { children: React.ReactNode }) {
163
+ return <ExcelProvider>{children}</ExcelProvider>;
164
+ }
103
165
 
104
- <script>
105
- import { ExcelImporter } from 'excelsaurus/astro';
106
- customElements.define('excel-importer', ExcelImporter);
166
+ // app/layout.tsx
167
+ import { Providers } from "./providers";
107
168
 
108
- window.handleData = (result) => {
109
- console.log(result.data);
110
- };
111
- </script>
169
+ export default function RootLayout({ children }) {
170
+ return (
171
+ <html>
172
+ <body>
173
+ <Providers>{children}</Providers>
174
+ </body>
175
+ </html>
176
+ );
177
+ }
112
178
  ```
113
179
 
114
- ### Web Worker (Non-blocking)
180
+ ### Drop-in Component
115
181
 
116
- ```typescript
117
- import { ExcelWorker } from "excelsaurus/worker";
182
+ ```tsx
183
+ import { ExcelDropzone } from "saurus-excel/react";
184
+
185
+ function UploadPage() {
186
+ return (
187
+ <ExcelDropzone
188
+ onData={(result) => {
189
+ console.log("Headers:", result.headers);
190
+ console.log("Rows:", result.rows);
191
+ }}
192
+ onError={(err) => console.error(err)}
193
+ options={{ hasHeaders: true, limit: 1000 }}
194
+ />
195
+ );
196
+ }
197
+ ```
118
198
 
119
- const worker = new ExcelWorker();
199
+ ### Available Hooks
120
200
 
121
- worker.onProgress((p) => updateProgressBar(p.percent));
122
- worker.onComplete((result) => displayData(result));
123
- worker.onError((err) => showError(err));
201
+ | Hook | Description |
202
+ | ------------------ | --------------------------- |
203
+ | `useExcelParser()` | Main hook for parsing files |
204
+ | `useExcelSheets()` | Get sheet names from file |
124
205
 
125
- await worker.parse(file);
206
+ ### Hook Return Values
207
+
208
+ ```tsx
209
+ const {
210
+ parse, // (file: File, options?) => Promise<ParseResult>
211
+ data, // ParseResult | null
212
+ loading, // boolean
213
+ error, // Error | null
214
+ progress, // number (0-100)
215
+ ready, // boolean - Wasm loaded
216
+ reset, // () => void
217
+ } = useExcelParser();
126
218
  ```
127
219
 
128
- ## 📖 API Reference
220
+ ---
129
221
 
130
- ### parseExcel(input, options?)
222
+ ## ⚙️ Bundler Configuration
131
223
 
132
- Parse an Excel file and return raw data.
224
+ ### Vite
225
+
226
+ ```typescript
227
+ // vite.config.ts
228
+ import { defineConfig } from "vite";
229
+
230
+ export default defineConfig({
231
+ optimizeDeps: {
232
+ exclude: ["saurus-excel"],
233
+ },
234
+ build: {
235
+ target: "esnext",
236
+ },
237
+ });
238
+ ```
239
+
240
+ ### Next.js
241
+
242
+ ```javascript
243
+ // next.config.js
244
+ module.exports = {
245
+ webpack: (config) => {
246
+ config.experiments = {
247
+ ...config.experiments,
248
+ asyncWebAssembly: true,
249
+ };
250
+ return config;
251
+ },
252
+ };
253
+ ```
254
+
255
+ ### Webpack 5
256
+
257
+ ```javascript
258
+ // webpack.config.js
259
+ module.exports = {
260
+ experiments: {
261
+ asyncWebAssembly: true,
262
+ },
263
+ };
264
+ ```
133
265
 
134
- | Option | Type | Default | Description |
135
- | ------------ | ------------------ | ----------- | -------------------- |
136
- | `sheet` | `string \| number` | `0` | Sheet name or index |
137
- | `limit` | `number` | `undefined` | Max rows to parse |
138
- | `skipRows` | `number` | `0` | Rows to skip |
139
- | `hasHeaders` | `boolean` | `true` | First row is headers |
266
+ ---
140
267
 
141
- ### parseExcelWithSchema(input, schema, options?)
268
+ ## 📖 API Reference
142
269
 
143
- Parse with schema validation.
270
+ ### parseExcel(bytes, options?)
144
271
 
145
- | Schema Field | Type | Description |
146
- | ------------ | ------------------ | ------------------------------------------------------- |
147
- | `name` | `string` | Output field name |
148
- | `column` | `number \| string` | Column index (0-based) or letter (A, B, C...) |
149
- | `type` | `string` | `string`, `number`, `integer`, `boolean`, `date`, `any` |
150
- | `required` | `boolean` | Is field required? |
151
- | `validate` | `string` | Built-in validator: `email`, `phone`, `url`, `nonempty` |
152
- | `default` | `any` | Default value if empty |
272
+ Parse an Excel file from Uint8Array.
153
273
 
154
- ### createExcelStream(input, options?)
274
+ ```typescript
275
+ const result = parseExcel(bytes, {
276
+ sheet: 0, // Sheet index or name (default: 0)
277
+ limit: 1000, // Max rows to parse (default: all)
278
+ skipRows: 0, // Rows to skip from start
279
+ hasHeaders: true, // Treat first row as headers
280
+ });
281
+ ```
155
282
 
156
- Create async iterator for streaming.
283
+ **Returns:**
157
284
 
158
- | Option | Type | Default | Description |
159
- | ------------ | ---------- | ------- | ----------------- |
160
- | `chunkSize` | `number` | `1000` | Rows per chunk |
161
- | `onProgress` | `function` | - | Progress callback |
285
+ ```typescript
286
+ {
287
+ headers: string[]; // Column headers
288
+ rows: CellValue[][]; // Row data
289
+ rowCount: number; // Total rows parsed
290
+ sheetName: string; // Sheet name
291
+ }
292
+ ```
162
293
 
163
- ### getSheetNames(input)
294
+ ### getSheetNames(bytes)
164
295
 
165
296
  Get list of sheet names in workbook.
166
297
 
298
+ ```typescript
299
+ const sheets = getSheetNames(bytes);
300
+ // ["Sheet1", "Sheet2", "Data"]
301
+ ```
302
+
303
+ ---
304
+
167
305
  ## 🏎 Performance
168
306
 
169
- Benchmarked against SheetJS with 100,000 rows:
307
+ Tested with 100,000 rows:
308
+
309
+ | Metric | SheetJS | Saurus-Excel | Improvement |
310
+ | ------------ | ------- | ------------ | --------------- |
311
+ | Parse Time | ~15s | ~2s | **7.5x faster** |
312
+ | Memory Usage | ~800MB | ~100MB | **8x less** |
313
+ | Bundle Size | ~300KB | ~150KB | **2x smaller** |
170
314
 
171
- | Metric | SheetJS | ExcelSaurus | Improvement |
172
- | ------------ | ------- | ----------- | --------------- |
173
- | Parse Time | ~15s | ~2s | **7.5x faster** |
174
- | Memory Usage | ~800MB | ~100MB | **8x less** |
175
- | Bundle Size | ~300KB | ~150KB | **2x smaller** |
315
+ ---
176
316
 
177
317
  ## 📝 License
178
318
 
179
- MIT ©
319
+ MIT © trietcn
180
320
 
181
321
  ---
182
322
 
package/dist/react.d.ts CHANGED
@@ -1,77 +1,115 @@
1
- import { C as CellValue, P as ParseOptions, S as Schema } from './types-C2-m7DtR.js';
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode } from 'react';
3
+ export { ReactNode } from 'react';
2
4
 
3
- /**
4
- * React integration for ExcelSaurus
5
- */
6
-
7
- interface UseExcelParserState<T = CellValue[][]> {
8
- /** Parsed data */
9
- data: T | null;
10
- /** Whether parsing is in progress */
11
- isLoading: boolean;
12
- /** Parse progress (0-100) */
13
- progress: number;
14
- /** Error if parsing failed */
15
- error: Error | null;
16
- /** Sheet name */
17
- sheetName: string | null;
18
- /** Row count */
5
+ type CellValue = string | number | boolean | null;
6
+ interface ParseResult {
7
+ headers: string[];
8
+ rows: CellValue[][];
19
9
  rowCount: number;
10
+ sheetName: string;
11
+ }
12
+ interface ParseOptions {
13
+ sheet?: string | number;
14
+ limit?: number;
15
+ skipRows?: number;
16
+ hasHeaders?: boolean;
20
17
  }
21
- interface UseExcelParserOptions extends ParseOptions {
22
- /** Schema for typed parsing */
23
- schema?: Schema;
18
+ interface UseExcelParserState {
19
+ data: ParseResult | null;
20
+ loading: boolean;
21
+ error: Error | null;
22
+ progress: number;
24
23
  }
25
- interface UseExcelParserReturn<T = CellValue[][]> extends UseExcelParserState<T> {
26
- /** Parse a file */
27
- parse: (file: File, options?: UseExcelParserOptions) => Promise<void>;
28
- /** Reset state */
24
+ interface UseExcelParserReturn extends UseExcelParserState {
25
+ parse: (file: File, options?: ParseOptions) => Promise<ParseResult>;
29
26
  reset: () => void;
27
+ ready: boolean;
30
28
  }
31
29
  /**
32
- * React hook for parsing Excel files
30
+ * Provider component for Saurus-Excel
31
+ * Wrap your app or component tree with this
33
32
  *
34
33
  * @example
35
34
  * ```tsx
36
- * function ImportComponent() {
37
- * const { parse, data, isLoading, error } = useExcelParser();
35
+ * // app/layout.tsx (Next.js App Router)
36
+ * import { ExcelProvider } from 'saurus-excel/react';
38
37
  *
38
+ * export default function RootLayout({ children }) {
39
39
  * return (
40
- * <input
41
- * type="file"
42
- * onChange={(e) => e.target.files?.[0] && parse(e.target.files[0])}
43
- * />
40
+ * <html>
41
+ * <body>
42
+ * <ExcelProvider>
43
+ * {children}
44
+ * </ExcelProvider>
45
+ * </body>
46
+ * </html>
44
47
  * );
45
48
  * }
46
49
  * ```
47
50
  */
48
- declare function useExcelParser<T extends Record<string, CellValue> = Record<string, CellValue>>(): UseExcelParserReturn<T[] | CellValue[][]>;
51
+ declare function ExcelProvider({ children }: {
52
+ children: ReactNode;
53
+ }): react_jsx_runtime.JSX.Element;
49
54
  /**
50
- * React hook for streaming Excel files
55
+ * Main hook for parsing Excel files
56
+ * Works with or without ExcelProvider
51
57
  *
52
58
  * @example
53
59
  * ```tsx
54
- * function StreamingImport() {
55
- * const { stream, chunks, progress, isStreaming } = useExcelStream();
60
+ * function ImportPage() {
61
+ * const { parse, data, loading, error, ready } = useExcelParser();
62
+ *
63
+ * if (!ready) return <p>Loading parser...</p>;
56
64
  *
57
65
  * return (
58
66
  * <input
59
67
  * type="file"
60
- * onChange={(e) => e.target.files?.[0] && stream(e.target.files[0])}
68
+ * onChange={(e) => e.target.files?.[0] && parse(e.target.files[0])}
61
69
  * />
62
70
  * );
63
71
  * }
64
72
  * ```
65
73
  */
66
- declare function useExcelStream(chunkSize?: number): {
67
- stream: (file: File, options?: ParseOptions) => Promise<void>;
68
- chunks: CellValue[][][];
69
- isStreaming: boolean;
70
- progress: number;
74
+ declare function useExcelParser(defaultOptions?: ParseOptions): UseExcelParserReturn;
75
+ /**
76
+ * Hook to get sheet names from Excel file
77
+ *
78
+ * @example
79
+ * ```tsx
80
+ * const { getSheetNames, sheets, loading } = useExcelSheets();
81
+ *
82
+ * const handleFile = async (file: File) => {
83
+ * const names = await getSheetNames(file);
84
+ * console.log(names); // ["Sheet1", "Sheet2"]
85
+ * };
86
+ * ```
87
+ */
88
+ declare function useExcelSheets(): {
89
+ getSheetNames: (file: File) => Promise<string[]>;
90
+ sheets: string[];
91
+ loading: boolean;
71
92
  error: Error | null;
72
- reset: () => void;
73
- /** All rows flattened */
74
- allRows: CellValue[][];
93
+ ready: boolean;
75
94
  };
95
+ /**
96
+ * Simple drop-in component for file upload
97
+ *
98
+ * @example
99
+ * ```tsx
100
+ * <ExcelDropzone
101
+ * onData={(result) => console.log(result)}
102
+ * onError={(err) => console.error(err)}
103
+ * />
104
+ * ```
105
+ */
106
+ declare function ExcelDropzone({ onData, onError, onProgress, options, className, children, }: {
107
+ onData: (result: ParseResult) => void;
108
+ onError?: (error: Error) => void;
109
+ onProgress?: (percent: number) => void;
110
+ options?: ParseOptions;
111
+ className?: string;
112
+ children?: ReactNode;
113
+ }): react_jsx_runtime.JSX.Element;
76
114
 
77
- export { useExcelParser, useExcelStream };
115
+ export { type CellValue, ExcelDropzone, ExcelProvider, type ParseOptions, type ParseResult, type UseExcelParserReturn, type UseExcelParserState, useExcelParser, useExcelSheets };
package/dist/react.js CHANGED
@@ -1,3 +1,2 @@
1
- import {useState,useRef,useCallback}from'react';var K=Object.defineProperty;var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>{for(var n in e)K(t,n,{get:e[n],enumerable:true});};var H={};L(H,{default:()=>ce,getSheetNames:()=>Q,init:()=>Z,initSync:()=>ie,parseExcel:()=>ee});function Q(t){try{let s=u.__wbindgen_add_to_stack_pointer(-16),a=D(t,u.__wbindgen_export),o=p;u.getSheetNames(s,a,o);var e=f().getInt32(s+0,!0),n=f().getInt32(s+4,!0),r=f().getInt32(s+8,!0);if(r)throw m(n);return m(e)}finally{u.__wbindgen_add_to_stack_pointer(16);}}function Z(){u.init();}function ee(t,e){try{let a=u.__wbindgen_add_to_stack_pointer(-16),o=D(t,u.__wbindgen_export),i=p;u.parseExcel(a,o,i,b(e));var n=f().getInt32(a+0,!0),r=f().getInt32(a+4,!0),s=f().getInt32(a+8,!0);if(s)throw m(r);return m(n)}finally{u.__wbindgen_add_to_stack_pointer(16);}}function $(){return {__proto__:null,"./excelsaurus_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(e,n){let r=Error(U(e,n));return b(r)},__wbg_Number_04624de7d0e8332d:function(e){return Number(c(e))},__wbg_String_8f0eb39a4a4c2f66:function(e,n){let r=String(c(n)),s=O(r,u.__wbindgen_export,u.__wbindgen_export2),a=p;f().setInt32(e+4,a,true),f().setInt32(e+0,s,true);},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(e,n){let r=c(n),s=typeof r=="bigint"?r:void 0;f().setBigInt64(e+8,x(s)?BigInt(0):s,true),f().setInt32(e+0,!x(s),true);},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(e){let n=c(e),r=typeof n=="boolean"?n:void 0;return x(r)?16777215:r?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(e,n){let r=v(c(n)),s=O(r,u.__wbindgen_export,u.__wbindgen_export2),a=p;f().setInt32(e+4,a,true),f().setInt32(e+0,s,true);},__wbg___wbindgen_in_47fa6863be6f2f25:function(e,n){return c(e)in c(n)},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(e){return typeof c(e)=="bigint"},__wbg___wbindgen_is_null_ac34f5003991759a:function(e){return c(e)===null},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(e){let n=c(e);return typeof n=="object"&&n!==null},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(e){return c(e)===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(e,n){return c(e)===c(n)},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(e,n){return c(e)==c(n)},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(e,n){let r=c(n),s=typeof r=="number"?r:void 0;f().setFloat64(e+8,x(s)?0:s,true),f().setInt32(e+0,!x(s),true);},__wbg___wbindgen_string_get_72fb696202c56729:function(e,n){let r=c(n),s=typeof r=="string"?r:void 0;var a=x(s)?0:O(s,u.__wbindgen_export,u.__wbindgen_export2),o=p;f().setInt32(e+4,o,true),f().setInt32(e+0,a,true);},__wbg___wbindgen_throw_be289d5034ed271b:function(e,n){throw new Error(U(e,n))},__wbg_error_7534b8e9a36f1ab4:function(e,n){let r,s;try{r=e,s=n,console.error(U(e,n));}finally{u.__wbindgen_export3(r,s,1);}},__wbg_get_with_ref_key_1dc361bd10053bfe:function(e,n){let r=c(e)[c(n)];return b(r)},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(e){let n;try{n=c(e)instanceof ArrayBuffer;}catch{n=false;}return n},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(e){let n;try{n=c(e)instanceof Uint8Array;}catch{n=false;}return n},__wbg_isSafeInteger_bfbc7332a9768d2a:function(e){return Number.isSafeInteger(c(e))},__wbg_length_32ed9a279acd054c:function(e){return c(e).length},__wbg_new_361308b2356cecd0:function(){let e=new Object;return b(e)},__wbg_new_3eb36ae241fe6f44:function(){let e=new Array;return b(e)},__wbg_new_8a6f238a6ece86ea:function(){let e=new Error;return b(e)},__wbg_new_dd2b680c8bf6ae29:function(e){let n=new Uint8Array(c(e));return b(n)},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(e,n,r){Uint8Array.prototype.set.call(ne(e,n),c(r));},__wbg_set_3f1d0b984ed272ed:function(e,n,r){c(e)[m(n)]=m(r);},__wbg_set_f43e577aea94465b:function(e,n,r){c(e)[n>>>0]=m(r);},__wbg_stack_0ed75d68575b0f3c:function(e,n){let r=c(n).stack,s=O(r,u.__wbindgen_export,u.__wbindgen_export2),a=p;f().setInt32(e+4,a,true),f().setInt32(e+0,s,true);},__wbindgen_cast_0000000000000001:function(e){return b(e)},__wbindgen_cast_0000000000000002:function(e,n){let r=U(e,n);return b(r)},__wbindgen_cast_0000000000000003:function(e){let n=BigInt.asUintN(64,e);return b(n)},__wbindgen_object_clone_ref:function(e){let n=c(e);return b(n)},__wbindgen_object_drop_ref:function(e){m(e);}}}}function b(t){E===w.length&&w.push(w.length+1);let e=E;return E=w[e],w[e]=t,e}function v(t){let e=typeof t;if(e=="number"||e=="boolean"||t==null)return `${t}`;if(e=="string")return `"${t}"`;if(e=="symbol"){let s=t.description;return s==null?"Symbol":`Symbol(${s})`}if(e=="function"){let s=t.name;return typeof s=="string"&&s.length>0?`Function(${s})`:"Function"}if(Array.isArray(t)){let s=t.length,a="[";s>0&&(a+=v(t[0]));for(let o=1;o<s;o++)a+=", "+v(t[o]);return a+="]",a}let n=/\[object ([^\]]+)\]/.exec(toString.call(t)),r;if(n&&n.length>1)r=n[1];else return toString.call(t);if(r=="Object")try{return "Object("+JSON.stringify(t)+")"}catch{return "Object"}return t instanceof Error?`${t.name}: ${t.message}
2
- ${t.stack}`:r}function te(t){t<132||(w[t]=E,E=t);}function ne(t,e){return t=t>>>0,S().subarray(t/1,t/1+e)}function f(){return (h===null||h.buffer.detached===true||h.buffer.detached===void 0&&h.buffer!==u.memory.buffer)&&(h=new DataView(u.memory.buffer)),h}function U(t,e){return t=t>>>0,se(t,e)}function S(){return (P===null||P.byteLength===0)&&(P=new Uint8Array(u.memory.buffer)),P}function c(t){return w[t]}function x(t){return t==null}function D(t,e){let n=e(t.length*1,1)>>>0;return S().set(t,n/1),p=t.length,n}function O(t,e,n){if(n===void 0){let i=R.encode(t),_=e(i.length,1)>>>0;return S().subarray(_,_+i.length).set(i),p=i.length,_}let r=t.length,s=e(r,1)>>>0,a=S(),o=0;for(;o<r;o++){let i=t.charCodeAt(o);if(i>127)break;a[s+o]=i;}if(o!==r){o!==0&&(t=t.slice(o)),s=n(s,r,r=o+t.length*3,1)>>>0;let i=S().subarray(s+o,s+r),_=R.encodeInto(t,i);o+=_.written,s=n(s,r,o,1)>>>0;}return p=o,s}function m(t){let e=c(t);return te(t),e}function se(t,e){return W+=e,W>=re&&(T=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true}),T.decode(),W=e),T.decode(S().subarray(t,t+e))}function q(t,e){return u=t.exports,h=null,P=null,u.__wbindgen_start(),u}async function ae(t,e){if(typeof Response=="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(s){if(t.ok&&n(t.type)&&t.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",s);else throw s}let r=await t.arrayBuffer();return await WebAssembly.instantiate(r,e)}else {let r=await WebAssembly.instantiate(t,e);return r instanceof WebAssembly.Instance?{instance:r,module:t}:r}function n(r){switch(r){case "basic":case "cors":case "default":return true}return false}}function ie(t){if(u!==void 0)return u;t!==void 0&&(Object.getPrototypeOf(t)===Object.prototype?{module:t}=t:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let e=$();t instanceof WebAssembly.Module||(t=new WebAssembly.Module(t));let n=new WebAssembly.Instance(t,e);return q(n)}async function ce(t){if(u!==void 0)return u;t!==void 0&&(Object.getPrototypeOf(t)===Object.prototype?{module_or_path:t}=t:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),t===void 0&&(t=new URL("excelsaurus_bg.wasm",import.meta.url));let e=$();(typeof t=="string"||typeof Request=="function"&&t instanceof Request||typeof URL=="function"&&t instanceof URL)&&(t=fetch(t));let{instance:n,module:r}=await ae(await t,e);return q(n)}var h,P,w,E,T,re,W,R,p,u,z=N(()=>{h=null;P=null;w=new Array(128).fill(void 0);w.push(void 0,null,true,false);E=w.length;T=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});T.decode();re=2146435072,W=0;R=new TextEncoder;"encodeInto"in R||(R.encodeInto=function(t,e){let n=R.encode(t);return e.set(n),{read:t.length,written:n.length}});p=0;});async function ue(){V||(M||(M=(async()=>{let t=await Promise.resolve().then(()=>(z(),H));await t.default(),V=t;})()),await M);}async function le(){if(await ue(),!V)throw new Error("Failed to initialize ExcelSaurus Wasm module");return V}async function C(t,e={}){let n=await le(),r=await fe(t);return n.parseExcel(r,{sheet:e.sheet?.toString(),limit:e.limit,skipRows:e.skipRows,hasHeaders:e.hasHeaders})}async function J(t,e,n={}){let r=await C(t,n),s=[],a=[];for(let o=0;o<r.rows.length;o++){let i=r.rows[o],_={},g=[];for(let l of e.fields){let A=typeof l.column=="number"?l.column:_e(l.column),d=i[A]??null;if((d===null||d==="")&&l.default!==void 0&&(d=l.default),l.required&&(d===null||d==="")){g.push({field:l.name,message:"Field is required"});continue}if(d!==null&&d!==""&&(de(d,l.type)||g.push({field:l.name,message:`Expected ${l.type}, got ${typeof d}`,value:String(d)}),l.validate)){let k=be(l.validate,d);k&&g.push({field:l.name,message:k,value:String(d)});}_[l.name]=d;}g.length>0&&(a.push({valid:false,rowIndex:o,errors:g}),!e.skipInvalid)||s.push(_);}return {data:s,errors:a.length>0?a:void 0,rowCount:s.length,sheetName:r.sheetName}}async function fe(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);let e=await t.arrayBuffer();return new Uint8Array(e)}function _e(t){let e=t.toUpperCase(),n=0;for(let r=0;r<e.length;r++)n=n*26+(e.charCodeAt(r)-64);return n-1}function de(t,e){if(e==="any")return true;switch(e){case "string":return typeof t=="string"||typeof t=="number";case "number":case "integer":return typeof t=="number";case "boolean":return typeof t=="boolean";case "date":case "datetime":return typeof t=="string";default:return true}}function be(t,e){let n=String(e);switch(t.toLowerCase()){case "email":return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)?null:"Invalid email format";case "phone":return /^\+?[0-9\s\-()]{7,20}$/.test(n)?null:"Invalid phone number";case "url":return /^https?:\/\/[^\s]+$/.test(n)?null:"Invalid URL";case "nonempty":return n.trim()!==""?null:"Value cannot be empty";default:return null}}var V,M,B=N(()=>{V=null,M=null;});var X={};L(X,{collectStream:()=>we,createExcelStream:()=>ge});async function ge(t,e={}){let n=e.chunkSize??1e3,r=await C(t,{sheet:e.sheet,skipRows:e.skipRows,hasHeaders:e.hasHeaders}),s=r.rows.length,a=Math.ceil(s/n);return {[Symbol.asyncIterator](){let o=0,i=0;return {async next(){if(o>=a)return {done:true,value:void 0};let _=o*n,g=Math.min(_+n,s),l=r.rows.slice(_,g);i+=l.length;let A=o===a-1;if(e.onProgress){let y={rowsProcessed:i,totalRows:s,percent:Math.round(i/s*100),chunkNumber:o+1};e.onProgress(y);}let d={rows:l,chunkIndex:o,isLast:A};return o++,{done:false,value:d}}}}}}async function we(t){let e=[];for await(let n of t)e.push(...n.rows);return e}var Y=N(()=>{B();});B();function Ae(){let[t,e]=useState({data:null,isLoading:false,progress:0,error:null,sheetName:null,rowCount:0}),n=useRef(null),r=useCallback(async(a,o={})=>{n.current?.abort(),n.current=new AbortController,e(i=>({...i,isLoading:true,error:null,progress:0}));try{let i;o.schema?(i=await J(a,o.schema,o),e({data:i.data,isLoading:!1,progress:100,error:null,sheetName:i.sheetName,rowCount:i.rowCount})):(i=await C(a,o),e({data:i.rows,isLoading:!1,progress:100,error:null,sheetName:i.sheetName,rowCount:i.rowCount}));}catch(i){e(_=>({..._,isLoading:false,error:i instanceof Error?i:new Error(String(i))}));}},[]),s=useCallback(()=>{n.current?.abort(),e({data:null,isLoading:false,progress:0,error:null,sheetName:null,rowCount:0});},[]);return {...t,parse:r,reset:s}}function Pe(t=1e3){let[e,n]=useState([]),[r,s]=useState(false),[a,o]=useState(0),[i,_]=useState(null),g=useCallback(async(A,d={})=>{s(true),n([]),o(0),_(null);try{let{createExcelStream:y}=await Promise.resolve().then(()=>(Y(),X)),k=await y(A,{...d,chunkSize:t,onProgress:F=>o(F.percent)});for await(let F of k)n(G=>[...G,F.rows]);}catch(y){_(y instanceof Error?y:new Error(String(y)));}finally{s(false),o(100);}},[t]),l=useCallback(()=>{n([]),o(0),_(null),s(false);},[]);return {stream:g,chunks:e,isStreaming:r,progress:a,error:i,reset:l,allRows:e.flat()}}export{Ae as useExcelParser,Pe as useExcelStream};//# sourceMappingURL=react.js.map
1
+ import {createContext,useState,useEffect,useMemo,useCallback,useContext}from'react';import {jsx,jsxs}from'react/jsx-runtime';var u=null,h=null,E=null;async function P(){if(u)return u;if(h)return h;if(typeof window>"u")throw new Error("Saurus-Excel requires browser environment");return h=(async()=>{try{let e=await import('../pkg/excelsaurus.js');return await e.default(),u=e,e}catch(e){throw E=e instanceof Error?e:new Error(String(e)),E}})(),h}var b=createContext(null);function A({children:e}){let[t,c]=useState(false),[r,o]=useState(null);useEffect(()=>{P().then(()=>c(true)).catch(s=>o(s));},[]);let g=useMemo(()=>({ready:t,error:r,parseExcel:(s,m)=>{if(!u)throw new Error("Wasm not initialized");return u.parseExcel(s,m||{})},getSheetNames:s=>{if(!u)throw new Error("Wasm not initialized");return u.getSheetNames(s)}}),[t,r]);return jsx(b.Provider,{value:g,children:e})}function v(){let e=useContext(b),[t,c]=useState(null);return useEffect(()=>{e||P().then(()=>{c({ready:true,error:null,parseExcel:(r,o)=>u.parseExcel(r,o||{}),getSheetNames:r=>u.getSheetNames(r)});}).catch(r=>{c({ready:false,error:r,parseExcel:()=>{throw r},getSheetNames:()=>{throw r}});});},[e]),e||t||{ready:false,error:null,parseExcel:()=>{throw new Error("Initializing...")},getSheetNames:()=>{throw new Error("Initializing...")}}}function U(e){let t=v(),[c,r]=useState({data:null,loading:false,error:null,progress:0}),o=useCallback(async(s,m)=>{if(!t.ready)throw new Error("Parser not ready. Wait for ready=true or wrap with ExcelProvider");r(l=>({...l,loading:true,error:null,progress:0}));try{r(d=>({...d,progress:30}));let l=await s.arrayBuffer(),a=new Uint8Array(l);r(d=>({...d,progress:60}));let n=t.parseExcel(a,{...e,...m});return r({data:n,loading:!1,error:null,progress:100}),n}catch(l){let a=l instanceof Error?l:new Error(String(l));throw r(n=>({...n,loading:false,error:a,progress:0})),a}},[t,e]),g=useCallback(()=>{r({data:null,loading:false,error:null,progress:0});},[]);return {...c,parse:o,reset:g,ready:t.ready}}function V(){let e=v(),[t,c]=useState([]),[r,o]=useState(false),[g,s]=useState(null);return {getSheetNames:useCallback(async l=>{if(!e.ready)throw new Error("Parser not ready");o(true),s(null);try{let a=new Uint8Array(await l.arrayBuffer()),n=e.getSheetNames(a);return c(n),n}catch(a){let n=a instanceof Error?a:new Error(String(a));throw s(n),n}finally{o(false);}},[e]),sheets:t,loading:r,error:g,ready:e.ready}}function k({onData:e,onError:t,onProgress:c,options:r,className:o,children:g}){let{parse:s,loading:m,ready:l}=U(r),[a,n]=useState(false),d=useCallback(async p=>{try{let i=await s(p);e(i);}catch(i){t?.(i instanceof Error?i:new Error(String(i)));}},[s,e,t]),S=useCallback(p=>{p.preventDefault(),n(false);let i=p.dataTransfer.files[0];i&&d(i);},[d]),C=useCallback(p=>{let i=p.target.files?.[0];i&&d(i);},[d]);return l?jsxs("div",{className:o,onDragOver:p=>{p.preventDefault(),n(true);},onDragLeave:()=>n(false),onDrop:S,style:{border:a?"2px dashed #4f46e5":"2px dashed #d1d5db",borderRadius:"8px",padding:"40px",textAlign:"center",cursor:"pointer",transition:"border-color 0.2s"},onClick:()=>document.getElementById("excel-input")?.click(),children:[jsx("input",{id:"excel-input",type:"file",accept:".xlsx,.xls,.xlsm,.xlsb,.ods",onChange:C,style:{display:"none"}}),g||(m?jsx("p",{children:"Parsing..."}):jsx("p",{children:"Drop Excel file here or click to upload"}))]}):jsx("div",{className:o,children:"Loading parser..."})}export{k as ExcelDropzone,A as ExcelProvider,U as useExcelParser,V as useExcelSheets};//# sourceMappingURL=react.js.map
3
2
  //# sourceMappingURL=react.js.map