142 lines
6.7 KiB
JavaScript
142 lines
6.7 KiB
JavaScript
import { defineConfig } from "vite";
|
|
import { sveltekit } from "@sveltejs/kit/vite";
|
|
import process from "node:process";
|
|
import { createHash } from "node:crypto";
|
|
import { readFileSync, writeFileSync } from "node:fs";
|
|
|
|
// The installer build sets RUNESTONE_VERSION. It writes package.json only after the build completes.
|
|
const packageVersion = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version;
|
|
const appVersion = process.env.RUNESTONE_VERSION || packageVersion;
|
|
|
|
const host = process.env.TAURI_DEV_HOST;
|
|
|
|
/**
|
|
* CSP mode for the smoke tests (`RUNESTONE_CSP=1`, or `pnpm smoke --csp`).
|
|
* The dev server sends the policy of `src-tauri/tauri.conf.json` with each HTML page, as the installed app does.
|
|
* It adds only what the dev server needs:
|
|
* - script-src: the SHA-256 hash of each inline script in the page. Tauri adds the same hashes to the installed app.
|
|
* - connect-src: the Vite HMR WebSocket on the address of the page.
|
|
*/
|
|
/** @returns {import("vite").Plugin} */
|
|
function contentSecurityPolicy() {
|
|
const config = JSON.parse(readFileSync(new URL("./src-tauri/tauri.conf.json", import.meta.url), "utf8"));
|
|
/** @type {Record<string, string>} */
|
|
const policy = config.app.security.csp;
|
|
/** @param {string} html @param {string | undefined} address */
|
|
const policyFor = (html, address) => {
|
|
const directives = { ...policy };
|
|
const hashes = [...html.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)]
|
|
.map(([, code]) => `'sha256-${createHash("sha256").update(code).digest("base64")}'`);
|
|
directives["script-src"] = [directives["script-src"], ...hashes].join(" ");
|
|
directives["connect-src"] = `${directives["connect-src"]} ws://${address}`;
|
|
return Object.entries(directives).map(([name, sources]) => `${name} ${sources}`).join("; ");
|
|
};
|
|
return {
|
|
name: "runestone-csp",
|
|
configureServer(server) {
|
|
// Buffer each HTML response, then send it with the policy header. Other responses pass unchanged,
|
|
// because Tauri sends the policy only with HTML pages.
|
|
server.middlewares.use((request, original, next) => {
|
|
if (request.method !== "GET" || !request.headers.accept?.includes("text/html")) return next();
|
|
/** @type {any} The response methods have overloads. The replacements accept all their forms. */
|
|
const response = original;
|
|
/** @type {Buffer[]} */
|
|
const chunks = [];
|
|
const send = { writeHead: response.writeHead.bind(response), end: response.end.bind(response) };
|
|
/** @type {any[] | undefined} */
|
|
let head;
|
|
/** @param {unknown} chunk @param {unknown} encoding */
|
|
const add = (chunk, encoding) => {
|
|
if (typeof chunk === "string") chunks.push(Buffer.from(chunk, /** @type {BufferEncoding} */ (typeof encoding === "string" ? encoding : "utf8")));
|
|
else if (chunk instanceof Uint8Array) chunks.push(Buffer.from(chunk));
|
|
};
|
|
/** @param {any[]} args */
|
|
response.writeHead = (...args) => { head = args; return response; };
|
|
/** @param {unknown} chunk @param {unknown} encoding @param {unknown} callback */
|
|
response.write = (chunk, encoding, callback) => {
|
|
add(chunk, encoding);
|
|
const done = typeof encoding === "function" ? encoding : callback;
|
|
if (typeof done === "function") done();
|
|
return true;
|
|
};
|
|
/** @param {unknown} chunk @param {unknown} encoding @param {unknown} callback */
|
|
response.end = (chunk, encoding, callback) => {
|
|
add(chunk, encoding);
|
|
const body = Buffer.concat(chunks);
|
|
/** @type {Record<string, unknown>} */
|
|
const headers = head?.find(item => item && typeof item === "object") ?? {};
|
|
const type = String(Object.entries(headers).find(([name]) => name.toLowerCase() === "content-type")?.[1] ?? response.getHeader("content-type") ?? "");
|
|
if (type.includes("text/html")) response.setHeader("Content-Security-Policy", policyFor(body.toString("utf8"), request.headers.host));
|
|
if (head) send.writeHead(...head);
|
|
return send.end(body, [chunk, encoding, callback].find(item => typeof item === "function"));
|
|
};
|
|
next();
|
|
});
|
|
},
|
|
};
|
|
}
|
|
|
|
// https://vite.dev/config/
|
|
/**
|
|
* The chunk report for `pnpm check:features` (scripts/featureChunks.mjs). With RUNESTONE_FEATURE_CHUNKS set, the client build
|
|
* writes its chunks to that file: names, entry flags, static imports, and module IDs. Other builds do not use it.
|
|
* @returns {import("vite").Plugin}
|
|
*/
|
|
function featureChunkReport() {
|
|
return {
|
|
name: "runestone-feature-chunks",
|
|
apply: "build",
|
|
generateBundle(_options, bundle) {
|
|
if (this.environment?.name === "ssr") return;
|
|
const chunks = Object.values(bundle).filter(item => item.type === "chunk").map(chunk => ({
|
|
fileName: chunk.fileName, isEntry: chunk.isEntry, isDynamicEntry: chunk.isDynamicEntry,
|
|
facadeModuleId: chunk.facadeModuleId, imports: chunk.imports, moduleIds: chunk.moduleIds, size: chunk.code.length,
|
|
}));
|
|
writeFileSync(/** @type {string} */ (process.env.RUNESTONE_FEATURE_CHUNKS), JSON.stringify(chunks));
|
|
},
|
|
};
|
|
}
|
|
|
|
export default defineConfig(() => ({
|
|
plugins: [...(process.env.RUNESTONE_CSP === "1" ? [contentSecurityPolicy()] : []), ...(process.env.RUNESTONE_FEATURE_CHUNKS ? [featureChunkReport()] : []), sveltekit()],
|
|
define: {
|
|
__RUNESTONE_VERSION__: JSON.stringify(appVersion),
|
|
},
|
|
worker: {
|
|
format: /** @type {"es"} */ ("es"),
|
|
},
|
|
optimizeDeps: {
|
|
// The minified PDF.js build is one ES module without imports. The dev server serves it as it is. Without this, the
|
|
// first PDF tab finds a new dependency and the dev server reloads the page.
|
|
exclude: ["pdfjs-dist"],
|
|
},
|
|
build: {
|
|
// The PDF Viewer reads the data files of PDF.js with fetch (src/lib/features/pdf/engine.ts). Keep them as files of
|
|
// the app, because the content security policy permits no data: address for fetch.
|
|
/** @param {string} file */
|
|
assetsInlineLimit: file => file.replaceAll("\\", "/").includes("/pdfjs-dist/") ? false : undefined,
|
|
},
|
|
|
|
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
|
|
//
|
|
// 1. prevent Vite from obscuring rust errors
|
|
clearScreen: false,
|
|
// 2. tauri expects a fixed port, fail if that port is not available
|
|
server: {
|
|
port: 1420,
|
|
strictPort: true,
|
|
host: host || "127.0.0.1",
|
|
hmr: host
|
|
? {
|
|
protocol: "ws",
|
|
host,
|
|
port: 1421,
|
|
}
|
|
: undefined,
|
|
watch: {
|
|
// 3. tell Vite to ignore watching `src-tauri`
|
|
ignored: ["**/src-tauri/**", "**/fixtures/**", "**/.runestone/**", "**/.audit/**", "**/output/**", "**/browser-runtime/dist/**", "**/browser-runtime/output/**"],
|
|
},
|
|
},
|
|
}));
|