### Run example applications Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/guides/examples.md Use these convenience scripts to install dependencies, build the library, and launch specific example applications. ```bash # Setup: install dependencies and build the library yarn playground:setup # Run examples yarn playground:react # React + Vite yarn playground:vanilla # Vanilla TypeScript yarn playground:angular # Angular yarn playground:node # Node.js CLI ``` -------------------------------- ### Setup dependencies and build Source: https://github.com/adelpro/quran-search-engine/blob/main/examples/vanilla-ts/README.md Run this command to install necessary dependencies and build the library. ```bash yarn playground:setup ``` -------------------------------- ### Run example applications via CLI Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Commands to install dependencies, build the library, and execute specific example applications. ```bash # Setup: install dependencies and build the library yarn playground:setup # Run individual examples yarn playground:react # React + Vite yarn playground:vanilla # Vanilla TypeScript yarn playground:angular # Angular yarn playground:node # Node.js CLI ``` -------------------------------- ### Run the example Source: https://github.com/adelpro/quran-search-engine/blob/main/examples/nodejs/README.md Execute this command to run the default example script. ```bash yarn playground:node ``` -------------------------------- ### Start development server Source: https://github.com/adelpro/quran-search-engine/blob/main/examples/vanilla-ts/README.md Run this command to start the development server for the vanilla TypeScript playground. ```bash yarn playground:vanilla ``` -------------------------------- ### Workspace setup commands Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Commands to install dependencies, build the library, and run tests within the monorepo. ```bash # Install all dependencies for the workspace and examples yarn install # Build the main library yarn build # Run tests across the workspace yarn test ``` -------------------------------- ### Install with NPM or pnpm Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/guides/installation.md Alternative installation commands for users preferring npm or pnpm. ```bash npm install quran-search-engine # or pnpm add quran-search-engine ``` -------------------------------- ### Install yarn globally Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Prerequisites for setting up the development environment. ```bash npm install -g yarn # or corepack enable yarn ``` -------------------------------- ### Initialize and Query in JavaScript (Node ESM) Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/guides/quick-start.md Shows the equivalent setup for Node.js ESM environments. ```javascript import { search, loadMorphology, loadQuranData, loadWordMap } from 'quran-search-engine'; const [quranData, morphologyMap, wordMap] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), ]); const response = search('الله الرحمن', quranData, morphologyMap, wordMap, { lemma: true, root: true, }); console.log(response.results[0]); ``` -------------------------------- ### Migration Example: v0.2.x Initialization Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/migration-guide.md The previous initialization pattern for search data in v0.2.x. ```typescript const [quranData, setQuranData] = useState([]); const [morphologyMap, setMorphologyMap] = useState | null>(null); const [wordMap, setWordMap] = useState(null); useEffect(() => { async function init() { const [data, morphology, dictionary] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), ]); setQuranData(data); setMorphologyMap(morphology); setWordMap(dictionary); } init(); }, []); const response = search( query, quranData, morphologyMap!, wordMap!, options, { page: 1, limit: 10 }, undefined, searchCache, ); ``` -------------------------------- ### normalizeArabic usage example Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Shows how to import and use normalizeArabic to prepare user input for searching. The example is truncated in the source, so only the import and start of the call are shown. ```TypeScript import { normalizeArabic } from 'quran-search-engine'; const ``` -------------------------------- ### Install quran-search-engine with yarn Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md The default command to add the library to your project using yarn. ```bash yarn add quran-search-engine ``` -------------------------------- ### Migration Example: v0.3.x Initialization Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/migration-guide.md The updated initialization pattern for v0.3.x, which includes semantic data and the inverted index. ```typescript const [quranData, setQuranData] = useState | null>(null); const [morphologyMap, setMorphologyMap] = useState | null>(null); const [wordMap, setWordMap] = useState(null); const [semanticMap, setSemanticMap] = useState | null>(null); const [invertedIndex, setInvertedIndex] = useState(null); useEffect(() => { async function init() { const [data, morphology, dictionary, semantic] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), loadSemanticData(), ]); setQuranData(data); setMorphologyMap(morphology); setWordMap(dictionary); setSemanticMap(semantic); const index = buildInvertedIndex(morphology, data, semantic); setInvertedIndex(index); } init(); }, []); const response = search( query, { quranData: quranData, morphologyMap: morphologyMap, wordMap: wordMap, invertedIndex: invertedIndex, semanticMap: semanticMap, }, options, { page: 1, limit: 10 }, undefined, searchCache, ); ``` -------------------------------- ### Initialize development environment Source: https://github.com/adelpro/quran-search-engine/blob/main/CONTRIBUTING.md Commands to enable Corepack, prepare the specific Yarn version, install dependencies, and run build, test, and lint tasks. ```bash corepack enable && corepack prepare yarn@4.18.0 --activate yarn install yarn build yarn test yarn lint ``` -------------------------------- ### Example JSON data structure Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/guides/english-arabic-search.md An example of the JSON format for mapping English terms to Arabic roots. ```json { "english": ["truth", "verity", "trueness", "accuracy"], "arabic": ["حق", "صدق"] } ``` -------------------------------- ### Example output Source: https://github.com/adelpro/quran-search-engine/blob/main/examples/nodejs/README.md The expected output format when running the search engine, showing data loading status and search results. ```text 🚀 Loading Quran Search Engine data... ✅ Loaded 6236 verses ✅ Loaded morphology data for 6236 verses ✅ Loaded word map with 77403 entries 🔍 Search for "Allah": "الله" ────────────────────────────────────────────────── 📊 Found 2568 matches - Exact: 2568 - Lemma: 0 - Root: 0 - Fuzzy: 0 1. Al-Fatiha (1:1) Match: exact (Score: 1) Text: بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ ... ``` -------------------------------- ### Response Shape Output Example Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/guides/quick-start.md Displays the expected output format for verse matches. ```sh 1 1 exact 6 1 3 lemma 4 ``` -------------------------------- ### Example Conventional Commits Source: https://github.com/adelpro/quran-search-engine/blob/main/CONTRIBUTING.md Examples of commit messages following the Conventional Commits standard enforced by @commitlint/config-conventional. ```text feat(search): add diacritics toggle fix(normalization): handle hamza edge case docs: clarify branch base in CONTRIBUTING perf(worker): cache tokenizer output per query ``` -------------------------------- ### Build the core library Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/guides/examples.md Build the core library from /src to ensure example applications detect local changes, as the project uses yarn workspace linking. ```bash # Build the core library once yarn build # Or rebuild on save iteratively yarn build --watch ``` -------------------------------- ### Combine All Performance Optimizations Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Recommended production setup combining parallel data loading, pre-computed Fuse index, and an LRU cache for instant repeat queries. ```ts import { loadQuranData, loadMorphology, loadWordMap, loadInvertedIndex, createArabicFuseSearch, LRUCache, search, } from 'quran-search-engine'; import type { SearchResponse, QuranText } from 'quran-search-engine'; // Load everything in parallel const [quranData, morphologyMap, wordMap, invertedIndex] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), loadInvertedIndex(), ]); // Pre-compute Fuse index (skips ~5-20ms rebuild per keystroke) const fuseIndex = createArabicFuseSearch(quranData, ['standard', 'uthmani']); // Shared LRU cache (instant repeat queries) const cache = new LRUCache>(50); // All optimizations active const result = search( query, { quranData, morphologyMap, wordMap, invertedIndex }, { lemma: true, root: true, fuzzy: true }, { page: 1, limit: 20 }, fuseIndex, // skip Fuse rebuild cache, // instant cache hit ); ``` -------------------------------- ### search function usage with options and pagination Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Demonstrates the main search API call with options for lemma, root, and semantic matching, plus pagination. The comment shows example output structure for pagination, counts, and first result. ```TypeScript import { search } from 'quran-search-engine'; const response = search( 'الله الرحمن', { quranData, morphologyMap, wordMap, semanticMap }, { lemma: true, root: true, semantic: true }, // options { page: 1, limit: 10 } // pagination ); // Example output: // response.pagination => { totalResults: 42, totalPages: 5, currentPage: 1, limit: 10 } // response.counts => { simple: 10, lemma: 18, root: 9, fuzzy: 5, semantic: 0, total: 42 } // response.results[0] => { gid: 123, matchType: 'exact', matchScore: 9, matchedTokens: ['...'], ... } ``` -------------------------------- ### Implement Custom Dataset Search Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Example of searching a custom dataset with specific verse structures and optional morphology/word maps. ```ts import { search, type VerseInput, type WordMap, type MorphologyAya } from 'quran-search-engine'; type MyVerse = VerseInput & { sura: number; aya: number; translation_en?: string; }; const myQuranData: MyVerse[] = [ { gid: 1, standard: 'بسم الله الرحمن الرحيم', uthmani: 'بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ', sura: 1, aya: 1, translation_en: 'In the name of Allah, the Entirely Merciful, the Especially Merciful.', }, ]; const morphologyMap = new Map(); const wordMap: WordMap = {}; const response = search( 'الله الرحمن', { quranData: myQuranData, morphologyMap, wordMap }, { lemma: false, root: false, }, ); // Example output: // response.results[0] => { gid: 1, sura: 1, aya: 1, matchType: 'exact', matchScore: 6, ... } ``` -------------------------------- ### Render Highlights in React Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md A React component example demonstrating how to map highlight ranges to styled span elements. ```tsx import { getHighlightRanges, type ScoredQuranText } from 'quran-search-engine'; import type { ReactNode } from 'react'; export function Verse({ verse }: { verse: ScoredQuranText }) { const ranges = getHighlightRanges(verse.uthmani, verse.matchedTokens, verse.tokenTypes); if (ranges.length === 0) return {verse.uthmani}; const parts: ReactNode[] = []; let cursor = 0; ranges.forEach((r, i) => { if (cursor < r.start) parts.push(verse.uthmani.slice(cursor, r.start)); parts.push( {verse.uthmani.slice(r.start, r.end)} , ); cursor = r.end; }); if (cursor < verse.uthmani.length) parts.push(verse.uthmani.slice(cursor)); return {parts}; } ``` -------------------------------- ### loadMorphology and search with error handling Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Example of using loadMorphology and search functions with try-catch blocks to handle specific error classes. ```APIDOC ## loadMorphology and search with error handling ### Description Demonstrates how to use the loadMorphology and search functions while catching specific error classes. ### Code Example ```ts import { loadMorphology, search, DataFileNotFoundError, DataParseError, InvalidPaginationError, MissingDependenciesError, ErrorCode, } from 'quran-search-engine'; // Data loading errors try { const morphology = await loadMorphology(); } catch (error) { if (error instanceof DataFileNotFoundError) { console.error('Missing file:', error.filePath); // Use fallback data } else if (error instanceof DataParseError) { console.error('Corrupted file:', error.filePath); // Re-download data } } // Search validation errors try { const results = search(query, { quranData, morphologyMap, wordMap }, options, { page: 1, limit: 10, }); } catch (error) { if (error instanceof InvalidPaginationError) { console.error('Invalid pagination:', error.message); } else if (error instanceof MissingDependenciesError) { console.error('Missing data:', error.missingDependencies); } } ``` ``` -------------------------------- ### JavaScript (Node/ESM): Basic search with quran-search-engine Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md JavaScript version of the basic search example. Loads Quran data, morphology, and word maps, then performs a search for 'الله الرحمن' with lemma, root, and semantic options. Logs the first result. Assumes an async context (Node 18+, ESM, or browser). ```JavaScript import { search, loadMorphology, loadQuranData, loadWordMap } from 'quran-search-engine'; const [quranData, morphologyMap, wordMap] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), ]); const response = search( 'الله الرحمن', { quranData, morphologyMap, wordMap }, { lemma: true, root: true, semantic: true, }, ); console.log(response.results[0]); ``` -------------------------------- ### Regex search with and without sura filtering Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Two regex search examples: the first finds verses ending with 'ون' using isRegex: true, and the second combines regex with suraId: 1 to search only in Al-Fatihah. Both bypass linguistic pipelines. ```TypeScript import { search } from 'quran-search-engine'; // Find verses ending with "ون" const response = search( '^.*ون$', { quranData, morphologyMap, wordMap }, { lemma: false, root: false, isRegex: true, }, ); // Combine with sura filtering const filtered = search( 'الله.*الرحمن', { quranData, morphologyMap, wordMap }, { lemma: false, root: false, isRegex: true, suraId: 1, // only search in Al-Fatihah }, ); ``` -------------------------------- ### Run development commands Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Standard commands for linting, testing, and building the project. ```bash yarn run lint yarn run test yarn run build ``` -------------------------------- ### Initialize and Query in TypeScript Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/guides/quick-start.md Demonstrates loading datasets in parallel and performing a search with lemma, root, and fuzzy options enabled. Requires an async environment such as Node 18+ or a browser. ```typescript import { search, loadMorphology, loadQuranData, loadWordMap, type SearchResponse, } from 'quran-search-engine'; // 1. Parallel Load all Datasets natively const [quranData, morphologyMap, wordMap] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), ]); // 2. Query and Pass Maps to search() const response: SearchResponse = search('الله الرحمن', quranData, morphologyMap, wordMap, { lemma: true, root: true, fuzzy: true, }); // 3. Iterate through highly scored verse matches response.results.forEach((verse) => { console.log( `Sura: ${verse.sura_id} | Aya: ${verse.aya_id} | Match: ${verse.matchType} | Score: ${verse.matchScore}`, ); }); ``` -------------------------------- ### Error code usage Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Example of using error codes to handle errors in a type-safe manner. ```APIDOC ## Error code usage ### Description Demonstrates how to use the ErrorCode enum to handle errors based on their code. ### Code Example ```ts import { search, ErrorCode } from 'quran-search-engine'; try { const results = search(query, { quranData, morphologyMap, wordMap }); } catch (error) { if (error.code === ErrorCode.DATA_FILE_NOT_FOUND) { // Handle missing file } else if (error.code === ErrorCode.VALIDATION_INVALID_PAGINATION) { // Handle invalid pagination } else if (error.code === ErrorCode.TOKENIZATION_INVALID_MODE) { // Handle invalid tokenization mode } } ``` ``` -------------------------------- ### search(query, context, options?, pagination?, fuseIndex?, cache?) Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/api/core.md The main entry point for querying the engine. Combines Exact, Lemma, Root, and Fuzzy matching dynamically based on the provided tokens. ```APIDOC ## search(query, context, options?, pagination?, fuseIndex?, cache?) ### Description The main entry point for querying the engine. Combines Exact, Lemma, Root, and Fuzzy matching dynamically based on the provided tokens. ### Parameters - `query` (string): The search query (can be multi-word). - `context` (SearchContext): Object containing `quranData`, `morphologyMap`, `wordMap`, and optionally `invertedIndex`, `semanticMap`, `phoneticMap`. - `options` (SearchOptions, optional): Toggles enabling linguistic matching features. - `pagination` (PaginationOptions, optional): Search result paging bounds. - `fuseIndex` (Fuse, optional): Pre-built Fuse index for performance. - `cache` (LRUCache, optional): LRU cache for result caching. ### Returns `SearchResponse` ### Example ```typescript import { search } from 'quran-search-engine'; const response = search( 'الله الرحمن', { quranData, morphologyMap, wordMap }, { lemma: true, root: true }, { page: 1, limit: 10 }, ); ``` ``` -------------------------------- ### Initialize and use LRUCache Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Shows how to instantiate the LRUCache class and use its primary methods for managing cached data. ```ts import { LRUCache } from 'quran-search-engine'; const cache = new LRUCache(100); // capacity = 100 entries cache.set('key', value); // Store a value cache.get('key'); // Retrieve (moves to most-recent) cache.has('key'); // Check existence cache.delete('key'); // Remove one entry cache.clear(); // Remove all entries cache.size; // Current number of entries ``` -------------------------------- ### Using createSearchWorker (Recommended) Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/performance.md The library provides a createSearchWorker factory that handles Worker communication automatically. Create the worker client with a workerUrl, initialize data inside the worker with initData(), run searches with runSearch(), and terminate when done. Use new URL('./search-worker.js', import.meta.url) for Vite/Webpack 5+/Next.js bundling. ```typescript import { createSearchWorker, loadQuranData, loadMorphology, loadWordMap, loadSemanticData, loadPhoneticData, } from 'quran-search-engine'; // Create the worker client const workerClient = createSearchWorker({ workerUrl: new URL('./search-worker.js', import.meta.url), }); // Initialize (loads data inside the worker) await workerClient.initData(); // Run searches const result = await workerClient.runSearch( 'الله', { lemma: true, root: true }, { page: 1, limit: 20 }, ); // Cleanup workerClient.terminate(); ``` -------------------------------- ### Perform search using English word Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/guides/english-arabic-search.md Example of calling the search function with root-based search enabled to find verses based on English input. ```typescript import { search } from 'quran-search-engine'; // Search using English word const result = search('truth', quranData, morphologyMap, wordMap, { lemma: true, root: true, // Important: enables root-based search semantic: true, }); // The library will: // 1. Look up "truth" in English→Arabic map // 2. Find roots ["حق", "صدق"] // 3. Search for all words derived from these roots // 4. Return matching verses ``` -------------------------------- ### Project Test Structure Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Overview of the directory structure for unit and integration tests within the project. ```bash src/ ├── core/ │ ├── range-parser.test.ts # Range search parsing tests │ ├── search.test.ts # Search algorithm, inverted index, LRU cache, and Fuse tests │ ├── lru-cache.test.ts # LRU cache tests │ └── tokenization.test.ts # Token matching tests ├── utils/ │ ├── loader.test.ts # Data loading tests │ ├── normalization.test.ts # Text processing tests │ └── highlight.ts # Highlighting utilities └── worker/ └── searchWorkerClient.test.ts # Worker client + fallback tests ``` -------------------------------- ### Catch WorkerNotInitializedError when runSearch called before initData Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/api/core.md Import WorkerNotInitializedError and call runSearch before initData to trigger the error. The example shows the import and the call that throws. ```typescript import { WorkerNotInitializedError } from 'quran-search-engine'; const client = createSearchWorker({ fallbackDeps }); await client.runSearch('test'); // Throws WorkerNotInitializedError ``` -------------------------------- ### Format validation errors with formatSchemaErrors Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/api/core.md Formats a ValidationResult into a human-readable string for logging or display. The example shows the expected output format for validation errors. ```typescript import { formatSchemaErrors } from 'quran-search-engine'; const result = validateQuranData(data); console.log(formatSchemaErrors(result)); // Output: // 1. [verses[0].gid] Expected number, received string // 2. [verses[1].standard] Required field missing ``` -------------------------------- ### Run verification script Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Commands to build the library and execute the end-to-end verification script using a TypeScript runner. ```bash # Build the library first yarn build # Then run verification (requires tsx or similar TypeScript runner) yarn tsx scripts/verify-loader.ts ``` -------------------------------- ### Load Inverted Index from Bundled Static Files Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Loads a pre-built inverted index from static files, resulting in zero CPU build cost at startup. ```ts import { loadInvertedIndex, search } from 'quran-search-engine'; const invertedIndex = await loadInvertedIndex(); const result = search( 'الرحمن', quranData, morphologyMap, wordMap, { lemma: true, root: true }, { page: 1, limit: 20 }, undefined, undefined, invertedIndex, ); ``` -------------------------------- ### Full Benchmark Script Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/performance.md A comprehensive script to measure data loading, index loading, and average search latency over multiple runs. ```typescript // scripts/benchmark.ts import { loadQuranData, loadMorphology, loadWordMap, loadInvertedIndex, buildInvertedIndex, search, LRUCache, createArabicFuseSearch, } from 'quran-search-engine'; import type { SearchResponse } from 'quran-search-engine'; async function main() { // --- Data Loading --- const mem0 = process.memoryUsage().heapUsed; const t0 = performance.now(); const [quranData, morphologyMap, wordMap] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), ]); const loadTime = performance.now() - t0; const mem1 = process.memoryUsage().heapUsed; console.log('=== Data Loading ==='); console.log(` Time: ${loadTime.toFixed(2)}ms`); console.log(` Memory: ${((mem1 - mem0) / 1024 / 1024).toFixed(2)} MB`); // --- Inverted Index --- const t1 = performance.now(); const invertedIndex = await loadInvertedIndex(); const indexTime = performance.now() - t1; console.log(`\n=== Inverted Index ===`); console.log(` loadInvertedIndex: ${indexTime.toFixed(2)}ms`); // --- Search Latency (avg of 5 runs) --- const cache = new LRUCache(100); const fuseIndex = createArabicFuseSearch(quranData, ['standard', 'uthmani']); const queries = ['الله', 'كتب', 'رحم', 'نار']; const runs = 5; console.log('\n=== Search Latency (avg of 5 runs) ==='); for (const q of queries) { let total = 0; let totalResults = 0; for (let i = 0; i < runs; i++) { const start = performance.now(); const res = search( q, { quranData, morphologyMap, wordMap, invertedIndex }, { lemma: true, root: true }, { page: 1, limit: 20 }, fuseIndex, cache, ); total += performance.now() - start; totalResults = res.pagination.totalResults; } console.log(` "${q}": ${(total / runs).toFixed(2)}ms avg (${totalResults} results)`); } } main(); ``` ```bash npx tsx scripts/benchmark.ts ``` -------------------------------- ### LRUCache class Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md A generic LRU cache class that can be passed to search() to cache results. Uses JavaScript Map internally for O(1) get, set, and eviction. ```APIDOC ## LRUCache class ### Description A generic LRU cache class that can be passed to search() to avoid recomputing identical queries. Uses JavaScript Map internally for O(1) get, set, and eviction. ### Constructor new LRUCache(capacity) ### Parameters - **capacity** (number) - Required - Maximum number of entries to store. ### Methods - **set(key, value)** - Stores a value. - **get(key)** - Retrieves a value (moves to most-recent). - **has(key)** - Checks existence. - **delete(key)** - Removes one entry. - **clear()** - Removes all entries. - **size** (property) - Current number of entries. ### Request Example ```ts import { LRUCache } from 'quran-search-engine'; const cache = new LRUCache(100); // capacity = 100 entries cache.set('key', value); // Store a value cache.get('key'); // Retrieve (moves to most-recent) cache.has('key'); // Check existence cache.delete('key'); // Remove one entry cache.clear(); // Remove all entries cache.size; // Current number of entries ``` ### Response No return value for methods except get and has which return the value or boolean respectively. ``` -------------------------------- ### Import SearchWorkerClient Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/migration-guide.md The import remains the same, though the implementation is simplified. ```typescript import type { SearchWorkerClient } from 'quran-search-engine'; ``` ```typescript // Still imported as SearchWorkerClient, but implementation is now simpler import type { SearchWorkerClient } from 'quran-search-engine'; ``` -------------------------------- ### Enable type-aware ESLint rules Source: https://github.com/adelpro/quran-search-engine/blob/main/examples/vite-react/README.md Update the ESLint configuration to include type-aware linting rules for TypeScript files. This setup requires specifying the project tsconfig files in the languageOptions. ```js export default defineConfig([ globalIgnores(['dist']), { files: ['**/*.{ts,tsx}'], extends: [ // Other configs... // Remove tseslint.configs.recommended and replace with this tseslint.configs.recommendedTypeChecked, // Alternatively, use this for stricter rules tseslint.configs.strictTypeChecked, // Optionally, add this for stylistic rules tseslint.configs.stylisticTypeChecked, // Other configs... ], languageOptions: { parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, // other options... }, }, ]); ``` -------------------------------- ### Import Core Types Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Import the main types required for interacting with the search engine. ```ts import type { HighlightRange, MatchType, MorphologyAya, PaginationOptions, QuranText, ScoredQuranText, SearchOptions, SearchCounts, SearchResponse, WordMap, } from 'quran-search-engine'; ``` -------------------------------- ### search(query, context, options?, pagination?, fuseIndex?, cache?) Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Main entry point for Quran search. Combines exact text matching, lemma/root matching, fuzzy fallback, semantic expansion, range lookups, and regex pattern matching. Returns results with scoring and pagination. ```APIDOC ## search(query, context, options?, pagination?, fuseIndex?, cache?) ### Description Main entry point for Quran search. Combines exact text matching, lemma/root matching, fuzzy fallback, semantic expansion, range lookups, and regex pattern matching. Returns results with scoring and pagination. ### Method Function ### Signature search(query: string, context: SearchContext, options?: AdvancedSearchOptions, pagination?: PaginationOptions, fuseIndex?: Fuse, cache?: LRUCache): SearchResponse ### Parameters - **query** (string) - Required - Search query (Arabic text or range like `2:255`). - **context** (SearchContext) - Required - Object containing `quranData`, `morphologyMap`, `wordMap`, etc. - **options** (AdvancedSearchOptions) - Optional - Toggles for lemma/root/fuzzy/semantic (default: `{ lemma: true, root: true }`). - **pagination** (PaginationOptions) - Optional - Page and limit (default: `{ page: 1, limit: 20 }`). - **fuseIndex** (Fuse) - Optional - Pre-built Fuse index — skips rebuild on every call. - **cache** (LRUCache) - Optional - LRU cache — returns cached result for identical calls. ### Optimization Include a `fuseIndex` (from `createArabicFuseSearch`) or an `invertedIndex` within the `context` to skip recalculations. Pass an `LRUCache` instance to cache results. ### Example ```ts import { search } from 'quran-search-engine'; const response = search( 'الله الرحمن', { quranData, morphologyMap, wordMap, semanticMap }, { lemma: true, root: true, semantic: true }, // options { page: 1, limit: 10 } // pagination ); // Example output: // response.pagination => { totalResults: 42, totalPages: 5, currentPage: 1, limit: 10 } // response.counts => { simple: 10, lemma: 18, root: 9, fuzzy: 5, semantic: 0, total: 42 } // response.results[0] => { gid: 123, matchType: 'exact', matchScore: 9, matchedTokens: ['...'], ... } ``` ### Scoring | Match type | Score per hit | | ---------- | ------------- | | Exact | +3 | | Lemma | +2 | | Semantic | +0.8 | | Root | +1 | | Fuzzy | +0.5 (fallback only) | | Range | 1 (direct lookup) | | Regex | 1 | ### Search Layers The search engine processes queries through a series of architectural layers: 1. **Range layer** — Verse-coordinate queries (`2:255`, `1:1-7`) short-circuit all linguistic processing. 2. **Boolean layer** — Complex logic (`AND`, `OR`, `NOT`, `()`) handled via an AST-based parser when `isBoolean: true`. 3. **Regex layer** — Pattern queries (when `isRegex: true`) run in isolation; linguistic layers are skipped. 4. **Simple layer** — Exact token matching in normalized Arabic text. 5. **Linguistic layer** — Lemma and root matching via morphology data. 6. **Fuse layer** — Fuzzy fallback (Fuse.js) for tokens that produced no matches above. 7. **Semantic layer** — Concept expansion (when `semantic: true`). 8. **Phonetic layer** — Latin→Arabic transliteration for non-Arabic queries. ``` -------------------------------- ### TypeScript: Search with LRUCache caching Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Creates an LRUCache holding the last 50 search results and passes it to the search function. The first call computes and caches the result; a second call with the same parameters returns the cached result instantly (same reference). The example logs true for result1 === result2 to confirm the cache hit. ```TypeScript import { search, LRUCache, loadQuranData, loadMorphology, loadWordMap } from 'quran-search-engine'; import type { SearchResponse, QuranText } from 'quran-search-engine'; const [quranData, morphologyMap, wordMap] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), ]); const context = { quranData, morphologyMap, wordMap }; // Create a cache that holds the last 50 search results const cache = new LRUCache>(50); // First call: computes and caches the result const result1 = search( 'الله', context, { lemma: true, root: true }, { page: 1, limit: 20 }, undefined, cache, ); // Second call with same params: returns cached result instantly (same reference) const result2 = search( 'الله', context, { lemma: true, root: true }, { page: 1, limit: 20 }, undefined, cache, ); console.log(result1 === result2); // true — cache hit ``` -------------------------------- ### search() basic usage Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/api/core.md Calls search() with a multi-word query, context object, options enabling lemma and root matching, and pagination. Returns a SearchResponse. ```typescript import { search } from 'quran-search-engine'; const response = search( 'الله الرحمن', { quranData, morphologyMap, wordMap }, { lemma: true, root: true }, { page: 1, limit: 10 }, ); ``` -------------------------------- ### loadQuranData() Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Loads the Quran dataset once at app startup (browser or Node) and returns an array of QuranText objects. This data can then be reused in searches. ```APIDOC ## loadQuranData() ### Description Loads the Quran dataset once at app startup (browser or Node), then reuse in searches. ### Method loadQuranData() ### Parameters None ### Returns - **Promise** - Array of QuranText objects, each containing fields like gid, uthmani, standard, sura_id, aya_id, etc. ### Example ```ts import { loadQuranData, type QuranText } from 'quran-search-engine'; const quranData: QuranText[] = await loadQuranData(); // Example output: // quranData[0] => { gid: 1, uthmani: '...', standard: '...', sura_id: 1, aya_id: 1, ... } ``` ``` -------------------------------- ### Measure Index Build or Load Time Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/performance.md Compare the performance of building the inverted index at runtime versus loading a pre-built index. ```typescript import { buildInvertedIndex, loadInvertedIndex } from 'quran-search-engine'; // Option A: Build at runtime (CPU cost) const t0 = performance.now(); const invertedIndex = buildInvertedIndex(morphologyMap, quranData); console.log(`buildInvertedIndex: ${(performance.now() - t0).toFixed(2)}ms`); // Option B: Load pre-built index (faster startup) const t1 = performance.now(); const invertedIndexLoaded = await loadInvertedIndex(); console.log(`loadInvertedIndex: ${(performance.now() - t1).toFixed(2)}ms`); ``` -------------------------------- ### Load Pre-built Inverted Index with loadInvertedIndex() Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Avoids the CPU cost of building the index by loading pre-computed JSON files from disk. ```ts import { loadInvertedIndex } from 'quran-search-engine'; // Load the pre-built index — no CPU build cost const invertedIndex = await loadInvertedIndex(); ``` -------------------------------- ### Perform Multi-word AND Search Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/guides/search-syntax.md Demonstrates a standard search using AND logic where the query is tokenized and intersected across the provided data. ```typescript const response = search('الله الرحمن', quranData, morphologyMap, wordMap, { lemma: true, root: true, }); // Internally: // Token 1 => Matches 'الله' // AND // Token 2 => Matches 'الرحمن' // Result => Sura 1:1, 1:3, etc. ``` -------------------------------- ### Measure Data Loading Time Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/performance.md Load datasets once at startup and measure the elapsed time using performance.now(). ```typescript import { loadQuranData, loadMorphology, loadWordMap } from 'quran-search-engine'; const start = performance.now(); const [quranData, morphologyMap, wordMap] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), ]); const loadTime = performance.now() - start; console.log(`Data loading: ${loadTime.toFixed(2)}ms`); console.log(` Verses: ${quranData.length}`); ``` -------------------------------- ### Perform a multi-word search Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Demonstrates how to execute a multi-word search query using the search function with lemma and root matching enabled. ```ts const response = search( 'الله الرحمن', { quranData, morphologyMap, wordMap }, { lemma: true, root: true, }, ); // Example output: // response.results => all returned verses match BOTH tokens (AND logic) ``` -------------------------------- ### Access SURAS constant and iterate all surahs Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/api/core.md Imports the SURAS Map and retrieves a specific surah by ID (2 for Al-Baqarah), logging its metadata. Also demonstrates iterating over all surahs with forEach. ```typescript import { SURAS } from 'quran-search-engine'; const alBaqarah = SURAS.get(2); console.log(alBaqarah); // { // id: 2, // sura_name: 'البقرة', // sura_name_en: 'Al-Baqarah', // sura_name_romanization: 'Al-Baqarah', // total_verses: 286, // juz_ids: [1, 2, 3], // page_start: 1, // page_end: 141 // } // Iterate all surahs SURAS.forEach((sura) => { console.log(`${sura.id}: ${sura.sura_name_en} (${sura.total_verses} verses)`); }); ``` -------------------------------- ### Build Inverted Index from Loaded Data Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Builds the inverted index at startup to replace O(n) linear scans with O(1) lookups. This approach avoids extra I/O but costs one CPU pass during initialization. ```ts import { buildInvertedIndex, loadMorphology, loadQuranData, loadWordMap, search, } from 'quran-search-engine'; const [quranData, morphologyMap, wordMap] = await Promise.all([ loadQuranData(), loadMorphology(), loadWordMap(), ]); // Build once — replaces O(n) scans with O(1) lookups const invertedIndex = buildInvertedIndex(morphologyMap, quranData); // Pass as 9th argument on every search const result = search( 'الرحمن', quranData, morphologyMap, wordMap, { lemma: true, root: true }, { page: 1, limit: 20 }, undefined, // preComputedFuseIndex undefined, // cache invertedIndex, // <--- 9th parameter ); ``` -------------------------------- ### Initialize Worker with Dynamic URL Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/migration-guide.md Loads the worker URL dynamically and initializes the search worker with it, then calls initData. ```typescript let workerUrl: string | null = null; async function loadWorkerUrl() { if (!workerUrl) { const mod = await import('quran-search-engine/worker?url'); workerUrl = mod.default; } return workerUrl; } // Then when initializing: const url = await loadWorkerUrl(); const client = createSearchWorker({ workerUrl: url }); await client.initData(); ``` -------------------------------- ### loadInvertedIndex() Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Loads the pre-built inverted index from bundled static JSON files (lemma-index.json, root-index.json, word-index.json) and reconstructs them as Map> structures. This avoids the CPU cost of buildInvertedIndex. ```APIDOC ## loadInvertedIndex() ### Description Loads the pre-built inverted index from the bundled static JSON files (lemma-index.json, root-index.json, word-index.json) and reconstructs them as Map> structures. This avoids the CPU cost of buildInvertedIndex. ### Method loadInvertedIndex() ### Parameters None ### Returns - **Promise** - The reconstructed inverted index object. ### Example ```ts import { loadInvertedIndex } from 'quran-search-engine'; // Load the pre-built index — no CPU build cost const invertedIndex = await loadInvertedIndex(); ``` ``` -------------------------------- ### getHighlightRanges(text, matchedTokens, tokenTypes?) Source: https://github.com/adelpro/quran-search-engine/blob/main/docs/reference/api/core.md Computes an array of non-overlapping highlight ranges over the original uthmani text. Pure function that avoids HTML rendering, placing control in the UI's hands. ```APIDOC ## getHighlightRanges(text, matchedTokens, tokenTypes?) ### Description Computes an array of non-overlapping highlight ranges over the original uthmani text. Pure function that avoids HTML rendering, placing control in the UI's hands. ### Parameters - `text` (string): The original uthmani text. - `matchedTokens` (unknown): The matched tokens from the search results. - `tokenTypes` (unknown, optional): The token types. ### Returns `HighlightRange[]` ### Example ```typescript import { getHighlightRanges } from 'quran-search-engine'; // verse is a ScoredQuranText object from the search results const ranges = getHighlightRanges(verse.uthmani, verse.matchedTokens, verse.tokenTypes); ``` ``` -------------------------------- ### Run local verification checks Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md A combined command to ensure all project checks pass locally before submitting changes. ```bash yarn run lint && yarn run test && yarn run build ``` -------------------------------- ### Load Quran Data with loadQuranData() Source: https://github.com/adelpro/quran-search-engine/blob/main/README.md Loads the Quran dataset once at application startup for reuse in search operations. ```ts import { loadQuranData, type QuranText } from 'quran-search-engine'; const quranData: QuranText[] = await loadQuranData(); // Example output: // quranData[0] => { gid: 1, uthmani: '...', standard: '...', sura_id: 1, aya_id: 1, ... } ```