UNPKG

@sheetxl/io

Version:

IO - Import/Export Libraries for SheetXL.

366 lines (365 loc) 17.7 kB
import { BufferUtils as L } from "@sheetxl/utils"; import { TextUtils as b } from "@sheetxl/sdk"; /** * @license @sheetxl/io - IO - Import/Export Libraries for SheetXL. - v0.7.27 * * (C) 2025-present SheetXL Inc. & Michael T. Ford * License: The license can be found at https://www.sheetxl.com/license. */ const _ = [{ key: "SheetXL", description: "SheetXL", mimeType: ".sxl", exts: ["sxl", "json"], isDefault: !0, handler: async (d, e) => (await import("./BerSIof5c2BKSkz9.mjs")).readBufferSXL(d, e) }, { key: "CSV", description: "Comma Delimited", mimeType: "text/csv", exts: ["csv"], handler: async (d, e) => (await import("./DsgiMjex6asoHRSD.mjs")).readBufferCSV(d, e) }, { key: "Excel", description: "Excel Workbook", mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", exts: ["xlsx", "xls", "xlsm"], handler: async (d, e) => (await import("./CIFJlX69I7tu96JE.mjs").then((n) => n.H)).readBufferXLSX(d, e) }], F = [{ key: "SheetXL", mimeType: "application/vnd.sheetxl.sheet", description: "SheetXL", exts: ["sxl", "json"], isDefault: !0, async handler(d, e) { return e?.format === "json" && (e = { compress: !1, ...e }), (await import("./BerSIof5c2BKSkz9.mjs")).writeBufferSXL(d, e); } }, { key: "CSV", mimeType: "text/csv", description: "Comma Delimited", exts: ["csv"], handler: async (d, e) => (await import("./DsgiMjex6asoHRSD.mjs")).writeBufferCSV(d, e) }, { key: "Excel", mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", description: "Excel Workbook", exts: ["xlsx"], tags: ["SheetJS Pro"], handler: async (d, e) => (await import("./CIFJlX69I7tu96JE.mjs").then((n) => n.H)).writeBufferXLSX(d, e) }], W = async (d, e) => { let n; typeof SharedArrayBuffer < "u" && e instanceof SharedArrayBuffer ? (n = new ArrayBuffer(e.byteLength), new Uint8Array(n).set(new Uint8Array(e))) : n = e, (function(t, r) { const o = URL.createObjectURL(t), a = document.createElement("a"); a.style.display = "none", a.href = o, a.download = r, document.body.appendChild(a), a.click(), document.body.removeChild(a), URL.revokeObjectURL(o); })(new Blob([n], { type: "application/octet-stream" }), d); }; class B { constructor(e = _, n = F) { this._readFormats = [], this._writeFormats = [], this._readFormats = Object.freeze([...e]), this._writeFormats = Object.freeze([...n]); } async getReadFormats(e) { return e ? this._filterFormats(e, this._readFormats) : [...this._readFormats]; } async getWriteFormats(e) { return this._writeFormats ? e ? this._filterFormats(e, this._writeFormats) : [...this._writeFormats] : []; } async writeArrayBuffer(e, n) { const t = (await this.getWriteFormats({ search: n?.format ?? "slx" }))[0]; return this._writeArrayBuffer(e, t, n); } async read(e) { if (!e) throw new Error("'options' must be provided for read."); let n = e.source; if (!n) throw new Error("'options.source' must be provided for read."); let t, r = e.name, o = e.format; !o && r && (t = b.getFileNameExtension(r)), typeof n == "function" && (n = n()), n && typeof n == "object" && typeof n.then == "function" && (n = await Promise.resolve(n)); const a = this._detectImportSourceType(n); if (!a) throw new Error("Unable to detect source type from provided input."); const s = this, i = async (f, u, l) => { if (!f && !u) throw new Error("Either format or file extension must be provided to determine read type."); const h = (await s.getReadFormats({ search: f, ext: u }))[0]; if (!h) throw new Error(`No read format available for '${e.format ?? u}' input.`); delete (e = { ...e, ...e?.typedCreateWorkbookOptions?.[h.key] }).typedCreateWorkbookOptions; const m = r ?? l ?? `read-${a}`; e.createWorkbookOptions = { ...e.createWorkbookOptions || {}, name: m }, e.readonly !== void 0 && (e.createWorkbookOptions = { readonly: e.readonly, ...e.createWorkbookOptions }, delete e.readonly); const w = e?.progress?.onStart; return w && await Promise.resolve(w({ format: h, name: m })), h; }, c = async (f, u, l) => { const h = await Promise.resolve(f), m = await this._readArrayBuffer(h, u, l); return l?.progress?.onComplete?.(), m; }; switch (a) { case "file": { const f = n, u = f?.name; let l = ""; u && (l = `${b.getBaseName(u)}`); const h = await i(o, b.getFileNameExtension(u), l); return c(f.arrayBuffer(), h, e); } case "blob": { const f = await i(o, t); return c(n.arrayBuffer(), f, e); } case "base64": { const f = await i(o, t); let u; if (n && typeof n == "object" && "base64" in n) u = n.base64; else if (typeof n == "string" && n.startsWith("data:")) { const [, l] = n.split(","); u = l; } else u = n; return c(L.base64ToArrayBuffer(u), f, e); } case "fetch": { let f, u, l = null; if (typeof n == "string") l = n; else { if (!n || typeof n != "object" || !("input" in n)) throw new Error("Invalid fetch source provided."); { const p = n; l = p.input, f = p.init, u = p.timeout; } } const h = u || 3e4, m = new AbortController(), w = setTimeout(() => m.abort(), h), y = typeof l == "string" ? l : l.toString(), g = t || b.getFileNameExtension(y), v = await i(o, g, b.getBaseName(y, !0)); try { const p = await fetch(l, { ...f, signal: m.signal }); if (clearTimeout(w), !p.ok) throw new Error(`Failed to fetch: ${p.status} ${p.statusText}`); const E = await p.arrayBuffer(); if (!E) throw new Error(`Unable to fetched content: ${y}`); return c(E, v, e); } catch (p) { throw clearTimeout(w), p.name === "AbortError" ? new Error(`Fetch timeout after ${h}ms: ${y}`) : p; } } case "buffer": return c(n, await i(o, t), e); case "stream": { const f = await i(o, t), u = n.getReader(), l = []; let h = 0; try { for (; ; ) { const { done: g, value: v } = await u.read(); if (g) break; l.push(v), h += v.length; } } finally { u.releaseLock(); } const m = new ArrayBuffer(h), w = new Uint8Array(m); let y = 0; for (const g of l) w.set(g, y), y += g.length; return c(m, f, e); } default: throw new Error(`Unsupported source type: ${a}`); } } async writeFile(e, n, t) { if (!e) throw new Error("File name must be provided."); if (!n) throw new Error("Workbook must be provided."); if (!n.isIWorkbook) throw new Error("Invalid workbook model provided. Must be an instance of IWorkbook."); const r = b.getFileNameExtension(e).toLowerCase(); r && (e = e.slice(0, e.length - r.length - 1)); const o = (await this.getWriteFormats({ search: t?.format, ext: r }))[0]; if (!o) throw new Error(`Unable to determine write type for '${e}'.`); const a = e + "." + (r || o.exts[0]); let s = null; try { s = await this._writeArrayBuffer(n, o, t); } catch (i) { throw typeof i == "string" ? new Error(i) : i; } try { await W(a, s); } catch (i) { throw new Error("Unable to write file.", { cause: i }); } return t?.progress?.onComplete?.(), !0; } async registerReadFormat(e) { this._registerFormatType(e, this._readFormats); } async registerWriteFormat(e) { this._registerFormatType(e, this._writeFormats); } async _registerFormatType(e, n) { if (!e) throw new Error("format must be provided."); } _detectImportSourceType(e) { return e && typeof e == "object" && "base64" in e ? "base64" : e && typeof e == "object" && "input" in e ? "fetch" : typeof e == "string" ? e.startsWith("data:") ? "base64" : (e.startsWith("http://") || e.startsWith("https://") || e.startsWith("/") || e.startsWith("./") || e.startsWith("../"), "fetch") : typeof File < "u" && e instanceof File ? "file" : typeof Blob < "u" && e instanceof Blob ? "blob" : e instanceof ArrayBuffer || ArrayBuffer.isView(e) ? "buffer" : typeof ReadableStream < "u" && e instanceof ReadableStream ? "stream" : null; } _filterFormats(e, n, t) { if (!e || Object.keys(e).length === 0) { if (!t) return [...n]; e = { ext: t }; } const r = e.search?.toLocaleLowerCase(); return n.filter((o) => { if (r) { const s = o.key.toLocaleLowerCase().includes(r), i = !!o.exts && o.exts.some((l) => l.toLocaleLowerCase().includes(r)), c = !!o.mimeType && o.mimeType.toLocaleLowerCase().includes(r), f = !!o.tags && o.tags.some((l) => l.toLocaleLowerCase().includes(r)), u = !!o.description && o.description.toLocaleLowerCase().includes(r); if (!(s || i || c || f || u)) return !1; } const a = e.ext || t; if (a) { const s = a.toLocaleLowerCase(); if (!o.exts.some((i) => i.toLocaleLowerCase() === s)) return !1; } if (e.mimeType && o.mimeType !== e.mimeType || e.key && o.key.toLocaleLowerCase() !== e.key.toLocaleLowerCase() || e.isDefault !== void 0 && o.isDefault !== e.isDefault) return !1; if (e.tags) { const s = o.tags || []; if (!(typeof e.tags == "string" ? [e.tags] : e.tags).every((i) => s.includes(i))) return !1; } return !0; }); } async _writeArrayBuffer(e, n, t) { if (!n) throw new Error(`Invalid write type for '${n}'.`); try { const r = n.handler; if (!r) throw new Error(`Unable to resolve handler for type: ${n.description ?? n}.`); return r(e, t); } catch (r) { throw new Error(`Unable to load handler for '${n}.'`, { cause: r }); } } async _readArrayBuffer(e, n, t = null) { if (!e) throw new Error("ArrayBuffer must be specified."); if (!n) throw new Error("format must be specified."); const r = n.handler; if (!r) throw new Error(`Unable to resolve handler for format type: ${n?.description ?? n}.`); let o; try { o = await r(e, t); } catch (a) { throw new Error("Unable to read", { cause: a }); } return o; } } const R = new B(); var k, x, S = (function() { if (x) return k; function d(t) { if (typeof t != "string") throw new TypeError("Path must be a string. Received " + JSON.stringify(t)); } function e(t, r) { for (var o, a = "", s = 0, i = -1, c = 0, f = 0; f <= t.length; ++f) { if (f < t.length) o = t.charCodeAt(f); else { if (o === 47) break; o = 47; } if (o === 47) { if (!(i === f - 1 || c === 1)) if (i !== f - 1 && c === 2) { if (a.length < 2 || s !== 2 || a.charCodeAt(a.length - 1) !== 46 || a.charCodeAt(a.length - 2) !== 46) { if (a.length > 2) { var u = a.lastIndexOf("/"); if (u !== a.length - 1) { u === -1 ? (a = "", s = 0) : s = (a = a.slice(0, u)).length - 1 - a.lastIndexOf("/"), i = f, c = 0; continue; } } else if (a.length === 2 || a.length === 1) { a = "", s = 0, i = f, c = 0; continue; } } r && (a.length > 0 ? a += "/.." : a = "..", s = 2); } else a.length > 0 ? a += "/" + t.slice(i + 1, f) : a = t.slice(i + 1, f), s = f - i - 1; i = f, c = 0; } else o === 46 && c !== -1 ? ++c : c = -1; } return a; } x = 1; var n = { resolve: function() { for (var t, r = "", o = !1, a = arguments.length - 1; a >= -1 && !o; a--) { var s; a >= 0 ? s = arguments[a] : (t === void 0 && (t = process.cwd()), s = t), d(s), s.length !== 0 && (r = s + "/" + r, o = s.charCodeAt(0) === 47); } return r = e(r, !o), o ? r.length > 0 ? "/" + r : "/" : r.length > 0 ? r : "."; }, normalize: function(t) { if (d(t), t.length === 0) return "."; var r = t.charCodeAt(0) === 47, o = t.charCodeAt(t.length - 1) === 47; return (t = e(t, !r)).length !== 0 || r || (t = "."), t.length > 0 && o && (t += "/"), r ? "/" + t : t; }, isAbsolute: function(t) { return d(t), t.length > 0 && t.charCodeAt(0) === 47; }, join: function() { if (arguments.length === 0) return "."; for (var t, r = 0; r < arguments.length; ++r) { var o = arguments[r]; d(o), o.length > 0 && (t === void 0 ? t = o : t += "/" + o); } return t === void 0 ? "." : n.normalize(t); }, relative: function(t, r) { if (d(t), d(r), t === r || (t = n.resolve(t)) === (r = n.resolve(r))) return ""; for (var o = 1; o < t.length && t.charCodeAt(o) === 47; ++o) ; for (var a = t.length, s = a - o, i = 1; i < r.length && r.charCodeAt(i) === 47; ++i) ; for (var c = r.length - i, f = s < c ? s : c, u = -1, l = 0; l <= f; ++l) { if (l === f) { if (c > f) { if (r.charCodeAt(i + l) === 47) return r.slice(i + l + 1); if (l === 0) return r.slice(i + l); } else s > f && (t.charCodeAt(o + l) === 47 ? u = l : l === 0 && (u = 0)); break; } var h = t.charCodeAt(o + l); if (h !== r.charCodeAt(i + l)) break; h === 47 && (u = l); } var m = ""; for (l = o + u + 1; l <= a; ++l) l !== a && t.charCodeAt(l) !== 47 || (m.length === 0 ? m += ".." : m += "/.."); return m.length > 0 ? m + r.slice(i + u) : (i += u, r.charCodeAt(i) === 47 && ++i, r.slice(i)); }, _makeLong: function(t) { return t; }, dirname: function(t) { if (d(t), t.length === 0) return "."; for (var r = t.charCodeAt(0), o = r === 47, a = -1, s = !0, i = t.length - 1; i >= 1; --i) if ((r = t.charCodeAt(i)) === 47) { if (!s) { a = i; break; } } else s = !1; return a === -1 ? o ? "/" : "." : o && a === 1 ? "//" : t.slice(0, a); }, basename: function(t, r) { if (r !== void 0 && typeof r != "string") throw new TypeError('"ext" argument must be a string'); d(t); var o, a = 0, s = -1, i = !0; if (r !== void 0 && r.length > 0 && r.length <= t.length) { if (r.length === t.length && r === t) return ""; var c = r.length - 1, f = -1; for (o = t.length - 1; o >= 0; --o) { var u = t.charCodeAt(o); if (u === 47) { if (!i) { a = o + 1; break; } } else f === -1 && (i = !1, f = o + 1), c >= 0 && (u === r.charCodeAt(c) ? --c === -1 && (s = o) : (c = -1, s = f)); } return a === s ? s = f : s === -1 && (s = t.length), t.slice(a, s); } for (o = t.length - 1; o >= 0; --o) if (t.charCodeAt(o) === 47) { if (!i) { a = o + 1; break; } } else s === -1 && (i = !1, s = o + 1); return s === -1 ? "" : t.slice(a, s); }, extname: function(t) { d(t); for (var r = -1, o = 0, a = -1, s = !0, i = 0, c = t.length - 1; c >= 0; --c) { var f = t.charCodeAt(c); if (f !== 47) a === -1 && (s = !1, a = c + 1), f === 46 ? r === -1 ? r = c : i !== 1 && (i = 1) : r !== -1 && (i = -1); else if (!s) { o = c + 1; break; } } return r === -1 || a === -1 || i === 0 || i === 1 && r === a - 1 && r === o + 1 ? "" : t.slice(r, a); }, format: function(t) { if (t === null || typeof t != "object") throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof t); return (function(r, o) { var a = o.dir || o.root, s = o.base || (o.name || "") + (o.ext || ""); return a ? a === o.root ? a + s : a + r + s : s; })("/", t); }, parse: function(t) { d(t); var r = { root: "", dir: "", base: "", ext: "", name: "" }; if (t.length === 0) return r; var o, a = t.charCodeAt(0), s = a === 47; s ? (r.root = "/", o = 1) : o = 0; for (var i = -1, c = 0, f = -1, u = !0, l = t.length - 1, h = 0; l >= o; --l) if ((a = t.charCodeAt(l)) !== 47) f === -1 && (u = !1, f = l + 1), a === 46 ? i === -1 ? i = l : h !== 1 && (h = 1) : i !== -1 && (h = -1); else if (!u) { c = l + 1; break; } return i === -1 || f === -1 || h === 0 || h === 1 && i === f - 1 && i === c + 1 ? f !== -1 && (r.base = r.name = c === 0 && s ? t.slice(1, f) : t.slice(c, f)) : (c === 0 && s ? (r.name = t.slice(1, i), r.base = t.slice(1, f)) : (r.name = t.slice(c, i), r.base = t.slice(c, f)), r.ext = t.slice(i, f)), c > 0 ? r.dir = t.slice(0, c - 1) : s && (r.dir = "/"), r; }, sep: "/", delimiter: ":", win32: null, posix: null }; return n.posix = n, k = n; })(); const A = /^(con|prn|aux|nul|com\d|lpt\d)$/i, C = /[<>:"/\\|?*\u0000-\u001F]/g, U = Object.freeze(Object.defineProperty({ __proto__: null, MAX_WORKBOOK_NAME_SIZE: 96, WINDOW_FILENAME_CHAR_RESERVED_REGEX: C, WINDOW_FILENAME_RESERVED_REGEX: A, isValidWindowsFilename: (d) => !(!d || d.length > 255) && !C.test(d) && !A.test(d) && d !== "." && d !== "..", relativePath: (d, e) => { try { return new URL(e), e; } catch { } if (e.startsWith("/") || /^[a-zA-Z]:/.test(e)) return e; if (typeof window > "u" || window.document === void 0) { if (typeof require < "u" && typeof process < "u") return S.Path.resolve(d, e); throw new Error("Unsupported environment"); } try { let n = d.startsWith("http") ? d : `file:///${d.replace(/\\/g, "/")}`; return n.endsWith("/") || (n += "/"), new URL(e, n).href; } catch { const n = document.createElement("a"); let t = d; return t.endsWith("/") || (t += "/"), n.href = new URL(e, t).href, n.href; } } }, Symbol.toStringTag, { value: "Module" })); export { B as DefaultWorkbookIO, U as IOUtils, R as WorkbookIO };