(
file: file,
request: Request,
options: FileResponseOptions<file> = {},
)
| 124 | * }) |
| 125 | */ |
| 126 | export async function createFileResponse<file extends FileLike>( |
| 127 | file: file, |
| 128 | request: Request, |
| 129 | options: FileResponseOptions<file> = {}, |
| 130 | ): Promise<Response> { |
| 131 | let { |
| 132 | cacheControl, |
| 133 | etag: etagStrategy = 'weak', |
| 134 | digest: digestOption = 'SHA-256', |
| 135 | lastModified: lastModifiedEnabled = true, |
| 136 | acceptRanges: acceptRangesOption, |
| 137 | } = options |
| 138 | |
| 139 | let headers = request.headers |
| 140 | |
| 141 | let contentType = mimeTypeToContentType(file.type) |
| 142 | let contentLength = file.size |
| 143 | |
| 144 | let etag: string | undefined |
| 145 | if (etagStrategy === 'weak') { |
| 146 | etag = generateWeakETag(file) |
| 147 | } else if (etagStrategy === 'strong') { |
| 148 | let digest = await computeDigest(file, digestOption) |
| 149 | etag = `"${digest}"` |
| 150 | } |
| 151 | |
| 152 | let lastModified: number | undefined |
| 153 | if (lastModifiedEnabled) { |
| 154 | lastModified = file.lastModified |
| 155 | } |
| 156 | |
| 157 | // Determine if we should accept ranges |
| 158 | // Default: enable ranges only for non-compressible MIME types |
| 159 | let acceptRangesEnabled = |
| 160 | acceptRangesOption !== undefined ? acceptRangesOption : !isCompressibleMimeType(contentType) |
| 161 | |
| 162 | let acceptRanges: 'bytes' | undefined |
| 163 | if (acceptRangesEnabled) { |
| 164 | acceptRanges = 'bytes' |
| 165 | } |
| 166 | |
| 167 | let hasIfMatch = headers.has('If-Match') |
| 168 | |
| 169 | // If-Match support: https://httpwg.org/specs/rfc9110.html#field.if-match |
| 170 | if (etag && hasIfMatch) { |
| 171 | let ifMatch = IfMatch.from(headers.get('If-Match')) |
| 172 | if (!ifMatch.matches(etag)) { |
| 173 | return new Response('Precondition Failed', { |
| 174 | status: 412, |
| 175 | headers: buildResponseHeaders({ |
| 176 | etag, |
| 177 | lastModified, |
| 178 | acceptRanges, |
| 179 | }), |
| 180 | }) |
| 181 | } |
| 182 | } |
| 183 |
no test coverage detected
searching dependent graphs…