@20baht/export 0.0.0-stage → 0.1.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) 2026 Nattapong Promthong
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 CHANGED
@@ -1,3 +1,125 @@
1
- # Temporary Holding Version
1
+ # @20baht/export
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Rows as a file someone opens in Excel or Google Sheets: a CSV, or an .xlsx workbook. Thai comes out as Thai,
4
+ a cell that looks like a formula is never run, and dates and amounts keep their meaning. It works on a server or in
5
+ a browser, and has no dependencies.
6
+
7
+ ```bash
8
+ bun add @20baht/export
9
+ ```
10
+
11
+ ## A sheet
12
+
13
+ Both formats read the same sheet: the columns (a header, and how a cell is read from a row) and the rows.
14
+
15
+ ```ts
16
+ import { csv, xlsx, type Sheet } from '@20baht/export';
17
+
18
+ interface Expense {
19
+ date: Date;
20
+ note: string;
21
+ amount: number;
22
+ account: { name: string };
23
+ }
24
+
25
+ const sheet: Sheet<Expense> = {
26
+ name: 'November', // the tab's name in a workbook
27
+ columns: [
28
+ { label: 'Date', key: 'date', format: 'dd/mm/yyyy' },
29
+ { label: 'Note', key: 'note' },
30
+ { label: 'Amount', key: 'amount', format: '#,##0.00' },
31
+ { label: 'Account', key: 'account.name' }, // a dotted key walks into the row
32
+ { label: 'Over 1,000', value: (row) => row.amount > 1000 }, // or work the cell out
33
+ ],
34
+ rows: expenses, // an array, any iterable, or an async iterable (a query read page by page)
35
+ };
36
+ ```
37
+
38
+ A cell is a string, a number, a boolean, a `Date`, or empty (`null` / `undefined`). Anything else is made into one:
39
+ a list is its items joined by `, `, a bigint its digits, an object its JSON.
40
+
41
+ ## CSV
42
+
43
+ ```ts
44
+ csv(sheet); // one string
45
+ csv(sheet, { timeZone: 'Asia/Bangkok', delimiter: ';' });
46
+ csvStream(sheet); // a ReadableStream<Uint8Array>, read from the rows as the reader asks
47
+ ```
48
+
49
+ What it writes, unless told otherwise:
50
+
51
+ - **RFC 4180**: records end in CRLF; a field holding a quote, the delimiter or a line break is quoted, a quote
52
+ inside doubled.
53
+ - **The UTF-8 byte order mark first** (`bom: false` to leave it out). Without it Excel reads a UTF-8 file in the
54
+ system's code page and Thai turns to mojibake.
55
+ - **No formula runs.** A text cell starting with `=`, `+`, `-`, `@`, a tab or a carriage return gets a `'` in front
56
+ (OWASP, CSV injection): `=HYPERLINK(…)` in a note shows as text instead of running. A number written as text
57
+ (`-120.50`) is left alone. `defuseFormulas: false` only for a file no spreadsheet opens.
58
+ - A date as `2026-11-24 09:30:00` on the clock of `timeZone` (default UTC), which Excel and Sheets read as a date.
59
+ A boolean as `TRUE` / `FALSE`. A column's `format` is for workbooks and is ignored here.
60
+
61
+ ## Excel workbook
62
+
63
+ ```ts
64
+ const bytes = await xlsx(sheet, { timeZone: 'Asia/Bangkok' });
65
+ const two = await xlsx([income, expenses]); // a tab per sheet
66
+ ```
67
+
68
+ - Text is text (never a formula), a number a number, a boolean a boolean.
69
+ - A date is a real date cell (serial days in Excel's 1900 date system), on the clock of `timeZone`, shown in the
70
+ column's `format` or `yyyy-mm-dd hh:mm:ss`.
71
+ - A column's `format` is any Excel number format: `'#,##0.00'`, `'0%'`, `'dd/mm/yyyy'`, `'[$฿-41E]#,##0.00'`.
72
+ - The header row is bold, stays in view when scrolling, and carries a filter.
73
+ - A column is as wide as what its first 200 rows hold (8 to 60 characters; Thai vowel and tone marks count as no
74
+ width), or `width`.
75
+ - Tab names are made ones Excel takes: at most 31 characters, none of `\ / ? * [ ] :`, no two the same.
76
+ - The parts are deflated where the runtime has `CompressionStream('deflate-raw')` (Bun, current Node, browsers),
77
+ stored where it has not. The same sheets give the same bytes.
78
+ - Past Excel's limits (1,048,576 rows, 16,384 columns, 32,767 characters in a cell) it throws a `RangeError`
79
+ naming the cell, rather than write a file Excel cannot open.
80
+
81
+ It is a writer for reports and exports, not a spreadsheet library: no formulas, merged cells, colours or charts.
82
+
83
+ ## A table's columns
84
+
85
+ A table declared once with the engine's `defineTable` (the one `<baht-table>` shows) gives an export the same
86
+ columns: the label as the header, an option's label in place of its key.
87
+
88
+ ```ts
89
+ import { tableColumns, xlsx } from '@20baht/export';
90
+ import { tickets } from './tables'; // defineTable(ticketForm)
91
+
92
+ const columns = tableColumns(tickets); // the visible columns, in order
93
+ const some = tableColumns(tickets, { keys: ['title', 'owner.name'], formats: { amount: '#,##0.00' } });
94
+ await xlsx({ name: 'Tickets', columns, rows });
95
+ ```
96
+
97
+ A walked column (`owner.name`) is headed `Owner · Name`. A key the table does not have throws. The table is read
98
+ by its shape, so this package does not depend on `@20baht/engine`.
99
+
100
+ ## A download
101
+
102
+ `download(body, filename)` is the `Response` a browser saves: Elysia, `Bun.serve`, Hono and Workers return it as
103
+ it is.
104
+
105
+ ```ts
106
+ import { csvStream, download, xlsx } from '@20baht/export';
107
+
108
+ app.get('/reports/expenses.csv', ({ query }) =>
109
+ download(csvStream({ columns, rows: expensesOf(query) }), 'ค่าใช้จ่าย พ.ย. 2569.csv'),
110
+ );
111
+ app.get('/reports/expenses.xlsx', async ({ query }) =>
112
+ download(await xlsx({ columns, rows: expensesOf(query) }), 'expenses.xlsx'),
113
+ );
114
+ ```
115
+
116
+ - `Content-Disposition` names the file twice (RFC 6266, RFC 8187): in ASCII for old clients, and as written,
117
+ UTF-8 and %-escaped, so a Thai name arrives intact. A path or a line break in the name is dropped.
118
+ - `Content-Type` from the extension (`.csv`, `.xlsx`, `.json`, `.txt`; else `application/octet-stream`);
119
+ `Cache-Control: no-store`, so a report is not kept between users; `X-Content-Type-Options: nosniff`.
120
+ - A third argument is a `ResponseInit`: a status, or headers of your own.
121
+
122
+ In a browser, `URL.createObjectURL(await download(bytes, name).blob())` behind an `<a download>`.
123
+
124
+ `contentDisposition(filename)` and `contentTypeOf(filename)` are there on their own, as are `CSV_TYPE` and
125
+ `XLSX_TYPE`.
package/dist/csv.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { type Sheet, type SyncSheet } from './sheet.js';
2
+ export interface CsvOptions {
3
+ /** The UTF-8 byte order mark first, so Excel reads the file as UTF-8. Default `true`. */
4
+ bom?: boolean;
5
+ /** Between fields. Default `,`. */
6
+ delimiter?: string;
7
+ /** After every record. Default `\r\n` (RFC 4180). */
8
+ eol?: string;
9
+ /** The header row first. Default `true`. */
10
+ header?: boolean;
11
+ /** The zone a date's wall clock is read in. Default `UTC`. */
12
+ timeZone?: string;
13
+ /**
14
+ * Put `'` before a text cell that starts with `=`, `+`, `-`, `@`, a tab or a carriage return, so a
15
+ * spreadsheet shows it rather than runs it. A number written as text (`-120.50`) is left alone.
16
+ * Default `true`; turn it off only for a file no spreadsheet will open.
17
+ */
18
+ defuseFormulas?: boolean;
19
+ }
20
+ /** The media type of a CSV file. */
21
+ export declare const CSV_TYPE = "text/csv; charset=utf-8";
22
+ /** The sheet as one CSV string. For rows that come page by page, `csvStream`. */
23
+ export declare const csv: <Row>(sheet: SyncSheet<Row>, options?: CsvOptions) => string;
24
+ /**
25
+ * The sheet as a stream of UTF-8 bytes, read from its rows as the reader asks for more: a large
26
+ * export goes out without being held in memory. The body of a `Response` as it is.
27
+ */
28
+ export declare const csvStream: <Row>(sheet: Sheet<Row>, options?: CsvOptions) => ReadableStream<Uint8Array>;
package/dist/csv.js ADDED
@@ -0,0 +1,80 @@
1
+ import { checkTimeZone, dateText } from './dates.js';
2
+ import { cellOf, rowsOf } from './sheet.js';
3
+ export const CSV_TYPE = 'text/csv; charset=utf-8';
4
+ const BOM = '';
5
+ const looksLikeFormula = (value) => /^[=+\-@\t\r]/.test(value) && !/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(value);
6
+ const resolve = (options) => {
7
+ const resolved = {
8
+ bom: options.bom ?? true,
9
+ delimiter: options.delimiter ?? ',',
10
+ eol: options.eol ?? '\r\n',
11
+ header: options.header ?? true,
12
+ timeZone: options.timeZone ?? 'UTC',
13
+ defuseFormulas: options.defuseFormulas ?? true,
14
+ };
15
+ if (resolved.delimiter.length === 0 || /["\r\n]/.test(resolved.delimiter))
16
+ throw new RangeError('a CSV delimiter is one or more characters, none of them a quote or a line break');
17
+ checkTimeZone(resolved.timeZone);
18
+ return resolved;
19
+ };
20
+ const field = (cell, options) => {
21
+ let text;
22
+ if (cell === null || cell === undefined)
23
+ text = '';
24
+ else if (cell instanceof Date)
25
+ text = dateText(cell, options.timeZone);
26
+ else if (typeof cell === 'number')
27
+ text = Number.isFinite(cell) ? String(cell) : '';
28
+ else if (typeof cell === 'boolean')
29
+ text = cell ? 'TRUE' : 'FALSE';
30
+ else
31
+ text = options.defuseFormulas && looksLikeFormula(cell) ? `'${cell}` : cell;
32
+ const quote = text.includes('"') ||
33
+ text.includes('\n') ||
34
+ text.includes('\r') ||
35
+ text.includes(options.delimiter);
36
+ return quote ? `"${text.replaceAll('"', '""')}"` : text;
37
+ };
38
+ const record = (cells, options) => cells.map((cell) => field(cell, options)).join(options.delimiter) + options.eol;
39
+ const headerOf = (columns, options) => (options.bom ? BOM : '') +
40
+ (options.header
41
+ ? record(columns.map((column) => column.label), options)
42
+ : '');
43
+ const rowRecord = (columns, row, options) => record(columns.map((column) => cellOf(column, row)), options);
44
+ export const csv = (sheet, options = {}) => {
45
+ const resolved = resolve(options);
46
+ let out = headerOf(sheet.columns, resolved);
47
+ for (const row of sheet.rows)
48
+ out += rowRecord(sheet.columns, row, resolved);
49
+ return out;
50
+ };
51
+ const CHUNK = 500;
52
+ export const csvStream = (sheet, options = {}) => {
53
+ const resolved = resolve(options);
54
+ const encoder = new TextEncoder();
55
+ const rows = rowsOf(sheet.rows);
56
+ let started = false;
57
+ return new ReadableStream({
58
+ async pull(controller) {
59
+ let text = '';
60
+ if (!started) {
61
+ started = true;
62
+ text = headerOf(sheet.columns, resolved);
63
+ }
64
+ for (let n = 0; n < CHUNK; n++) {
65
+ const next = await rows.next();
66
+ if (next.done) {
67
+ if (text)
68
+ controller.enqueue(encoder.encode(text));
69
+ controller.close();
70
+ return;
71
+ }
72
+ text += rowRecord(sheet.columns, next.value, resolved);
73
+ }
74
+ controller.enqueue(encoder.encode(text));
75
+ },
76
+ async cancel() {
77
+ await rows.return(undefined);
78
+ },
79
+ });
80
+ };
@@ -0,0 +1,6 @@
1
+ /** Throws a RangeError now when `timeZone` is not one Intl knows. */
2
+ export declare const checkTimeZone: (timeZone: string) => void;
3
+ /** `2026-11-24 09:30:00` on the zone's clock: what Excel and Sheets read as a date and time. */
4
+ export declare const dateText: (date: Date, timeZone: string) => string;
5
+ /** The instant as an Excel serial date (days since 1899-12-30, the time a fraction), on the zone's clock. */
6
+ export declare const serialDate: (date: Date, timeZone: string) => number;
package/dist/dates.js ADDED
@@ -0,0 +1,39 @@
1
+ const formatters = new Map();
2
+ const formatterOf = (timeZone) => {
3
+ let found = formatters.get(timeZone);
4
+ if (!found) {
5
+ found = new Intl.DateTimeFormat('en-US', {
6
+ timeZone,
7
+ hourCycle: 'h23',
8
+ year: 'numeric',
9
+ month: '2-digit',
10
+ day: '2-digit',
11
+ hour: '2-digit',
12
+ minute: '2-digit',
13
+ second: '2-digit',
14
+ });
15
+ formatters.set(timeZone, found);
16
+ }
17
+ return found;
18
+ };
19
+ const wallClock = (date, timeZone) => {
20
+ const parts = {};
21
+ for (const part of formatterOf(timeZone).formatToParts(date))
22
+ if (part.type !== 'literal')
23
+ parts[part.type] = Number(part.value);
24
+ return Date.UTC(parts.year ?? 1970, (parts.month ?? 1) - 1, parts.day ?? 1, parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, date.getUTCMilliseconds());
25
+ };
26
+ export const checkTimeZone = (timeZone) => {
27
+ formatterOf(timeZone);
28
+ };
29
+ const pad = (n) => String(n).padStart(2, '0');
30
+ export const dateText = (date, timeZone) => {
31
+ if (Number.isNaN(date.getTime()))
32
+ return '';
33
+ const at = new Date(wallClock(date, timeZone));
34
+ return (`${String(at.getUTCFullYear())}-${pad(at.getUTCMonth() + 1)}-${pad(at.getUTCDate())} ` +
35
+ `${pad(at.getUTCHours())}:${pad(at.getUTCMinutes())}:${pad(at.getUTCSeconds())}`);
36
+ };
37
+ const DAY = 86_400_000;
38
+ const EPOCH = Date.UTC(1899, 11, 30);
39
+ export const serialDate = (date, timeZone) => (wallClock(date, timeZone) - EPOCH) / DAY;
@@ -0,0 +1,10 @@
1
+ /** `attachment; filename="report.csv"; filename*=UTF-8''…`: the name in ASCII, and as it is. */
2
+ export declare const contentDisposition: (filename: string) => string;
3
+ /** The media type for a file name's extension; `application/octet-stream` for one not known. */
4
+ export declare const contentTypeOf: (filename: string) => string;
5
+ /**
6
+ * The body as a download named `filename`: its type from the extension, `no-store` so a report is
7
+ * not kept by a cache between users, `nosniff` so it is never read as a page. `init` adds headers or
8
+ * sets a status.
9
+ */
10
+ export declare const download: (body: string | Uint8Array | ReadableStream<Uint8Array>, filename: string, init?: ResponseInit) => Response;
@@ -0,0 +1,32 @@
1
+ import { CSV_TYPE } from './csv.js';
2
+ import { XLSX_TYPE } from './xlsx.js';
3
+ const TYPES = {
4
+ csv: CSV_TYPE,
5
+ xlsx: XLSX_TYPE,
6
+ json: 'application/json; charset=utf-8',
7
+ txt: 'text/plain; charset=utf-8',
8
+ };
9
+ const safeName = (filename) => {
10
+ const name = (filename.split(/[\\/]/).pop() ?? '').replace(/[\u0000-\u001f\u007f]/g, '').trim();
11
+ return name || 'download';
12
+ };
13
+ const encoded = (name) => encodeURIComponent(name).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
14
+ export const contentDisposition = (filename) => {
15
+ const name = safeName(filename);
16
+ const ascii = name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_');
17
+ return `attachment; filename="${ascii}"; filename*=UTF-8''${encoded(name)}`;
18
+ };
19
+ export const contentTypeOf = (filename) => {
20
+ const extension = /\.([^.]+)$/.exec(filename)?.[1]?.toLowerCase();
21
+ return (extension && TYPES[extension]) ?? 'application/octet-stream';
22
+ };
23
+ export const download = (body, filename, init = {}) => {
24
+ const headers = new Headers(init.headers);
25
+ if (!headers.has('content-type'))
26
+ headers.set('content-type', contentTypeOf(filename));
27
+ headers.set('content-disposition', contentDisposition(filename));
28
+ if (!headers.has('cache-control'))
29
+ headers.set('cache-control', 'no-store');
30
+ headers.set('x-content-type-options', 'nosniff');
31
+ return new Response(body, { ...init, headers });
32
+ };
@@ -0,0 +1,5 @@
1
+ export { csv, csvStream, CSV_TYPE, type CsvOptions } from './csv.js';
2
+ export { contentDisposition, contentTypeOf, download } from './download.js';
3
+ export type { Cell, Column, Sheet, SyncSheet } from './sheet.js';
4
+ export { tableColumns, type TableColumnLike, type TableColumnsOptions, type TableLike, } from './table.js';
5
+ export { columnName, xlsx, XLSX_TYPE, type XlsxOptions } from './xlsx.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { csv, csvStream, CSV_TYPE } from './csv.js';
2
+ export { contentDisposition, contentTypeOf, download } from './download.js';
3
+ export { tableColumns, } from './table.js';
4
+ export { columnName, xlsx, XLSX_TYPE } from './xlsx.js';
@@ -0,0 +1,39 @@
1
+ /** What one cell holds. `null` and `undefined` are an empty cell. */
2
+ export type Cell = string | number | boolean | Date | null | undefined;
3
+ /** One column: its header, and how its cell is read from a row. */
4
+ export interface Column<Row> {
5
+ /** The header. */
6
+ label: string;
7
+ /**
8
+ * The row's property the cell is. A dotted key (`owner.name`) is the row's own `owner.name` if it
9
+ * has one, else `row.owner.name`. With `value`, unused.
10
+ */
11
+ key?: string;
12
+ /** The cell, worked out from the row. Wins over `key`. */
13
+ value?(row: Row): unknown;
14
+ /**
15
+ * An Excel number format for the column's numbers and dates in a workbook: `'#,##0.00'`,
16
+ * `'yyyy-mm-dd'`. A CSV writes values, not formats, and ignores it.
17
+ */
18
+ format?: string;
19
+ /** The column's width in a workbook, in characters. Unset: as wide as what it holds (8 to 60). */
20
+ width?: number;
21
+ }
22
+ /** A sheet: a name (a workbook's tab), the columns and the rows. */
23
+ export interface Sheet<Row> {
24
+ /** The tab's name in a workbook. Unset: `Sheet1`, `Sheet2`, … */
25
+ name?: string;
26
+ columns: readonly Column<Row>[];
27
+ /** An array, any iterable, or an async iterable (a query read page by page). */
28
+ rows: Iterable<Row> | AsyncIterable<Row>;
29
+ }
30
+ /** A sheet whose rows are all at hand: what `csv()` takes. */
31
+ export interface SyncSheet<Row> extends Sheet<Row> {
32
+ rows: Iterable<Row>;
33
+ }
34
+ /** The value at `key` in a row: its own property, else walked along the dots. */
35
+ export declare const valueAt: (row: unknown, key: string) => unknown;
36
+ /** A column's cell in a row. */
37
+ export declare const cellOf: <Row>(column: Column<Row>, row: Row) => Cell;
38
+ /** The rows of a sheet, one at a time, whether they are an array or come page by page. */
39
+ export declare function rowsOf<Row>(rows: Iterable<Row> | AsyncIterable<Row>): AsyncGenerator<Row>;
package/dist/sheet.js ADDED
@@ -0,0 +1,61 @@
1
+ const own = (value, key) => Object.prototype.hasOwnProperty.call(value, key)
2
+ ? value[key]
3
+ : undefined;
4
+ export const valueAt = (row, key) => {
5
+ if (typeof row !== 'object' || row === null)
6
+ return undefined;
7
+ const direct = own(row, key);
8
+ if (direct !== undefined || !key.includes('.'))
9
+ return direct;
10
+ let at = row;
11
+ for (const part of key.split('.')) {
12
+ if (typeof at !== 'object' || at === null)
13
+ return undefined;
14
+ at = own(at, part);
15
+ }
16
+ return at;
17
+ };
18
+ const toCell = (value) => {
19
+ if (value === null || value === undefined)
20
+ return value;
21
+ if (value instanceof Date)
22
+ return value;
23
+ switch (typeof value) {
24
+ case 'string':
25
+ case 'number':
26
+ case 'boolean':
27
+ return value;
28
+ case 'bigint':
29
+ return value.toString();
30
+ case 'object':
31
+ return Array.isArray(value)
32
+ ? value.map((item) => cellText(toCell(item))).join(', ')
33
+ : JSON.stringify(value);
34
+ case 'symbol':
35
+ case 'undefined':
36
+ case 'function':
37
+ return undefined;
38
+ }
39
+ };
40
+ export const cellOf = (column, row) => {
41
+ if (column.value)
42
+ return toCell(column.value(row));
43
+ return column.key === undefined ? undefined : toCell(valueAt(row, column.key));
44
+ };
45
+ const cellText = (cell) => {
46
+ if (cell === null || cell === undefined)
47
+ return '';
48
+ if (cell instanceof Date)
49
+ return Number.isNaN(cell.getTime()) ? '' : cell.toISOString();
50
+ return String(cell);
51
+ };
52
+ export async function* rowsOf(rows) {
53
+ if (Symbol.asyncIterator in rows) {
54
+ for await (const row of rows)
55
+ yield row;
56
+ }
57
+ else {
58
+ for (const row of rows)
59
+ yield row;
60
+ }
61
+ }
@@ -0,0 +1,28 @@
1
+ import { type Column } from './sheet.js';
2
+ /** A column as `defineTable` declares it: the part of `TableColumn` an export reads. */
3
+ export interface TableColumnLike {
4
+ readonly label: string;
5
+ /** A cell's text by its value: an option's label for its key. */
6
+ readonly labels?: Readonly<Record<string, string>>;
7
+ /** The columns of the record a reference points at (`owner.name`). */
8
+ readonly fields?: Readonly<Record<string, TableColumnLike>>;
9
+ /** A heading over its fields only, never a cell. */
10
+ readonly group?: true;
11
+ }
12
+ /** A table as `defineTable` returns it: its columns by key, and the ones that show, in order. */
13
+ export interface TableLike {
14
+ readonly columns: Readonly<Record<string, TableColumnLike>>;
15
+ readonly visible?: readonly string[];
16
+ }
17
+ export interface TableColumnsOptions {
18
+ /** The columns, in order: a key of the table or a walked key (`owner.name`). Default: `visible`. */
19
+ keys?: readonly string[];
20
+ /** The number format of a column by key, for a workbook (`{ amount: '#,##0.00' }`). */
21
+ formats?: Readonly<Record<string, string>>;
22
+ }
23
+ /**
24
+ * The columns of an export, read from a table: each `visible` column (or each of `keys`), its label as
25
+ * the header (a walked column's is `Owner · Name`), a choice's cell as its option's label. A group
26
+ * column, which is only a heading, is left out. A key the table does not have throws.
27
+ */
28
+ export declare const tableColumns: <Row = Record<string, unknown>>(table: TableLike, options?: TableColumnsOptions) => Column<Row>[];
package/dist/table.js ADDED
@@ -0,0 +1,57 @@
1
+ import { valueAt } from './sheet.js';
2
+ const columnAt = (table, key) => {
3
+ const top = Object.prototype.hasOwnProperty.call(table.columns, key)
4
+ ? table.columns[key]
5
+ : undefined;
6
+ if (top)
7
+ return { column: top, path: [top.label] };
8
+ const parts = key.split('.');
9
+ let fields = table.columns;
10
+ const path = [];
11
+ let column;
12
+ for (const part of parts) {
13
+ column =
14
+ fields && Object.prototype.hasOwnProperty.call(fields, part) ? fields[part] : undefined;
15
+ if (!column)
16
+ return undefined;
17
+ path.push(column.label);
18
+ fields = column.fields;
19
+ }
20
+ return column ? { column, path } : undefined;
21
+ };
22
+ export const tableColumns = (table, options = {}) => {
23
+ const keys = options.keys ?? table.visible ?? Object.keys(table.columns);
24
+ const columns = [];
25
+ for (const key of keys) {
26
+ const found = columnAt(table, key);
27
+ if (!found)
28
+ throw new RangeError(`the table has no column "${key}"`);
29
+ if (found.column.group)
30
+ continue;
31
+ const labels = found.column.labels;
32
+ const format = options.formats?.[key];
33
+ columns.push({
34
+ label: found.path.join(' · '),
35
+ key,
36
+ ...(labels
37
+ ? {
38
+ value: (row) => {
39
+ const value = valueAt(row, key);
40
+ if (typeof value === 'string' || typeof value === 'number') {
41
+ const text = String(value);
42
+ return Object.prototype.hasOwnProperty.call(labels, text) ? labels[text] : value;
43
+ }
44
+ if (Array.isArray(value))
45
+ return value.map((item) => (typeof item === 'string' || typeof item === 'number') &&
46
+ Object.prototype.hasOwnProperty.call(labels, String(item))
47
+ ? labels[String(item)]
48
+ : item);
49
+ return value;
50
+ },
51
+ }
52
+ : {}),
53
+ ...(format === undefined ? {} : { format }),
54
+ });
55
+ }
56
+ return columns;
57
+ };
package/dist/xlsx.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { type Sheet } from './sheet.js';
2
+ export interface XlsxOptions {
3
+ /** The zone a date's wall clock is read in. Default `UTC`. */
4
+ timeZone?: string;
5
+ /** Deflate the parts where the runtime can (`CompressionStream`). Default `true`. */
6
+ compress?: boolean;
7
+ }
8
+ /** The media type of an .xlsx file. */
9
+ export declare const XLSX_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
10
+ /** `A`, `Z`, `AA`: the letters of a column counted from 0. */
11
+ export declare const columnName: (index: number) => string;
12
+ /**
13
+ * The sheets as the bytes of an .xlsx file. One sheet, or several (a tab each). Rows may come page by
14
+ * page (an async iterable); the workbook is still built whole before it is returned.
15
+ */
16
+ export declare const xlsx: (sheets: Sheet<unknown> | readonly Sheet<unknown>[], options?: XlsxOptions) => Promise<Uint8Array>;
package/dist/xlsx.js ADDED
@@ -0,0 +1,211 @@
1
+ import { checkTimeZone, serialDate } from './dates.js';
2
+ import { cellOf, rowsOf } from './sheet.js';
3
+ import { zip } from './zip.js';
4
+ export const XLSX_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
5
+ const MAX_ROWS = 1_048_576;
6
+ const MAX_COLUMNS = 16_384;
7
+ const MAX_TEXT = 32_767;
8
+ const DATE_FORMAT = 'yyyy-mm-dd hh:mm:ss';
9
+ const escaped = (value) => value
10
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f￾￿]/g, '')
11
+ .replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, '')
12
+ .replaceAll('&', '&amp;')
13
+ .replaceAll('<', '&lt;')
14
+ .replaceAll('>', '&gt;')
15
+ .replaceAll('"', '&quot;');
16
+ export const columnName = (index) => {
17
+ let name = '';
18
+ for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26))
19
+ name = String.fromCharCode(65 + ((n - 1) % 26)) + name;
20
+ return name;
21
+ };
22
+ const textWidth = (text) => {
23
+ let width = 0;
24
+ for (const char of text) {
25
+ if (/\p{M}/u.test(char))
26
+ continue;
27
+ width += /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩\u{20000}-\u{3fffd}]/u.test(char) ? 2 : 1;
28
+ }
29
+ return width;
30
+ };
31
+ class Styles {
32
+ #formats = new Map();
33
+ of(format) {
34
+ if (format === undefined || format === '')
35
+ return 0;
36
+ let index = this.#formats.get(format);
37
+ if (index === undefined) {
38
+ index = this.#formats.size + 2;
39
+ this.#formats.set(format, index);
40
+ }
41
+ return index;
42
+ }
43
+ xml() {
44
+ const formats = [...this.#formats.keys()];
45
+ const numFmts = formats.length
46
+ ? `<numFmts count="${String(formats.length)}">${formats
47
+ .map((code, i) => `<numFmt numFmtId="${String(164 + i)}" formatCode="${escaped(code)}"/>`)
48
+ .join('')}</numFmts>`
49
+ : '';
50
+ const xfs = formats
51
+ .map((_, i) => `<xf numFmtId="${String(164 + i)}" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/>`)
52
+ .join('');
53
+ return (`${XML}<styleSheet xmlns="${MAIN}">${numFmts}` +
54
+ `<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts>` +
55
+ `<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>` +
56
+ `<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>` +
57
+ `<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>` +
58
+ `<cellXfs count="${String(formats.length + 2)}"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>` +
59
+ `<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>${xfs}</cellXfs>` +
60
+ `<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>` +
61
+ `</styleSheet>`);
62
+ }
63
+ }
64
+ const cellXml = (cell, ref, plan, styles, timeZone) => {
65
+ if (cell === null || cell === undefined || cell === '')
66
+ return '';
67
+ if (typeof cell === 'number') {
68
+ if (!Number.isFinite(cell))
69
+ return '';
70
+ const s = plan.numberStyle ? ` s="${String(plan.numberStyle)}"` : '';
71
+ return `<c r="${ref}"${s}><v>${String(cell)}</v></c>`;
72
+ }
73
+ if (typeof cell === 'boolean')
74
+ return `<c r="${ref}" t="b"><v>${cell ? '1' : '0'}</v></c>`;
75
+ if (cell instanceof Date) {
76
+ if (Number.isNaN(cell.getTime()))
77
+ return '';
78
+ const style = plan.numberStyle || styles.of(DATE_FORMAT);
79
+ return `<c r="${ref}" s="${String(style)}"><v>${String(serialDate(cell, timeZone))}</v></c>`;
80
+ }
81
+ if (cell.length > MAX_TEXT)
82
+ throw new RangeError(`cell ${ref} holds ${String(cell.length)} characters; a workbook cell holds at most ${String(MAX_TEXT)}`);
83
+ return `<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${escaped(cell)}</t></is></c>`;
84
+ };
85
+ const MEASURED_ROWS = 200;
86
+ const shownWidth = (cell) => {
87
+ if (cell === null || cell === undefined)
88
+ return 0;
89
+ if (cell instanceof Date)
90
+ return 19;
91
+ if (typeof cell === 'string')
92
+ return Math.max(...cell.split('\n').map(textWidth));
93
+ return String(cell).length;
94
+ };
95
+ const sheetXml = async (sheet, styles, timeZone) => {
96
+ const columns = sheet.columns;
97
+ if (columns.length > MAX_COLUMNS)
98
+ throw new RangeError(`a sheet has at most ${String(MAX_COLUMNS)} columns`);
99
+ const plans = columns.map((column) => ({
100
+ numberStyle: styles.of(column.format),
101
+ format: column.format,
102
+ width: column.width,
103
+ measured: textWidth(column.label),
104
+ }));
105
+ const header = `<row r="1">` +
106
+ columns
107
+ .map((column, i) => column.label
108
+ ? `<c r="${columnName(i)}1" s="1" t="inlineStr"><is><t xml:space="preserve">${escaped(column.label)}</t></is></c>`
109
+ : '')
110
+ .join('') +
111
+ `</row>`;
112
+ const body = [];
113
+ let r = 1;
114
+ for await (const row of rowsOf(sheet.rows)) {
115
+ r++;
116
+ if (r > MAX_ROWS)
117
+ throw new RangeError(`a sheet has at most ${String(MAX_ROWS - 1)} rows under its header`);
118
+ let cells = '';
119
+ columns.forEach((column, i) => {
120
+ const cell = cellOf(column, row);
121
+ const plan = plans[i];
122
+ if (r <= MEASURED_ROWS + 1)
123
+ plan.measured = Math.max(plan.measured, shownWidth(cell));
124
+ cells += cellXml(cell, `${columnName(i)}${String(r)}`, plan, styles, timeZone);
125
+ });
126
+ body.push(`<row r="${String(r)}">${cells}</row>`);
127
+ }
128
+ const cols = plans
129
+ .map((plan, i) => {
130
+ const n = String(i + 1);
131
+ const width = plan.width ?? Math.min(60, Math.max(8, plan.measured + 2));
132
+ return `<col min="${n}" max="${n}" width="${String(width)}" customWidth="1"/>`;
133
+ })
134
+ .join('');
135
+ const last = `${columnName(Math.max(0, columns.length - 1))}${String(r)}`;
136
+ return (`${XML}<worksheet xmlns="${MAIN}">` +
137
+ `<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>` +
138
+ `<sheetFormatPr defaultRowHeight="15"/>` +
139
+ (cols ? `<cols>${cols}</cols>` : '') +
140
+ `<sheetData>${header}${body.join('')}</sheetData>` +
141
+ (columns.length ? `<autoFilter ref="A1:${last}"/>` : '') +
142
+ `</worksheet>`);
143
+ };
144
+ const sheetNames = (sheets) => {
145
+ const taken = new Set();
146
+ return sheets.map((sheet, i) => {
147
+ let base = (sheet.name ?? '')
148
+ .replace(/[\\/?*[\]:]/g, ' ')
149
+ .replace(/^'+|'+$/g, '')
150
+ .trim()
151
+ .slice(0, 31);
152
+ if (!base)
153
+ base = `Sheet${String(i + 1)}`;
154
+ if (base.toLowerCase() === 'history')
155
+ base = `${base} 1`;
156
+ let name = base;
157
+ for (let n = 2; taken.has(name.toLowerCase()); n++) {
158
+ const suffix = ` (${String(n)})`;
159
+ name = base.slice(0, 31 - suffix.length) + suffix;
160
+ }
161
+ taken.add(name.toLowerCase());
162
+ return name;
163
+ });
164
+ };
165
+ const XML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`;
166
+ const MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
167
+ const REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
168
+ const PKG = 'http://schemas.openxmlformats.org/package/2006';
169
+ const PART = 'application/vnd.openxmlformats-officedocument.spreadsheetml';
170
+ export const xlsx = async (sheets, options = {}) => {
171
+ const list = Array.isArray(sheets)
172
+ ? sheets
173
+ : [sheets];
174
+ if (list.length === 0)
175
+ throw new RangeError('a workbook has at least one sheet');
176
+ const timeZone = options.timeZone ?? 'UTC';
177
+ checkTimeZone(timeZone);
178
+ const styles = new Styles();
179
+ const names = sheetNames(list);
180
+ const parts = [];
181
+ for (const sheet of list)
182
+ parts.push(await sheetXml(sheet, styles, timeZone));
183
+ const ids = list.map((_, i) => String(i + 1));
184
+ const encoder = new TextEncoder();
185
+ const file = (path, text) => ({ path, data: encoder.encode(text) });
186
+ return zip([
187
+ file('[Content_Types].xml', `${XML}<Types xmlns="${PKG}/content-types">` +
188
+ `<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
189
+ `<Default Extension="xml" ContentType="application/xml"/>` +
190
+ `<Override PartName="/xl/workbook.xml" ContentType="${PART}.sheet.main+xml"/>` +
191
+ `<Override PartName="/xl/styles.xml" ContentType="${PART}.styles+xml"/>` +
192
+ ids
193
+ .map((id) => `<Override PartName="/xl/worksheets/sheet${id}.xml" ContentType="${PART}.worksheet+xml"/>`)
194
+ .join('') +
195
+ `</Types>`),
196
+ file('_rels/.rels', `${XML}<Relationships xmlns="${PKG}/relationships"><Relationship Id="rId1" Type="${REL}/officeDocument" Target="xl/workbook.xml"/></Relationships>`),
197
+ file('xl/workbook.xml', `${XML}<workbook xmlns="${MAIN}" xmlns:r="${REL}"><bookViews><workbookView/></bookViews><sheets>` +
198
+ ids
199
+ .map((id, i) => `<sheet name="${escaped(names[i] ?? '')}" sheetId="${id}" r:id="rId${id}"/>`)
200
+ .join('') +
201
+ `</sheets></workbook>`),
202
+ file('xl/_rels/workbook.xml.rels', `${XML}<Relationships xmlns="${PKG}/relationships">` +
203
+ ids
204
+ .map((id) => `<Relationship Id="rId${id}" Type="${REL}/worksheet" Target="worksheets/sheet${id}.xml"/>`)
205
+ .join('') +
206
+ `<Relationship Id="rId${String(list.length + 1)}" Type="${REL}/styles" Target="styles.xml"/>` +
207
+ `</Relationships>`),
208
+ file('xl/styles.xml', styles.xml()),
209
+ ...parts.map((text, i) => file(`xl/worksheets/sheet${ids[i] ?? ''}.xml`, text)),
210
+ ], options.compress ?? true);
211
+ };
package/dist/zip.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /** CRC-32 (ISO 3309), the checksum a zip keeps of every file. */
2
+ export declare const crc32: (bytes: Uint8Array) => number;
3
+ export interface ZipFile {
4
+ path: string;
5
+ data: Uint8Array;
6
+ }
7
+ /** The files as one zip archive. */
8
+ export declare const zip: (files: readonly ZipFile[], compress: boolean) => Promise<Uint8Array>;
package/dist/zip.js ADDED
@@ -0,0 +1,114 @@
1
+ const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, n) => {
2
+ let c = n;
3
+ for (let k = 0; k < 8; k++)
4
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
5
+ return c >>> 0;
6
+ });
7
+ export const crc32 = (bytes) => {
8
+ let crc = 0xffffffff;
9
+ for (const byte of bytes)
10
+ crc = (CRC_TABLE[(crc ^ byte) & 0xff] ?? 0) ^ (crc >>> 8);
11
+ return (crc ^ 0xffffffff) >>> 0;
12
+ };
13
+ const concat = (parts) => {
14
+ const out = new Uint8Array(parts.reduce((n, part) => n + part.length, 0));
15
+ let at = 0;
16
+ for (const part of parts) {
17
+ out.set(part, at);
18
+ at += part.length;
19
+ }
20
+ return out;
21
+ };
22
+ const deflateRaw = async (bytes) => {
23
+ let stream;
24
+ try {
25
+ stream = new CompressionStream('deflate-raw');
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ const writer = stream.writable.getWriter();
31
+ const writing = writer.write(bytes).then(() => writer.close());
32
+ const chunks = [];
33
+ const reader = stream.readable.getReader();
34
+ for (;;) {
35
+ const { done, value } = await reader.read();
36
+ if (done)
37
+ break;
38
+ chunks.push(value);
39
+ }
40
+ await writing;
41
+ return concat(chunks);
42
+ };
43
+ class Writer {
44
+ #parts = [];
45
+ #length = 0;
46
+ get length() {
47
+ return this.#length;
48
+ }
49
+ u16(n) {
50
+ return this.bytes(Uint8Array.of(n & 0xff, (n >>> 8) & 0xff));
51
+ }
52
+ u32(n) {
53
+ return this.u16(n & 0xffff).u16(n >>> 16);
54
+ }
55
+ bytes(bytes) {
56
+ this.#parts.push(bytes);
57
+ this.#length += bytes.length;
58
+ return this;
59
+ }
60
+ done() {
61
+ return concat(this.#parts);
62
+ }
63
+ }
64
+ const DOS_TIME = 0;
65
+ const DOS_DATE = (0 << 9) | (1 << 5) | 1;
66
+ const UTF8 = 0x0800;
67
+ const LIMIT = 0xffffffff;
68
+ export const zip = async (files, compress) => {
69
+ const encoder = new TextEncoder();
70
+ const out = new Writer();
71
+ const central = new Writer();
72
+ for (const file of files) {
73
+ const name = encoder.encode(file.path);
74
+ const deflated = compress ? await deflateRaw(file.data) : undefined;
75
+ const stored = !deflated || deflated.length >= file.data.length;
76
+ const body = stored ? file.data : deflated;
77
+ const crc = crc32(file.data);
78
+ const offset = out.length;
79
+ if (offset + body.length > LIMIT)
80
+ throw new RangeError('a workbook past 4 GB cannot be written');
81
+ const fields = (w) => w
82
+ .u16(20)
83
+ .u16(UTF8)
84
+ .u16(stored ? 0 : 8)
85
+ .u16(DOS_TIME)
86
+ .u16(DOS_DATE)
87
+ .u32(crc)
88
+ .u32(body.length)
89
+ .u32(file.data.length)
90
+ .u16(name.length)
91
+ .u16(0);
92
+ fields(out.u32(0x04034b50)).bytes(name).bytes(body);
93
+ fields(central.u32(0x02014b50).u16(20))
94
+ .u16(0)
95
+ .u16(0)
96
+ .u16(0)
97
+ .u32(0)
98
+ .u32(offset)
99
+ .bytes(name);
100
+ }
101
+ const directory = central.done();
102
+ const start = out.length;
103
+ return out
104
+ .bytes(directory)
105
+ .u32(0x06054b50)
106
+ .u16(0)
107
+ .u16(0)
108
+ .u16(files.length)
109
+ .u16(files.length)
110
+ .u32(directory.length)
111
+ .u32(start)
112
+ .u16(0)
113
+ .done();
114
+ };
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@20baht/export",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=20.19.0"
7
+ },
8
+ "description": "Rows as a CSV or an .xlsx file, on a server or in a browser: Thai that opens in Excel, no formula a cell can smuggle in, dates and number formats, a table's columns as the header. No dependencies.",
9
+ "license": "MIT",
10
+ "author": "Nattapong Promthong",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/bank20baht/20baht.git",
14
+ "directory": "packages/core/export"
15
+ },
16
+ "homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/export#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/bank20baht/20baht/issues"
19
+ },
20
+ "keywords": [
21
+ "csv",
22
+ "xlsx",
23
+ "excel",
24
+ "export",
25
+ "spreadsheet",
26
+ "download",
27
+ "report"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "import": "./dist/index.js",
39
+ "default": "./dist/index.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "scripts": {
44
+ "build": "rm -rf dist && tsc -p tsconfig.json --removeComments && tsc -p tsconfig.json --emitDeclarationOnly",
45
+ "test": "vitest run",
46
+ "test:watch": "vitest",
47
+ "test:coverage": "vitest run --coverage"
48
+ },
49
+ "devDependencies": {
50
+ "@20baht/engine": "workspace:*",
51
+ "typescript": "^5.9.3",
52
+ "vitest": "^3.2.4"
53
+ },
54
+ "main": "./dist/index.js",
55
+ "types": "./dist/index.d.ts",
56
+ "sideEffects": false
57
+ }