### Install All Project Dependencies Source: https://github.com/stepbible/bibleengine/blob/master/README.md Run this command after cloning the repository to install all necessary Node.js packages for the project. ```bash yarn install ``` -------------------------------- ### Start Docker Compose for Local Database Source: https://github.com/stepbible/bibleengine/blob/master/README.md Use this command to start a local PostgreSQL database for testing and development. Ensure Docker and Docker Compose are installed. ```bash docker-compose up postgres-db ``` -------------------------------- ### REST API Server Endpoints Source: https://context7.com/stepbible/bibleengine/llms.txt Examples of using curl to interact with the BibleEngine REST API server. Covers endpoints for retrieving versions, books, chapter data, search results, and dictionary entries. ```bash # List all versions curl https://api.example.com/bible/versions # Get a single version curl https://api.example.com/bible/versions/ESV # Get books for a version curl https://api.example.com/bible/versions/ESV/books # Get section structure for a book (table of contents) curl https://api.example.com/bible/sections/ESV/Gen # Get a full chapter curl https://api.example.com/bible/ref/ESV/Gen/1 # Get a single verse curl https://api.example.com/bible/ref/ESV/Jhn/3/16 # Get a verse range across chapters curl "https://api.example.com/bible/ref/ESV/Rom/3/23?chapterEnd=3&verseEnd=24" # Arbitrary reference range (POST) curl -X POST https://api.example.com/bible/ref \ -H 'Content-Type: application/json' \ -d '{"versionUid":"ESV","bookOsisId":"Psa","versionChapterNum":23}' # Dictionary — all entries for a Strong number curl https://api.example.com/bible/definitions/G26 # Dictionary — entry from a specific dictionary curl https://api.example.com/bible/definitions/H430/BDB # Full-text search (fuzzy, sorted by reference, page 1 of 50) curl "https://api.example.com/bible/search/ESV/love%20one%20another?queryMode=fuzzy&sortMode=reference&page=1&count=50" ``` -------------------------------- ### Get Bible Books for a Version Source: https://context7.com/stepbible/bibleengine/llms.txt Retrieves an ordered list of Bible book metadata for a specified version. Use the numeric ID or the string UID (preferred for client code). ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'sqlite', database: './bible.db' }); // Using the internal numeric ID const version = await engine.getVersion('ESV'); const books = await engine.getBooksForVersion(version!.id); books.forEach(b => console.log(`${b.osisId}: ${b.chaptersCount.length} chapters`)); // → Gen: 50 chapters, Exod: 40 chapters, ... // Using the string UID (preferred for client code) const booksKJV = await engine.getBooksForVersionUid('KJV'); console.log(booksKJV[0]!.title); // 'Genesis' ``` -------------------------------- ### Get Book Sections for a Version Source: https://context7.com/stepbible/bibleengine/llms.txt Retrieves the hierarchical section structure (headings) for a specific book, including version-relative chapter/verse range labels. Useful for generating a table of contents. ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'sqlite', database: './bible.db' }); const sections = await engine.getBookSectionsForVersionUid('ESV', 'Rom'); sections.forEach(section => { console.log(`[${section.rangeLabel}] ${section.title}`); // → [1:1-7] Greeting // → [1:8-17] Longing to Go to Rome section.subSections.forEach(sub => { console.log(` [${sub.rangeLabel}] ${sub.title}`); }); }); ``` -------------------------------- ### Get Dictionary Entries by Strong Number Source: https://context7.com/stepbible/bibleengine/llms.txt Looks up Strong's dictionary entries by Strong number and optional dictionary identifier. Returns morphological data, glosses, lemma, and transliteration. ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'sqlite', database: './bible.db' }); // All dictionary entries for a Strong number const entries = await engine.getDictionaryEntries('G26'); entries.forEach(e => { console.log(e.strong); // 'G26' console.log(e.dictionary); // 'TBESG' / 'BDB' etc. console.log(e.lemma); // 'ἀγάπη' console.log(e.gloss); // 'love' console.log(e.transliteration); // 'agapē' }); // Entry from a specific dictionary const bdbEntry = await engine.getDictionaryEntries('H430', 'BDB'); console.log(bdbEntry[0]?.lemma); // 'אֱלֹהִים' ``` -------------------------------- ### Initialize Client with Local DB and Server Fallback Source: https://github.com/stepbible/bibleengine/blob/master/client/README.md Instantiate the BibleEngineClient for scenarios requiring a local database with a server fallback. Ensure the correct driver and connection options are provided. ```typescript import { BibleEngineClient } from '@bible-engine/client'; const beClient = new BibleEngineClient({ bibleEngineConnectionOptions: { type: 'capacitor', driver: this.sqlite, // specific for the capacitor-typeorm-driver, you have to pass the sqlite driver journalMode: 'WAL', name: 'bibleEngine', database: `bibles_${environment.dbBiblesVersion}`, synchronize: false, logging: ['error'], }, apiBaseUrl: 'https://bible-engine.example.test/api', // the URL to the BibleEngine server }); // access data from where it's available const bibleData = await beClient.getReferenceRange({ ... }); // access local BibleEngine directly const localVersions = await beClient.localBibleEngine.getVersions('en'); // access server directly (you can use intellisense to get a list of all available api methods) const remoteVersions = await beClient.remoteApi.getVersions('en'); ``` -------------------------------- ### Instantiate BibleEngine with DataSourceOptions Source: https://context7.com/stepbible/bibleengine/llms.txt Instantiates the core engine with TypeORM DataSourceOptions. Supports various database types like SQLite, PostgreSQL, and MySQL/MariaDB. Options can be passed to enable features like full-text search (fts) or to override SQL execution. ```typescript import { BibleEngine } from '@bible-engine/core'; // SQLite (local file — typical for mobile/desktop apps) const engine = new BibleEngine({ type: 'sqlite', database: './output/bible.db', }); // In-memory SQLite (useful for tests) const testEngine = new BibleEngine({ type: 'sqlite', database: ':memory:', }); // PostgreSQL with full-text search enabled const pgEngine = new BibleEngine( { type: 'postgres', host: 'localhost', port: 5432, username: 'bibleuser', password: 'secret', database: 'bibleengine', }, { fts: true } ); // MySQL with a custom SQL executor (for performance on large inserts) const mysqlEngine = new BibleEngine( { type: 'mysql', host: 'localhost', database: 'bibleengine', username: 'root', password: '', }, { fts: true, executeSqlSetOverride: async (sqlSet) => { for (const { statement, values } of sqlSet) { await customMysqlClient.execute(statement, values); } }, } ); // Reuse an existing connection (useful in development) const devEngine = new BibleEngine( { type: 'sqlite', database: './bible.db' }, { checkForExistingConnection: true } ); ``` -------------------------------- ### Add Bible Version and Books with Content Source: https://github.com/stepbible/bibleengine/blob/master/core/README.md Use this snippet to initialize a BibleEngine instance, add a new Bible version, and then populate it with book content. Ensure your parser method returns data conforming to `models/BibleInput.ts`. ```typescript import { BibleEngine } from '@bible-engine/core'; const bibleEngine = new BibleEngine({ type: 'sqlite', database: `${dirProjectRoot}/output/bible.db`, }); const version = await bibleEngine.addVersion( new BibleVersion({ version: 'XSB', title: 'X Standard Bible', language: 'en-US', chapterVerseSeparator: ':', }) ); const books = [{ num: 1, file: 'gen.xml' }]; for (const book of books) { /* * Of course the real magic needs to happen in the following line. * Your method needs to return data as defined in `models/BibleInput.ts` */ const contents = myParserMethod(book.file); await bibleEngine.addBookWithContent(version.id, { book: { number: book.num, osisId: getOsisIdFromBookGenericId(book.num), abbreviation: book.abbr, title: book.title, type: 'ot', }, contents, }); } bibleEngine.finalizeVersion(version.id); ``` -------------------------------- ### Initialize BibleEngineClient for Local, Remote, or Hybrid Access Source: https://context7.com/stepbible/bibleengine/llms.txt Initializes a client for accessing Bible data. Can be configured for local SQLite databases, remote HTTP APIs, or a hybrid approach with fallback. Requires connection options for local or API base URL for remote access. ```typescript import { BibleEngineClient } from '@bible-engine/client'; // Local-only client const localClient = new BibleEngineClient({ bibleEngineConnectionOptions: { type: 'sqlite', database: './bible.db' }, }); // Remote-only client const remoteClient = new BibleEngineClient({ apiBaseUrl: 'https://api.example.com', }); // Hybrid client (local with remote fallback) const hybridClient = new BibleEngineClient({ bibleEngineConnectionOptions: { type: 'sqlite', database: './bible.db' }, apiBaseUrl: 'https://api.example.com', }); // Get all available versions const versions = await hybridClient.getVersions(); // Fetch a chapter (uses local DB or remote GET /bible/ref/:uid/:osisId/:chapterNr) const genesis1 = await hybridClient.getFullDataForReferenceRange({ versionUid: 'ESV', bookOsisId: 'Gen', versionChapterNum: 1, }); // Get books for a version const books = await hybridClient.getBooksForVersion('ESV'); // Get section structure / table of contents for a book const sections = await hybridClient.getSectionsForBook('ESV', 'Psa'); // Full-text search (falls back to remote if no local FTS index) const results = await hybridClient.search({ versionUid: 'ESV', query: 'righteousness', queryMode: 'fuzzy', sortMode: 'relevance', pagination: { page: 1, count: 25 }, }); // Force remote lookup for a specific call const remoteChapter = await hybridClient.getFullDataForReferenceRange( { versionUid: 'NIV', bookOsisId: 'Jhn', versionChapterNum: 1 }, true // forceRemote = true ); // Dictionary lookup const entry = await hybridClient.getDictionaryEntry('G26', 'TBESG'); console.log(entry?.gloss); // 'love' ``` -------------------------------- ### Initialize Client for Remote-Only Access Source: https://github.com/stepbible/bibleengine/blob/master/client/README.md Instantiate the BibleApi for scenarios where only remote server access to BibleEngine is needed. Provide the API base URL during initialization. ```typescript import { BibleApi } from '@bible-engine/client'; const beApi = new BibleApi(apiBaseUrl); const bibleData = await beApi.getReferenceRage({...}); ``` -------------------------------- ### Import BibleEngine File Source: https://github.com/stepbible/bibleengine/blob/master/importers/README.md This snippet demonstrates importing a BibleEngine file (.bef) into the BibleEngine. It requires filesystem access for unzipping and reading JSON files, and integrates with Capacitor and Ionic for file operations. It allows for adding version metadata and book content, with an option to defer content import. ```typescript const bibleEngine = new BibleEngine({ /* CONFIG */ }); const importFile = '../import/ESV.bef'; const targetDir = '../data/ESV'; const unzipResult = await this.zip.unzip( importFile, targetDir, (progress: { loaded: number; total: number }) => console.log('Unzipping, ' + Math.round((progress.loaded / progress.total) * 100) + '%') ); if (unzipResult === 0) { const versionData = await Filesystem.readFile({ path: `${targetDir}/version.json`, encoding: FilesystemEncoding.UTF8, }).then((file) => JSON.parse(file.data)); const versionIndex: IBibleBook[] = await Filesystem.readFile({ path: `${targetDir}/index.json`, encoding: FilesystemEncoding.UTF8, }).then((file) => JSON.parse(file.data)); const versionEntity = await bibleEngine.addVersion(versionData); for (const book of versionIndex) { /* * If you don't want to import all the data right away (due to client resources) * you can only save the book metadata and set `dataLocation` to `file` and run * `addBookWithContent` later when needed (see next code block) */ await bibleEngine.addBook({ ...book, dataLocation: 'file', versionId: versionEntity.id, }); /* * Alternatively import all the data at once */ const bookData: BookWithContentForInput = await Filesystem.readFile({ path: `${targetDir}/${book.osisId}.json`, encoding: FilesystemEncoding.UTF8, }).then((file) => JSON.parse(file.data)); await bibleEngine.addBookWithContent(versionEntity.id, bookData); } return true; } else { console.error(`importing "${importFile}" failed`); return false; } ``` -------------------------------- ### Sync Bible Versions (POST) Source: https://context7.com/stepbible/bibleengine/llms.txt Use this endpoint to send your current version list to the server for synchronization. Ensure the Content-Type is application/json. ```bash curl -X POST https://api.example.com/bible/versions/en \ -H 'Content-Type: application/json' \ -d '{"ESV":{"lastUpdate":"2023-01-01","dataLocation":"remote"}}' ``` -------------------------------- ### BibleEngine Constructor Source: https://context7.com/stepbible/bibleengine/llms.txt Instantiates the core engine with TypeORM DataSourceOptions. It normalizes the database type, runs schema migrations, and provides access to the EntityManager. ```APIDOC ## BibleEngine Constructor Instantiates the core engine with a TypeORM `DataSourceOptions` object. The constructor normalizes the database type, runs schema migrations automatically, and exposes a `pDB` promise that resolves to the active `EntityManager`. Supported database types are `sqlite` (and its variants: `better-sqlite3`, `expo`, `react-native`, `cordova`, `sqljs`, `capacitor`), `postgres`, and `mysql`/`mariadb`. ```typescript import { BibleEngine } from '@bible-engine/core'; // SQLite (local file — typical for mobile/desktop apps) const engine = new BibleEngine({ type: 'sqlite', database: './output/bible.db', }); // In-memory SQLite (useful for tests) const testEngine = new BibleEngine({ type: 'sqlite', database: ':memory:', }); // PostgreSQL with full-text search enabled const pgEngine = new BibleEngine( { type: 'postgres', host: 'localhost', port: 5432, username: 'bibleuser', password: 'secret', database: 'bibleengine', }, { fts: true } ); // MySQL with a custom SQL executor (for performance on large inserts) const mysqlEngine = new BibleEngine( { type: 'mysql', host: 'localhost', database: 'bibleengine', username: 'root', password: '', }, { fts: true, executeSqlSetOverride: async (sqlSet) => { for (const { statement, values } of sqlSet) { await customMysqlClient.execute(statement, values); } }, } ); // Reuse an existing connection (useful in development) const devEngine = new BibleEngine( { type: 'sqlite', database: './bible.db' }, { checkForExistingConnection: true } ); ``` ``` -------------------------------- ### Create SQLite Database with OSIS Importer Source: https://context7.com/stepbible/bibleengine/llms.txt Orchestrates the registration and sequential execution of importer plugins to populate a BibleEngine database. Requires specifying the database type, path, and importer-specific options like source path and version metadata. ```typescript import { BeDatabaseCreator } from '@bible-engine/importers'; import { OsisImporter } from '@bible-engine/importers/bible/osis'; import { SwordImporter } from '@bible-engine/importers/bible/sword'; // Create a fresh SQLite database from an OSIS XML file const creator = new BeDatabaseCreator({ type: 'sqlite', database: './output/esv.db', }); creator.addImporter(OsisImporter, { sourcePath: './data/ESV.xml', versionMeta: { uid: 'ESV', title: 'English Standard Version', language: 'en', chapterVerseSeparator: ':', hasStrongs: false, copyrightShort: '© 2001 Crossway', }, skip: { crossRefs: false, notes: false, strongs: false }, autoGenMissingParagraphs: true, }); await creator.createDatabase(); console.log('ESV database ready at ./output/esv.db'); // SWORD module import const swordCreator = new BeDatabaseCreator({ type: 'sqlite', database: './output/kjv.db' }); swordCreator.addImporter(SwordImporter, { sourcePath: './data/KJV.zip', }); await swordCreator.createDatabase(); ``` -------------------------------- ### Create Bible Database with Importers Source: https://github.com/stepbible/bibleengine/blob/master/importers/README.md Use BeDatabaseCreator to set up a new database for BibleEngine. It's recommended to include V11nImporter for normalized references and can optionally include SwordImporter or OsisImporter with specified data paths. ```typescript import { BeDatabaseCreator, V11nImporter, OsisImporter, SwordImporter, } from '@bible-engine/importers'; const creator = new BeDatabaseCreator({ type: 'mysql', host: 'localhost', port: 3306, username: 'bibleengine', password: 'bibleengine', database: 'bibleengine', dropSchema: true, }); // BibleEngine works without the versification rules form STEPData, however references won't be // internally normalized then, i.e. BibleEngine can't ensure that it returns the correct text when // switching or comparing versions. It's recommend to always use `V11nImporter` when creating // BibleEngine databases. This won't overwrite original version numbering, it "just" adds the // information which version-numbers refer to which text (which is identified by a normalized id). creator.addImporter(V11nImporter); creator.addImporter(SwordImporter, '../data/ESV2016_th.zip'); creator.addImporter(OsisImporter, { sourcePath: '../data/ESV.osis.xml', // you can pass/overwrite metadata that is not in the source file or that isn't properly parsed (yet) versionMeta: {}, bookMeta: {}, }); creator.createDatabase(); ``` -------------------------------- ### addBookWithContent Source: https://context7.com/stepbible/bibleengine/llms.txt Imports a complete Bible book with all its structured content into the database using an atomic transaction. Accepts BookWithContentForInput which mirrors the output of any BibleEngine importer. ```APIDOC ## addBookWithContent ### Description Imports a complete Bible book with all its structured content (phrases, paragraphs, sections, notes, cross-references, and Strong's numbers) into the database using an atomic transaction. Accepts `BookWithContentForInput` which mirrors the output of any BibleEngine importer. ### Method ```typescript await engine.addBookWithContent(version, bookWithContent, options) ``` ### Parameters - **version**: The version object to which the book will be added. - **bookWithContent**: An object containing the book's metadata and its structured content. - **book**: Object with book details (osisId, number, abbreviation, title, type). - **contents**: An array of IBibleContent objects representing the structured content of the book. - **options**: Optional settings for the import process. - **skipCrossRefs** (boolean): Whether to skip importing cross-references. - **skipNotes** (boolean): Whether to skip importing notes. - **skipStrongs** (boolean): Whether to skip importing Strong's numbers. - **ignoreSectionsWithoutTitle** (boolean): Whether to ignore sections that do not have a title. ### Request Example ```typescript // Minimal structured content example (Genesis 1:1) const contents: IBibleContent[] = [ { type: 'group', groupType: 'paragraph', contents: [ { type: 'phrase', content: 'In the beginning God created the heaven and the earth.', versionChapterNum: 1, versionVerseNum: 1, versionSubverseNum: 1, }, ], }, ]; await engine.addBookWithContent(version, { book: { osisId: 'Gen', number: 1, abbreviation: 'Gen', title: 'Genesis', type: 'ot', }, contents, }, { skipCrossRefs: false, skipNotes: false, skipStrongs: false, ignoreSectionsWithoutTitle: false, }); ``` ``` -------------------------------- ### Generate a New TypeORM Migration Source: https://github.com/stepbible/bibleengine/blob/master/README.md Create a new database migration file to capture schema changes. Replace 'SomeMigrationName' with a descriptive name for your migration. ```bash yarn typeorm migration:generate -n SomeMigrationName ``` -------------------------------- ### Run TypeORM Migrations Source: https://github.com/stepbible/bibleengine/blob/master/README.md Apply pending database migrations to update the schema. This command executes the generated migration files. ```bash yarn typeorm migration:run ``` -------------------------------- ### addDictionaryEntries / addV11nRules Source: https://context7.com/stepbible/bibleengine/llms.txt Bulk-imports dictionary entries (lexicon data) and versification normalization rules into the database. Both methods use chunked saves (100 records per batch) and run `OPTIMIZE TABLE` on MySQL after insertion. ```APIDOC ## addDictionaryEntries / addV11nRules ### Description Bulk-imports dictionary entries (lexicon data) and versification normalization rules into the database. Both methods use chunked saves (100 records per batch) and run `OPTIMIZE TABLE` on MySQL after insertion. ### Usage ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'mysql', host: 'localhost', database: 'bibleengine', username: 'root', password: '' }); // Add lexicon entries await engine.addDictionaryEntries([ { strong: 'H1', dictionary: 'BDB', lemma: 'אָב', transliteration: 'ab', gloss: 'father', }, { strong: 'G1', dictionary: 'TBESG', lemma: 'Ἄλφα', transliteration: 'Alpha', gloss: 'Alpha (first letter)', }, ]); // Add versification rules (e.g. from STEPBible v11n data) import { V11nRuleEntity } from '@bible-engine/core'; const rules: V11nRuleEntity[] = loadV11nRules(); // from your data source await engine.addV11nRules(rules); ``` ``` -------------------------------- ### Add Bible Book with Structured Content Source: https://context7.com/stepbible/bibleengine/llms.txt Imports a complete Bible book with all its structured content into the database using an atomic transaction. Ensure the version is added first and finalize the version after all books are imported. ```typescript import { BibleEngine, IBibleContent } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'sqlite', database: './bible.db' }); const version = await engine.addVersion({ uid: 'KJV', title: 'King James Version', language: 'en', chapterVerseSeparator: ':' }); // Minimal structured content example (Genesis 1:1) const contents: IBibleContent[] = [ { type: 'group', groupType: 'paragraph', contents: [ { type: 'phrase', content: 'In the beginning God created the heaven and the earth.', versionChapterNum: 1, versionVerseNum: 1, versionSubverseNum: 1, }, ], }, ]; await engine.addBookWithContent(version, { book: { osisId: 'Gen', number: 1, abbreviation: 'Gen', title: 'Genesis', type: 'ot', }, contents, }, { skipCrossRefs: false, skipNotes: false, skipStrongs: false, ignoreSectionsWithoutTitle: false, }); await engine.finalizeVersion(version.id); // normalizes cross-refs, optimizes tables ``` -------------------------------- ### BeDatabaseCreator Source: https://context7.com/stepbible/bibleengine/llms.txt Orchestrates the registration and sequential execution of importer plugins to populate a BibleEngine database. Supports various importer types like OsisImporter, SwordImporter, UsxImporter, and CsvImporter. ```APIDOC ## BeDatabaseCreator (Importers) A high-level orchestrator from `@bible-engine/importers` that registers one or more importer plugins and runs them sequentially to populate a BibleEngine database. Importers include `OsisImporter`, `SwordImporter`, `UsxImporter`, and `CsvImporter`. ```typescript import { BeDatabaseCreator } from '@bible-engine/importers'; import { OsisImporter } from '@bible-engine/importers/bible/osis'; import { SwordImporter } from '@bible-engine/importers/bible/sword'; // Create a fresh SQLite database from an OSIS XML file const creator = new BeDatabaseCreator({ type: 'sqlite', database: './output/esv.db', }); creator.addImporter(OsisImporter, { sourcePath: './data/ESV.xml', versionMeta: { uid: 'ESV', title: 'English Standard Version', language: 'en', chapterVerseSeparator: ':', hasStrongs: false, copyrightShort: '© 2001 Crossway', }, skip: { crossRefs: false, notes: false, strongs: false }, autoGenMissingParagraphs: true, }); await creator.createDatabase(); console.log('ESV database ready at ./output/esv.db'); // SWORD module import const swordCreator = new BeDatabaseCreator({ type: 'sqlite', database: './output/kjv.db' }); swordCreator.addImporter(SwordImporter, { sourcePath: './data/KJV.zip', }); await swordCreator.createDatabase(); ``` ``` -------------------------------- ### Bulk Import Dictionary Entries and Versification Rules Source: https://context7.com/stepbible/bibleengine/llms.txt Bulk-imports dictionary entries (lexicon data) and versification normalization rules into the database. Uses chunked saves and runs OPTIMIZE TABLE on MySQL after insertion. ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'mysql', host: 'localhost', database: 'bibleengine', username: 'root', password: '' }); // Add lexicon entries await engine.addDictionaryEntries([ { strong: 'H1', dictionary: 'BDB', lemma: 'אָב', transliteration: 'ab', gloss: 'father', }, { strong: 'G1', dictionary: 'TBESG', lemma: 'Ἄλφα', transliteration: 'Alpha', gloss: 'Alpha (first letter)', }, ]); // Add versification rules (e.g. from STEPBible v11n data) import { V11nRuleEntity } from '@bible-engine/core'; const rules: V11nRuleEntity[] = loadV11nRules(); // from your data source await engine.addV11nRules(rules); ``` -------------------------------- ### BibleEngineClient Source: https://context7.com/stepbible/bibleengine/llms.txt Provides a unified access layer that transparently tries the local BibleEngine first and falls back to a remote HTTP API. The `forceRemote` flag overrides local lookup for any method. The client automatically selects the most cacheable REST endpoint when calling the remote API. ```APIDOC ## BibleEngineClient The `@bible-engine/client` package provides a unified access layer that transparently tries the local `BibleEngine` first and falls back to a remote HTTP API. The `forceRemote` flag overrides local lookup for any method. The client automatically selects the most cacheable REST endpoint (`getChapter` → `getVerses` → `getReferenceRange`) when calling the remote API. ```typescript import { BibleEngineClient } from '@bible-engine/client'; // Local-only client const localClient = new BibleEngineClient({ bibleEngineConnectionOptions: { type: 'sqlite', database: './bible.db' }, }); // Remote-only client const remoteClient = new BibleEngineClient({ apiBaseUrl: 'https://api.example.com', }); // Hybrid client (local with remote fallback) const hybridClient = new BibleEngineClient({ bibleEngineConnectionOptions: { type: 'sqlite', database: './bible.db' }, apiBaseUrl: 'https://api.example.com', }); // Get all available versions const versions = await hybridClient.getVersions(); // Fetch a chapter (uses local DB or remote GET /bible/ref/:uid/:osisId/:chapterNr) const genesis1 = await hybridClient.getFullDataForReferenceRange({ versionUid: 'ESV', bookOsisId: 'Gen', versionChapterNum: 1, }); // Get books for a version const books = await hybridClient.getBooksForVersion('ESV'); // Get section structure / table of contents for a book const sections = await hybridClient.getSectionsForBook('ESV', 'Psa'); // Full-text search (falls back to remote if no local FTS index) const results = await hybridClient.search({ versionUid: 'ESV', query: 'righteousness', queryMode: 'fuzzy', sortMode: 'relevance', pagination: { page: 1, count: 25 }, }); // Force remote lookup for a specific call const remoteChapter = await hybridClient.getFullDataForReferenceRange( { versionUid: 'NIV', bookOsisId: 'Jhn', versionChapterNum: 1 }, true // forceRemote = true ); // Dictionary lookup const entry = await hybridClient.getDictionaryEntry('G26', 'TBESG'); console.log(entry?.gloss); // 'love' ``` ``` -------------------------------- ### Read Full Bible Data for a Reference Range Source: https://github.com/stepbible/bibleengine/blob/master/core/README.md This snippet demonstrates how to read comprehensive Bible data for a specified range using core methods. It requires a pre-configured BibleEngine instance connected to a database. ```typescript import { BibleEngine } from '@bible-engine/core'; const bibleEngine = new BibleEngine({ type: 'sqlite', database: `${dirProjectRoot}/output/bible.db`, }); const bibleData = await bibleEngine.getFullDataForReferenceRange({ versionUid: 'ESV', bookOsisId: 'Gen', versionChapterNum: 1, }); ``` -------------------------------- ### REST API Server (BibleController) Source: https://context7.com/stepbible/bibleengine/llms.txt Exposes a REST API via `routing-controllers` mounted under the `/bible` prefix. All endpoints return JSON; errors are mapped to HTTP status codes from `BibleEngineError.httpCode`. ```APIDOC ## REST API Server (BibleController) The `@bible-engine/server` package exposes a REST API via `routing-controllers` mounted under the `/bible` prefix. All endpoints return JSON; errors are mapped to HTTP status codes from `BibleEngineError.httpCode`. ```bash # List all versions curl https://api.example.com/bible/versions # Get a single version curl https://api.example.com/bible/versions/ESV # Get books for a version curl https://api.example.com/bible/versions/ESV/books # Get section structure for a book (table of contents) curl https://api.example.com/bible/sections/ESV/Gen # Get a full chapter curl https://api.example.com/bible/ref/ESV/Gen/1 # Get a single verse curl https://api.example.com/bible/ref/ESV/Jhn/3/16 # Get a verse range across chapters curl "https://api.example.com/bible/ref/ESV/Rom/3/23?chapterEnd=3&verseEnd=24" # Arbitrary reference range (POST) curl -X POST https://api.example.com/bible/ref \ -H 'Content-Type: application/json' \ -d '{"versionUid":"ESV","bookOsisId":"Psa","versionChapterNum":23}' # Dictionary — all entries for a Strong number curl https://api.example.com/bible/definitions/G26 # Dictionary — entry from a specific dictionary curl https://api.example.com/bible/definitions/H430/BDB # Full-text search (fuzzy, sorted by reference, page 1 of 50) curl "https://api.example.com/bible/search/ESV/love%20one%20another?queryMode=fuzzy&sortMode=reference&page=1&count=50" ``` ``` -------------------------------- ### Bible Reference System Utilities Source: https://context7.com/stepbible/bibleengine/llms.txt Utilize these functions for generating and parsing normalized reference and phrase IDs. Includes type guards for checking reference normalization. ```typescript import { generateReferenceId, generatePhraseId, parseReferenceId, parsePhraseId, generateNormalizedRangeFromVersionRange, isReferenceNormalized, } from '@bible-engine/core'; // Construct a normalized reference ID (used internally as a DB key) const refId = generateReferenceId({ bookOsisId: 'Gen', isNormalized: true, normalizedChapterNum: 1, normalizedVerseNum: 1, normalizedSubverseNum: 1, }); // Parse a reference ID back to components const parsed = parseReferenceId(refId); console.log(parsed.normalizedChapterNum); // 1 console.log(parsed.normalizedVerseNum); // 1 // Generate a phrase-level ID (includes phraseNum for multiple phrases per verse) const phraseId = generatePhraseId({ isNormalized: true, bookOsisId: 'Gen', versionId: 1, normalizedChapterNum: 1, normalizedVerseNum: 1, normalizedSubverseNum: 1, phraseNum: 3, }); const parsedPhrase = parsePhraseId(phraseId); console.log(parsedPhrase.phraseNum); // 3 // Check if a reference is already normalized (TypeScript type-guard) const ref = { bookOsisId: 'Gen', versionChapterNum: 1, versionVerseNum: 1 }; if (isReferenceNormalized(ref)) { // ref is IBibleReferenceNormalized here } else { const normalized = generateNormalizedRangeFromVersionRange({ versionId: 1, bookOsisId: 'Gen', versionChapterNum: 1, versionVerseNum: 1, }); } ``` -------------------------------- ### getDictionaryEntries Source: https://context7.com/stepbible/bibleengine/llms.txt Looks up Strong's dictionary entries by Strong number and optional dictionary identifier. Returns morphological data, glosses, lemma, and transliteration sourced from Tyndale House STEPBible datasets. ```APIDOC ## getDictionaryEntries ### Description Looks up Strong's dictionary entries by Strong number and optional dictionary identifier. Returns morphological data, glosses, lemma, and transliteration sourced from Tyndale House STEPBible datasets. ### Usage ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'sqlite', database: './bible.db' }); // All dictionary entries for a Strong number const entries = await engine.getDictionaryEntries('G26'); entries.forEach(e => { console.log(e.strong); console.log(e.dictionary); console.log(e.lemma); console.log(e.gloss); console.log(e.transliteration); }); // Entry from a specific dictionary const bdbEntry = await engine.getDictionaryEntries('H430', 'BDB'); console.log(bdbEntry[0]?.lemma); // 'אֱלֹהִים' ``` ``` -------------------------------- ### Export Bible to .bef Format Source: https://github.com/stepbible/bibleengine/blob/master/importers/README.md Utilize BeImportFileCreator to export Bible data from a database into the pre-loadable BibleEngineFile (.bef) format. This process can be initiated for all versions within the configured database. ```typescript import { BeImportFileCreator } from '@bible-engine/importers'; const creator = new BeImportFileCreator( { type: 'mysql', host: 'localhost', port: 3306, username: 'bibleengine', password: 'bibleengine', database: 'bibleengine', }, './preload/bibles' ); await creator.createAllVersions(); ``` -------------------------------- ### Retrieve Bible Versions Source: https://context7.com/stepbible/bibleengine/llms.txt Retrieves all available Bible versions or a single version by UID. `getVersions` accepts an optional BCP47 language code prefix for filtering. Use this to list available versions or fetch details of a specific version. ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'sqlite', database: './bible.db' }); // List all versions const allVersions = await engine.getVersions(); allVersions.forEach(v => console.log(`${v.uid}: ${v.title} (${v.language})`)); // Filter by language prefix const englishVersions = await engine.getVersions('en'); const multiLangVersions = await engine.getVersions(['en', 'de', 'fr']); // Single version by UID const esv = await engine.getVersion('ESV'); if (!esv) throw new Error('ESV not installed'); console.log(esv.hasStrongs); // true/false console.log(esv.type); // 'formal' | 'dynamic' | 'free' | 'orig' ``` -------------------------------- ### getVersions / getVersion Source: https://context7.com/stepbible/bibleengine/llms.txt Retrieves all available Bible versions or a single version by UID. `getVersions` accepts an optional BCP47 language code prefix for filtering. ```APIDOC ## getVersions / getVersion ### Description Retrieves all available Bible versions or a single version by UID. `getVersions` accepts an optional BCP47 language code prefix for filtering. ### Method ```typescript await engine.getVersions(languagePrefix?) await engine.getVersion(uid) ``` ### Parameters - **languagePrefix** (string | string[], optional): A BCP47 language code prefix or an array of prefixes to filter versions. - **uid** (string): The Unique Identifier (UID) of the Bible version to retrieve. ### Request Example ```typescript // List all versions const allVersions = await engine.getVersions(); // Filter by language prefix const englishVersions = await engine.getVersions('en'); const multiLangVersions = await engine.getVersions(['en', 'de', 'fr']); // Single version by UID const esv = await engine.getVersion('ESV'); ``` ### Response #### Success Response (200) - **getVersions**: An array of version objects. - **getVersion**: A single version object. - **hasStrongs** (boolean): Indicates if the version includes Strong's numbers. - **type** (string): The type of the version ('formal' | 'dynamic' | 'free' | 'orig'). ``` -------------------------------- ### Add a new Bible version to the database Source: https://context7.com/stepbible/bibleengine/llms.txt Persists a new Bible version record. Returns the saved entity including its local ID and stable UID, which is required for subsequent operations like adding books. ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'sqlite', database: './bible.db' }); const version = await engine.addVersion({ uid: 'ESV', abbreviation: 'ESV', title: 'English Standard Version', description: { type: 'root', contents: [] }, language: 'en-US', chapterVerseSeparator: ':', hasStrongs: false, isPlaintext: false, type: 'formal', copyrightShort: '© 2001 by Crossway Bibles', }); console.log(version.id); // local DB id, e.g. 1 console.log(version.uid); // 'ESV' ``` -------------------------------- ### addVersion Source: https://context7.com/stepbible/bibleengine/llms.txt Persists a new Bible version record to the database. It returns the saved BibleVersionEntity, including its auto-generated local ID, which is necessary for subsequent operations like adding books with content. The `uid` field serves as the stable public identifier for all query APIs. ```APIDOC ## addVersion Persists a new Bible version record to the database. Returns the saved `BibleVersionEntity`, including the auto-generated local `id` that is needed when calling `addBookWithContent`. The `uid` field is the stable public identifier used in all query APIs. ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'sqlite', database: './bible.db' }); const version = await engine.addVersion({ uid: 'ESV', abbreviation: 'ESV', title: 'English Standard Version', description: { type: 'root', contents: [] }, language: 'en-US', chapterVerseSeparator: ':', hasStrongs: false, isPlaintext: false, type: 'formal', copyrightShort: '© 2001 by Crossway Bibles', }); console.log(version.id); // local DB id, e.g. 1 console.log(version.uid); // 'ESV' ``` ``` -------------------------------- ### finalizeVersion Source: https://context7.com/stepbible/bibleengine/llms.txt Must be called once after all books of a version have been imported. It normalizes all cross-references and optimizes tables. ```APIDOC ## finalizeVersion ### Description Must be called once after all books of a version have been imported. It normalizes all cross-references stored as version-specific references into the canonical reference system, and on MySQL/MariaDB runs `OPTIMIZE TABLE` on all Bible tables. ### Method ```typescript await engine.finalizeVersion(versionId) ``` ### Parameters - **versionId**: The ID of the version to finalize. ### Request Example ```typescript await engine.finalizeVersion(version.id); ``` ``` -------------------------------- ### getFullDataForReferenceRange Source: https://context7.com/stepbible/bibleengine/llms.txt The primary read API. Returns a rich IBibleOutputRich object containing the full structured content for any reference range, plus surrounding context. ```APIDOC ## getFullDataForReferenceRange ### Description The primary read API. Returns a rich `IBibleOutputRich` object containing the full structured content (phrases, paragraphs, sections, cross-references, notes) for any reference range, plus surrounding context ranges and section hierarchies for UI rendering. ### Method ```typescript await engine.getFullDataForReferenceRange(referenceRange, stripUnnecessaryData) ``` ### Parameters - **referenceRange**: An object specifying the reference range. - **versionUid** (string): The UID of the Bible version. - **bookOsisId** (string): The OSIS ID of the book. - **versionChapterNum** (number): The chapter number. - **versionVerseNum** (number, optional): The verse number. - **versionChapterEndNum** (number, optional): The end chapter number for a range. - **versionVerseEndNum** (number, optional): The end verse number for a range. - **stripUnnecessaryData** (boolean, optional): If true, removes local IDs and slims the payload. ### Request Example ```typescript // Fetch a full chapter const chapter = await engine.getFullDataForReferenceRange({ versionUid: 'ESV', bookOsisId: 'Gen', versionChapterNum: 1, }); // Fetch a verse range const verses = await engine.getFullDataForReferenceRange({ versionUid: 'ESV', bookOsisId: 'Jhn', versionChapterNum: 3, versionVerseNum: 16, versionChapterEndNum: 3, versionVerseEndNum: 17, }); // Fetch a whole book (stripped to minimize data for transmission) const book = await engine.getFullDataForReferenceRange( { versionUid: 'KJV', bookOsisId: 'Psa' }, true // stripUnnecessaryData = true ); ``` ### Response #### Success Response (200) - **version**: Object containing version details. - **versionBook**: Object containing version book details. - **content**: `IBibleContent[]` - structured content including sections, paragraphs, and phrases. - **contextRanges**: Object containing surrounding context ranges, including `nextRange`. ``` -------------------------------- ### Finalize Bible Version Import Source: https://context7.com/stepbible/bibleengine/llms.txt Must be called once after all books of a version have been imported. It normalizes cross-references and optimizes database tables. This function is essential for preparing the version for querying. ```typescript import { BibleEngine } from '@bible-engine/core'; const engine = new BibleEngine({ type: 'sqlite', database: './bible.db' }); const version = await engine.addVersion({ uid: 'NET', title: 'NET Bible', language: 'en', chapterVerseSeparator: ':' }); // ... (add all books) ... await engine.finalizeVersion(version.id); // ✓ Cross-references are now normalized // ✓ Database is ready for querying ```