⚡ Compress vendor assets and add bounded static runtime fallback

This commit is contained in:
Codex 2026-11-01 19:54:09 -08:00
parent 07fbbc061b
commit c9b941183d
13 changed files with 444 additions and 79 deletions

View File

@ -83,19 +83,38 @@ func spaHandler(apiHandler http.Handler, distDir string) http.Handler {
}
var precompressedContentTypes = map[string]string{
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".wasm": "application/wasm",
}
func requestAcceptsGzip(request *http.Request) bool {
wildcard := false
for _, encoding := range request.Header.Values("Accept-Encoding") {
for _, part := range strings.Split(encoding, ",") {
if strings.TrimSpace(strings.SplitN(part, ";", 2)[0]) == "gzip" {
return true
fields := strings.Split(part, ";")
name := strings.ToLower(strings.TrimSpace(fields[0]))
quality := 1.0
for _, parameter := range fields[1:] {
pair := strings.SplitN(strings.TrimSpace(parameter), "=", 2)
if len(pair) == 2 && strings.EqualFold(pair[0], "q") {
value, err := strconv.ParseFloat(pair[1], 64)
if err != nil || value < 0 || value > 1 {
quality = 0
} else {
quality = value
}
}
}
if name == "gzip" {
return quality > 0
}
if name == "*" {
wildcard = quality > 0
}
}
}
return false
return wildcard
}
// servePrecompressedAsset streams the build-time .gz sibling for compressible

View File

@ -0,0 +1,79 @@
package main
import (
"bytes"
"compress/gzip"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestVendorPrecompressionNegotiation(t *testing.T) {
root := t.TempDir()
for _, name := range []string{"element.slim.js", "movi.wasm"} {
path := filepath.Join(root, "vendor", "player", name)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
raw := []byte("frozen runtime bytes")
var compressed bytes.Buffer
z := gzip.NewWriter(&compressed)
_, _ = z.Write(raw)
_ = z.Close()
if err := os.WriteFile(path, raw, 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path+".gz", compressed.Bytes(), 0o644); err != nil {
t.Fatal(err)
}
handler := spaHandler(http.NotFoundHandler(), root)
for _, tc := range []struct {
encoding, method, rangeHeader string
gzip bool
status int
}{
{"gzip", "GET", "", true, 200}, {"br, gzip;q=0.8", "GET", "", true, 200},
{"gzip;q=0, *;q=1", "GET", "", false, 200}, {"br", "GET", "", false, 200},
{"gzip", "HEAD", "", true, 200}, {"gzip", "GET", "bytes=0-3", false, 206},
} {
request := httptest.NewRequest(tc.method, "/vendor/player/"+name, nil)
request.Header.Set("Accept-Encoding", tc.encoding)
if tc.rangeHeader != "" {
request.Header.Set("Range", tc.rangeHeader)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != tc.status || (response.Header().Get("Content-Encoding") == "gzip") != tc.gzip {
t.Fatalf("%s %+v: status=%d headers=%v", name, tc, response.Code, response.Header())
}
if tc.method == "HEAD" {
if response.Body.Len() != 0 {
t.Fatal("HEAD returned a body")
}
continue
}
body := response.Body.Bytes()
if tc.gzip {
reader, err := gzip.NewReader(bytes.NewReader(body))
if err != nil {
t.Fatal(err)
}
body, err = io.ReadAll(reader)
if err != nil {
t.Fatal(err)
}
_ = reader.Close()
}
expected := raw
if tc.status == 206 {
expected = raw[:4]
}
if !bytes.Equal(body, expected) {
t.Fatalf("mismatched delivered bytes for %+v", tc)
}
}
}
}

View File

@ -19,7 +19,7 @@ into a NEW versioned directory next to this one, update `MOVI_VERSION` in
## Local patch (2026-10-12): playback-rate cap raised 2 → 4
`element.slim.js` differs from the pristine npm tarball by exactly one change:
`element.slim.js` differs from the pristine npm tarball by the rate-cap change and the bounded WASM loading extension below:
`getMaxAllowedRate()` returns `4` instead of `2`. Upstream hard-caps the host
element's `playbackRate` setter (`Math.max(0.25, Math.min(max, value))`), which
silently clamped the workbench speed selector (0.5–4×) to 2× — reviewers and
@ -31,11 +31,11 @@ not, re-apply this one-line patch to the new dist and update the hash below.
Because `/vendor/` is served with a year-long immutable Cache-Control
(`cmd/api/main.go`), any patch to `element.slim.js` MUST also bump the `?v=`
marker in `MOVI_ELEMENT_JS_URL` (`src/lib/movi-player.ts`); current marker
`rate-cap-4-20261012` (guarded by `tests/frontend/movi-player.test.mjs`).
`static-fallback-20261101` (guarded by `tests/frontend/movi-player.test.mjs`).
SHA-256 (this directory, element.slim.js includes the patch above):
- `element.slim.js` `c243c027397494d93c6e6dd73260e8f9b7fb57525f2993f34067d54a64ca0c5c`
- `element.slim.js` `e79a25cf22b6be37702b582623dca8b934baaa28f80a0ab84be056eecbbc97dc`
- `movi.wasm` `a90da45449126b10b68ac2b816aa28b9ce43cd7d3e307e7201e0ebd73f92f530`
## Host-element quirks (found in production, 2026-10-12)
@ -83,3 +83,18 @@ element via a plain module `<script>` tag, the built deployment keeps the
Loaded by `src/lib/movi-player.ts` (dynamic import, no bundler processing).
Served from `public/` so both `vite dev` and the built web dist expose it at
`/vendor/movi-player-0.4.1/`.
## Local patch (2026-11-01): bounded static WASM fallback
The shared WASM compile function optionally delegates to
`globalThis[Symbol.for("droboticflow.movi.compileWasm")]`, installed by the application
before loading the element. It retains lazy software-decoder initialization and
shares one compile across cameras. A configured external failure falls back
sequentially to the same local binary. An exhausted application loader propagates
its error instead of triggering the vendor's additional fetch loop. Without the
hook the upstream load path remains unchanged. No media fetch is intercepted.
Upgrade check: run `static-runtime.test.mjs` and the actual WASM browser canary;
verify no module/WASM request before playback needs it, one external attempt,
local fallback, and bounded failure recovery. External deployments must use a
new immutable directory for this patched script; do not overwrite an old URL.

View File

@ -2526,8 +2526,9 @@ async function $(wasmBinary) {
const A2 = O ?? X;
if (!A2) return;
let I2;
const compileOwnedWasm = globalThis[Symbol.for("droboticflow.movi.compileWasm")];
try {
I2 = await function(A3) {
I2 = typeof compileOwnedWasm === "function" ? await compileOwnedWasm() : await function(A3) {
if (_) return _;
const I3 = (async () => {
try {
@ -2544,6 +2545,7 @@ async function $(wasmBinary) {
}), I3;
}(A2);
} catch (A3) {
if (typeof compileOwnedWasm === "function") throw A3;
return void g.warn(x, `Shared WASM compile failed (${A3}); falling back to the loader's own fetch`);
}
return (A3, C2) => {

View File

@ -0,0 +1,13 @@
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { gzipSync } from "node:zlib";
export function precompressAssets(directory) {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const target = join(directory, entry.name);
if (entry.isDirectory()) precompressAssets(target);
else if (entry.isFile() && /\.(js|css|wasm)$/.test(entry.name)) {
writeFileSync(`${target}.gz`, gzipSync(readFileSync(target), { level: 9 }));
}
}
}

View File

@ -1,3 +1,4 @@
import { createRuntimeLoader, createWasmCompiler, staticRuntimeBase } from "./static-runtime.js";
import { buildAPIRequestHeaders } from "../services/api/http.js";
/**
@ -13,7 +14,8 @@ import { buildAPIRequestHeaders } from "../services/api/http.js";
export const MOVI_VERSION = "0.4.1";
const MOVI_BASE = `/vendor/movi-player-${MOVI_VERSION}`;
const MOVI_LOCAL_BASE = `/vendor/movi-player-${MOVI_VERSION}`;
const MOVI_BASE = staticRuntimeBase(import.meta.env.VITE_MOVI_ASSET_BASE_URL, MOVI_LOCAL_BASE, import.meta.env.DEV);
// Cache-busting marker for the vendored dist. /vendor/ files are served with
// `Cache-Control: public, max-age=31536000, immutable` (cmd/api/main.go), so
@ -27,11 +29,13 @@ const MOVI_BASE = `/vendor/movi-player-${MOVI_VERSION}`;
// resolver and trips the transform middleware ("should not be imported from
// source code"), which breaks every page in dev with an error overlay. Dev
// responses carry no immutable cache headers, so the marker buys nothing there.
export const MOVI_ELEMENT_CACHE_BUST = "rate-cap-4-20261012";
export const MOVI_ELEMENT_CACHE_BUST = "static-fallback-20261101";
export const MOVI_ELEMENT_JS_URL = import.meta.env.DEV
? `${MOVI_BASE}/element.slim.js`
: `${MOVI_BASE}/element.slim.js?v=${MOVI_ELEMENT_CACHE_BUST}`;
export const MOVI_WASM_URL = `${MOVI_BASE}/movi.wasm`;
export const MOVI_LOCAL_WASM_URL = `${MOVI_LOCAL_BASE}/movi.wasm`;
export let MOVI_WASM_URL = `${MOVI_BASE}/movi.wasm`;
export const MOVI_LOCAL_JS_URL = `${MOVI_LOCAL_BASE}/element.slim.js?v=${MOVI_ELEMENT_CACHE_BUST}`;
export type MoviRuntimeMode = "movi" | "native";
@ -71,46 +75,38 @@ function readMoviForce(): MoviForcePreference {
return "";
}
let loadPromise: Promise<void> | null = null;
const compileWasm = createWasmCompiler({ remote: MOVI_WASM_URL, local: MOVI_LOCAL_WASM_URL });
// Narrow vendor extension: no global fetch override and no access to customer media.
Reflect.set(globalThis, Symbol.for("droboticflow.movi.compileWasm"), compileWasm);
const loadRuntime = createRuntimeLoader({
remote: MOVI_ELEMENT_JS_URL,
local: import.meta.env.DEV ? MOVI_ELEMENT_JS_URL : MOVI_LOCAL_JS_URL,
ready: () => Boolean(customElements.get("movi-player")),
fallback: () => {
MOVI_WASM_URL = MOVI_LOCAL_WASM_URL;
},
load: (url: string) =>
import.meta.env.DEV
? new Promise<void>((resolve, reject) => {
const script = document.createElement("script");
script.type = "module";
script.src = url;
script.onload = () => resolve();
script.onerror = () => {
script.remove();
reject(new Error("播放器模块加载失败"));
};
document.head.appendChild(script);
})
: import(/* @vite-ignore */ url).then(() => undefined),
});
/**
* Register the `<movi-player>` custom element exactly once per page. The
* dynamic import of a computed URL keeps the 4.9MB module out of the app
* bundle; `@vite-ignore` keeps Vite from trying to resolve the runtime path.
*/
export function loadMoviPlayer(): Promise<void> {
if (typeof window === "undefined" || !("customElements" in window)) {
return Promise.reject(new Error("custom elements unavailable"));
}
if (customElements.get("movi-player")) return Promise.resolve();
if (!loadPromise) {
loadPromise = (
import.meta.env.DEV
? new Promise<void>((resolve, reject) => {
// Vite's dev server refuses to serve /public assets through the
// module pipeline (`?import` → "should not be imported from source
// code"), which hard-blocks the whole page with an error overlay.
// A module script tag fetches the same static file outside that
// pipeline; dev responses carry no immutable cache headers, so the
// bust marker is unnecessary there.
const script = document.createElement("script");
script.type = "module";
script.src = MOVI_ELEMENT_JS_URL;
script.onload = () => resolve();
script.onerror = () => {
script.remove();
reject(new Error(`movi element load failed: ${script.src}`));
};
document.head.appendChild(script);
})
: import(/* @vite-ignore */ MOVI_ELEMENT_JS_URL).then(() => undefined)
).catch((error) => {
// Reset so a later mount can retry (e.g. transient network failure).
loadPromise = null;
throw error;
});
}
return loadPromise;
return loadRuntime();
}
/** Strip a `#t=start,end` media fragment and return its parts. */

83
src/lib/static-runtime.js Normal file
View File

@ -0,0 +1,83 @@
export function staticRuntimeBase(configured, localBase, development = false) {
if (development || !String(configured || "").trim()) return localBase;
const url = new URL(String(configured));
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) {
throw new Error("静态资源地址必须是无凭证的 HTTPS 版本目录");
}
return url.href.replace(/\/$/, "");
}
export function createRuntimeLoader({ remote, local, load, ready, fallback }) {
let pending = null;
let useLocal = remote === local;
return () => {
if (ready()) return Promise.resolve();
if (!pending) {
pending = (async () => {
try {
await load(useLocal ? local : remote);
} catch (error) {
if (useLocal) throw error;
useLocal = true;
fallback();
if (!ready()) await load(local);
}
if (!ready()) throw new Error("播放器模块未完成注册");
})().catch((error) => {
pending = null;
throw error;
});
}
return pending;
};
}
// The vendor calls this only when software decoding is needed, never on page entry.
export function createWasmCompiler({
remote,
local,
fetchResource = fetch,
compile = WebAssembly.compile,
compileStreaming = WebAssembly.compileStreaming,
timeoutMs = 30000,
}) {
let pending = null;
let useLocal = remote === local;
const load = async (url) => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetchResource(url, { credentials: "omit", signal: controller.signal });
if (!response.ok) throw new Error(`WASM HTTP ${response.status}`);
const copy = response.clone();
if (compileStreaming) {
try {
const module = await compileStreaming(response);
void copy.body?.cancel();
return module;
} catch {
/* Reuse bytes for servers with a wrong MIME type. */
}
}
return await compile(await copy.arrayBuffer());
} finally {
clearTimeout(timeout);
}
};
return () => {
if (!pending)
pending = (async () => {
try {
return await load(useLocal ? local : remote);
} catch (error) {
if (useLocal) throw error;
useLocal = true;
return await load(local);
}
})().catch((error) => {
pending = null;
throw error;
});
return pending;
};
}

View File

@ -0,0 +1,71 @@
import { chromium } from "playwright";
import assert from "node:assert/strict";
import fs from "node:fs/promises";
const base = process.env.ACCEPTANCE_TEST_URL || "http://127.0.0.1:5199";
assert(["127.0.0.1", "localhost"].includes(new URL(base).hostname));
const media = await fs.readFile(new URL("../../local-data/verification/acceptance/fixture.mp4", import.meta.url));
const browser = await chromium.launch({
executablePath: "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
headless: true,
args: ["--no-proxy-server"],
});
try {
const page = await browser.newPage();
const requests = [],
errors = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("request", (r) => {
if (r.url().includes(".wasm")) requests.push(new URL(r.url()).pathname);
});
await page.route("**/unavailable/movi.wasm", (r) => r.abort("failed"));
await page.route("**/synthetic.mp4", (r) => {
const range = /bytes=(\d+)-(\d*)/.exec(r.request().headers().range || "");
const start = range ? Number(range[1]) : 0,
end = range?.[2] ? Math.min(Number(range[2]), media.length - 1) : media.length - 1;
return r.fulfill({
status: range ? 206 : 200,
contentType: "video/mp4",
body: r.request().method() === "HEAD" ? undefined : media.subarray(start, end + 1),
headers: {
"Content-Length": String(end - start + 1),
"Accept-Ranges": "bytes",
...(range ? { "Content-Range": `bytes ${start}-${end}/${media.length}` } : {}),
},
});
});
await page.goto(base);
await page.evaluate(async () => {
const runtime = await import("/src/lib/movi-player.ts");
const { createWasmCompiler } = await import("/src/lib/static-runtime.js");
globalThis[Symbol.for("droboticflow.movi.compileWasm")] = createWasmCompiler({
remote: "/unavailable/movi.wasm",
local: "/vendor/movi-player-0.4.1/movi.wasm",
});
await runtime.loadMoviPlayer();
});
assert.deepEqual(requests, [], "module registration must not eagerly download WASM");
await page.evaluate(() => {
for (let i = 0; i < 2; i++) {
const p = document.createElement("movi-player");
p.setAttribute("wasmurl", "/unavailable/movi.wasm");
p.setAttribute("engine", "wasm");
p.setAttribute("sw", "software");
p.setAttribute("muted", "");
p.setAttribute("preload", "auto");
p.setAttribute("src", "/synthetic.mp4");
document.body.append(p);
}
});
await page.waitForFunction(
() =>
[...document.querySelectorAll("movi-player")].length === 2 &&
[...document.querySelectorAll("movi-player")].every((p) => p.readyState >= 2 && p.duration > 0),
{},
{ timeout: 60000 },
);
assert.deepEqual(requests, ["/unavailable/movi.wasm", "/vendor/movi-player-0.4.1/movi.wasm"]);
assert.deepEqual(errors, []);
console.log(JSON.stringify({ passed: true, players: 2, wasmRequests: requests }));
} finally {
await browser.close();
}

View File

@ -42,7 +42,7 @@ test("module declares vendored version, asset paths, and endpoint", () => {
// contract). The marker lives in MOVI_ELEMENT_CACHE_BUST and is appended to
// the built-deployment URL only; Vite dev must keep the query-less path
// (public-dir assets cannot go through the dev module pipeline).
assert.match(moduleSource, /MOVI_ELEMENT_CACHE_BUST = "rate-cap-4-20261012"/);
assert.match(moduleSource, /MOVI_ELEMENT_CACHE_BUST = "static-fallback-20261101"/);
assert.match(moduleSource, /`\$\{MOVI_BASE\}\/element\.slim\.js\?v=\$\{MOVI_ELEMENT_CACHE_BUST\}`/);
assert.match(moduleSource, /import\.meta\.env\.DEV/);
assert.match(moduleSource, /movi\.wasm/);

View File

@ -2,10 +2,12 @@ import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import ts from "typescript";
import * as staticRuntime from "../../src/lib/static-runtime.js";
import { buildAPIRequestHeaders } from "../../src/services/api/http.js";
const source = fs
.readFileSync(new URL("../../src/lib/movi-player.ts", import.meta.url), "utf8")
.replaceAll("import.meta.env.DEV", "false");
.replaceAll("import.meta.env.DEV", "false")
.replaceAll("import.meta.env.VITE_MOVI_ASSET_BASE_URL", "undefined");
const code = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText;
@ -14,6 +16,7 @@ function reporter(fetch) {
now = 10000;
const exports = {};
const require = (path) => {
if (path === "./static-runtime.js") return staticRuntime;
assert.equal(path, "../services/api/http.js");
return { buildAPIRequestHeaders: (options) => buildAPIRequestHeaders({ ...options, cookieString: cookie }) };
};

View File

@ -0,0 +1,25 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { gunzipSync } from "node:zlib";
import { precompressAssets } from "../../scripts/lib/precompress-assets.mjs";
test("final emitted chunks and copied vendor assets have byte-identical gzip siblings", () => {
const root = mkdtempSync(join(tmpdir(), "static-assets-"));
try {
const paths = ["assets/app.js", "assets/style.css", "vendor/player/element.slim.js", "vendor/player/movi.wasm"];
for (const path of paths) {
mkdirSync(join(root, path, ".."), { recursive: true });
writeFileSync(join(root, path), `final transformed bytes: ${path}`);
}
writeFileSync(join(root, "video.mp4"), "already encoded");
precompressAssets(root);
for (const path of paths)
assert.deepEqual(gunzipSync(readFileSync(join(root, path + ".gz"))), readFileSync(join(root, path)));
assert.equal(existsSync(join(root, "video.mp4.gz")), false);
} finally {
rmSync(root, { recursive: true, force: true });
}
});

View File

@ -0,0 +1,84 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createRuntimeLoader, staticRuntimeBase } from "../../src/lib/static-runtime.js";
test("static delivery remains local by default and never accepts credential-bearing URLs", () => {
assert.equal(staticRuntimeBase("", "/vendor/v1"), "/vendor/v1");
assert.equal(staticRuntimeBase("https://assets.example/v1/", "/vendor/v1"), "https://assets.example/v1");
assert.equal(staticRuntimeBase("https://assets.example/v1", "/vendor/v1", true), "/vendor/v1");
for (const base of [
"http://assets.example/v1",
"https://token@assets.example/v1",
"https://assets.example/v1?secret=x",
]) {
assert.throws(() => staticRuntimeBase(base, "/vendor/v1"));
}
});
test("concurrent mounts share one remote attempt and one sequential local fallback", async () => {
const calls = [];
let ready = false;
let fallbacks = 0;
const load = createRuntimeLoader({
remote: "remote",
local: "local",
ready: () => ready,
fallback: () => fallbacks++,
load: async (url) => {
calls.push(url);
await Promise.resolve();
if (url === "remote") throw new Error("offline");
ready = true;
},
});
await Promise.all(Array.from({ length: 20 }, () => load()));
await load();
assert.deepEqual(calls, ["remote", "local"]);
assert.equal(fallbacks, 1);
});
test("failed fallback is recoverable without retrying the failed remote or hiding errors", async () => {
const calls = [];
let available = false;
let ready = false;
const load = createRuntimeLoader({
remote: "remote",
local: "local",
ready: () => ready,
fallback: () => {},
load: async (url) => {
calls.push(url);
if (!available) throw new Error("offline");
ready = true;
},
});
await assert.rejects(load(), /offline/);
available = true;
await load();
assert.deepEqual(calls, ["remote", "local", "local"]);
});
test("lazy WASM compilation shares bytes, falls back sequentially, and stops retrying external failures", async () => {
const { createWasmCompiler } = await import("../../src/lib/static-runtime.js");
const requests = [];
let localFails = true;
const compile = createWasmCompiler({
remote: "https://assets.test/player.wasm",
local: "/local.wasm",
fetchResource: async (url) => {
requests.push(url);
if (url.startsWith("https") || localFails) throw Error("offline");
return new Response(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]), {
headers: { "Content-Type": "application/octet-stream" },
});
},
});
assert.deepEqual(requests, []);
await Promise.all(Array.from({ length: 12 }, () => assert.rejects(compile())));
assert.deepEqual(requests, ["https://assets.test/player.wasm", "/local.wasm"]);
localFails = false;
const m = await compile();
assert.ok(m instanceof WebAssembly.Module);
assert.deepEqual(requests, ["https://assets.test/player.wasm", "/local.wasm", "/local.wasm"]);
assert.equal(await compile(), m);
});

View File

@ -1,8 +1,8 @@
import { localDevStatusPlugin } from "./scripts/lib/local-dev-status.mjs";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { createReadStream, existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { gzipSync } from "node:zlib";
import { createReadStream, existsSync, statSync } from "node:fs";
import { precompressAssets } from "./scripts/lib/precompress-assets.mjs";
import path from "path";
import { defineConfig } from "vite";
import { frontendManualChunk } from "./scripts/lib/frontend-chunking.mjs";
@ -12,7 +12,6 @@ export default defineConfig(() => {
const proxyTargets = viteProxyTargets(process.env);
const captureWorkbenchMockVideo = process.env.CAPTURE_WORKBENCH_MOCK_VIDEO?.trim();
let resolvedOutDir: string | undefined;
const compressedTargets: string[] = [];
return {
plugins: [
@ -53,38 +52,14 @@ export default defineConfig(() => {
},
},
{
// Emit precompressed .gz siblings for JS/CSS assets. The Go SPA
// handler (cmd/api/main.go) serves them directly to clients that
// send Accept-Encoding: gzip, avoiding on-the-fly compression in
// the API pod.
//
// Must run in writeBundle reading the final on-disk files: in
// rolldown-vite the import-analysis transform that injects
// __vite__mapDeps runs after generateBundle, so compressing
// output.code there would produce .gz files that no longer match
// the emitted .js and crash gzip clients with ReferenceError.
name: "precompress-static-assets",
apply: "build",
configResolved(config) {
resolvedOutDir = config.build.outDir;
},
generateBundle(_options, bundle) {
compressedTargets.length = 0;
for (const fileName of Object.keys(bundle)) {
if (/\.(js|css)$/.test(fileName)) {
compressedTargets.push(fileName);
}
}
},
writeBundle() {
const outDir = path.resolve(process.cwd(), resolvedOutDir ?? "dist");
for (const fileName of compressedTargets) {
if (!fileName) {
continue;
}
const target = path.join(outDir, fileName);
writeFileSync(`${target}.gz`, gzipSync(readFileSync(target), { level: 9 }));
}
closeBundle() {
// Read final files, including public/vendor and late import-analysis transforms.
precompressAssets(path.resolve(process.cwd(), resolvedOutDir ?? "dist"));
},
},
],