shamela
Version:
Library to interact with the Maktabah Shamela v4 APIs
630 lines (576 loc) • 27.7 kB
JavaScript
import {createClient as $SK0tW$createClient} from "@libsql/client";
import {promises as $SK0tW$promises} from "node:fs";
import $SK0tW$nodepath from "node:path";
import $SK0tW$nodeprocess from "node:process";
import {URL as $SK0tW$URL} from "node:url";
import $SK0tW$pino from "pino";
import $SK0tW$pinopretty from "pino-pretty";
import $SK0tW$path from "path";
import {promises as $SK0tW$promises1, createWriteStream as $SK0tW$createWriteStream} from "fs";
import $SK0tW$https from "https";
import $SK0tW$os from "os";
import {pipeline as $SK0tW$pipeline} from "stream/promises";
import $SK0tW$unzipper from "unzipper";
import {Buffer as $SK0tW$Buffer} from "buffer";
import $SK0tW$process from "process";
import {URL as $SK0tW$URL1, URLSearchParams as $SK0tW$URLSearchParams} from "url";
const $526b48a37e8a8ec6$var$stream = (0, $SK0tW$pinopretty)({
colorize: true
});
const $526b48a37e8a8ec6$var$logger = (0, $SK0tW$pino)({
base: {
hostname: undefined,
pid: undefined
},
level: (0, $SK0tW$nodeprocess).env.LOG_LEVEL || 'info'
}, $526b48a37e8a8ec6$var$stream);
var $526b48a37e8a8ec6$export$2e2bcd8739ae039 = $526b48a37e8a8ec6$var$logger;
const $26460f21c4456828$export$1d57574773c8bc58 = async (db, dbName)=>{
const { rows: tables } = await db.execute(`SELECT name,sql FROM ${dbName}.sqlite_master WHERE type='table'`);
return tables.map((row)=>{
const fields = row.sql.split(', ').map((field)=>field.split(' ')[0]);
return {
fields: fields,
name: row.name
};
});
};
const $26460f21c4456828$export$3274d151f0598f1 = async (client, table)=>{
const { rows: rows } = await client.execute(`SELECT * FROM ${table}`);
return rows;
};
const $746504ca27eabe49$var$MAIN_DB_ALIAS = 'main';
const $746504ca27eabe49$export$ee56083bb7df7ecc = (dbFile, alias)=>`ATTACH DATABASE '${dbFile}' AS ${alias}`;
const $746504ca27eabe49$export$1f75c01d8a920a35 = (patchAlias, tableName, aslAlias = $746504ca27eabe49$var$MAIN_DB_ALIAS)=>`
UPDATE ${aslAlias}.${tableName}
SET content = ${$746504ca27eabe49$var$updatePageColumn('content', aslAlias, patchAlias)},
part = ${$746504ca27eabe49$var$updatePageColumn('part', aslAlias, patchAlias)},
page = ${$746504ca27eabe49$var$updatePageColumn('page', aslAlias, patchAlias)},
number = ${$746504ca27eabe49$var$updatePageColumn('number', aslAlias, patchAlias)}
WHERE EXISTS (
SELECT 1
FROM ${patchAlias}.${tableName}
WHERE ${aslAlias}.${tableName}.id = ${patchAlias}.${tableName}.id
);
`;
const $746504ca27eabe49$var$updateTitleColumn = (columnName, aslAlias, patchAlias)=>`
(SELECT CASE
WHEN ${patchAlias}.title.${columnName} != '#' THEN ${patchAlias}.title.${columnName}
ELSE ${aslAlias}.title.${columnName}
END
FROM ${patchAlias}.title
WHERE ${aslAlias}.title.id = ${patchAlias}.title.id)
`;
const $746504ca27eabe49$export$a38d1618b943c74f = (patchAlias, tableName, aslAlias = $746504ca27eabe49$var$MAIN_DB_ALIAS)=>`
UPDATE ${aslAlias}.${tableName}
SET content = ${$746504ca27eabe49$var$updateTitleColumn('content', aslAlias, patchAlias)},
page = ${$746504ca27eabe49$var$updateTitleColumn('page', aslAlias, patchAlias)},
parent = ${$746504ca27eabe49$var$updateTitleColumn('parent', aslAlias, patchAlias)}
WHERE EXISTS (
SELECT 1
FROM ${patchAlias}.${tableName}
WHERE ${aslAlias}.${tableName}.id = ${patchAlias}.${tableName}.id
);
`;
const $746504ca27eabe49$export$33bbb3ec7652e187 = (name, fields)=>`CREATE TABLE IF NOT EXISTS ${name} (${fields.join(', ')})`;
const $746504ca27eabe49$export$7fec5208c714b262 = (alias)=>`DETACH DATABASE ${alias}`;
const $746504ca27eabe49$var$updatePageColumn = (columnName, aslAlias, patchAlias)=>`
(SELECT CASE
WHEN ${patchAlias}.page.${columnName} != '#' THEN ${patchAlias}.page.${columnName}
ELSE ${aslAlias}.page.${columnName}
END
FROM ${patchAlias}.page
WHERE ${aslAlias}.page.id = ${patchAlias}.page.id)
`;
const $746504ca27eabe49$export$3ef07b9580a45514 = (table, fieldToValue, isDeleted = false)=>{
const combinedRecords = {
...fieldToValue,
is_deleted: isDeleted ? '1' : '0'
};
const sortedKeys = Object.keys(combinedRecords).sort();
const sortedValues = sortedKeys.map((key)=>combinedRecords[key]);
return `INSERT INTO ${table} (${sortedKeys.toString()}) VALUES (${sortedValues.map((val)=>{
if (val === null) return 'NULL';
return typeof val === 'string' ? `'${val}'` : val;
}).toString()})`;
};
var $e5a23c058b2763fa$export$a17a6870a08b950e = /*#__PURE__*/ function(Tables) {
Tables["Authors"] = "authors";
Tables["Books"] = "books";
Tables["Categories"] = "categories";
Tables["Page"] = "page";
Tables["Title"] = "title";
return Tables;
}({});
const $d7a7877f07ff6c69$var$PATCH_DB_ALIAS = 'patch';
const $d7a7877f07ff6c69$var$ASL_DB_ALIAS = 'asl';
const $d7a7877f07ff6c69$var$buildCopyStatements = (patchTables, aslTables, table, fields, patchQuery)=>{
const statements = [];
if (patchTables.find((t)=>t.name === table)) {
statements.push(`INSERT INTO main.${table}
SELECT ${fields.join(',')}
FROM ${$d7a7877f07ff6c69$var$ASL_DB_ALIAS}.${table}
WHERE id NOT IN (
SELECT id
FROM ${$d7a7877f07ff6c69$var$PATCH_DB_ALIAS}.${table}
WHERE is_deleted='1'
)`);
statements.push(patchQuery);
} else {
let copyStatement = `INSERT INTO main.${table} SELECT ${fields.join(',')} FROM ${$d7a7877f07ff6c69$var$ASL_DB_ALIAS}.${table}`;
if (aslTables.find((t)=>t.name === table)?.fields.includes('is_deleted')) copyStatement += ` WHERE is_deleted='0'`;
statements.push(copyStatement);
}
return statements;
};
const $d7a7877f07ff6c69$export$a8b8e03e6bbe5473 = async (db, aslDB, patchDB)=>{
await Promise.all([
db.execute((0, $746504ca27eabe49$export$ee56083bb7df7ecc)(aslDB, $d7a7877f07ff6c69$var$ASL_DB_ALIAS)),
db.execute((0, $746504ca27eabe49$export$ee56083bb7df7ecc)(patchDB, $d7a7877f07ff6c69$var$PATCH_DB_ALIAS))
]);
const [patchTables, aslTables] = await Promise.all([
(0, $26460f21c4456828$export$1d57574773c8bc58)(db, $d7a7877f07ff6c69$var$PATCH_DB_ALIAS),
(0, $26460f21c4456828$export$1d57574773c8bc58)(db, $d7a7877f07ff6c69$var$ASL_DB_ALIAS)
]);
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).debug({
aslTables: aslTables,
patchTables: patchTables
}, `Applying patches for...`);
await db.batch([
...$d7a7877f07ff6c69$var$buildCopyStatements(patchTables, aslTables, (0, $e5a23c058b2763fa$export$a17a6870a08b950e).Page, [
'id',
'content',
'part',
'page',
'number'
], (0, $746504ca27eabe49$export$1f75c01d8a920a35)($d7a7877f07ff6c69$var$PATCH_DB_ALIAS, (0, $e5a23c058b2763fa$export$a17a6870a08b950e).Page)),
...$d7a7877f07ff6c69$var$buildCopyStatements(patchTables, aslTables, (0, $e5a23c058b2763fa$export$a17a6870a08b950e).Title, [
'id',
'content',
'page',
'parent'
], (0, $746504ca27eabe49$export$a38d1618b943c74f)($d7a7877f07ff6c69$var$PATCH_DB_ALIAS, (0, $e5a23c058b2763fa$export$a17a6870a08b950e).Title))
]);
return db.batch([
(0, $746504ca27eabe49$export$7fec5208c714b262)($d7a7877f07ff6c69$var$ASL_DB_ALIAS),
(0, $746504ca27eabe49$export$7fec5208c714b262)($d7a7877f07ff6c69$var$PATCH_DB_ALIAS)
]);
};
const $d7a7877f07ff6c69$export$61101aa23c771e7c = async (db, aslDB)=>{
await db.execute((0, $746504ca27eabe49$export$ee56083bb7df7ecc)(aslDB, $d7a7877f07ff6c69$var$ASL_DB_ALIAS));
const tables = await (0, $26460f21c4456828$export$1d57574773c8bc58)(db, $d7a7877f07ff6c69$var$ASL_DB_ALIAS);
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).debug({
tables: tables
}, `copyTableData...`);
await db.batch([
`INSERT INTO main.${(0, $e5a23c058b2763fa$export$a17a6870a08b950e).Title} SELECT id,content,page,parent FROM ${$d7a7877f07ff6c69$var$ASL_DB_ALIAS}.${(0, $e5a23c058b2763fa$export$a17a6870a08b950e).Title}`,
`INSERT INTO main.${(0, $e5a23c058b2763fa$export$a17a6870a08b950e).Page} SELECT id,content,part,page,number FROM ${$d7a7877f07ff6c69$var$ASL_DB_ALIAS}.${(0, $e5a23c058b2763fa$export$a17a6870a08b950e).Page}`
]);
return db.execute((0, $746504ca27eabe49$export$7fec5208c714b262)($d7a7877f07ff6c69$var$ASL_DB_ALIAS));
};
const $d7a7877f07ff6c69$export$5d28a6b0dd65e4c4 = async (db)=>{
return db.batch([
`CREATE TABLE page (id INTEGER PRIMARY KEY, content TEXT, part INTEGER, page INTEGER, number INTEGER)`,
`CREATE TABLE title (id INTEGER PRIMARY KEY, content TEXT, page INTEGER, parent INTEGER)`
]);
};
const $d7a7877f07ff6c69$export$3bd13330ac8e761e = async (db)=>{
const rows = await (0, $26460f21c4456828$export$3274d151f0598f1)(db, (0, $e5a23c058b2763fa$export$a17a6870a08b950e).Page);
const pages = rows.map((row)=>{
const { content: content, id: id, number: number, page: page, part: part } = row;
return {
content: content,
id: id,
...page && {
page: page
},
...number && {
number: number
},
...part && {
part: part
}
};
});
return pages;
};
const $d7a7877f07ff6c69$export$8987cf231214301f = async (db)=>{
const rows = await (0, $26460f21c4456828$export$3274d151f0598f1)(db, (0, $e5a23c058b2763fa$export$a17a6870a08b950e).Title);
const titles = rows.map((row)=>{
const r = row;
return {
content: r.content,
id: r.id,
page: r.page,
...r.parent && {
number: r.parent
}
};
});
return titles;
};
const $d7a7877f07ff6c69$export$7a171f172be0782e = async (db)=>{
const [pages, titles] = await Promise.all([
$d7a7877f07ff6c69$export$3bd13330ac8e761e(db),
$d7a7877f07ff6c69$export$8987cf231214301f(db)
]);
return {
pages: pages,
titles: titles
};
};
const $1857efaf39b32304$export$5bc725975f47e62c = 0;
const $1857efaf39b32304$export$3deaf0b0365f781e = '99999';
const $09a9521c7a529893$export$b3179f41dfd6e35b = async (db, sourceTables)=>{
const aliasToPath = sourceTables.reduce((acc, tablePath)=>{
const { name: name } = (0, $SK0tW$path).parse(tablePath);
return {
...acc,
[name]: tablePath
};
}, {});
const attachStatements = Object.entries(aliasToPath).map(([alias, dbPath])=>(0, $746504ca27eabe49$export$ee56083bb7df7ecc)(dbPath, alias));
await db.batch(attachStatements);
const insertStatements = [
`INSERT INTO ${(0, $e5a23c058b2763fa$export$a17a6870a08b950e).Authors} SELECT id,name,biography,(CASE WHEN death_number = ${(0, $1857efaf39b32304$export$3deaf0b0365f781e)} THEN NULL ELSE death_number END) AS death_number FROM author WHERE is_deleted='0'`,
`INSERT INTO ${(0, $e5a23c058b2763fa$export$a17a6870a08b950e).Books} SELECT id,name,category,type,(CASE WHEN date = ${(0, $1857efaf39b32304$export$3deaf0b0365f781e)} THEN NULL ELSE date END) AS date,author,printed,major_release,minor_release,bibliography,hint,pdf_links,metadata FROM book WHERE is_deleted='0'`,
`INSERT INTO ${(0, $e5a23c058b2763fa$export$a17a6870a08b950e).Categories} SELECT id,name FROM category WHERE is_deleted='0'`
];
await db.batch(insertStatements);
const detachStatements = Object.keys(aliasToPath).map((0, $746504ca27eabe49$export$7fec5208c714b262));
await db.batch(detachStatements);
};
const $09a9521c7a529893$export$5d28a6b0dd65e4c4 = async (db)=>{
return db.batch([
`CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT, biography TEXT, death INTEGER)`,
`CREATE TABLE books (id INTEGER PRIMARY KEY, name TEXT, category INTEGER, type INTEGER, date INTEGER, author TEXT, printed INTEGER, major INTEGER, minor INTEGER, bibliography TEXT, hint TEXT, pdf_links TEXT, metadata TEXT)`,
`CREATE TABLE categories (id INTEGER PRIMARY KEY, name TEXT)`
]);
};
const $09a9521c7a529893$export$b3b931905baa18df = async (db)=>{
const rows = await (0, $26460f21c4456828$export$3274d151f0598f1)(db, (0, $e5a23c058b2763fa$export$a17a6870a08b950e).Authors);
const authors = rows.map((r)=>({
...r.biography && {
biography: r.biography
},
...r.death && {
death: r.death
},
id: r.id,
name: r.name
}));
return authors;
};
const $09a9521c7a529893$export$7111c27bf38a004f = async (db)=>{
const rows = await (0, $26460f21c4456828$export$3274d151f0598f1)(db, (0, $e5a23c058b2763fa$export$a17a6870a08b950e).Books);
const books = rows.map((row)=>{
const r = row;
return {
author: $09a9521c7a529893$var$parseAuthor(r.author),
bibliography: r.bibliography,
category: r.category,
id: r.id,
major: r.major,
metadata: JSON.parse(r.metadata),
name: r.name,
printed: r.printed,
type: r.type,
...r.date && r.date.toString() !== (0, $1857efaf39b32304$export$3deaf0b0365f781e) && {
date: r.date
},
...r.hint && {
hint: r.hint
},
...r.pdf_links && {
pdfLinks: $09a9521c7a529893$var$parsePdfLinks(r.pdf_links)
},
...r.minor && {
minorRelease: r.minor
}
};
});
return books;
};
const $09a9521c7a529893$export$36bfd9279b3a24b7 = async (db)=>{
const rows = await (0, $26460f21c4456828$export$3274d151f0598f1)(db, (0, $e5a23c058b2763fa$export$a17a6870a08b950e).Categories);
const categories = rows.map((r)=>({
id: r.id,
name: r.name
}));
return categories;
};
const $09a9521c7a529893$var$parseAuthor = (value)=>{
const result = value.split(',\\s+').map((id)=>parseInt(id.trim()));
return result.length > 1 ? result : result[0];
};
const $09a9521c7a529893$var$parsePdfLinks = (value)=>{
const result = JSON.parse(value);
if (result.files) result.files = result.files.map((f)=>{
const [file, id] = f.split('|');
return {
...id && {
id: id
},
file: file
};
});
return result;
};
const $09a9521c7a529893$export$7a171f172be0782e = async (db)=>{
const [authors, books, categories] = await Promise.all([
$09a9521c7a529893$export$b3b931905baa18df(db),
$09a9521c7a529893$export$7111c27bf38a004f(db),
$09a9521c7a529893$export$36bfd9279b3a24b7(db)
]);
return {
authors: authors,
books: books,
categories: categories
};
};
const $fd2c9bc034ddc705$export$1c500f521ad591da = async (prefix = 'shamela')=>{
const tempDirBase = (0, $SK0tW$path).join((0, $SK0tW$os).tmpdir(), prefix);
return (0, $SK0tW$promises1).mkdtemp(tempDirBase);
};
const $fd2c9bc034ddc705$export$ffc21166d570a16 = async (path)=>!!await (0, $SK0tW$promises1).stat(path).catch(()=>false);
async function $fd2c9bc034ddc705$export$fb61e277af91ac0(url, outputDir) {
const extractedFiles = [];
const entryPromises = [];
try {
// Make HTTPS request and get the response stream
const response = await new Promise((resolve, reject)=>{
(0, $SK0tW$https).get(url, (res)=>{
if (res.statusCode !== 200) reject(new Error(`Failed to download ZIP file: ${res.statusCode} ${res.statusMessage}`));
else resolve(res);
}).on('error', (err)=>{
reject(new Error(`HTTPS request failed: ${err.message}`));
});
});
// Create unzip stream
const unzipStream = (0, $SK0tW$unzipper).Parse();
// Handle entries in the ZIP file
unzipStream.on('entry', (entry)=>{
const entryPromise = (async ()=>{
const filePath = (0, $SK0tW$path).join(outputDir, entry.path);
if (entry.type === 'Directory') {
// Ensure the directory exists
await (0, $SK0tW$promises1).mkdir(filePath, {
recursive: true
});
entry.autodrain();
} else {
// Ensure the parent directory exists
const dir = (0, $SK0tW$path).dirname(filePath);
await (0, $SK0tW$promises1).mkdir(dir, {
recursive: true
});
// Pipe the entry to a file
await (0, $SK0tW$pipeline)(entry, (0, $SK0tW$createWriteStream)(filePath));
extractedFiles.push(filePath);
}
})().catch((err)=>{
// Emit errors to be handled by the unzipStream error handler
unzipStream.emit('error', err);
});
// Collect the promises
entryPromises.push(entryPromise);
});
// Handle errors in the unzip stream
unzipStream.on('error', (err)=>{
throw new Error(`Error during extraction: ${err.message}`);
});
// Pipe the response into the unzip stream
await (0, $SK0tW$pipeline)(response, unzipStream);
// Wait for all entry promises to complete
await Promise.all(entryPromises);
return extractedFiles;
} catch (error) {
throw new Error(`Error processing URL: ${error.message}`);
}
}
const $59b98b7fd5edf160$export$b5cd97dee32de81d = (endpoint, queryParams, useAuth = true)=>{
const url = new (0, $SK0tW$URL1)(endpoint);
{
const params = new (0, $SK0tW$URLSearchParams)();
Object.entries(queryParams).forEach(([key, value])=>{
params.append(key, value.toString());
});
if (useAuth) params.append('api_key', (0, $SK0tW$process).env.SHAMELA_API_KEY);
url.search = params.toString();
}
return url;
};
const $59b98b7fd5edf160$export$c9e6217566c54f42 = (url)=>{
return new Promise((resolve, reject)=>{
(0, $SK0tW$https).get(url, (res)=>{
const contentType = res.headers['content-type'] || '';
const dataChunks = [];
res.on('data', (chunk)=>{
dataChunks.push(chunk);
});
res.on('end', ()=>{
const fullData = (0, $SK0tW$Buffer).concat(dataChunks);
if (contentType.includes('application/json')) try {
const json = JSON.parse(fullData.toString('utf-8'));
resolve(json);
} catch (error) {
reject(new Error(`Failed to parse JSON: ${error.message}`));
}
else resolve(fullData);
});
}).on('error', (error)=>{
reject(new Error(`Error making request: ${error.message}`));
});
});
};
const $6605706916cc9c29$var$SOURCE_TABLES = [
'author.sqlite',
'book.sqlite',
'category.sqlite'
];
const $6605706916cc9c29$export$37467b7f8cfc50b0 = ()=>{
if (!(0, $SK0tW$process).env.SHAMELA_API_MASTER_PATCH_ENDPOINT) throw new Error('SHAMELA_API_MASTER_PATCH_ENDPOINT environment variable not set');
if (!(0, $SK0tW$process).env.SHAMELA_API_KEY) throw new Error('SHAMELA_API_KEY environment variable not set');
};
const $6605706916cc9c29$export$c7660b0cda39b7c3 = (sourceTablePaths)=>{
const sourceTableNames = sourceTablePaths.map((tablePath)=>(0, $SK0tW$path).parse(tablePath).base);
return $6605706916cc9c29$var$SOURCE_TABLES.every((table)=>sourceTableNames.includes(table));
};
const $e6ba238abdbefe7a$var$fixHttpsProtocol = (originalUrl)=>{
const url = new (0, $SK0tW$URL)(originalUrl);
url.protocol = 'https';
return url.toString();
};
const $e6ba238abdbefe7a$export$4c209aa17b4b3e57 = async (id, options)=>{
(0, $6605706916cc9c29$export$37467b7f8cfc50b0)();
const url = (0, $59b98b7fd5edf160$export$b5cd97dee32de81d)(`${(0, $SK0tW$nodeprocess).env.SHAMELA_API_BOOKS_ENDPOINT}/${id}`, {
major_release: (options?.majorVersion || 0).toString(),
minor_release: (options?.minorVersion || 0).toString()
});
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`Fetching shamela.ws book link: ${url.toString()}`);
try {
const response = await (0, $59b98b7fd5edf160$export$c9e6217566c54f42)(url);
return {
majorRelease: response.major_release,
majorReleaseUrl: $e6ba238abdbefe7a$var$fixHttpsProtocol(response.major_release_url),
...response.minor_release_url && {
minorReleaseUrl: $e6ba238abdbefe7a$var$fixHttpsProtocol(response.minor_release_url)
},
...response.minor_release_url && {
minorRelease: response.minor_release
}
};
} catch (error) {
throw new Error(`Error fetching master patch: ${error.message}`);
}
};
const $e6ba238abdbefe7a$export$3560c45fd9de930d = async (id, options)=>{
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`downloadBook ${id} ${JSON.stringify(options)}`);
const outputDir = await (0, $fd2c9bc034ddc705$export$1c500f521ad591da)('shamela_downloadBook');
const bookResponse = options?.bookMetadata || await $e6ba238abdbefe7a$export$4c209aa17b4b3e57(id);
const [[bookDatabase], [patchDatabase] = []] = await Promise.all([
(0, $fd2c9bc034ddc705$export$fb61e277af91ac0)(bookResponse.majorReleaseUrl, outputDir),
...bookResponse.minorReleaseUrl ? [
(0, $fd2c9bc034ddc705$export$fb61e277af91ac0)(bookResponse.minorReleaseUrl, outputDir)
] : []
]);
const dbPath = (0, $SK0tW$nodepath).join(outputDir, 'book.db');
const client = (0, $SK0tW$createClient)({
url: `file:${dbPath}`
});
try {
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`Creating tables`);
await (0, $d7a7877f07ff6c69$export$5d28a6b0dd65e4c4)(client);
if (patchDatabase) {
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`Applying patches from ${patchDatabase} to ${bookDatabase}`);
await (0, $d7a7877f07ff6c69$export$a8b8e03e6bbe5473)(client, bookDatabase, patchDatabase);
} else {
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`Copying table data from ${bookDatabase}`);
await (0, $d7a7877f07ff6c69$export$61101aa23c771e7c)(client, bookDatabase);
}
const { ext: extension } = (0, $SK0tW$nodepath).parse(options.outputFile.path);
if (extension === '.json') {
const result = await (0, $d7a7877f07ff6c69$export$7a171f172be0782e)(client);
await (0, $SK0tW$promises).writeFile(options.outputFile.path, JSON.stringify(result, undefined, 2), 'utf8');
}
client.close();
if (extension === '.db' || extension === '.sqlite') await (0, $SK0tW$promises).rename(dbPath, options.outputFile.path);
await (0, $SK0tW$promises).rm(outputDir, {
recursive: true
});
} finally{
client.close();
}
return options.outputFile.path;
};
const $e6ba238abdbefe7a$export$b96de494209cdc35 = async (version = 0)=>{
(0, $6605706916cc9c29$export$37467b7f8cfc50b0)();
const url = (0, $59b98b7fd5edf160$export$b5cd97dee32de81d)((0, $SK0tW$nodeprocess).env.SHAMELA_API_MASTER_PATCH_ENDPOINT, {
version: version.toString()
});
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`Fetching shamela.ws master database patch link: ${url.toString()}`);
try {
const response = await (0, $59b98b7fd5edf160$export$c9e6217566c54f42)(url);
return {
url: response.patch_url,
version: response.version
};
} catch (error) {
throw new Error(`Error fetching master patch: ${error.message}`);
}
};
const $e6ba238abdbefe7a$export$52a3cb82930b902c = (bookId)=>{
const { host: host } = new (0, $SK0tW$URL)((0, $SK0tW$nodeprocess).env.SHAMELA_API_MASTER_PATCH_ENDPOINT);
return `${host}/covers/${bookId}.jpg`;
};
const $e6ba238abdbefe7a$export$fd8b6353fde3f1de = async (options)=>{
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`downloadMasterDatabase ${JSON.stringify(options)}`);
const outputDir = await (0, $fd2c9bc034ddc705$export$1c500f521ad591da)('shamela_downloadMaster');
const masterResponse = options.masterMetadata || await $e6ba238abdbefe7a$export$b96de494209cdc35((0, $1857efaf39b32304$export$5bc725975f47e62c));
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`Downloading master database from: ${JSON.stringify(masterResponse)}`);
const sourceTables = await (0, $fd2c9bc034ddc705$export$fb61e277af91ac0)($e6ba238abdbefe7a$var$fixHttpsProtocol(masterResponse.url), outputDir);
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`sourceTables downloaded: ${sourceTables.toString()}`);
if (!(0, $6605706916cc9c29$export$c7660b0cda39b7c3)(sourceTables)) {
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).error(`Some source tables were not found: ${sourceTables.toString()}`);
throw new Error('Expected tables not found!');
}
const dbPath = (0, $SK0tW$nodepath).join(outputDir, 'master.db');
const client = (0, $SK0tW$createClient)({
url: `file:${dbPath}`
});
try {
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`Creating tables`);
await (0, $09a9521c7a529893$export$5d28a6b0dd65e4c4)(client);
(0, $526b48a37e8a8ec6$export$2e2bcd8739ae039).info(`Copying data to master table`);
await (0, $09a9521c7a529893$export$b3179f41dfd6e35b)(client, sourceTables);
const { ext: extension } = (0, $SK0tW$nodepath).parse(options.outputFile.path);
if (extension === '.json') {
const result = await (0, $09a9521c7a529893$export$7a171f172be0782e)(client);
await (0, $SK0tW$promises).writeFile(options.outputFile.path, JSON.stringify(result, undefined, 2), 'utf8');
}
client.close();
if (extension === '.db' || extension === '.sqlite') await (0, $SK0tW$promises).rename(dbPath, options.outputFile.path);
await (0, $SK0tW$promises).rm(outputDir, {
recursive: true
});
} finally{
client.close();
}
return options.outputFile.path;
};
const $e6ba238abdbefe7a$export$be7c2acc48adceee = async (id)=>{
const outputDir = await (0, $fd2c9bc034ddc705$export$1c500f521ad591da)('shamela_getBookData');
const outputPath = await $e6ba238abdbefe7a$export$3560c45fd9de930d(id, {
outputFile: {
path: (0, $SK0tW$nodepath).join(outputDir, `${id}.json`)
}
});
const data = JSON.parse(await (0, $SK0tW$promises).readFile(outputPath, 'utf8'));
await (0, $SK0tW$promises).rm(outputDir, {
recursive: true
});
return data;
};
var $e9528ebec83086b6$exports = {};
export {$e6ba238abdbefe7a$export$3560c45fd9de930d as downloadBook, $e6ba238abdbefe7a$export$fd8b6353fde3f1de as downloadMasterDatabase, $e6ba238abdbefe7a$export$be7c2acc48adceee as getBook, $e6ba238abdbefe7a$export$4c209aa17b4b3e57 as getBookMetadata, $e6ba238abdbefe7a$export$b96de494209cdc35 as getMasterMetadata};
//# sourceMappingURL=main.js.map