Files
RuneStone/vite.config.js
T
Knotty Wyvern 724402729e Replace Monaco with one CodeMirror editor and nest list items with Tab
Phase 4b. DocumentEditor.svelte replaces LiveWriter.svelte and the Monaco
EditorHost.svelte. Each open document has one CodeMirror state. Write and
Source are two compartment configurations of it, so they share the undo
history. editorStates.ts keeps the state while the tab stays open. The
Monaco model, the diff bridge, its timers, and sessions.ts are gone.

- Source: syntax colors from the theme tokens, lazy language packages,
  line numbers, folding, and the current line in IDE, wrapped lines in
  Writing, several carets, and bracket matching and closing.
- Lists (card 088e778b): Tab nests a list item and Shift+Tab moves it
  up, in Write and Source. Both renumber the list. The source keeps
  "1.". Write and Read show numbers, letters, then Roman numerals.
- Indent (card 696c30ce): a fixed 4 spaces in Write and Source.
- The code menu uses CodeMirror commands. The command palette item and
  the Monaco styles, search, theme, and workers are removed.
- @codemirror/legacy-modes is pinned to 6.5.4. Version 6.5.5 uses
  parser types that do not match @codemirror/language 6.12.
- 26 smoke tests use CodeMirror instead of Monaco. New tests:
  editor/listNesting and the markdownLists unit tests.
- Docs: development, UI design, plugin host, user guide, and UI-040.

pnpm check, pnpm test (341 of 341), and pnpm build pass. The full smoke
suite passes, except one template test that passed on retry.
2026-10-28 10:48:44 -07:00

111 lines
5.1 KiB
JavaScript

import { defineConfig } from "vite";
import { sveltekit } from "@sveltejs/kit/vite";
import process from "node:process";
import { createHash } from "node:crypto";
import { readFileSync } 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/
export default defineConfig(() => ({
plugins: [...(process.env.RUNESTONE_CSP === "1" ? [contentSecurityPolicy()] : []), sveltekit()],
define: {
__RUNESTONE_VERSION__: JSON.stringify(appVersion),
},
worker: {
format: /** @type {"es"} */ ("es"),
},
// 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/**"],
},
},
}));