/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/storage/Dataset * * Append-only JSONL dataset backed by `Bun.file().writer()`. * * Inspired by Crawlee's Dataset * (packages/core/src/storages/dataset.ts) but rewritten Bun-native: * - Uses `Bun.file().writer()` for buffered, non-blocking append writes. * - No CSV dependency (optional CSV export uses hand-rolled serializer). * - Auto-creates storage directory via `Bun.write`. * - Supports JSON + JSONL + CSV export. * - Atomic metadata file with record count (via `Bun.write`). * * Each dataset lives in: * `/datasets//data.jsonl` (rows, one JSON object per line) * `/datasets//meta.json` (count, createdAt, etc.) * * @example * ```ts * const ds = await Dataset.open("products"); * await ds.pushData({ title: "Widget", price: 9.99 }); * await ds.pushData([{ title: "Gadget" }, { title: "Gizmo" }]); * await ds.exportToJson("./out/products.json"); * const count = await ds.getItemCount(); * await ds.close(); * ``` */ import { join } from "node:path"; import { BxcConfig } from "../config/BxcConfig.ts"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export type DatasetItem = Record; export interface DatasetOptions { /** * Root directory for all datasets. * Default: `"./storage"`. */ storageDir?: string; } export interface DatasetMeta { name: string; createdAt: string; itemCount: number; } export interface DatasetExportOptions { /** Maximum number of rows to export. Default: all. */ limit?: number; /** Rows to skip from the beginning. Default: 0. */ offset?: number; } export interface DatasetSqliteExportOptions extends DatasetExportOptions { /** Table name in SQLite database. Default: "items" */ tableName?: string; /** Enable FTS5 full-text search table and trigger. Default: true */ fts?: boolean; /** Batch size per transaction. Default: 500 */ batchSize?: number; } export interface DatasetPostgresExportOptions extends DatasetExportOptions { /** Table name in PostgreSQL database. Default: "bxc_dataset_items" */ tableName?: string; /** Batch size for insertion. Default: 100 */ batchSize?: number; } // --------------------------------------------------------------------------- // Dataset // --------------------------------------------------------------------------- export class Dataset { readonly #dataPath: string; readonly #metaPath: string; readonly #name: string; #writer: ReturnType["writer"]> | null = null; #itemCount = 0; private constructor( name: string, dataPath: string, metaPath: string, initialCount: number, ) { this.#name = name; this.#dataPath = dataPath; this.#metaPath = metaPath; this.#itemCount = initialCount; } // --------------------------------------------------------------------------- // Factory // --------------------------------------------------------------------------- /** * Open (or create) a named dataset. * Datasets with the same name resume from where they left off. */ static async open(name: string, opts: DatasetOptions = {}): Promise { const storageDir = opts.storageDir ?? BxcConfig.getGlobal().storageDir; const dir = join(storageDir, "datasets", name); const dataPath = join(dir, "data.jsonl"); const metaPath = join(dir, "meta.json"); // Ensure directory exists by writing a placeholder if needed // bun:mkdir is not available; use Bun.write to an empty sentinel const metaFile = Bun.file(metaPath); let initialCount = 0; if (await metaFile.exists()) { try { const meta = (await metaFile.json()) as DatasetMeta; initialCount = meta.itemCount ?? 0; } catch { initialCount = 0; } } else { // Bootstrap meta const meta: DatasetMeta = { name, createdAt: new Date().toISOString(), itemCount: 0, }; await Bun.write(metaPath, JSON.stringify(meta, null, 2)); } return new Dataset(name, dataPath, metaPath, initialCount); } // --------------------------------------------------------------------------- // Write // --------------------------------------------------------------------------- /** * Append one or more items to the dataset. * Each item must be a plain JSON-serializable object. */ async pushData(data: DatasetItem | DatasetItem[]): Promise { const items = Array.isArray(data) ? data : [data]; if (items.length === 0) return; // Lazy-init the streaming writer (append mode) if (this.#writer === null) { this.#writer = Bun.file(this.#dataPath).writer(); } const writer = this.#writer; let newlines = ""; for (const item of items) { if (typeof item !== "object" || item === null || Array.isArray(item)) { throw new TypeError( `Dataset items must be plain objects, got: ${typeof item}`, ); } newlines += JSON.stringify(item) + "\n"; this.#itemCount++; } // Write all new lines in a single call for efficiency writer.write(newlines); await writer.flush(); // Update meta atomically await this.#writeMeta(); } // --------------------------------------------------------------------------- // Read / export // --------------------------------------------------------------------------- /** * Read all items from the dataset into an array. * Uses `Bun.file().text()` and splits on newlines — memory-efficient for * moderate datasets (< 1 GB). */ async getData(opts: DatasetExportOptions = {}): Promise { const file = Bun.file(this.#dataPath); if (!(await file.exists())) return []; const text = await file.text(); const offset = opts.offset ?? 0; const limit = opts.limit ?? Infinity; const lines = text.split("\n").filter((l) => l.trim().length > 0); const sliced = lines.slice( offset, limit === Infinity ? undefined : offset + limit, ); const items: DatasetItem[] = []; for (const line of sliced) { try { items.push(JSON.parse(line) as DatasetItem); } catch { // Skip malformed lines } } return items; } /** Return the total number of items stored. */ getItemCount(): number { return this.#itemCount; } /** * Export data as a formatted JSON array to `outputPath`. * Uses `Bun.write` for atomic single-shot write. */ async exportToJson( outputPath: string, opts?: DatasetExportOptions, ): Promise { const items = await this.getData(opts); await Bun.write(outputPath, JSON.stringify(items, null, 2)); } /** * Export data as CSV to `outputPath`. * Column order is derived from the keys of the first item. * Fields containing commas, newlines, or quotes are properly escaped (RFC 4180). */ async exportToCsv( outputPath: string, opts?: DatasetExportOptions, ): Promise { const items = await this.getData(opts); if (items.length === 0) { await Bun.write(outputPath, ""); return; } const headers = Object.keys(items[0]); const escape = (v: unknown): string => { const s = v === null || v === undefined ? "" : String(v); if ( s.includes(",") || s.includes('"') || s.includes("\n") || s.includes("\r") ) { return `"${s.replace(/"/g, '""')}"`; } return s; }; const csvLines = [ headers.map(escape).join(","), ...items.map((row) => headers.map((h) => escape(row[h])).join(",")), ]; await Bun.write(outputPath, csvLines.join("\n") + "\n"); } /** * Export data as XML to `outputPath`. * Items are wrapped in .... * Keys are turned into elements, properly escaped. */ async exportToXml( outputPath: string, opts?: DatasetExportOptions, ): Promise { const items = await this.getData(opts); const escapeXml = (v: unknown): string => { const s = v === null || v === undefined ? "" : String(v); return s .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); }; let xml = '\n\n'; for (const item of items) { xml += " \n"; for (const [k, v] of Object.entries(item)) { xml += ` <${k}>${escapeXml(v)}\n`; } xml += " \n"; } xml += "\n"; await Bun.write(outputPath, xml); } /** * Export data as a simple, pretty HTML table to `outputPath`. */ async exportToHtml( outputPath: string, opts?: DatasetExportOptions, ): Promise { const items = await this.getData(opts); if (items.length === 0) { await Bun.write( outputPath, "\n\n\n

No data

\n\n\n", ); return; } const headers = Object.keys(items[0]); const escapeHtml = (v: unknown): string => { const s = v === null || v === undefined ? "" : String(v); return s .replace(/&/g, "&") .replace(//g, ">"); }; let html = "\n\n\n\n\n\n"; html += "\n \n \n"; for (const h of headers) { html += ` \n`; } html += " \n \n \n"; for (const item of items) { html += " \n"; for (const h of headers) { html += ` \n`; } html += " \n"; } html += " \n
${escapeHtml(h)}
${escapeHtml(item[h])}
\n\n\n"; await Bun.write(outputPath, html); } /** * Export data as multiple JSON files in `outputDir`, matching legacy Apify/Crawlee local storage format. * Each item will be saved as `{index}.json` (starting at 000000001.json). */ async exportToDirectory( outputDir: string, opts?: DatasetExportOptions, ): Promise { const items = await this.getData(opts); const { mkdirSync, writeFileSync } = require("node:fs"); mkdirSync(outputDir, { recursive: true }); let idx = 1; for (const item of items) { const filename = `${String(idx).padStart(9, "0")}.json`; writeFileSync( join(outputDir, filename), JSON.stringify(item, null, 2), "utf8", ); idx++; } } /** * Export dataset items into a high-performance SQLite database with optional FTS5 full-text search. * Performs inserts in batched transactions for maximum I/O throughput. */ async exportToSqlite( outputPath: string, opts?: DatasetSqliteExportOptions, ): Promise<{ exported: number; path: string }> { const items = await this.getData(opts); const { Database } = await import("bun:sqlite"); const { dirname } = await import("node:path"); const { mkdirSync } = await import("node:fs"); const dir = dirname(outputPath); if (dir && dir !== ".") { mkdirSync(dir, { recursive: true }); } const db = new Database(outputPath); db.exec("PRAGMA journal_mode = WAL;"); db.exec("PRAGMA synchronous = NORMAL;"); db.exec("PRAGMA busy_timeout = 5000;"); const tableName = opts?.tableName ?? "items"; const enableFts = opts?.fts ?? true; db.exec(` CREATE TABLE IF NOT EXISTS "${tableName}" ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT UNIQUE, title TEXT, markdown TEXT, status INTEGER, metadata TEXT, data TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX IF NOT EXISTS "idx_${tableName}_url" ON "${tableName}"(url); `); if (enableFts) { try { db.exec(` CREATE VIRTUAL TABLE IF NOT EXISTS "${tableName}_fts" USING fts5(url, title, markdown); CREATE TRIGGER IF NOT EXISTS "trg_${tableName}_ai" AFTER INSERT ON "${tableName}" BEGIN INSERT INTO "${tableName}_fts"(rowid, url, title, markdown) VALUES (new.id, coalesce(new.url, ''), coalesce(new.title, ''), coalesce(new.markdown, '')); END; `); } catch { // Ignore if FTS5 table already exists or not supported } } const insertStmt = db.prepare(` INSERT INTO "${tableName}" (url, title, markdown, status, metadata, data) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(url) DO UPDATE SET title = excluded.title, markdown = excluded.markdown, status = excluded.status, metadata = excluded.metadata, data = excluded.data; `); const batchSize = opts?.batchSize ?? 500; const insertBatch = db.transaction((batch: DatasetItem[]) => { for (const item of batch) { const url = (item.url as string) || (item.link as string) || `item-${crypto.randomUUID()}`; const title = (item.title as string) || (item.name as string) || null; const markdown = (item.markdown as string) || (item.text as string) || (item.content as string) || null; const status = typeof item.status === "number" ? item.status : 200; const metadata = item.metadata ? JSON.stringify(item.metadata) : null; const data = JSON.stringify(item); insertStmt.run(url, title, markdown, status, metadata, data); } }); for (let i = 0; i < items.length; i += batchSize) { insertBatch(items.slice(i, i + batchSize)); } db.close(); return { exported: items.length, path: outputPath }; } /** * Export dataset items into a PostgreSQL database table with upserts and JSONB storage. * Powered by Bun's native high-performance SQL driver. */ async exportToPostgres( connectionUrl?: string, opts?: DatasetPostgresExportOptions, ): Promise<{ exported: number }> { const items = await this.getData(opts); if (items.length === 0) { return { exported: 0 }; } const { SQL } = await import("bun"); const url = connectionUrl || process.env.DATABASE_URL || process.env.APHRODY_PG_URL; if (!url) { throw new Error( "PostgreSQL export requires --pg-url, DATABASE_URL or APHRODY_PG_URL.", ); } const sql = new SQL(url); try { await sql` CREATE TABLE IF NOT EXISTS bxc_dataset_items ( id BIGSERIAL PRIMARY KEY, dataset_name TEXT NOT NULL, url TEXT, title TEXT, content TEXT, metadata JSONB, raw_data JSONB, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); CREATE UNIQUE INDEX IF NOT EXISTS idx_bxc_ds_url ON bxc_dataset_items(dataset_name, url); `; const batchSize = opts?.batchSize ?? 100; for (let i = 0; i < items.length; i += batchSize) { const batch = items.slice(i, i + batchSize); for (const item of batch) { const itemUrl = (item.url as string) || (item.link as string) || `item-${crypto.randomUUID()}`; const title = (item.title as string) || (item.name as string) || null; const content = (item.markdown as string) || (item.text as string) || (item.content as string) || null; const metadataJson = JSON.stringify(item.metadata || {}); const rawDataJson = JSON.stringify(item); await sql` INSERT INTO bxc_dataset_items (dataset_name, url, title, content, metadata, raw_data, updated_at) VALUES (${this.#name}, ${itemUrl}, ${title}, ${content}, ${metadataJson}::jsonb, ${rawDataJson}::jsonb, NOW()) ON CONFLICT (dataset_name, url) DO UPDATE SET title = EXCLUDED.title, content = EXCLUDED.content, metadata = EXCLUDED.metadata, raw_data = EXCLUDED.raw_data, updated_at = NOW(); `; } } return { exported: items.length }; } finally { sql.close(); } } // --------------------------------------------------------------------------- // Management // --------------------------------------------------------------------------- /** * Drop all data in this dataset (truncate both files). */ async clear(): Promise { await this.close(); await Bun.write(this.#dataPath, ""); this.#itemCount = 0; await this.#writeMeta(); } /** * Flush and close the underlying file writer. * Must be called before process exit to ensure all data is written. */ async close(): Promise { if (this.#writer !== null) { await this.#writer.end(); this.#writer = null; } } // --------------------------------------------------------------------------- // Private // --------------------------------------------------------------------------- async #writeMeta(): Promise { const meta: DatasetMeta = { name: this.#name, createdAt: new Date().toISOString(), itemCount: this.#itemCount, }; // Bun.write is atomic on POSIX (write to temp + rename under the hood) await Bun.write(this.#metaPath, JSON.stringify(meta, null, 2)); } }