UNPKG

shamela

Version:

Library to interact with the Maktabah Shamela v4 APIs

227 lines (226 loc) 10.8 kB
import { _ as TitleSpanStrategy, a as DownloadBookOptions, c as GetBookMetadataResponsePayload, d as NormalizeTitleSpanOptions, f as OutputOptions, g as Title, h as ShamelaConfigKey, i as Category, l as GetMasterMetadataResponsePayload, m as ShamelaConfig, n as Book, o as DownloadMasterOptions, p as Page, r as BookData, s as GetBookMetadataOptions, t as Author, u as MasterData } from "./types-CeDA67OZ.js"; import { Line, convertContentToMarkdown, htmlToMarkdown, mapPageCharacterContent, moveContentAfterLineBreakIntoSpan, normalizeHtml, normalizeLineEndings, normalizeTitleSpans, parseContentRobust, removeArabicNumericPageMarkers, removeTagsExceptSpan, splitPageBodyFromFooter, stripHtmlTags } from "./content.js"; import { BookMetadata, DenormalizedAuthor, DenormalizedBook, DenormalizedCategory, denormalizeBooks } from "./transform.js"; import { DEFAULT_MAPPING_RULES, DEFAULT_MASTER_METADATA_VERSION, FOOTNOTE_MARKER, FOREWORD_MARKER, UNKNOWN_VALUE_PLACEHOLDER } from "./utils/constants.js"; //#region src/api.d.ts /** * Retrieves metadata for a specific book from the Shamela API. * * This function fetches book release information including major and minor release * URLs and version numbers from the Shamela web service. * * @param id - The unique identifier of the book to fetch metadata for * @param options - Optional parameters for specifying major and minor versions * @returns A promise that resolves to book metadata including release URLs and versions * * @throws {Error} When environment variables are not set or API request fails * * @example * ```typescript * const metadata = await getBookMetadata(123, { majorVersion: 1, minorVersion: 2 }); * console.log(metadata.majorReleaseUrl); // Download URL for the book * ``` */ declare const getBookMetadata: (id: number, options?: GetBookMetadataOptions) => Promise<GetBookMetadataResponsePayload>; /** * Downloads and processes a book from the Shamela database. * * This function downloads the book's database files, applies patches if available, * creates the necessary database tables, and exports the data to the specified format. * The output can be either a JSON file or a SQLite database file. * * @param id - The unique identifier of the book to download * @param options - Configuration options including output file path and optional book metadata * @returns A promise that resolves to the path of the created output file * * @throws {Error} When download fails, database operations fail, or file operations fail * * @example * ```typescript * // Download as JSON * const jsonPath = await downloadBook(123, { * outputFile: { path: './book.json' } * }); * * // Download as SQLite database * const dbPath = await downloadBook(123, { * outputFile: { path: './book.db' } * }); * ``` */ declare const downloadBook: (id: number, options: DownloadBookOptions) => Promise<string>; /** * Retrieves metadata for the master database from the Shamela API. * * The master database contains information about all books, authors, and categories * in the Shamela library. This function fetches the download URL and version * information for the master database patches. * * @param version - The version number to check for updates (defaults to 0) * @returns A promise that resolves to master database metadata including download URL and version * * @throws {Error} When environment variables are not set or API request fails * * @example * ```typescript * const masterMetadata = await getMasterMetadata(5); * console.log(masterMetadata.url); // URL to download master database patch * console.log(masterMetadata.version); // Latest version number * ``` */ declare const getMasterMetadata: (version?: number) => Promise<GetMasterMetadataResponsePayload>; /** * Generates the URL for a book's cover image. * * This function constructs the URL to access the cover image for a specific book * using the book's ID and the API endpoint host. * * @param bookId - The unique identifier of the book * @returns The complete URL to the book's cover image * * @example * ```typescript * const coverUrl = getCoverUrl(123); * console.log(coverUrl); // "https://api.shamela.ws/covers/123.jpg" * ``` */ declare const getCoverUrl: (bookId: number) => string; /** * Downloads and processes the master database from the Shamela service. * * The master database contains comprehensive information about all books, authors, * and categories available in the Shamela library. This function downloads the * database files, creates the necessary tables, and exports the data in the * specified format (JSON or SQLite). * * @param options - Configuration options including output file path and optional master metadata * @returns A promise that resolves to the path of the created output file * * @throws {Error} When download fails, expected tables are missing, database operations fail, or file operations fail * * @example * ```typescript * // Download master database as JSON * const jsonPath = await downloadMasterDatabase({ * outputFile: { path: './master.json' } * }); * * // Download master database as SQLite * const dbPath = await downloadMasterDatabase({ * outputFile: { path: './master.db' } * }); * ``` */ declare const downloadMasterDatabase: (options: DownloadMasterOptions) => Promise<string>; /** * Retrieves complete book data including pages and titles. * * This is a convenience function that downloads a book's data and returns it * as a structured JavaScript object. The function handles the temporary file * creation and cleanup automatically. * * @param id - The unique identifier of the book to retrieve * @returns A promise that resolves to the complete book data including pages and titles * * @throws {Error} When download fails, file operations fail, or JSON parsing fails * * @example * ```typescript * const bookData = await getBook(123); * console.log(bookData.pages.length); // Number of pages in the book * console.log(bookData.titles?.length); // Number of title entries * ``` */ declare const getBook: (id: number) => Promise<BookData>; /** * Retrieves complete master data including authors, books, and categories. * * This convenience function downloads the master database archive, builds an in-memory * SQLite database, and returns structured data for immediate consumption alongside * the version number of the snapshot. * * @param forceVersion - Optional version number to fetch a specific master database snapshot (defaults to DEFAULT_MASTER_METADATA_VERSION) * @returns A promise that resolves to the complete master dataset and its version */ declare const getMaster: (forceVersion?: number) => Promise<MasterData>; //#endregion //#region src/utils/logger.d.ts /** * Signature accepted by logger methods. */ type LogFunction = (...args: unknown[]) => void; /** * Contract expected from logger implementations consumed by the library. */ interface Logger { debug: LogFunction; error: LogFunction; info: LogFunction; warn: LogFunction; } //#endregion //#region src/config.d.ts /** * Runtime configuration options accepted by {@link configure}. */ type ConfigureOptions = Partial<ShamelaConfig> & { logger?: Logger; }; /** * Updates the runtime configuration for the library. * * This function merges the provided options with existing overrides and optionally * configures a custom logger implementation. * * @param config - Runtime configuration overrides and optional logger instance */ declare const configure: (config: ConfigureOptions) => void; /** * Retrieves a single configuration value. * * @param key - The configuration key to read * @returns The configuration value when available */ declare const getConfigValue: <Key extends ShamelaConfigKey>(key: Key) => ShamelaConfig[Key]; /** * Resolves the current configuration by combining runtime overrides and environment variables. * * @returns The resolved {@link ShamelaConfig} */ declare const getConfig: () => ShamelaConfig; /** * Retrieves a configuration value and throws if it is missing. * * @param key - The configuration key to require * @throws {Error} If the configuration value is not defined * @returns The resolved configuration value */ declare const requireConfigValue: <Key extends Exclude<ShamelaConfigKey, "fetchImplementation">>(key: Key) => NonNullable<ShamelaConfig[Key]>; /** * Clears runtime configuration overrides and restores the default logger. */ declare const resetConfig: () => void; //#endregion //#region src/utils/network.d.ts /** * Builds a URL with query parameters and optional authentication. * @param {string} endpoint - The base endpoint URL * @param {Record<string, any>} queryParams - Object containing query parameters to append * @param {boolean} [useAuth=true] - Whether to include the API key from environment variables * @returns {URL} The constructed URL object with query parameters */ declare const buildUrl: (endpoint: string, queryParams: Record<string, any>, useAuth?: boolean) => URL; /** * Makes an HTTPS GET request and returns the response data using the configured fetch implementation. * @template T - The expected return type (Buffer or Record<string, any>) * @param {string | URL} url - The URL to make the request to * @param options - Optional overrides including a custom fetch implementation * @returns {Promise<T>} A promise that resolves to the response data, parsed as JSON if content-type is application/json, otherwise as Buffer * @throws {Error} When the request fails or JSON parsing fails */ declare const httpsGet: <T extends Uint8Array | Record<string, any>>(url: string | URL, options?: { fetchImpl?: typeof fetch; }) => Promise<T>; //#endregion export { Author, Book, BookData, BookMetadata, Category, type ConfigureOptions, DEFAULT_MAPPING_RULES, DEFAULT_MASTER_METADATA_VERSION, DenormalizedAuthor, DenormalizedBook, DenormalizedCategory, DownloadBookOptions, DownloadMasterOptions, FOOTNOTE_MARKER, FOREWORD_MARKER, GetBookMetadataOptions, GetBookMetadataResponsePayload, GetMasterMetadataResponsePayload, Line, type Logger, MasterData, NormalizeTitleSpanOptions, OutputOptions, Page, ShamelaConfig, ShamelaConfigKey, Title, TitleSpanStrategy, UNKNOWN_VALUE_PLACEHOLDER, buildUrl, configure, convertContentToMarkdown, denormalizeBooks, downloadBook, downloadMasterDatabase, getBook, getBookMetadata, getConfig, getConfigValue, getCoverUrl, getMaster, getMasterMetadata, htmlToMarkdown, httpsGet, mapPageCharacterContent, moveContentAfterLineBreakIntoSpan, normalizeHtml, normalizeLineEndings, normalizeTitleSpans, parseContentRobust, removeArabicNumericPageMarkers, removeTagsExceptSpan, requireConfigValue, resetConfig, splitPageBodyFromFooter, stripHtmlTags }; //# sourceMappingURL=index.d.ts.map