Fix embedded preview chunks and serve JavaScript without gzip copies

This commit is contained in:
SantaSpeen committed 2026-10-22 21:50:55 +03:00
1 parent 6d8faa7d03
commit 6873f04bfb
8 files changed
+300 -3

No files matched your search

+2
View File
@@ -23,3 +23,5 @@
Для приватных файлов используются обычные авторизованные API; для публичных — только API текущей ссылки с её токеном. Публичная ссылка на отдельный файл не запрашивает содержимое его родительской папки.
В сборщике `xmlbuilder2` направлен на официальный браузерный bundle: серверный entry зависимости VTK требует Node EventEmitter и не запускается в браузере. CSP страницы не ослабляется, сторонние CDN не используются.
Встроенные ресурсы включают служебные чанки Vite с начальным `__`; сервер отдаёт исходный JS, если gzip-копия не создана из-за малого размера. Go-тесты проверяют полноту встраивания и оба варианта отдачи. Дополнительная функциональная проверка: `DICOM_BROWSER_TEST=1 go test ./http -run TestProductionDICOMPreviewBrowser -v`. Нужны собранный frontend, Node 24, Playwright (путь можно задать в `PLAYWRIGHT_MODULE`) и браузер (`BROWSER_EXECUTABLE`). Проверка использует синтетические DICOM, настоящий встроенный сервер и CSP, без скриншотов и пользовательских данных.
+3 -1
View File
@@ -4,7 +4,9 @@ package frontend
import "embed"
//go:embed dist/*
// Vite emits shared chunks beginning with underscores. The default recursive
// embed walk excludes those files, breaking dynamic imports in release builds.
//go:embed all:dist/*
var assets embed.FS
func Assets() embed.FS {
+29
View File
@@ -0,0 +1,29 @@
//go:build !dev
package frontend
import (
"io/fs"
"os"
"testing"
)
func TestReleaseEmbedsEveryBuiltAsset(t *testing.T) {
// Check the build output itself, including Vite's __vite-* chunks. Missing
// optional gzip files are valid; missing originals in the binary are not.
err := fs.WalkDir(os.DirFS("."), "dist", func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
if _, err := fs.Stat(Assets(), path); err != nil {
t.Errorf("asset absent from release binary: %s: %v", path, err)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
+145
View File
@@ -0,0 +1,145 @@
// Run by the optional Go browser regression. Every API response is synthetic;
// HTML, CSP and static assets come from the real embedded Go server.
const path = require("node:path"),
http = require("node:http");
const { pathToFileURL } = require("node:url");
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
(async () => {
const { fixture } = await import(
pathToFileURL(
path.join(__dirname, "../src/utils/__tests__/fixtures/dicom.ts")
)
);
const item = (i) => ({
name: `scan_${i}.dcm`,
path: `/series/scan_${i}.dcm`,
extension: ".dcm",
type: "blob",
isDir: false,
size: 500,
modified: "2026-10-22T00:00:00Z",
mode: 420,
});
const listing = {
name: "series",
path: "/series/",
isDir: true,
type: "dir",
items: [item(0), item(1), item(2)],
sorting: { by: "name", asc: true },
numFiles: 3,
numDirs: 0,
};
const perm = {
admin: true,
create: true,
rename: true,
modify: true,
delete: true,
share: true,
download: true,
};
const user = {
id: 1,
username: "smoke",
locale: "en",
perm,
scope: "/",
viewMode: "list",
sorting: { by: "name", asc: true },
rules: [],
commands: [],
theme: "dark",
showPreview: true,
};
const server = http.createServer((req, res) => {
const u = new URL(req.url, "http://localhost");
const json = (data) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(data));
};
if (u.pathname === "/api/session") return json(user);
if (u.pathname === "/api/addons") return json([]);
if (u.pathname.startsWith("/api/resources"))
return json(
/scan_(\d+)\.dcm$/.test(u.pathname)
? item(Number(u.pathname.match(/scan_(\d+)/)[1]))
: listing
);
if (u.pathname.startsWith("/api/usage"))
return json({ used: 0, total: 1000 });
if (u.pathname.startsWith("/api/raw")) {
res.setHeader("Content-Type", "application/dicom");
return res.end(
Buffer.from(
fixture(16, {
slice: Number(u.pathname.match(/scan_(\d+)/)?.[1] || 0),
})
)
);
}
res.writeHead(404);
res.end();
});
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const browser = await chromium.launch({
executablePath: process.env.BROWSER_EXECUTABLE,
headless: true,
args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"],
});
try {
const page = await browser.newPage(),
errors = [];
page.on("pageerror", (e) => errors.push(String(e)));
page.on("response", (r) => {
if (r.status() >= 400 && new URL(r.url()).pathname.startsWith("/static/"))
errors.push(`HTTP ${r.status()}: ${r.url()}`);
});
const base = process.env.FILEBROWSER_PREVIEW_URL;
if (!base) throw new Error("FILEBROWSER_PREVIEW_URL is required");
await page.route(base + "/api/**", async (route) => {
const response = await route.fetch({
url:
"http://127.0.0.1:" +
server.address().port +
new URL(route.request().url()).pathname,
});
await route.fulfill({ response });
});
await page.goto(base + "/files/series/scan_1.dcm");
await page.waitForFunction(
() =>
document.querySelector(".dicom-viewer .document-stage canvas")
?.width === 2,
null,
{ timeout: 20000 }
);
await page
.getByRole("button", { name: "Open as 3D (3)", exact: true })
.click();
await page
.locator(".dicom-volume-stage canvas")
.waitFor({ timeout: 20000 });
for (const label of ["Axial", "Sagittal", "Coronal", "3D"]) {
await page.getByRole("button", { name: label, exact: true }).click();
await page.waitForTimeout(150);
}
await page.getByRole("button", { name: "Back to 2D", exact: true }).click();
await page.waitForFunction(
() =>
!document.querySelector(".dicom-volume-stage") &&
document.querySelector(".dicom-viewer .document-stage canvas")
?.width === 2
);
if (errors.length) throw new Error(errors.join("\n"));
console.log(
"DICOM preview in embedded server: 2D, series offer, 3D, MPR and return to 2D passed"
);
} finally {
await browser.close();
server.close();
}
})().catch((e) => {
console.error(e);
process.exitCode = 1;
});
+6
View File
@@ -117,6 +117,12 @@ func getStaticHandlers(store *storage.Storage, server *settings.Server, assetsFs
f, err := assetsFs.Open(r.URL.Path + ".gz")
if err != nil {
// Compression may skip tiny chunks when gzip would make them larger.
// Their original JavaScript is still part of the distribution.
if errors.Is(err, fs.ErrNotExist) {
http.FileServer(http.FS(assetsFs)).ServeHTTP(w, r)
return 0, nil
}
return http.StatusNotFound, err
}
defer f.Close()
+113
View File
@@ -0,0 +1,113 @@
package fbhttp
import (
"bytes"
"compress/gzip"
"io"
"io/fs"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"testing"
"testing/fstest"
"github.com/filebrowser/filebrowser/v2/frontend"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/users"
)
// Optional end-to-end check against the real embedded server, not Vite's file
// server. Set DICOM_BROWSER_TEST=1 and provide Playwright plus a browser binary.
func TestProductionDICOMPreviewBrowser(t *testing.T) {
if os.Getenv("DICOM_BROWSER_TEST") != "1" {
t.Skip("optional browser regression")
}
assets, err := fs.Sub(frontend.Assets(), "dist")
if err != nil {
t.Fatal(err)
}
st := scopedUserStorage(t, t.TempDir(), users.Permissions{}, []byte("key"))
index, static := getStaticHandlers(st, &settings.Server{}, assets)
mux := http.NewServeMux()
mux.Handle("/static/", static)
mux.Handle("/", index)
server := httptest.NewServer(mux)
defer server.Close()
command := exec.Command("node", "../frontend/scripts/check-dicom-preview.cjs")
command.Env = append(os.Environ(), "FILEBROWSER_PREVIEW_URL="+server.URL)
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("%v\n%s", err, output)
}
t.Log(string(output))
}
func TestStaticJavaScriptWithAndWithoutGzip(t *testing.T) {
st := scopedUserStorage(t, t.TempDir(), users.Permissions{}, []byte("key"))
var compressed bytes.Buffer
w := gzip.NewWriter(&compressed)
_, _ = w.Write([]byte("export const large = true;"))
if err := w.Close(); err != nil {
t.Fatal(err)
}
assets := fstest.MapFS{
"assets/__tiny.js": &fstest.MapFile{Data: []byte("export {};\n")},
"assets/large.js.gz": &fstest.MapFile{Data: compressed.Bytes()},
}
_, handler := getStaticHandlers(st, &settings.Server{}, assets)
for _, encoding := range []string{"", "gzip"} {
for name, want := range map[string]string{"__tiny.js": "export {};\n", "large.js": "export const large = true;"} {
r := httptest.NewRequest("GET", "/static/assets/"+name, nil)
r.Header.Set("Accept-Encoding", encoding)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, r)
if rec.Code != 200 {
t.Fatalf("%s (%s): HTTP %d", name, encoding, rec.Code)
}
body := rec.Body.Bytes()
if rec.Header().Get("Content-Encoding") == "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()
}
if string(body) != want {
t.Fatalf("%s: incorrect body", name)
}
if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Fatal("missing nosniff")
}
}
}
}
func TestEmbeddedPreviewChunkCanBeServed(t *testing.T) {
assets, err := fs.Sub(frontend.Assets(), "dist")
if err != nil {
t.Fatal(err)
}
names, err := fs.Glob(assets, "assets/__vite-browser-external-*.js")
if err != nil {
t.Fatal(err)
}
if len(names) == 0 {
t.Skip("build frontend to check production chunks")
}
st := scopedUserStorage(t, t.TempDir(), users.Permissions{}, []byte("key"))
_, handler := getStaticHandlers(st, &settings.Server{}, assets)
for _, name := range names {
r := httptest.NewRequest("GET", "/static/"+name, nil)
r.Header.Set("Accept-Encoding", "gzip")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, r)
if rec.Code != 200 || rec.Body.Len() == 0 {
t.Fatalf("embedded chunk %s: HTTP %d", name, rec.Code)
}
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
param([string]$Version = '3.0.0-sso.25')
param([string]$Version = '3.0.0-sso.26')
$ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Push-Location $repo
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
VERSION="${VERSION:-3.0.0-sso.25}"
VERSION="${VERSION:-3.0.0-sso.26}"
COMMIT=$(git rev-parse --short HEAD)
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
mkdir -p build/release/linux-amd64