Skip to content

Commit 3ff9b21

Browse files
committed
refactor: remove unused normalizeDataUrlsToFilePaths function
- Function was only used in tests, not in production code - Dual-storage approach (images + imagesBase64) eliminated need for base64→file conversion - Removed ~60 lines of function code + ~90 lines of tests - Simplified imageDataUrl module to focus on production use case - Kept normalizeImageRefsToDataUrls which is used in production (Task.ts)
1 parent 7ddfa4e commit 3ff9b21

File tree

2 files changed

+3
-163
lines changed

2 files changed

+3
-163
lines changed
Lines changed: 2 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
2-
import { normalizeImageRefsToDataUrls, normalizeDataUrlsToFilePaths } from "../imageDataUrl"
1+
import { describe, it, expect, vi, beforeEach } from "vitest"
2+
import { normalizeImageRefsToDataUrls } from "../imageDataUrl"
33
import * as fs from "fs/promises"
44
import * as path from "path"
5-
import * as os from "os"
65

76
// Mock fs module
87
vi.mock("fs/promises")
@@ -64,97 +63,3 @@ describe("normalizeImageRefsToDataUrls", () => {
6463
expect(result).toEqual([])
6564
})
6665
})
67-
68-
describe("normalizeDataUrlsToFilePaths", () => {
69-
const testGlobalStoragePath = path.join(os.tmpdir(), "test-roo-code-storage")
70-
71-
beforeEach(async () => {
72-
vi.clearAllMocks()
73-
// Mock mkdir to succeed
74-
vi.mocked(fs.mkdir).mockResolvedValue(undefined)
75-
// Mock writeFile to succeed
76-
vi.mocked(fs.writeFile).mockResolvedValue(undefined)
77-
// Mock access to fail initially (file doesn't exist)
78-
vi.mocked(fs.access).mockRejectedValue(new Error("File not found"))
79-
})
80-
81-
afterEach(() => {
82-
vi.clearAllMocks()
83-
})
84-
85-
it("should pass through non-data URLs unchanged", async () => {
86-
const filePath = "/path/to/image.png"
87-
const result = await normalizeDataUrlsToFilePaths([filePath], testGlobalStoragePath)
88-
89-
expect(result).toEqual([filePath])
90-
expect(fs.writeFile).not.toHaveBeenCalled()
91-
})
92-
93-
it("should convert data URLs to file paths", async () => {
94-
const dataUrl =
95-
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
96-
97-
const result = await normalizeDataUrlsToFilePaths([dataUrl], testGlobalStoragePath)
98-
99-
expect(result).toHaveLength(1)
100-
expect(result[0]).toMatch(/temp-images/)
101-
expect(result[0]).toMatch(/\.png$/)
102-
expect(fs.mkdir).toHaveBeenCalledWith(
103-
expect.stringContaining("temp-images"),
104-
expect.objectContaining({ recursive: true }),
105-
)
106-
expect(fs.writeFile).toHaveBeenCalledWith(expect.stringMatching(/temp-images.*\.png$/), expect.any(Buffer))
107-
})
108-
109-
it("should handle mixed arrays of data URLs and file paths", async () => {
110-
const dataUrl = "data:image/jpeg;base64,test123"
111-
const filePath = "/existing/image.png"
112-
113-
const result = await normalizeDataUrlsToFilePaths([filePath, dataUrl], testGlobalStoragePath)
114-
115-
expect(result).toHaveLength(2)
116-
expect(result[0]).toBe(filePath) // File path unchanged
117-
expect(result[1]).toMatch(/temp-images/) // Data URL converted
118-
expect(result[1]).toMatch(/\.jpeg$/) // Correct extension from MIME type
119-
})
120-
121-
it("should handle errors gracefully", async () => {
122-
const dataUrl = "data:image/png;base64,test"
123-
124-
// Mock writeFile to fail
125-
vi.mocked(fs.writeFile).mockRejectedValue(new Error("Write failed"))
126-
127-
const result = await normalizeDataUrlsToFilePaths([dataUrl], testGlobalStoragePath)
128-
129-
// Should return original data URL as fallback
130-
expect(result).toEqual([dataUrl])
131-
})
132-
133-
it("should handle invalid data URL format", async () => {
134-
const invalidDataUrl = "data:image/png" // Missing base64 data
135-
136-
const result = await normalizeDataUrlsToFilePaths([invalidDataUrl], testGlobalStoragePath)
137-
138-
// Should skip invalid URLs
139-
expect(result).toHaveLength(0)
140-
})
141-
142-
it("should handle empty arrays", async () => {
143-
const result = await normalizeDataUrlsToFilePaths([], testGlobalStoragePath)
144-
expect(result).toEqual([])
145-
})
146-
147-
it("should extract correct file extensions from MIME types", async () => {
148-
const testCases = [
149-
{ dataUrl: "data:image/png;base64,test", expectedExt: ".png" },
150-
{ dataUrl: "data:image/jpeg;base64,test", expectedExt: ".jpeg" },
151-
{ dataUrl: "data:image/gif;base64,test", expectedExt: ".gif" },
152-
{ dataUrl: "data:image/webp;base64,test", expectedExt: ".webp" },
153-
]
154-
155-
for (const { dataUrl, expectedExt } of testCases) {
156-
const result = await normalizeDataUrlsToFilePaths([dataUrl], testGlobalStoragePath)
157-
expect(result[0]).toMatch(new RegExp(`${expectedExt.replace(".", "\\.")}$`))
158-
}
159-
})
160-
})

src/integrations/misc/imageDataUrl.ts

Lines changed: 1 addition & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import * as fs from "fs/promises"
22
import * as path from "path"
3-
import * as crypto from "crypto"
4-
import { getImageBase64ForPath, setImageBase64ForPath } from "./image-cache"
3+
import { getImageBase64ForPath } from "./image-cache"
54

65
/**
76
* Converts webview URIs to base64 data URLs for API calls.
@@ -44,70 +43,6 @@ export async function normalizeImageRefsToDataUrls(imageRefs: string[]): Promise
4443
return results
4544
}
4645

47-
/**
48-
* Converts base64 data URLs to file paths suitable for webview URIs.
49-
* Writes base64 images to temporary files and returns their paths.
50-
*
51-
* NOTE: This function is primarily used for testing. In production, the dual-storage
52-
* approach (images + imagesBase64 in ClineMessage) eliminates the need for this conversion.
53-
* No caching is implemented since this is a test utility.
54-
*/
55-
export async function normalizeDataUrlsToFilePaths(dataUrls: string[], globalStoragePath: string): Promise<string[]> {
56-
const results: string[] = []
57-
58-
// Ensure temp directory exists
59-
const tempDir = path.join(globalStoragePath, "temp-images")
60-
try {
61-
await fs.mkdir(tempDir, { recursive: true })
62-
} catch (error) {
63-
console.error("Failed to create temp-images directory:", error)
64-
return dataUrls // Return original data URLs as fallback
65-
}
66-
67-
for (const dataUrl of dataUrls) {
68-
// If it's not a data URL, keep it as is (might be a file path already)
69-
if (!dataUrl.startsWith("data:image/")) {
70-
results.push(dataUrl)
71-
continue
72-
}
73-
74-
try {
75-
// Extract base64 data and MIME type
76-
const commaIndex = dataUrl.indexOf(",")
77-
if (commaIndex === -1) {
78-
console.error("Invalid data URL format:", dataUrl.substring(0, 50))
79-
continue
80-
}
81-
82-
const header = dataUrl.substring(0, commaIndex)
83-
const base64Data = dataUrl.substring(commaIndex + 1)
84-
85-
// Determine file extension from MIME type
86-
const mimeMatch = header.match(/data:image\/([^;]+)/)
87-
const extension = mimeMatch ? `.${mimeMatch[1]}` : ".png"
88-
89-
// Create a unique hash for this image
90-
const hash = crypto.createHash("md5").update(dataUrl).digest("hex")
91-
92-
// Write to temp file
93-
const filePath = path.join(tempDir, `${hash}${extension}`)
94-
const buffer = Buffer.from(base64Data, "base64")
95-
await fs.writeFile(filePath, buffer)
96-
97-
// Cache the reverse mapping for image-cache lookups
98-
setImageBase64ForPath(filePath, dataUrl)
99-
100-
results.push(filePath)
101-
} catch (error) {
102-
console.error("Failed to convert base64 data URL to file path:", error)
103-
// Keep the original data URL as fallback
104-
results.push(dataUrl)
105-
}
106-
}
107-
108-
return results
109-
}
110-
11146
/**
11247
* Converts a webview URI to a file system path
11348
*/

0 commit comments

Comments
 (0)