@danielsimonjr/memory-mcp 12.2.3 → 12.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +88 -102
  2. package/dist/index.js +6 -0
  3. package/dist/server/toolDefinitions.d.ts.map +1 -1
  4. package/dist/server/toolDefinitions.js +745 -3
  5. package/dist/server/toolHandlers.d.ts +1 -9
  6. package/dist/server/toolHandlers.d.ts.map +1 -1
  7. package/dist/server/toolHandlers.js +859 -11
  8. package/package.json +9 -6
  9. package/dist/core/EntityManager.d.ts +0 -263
  10. package/dist/core/EntityManager.d.ts.map +0 -1
  11. package/dist/core/EntityManager.js +0 -478
  12. package/dist/core/GraphStorage.d.ts +0 -344
  13. package/dist/core/GraphStorage.d.ts.map +0 -1
  14. package/dist/core/GraphStorage.js +0 -708
  15. package/dist/core/GraphTraversal.d.ts +0 -136
  16. package/dist/core/GraphTraversal.d.ts.map +0 -1
  17. package/dist/core/GraphTraversal.js +0 -556
  18. package/dist/core/HierarchyManager.d.ts +0 -111
  19. package/dist/core/HierarchyManager.d.ts.map +0 -1
  20. package/dist/core/HierarchyManager.js +0 -224
  21. package/dist/core/ManagerContext.d.ts +0 -72
  22. package/dist/core/ManagerContext.d.ts.map +0 -1
  23. package/dist/core/ManagerContext.js +0 -118
  24. package/dist/core/ObservationManager.d.ts +0 -85
  25. package/dist/core/ObservationManager.d.ts.map +0 -1
  26. package/dist/core/ObservationManager.js +0 -123
  27. package/dist/core/RelationManager.d.ts +0 -131
  28. package/dist/core/RelationManager.d.ts.map +0 -1
  29. package/dist/core/RelationManager.js +0 -210
  30. package/dist/core/SQLiteStorage.d.ts +0 -354
  31. package/dist/core/SQLiteStorage.d.ts.map +0 -1
  32. package/dist/core/SQLiteStorage.js +0 -917
  33. package/dist/core/StorageFactory.d.ts +0 -45
  34. package/dist/core/StorageFactory.d.ts.map +0 -1
  35. package/dist/core/StorageFactory.js +0 -64
  36. package/dist/core/TransactionManager.d.ts +0 -259
  37. package/dist/core/TransactionManager.d.ts.map +0 -1
  38. package/dist/core/TransactionManager.js +0 -392
  39. package/dist/core/index.d.ts +0 -16
  40. package/dist/core/index.d.ts.map +0 -1
  41. package/dist/core/index.js +0 -17
  42. package/dist/features/AnalyticsManager.d.ts +0 -44
  43. package/dist/features/AnalyticsManager.d.ts.map +0 -1
  44. package/dist/features/AnalyticsManager.js +0 -223
  45. package/dist/features/ArchiveManager.d.ts +0 -121
  46. package/dist/features/ArchiveManager.d.ts.map +0 -1
  47. package/dist/features/ArchiveManager.js +0 -240
  48. package/dist/features/CompressionManager.d.ts +0 -109
  49. package/dist/features/CompressionManager.d.ts.map +0 -1
  50. package/dist/features/CompressionManager.js +0 -404
  51. package/dist/features/IOManager.d.ts +0 -221
  52. package/dist/features/IOManager.d.ts.map +0 -1
  53. package/dist/features/IOManager.js +0 -997
  54. package/dist/features/StreamingExporter.d.ts +0 -105
  55. package/dist/features/StreamingExporter.d.ts.map +0 -1
  56. package/dist/features/StreamingExporter.js +0 -150
  57. package/dist/features/TagManager.d.ts +0 -147
  58. package/dist/features/TagManager.d.ts.map +0 -1
  59. package/dist/features/TagManager.js +0 -210
  60. package/dist/features/index.d.ts +0 -12
  61. package/dist/features/index.d.ts.map +0 -1
  62. package/dist/features/index.js +0 -11
  63. package/dist/search/BasicSearch.d.ts +0 -51
  64. package/dist/search/BasicSearch.d.ts.map +0 -1
  65. package/dist/search/BasicSearch.js +0 -137
  66. package/dist/search/BooleanSearch.d.ts +0 -98
  67. package/dist/search/BooleanSearch.d.ts.map +0 -1
  68. package/dist/search/BooleanSearch.js +0 -430
  69. package/dist/search/EmbeddingService.d.ts +0 -178
  70. package/dist/search/EmbeddingService.d.ts.map +0 -1
  71. package/dist/search/EmbeddingService.js +0 -358
  72. package/dist/search/FuzzySearch.d.ts +0 -118
  73. package/dist/search/FuzzySearch.d.ts.map +0 -1
  74. package/dist/search/FuzzySearch.js +0 -312
  75. package/dist/search/RankedSearch.d.ts +0 -71
  76. package/dist/search/RankedSearch.d.ts.map +0 -1
  77. package/dist/search/RankedSearch.js +0 -238
  78. package/dist/search/SavedSearchManager.d.ts +0 -79
  79. package/dist/search/SavedSearchManager.d.ts.map +0 -1
  80. package/dist/search/SavedSearchManager.js +0 -145
  81. package/dist/search/SearchFilterChain.d.ts +0 -120
  82. package/dist/search/SearchFilterChain.d.ts.map +0 -1
  83. package/dist/search/SearchFilterChain.js +0 -185
  84. package/dist/search/SearchManager.d.ts +0 -285
  85. package/dist/search/SearchManager.d.ts.map +0 -1
  86. package/dist/search/SearchManager.js +0 -338
  87. package/dist/search/SearchSuggestions.d.ts +0 -27
  88. package/dist/search/SearchSuggestions.d.ts.map +0 -1
  89. package/dist/search/SearchSuggestions.js +0 -57
  90. package/dist/search/SemanticSearch.d.ts +0 -146
  91. package/dist/search/SemanticSearch.d.ts.map +0 -1
  92. package/dist/search/SemanticSearch.js +0 -313
  93. package/dist/search/TFIDFIndexManager.d.ts +0 -63
  94. package/dist/search/TFIDFIndexManager.d.ts.map +0 -1
  95. package/dist/search/TFIDFIndexManager.js +0 -215
  96. package/dist/search/VectorStore.d.ts +0 -235
  97. package/dist/search/VectorStore.d.ts.map +0 -1
  98. package/dist/search/VectorStore.js +0 -311
  99. package/dist/search/index.d.ts +0 -18
  100. package/dist/search/index.d.ts.map +0 -1
  101. package/dist/search/index.js +0 -21
  102. package/dist/types/index.d.ts +0 -13
  103. package/dist/types/index.d.ts.map +0 -1
  104. package/dist/types/index.js +0 -12
  105. package/dist/types/types.d.ts +0 -1234
  106. package/dist/types/types.d.ts.map +0 -1
  107. package/dist/types/types.js +0 -9
  108. package/dist/utils/compressedCache.d.ts +0 -192
  109. package/dist/utils/compressedCache.d.ts.map +0 -1
  110. package/dist/utils/compressedCache.js +0 -309
  111. package/dist/utils/compressionUtil.d.ts +0 -214
  112. package/dist/utils/compressionUtil.d.ts.map +0 -1
  113. package/dist/utils/compressionUtil.js +0 -247
  114. package/dist/utils/constants.d.ts +0 -245
  115. package/dist/utils/constants.d.ts.map +0 -1
  116. package/dist/utils/constants.js +0 -252
  117. package/dist/utils/entityUtils.d.ts +0 -321
  118. package/dist/utils/entityUtils.d.ts.map +0 -1
  119. package/dist/utils/entityUtils.js +0 -538
  120. package/dist/utils/errors.d.ts +0 -77
  121. package/dist/utils/errors.d.ts.map +0 -1
  122. package/dist/utils/errors.js +0 -121
  123. package/dist/utils/formatters.d.ts +0 -145
  124. package/dist/utils/formatters.d.ts.map +0 -1
  125. package/dist/utils/formatters.js +0 -132
  126. package/dist/utils/index.d.ts +0 -22
  127. package/dist/utils/index.d.ts.map +0 -1
  128. package/dist/utils/index.js +0 -75
  129. package/dist/utils/indexes.d.ts +0 -270
  130. package/dist/utils/indexes.d.ts.map +0 -1
  131. package/dist/utils/indexes.js +0 -526
  132. package/dist/utils/logger.d.ts +0 -24
  133. package/dist/utils/logger.d.ts.map +0 -1
  134. package/dist/utils/logger.js +0 -33
  135. package/dist/utils/parallelUtils.d.ts +0 -72
  136. package/dist/utils/parallelUtils.d.ts.map +0 -1
  137. package/dist/utils/parallelUtils.js +0 -169
  138. package/dist/utils/schemas.d.ts +0 -374
  139. package/dist/utils/schemas.d.ts.map +0 -1
  140. package/dist/utils/schemas.js +0 -484
  141. package/dist/utils/searchAlgorithms.d.ts +0 -99
  142. package/dist/utils/searchAlgorithms.d.ts.map +0 -1
  143. package/dist/utils/searchAlgorithms.js +0 -167
  144. package/dist/utils/searchCache.d.ts +0 -108
  145. package/dist/utils/searchCache.d.ts.map +0 -1
  146. package/dist/utils/searchCache.js +0 -209
  147. package/dist/utils/taskScheduler.d.ts +0 -290
  148. package/dist/utils/taskScheduler.d.ts.map +0 -1
  149. package/dist/utils/taskScheduler.js +0 -466
  150. package/dist/workers/WorkerPool.d.ts +0 -81
  151. package/dist/workers/WorkerPool.d.ts.map +0 -1
  152. package/dist/workers/WorkerPool.js +0 -121
  153. package/dist/workers/index.d.ts +0 -12
  154. package/dist/workers/index.d.ts.map +0 -1
  155. package/dist/workers/index.js +0 -9
  156. package/dist/workers/levenshteinWorker.d.ts +0 -60
  157. package/dist/workers/levenshteinWorker.d.ts.map +0 -1
  158. package/dist/workers/levenshteinWorker.js +0 -98
@@ -1,167 +0,0 @@
1
- /**
2
- * Search Algorithms
3
- *
4
- * Algorithms for search operations: Levenshtein distance for fuzzy matching
5
- * and TF-IDF for relevance scoring.
6
- *
7
- * @module utils/searchAlgorithms
8
- */
9
- // ==================== Levenshtein Distance ====================
10
- /**
11
- * Calculate Levenshtein distance between two strings.
12
- *
13
- * Returns the minimum number of single-character edits needed to change
14
- * one word into another.
15
- *
16
- * **Algorithm**: Space-optimized dynamic programming using only two rows.
17
- * Time complexity: O(m*n), Space complexity: O(min(m,n)).
18
- *
19
- * This optimization reduces memory usage from O(m*n) to O(min(m,n)) by
20
- * observing that each row only depends on the previous row.
21
- *
22
- * @param str1 - First string to compare
23
- * @param str2 - Second string to compare
24
- * @returns Minimum number of edits required (0 = identical strings)
25
- *
26
- * @example
27
- * ```typescript
28
- * levenshteinDistance("kitten", "sitting"); // Returns 3
29
- * levenshteinDistance("hello", "hello"); // Returns 0
30
- * levenshteinDistance("abc", ""); // Returns 3
31
- * ```
32
- */
33
- export function levenshteinDistance(str1, str2) {
34
- // Ensure str1 is the shorter string for optimal space usage
35
- if (str1.length > str2.length) {
36
- [str1, str2] = [str2, str1];
37
- }
38
- const m = str1.length;
39
- const n = str2.length;
40
- // Use two rows instead of full matrix - O(min(m,n)) space
41
- let prev = Array.from({ length: m + 1 }, (_, i) => i);
42
- let curr = new Array(m + 1);
43
- for (let j = 1; j <= n; j++) {
44
- curr[0] = j; // Distance from empty string
45
- for (let i = 1; i <= m; i++) {
46
- if (str1[i - 1] === str2[j - 1]) {
47
- // Characters match, no edit needed
48
- curr[i] = prev[i - 1];
49
- }
50
- else {
51
- // Take minimum of three operations
52
- curr[i] = 1 + Math.min(prev[i - 1], // substitution
53
- prev[i], // deletion
54
- curr[i - 1] // insertion
55
- );
56
- }
57
- }
58
- // Swap rows for next iteration
59
- [prev, curr] = [curr, prev];
60
- }
61
- return prev[m];
62
- }
63
- // ==================== TF-IDF ====================
64
- /**
65
- * Calculate Term Frequency (TF) for a term in a document.
66
- *
67
- * TF = (Number of times term appears in document) / (Total terms in document)
68
- *
69
- * @param term - The search term
70
- * @param document - The document text
71
- * @returns Term frequency (0.0 to 1.0)
72
- */
73
- export function calculateTF(term, document) {
74
- const termLower = term.toLowerCase();
75
- const tokens = tokenize(document);
76
- if (tokens.length === 0)
77
- return 0;
78
- const termCount = tokens.filter(t => t === termLower).length;
79
- return termCount / tokens.length;
80
- }
81
- /**
82
- * Calculate Inverse Document Frequency (IDF) for a term across documents.
83
- *
84
- * IDF = log(Total documents / Documents containing term)
85
- *
86
- * Note: For bulk IDF calculation, prefer calculateIDFFromTokenSets which
87
- * avoids re-tokenizing documents for each term.
88
- *
89
- * @param term - The search term
90
- * @param documents - Array of document texts
91
- * @returns Inverse document frequency
92
- */
93
- export function calculateIDF(term, documents) {
94
- if (documents.length === 0)
95
- return 0;
96
- const termLower = term.toLowerCase();
97
- const docsWithTerm = documents.filter(doc => tokenize(doc).includes(termLower)).length;
98
- if (docsWithTerm === 0)
99
- return 0;
100
- return Math.log(documents.length / docsWithTerm);
101
- }
102
- /**
103
- * Calculate Inverse Document Frequency (IDF) from pre-tokenized documents.
104
- *
105
- * IDF = log(Total documents / Documents containing term)
106
- *
107
- * **Optimized**: Avoids re-tokenizing documents for each term. Pre-tokenize
108
- * documents once and convert to Sets for O(1) lookup per document.
109
- *
110
- * @param term - The search term (should already be lowercase)
111
- * @param tokenSets - Array of Sets, each containing unique tokens for a document
112
- * @returns Inverse document frequency
113
- *
114
- * @example
115
- * ```typescript
116
- * const docs = ["hello world", "hello there"];
117
- * const tokenSets = docs.map(d => new Set(tokenize(d)));
118
- * calculateIDFFromTokenSets("hello", tokenSets); // Low IDF (common term)
119
- * calculateIDFFromTokenSets("world", tokenSets); // Higher IDF (less common)
120
- * ```
121
- */
122
- export function calculateIDFFromTokenSets(term, tokenSets) {
123
- if (tokenSets.length === 0)
124
- return 0;
125
- const termLower = term.toLowerCase();
126
- let docsWithTerm = 0;
127
- for (const tokenSet of tokenSets) {
128
- if (tokenSet.has(termLower)) {
129
- docsWithTerm++;
130
- }
131
- }
132
- if (docsWithTerm === 0)
133
- return 0;
134
- return Math.log(tokenSets.length / docsWithTerm);
135
- }
136
- /**
137
- * Calculate TF-IDF score for a term in a document.
138
- *
139
- * TF-IDF = TF * IDF
140
- *
141
- * Higher scores indicate more important/relevant terms.
142
- *
143
- * @param term - The search term
144
- * @param document - The document text
145
- * @param documents - Array of all documents
146
- * @returns TF-IDF score
147
- */
148
- export function calculateTFIDF(term, document, documents) {
149
- const tf = calculateTF(term, document);
150
- const idf = calculateIDF(term, documents);
151
- return tf * idf;
152
- }
153
- /**
154
- * Tokenize text into lowercase words.
155
- *
156
- * Splits on whitespace and removes punctuation.
157
- *
158
- * @param text - Text to tokenize
159
- * @returns Array of lowercase tokens
160
- */
161
- export function tokenize(text) {
162
- return text
163
- .toLowerCase()
164
- .replace(/[^\w\s]/g, ' ')
165
- .split(/\s+/)
166
- .filter(token => token.length > 0);
167
- }
@@ -1,108 +0,0 @@
1
- /**
2
- * Search Result Cache
3
- *
4
- * Simple LRU-style cache for search results with TTL support.
5
- * Improves performance for repeated queries without external dependencies.
6
- *
7
- * @module utils/searchCache
8
- */
9
- import type { SearchResult, KnowledgeGraph } from '../types/index.js';
10
- /**
11
- * Cache statistics for monitoring.
12
- */
13
- export interface CacheStats {
14
- hits: number;
15
- misses: number;
16
- size: number;
17
- hitRate: number;
18
- }
19
- /**
20
- * Simple LRU cache implementation for search results.
21
- *
22
- * Features:
23
- * - Maximum size limit (LRU eviction when full)
24
- * - TTL-based expiration
25
- * - Cache statistics tracking
26
- * - Hash-based key generation from query parameters
27
- */
28
- export declare class SearchCache<T = SearchResult[] | KnowledgeGraph> {
29
- private maxSize;
30
- private ttlMs;
31
- private cache;
32
- private accessOrder;
33
- private hits;
34
- private misses;
35
- constructor(maxSize?: number, ttlMs?: number);
36
- /**
37
- * Generate cache key from query parameters.
38
- */
39
- private generateKey;
40
- /**
41
- * Get value from cache.
42
- *
43
- * @param params - Query parameters to generate cache key
44
- * @returns Cached value or undefined if not found/expired
45
- */
46
- get(params: Record<string, unknown>): T | undefined;
47
- /**
48
- * Set value in cache.
49
- *
50
- * @param params - Query parameters to generate cache key
51
- * @param value - Value to cache
52
- */
53
- set(params: Record<string, unknown>, value: T): void;
54
- /**
55
- * Invalidate all cached entries.
56
- */
57
- clear(): void;
58
- /**
59
- * Remove specific entry from access order.
60
- */
61
- private removeFromAccessOrder;
62
- /**
63
- * Get cache statistics.
64
- */
65
- getStats(): CacheStats;
66
- /**
67
- * Reset cache statistics.
68
- */
69
- resetStats(): void;
70
- /**
71
- * Clean up expired entries.
72
- *
73
- * Should be called periodically to prevent memory buildup.
74
- */
75
- cleanupExpired(): void;
76
- /**
77
- * Get current cache size.
78
- */
79
- get size(): number;
80
- /**
81
- * Check if cache has entry for params.
82
- */
83
- has(params: Record<string, unknown>): boolean;
84
- }
85
- /**
86
- * Global search caches for different search types.
87
- */
88
- export declare const searchCaches: {
89
- basic: SearchCache<KnowledgeGraph>;
90
- ranked: SearchCache<SearchResult[]>;
91
- boolean: SearchCache<KnowledgeGraph>;
92
- fuzzy: SearchCache<KnowledgeGraph>;
93
- };
94
- /**
95
- * Clear all search caches.
96
- *
97
- * Should be called when graph is modified to ensure cache consistency.
98
- */
99
- export declare function clearAllSearchCaches(): void;
100
- /**
101
- * Get combined statistics for all caches.
102
- */
103
- export declare function getAllCacheStats(): Record<string, CacheStats>;
104
- /**
105
- * Clean up expired entries in all caches.
106
- */
107
- export declare function cleanupAllCaches(): void;
108
- //# sourceMappingURL=searchCache.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"searchCache.d.ts","sourceRoot":"","sources":["../../src/utils/searchCache.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAWtE;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;GAQG;AACH,qBAAa,WAAW,CAAC,CAAC,GAAG,YAAY,EAAE,GAAG,cAAc;IAOxD,OAAO,CAAC,OAAO;IACf,OAAO,CAAC,KAAK;IAPf,OAAO,CAAC,KAAK,CAAyC;IACtD,OAAO,CAAC,WAAW,CAAgB;IACnC,OAAO,CAAC,IAAI,CAAK;IACjB,OAAO,CAAC,MAAM,CAAK;gBAGT,OAAO,GAAE,MAAY,EACrB,KAAK,GAAE,MAAsB;IAGvC;;OAEG;IACH,OAAO,CAAC,WAAW;IASnB;;;;;OAKG;IACH,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,GAAG,SAAS;IAyBnD;;;;;OAKG;IACH,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI;IAyBpD;;OAEG;IACH,KAAK,IAAI,IAAI;IAKb;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAO7B;;OAEG;IACH,QAAQ,IAAI,UAAU;IAUtB;;OAEG;IACH,UAAU,IAAI,IAAI;IAKlB;;;;OAIG;IACH,cAAc,IAAI,IAAI;IAgBtB;;OAEG;IACH,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;OAEG;IACH,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO;CAe9C;AAED;;GAEG;AACH,eAAO,MAAM,YAAY;;;;;CAKxB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAK3C;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAO7D;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAKvC"}
@@ -1,209 +0,0 @@
1
- /**
2
- * Search Result Cache
3
- *
4
- * Simple LRU-style cache for search results with TTL support.
5
- * Improves performance for repeated queries without external dependencies.
6
- *
7
- * @module utils/searchCache
8
- */
9
- /**
10
- * Simple LRU cache implementation for search results.
11
- *
12
- * Features:
13
- * - Maximum size limit (LRU eviction when full)
14
- * - TTL-based expiration
15
- * - Cache statistics tracking
16
- * - Hash-based key generation from query parameters
17
- */
18
- export class SearchCache {
19
- maxSize;
20
- ttlMs;
21
- cache = new Map();
22
- accessOrder = [];
23
- hits = 0;
24
- misses = 0;
25
- constructor(maxSize = 500, ttlMs = 5 * 60 * 1000 // 5 minutes default
26
- ) {
27
- this.maxSize = maxSize;
28
- this.ttlMs = ttlMs;
29
- }
30
- /**
31
- * Generate cache key from query parameters.
32
- */
33
- generateKey(params) {
34
- // Sort keys for consistent hashing
35
- const sorted = Object.keys(params)
36
- .sort()
37
- .map(key => `${key}:${JSON.stringify(params[key])}`)
38
- .join('|');
39
- return sorted;
40
- }
41
- /**
42
- * Get value from cache.
43
- *
44
- * @param params - Query parameters to generate cache key
45
- * @returns Cached value or undefined if not found/expired
46
- */
47
- get(params) {
48
- const key = this.generateKey(params);
49
- const entry = this.cache.get(key);
50
- if (!entry) {
51
- this.misses++;
52
- return undefined;
53
- }
54
- // Check expiration
55
- if (Date.now() > entry.expiresAt) {
56
- this.cache.delete(key);
57
- this.removeFromAccessOrder(key);
58
- this.misses++;
59
- return undefined;
60
- }
61
- // Update access order (move to end = most recently used)
62
- this.removeFromAccessOrder(key);
63
- this.accessOrder.push(key);
64
- this.hits++;
65
- return entry.value;
66
- }
67
- /**
68
- * Set value in cache.
69
- *
70
- * @param params - Query parameters to generate cache key
71
- * @param value - Value to cache
72
- */
73
- set(params, value) {
74
- const key = this.generateKey(params);
75
- // Remove old entry if exists
76
- if (this.cache.has(key)) {
77
- this.removeFromAccessOrder(key);
78
- }
79
- // Evict least recently used if at capacity
80
- if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
81
- const lruKey = this.accessOrder.shift();
82
- if (lruKey) {
83
- this.cache.delete(lruKey);
84
- }
85
- }
86
- // Add new entry
87
- this.cache.set(key, {
88
- value,
89
- timestamp: Date.now(),
90
- expiresAt: Date.now() + this.ttlMs,
91
- });
92
- this.accessOrder.push(key);
93
- }
94
- /**
95
- * Invalidate all cached entries.
96
- */
97
- clear() {
98
- this.cache.clear();
99
- this.accessOrder = [];
100
- }
101
- /**
102
- * Remove specific entry from access order.
103
- */
104
- removeFromAccessOrder(key) {
105
- const index = this.accessOrder.indexOf(key);
106
- if (index > -1) {
107
- this.accessOrder.splice(index, 1);
108
- }
109
- }
110
- /**
111
- * Get cache statistics.
112
- */
113
- getStats() {
114
- const total = this.hits + this.misses;
115
- return {
116
- hits: this.hits,
117
- misses: this.misses,
118
- size: this.cache.size,
119
- hitRate: total > 0 ? this.hits / total : 0,
120
- };
121
- }
122
- /**
123
- * Reset cache statistics.
124
- */
125
- resetStats() {
126
- this.hits = 0;
127
- this.misses = 0;
128
- }
129
- /**
130
- * Clean up expired entries.
131
- *
132
- * Should be called periodically to prevent memory buildup.
133
- */
134
- cleanupExpired() {
135
- const now = Date.now();
136
- const keysToDelete = [];
137
- for (const [key, entry] of this.cache.entries()) {
138
- if (now > entry.expiresAt) {
139
- keysToDelete.push(key);
140
- }
141
- }
142
- for (const key of keysToDelete) {
143
- this.cache.delete(key);
144
- this.removeFromAccessOrder(key);
145
- }
146
- }
147
- /**
148
- * Get current cache size.
149
- */
150
- get size() {
151
- return this.cache.size;
152
- }
153
- /**
154
- * Check if cache has entry for params.
155
- */
156
- has(params) {
157
- const key = this.generateKey(params);
158
- const entry = this.cache.get(key);
159
- if (!entry)
160
- return false;
161
- // Check expiration
162
- if (Date.now() > entry.expiresAt) {
163
- this.cache.delete(key);
164
- this.removeFromAccessOrder(key);
165
- return false;
166
- }
167
- return true;
168
- }
169
- }
170
- /**
171
- * Global search caches for different search types.
172
- */
173
- export const searchCaches = {
174
- basic: new SearchCache(),
175
- ranked: new SearchCache(),
176
- boolean: new SearchCache(),
177
- fuzzy: new SearchCache(),
178
- };
179
- /**
180
- * Clear all search caches.
181
- *
182
- * Should be called when graph is modified to ensure cache consistency.
183
- */
184
- export function clearAllSearchCaches() {
185
- searchCaches.basic.clear();
186
- searchCaches.ranked.clear();
187
- searchCaches.boolean.clear();
188
- searchCaches.fuzzy.clear();
189
- }
190
- /**
191
- * Get combined statistics for all caches.
192
- */
193
- export function getAllCacheStats() {
194
- return {
195
- basic: searchCaches.basic.getStats(),
196
- ranked: searchCaches.ranked.getStats(),
197
- boolean: searchCaches.boolean.getStats(),
198
- fuzzy: searchCaches.fuzzy.getStats(),
199
- };
200
- }
201
- /**
202
- * Clean up expired entries in all caches.
203
- */
204
- export function cleanupAllCaches() {
205
- searchCaches.basic.cleanupExpired();
206
- searchCaches.ranked.cleanupExpired();
207
- searchCaches.boolean.cleanupExpired();
208
- searchCaches.fuzzy.cleanupExpired();
209
- }