Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

file-storage.test.ts

187 lines6.4 KB

1import { mkdtemp, rm } from 'node:fs/promises'
2import { existsSync } from 'node:fs'
3import { tmpdir } from 'node:os'
4import { join } from 'node:path'
5import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
6import { createFileSnippetStorage } from '../src/storage/file-storage'
7import { createAlwaysTrustedStrategy } from '../src/trust-strategies'
8import type { SnippetStorage } from '../src/types'
9​
10function makeSnippetInput(overrides: Partial<Record<string, unknown>> = {}) {
11 return {
12 id: 'id-1',
13 name: 'fetch_data',
14 description: 'Fetches data',
15 code: 'return input;',
16 inputSchema: { type: 'object', properties: {} },
17 outputSchema: { type: 'object', properties: {} },
18 usageHints: ['Use for fetching'],
19 dependsOn: [],
20 trustLevel: 'untrusted' as const,
21 stats: { executions: 0, successRate: 0 },
22 ...overrides,
23 } as Parameters<SnippetStorage['save']>[0]
25​
26describe('createFileSnippetStorage', () => {
27 let dir: string
28 let storage: SnippetStorage
29​
30 beforeEach(async () => {
31 dir = await mkdtemp(join(tmpdir(), 'snippets-test-'))
32 storage = createFileSnippetStorage(dir)
33 })
34​
35 afterEach(async () => {
36 await rm(dir, { recursive: true, force: true })
37 })
38​
39 it('returns empty index for a fresh directory', async () => {
40 expect(await storage.loadIndex()).toEqual([])
41 })
42​
43 it('creates the directory if it does not exist yet', async () => {
44 const nested = join(dir, 'nested', 'deep')
45 const deepStorage = createFileSnippetStorage(nested)
46 await expect(deepStorage.loadIndex()).resolves.toEqual([])
47 })
48​
49 it('saves a snippet and round-trips it via get', async () => {
50 const saved = await storage.save(makeSnippetInput({ name: 'alpha' }))
51 expect(saved.createdAt).toBeTruthy()
52 expect(saved.updatedAt).toBeTruthy()
53​
54 const fetched = await storage.get('alpha')
55 expect(fetched).not.toBeNull()
56 expect(fetched!.code).toBe('return input;')
57 })
58​
59 it('persists snippets across independent storage instances pointing at the same dir', async () => {
60 await storage.save(makeSnippetInput({ name: 'persistent' }))
61​
62 const second = createFileSnippetStorage(dir)
63 const reloaded = await second.get('persistent')
64 expect(reloaded).not.toBeNull()
65 expect(reloaded!.name).toBe('persistent')
66 })
67​
68 it('separates code from metadata on disk', async () => {
69 await storage.save(makeSnippetInput({ name: 'x', code: 'return 42;' }))
70 const { readFile } = await import('node:fs/promises')
71 const meta = JSON.parse(
72 await readFile(join(dir, 'x', 'meta.json'), 'utf-8'),
73 )
74 const code = await readFile(join(dir, 'x', 'code.ts'), 'utf-8')
75 expect(meta).not.toHaveProperty('code')
76 expect(code).toBe('return 42;')
77 })
78​
79 it('preserves createdAt when updating an existing snippet', async () => {
80 // Deterministic clock: real timer sleeps are flaky because
81 // Date.prototype.toISOString() has millisecond resolution and on fast
82 // machines two saves can land in the same millisecond.
83 vi.useFakeTimers()
84 try {
85 vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))
86 const first = await storage.save(makeSnippetInput({ name: 'x' }))
87 vi.setSystemTime(new Date('2026-01-01T00:00:01.000Z'))
88 const second = await storage.save(
89 makeSnippetInput({ name: 'x', description: 'updated' }),
90 )
91 expect(second.createdAt).toBe(first.createdAt)
92 expect(second.updatedAt).not.toBe(first.updatedAt)
93 expect(second.description).toBe('updated')
94 } finally {
95 vi.useRealTimers()
96 }
97 })
98​
99 it('deletes a snippet including its directory and index entry', async () => {
100 await storage.save(makeSnippetInput({ name: 'doomed' }))
101 expect(await storage.delete('doomed')).toBe(true)
102 expect(await storage.get('doomed')).toBeNull()
103 expect(await storage.loadIndex()).toEqual([])
104 })
105​
106 it('returns false when deleting a missing snippet', async () => {
107 expect(await storage.delete('missing')).toBe(false)
108 })
109​
110 it('searches via matching and respects limit', async () => {
111 await storage.save(makeSnippetInput({ id: '1', name: 'github_stats' }))
112 await storage.save(makeSnippetInput({ id: '2', name: 'npm_search' }))
113 await storage.save(makeSnippetInput({ id: '3', name: 'other_github_tool' }))
114​
115 const results = await storage.search('github', { limit: 2 })
116 expect(results).toHaveLength(2)
117 for (const r of results) {
118 expect(r.name).toContain('github')
119 }
120 })
121​
122 it('updateStats increments and applies the trust strategy', async () => {
123 const alwaysTrusted = createFileSnippetStorage({
124 directory: dir,
125 trustStrategy: createAlwaysTrustedStrategy(),
126 })
127 await alwaysTrusted.save(
128 makeSnippetInput({ name: 'x', trustLevel: 'untrusted' }),
129 )
130 await alwaysTrusted.updateStats('x', true)
131 const after = await alwaysTrusted.get('x')
132 expect(after!.stats.executions).toBe(1)
133 expect(after!.trustLevel).toBe('trusted')
134 })
135​
136 it('updateStats is a no-op when snippet does not exist', async () => {
137 await expect(storage.updateStats('missing', true)).resolves.toBeUndefined()
138 })
139​
140 it('exposes the configured trust strategy', () => {
141 const strategy = createAlwaysTrustedStrategy()
142 const s = createFileSnippetStorage({
143 directory: dir,
144 trustStrategy: strategy,
145 })
146 expect(s.trustStrategy).toBe(strategy)
147 })
148​
149 describe('rejects path traversal in snippet names', () => {
150 const unsafeNames = [
151 '..',
152 '../escape',
153 'a/b',
154 'foo/../bar',
155 '/abs',
156 'win\\seg',
157 ]
158​
159 it('save() throws and writes nothing outside the directory', async () => {
160 for (const name of unsafeNames) {
161 await expect(storage.save(makeSnippetInput({ name }))).rejects.toThrow(
162 /Invalid snippet name/,
163 )
164 }
165 // The `../escape` attempt must not have created a sibling of `dir`.
166 expect(existsSync(join(dir, '..', 'escape'))).toBe(false)
167 })
168​
169 it('delete() throws for unsafe names', async () => {
170 await expect(storage.delete('../escape')).rejects.toThrow(
171 /Invalid snippet name/,
172 )
173 })
174​
175 it('get() returns null for unsafe names', async () => {
176 expect(await storage.get('../escape')).toBeNull()
177 })
178​
179 it('still accepts ordinary identifier names', async () => {
180 const saved = await storage.save(
181 makeSnippetInput({ name: 'fetch_github-stats2' }),
182 )
183 expect(saved.name).toBe('fetch_github-stats2')
184 expect(await storage.get('fetch_github-stats2')).not.toBeNull()
185 })
186 })
187})