Open History to see the last commit
1import { createDefaultTrustStrategy } from '../trust-strategies'
2import type {
3 Snippet,
4 SnippetIndexEntry,
5 SnippetSearchOptions,
6 SnippetStorage,
7} from '../types'
8import type { TrustStrategy } from '../trust-strategies'
9
10export interface MemorySnippetStorageOptions {
11 /**
12 * Initial snippets to populate the storage with
13 */
14 initialSnippets?: Array<Snippet>
15
16 /**
17 * Trust strategy for determining snippet trust levels
18 * @default createDefaultTrustStrategy()
19 */
20 trustStrategy?: TrustStrategy
21}
22
23/**
24 * In-memory snippet storage for testing and demos
25 */
26export function createMemorySnippetStorage(
27 optionsOrSnippets: MemorySnippetStorageOptions | Array<Snippet> = [],
28): SnippetStorage {
29 const options = Array.isArray(optionsOrSnippets)
30 ? { initialSnippets: optionsOrSnippets }
31 : optionsOrSnippets
32
33 const { initialSnippets = [], trustStrategy = createDefaultTrustStrategy() } =
34 options
35
36 // Store snippets in a Map for O(1) lookup
37 const snippets = new Map<string, Snippet>()
38
39 // Initialize with any provided snippets
40 for (const snippet of initialSnippets) {
41 snippets.set(snippet.name, snippet)
42 }
43
44 function loadIndex(): Promise<Array<SnippetIndexEntry>> {
45 return Promise.resolve(
46 Array.from(snippets.values()).map((snippet) => ({
47 id: snippet.id,
48 name: snippet.name,
49 description: snippet.description,
50 usageHints: snippet.usageHints,
51 trustLevel: snippet.trustLevel,
52 })),
53 )
54 }
55
56 function loadAll(): Promise<Array<Snippet>> {
57 return Promise.resolve(Array.from(snippets.values()))
58 }
59
60 function get(name: string): Promise<Snippet | null> {
61 return Promise.resolve(snippets.get(name) ?? null)
62 }
63
64 function save(
65 snippet: Omit<Snippet, 'createdAt' | 'updatedAt'>,
66 ): Promise<Snippet> {
67 const now = new Date().toISOString()
68 const existing = snippets.get(snippet.name)
69
70 const fullSnippet: Snippet = {
71 ...snippet,
72 createdAt: existing?.createdAt ?? now,
73 updatedAt: now,
74 }
75
76 snippets.set(snippet.name, fullSnippet)
77 return Promise.resolve(fullSnippet)
78 }
79
80 function deleteSnippet(name: string): Promise<boolean> {
81 if (!snippets.has(name)) {
82 return Promise.resolve(false)
83 }
84 snippets.delete(name)
85 return Promise.resolve(true)
86 }
87
88 function search(
89 query: string,
90 searchOptions: SnippetSearchOptions = {},
91 ): Promise<Array<SnippetIndexEntry>> {
92 const { limit = 5 } = searchOptions
93
94 // Simple text matching
95 const queryLower = query.toLowerCase()
96 const terms = queryLower.split(/\s+/)
97
98 const scored = Array.from(snippets.values()).map((snippet) => {
99 let score = 0
100 const searchText = [
101 snippet.name,
102 snippet.description,
103 ...snippet.usageHints,
104 ]
105 .join(' ')
106 .toLowerCase()
107
108 for (const term of terms) {
109 if (searchText.includes(term)) {
110 score += 1
111 }
112 // Boost exact name matches
113 if (snippet.name.toLowerCase().includes(term)) {
114 score += 2
115 }
116 }
117
118 return { snippet, score }
119 })
120
121 return Promise.resolve(
122 scored
123 .filter((s) => s.score > 0)
124 .sort((a, b) => b.score - a.score)
125 .slice(0, limit)
126 .map((s) => ({
127 id: s.snippet.id,
128 name: s.snippet.name,
129 description: s.snippet.description,
130 usageHints: s.snippet.usageHints,
131 trustLevel: s.snippet.trustLevel,
132 })),
133 )
134 }
135
136 function updateStats(name: string, success: boolean): Promise<void> {
137 const snippet = snippets.get(name)
138 if (!snippet) return Promise.resolve()
139
140 const { executions, successRate } = snippet.stats
141 const newExecutions = executions + 1
142 const newSuccessRate =
143 (successRate * executions + (success ? 1 : 0)) / newExecutions
144
145 const newStats = { executions: newExecutions, successRate: newSuccessRate }
146
147 // Use trust strategy to calculate new trust level
148 const newTrustLevel = trustStrategy.calculateTrustLevel(
149 snippet.trustLevel,
150 newStats,
151 )
152
153 snippets.set(name, {
154 ...snippet,
155 stats: newStats,
156 trustLevel: newTrustLevel,
157 updatedAt: new Date().toISOString(),
158 })
159 return Promise.resolve()
160 }
161
162 return {
163 loadIndex,
164 loadAll,
165 get,
166 save,
167 delete: deleteSnippet,
168 search,
169 updateStats,
170 trustStrategy,
171 }
172}