/** * 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. */ import { type CommonOptions, logger, EXIT } from "./shared.ts"; import { Dataset } from "../storage/Dataset.ts"; function printUsage(): void { Bun.stdout.write( `bxc export — Export crawled dataset items to SQLite, PostgreSQL, JSON, CSV, or HTML. Usage: bxc export [dataset_name] [options] Destinations: --to Export target: sqlite | postgres | json | csv | xml | html (default: sqlite) --out Output file path (required for sqlite, json, csv, xml, html) --pg-url PostgreSQL connection URL (or env APHRODY_PG_URL / DATABASE_URL) --table Target database table name (default: "items" or "bxc_dataset_items") --no-fts Disable FTS5 virtual table when exporting to SQLite --limit Maximum items to export --offset Offset items from beginning Examples: bxc export default --to sqlite --out ./crawled_data.sqlite bxc export default --to postgres --pg-url postgresql://user:pass@localhost:5432/db bxc export products --to json --out ./products.json `, ); } export async function main( argv: string[], baseOpts: CommonOptions, cliOptions?: { exitProcess?: boolean }, ): Promise { const exitProcess = cliOptions?.exitProcess ?? process.env.NODE_ENV !== "test"; let datasetName = "default"; let target: "sqlite" | "postgres" | "json" | "csv" | "xml" | "html" = "sqlite"; let outputPath: string | undefined; let pgUrl: string | undefined; let tableName: string | undefined; let storageDir: string | undefined; let fts = true; let limit: number | undefined; let offset: number | undefined; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg === "--to") { const val = argv[++i]?.toLowerCase(); if (val === "sqlite" || val === "postgres" || val === "json" || val === "csv" || val === "xml" || val === "html") { target = val; } else { logger.error(`Invalid --to target: ${val}`); if (exitProcess) process.exit(EXIT.MISUSE); return; } } else if (arg === "--out") { outputPath = argv[++i]; } else if (arg === "--pg-url") { pgUrl = argv[++i]; } else if (arg === "--storage-dir") { storageDir = argv[++i]; } else if (arg === "--table") { tableName = argv[++i]; } else if (arg === "--no-fts") { fts = false; } else if (arg === "--limit") { limit = parseInt(argv[++i], 10); } else if (arg === "--offset") { offset = parseInt(argv[++i], 10); } else if (arg === "--help" || arg === "-h") { printUsage(); return; } else if (arg.startsWith("-")) { logger.error(`Unknown option: ${arg}`); printUsage(); if (exitProcess) process.exit(EXIT.MISUSE); return; } else { datasetName = arg; } } const ds = await Dataset.open(datasetName, { storageDir }); const count = ds.getItemCount(); logger.log(`[export] Exporting dataset "${datasetName}" (${count} items) to ${target}...`); try { if (target === "sqlite") { const out = outputPath ?? `./${datasetName}.sqlite`; const res = await ds.exportToSqlite(out, { tableName, fts, limit, offset }); logger.log(`[export] Successfully exported ${res.exported} items to SQLite database: ${res.path}`); } else if (target === "postgres") { const res = await ds.exportToPostgres(pgUrl, { tableName, limit, offset }); logger.log(`[export] Successfully exported ${res.exported} items to PostgreSQL`); } else if (target === "json") { const out = outputPath ?? `./${datasetName}.json`; await ds.exportToJson(out, { limit, offset }); logger.log(`[export] Successfully exported JSON to: ${out}`); } else if (target === "csv") { const out = outputPath ?? `./${datasetName}.csv`; await ds.exportToCsv(out, { limit, offset }); logger.log(`[export] Successfully exported CSV to: ${out}`); } else if (target === "xml") { const out = outputPath ?? `./${datasetName}.xml`; await ds.exportToXml(out, { limit, offset }); logger.log(`[export] Successfully exported XML to: ${out}`); } else if (target === "html") { const out = outputPath ?? `./${datasetName}.html`; await ds.exportToHtml(out, { limit, offset }); logger.log(`[export] Successfully exported HTML to: ${out}`); } } catch (err) { logger.error(`[export] Export failed: ${err}`); if (exitProcess) process.exit(EXIT.SOFTWARE); throw err; } finally { await ds.close(); } }