@sveltejs/kit
Version:
SvelteKit is the fastest way to build Svelte apps
84 lines (69 loc) • 2.32 kB
JavaScript
import { read_implementation, manifest } from '../../server/internal.js';
import { assets } from '#app/paths';
import { base64_decode, text_encoder } from '../../utils.js';
import * as e from '../../../messages/server-errors.js';
/**
* Read the contents of an imported asset from the filesystem
* @example
* ```js
* import { read } from '$app/server';
* import somefile from './somefile.txt';
*
* const asset = read(somefile);
* const text = await asset.text();
* ```
* @param {string} asset
* @returns {Response}
* @since 2.4.0
*/
export function read(asset) {
__SVELTEKIT_TRACK__('$app/server:read');
if (!read_implementation) {
e.read_implementation_missing();
}
// handle inline assets internally
const match = /^data:([^;,]+)?(;base64)?,/.exec(asset);
if (match) {
const type = match[1] ?? 'application/octet-stream';
const data = asset.slice(match[0].length);
if (match[2] !== undefined) {
const decoded = base64_decode(data);
// @ts-ignore passing a Uint8Array to `new Response(...)` is fine
return new Response(decoded, {
headers: {
'Content-Length': decoded.byteLength.toString(),
'Content-Type': type
}
});
}
const decoded = text_encoder.encode(decodeURIComponent(data));
return new Response(decoded, {
headers: {
'Content-Length': decoded.byteLength.toString(),
'Content-Type': type
}
});
}
// Vite keeps some of the import's query or hash on the asset URL (e.g. `?v=1`, or `?no-inline`
// during dev), so strip it the same way as Vite's `cleanUrl`, which treats the first `?` or `#`
// as the end of the file path
const pathname = asset.replace(/[?#].*$/, '');
const file = decodeURIComponent(
__SVELTEKIT_DEV__ && pathname.startsWith(assets + '/@fs')
? pathname.slice(assets.length)
: pathname.slice(assets.length + 1)
);
if (file in manifest.server_assets) {
const length = manifest.server_assets[file];
const type = manifest.mime_types[file.slice(file.lastIndexOf('.'))];
return new Response(read_implementation(file), {
headers: {
'Content-Length': '' + length,
'Content-Type': type
}
});
}
e.read_asset_missing({ file });
}
export { getRequestEvent } from '@sveltejs/kit/internal/server';
export { query, prerender, command, form, requested } from './remote/index.js';