@aiquants/fuzzy-search
Version:
Advanced fuzzy search library with Levenshtein distance, n-gram indexing, and Web Worker support
1,091 lines (1,085 loc) • 50 kB
TypeScript
/**
* @module types/index
* @description Core types for the fuzzy search library.
* @description あいまい検索ライブラリのコア型定義。
*/
/**
* @interface FuzzySearchOptions
* @description Configuration options for fuzzy search functionality.
* @description あいまい検索機能の設定オプション。
*/
interface FuzzySearchOptions {
/**
* @property {number} threshold - Similarity threshold (0.0-1.0).
* @description 類似度の閾値。この値以上のスコアを持つアイテムが結果に含まれます。
*/
threshold: number;
/**
* @property {boolean} caseSensitive - Whether to perform case-sensitive search.
* @description 大文字小文字を区別するかどうか。true の場合、区別して検索します。
*/
caseSensitive: boolean;
/**
* @property {number} learningWeight - Learning weight for user behavior (0.0-2.0).
* @description ユーザーの選択行動に基づく学習による重み付け。1.0より大きいと学習効果が強まります。
*/
learningWeight: number;
/**
* @property {number} debounceMs - Debounce time in milliseconds.
* @description 検索入力のデバウンス時間(ミリ秒)。連続入力時の不要な検索処理を防ぎます。
*/
debounceMs: number;
/**
* @property {'and' | 'or'} multiTermOperator - Logical operator applied to space-separated query terms.
* @description スペース区切りのクエリ語に適用する論理演算子。
*/
multiTermOperator: "and" | "or";
/**
* @property {boolean} autoSearchOnIndexRebuild - Whether to trigger a search immediately after the index is rebuilt.
* @description インデックス再構築直後に自動的に検索を実行するかどうか。
*/
autoSearchOnIndexRebuild: boolean;
/**
* @property {Record<string, number>} customWeights - Custom field weights for scoring.
* @description 特定のフィールドに対するカスタムの重み設定。スコアリングに影響します。
*/
customWeights: Record<string, number>;
/**
* @property {number} ngramSize - N-gram size for indexing (default: 2).
* @description インデックス作成に使用する N-gram のサイズ。通常は2または3が使われます。
*/
ngramSize: number;
/**
* @property {number} minNgramOverlap - Minimum n-gram overlap for candidate filtering.
* @description 候補フィルタリングのための最小 N-gram 重複数。
*/
minNgramOverlap: number;
/**
* @property {'score' | 'relevance' | 'original'} sortBy - Sort results by field.
* @description 検索結果のソート基準。'score' (類似度スコア)、'relevance' (関連性)、'original' (元の順序) から選択します。
*/
sortBy: "score" | "relevance" | "original";
/**
* @property {'asc' | 'desc'} sortOrder - Sort order (ascending or descending).
* @description ソート順序 (昇順または降順)。
*/
sortOrder: "asc" | "desc";
/**
* @property {boolean} enableIndexFiltering - Enable index-based filtering stage.
* @description インデックスベースのフィルタリングステージを有効にするかどうか。
*/
enableIndexFiltering: boolean;
/**
* @property {boolean} enableLevenshtein - Enable Levenshtein distance calculation stage.
* @description レーベンシュタイン距離計算ステージを有効にするかどうか。
*/
enableLevenshtein: boolean;
/**
* @property {'index-first' | 'levenshtein-first' | 'balanced'} parallelSearchStrategy - Parallel search strategy.
* @description 並列検索の戦略。'index-first' (インデックス優先)、'levenshtein-first' (レーベンシュタイン優先)、'balanced' (バランス) から選択します。
*/
parallelSearchStrategy: "index-first" | "levenshtein-first" | "balanced";
/**
* @property {object} [workerUrls] - Custom Worker URLs for external hosting.
* @description 外部ホスティング用のカスタム Worker URL。
*/
workerUrls?: {
/**
* @property {string} [indexWorker] - URL for the index worker.
* @description Index Worker の URL。
*/
indexWorker?: string;
/**
* @property {string} [levenshteinWorker] - URL for the levenshtein worker.
* @description Levenshtein Worker の URL。
*/
levenshteinWorker?: string;
};
/**
* @property {object} [indexWorkerOptions] - Index Worker specific parameters.
* @description Index Worker 固有のパラメータ。
*/
indexWorkerOptions?: {
/**
* @property {IndexStrategy} [strategy] - Index Worker search strategy ('fast' | 'accurate' | 'hybrid').
* @description Index Worker の検索戦略。
*/
strategy?: IndexStrategy;
/**
* @property {number} [threshold] - Similarity threshold for Index Worker (0.0-1.0).
* @description Index Worker 用の類似度閾値。
*/
threshold?: number;
/**
* @property {number} [ngramOverlapThreshold] - N-gram overlap threshold ratio (0.0-1.0).
* @description N-gram 重複閾値の比率。
*/
ngramOverlapThreshold?: number;
/**
* @property {number} [minCandidatesRatio] - Minimum candidates ratio for fast search (0.0-1.0).
* @description 高速検索用の最小候補比率。
*/
minCandidatesRatio?: number;
/**
* @property {number} [maxCandidatesRatio] - Maximum candidates ratio to trigger filtering (0.0-1.0).
* @description フィルタリングを発動するための最大候補比率。
*/
maxCandidatesRatio?: number;
/**
* @property {number} [jaroWinklerPrefix] - Jaro-Winkler prefix scaling factor (0.0-0.25).
* @description Jaro-Winkler アルゴリズムの接頭辞スケーリング係数。
*/
jaroWinklerPrefix?: number;
/**
* @property {number} [maxResults] - Maximum number of results for Index Worker.
* @description Index Worker 用の最大結果数。
*/
maxResults?: number;
/**
* @property {number} [relevanceFieldWeight] - Weight for matched field count in relevance score (0.0-1.0).
* @description relevance スコア計算時のマッチフィールド数の重み。
*/
relevanceFieldWeight?: number;
/**
* @property {number} [relevancePerfectMatchBonus] - Bonus for perfect match in relevance score (0.0-1.0).
* @description relevance スコア計算時の完全一致ボーナス。
*/
relevancePerfectMatchBonus?: number;
};
/**
* @property {object} [levenshteinWorkerOptions] - Levenshtein Worker specific parameters.
* @description Levenshtein Worker 固有のパラメータ。
*/
levenshteinWorkerOptions?: {
/**
* @property {number} [threshold] - Similarity threshold for Levenshtein Worker (0.0-1.0).
* @description Levenshtein Worker 用の類似度閾値。
*/
threshold?: number;
/**
* @property {number} [lengthSimilarityThreshold] - Length-based similarity threshold for early rejection.
* @description 長さベースの類似度閾値(早期リジェクション用)。
*/
lengthSimilarityThreshold?: number;
/**
* @property {number} [partialMatchBonus] - Partial match bonus score.
* @description 部分一致が検出された場合に加算されるボーナススコア。
*/
partialMatchBonus?: number;
/**
* @property {number} [lengthDiffPenalty] - Length difference penalty ratio.
* @description 文字列長の差によるペナルティの比率。
*/
lengthDiffPenalty?: number;
/**
* @property {number} [maxResults] - Maximum number of results for Levenshtein Worker.
* @description Levenshtein Worker 用の最大結果数。
*/
maxResults?: number;
/**
* @property {number} [relevanceFieldWeight] - Weight for matched field count in relevance score (0.0-1.0).
* @description relevance スコア計算時のマッチフィールド数の重み。
*/
relevanceFieldWeight?: number;
};
}
/**
* @type PartialFuzzySearchOptions
* @description Partial options for initializing fuzzy search. Allows overriding a subset of the default options.
* @description あいまい検索初期化用の部分オプション。デフォルトオプションの一部を上書きできます。
*/
type PartialFuzzySearchOptions = Partial<FuzzySearchOptions>;
/**
* @const DEFAULT_FUZZY_SEARCH_OPTIONS
* @description Default options for fuzzy search. Used when no options are provided.
* @description あいまい検索のデフォルトオプション。オプションが指定されなかった場合に使用されます。
*/
declare const DEFAULT_FUZZY_SEARCH_OPTIONS: FuzzySearchOptions;
/**
* @interface SearchResultItem
* @description Represents an individual search result item with metadata.
* @description メタデータを含む個別の検索結果アイテムを表します。
* @template T - The type of the original item.
*/
interface SearchResultItem<T = unknown> {
/**
* @property {T} item - The original item from the search dataset.
* @description 検索データセットの元のアイテム。
*/
item: T;
/**
* @property {number} score - Final similarity score (0.0-1.0+). May exceed 1.0 in Relevance mode due to bonuses.
* @description 最終的な類似度スコア (0.0-1.0+)。Relevance モードではボーナスにより 1.0 を超える場合があります。
*/
score: number;
/**
* @property {number} baseScore - Base similarity score before any adjustments (0.0-1.0).
* @description 調整前の基本類似度スコア (0.0-1.0)。Relevance モードの重み付け前の値です。
*/
baseScore: number;
/**
* @property {string[]} matchedFields - Fields that matched the search query.
* @description 検索クエリにマッチしたフィールドのリスト。
*/
matchedFields: string[];
/**
* @property {number} [originalIndex] - Original index in the source dataset.
* @description 元のデータセットにおけるインデックス。
*/
originalIndex?: number;
/**
* @property {Record<string, unknown>} [metadata] - Additional metadata for the result.
* @description 結果に関連する追加のメタデータ。
*/
metadata?: Record<string, unknown>;
}
/**
* @interface SearchResults
* @description Represents the complete search results, including items and metadata.
* @description アイテムとメタデータを含む完全な検索結果を表します。
* @template T - The type of the items in the results.
*/
interface SearchResults<T = unknown> {
/**
* @property {SearchResultItem<T>[]} results - Array of search result items.
* @description 検索結果アイテムの配列。
*/
results: SearchResultItem<T>[];
/**
* @property {number} totalItems - Total number of items searched.
* @description 検索対象となった総アイテム数。
*/
totalItems: number;
/**
* @property {number} processingTime - Time taken for the search operation (ms).
* @description 検索処理全体にかかった時間(ミリ秒)。
*/
processingTime: number;
/**
* @property {string} query - The search query that was used.
* @description この検索で使用された検索クエリ。
*/
query: string;
/**
* @property {Partial<FuzzySearchOptions>} [options] - Search options used for this search.
* @description この検索で使用された検索オプション。
*/
options?: Partial<FuzzySearchOptions>;
/**
* @property {SearchStats} [stats] - Additional search statistics.
* @description 追加の検索統計情報。
*/
stats?: SearchStats;
}
/**
* @type IndexStrategy
* @description Enumeration of available index strategies.
* @description 利用可能なインデックス戦略の列挙。
* - `fast`: N-gram index only for quick filtering. 高速なフィルタリングのためのN-gramインデックスのみ。
* - `accurate`: Word-based and phonetic indexes for higher accuracy. 高精度な単語ベースおよび音韻インデックス。
* - `hybrid`: A combination of fast and accurate strategies. 高速戦略と高精度戦略の組み合わせ。
*/
type IndexStrategy = "fast" | "accurate" | "hybrid";
/**
* @type ParallelSearchStrategy
* @description Options for parallel search strategy.
* @description 並列検索戦略のオプション。
*
* @x-type-gen-skip-doc
*/
type ParallelSearchStrategy = "index-first" | "levenshtein-first" | "balanced";
/**
* @interface ParallelSearchStageResult
* @description Represents the result from a single stage in the parallel search pipeline.
* @description 並列検索パイプラインの単一ステージからの結果を表します。
* @template T - The type of the items in the results.
*/
interface ParallelSearchStageResult<T = unknown> {
/**
* @property {'index' | 'levenshtein'} stage - Stage identifier.
* @description ステージの識別子 ('index' または 'levenshtein')。
*/
stage: "index" | "levenshtein";
/**
* @property {SearchResultItem<T>[]} results - Search results from this stage.
* @description このステージからの検索結果。
*/
results: SearchResultItem<T>[];
/**
* @property {number} processingTime - Processing time for this stage.
* @description このステージの処理時間。
*/
processingTime: number;
/**
* @property {number} confidence - Confidence score for the results of this stage.
* @description このステージの結果に対する信頼度スコア。
*/
confidence: number;
/**
* @property {number} candidatesProcessed - Number of candidates processed in this stage.
* @description このステージで処理された候補数。
*/
candidatesProcessed: number;
}
/**
* @interface MergedParallelSearchResult
* @description Represents the merged result from the parallel search pipeline.
* @description 並列検索パイプラインからマージされた結果を表します。
* @template T - The type of the items in the results.
*/
interface MergedParallelSearchResult<T = unknown> {
/**
* @property {SearchResultItem<T>[]} results - Final merged search results.
* @description 最終的にマージされた検索結果。
*/
results: SearchResultItem<T>[];
/**
* @property {ParallelSearchStageResult<T>} indexStage - Results from the index stage.
* @description インデックスステージからの結果。
*/
indexStage: ParallelSearchStageResult<T>;
/**
* @property {ParallelSearchStageResult<T>} levenshteinStage - Results from the Levenshtein stage.
* @description レーベンシュタインステージからの結果。
*/
levenshteinStage: ParallelSearchStageResult<T>;
/**
* @property {number} totalProcessingTime - Total processing time for the entire pipeline.
* @description パイプライン全体の総処理時間。
*/
totalProcessingTime: number;
/**
* @property {ParallelSearchStrategy} mergeStrategy - Merge strategy used.
* @description 使用されたマージ戦略。
*/
mergeStrategy: ParallelSearchStrategy;
/**
* @property {number} mergeQuality - Quality score of the merged results.
* @description マージされた結果の品質スコア。
*/
mergeQuality: number;
}
/**
* @interface UnifiedWorkerResponse
* @description Completely unified response structure for all worker types.
* @description すべてのワーカータイプに対応する完全統一レスポンス構造。
* @template T - The type of items in the search results.
*/
interface UnifiedWorkerResponse<T = unknown> {
type: string;
id: string;
stats: UnifiedWorkerStats;
metrics: WorkerPerformanceMetrics;
processingTime: number;
results?: SearchResultItem<T>[];
error?: string;
workerType: "index" | "levenshtein";
operationMeta?: Record<string, unknown>;
}
/**
* @interface PerformanceInsights
* @description Data providing insights into search performance.
* @description 検索パフォーマンスに関する洞察を提供するデータ。
*/
interface PerformanceInsights {
recentAverageProcessingTime: number;
recentAverageResultCount: number;
throughputPerSecond: number;
totalHistoryEntries: number;
mostCommonQueryLength: number;
bestPerformingField: string;
similarityDistribution: {
highSimilarity: number;
mediumSimilarity: number;
lowSimilarity: number;
veryLowSimilarity: number;
};
}
/**
* @interface PerformanceHistoryEntry
* @description Individual performance history entry for tracking operation performance.
* @description 操作パフォーマンスを追跡するための個別のパフォーマンス履歴エントリ。
*/
interface PerformanceHistoryEntry {
timestamp: number;
queryLength: number;
itemCount: number;
processingTime: number;
resultCount: number;
operationType: string;
additionalMetrics?: Record<string, unknown>;
}
/**
* @interface FieldStatistic
* @description Statistics for individual search fields across all operations.
* @description 全操作における個別検索フィールドの統計。
*/
interface FieldStatistic {
matchCount: number;
averageScore: number;
totalScore: number;
bestScore: number;
worstScore: number;
}
/**
* @interface UnifiedWorkerStats
* @description Completely unified statistics interface for all worker types.
* @description すべてのワーカータイプに対応する完全統一統計インターフェース。
*/
interface UnifiedWorkerStats {
/**
* @property basic Basic statistics common to all workers.
* @description 全ワーカー共通の基本統計。
*/
basic: {
totalSearches: number;
totalProcessingTime: number;
averageSearchTime: number;
lastSearchTime: number;
errorCount: number;
timestamp: number;
};
/**
* @property workerSpecific Worker-type specific statistics.
* @description ワーカータイプ固有の統計。
*/
workerSpecific: {
workerType: "index" | "levenshtein";
operationCount: number;
operationDistribution: Record<string, number>;
specificMetrics: Record<string, unknown>;
};
/**
* @property analysis Advanced analysis and insights.
* @description 高度な分析とインサイト。
*/
analysis: {
fieldPerformance: Record<string, FieldStatistic>;
performanceInsights: PerformanceInsights;
recentHistory: PerformanceHistoryEntry[];
};
}
/**
* @interface WorkerPerformanceMetrics
* @description Performance metrics for detailed monitoring of a Worker.
* @description Worker の詳細な監視のためのパフォーマンスメトリクス。
*/
interface WorkerPerformanceMetrics {
timings: {
averageProcessingTime: number;
fastestProcessing: number;
slowestProcessing: number;
lastProcessingTime: number;
};
throughput: {
operationsPerSecond: number;
totalOperations: number;
};
quality: {
successRate: number;
errorRate: number;
timeoutRate: number;
};
}
/**
* @interface SearchStats
* @description Overall search statistics for performance monitoring.
* @description パフォーマンス監視のための全体的な検索統計。
*/
interface SearchStats {
/**
* @property {number} totalSearches - Total number of searches performed.
* @description 実行された総検索数。
*/
totalSearches: number;
/**
* @property {number} averageSearchTime - Average search time in milliseconds.
* @description 平均検索時間(ミリ秒)。
*/
averageSearchTime: number;
/**
* @property {Array<{ query: string; count: number }>} popularQueries - Popular search queries.
* @description 人気のある検索クエリとその実行回数。
*/
popularQueries: Array<{
query: string;
count: number;
}>;
/**
* @property {Record<string, { averageTime: number; sampleSize: number }>} performanceBySize - Performance statistics by dataset size.
* @description データセットのサイズ別のパフォーマンス統計。
*/
performanceBySize: Record<string, {
averageTime: number;
sampleSize: number;
}>;
/**
* @property {object} workers - Worker statistics information.
* @description 各ワーカーの統計情報。
*/
workers: {
index: {
stats: UnifiedWorkerStats;
};
levenshtein: {
stats: UnifiedWorkerStats;
};
};
}
/**
* @interface SearchHistory
* @description Represents a single entry in the search history for learning and analytics.
* @description 学習と分析のための検索履歴の単一エントリを表します。
*/
interface SearchHistory {
/**
* @property {string} query - The search query.
* @description 検索クエリ。
*/
query: string;
/**
* @property {number} timestamp - Timestamp of the search.
* @description 検索が実行されたときのタイムスタンプ。
*/
timestamp: number;
/**
* @property {number} resultCount - Number of results found.
* @description 見つかった結果の数。
*/
resultCount: number;
/**
* @property {number} processingTime - Processing time in milliseconds.
* @description 処理にかかった時間(ミリ秒)。
*/
processingTime: number;
/**
* @property {number} [searchTime] - Alias for processingTime.
* @description processingTime のエイリアス。
*/
searchTime?: number;
/**
* @property {number} [selectedIndex] - Index of the selected result, if any.
* @description ユーザーが選択した結果のインデックス(存在する場合)。
*/
selectedIndex?: number;
/**
* @property {string} [selectedItemId] - ID of the selected item, if any.
* @description ユーザーが選択したアイテムのID(存在する場合)。
*/
selectedItemId?: string;
/**
* @property {number} [satisfactionScore] - User satisfaction score (1-5).
* @description ユーザー満足度スコア(1-5)。
*/
satisfactionScore?: number;
/**
* @property {boolean} successful - Whether the search was considered successful.
* @description 検索が成功したと見なされたかどうか。
*/
successful: boolean;
/**
* @property {string} [context] - Context or source of the search.
* @description 検索が実行されたコンテキストまたはソース。
*/
context?: string;
}
/**
* @interface LearningData
* @description Data structure for storing learned information to improve search results.
* @description 検索結果を改善するために学習した情報を格納するためのデータ構造。
*/
interface LearningData {
/**
* @property {Record<string, number>} fieldWeights - Field-specific weights learned from user behavior.
* @description ユーザーの行動から学習したフィールド固有の重み。
*/
fieldWeights: Record<string, number>;
/**
* @property {Record<string, number>} queryPatterns - Query patterns and their frequency count.
* @description クエリのパターンとその出現頻度。
*/
queryPatterns: Record<string, number>;
/**
* @property {object} userPreferences - User preferences and behavior.
* @description ユーザーの好みと行動の記録。
*/
userPreferences: {
preferredThreshold: number;
frequentFields: string[];
searchStyle: "exact" | "fuzzy" | "mixed";
lastUsedOptions: Partial<FuzzySearchOptions>;
};
/**
* @property {object} performanceMetrics - Performance metrics for learning optimization.
* @description 学習の最適化に使用されるパフォーマンス指標。
*/
performanceMetrics: {
averageSearchTime: Record<string, number>;
indexBuildTime: number;
};
}
/**
* @type ExtractItemType
* @description Utility type to extract the item type from a SearchResultItem.
* @description SearchResultItem からアイテムの型を抽出するためのユーティリティ型。
* @template T - The type of the SearchResultItem.
*/
type ExtractItemType<T> = T extends SearchResultItem<infer U> ? U : never;
/**
* @type SearchFields
* @description Defines the search fields with type safety, accepting keys of T or strings.
* @description 型安全性を備えた検索フィールドを定義します。T のキーまたは文字列を受け入れます。
* @template T - The type of the items being searched.
*/
type SearchFields<T> = Array<keyof T | string>;
/**
* @type SearchResultCallback
* @description Callback function type for handling search results.
* @description 検索結果を処理するためのコールバック関数型。
* @template T - The type of the items in the results.
*/
type SearchResultCallback<T> = (results: SearchResults<T>) => void;
/**
* @function isSearchResultItem
* @description Type guard to check if an object is a SearchResultItem.
* @description オブジェクトが SearchResultItem かどうかをチェックする型ガード。
* @param {unknown} obj - The object to check.
* @returns {boolean} - True if the object is a SearchResultItem.
* @template T - The expected type of the item within the SearchResultItem.
*/
declare function isSearchResultItem<T>(obj: unknown): obj is SearchResultItem<T>;
/**
* @type UseFuzzySearchOptions
* @description Options type for the useFuzzySearch hook, extending PartialFuzzySearchOptions.
* @description useFuzzySearch フック用のオプション型。PartialFuzzySearchOptions を拡張します。
*/
type UseFuzzySearchOptions = PartialFuzzySearchOptions;
/**
* @interface PerformanceMetrics
* @description Data type for the performance metrics callback.
* @description パフォーマンス指標コールバック用のデータ型。
*/
interface PerformanceMetrics {
totalSearches: number;
averageSearchTime: number;
itemCount: number;
resultsCount: number;
workerStats?: {
index?: UnifiedWorkerStats;
levenshtein?: UnifiedWorkerStats;
};
}
/**
* @interface FuzzySearchResult
* @description The return type for the simplified fuzzy search hook.
* @description 簡易版のあいまい検索フックの戻り値の型。
* @template T - The type of the items being searched.
*/
interface FuzzySearchResult<T> {
searchTerm: string;
setSearchTerm: (term: string) => void;
filteredItems: SearchResultItem<T>[];
isSearching: boolean;
isIndexBuilding: boolean;
error: string | null;
searchHistory: SearchHistory[];
options: FuzzySearchOptions;
selectItem: (item: T, index: number) => void;
clearSearch: () => void;
clearHistory: () => void;
resetStats: () => Promise<void>;
getSearchSuggestions: (query: string, limit?: number) => string[];
performanceMetrics: PerformanceMetrics;
rebuildIndex: (customOptions?: UseFuzzySearchOptions) => Promise<void>;
}
/**
* @module core/FuzzySearchManager
* @description Advanced fuzzy search manager with Web Worker integration and learning capabilities.
* @description Web Worker統合と学習機能を備えた高度なあいまい検索管理クラス。
*/
/**
* @class FuzzySearchManager
* @description Manages fuzzy search operations, integrating Web Workers for performance and including learning capabilities.
* @description Web Worker を統合してパフォーマンスを向上させ、学習機能も備えた、あいまい検索操作を管理するクラス。
* @template T - The type of items to be searched.
*/
declare class FuzzySearchManager<T = unknown> {
private defaultOptions;
private indexWorker;
private levenshteinWorker;
private searchHistory;
private learningData;
private requestId;
private pendingRequests;
private eventEmitter;
private workersInitialized;
private isIndexBuilt;
private lastIndexedDataHash;
private stats;
/**
* Constructor for the FuzzySearchManager.
* @param {FuzzySearchOptions} [defaultOptions] - Default options for fuzzy search.
*/
constructor(defaultOptions?: FuzzySearchOptions);
/**
* @private
* @method initializeWorkers
* @description Initializes both Index Strategy and Levenshtein Distance Workers using the global manager.
* @description グローバルマネージャーを使用して Index Strategy と Levenshtein Distance Worker の両方を初期化します。
* @returns {Promise<void>} A promise that resolves when workers are initialized and configured.
*/
private initializeWorkers;
/**
* @private
* @method testWorkerConnectivity
* @description Tests worker connectivity by sending ping messages and waiting for pong responses.
* @description ping メッセージを送信し、pong 応答を待つことでワーカーの接続性をテストします。
* @returns {Promise<void>} A promise that resolves when both workers have responded.
*/
private testWorkerConnectivity;
/**
* @private
* @method pingWorker
* @description Sends a ping message to a worker and waits for the pong response.
* @description ワーカーに ping メッセージを送り、pong 応答を待機します。
* @param {Worker} worker - The worker instance to ping.
* @param {'index' | 'levenshtein'} workerName - The worker identifier.
* @returns {Promise<void>} A promise that resolves when the worker responds.
*/
private pingWorker;
/**
* @private
* @method handleIndexWorkerMessage
* @description Handles messages received from the Index Strategy Worker.
* @description Index Strategy Worker から受信したメッセージを処理します。
* @param {MessageEvent} event - The message event from the worker.
*/
private handleIndexWorkerMessage;
/**
* @private
* @method handleIndexWorkerError
* @description Handles errors from the Index Strategy Worker.
* @description Index Strategy Worker からのエラーを処理します。
* @param {ErrorEvent} error - The error event from the worker.
*/
private handleIndexWorkerError;
/**
* @private
* @method handleLevenshteinWorkerMessage
* @description Handles messages received from the Levenshtein Distance Worker.
* @description Levenshtein Distance Worker から受信したメッセージを処理します。
* @param {MessageEvent<UnifiedWorkerResponse<T>>} event - The message event from the worker.
*/
private handleLevenshteinWorkerMessage;
/**
* @private
* @method handleLevenshteinWorkerError
* @description Handles errors from the Levenshtein Distance Worker.
* @description Levenshtein Distance Worker からのエラーを処理します。
* @param {ErrorEvent} error - The error event from the worker.
*/
private handleLevenshteinWorkerError;
/**
* @private
* @method isLocalStorageAvailable
* @description Checks if localStorage is available and accessible.
* @description localStorage が利用可能でアクセスできるかを確認します。
* @returns {boolean} True if localStorage is available, false otherwise.
*/
private isLocalStorageAvailable;
/**
* @private
* @method loadLearningData
* @description Loads learning data from localStorage. If not available, initializes with default data.
* @description localStorage から学習データを読み込みます。データが存在しない場合は、デフォルトデータで初期化します。
*/
private loadLearningData;
/**
* @private
* @method initializeDefaultLearningData
* @description Initializes the learning data with default values.
* @description 学習データをデフォルト値で初期化します。
*/
private initializeDefaultLearningData;
/**
* @private
* @method saveLearningData
* @description Saves the current learning data to localStorage.
* @description 現在の学習データを localStorage に保存します。
*/
private saveLearningData;
/**
* @method search
* @description Performs a fuzzy search using Web Workers. It orchestrates index building, parallel searching, and result merging.
* @description Web Worker を使用してあいまい検索を実行します。インデックス構築、並列検索、結果のマージを統括します。
* @param {string} query - The search query.
* @param {T[]} items - The array of items to search through.
* @param {string[]} searchFields - The fields within the items to search.
* @param {Partial<FuzzySearchOptions>} [options] - Options to override the defaults for this search.
* @returns {Promise<SearchResultItem<T>[]>} A promise that resolves with the search results.
*/
search(query: string, items: T[], searchFields: string[], options?: Partial<FuzzySearchOptions>): Promise<SearchResultItem<T>[]>;
/**
* @private
* @method buildIndex
* @description Sends a request to the Index Strategy Worker to build an index for the provided data.
* @description 提供されたデータのためのインデックスを構築するよう、Index Strategy Worker にリクエストを送信します。
* @param {T[]} items - The items to index.
* @param {string[]} searchFields - The fields to index.
* @param {FuzzySearchOptions} options - The search options.
* @returns {Promise<void>} A promise that resolves when the index is ready.
*/
private buildIndex;
/**
* @private
* @method searchParallel
* @description Executes the search pipeline in parallel using both the Index and Levenshtein workers.
* @description Index Worker と Levenshtein Worker の両方を使用して、検索パイプラインを並列実行します。
* @param {string} query - The search query.
* @param {T[]} items - The items to search.
* @param {string[]} searchFields - The fields to search in.
* @param {FuzzySearchOptions} options - The search options.
* @returns {Promise<SearchResultItem<T>[]>} A promise that resolves with the merged search results.
*/
private searchParallel;
/**
* @private
* @method runIndexStage
* @description Runs the index search stage of the parallel pipeline.
* @description 並列パイプラインのインデックス検索ステージを実行します。
* @param {string} query - The search query.
* @param {T[]} items - The items to search.
* @param {string[]} searchFields - The fields to search in.
* @param {FuzzySearchOptions} options - The search options.
* @returns {Promise<ParallelSearchStageResult<T>>} A promise that resolves with the results of the index stage.
*/
private runIndexStage;
/**
* @private
* @method runLevenshteinStage
* @description Runs the Levenshtein distance search stage of the parallel pipeline.
* @description 並列パイプラインのレーベンシュタイン距離検索ステージを実行します。
* @param {string} query - The search query.
* @param {T[]} items - The items to search.
* @param {string[]} searchFields - The fields to search in.
* @param {FuzzySearchOptions} options - The search options.
* @returns {Promise<ParallelSearchStageResult<T>>} A promise that resolves with the results of the Levenshtein stage.
*/
private runLevenshteinStage;
/**
* @private
* @method executeWorkerStage
* @description Executes a search stage by posting a request to the worker and managing the pending promise lifecycle.
* @description ワーカーにリクエストを送信し、保留中のプロミスを管理して検索ステージを実行します。
* @param {Worker | null} worker - The target worker instance.
* @param {IndexWorkerRequest<T> | LevenshteinWorkerRequest<T>} request - The request payload to send.
* @param {{ stage: 'index' | 'levenshtein'; confidence: number; timeoutMessage: string; unavailableMessage: string }} config - Stage configuration metadata.
* @returns {Promise<ParallelSearchStageResult<T>>} A promise resolving with the stage result.
*/
private executeWorkerStage;
/**
* @private
* @method mergeParallelResults
* @description Merges results from parallel search stages using a specified strategy.
* @description 指定された戦略を用いて、並列検索ステージからの結果をマージします。
* @param {ParallelSearchStageResult<T>} indexResult - The results from the index stage.
* @param {ParallelSearchStageResult<T>} levenshteinResult - The results from the Levenshtein stage.
* @param {ParallelSearchStrategy} strategy - The merging strategy to use.
* @param {FuzzySearchOptions} options - The search options containing sortBy and sortOrder.
* @returns {MergedParallelSearchResult<T>} The merged search result.
*/
private mergeParallelResults;
/**
* @private
* @method mergeByScore
* @description Merges an array of search results by score, removing duplicates based on originalIndex.
* @description スコアに基づいて検索結果の配列をマージし、originalIndex を使って重複を削除します。
* @param {SearchResultItem<T>[]} results - The search results to merge.
* @param {FuzzySearchOptions} options - The search options containing sortBy and sortOrder.
* @returns {SearchResultItem<T>[]} The merged and sorted search results.
*/
private mergeByScore;
/**
* @private
* @method generateDataHash
* @description Generates a simple hash for the current dataset to detect changes and avoid unnecessary index rebuilding.
* @description データセットの変更を検出し、不要なインデックスの再構築を避けるために、現在のデータセットのシンプルなハッシュを生成します。
* @param {T[]} items - The array of items.
* @param {string[]} searchFields - The fields being searched.
* @returns {string} A string hash representing the dataset.
*/
private generateDataHash;
/**
* @private
* @method updateStats
* @description Updates the overall search statistics.
* @description 全体的な検索統計を更新します。
* @param {string} _query - The search query (currently unused, but kept for future use).
* @param {number} processingTime - The time taken for the search.
*/
private updateStats;
/**
* @private
* @method updateLearningData
* @description Updates the learning data based on search patterns and performance.
* @description 検索パターンとパフォーマンスに基づいて学習データを更新します。
* @param {string} query - The search query.
* @param {number} itemCount - The number of items searched.
* @param {number} processingTime - The time taken for the search.
*/
private updateLearningData;
/**
* @private
* @method getPerformanceSizeKey
* @description Gets a size key for categorizing datasets to track performance by size.
* @description データセットを分類し、サイズ別のパフォーマンスを追跡するためのサイズキーを取得します。
* @param {number} itemCount - The number of items in the dataset.
* @returns {string} The size category key ('small', 'medium', 'large', 'xlarge').
*/
private getPerformanceSizeKey;
/**
* @private
* @method cleanupPendingRequests
* @description Cleans up pending requests that have timed out.
* @description タイムアウトした保留中のリクエストをクリーンアップします。
*/
private cleanupPendingRequests;
/**
* @method updateSearchHistory
* @description Updates the search history for learning and analytical purposes.
* @description 学習および分析目的で検索履歴を更新します。
* @param {string} query - The search query.
* @param {string} [selectedItemId] - The ID of the item selected by the user.
* @param {number} [resultCount=0] - The number of results returned.
* @param {number} [searchTime=0] - The time taken for the search.
*/
updateSearchHistory(query: string, selectedItemId?: string, resultCount?: number, searchTime?: number): void;
/**
* @method getStats
* @description Asynchronously retrieves the latest statistics from all workers and returns the updated stats object.
* @description 全てのワーカーから最新の統計情報を非同期で取得し、更新された統計オブジェクトを返します。
* @param {number} [timeout=5000] - Timeout in milliseconds to wait for worker responses.
* @returns {Promise<SearchStats>} A promise that resolves with the latest search statistics.
*/
getStats(timeout?: number): Promise<SearchStats>;
/**
* @method getCurrentStats
* @description Gets the current statistics without triggering additional worker requests.
* @description 追加のワーカーリクエストをトリガーせずに現在の統計情報を取得します。
* @returns {SearchStats} The current search statistics.
*/
getCurrentStats(): SearchStats;
/**
* @method resetStats
* @description Resets statistics for all workers and clears the local stats cache.
* @description 全てのワーカーの統計情報をリセットし、ローカルの統計キャッシュをクリアします。
* @param {number} [timeout=5000] - Timeout in milliseconds to wait for worker responses.
* @returns {Promise<void>} A promise that resolves when all statistics have been reset.
*/
resetStats(timeout?: number): Promise<void>;
/**
* @private
* @method waitForWorkerStats
* @description Awaits a stats update event from the specified worker within the timeout window.
* @description 指定ワーカーからの統計更新イベントをタイムアウト時間内に待機します。
* @param {Worker | null} worker - The worker instance to query.
* @param {'index' | 'levenshtein'} workerName - The worker identifier.
* @param {number} timeout - Timeout in milliseconds for the wait.
* @returns {Promise<void>} A promise resolving when the event arrives or timeout occurs.
*/
private waitForWorkerStats;
/**
* @private
* @method resetWorkerStats
* @description Requests a worker to reset its statistics and waits for confirmation.
* @description ワーカーに統計リセットを要求し、完了通知を待機します。
* @param {Worker | null} worker - The worker instance to reset.
* @param {'index' | 'levenshtein'} workerName - The worker identifier.
* @param {number} timeout - Timeout in milliseconds for the wait.
* @returns {Promise<void>} A promise resolving when the reset completes or timeout occurs.
*/
private resetWorkerStats;
/**
* @private
* @method createEmptyWorkerStats
* @description Builds an empty UnifiedWorkerStats object for a given worker type.
* @description 指定されたワーカー種別の空の UnifiedWorkerStats オブジェクトを生成します。
* @param {'index' | 'levenshtein'} workerType - Target worker type.
* @returns {UnifiedWorkerStats} A freshly initialized stats object.
*/
private createEmptyWorkerStats;
/**
* @method getSearchHistory
* @description Gets the search history.
* @description 検索履歴を取得します。
* @returns {SearchHistory[]} A copy of the search history.
*/
getSearchHistory(): SearchHistory[];
/**
* @method on
* @description Registers an event listener for a specified event.
* @description 指定されたイベントのイベントリスナーを登録します。
* @param {string} event - The name of the event.
* @param {(data?: unknown) => void} listener - The callback function.
*/
on(event: string, listener: (data?: unknown) => void): void;
/**
* @method off
* @description Unregisters an event listener for a specified event.
* @description 指定されたイベントのイベントリスナーを登録解除します。
* @param {string} event - The name of the event.
* @param {(data?: unknown) => void} listener - The callback function to remove.
*/
off(event: string, listener: (data?: unknown) => void): void;
/**
* @method prebuildIndex
* @description Pre-builds the index with the given data to improve the performance of the first search.
* @description 初回検索のパフォーマンスを向上させるため、指定されたデータで事前にインデックスを構築します。
* @param {T[]} items - The items to index.
* @param {string[]} searchFields - The fields to index.
* @param {Partial<FuzzySearchOptions>} [options] - Search options for index building.
* @returns {Promise<void>} A promise that resolves when the index has been built.
*/
prebuildIndex(items: T[], searchFields: string[], options?: Partial<FuzzySearchOptions>): Promise<void>;
/**
* @description Forces a complete rebuild of the search index for the given items and fields.
* This method will clear existing indices and rebuild them from scratch.
* 指定されたアイテムとフィールドに対して検索インデックスの完全な再構築を強制実行します。
* このメソッドは既存のインデックスをクリアしてゼロから再構築します。
*
* @param items The items to rebuild the index for.
* @param searchFields The fields to include in the index.
* @param options The search options to use for building the index.
* @returns A promise that resolves when the index rebuild is complete.
* @param items インデックス再構築対象のアイテム。
* @param searchFields インデックスに含めるフィールド。
* @param options インデックス構築に使用する検索オプション。
* @returns インデックス再構築完了時に解決するPromise。
*/
rebuildIndex(items: T[], searchFields: string[], options?: Partial<FuzzySearchOptions>): Promise<void>;
/**
* @method dispose
* @description Disposes of the manager, releasing its reference to the global workers and cleaning up resources.
* @description マネージャーを破棄し、グローバルワーカーへの参照を解放してリソースをクリーンアップします。
*/
dispose(): void;
}
/**
* React hooks and utilities for fuzzy search functionality.
* あいまい検索機能用のReactフックとユーティリティ。
*
* Note: This module requires React as a peer dependency.
* 注意:このモジュールはReactをピア依存関係として必要とします。
*/
/**
* A simplified fuzzy search hook with stable state management.
* This hook provides an easy-to-use interface for performing fuzzy searches on a list of items.
* 安定した状態管理を持つ簡易あいまい検索フック。
* このフックは、アイテムのリストに対してあいまい検索を実行するための使いやすいインターフェースを提供します。
* @param items The array of items to search through.
* @param searchFields The fields in the items to search against.
* @param initialOptions Optional initial configuration for the fuzzy search.
* @returns An object containing the search state and functions.
*/
declare function useFuzzySearch<T>(items: T[], searchFields: Array<keyof T | string>, initialOptions?: UseFuzzySearchOptions): FuzzySearchResult<T>;
export { DEFAULT_FUZZY_SEARCH_OPTIONS, type ExtractItemType, type FieldStatistic, FuzzySearchManager, type FuzzySearchOptions, type LearningData, type MergedParallelSearchResult, type ParallelSearchStageResult, type ParallelSearchStrategy, type PartialFuzzySearchOptions, type PerformanceHistoryEntry, type PerformanceInsights, type SearchFields, type SearchHistory, type SearchResultCallback, type SearchResultItem, type SearchResults, type SearchStats, type UnifiedWorkerResponse, type UnifiedWorkerStats, type UseFuzzySearchOptions, isSearchResultItem, useFuzzySearch };