2e02204dc9
**TODO** - [x] Ensure [body-stream](https://github.com/kikobeats/next.js/blob/edge-runtime/packages/next/server/body-streams.ts) is up-to-date with https://github.com/vercel/edge-runtime/blob/main/packages/runtime/src/server/body-streams.ts Changelog: https://github.com/vercel/edge-runtime/releases/tag/edge-runtime%401.1.0-beta.33
40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'
|
|
import { createReadStream, promises as fs } from 'fs'
|
|
import { requestToBodyStream } from '../../body-streams'
|
|
import { resolve } from 'path'
|
|
|
|
/**
|
|
* Short-circuits the `fetch` function
|
|
* to return a stream for a given asset, if a user used `new URL("file", import.meta.url)`.
|
|
* This allows to embed assets in Edge Runtime.
|
|
*/
|
|
export async function fetchInlineAsset(options: {
|
|
input: RequestInfo | URL
|
|
distDir: string
|
|
assets: EdgeFunctionDefinition['assets']
|
|
context: { Response: typeof Response; ReadableStream: typeof ReadableStream }
|
|
}): Promise<Response | undefined> {
|
|
const inputString = String(options.input)
|
|
if (!inputString.startsWith('blob:')) {
|
|
return
|
|
}
|
|
|
|
const hash = inputString.replace('blob:', '')
|
|
const asset = options.assets?.find((x) => x.name === hash)
|
|
if (!asset) {
|
|
return
|
|
}
|
|
|
|
const filePath = resolve(options.distDir, asset.filePath)
|
|
const fileIsReadable = await fs.access(filePath).then(
|
|
() => true,
|
|
() => false
|
|
)
|
|
|
|
if (fileIsReadable) {
|
|
const readStream = createReadStream(filePath)
|
|
return new options.context.Response(
|
|
requestToBodyStream(options.context, Uint8Array, readStream)
|
|
)
|
|
}
|
|
}
|