UNPKG

one

Version:

One is a new React Framework that makes Vite serve both native and web.

42 lines (41 loc) 2.14 kB
import { existsSync } from "node:fs"; import { dirname, relative, resolve } from "node:path"; import { processImageMeta } from "../../image/getImageData"; const IMAGEDATA_SUFFIX = "?imagedata", VIRTUAL_PREFIX = "\0imagedata:"; function imageDataPlugin() { let publicDir, root; function getSrcPath(filePath) { return filePath.startsWith(publicDir) ? "/" + relative(publicDir, filePath) : "/" + relative(root, filePath); } function isPathWithinBounds(filePath, allowedDir) { const resolved = resolve(filePath), allowed = resolve(allowedDir); return resolved.startsWith(allowed + "/") || resolved === allowed; } function createImageDataExport(src, width = 0, height = 0, blurDataURL = "") { return `export default ${JSON.stringify({ src, width, height, blurDataURL })}`; } return { name: "one:imagedata", enforce: "pre", configResolved(resolvedConfig) { publicDir = resolvedConfig.publicDir, root = resolvedConfig.root; }, async resolveId(id, importer) { if (!id.endsWith(IMAGEDATA_SUFFIX)) return null; const cleanId = id.slice(0, -IMAGEDATA_SUFFIX.length); let filePath, allowedDir; return cleanId.startsWith("/") ? (filePath = resolve(publicDir, cleanId.slice(1)), allowedDir = publicDir) : importer ? (filePath = resolve(dirname(importer.replace(VIRTUAL_PREFIX, "")), cleanId), allowedDir = root) : (filePath = resolve(root, cleanId), allowedDir = root), isPathWithinBounds(filePath, allowedDir) ? existsSync(filePath) ? VIRTUAL_PREFIX + filePath : (console.warn(`[one] ?imagedata: File not found: ${filePath}`), null) : (console.warn(`[one] ?imagedata: Path traversal blocked: ${cleanId}`), null); }, async load(id) { if (!id.startsWith(VIRTUAL_PREFIX)) return null; const filePath = id.slice(VIRTUAL_PREFIX.length), src = getSrcPath(filePath); this.addWatchFile(filePath); const meta = await processImageMeta(filePath); return meta ? createImageDataExport(src, meta.width, meta.height, meta.blurDataURL) : createImageDataExport(src); } }; } export { imageDataPlugin }; //# sourceMappingURL=imageDataPlugin.js.map