1 import { FileTypes, LocalFileServiceOptions } from "@medusajs/framework/types"
2 import {
3 AbstractFileProviderService,
4 MedusaError,
5 } from "@medusajs/framework/utils"
6 import { createReadStream, createWriteStream } from "fs"
7 import fs from "fs/promises"
8 import path from "path"
9 import type { Readable, Writable } from "stream"
10
11 /**
12 * Decodes the string `content` of an uploaded file into a Buffer.
13 *
14 * Upload inputs arrive as a string that may be base64, UTF-8 text (e.g. a CSV
15 * with special characters, see #13649) or a binary/latin1 string (e.g. an image
16 * produced via `buffer.toString("binary")`, as the upload docs instruct).
17 * Decoding a binary string as UTF-8 corrupts every byte > 127 (a PNG's leading
18 * `0x89` becomes `0xC2 0x89`), so the encoding is chosen from the file's MIME
19 * type, defaulting to binary for non-text content.
20 */
21 function decodeFileContent(content: string, mimeType?: string): Buffer {
22 const decodedBase64 = Buffer.from(content, "base64")
23 if (decodedBase64.toString("base64") === content) {
24 return decodedBase64
25 }
26
27 const isTextContent =
28 mimeType?.startsWith("text/") ||
29 mimeType?.includes("csv") ||
30 mimeType?.includes("json") ||
31 mimeType?.includes("xml")
32
33 return isTextContent
34 ? Buffer.from(content, "utf8")
35 : Buffer.from(content, "binary")
36 }
37
38
39 export class LocalFileService extends AbstractFileProviderService {
40 static identifier = "localfs"
41 protected uploadDir_: string
42 protected privateUploadDir_: string
43 protected backendUrl_: string
44
45 constructor(_, options: LocalFileServiceOptions) {
46 super()
47 this.uploadDir_ = options?.upload_dir || path.join(process.cwd(), "static")
48
49 // Since there is no way to serve private files through a static server, we simply place them in `static`.
50 // This means that the files will be available publicly if the filename is known. Since the local file provider
51 // is for development only, this shouldn't be an issue. If you really want to use it in production (and you shouldn't)
52 // You can change the private upload dir to `/private` but none of the functionalities where you use a presigned URL will work.
53 this.privateUploadDir_ =
54 options?.private_upload_dir || path.join(process.cwd(), "static")
55 this.backendUrl_ = options?.backend_url || "http://localhost:9000/static"
56 }
57
58 async upload(
59 file: FileTypes.ProviderUploadFileDTO
60 ): Promise<FileTypes.ProviderFileResultDTO> {
61 if (!file) {
62 throw new MedusaError(MedusaError.Types.INVALID_DATA, `No file provided`)
63 }
64
65 if (!file.filename) {
66 throw new MedusaError(
67 MedusaError.Types.INVALID_DATA,
68 `No filename provided`
69 )
70 }
71
72 const parsedFilename = path.parse(file.filename)
73 const baseDir =
74 file.access === "public" ? this.uploadDir_ : this.privateUploadDir_
75 await this.ensureDirExists(baseDir, parsedFilename.dir)
76
77 const fileKey = path.join(
78 parsedFilename.dir,
79 // We prepend "private" to the file key so deletions and presigned URLs can know which folder to look into
80 `${file.access === "public" ? "" : "private-"}${Date.now()}-${
81 parsedFilename.base
82 }`
83 )
84
85 const filePath = this.getUploadFilePath(baseDir, fileKey)
86 const fileUrl = this.getUploadFileUrl(fileKey)
87
88 const content = decodeFileContent(file.content, file.mimeType)
89
90 await fs.writeFile(filePath, content)
91
92 return {
93 key: fileKey,
94 url: fileUrl,
95 }
96 }
97
98 async getUploadStream(fileData: FileTypes.ProviderUploadStreamDTO): Promise<{
99 writeStream: Writable
100 promise: Promise<FileTypes.ProviderFileResultDTO>
101 url: string
102 fileKey: string
103 }> {
104 if (!fileData.filename) {
105 throw new MedusaError(
106 MedusaError.Types.INVALID_DATA,
107 `No filename provided`
108 )
109 }
110
111 const parsedFilename = path.parse(fileData.filename)
112 const baseDir =
113 fileData.access === "public" ? this.uploadDir_ : this.privateUploadDir_
114 await this.ensureDirExists(baseDir, parsedFilename.dir)
115
116 const fileKey = path.join(
117 parsedFilename.dir,
118 // We prepend "private" to the file key so deletions and presigned URLs can know which folder to look into
119 `${fileData.access === "public" ? "" : "private-"}${Date.now()}-${
120 parsedFilename.base
121 }`
122 )
123
124 const filePath = this.getUploadFilePath(baseDir, fileKey)
125 const fileUrl = this.getUploadFileUrl(fileKey)
126
127 const writeStream = createWriteStream(filePath)
128
129 const promise = new Promise<FileTypes.ProviderFileResultDTO>(
130 (resolve, reject) => {
131 writeStream.on("finish", () => {
132 resolve({
133 url: fileUrl,
134 key: fileKey,
135 })
136 })
137 writeStream.on("error", (err) => {
138 reject(err)
139 })
140 }
141 )
142
143 return {
144 writeStream,
145 promise,
146 url: fileUrl,
147 fileKey,
148 }
149 }
150
151 async delete(
152 files: FileTypes.ProviderDeleteFileDTO | FileTypes.ProviderDeleteFileDTO[]
153 ): Promise<void> {
154 files = Array.isArray(files) ? files : [files]
155
156 await Promise.all(
157 files.map(async (file) => {
158 const baseDir = file.fileKey.startsWith("private-")
159 ? this.privateUploadDir_
160 : this.uploadDir_
161
162 const filePath = this.getUploadFilePath(baseDir, file.fileKey)
163 try {
164 await fs.access(filePath, fs.constants.W_OK)
165 await fs.unlink(filePath)
166 } catch (e) {
167 // The file does not exist, we don't do anything
168 if (e.code !== "ENOENT") {
169 throw e
170 }
171 }
172 })
173 )
174
175 return
176 }
177
178 async getDownloadStream(
179 file: FileTypes.ProviderGetFileDTO
180 ): Promise<Readable> {
181 const baseDir = file.fileKey.startsWith("private-")
182 ? this.privateUploadDir_
183 : this.uploadDir_
184
185 const filePath = this.getUploadFilePath(baseDir, file.fileKey)
186 return createReadStream(filePath)
187 }
188
189 async getAsBuffer(file: FileTypes.ProviderGetFileDTO): Promise<Buffer> {
190 const baseDir = file.fileKey.startsWith("private-")
191 ? this.privateUploadDir_
192 : this.uploadDir_
193
194 const filePath = this.getUploadFilePath(baseDir, file.fileKey)
195 return fs.readFile(filePath)
196 }
197
198 // The local file provider doesn't support presigned URLs for private files (i.e files not placed in /static).
199 async getPresignedDownloadUrl(
200 file: FileTypes.ProviderGetFileDTO
201 ): Promise<string> {
202 const isPrivate = file.fileKey.startsWith("private-")
203 const baseDir = isPrivate ? this.privateUploadDir_ : this.uploadDir_
204
205 const filePath = this.getUploadFilePath(baseDir, file.fileKey)
206
207 try {
208 await fs.access(filePath, fs.constants.F_OK)
209 } catch {
210 throw new MedusaError(
211 MedusaError.Types.NOT_FOUND,
212 `File with key ${file.fileKey} not found`
213 )
214 }
215
216 return this.getUploadFileUrl(file.fileKey)
217 }
218
219 /**
220 * Returns the pre-signed URL that the client (frontend) can use to trigger
221 * a file upload. In this case, the Medusa backend will implement the
222 * "/upload" endpoint to perform the file upload.
223 */
224 async getPresignedUploadUrl(
225 fileData: FileTypes.ProviderGetPresignedUploadUrlDTO
226 ): Promise<FileTypes.ProviderFileResultDTO> {
227 if (!fileData?.filename) {
228 throw new MedusaError(
229 MedusaError.Types.INVALID_DATA,
230 `No filename provided`
231 )
232 }
233
234 return {
235 url: "/admin/uploads",
236 key: fileData.filename,
237 }
238 }
239
240 private getUploadFilePath = (baseDir: string, fileKey: string) => {
241 const resolvedBase = path.resolve(baseDir)
242 const resolved = path.resolve(resolvedBase, fileKey)
243 const relative = path.relative(resolvedBase, resolved)
244 if (
245 relative === ".." ||
246 relative.startsWith(`..${path.sep}`) ||
247 path.isAbsolute(relative)
248 ) {
249 throw new MedusaError(
250 MedusaError.Types.INVALID_DATA,
251 `Invalid file key: ${fileKey}`
252 )
253 }
254 return resolved
255 }
256
257 private getUploadFileUrl = (fileKey: string) => {
258 const baseUrl = new URL(this.backendUrl_)
259 baseUrl.pathname = path.join(baseUrl.pathname, fileKey)
260 return baseUrl.href
261 }
262
263 private async ensureDirExists(baseDir: string, dirPath: string) {
264 const relativePath = path.join(baseDir, dirPath)
265 try {
266 await fs.access(relativePath, fs.constants.F_OK)
267 } catch (e) {
268 await fs.mkdir(relativePath, { recursive: true })
269 }
270
271 return relativePath
272 }
273 }