#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
perf(build): precompress the dist, shrink startup, defer the pdfium wasm (#8043)
brios313794c573df
diff --git a/.taskfiles/desktop.yml b/.taskfiles/desktop.ymlindex bee37fa019..b050ba0cee 100644--- a/.taskfiles/desktop.yml+++ b/.taskfiles/desktop.yml@@ -1,5 +1,10 @@version: '3'+# Tauri's beforeBuildCommand builds the frontend, so the desktop entrypoint+# needs the same threadpool size as the frontend build tasks.+env:+ UV_THREADPOOL_SIZE: "16"+vars:# jdk.dynalink is required by VeraPDF (PDF/A validation); without it the bundled JRE throws# NoClassDefFoundError: jdk/dynalink/Namespace at runtime in get-info-on-pdf and verify-pdf@@ -136,10 +141,10 @@ tasks:platforms: [windows]- cmd: ./gradlew bootJar --no-daemon -PjpdfiumPlatforms={{.JPDFIUM_PLATFORMS}}platforms: [linux, darwin]- - mkdir -p frontend/editor/src-tauri/libs- - cp app/core/build/libs/stirling-pdf-*.jar frontend/editor/src-tauri/libs/- status:- - test -f frontend/editor/src-tauri/libs/stirling-pdf-*.jar+ # The bundle globs libs/*.jar, so an old jar left behind would ship too+ # (and could be selected as the backend). The script stages only the jar+ # this build just produced, replacing whatever the last build left there.+ - node frontend/editor/scripts/stage-backend-jar.mjs app/core/build/libs frontend/editor/src-tauri/libsjlink:runtime:desc: "Create custom JRE with jlink"diff --git a/.taskfiles/frontend.yml b/.taskfiles/frontend.ymlindex bd7e101d36..aa4d5362de 100644--- a/.taskfiles/frontend.yml+++ b/.taskfiles/frontend.yml@@ -1,5 +1,12 @@version: '3'+# The precompression pass queues more zlib jobs than the default four-thread+# pool can keep busy. It has to be set before Node starts: loading the Vite+# config already touches the pool, so an assignment inside the config is too+# late.+env:+ UV_THREADPOOL_SIZE: "16"+# Tasks operate from the workspace root (frontend/). Editor commands pass# `editor` as the vite project root (positional after `build` / before the# mode flag) or use `--project editor/...` for tsc — so the editor livesdiff --git a/app/core/build.gradle b/app/core/build.gradleindex f8ba95ac3c..b0f74064cf 100644--- a/app/core/build.gradle+++ b/app/core/build.gradle@@ -296,9 +296,10 @@ tasks.register('copyFrontendAssets', Copy) {// Exclude files that conflict with backend static resourcesexclude 'robots.txt' // Backend already has thisexclude 'favicon.ico' // Backend already has this- // Backend ships its own NotoSans-Regular.ttf here and it is git-tracked;- // letting the editor's copy win would dirty the source tree on every build.- exclude 'fonts/NotoSans-Regular.ttf'+ // The raw TTFs are already git-tracked under static/fonts and copied by+ // processResources; only the precompressed siblings add anything, and+ // copying the raw set back would dirty the source tree on every build.+ exclude 'fonts/*.ttf'}into resourcesStaticDirduplicatesStrategy = DuplicatesStrategy.INCLUDE // Let frontend overwrite when needed@@ -316,15 +317,19 @@ tasks.register('cleanFrontendAssets', Delete) {description = 'Remove previously generated frontend assets from static resources'delete generatedFrontendPaths.collect { new File(resourcesStaticDir, it) }// Prerendered per-route SPA pages (e.g. compress.html) carry per-tool OG tags and are- // copied from the frontend build. Remove stale ones so renamed/removed tools don't linger.+ // copied from the frontend build. Remove stale ones so renamed/removed tools don't linger,+ // including the .br/.gz siblings the compression pass writes next to each page.// api-landing.html, mobile-upload.html and mobile-sign.html are real backend source files,// not generated artifacts.- delete fileTree(dir: resourcesStaticDir, includes: ['*.html'], excludes: ['api-landing.html', 'mobile-upload.html', 'mobile-sign.html'])+ delete fileTree(dir: resourcesStaticDir, includes: ['*.html', '*.html.br', '*.html.gz'], excludes: ['api-landing.html', 'mobile-upload.html', 'mobile-sign.html'])// Nested prerendered route pages (e.g. settings/people.html, processor/sources.html)delete new File(resourcesStaticDir, 'settings')delete new File(resourcesStaticDir, 'processor')// Generated SEO sitemap (only emitted when a canonical domain is set at build).- delete new File(resourcesStaticDir, 'sitemap.xml')+ delete fileTree(dir: resourcesStaticDir, includes: ['sitemap.xml', 'sitemap.xml.br', 'sitemap.xml.gz'])+ // Precompressed siblings of the tracked TTFs; only a frontend build produces+ // them, and the backend-only JAR (desktop bundles it) serves the raw fonts.+ delete fileTree(dir: new File(resourcesStaticDir, 'fonts'), includes: ['*.br', '*.gz'])}tasks.register('copyApiLandingPage', Copy) {diff --git a/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java b/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.javaindex 43e26168e3..91e513fed6 100644--- a/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java+++ b/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java@@ -3,17 +3,26 @@ package stirling.software.SPDF.config;import java.time.Duration;import java.util.ArrayList;import java.util.List;+import java.util.Locale;import java.util.concurrent.TimeUnit;+import java.util.stream.Stream;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Configuration;+import org.springframework.core.io.Resource;import org.springframework.http.CacheControl;+import org.springframework.http.HttpHeaders;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import org.springframework.web.servlet.resource.EncodedResourceResolver;+import org.springframework.web.servlet.resource.HttpResource;+import org.springframework.web.servlet.resource.ResourceResolver;+import org.springframework.web.servlet.resource.ResourceResolverChain;++import jakarta.servlet.http.HttpServletRequest;import lombok.RequiredArgsConstructor;@@ -32,6 +41,13 @@ public class WebMvcConfig implements WebMvcConfigurer {private static final CacheControl NO_CACHE = CacheControl.noCache();private static final CacheControl IMMUTABLE_ONE_YEAR =CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic().immutable();+ // For resources whose names are stable across releases (no content hash):+ // a day of freshness so repeat opens are a cheap conditional request, plus+ // stale-while-revalidate so a shared cache can still answer instantly.+ private static final CacheControl STABLE_ONE_DAY =+ CacheControl.maxAge(Duration.ofDays(1))+ .cachePublic()+ .staleWhileRevalidate(Duration.ofDays(7));@Overridepublic void addInterceptors(InterceptorRegistry registry) {@@ -53,7 +69,7 @@ public class WebMvcConfig implements WebMvcConfigurer {.addResourceLocations(staticPath, "classpath:/static/").setCacheControl(CacheControl.noStore()).resourceChain(true)- .addResolver(new EncodedResourceResolver());+ .addResolver(new PreferredEncodingResourceResolver());// 2. Vite fingerprinted assets (immutable)// These already have content hashes in filenames (e.g. index-ChAS4tCC.js)@@ -61,18 +77,22 @@ public class WebMvcConfig implements WebMvcConfigurer {.addResourceLocations(staticPath + "assets/", "classpath:/static/assets/").setCacheControl(IMMUTABLE_ONE_YEAR).resourceChain(true)- .addResolver(new EncodedResourceResolver());+ .addResolver(new PreferredEncodingResourceResolver());- // 3. Media and fonts (immutable)+ // 3. Media and fonts (stable names, revalidated)+ // The fallback faces ship inside the JAR under names that never change,+ // so a one-year immutable policy would strand a browser on one release's+ // bytes. A day of freshness plus SWR keeps repeat opens cheap without+ // pinning an update.registry.addResourceHandler("/images/**", "/fonts/**").addResourceLocations(staticPath + "images/","classpath:/static/images/",staticPath + "fonts/","classpath:/static/fonts/")- .setCacheControl(IMMUTABLE_ONE_YEAR)+ .setCacheControl(STABLE_ONE_DAY).resourceChain(true)- .addResolver(new EncodedResourceResolver());+ .addResolver(new PreferredEncodingResourceResolver());// 4. Branding and stable non-fingerprinted assets (1 day + SWR)// Use stale-while-revalidate to improve perceived performance.@@ -119,12 +139,9 @@ public class WebMvcConfig implements WebMvcConfigurer {"classpath:/static/icons/",staticPath + "modern-logo/","classpath:/static/modern-logo/")- .setCacheControl(- CacheControl.maxAge(Duration.ofDays(1))- .cachePublic()- .staleWhileRevalidate(Duration.ofDays(7)))+ .setCacheControl(STABLE_ONE_DAY).resourceChain(true)- .addResolver(new EncodedResourceResolver());+ .addResolver(new PreferredEncodingResourceResolver());// 5. Catch-all (SPA fallback)// Must check with server to ensure index.html is always fresh.@@ -132,7 +149,112 @@ public class WebMvcConfig implements WebMvcConfigurer {.addResourceLocations(staticPath, "classpath:/static/").setCacheControl(NO_CACHE).resourceChain(true)- .addResolver(new EncodedResourceResolver());+ .addResolver(new PreferredEncodingResourceResolver());+ }++ /**+ * Serves the smallest precompressed variant the client accepts, in server preference order+ * (brotli before gzip). The framework resolver walks the client's Accept-Encoding in the order+ * sent, and browsers list gzip before br, so the brotli siblings were never selected (Spring+ * Framework #37210). This applies the preference upstream is adopting in #37213 by asking a+ * single-coding resolver per coding; remove it when the pinned Spring version carries the fix.+ * Quality factors do not reorder, matching the upstream behavior. The one exception is an+ * explicit refusal (q=0, RFC 9110 section 12.5.3): a client that forbids a coding must get the+ * next acceptable variant, never the forbidden bytes.+ *+ * <p>Hazard: the resource chain caches resolved resources under the accepted coding set and,+ * like this resolver, ignores quality values, so a refusal is honored on the first resolve of+ * that set and can be missed on a later request whose header reduces to the same set. Real+ * browsers only ever list brotli and gzip as acceptable, so this needs a hand-crafted request+ * to trigger.+ */+ static final class PreferredEncodingResourceResolver implements ResourceResolver {++ private record Coding(String name, EncodedResourceResolver resolver) {}++ private final List<Coding> codings;++ PreferredEncodingResourceResolver() {+ this.codings =+ Stream.of("br", "gzip")+ .map(+ name -> {+ EncodedResourceResolver resolver =+ new EncodedResourceResolver();+ resolver.setContentCodings(List.of(name));+ return new Coding(name, resolver);+ })+ .toList();+ }++ @Override+ public Resource resolveResource(+ HttpServletRequest request,+ String requestPath,+ List<? extends Resource> locations,+ ResourceResolverChain chain) {+ if (request != null) {+ for (Coding coding : this.codings) {+ if (!accepts(request, coding.name())) {+ continue;+ }+ Resource resolved =+ coding.resolver()+ .resolveResource(request, requestPath, locations, chain);+ if (isEncodedWith(resolved, coding.name())) {+ return resolved;+ }+ }+ }+ return chain.resolveResource(request, requestPath, locations);+ }++ @Override+ public String resolveUrlPath(+ String resourcePath,+ List<? extends Resource> locations,+ ResourceResolverChain chain) {+ return chain.resolveUrlPath(resourcePath, locations);+ }++ private static boolean accepts(HttpServletRequest request, String coding) {+ String header = request.getHeader(HttpHeaders.ACCEPT_ENCODING);+ if (header == null) {+ return false;+ }+ for (String token : header.toLowerCase(Locale.ROOT).split(",")) {+ String[] parts = token.split(";");+ if (!parts[0].trim().equals(coding)) {+ continue;+ }+ // "br;q=0" lists the coding only to forbid it. A missing or+ // unparseable qvalue keeps the historic lenient behavior.+ boolean refused = false;+ for (int i = 1; i < parts.length; i++) {+ String param = parts[i].trim();+ if (param.startsWith("q=")) {+ try {+ refused = Double.parseDouble(param.substring(2).trim()) == 0;+ } catch (NumberFormatException e) {+ // Invalid qvalue is not a refusal; stay lenient.+ }+ break;+ }+ }+ if (!refused) {+ return true;+ }+ }+ return false;+ }++ private static boolean isEncodedWith(Resource resource, String coding) {+ return resource instanceof HttpResource httpResource+ && coding.equals(+ httpResource+ .getResponseHeaders()+ .getFirst(HttpHeaders.CONTENT_ENCODING));+ }}@Overridediff --git a/app/core/src/main/resources/static/fonts/NotoSansJP-Regular.ttf b/app/core/src/main/resources/static/fonts/NotoSansJP-Regular.ttfindex 1583096a2d..3bce8f683b 100644Binary files a/app/core/src/main/resources/static/fonts/NotoSansJP-Regular.ttf and b/app/core/src/main/resources/static/fonts/NotoSansJP-Regular.ttf differdiff --git a/app/core/src/main/resources/static/fonts/NotoSansKR-Regular.ttf b/app/core/src/main/resources/static/fonts/NotoSansKR-Regular.ttfindex b386890ba9..90a4a2aad6 100644Binary files a/app/core/src/main/resources/static/fonts/NotoSansKR-Regular.ttf and b/app/core/src/main/resources/static/fonts/NotoSansKR-Regular.ttf differdiff --git a/app/core/src/main/resources/static/fonts/NotoSansSC-Regular.ttf b/app/core/src/main/resources/static/fonts/NotoSansSC-Regular.ttfindex fb0637bafb..23164652bd 100644Binary files a/app/core/src/main/resources/static/fonts/NotoSansSC-Regular.ttf and b/app/core/src/main/resources/static/fonts/NotoSansSC-Regular.ttf differdiff --git a/app/core/src/main/resources/static/fonts/NotoSansTC-Regular.ttf b/app/core/src/main/resources/static/fonts/NotoSansTC-Regular.ttfindex 75e2b0806a..b1c97a5787 100644Binary files a/app/core/src/main/resources/static/fonts/NotoSansTC-Regular.ttf and b/app/core/src/main/resources/static/fonts/NotoSansTC-Regular.ttf differdiff --git a/app/core/src/test/java/stirling/software/SPDF/config/WebMvcConfigTest.java b/app/core/src/test/java/stirling/software/SPDF/config/WebMvcConfigTest.javaindex 200ca99a71..9201141d51 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/WebMvcConfigTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/WebMvcConfigTest.java@@ -11,6 +11,9 @@ import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.List;import org.junit.jupiter.api.AfterEach;@@ -19,17 +22,27 @@ import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.api.io.TempDir;import org.mockito.ArgumentCaptor;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.mockito.junit.jupiter.MockitoSettings;import org.mockito.quality.Strictness;+import org.springframework.core.io.FileSystemResource;+import org.springframework.core.io.Resource;+import org.springframework.http.CacheControl;+import org.springframework.http.HttpHeaders;+import org.springframework.mock.web.MockHttpServletRequest;import org.springframework.web.servlet.config.annotation.CorsRegistration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.InterceptorRegistration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;+import org.springframework.web.servlet.resource.HttpResource;+import org.springframework.web.servlet.resource.ResourceResolverChain;++import jakarta.servlet.http.HttpServletRequest;import stirling.software.common.model.ApplicationProperties;@@ -117,6 +130,45 @@ class WebMvcConfigTest {captor.getAllValues().stream().flatMap(java.util.Arrays::stream).toList();assertThat(allPatterns).contains("/**", "/assets/**", "/sw.js");}++ @Test+ @DisplayName("revalidates fonts rather than pinning them immutably for a year")+ void fontsAreRevalidated() {+ ResourceHandlerRegistry registry = mock(ResourceHandlerRegistry.class);+ ResourceHandlerRegistration sw =+ mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);+ ResourceHandlerRegistration assets =+ mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);+ ResourceHandlerRegistration media =+ mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);+ ResourceHandlerRegistration branding =+ mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);+ ResourceHandlerRegistration catchAll =+ mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);+ when(registry.addResourceHandler(any(String[].class)))+ .thenReturn(sw, assets, media, branding, catchAll);+ // addResourceLocations is the chain link before setCacheControl.+ when(sw.addResourceLocations(any(String[].class))).thenReturn(sw);+ when(assets.addResourceLocations(any(String[].class))).thenReturn(assets);+ when(media.addResourceLocations(any(String[].class))).thenReturn(media);+ when(branding.addResourceLocations(any(String[].class))).thenReturn(branding);+ when(catchAll.addResourceLocations(any(String[].class))).thenReturn(catchAll);++ config.addResourceHandlers(registry);++ // Third registration is the media/fonts group. The names never change+ // across releases, so the tier has to allow revalidation; repeating a+ // 17 MB CJK face is still cheap because an unchanged file answers the+ // conditional request with 304.+ ArgumentCaptor<String[]> patterns = ArgumentCaptor.forClass(String[].class);+ verify(registry, times(5)).addResourceHandler(patterns.capture());+ assertThat(patterns.getAllValues().get(2)).contains("/fonts/**");++ ArgumentCaptor<CacheControl> caches = ArgumentCaptor.forClass(CacheControl.class);+ verify(media).setCacheControl(caches.capture());+ String header = caches.getValue().getHeaderValue();+ assertThat(header).contains("max-age=86400").doesNotContain("immutable");+ }}@Nested@@ -199,4 +251,104 @@ class WebMvcConfigTest {verify(registry).addMapping("/**");}}++ @Nested+ @DisplayName("PreferredEncodingResourceResolver")+ class PreferredEncodingResourceResolverTest {++ @TempDir Path tempDir;++ private WebMvcConfig.PreferredEncodingResourceResolver resolver;++ @BeforeEach+ void setUp() throws Exception {+ resolver = new WebMvcConfig.PreferredEncodingResourceResolver();+ Files.writeString(tempDir.resolve("app.js"), "plain");+ }++ @Test+ @DisplayName("prefers brotli when the client lists gzip first")+ void prefersBrotli() throws IOException {+ writeVariants();+ assertThat(resolve("gzip, deflate, br")).isEqualTo("br");+ }++ @Test+ @DisplayName("serves gzip when brotli is not accepted")+ void servesGzipWhenBrotliNotAccepted() throws IOException {+ writeVariants();+ assertThat(resolve("gzip, deflate")).isEqualTo("gzip");+ }++ @Test+ @DisplayName("falls back to gzip when the brotli sibling is missing")+ void fallsBackWhenBrotliSiblingMissing() throws IOException {+ Files.writeString(tempDir.resolve("app.js.gz"), "gz");+ assertThat(resolve("gzip, deflate, br")).isEqualTo("gzip");+ }++ @Test+ @DisplayName("serves the unencoded resource when no coding is accepted")+ void servesPlainWhenNoCodingAccepted() {+ assertThat(resolve("identity")).isNull();+ }++ @Test+ @DisplayName("honors an explicit brotli refusal and serves gzip")+ void honorsExplicitBrotliRefusal() throws IOException {+ writeVariants();+ assertThat(resolve("br;q=0, gzip")).isEqualTo("gzip");+ }++ @Test+ @DisplayName("serves the unencoded resource when the only listed coding is refused")+ void servesPlainWhenOnlyListedCodingRefused() throws IOException {+ writeVariants();+ assertThat(resolve("br;q=0")).isNull();+ }++ @Test+ @DisplayName("treats an unparseable quality value as listed")+ void treatsInvalidQualityAsListed() throws IOException {+ writeVariants();+ assertThat(resolve("br;q=nope, gzip, br")).isEqualTo("br");+ }++ private void writeVariants() throws IOException {+ Files.writeString(tempDir.resolve("app.js.br"), "br");+ Files.writeString(tempDir.resolve("app.js.gz"), "gz");+ }++ /** Content-Encoding of the resolved resource, or null when it is unencoded. */+ private String resolve(String acceptEncoding) {+ MockHttpServletRequest request = new MockHttpServletRequest();+ request.addHeader(HttpHeaders.ACCEPT_ENCODING, acceptEncoding);+ Resource resource =+ resolver.resolveResource(+ request,+ "app.js",+ List.of(new FileSystemResource(tempDir)),+ new ResourceResolverChain() {+ @Override+ public Resource resolveResource(+ HttpServletRequest r,+ String path,+ List<? extends Resource> locations) {+ return new FileSystemResource(tempDir.resolve(path));+ }++ @Override+ public String resolveUrlPath(+ String resourceUrlPath,+ List<? extends Resource> locations) {+ return resourceUrlPath;+ }+ });+ assertThat(resource).isNotNull();+ if (resource instanceof HttpResource httpResource) {+ return httpResource.getResponseHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);+ }+ return null;+ }+ }}diff --git a/docker/frontend/Dockerfile b/docker/frontend/Dockerfileindex b84a420af8..dee2012f48 100644--- a/docker/frontend/Dockerfile+++ b/docker/frontend/Dockerfile@@ -23,6 +23,7 @@ ARG VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY=""# Build vite from editor/, output lands in editor/dist/.RUN set -eu; \+ export UV_THREADPOOL_SIZE="${UV_THREADPOOL_SIZE:-16}"; \export STIRLING_FLAVOR="${STIRLING_FLAVOR}"; \if [ -n "${VITE_SUPABASE_URL}" ]; then export VITE_SUPABASE_URL="${VITE_SUPABASE_URL}"; fi; \if [ -n "${VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY}" ]; then export VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY="${VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY}"; fi; \diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 53b10ddd01..aff5a2d21e 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -55,7 +55,9 @@ keepWorking = "Keep Working"loading = "Loading..."loginAgreementAccept = "Accept"loginAgreementDecline = "Decline"+loginAgreementLoadFailed = "The login agreement could not be loaded."loginAgreementProvider = "This notice is provided by your administrator, not Stirling PDF Inc."+loginAgreementRetry = "Retry"loginAgreementTitle = "Login Agreement"logOut = "Log out"marginTooltip = "Distance between the page number and the edge of the page."@@ -7975,6 +7977,7 @@ before = "Set"title = "Stirling connection not configured"[portal.accountLink.notice]+loadFailed = "The account linking dialog could not be loaded."openFailed = "Could not open your browser. Open Usage & billing on your connected server to link an account."[portal.accountLink.panel]diff --git a/frontend/editor/scripts/stage-backend-jar.mjs b/frontend/editor/scripts/stage-backend-jar.mjsnew file mode 100644index 0000000000..030f935ee9--- /dev/null+++ b/frontend/editor/scripts/stage-backend-jar.mjs@@ -0,0 +1,61 @@+#!/usr/bin/env node+// Stages the bootJar the desktop bundle expects under src-tauri/libs.+//+// tauri.conf.json bundles the whole libs/*.jar glob, so exactly one artifact+// must be present. The build's own version.properties names that artifact;+// scanning by mtime would be wrong because Gradle leaves an up-to-date bootJar+// output untouched, which lets a previously built jar look newer and get staged+// instead of the version that actually shipped.+//+// Usage: stage-backend-jar.mjs <sourceDir> <destDir> [version]+import {+ copyFileSync,+ existsSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ rmSync,+} from "node:fs";+import { join } from "node:path";++const [sourceDir, destDir, versionArg] = process.argv.slice(2);++const VERSION_PROPERTIES = "app/common/src/main/resources/version.properties";++function resolveVersion() {+ if (versionArg) return versionArg;+ if (!existsSync(VERSION_PROPERTIES)) {+ console.error(+ `Missing ${VERSION_PROPERTIES}; run the backend build or pass a version.`,+ );+ process.exit(1);+ }+ const match = readFileSync(VERSION_PROPERTIES, "utf8").match(+ /^version=(.+)$/m,+ );+ if (!match) {+ console.error(`No version= entry in ${VERSION_PROPERTIES}`);+ process.exit(1);+ }+ return match[1].trim();+}++const jarName = `stirling-pdf-${resolveVersion()}.jar`;+const source = join(sourceDir, jarName);++if (!existsSync(source)) {+ console.error(+ `Expected ${jarName} in ${sourceDir}; the backend build did not produce it.`,+ );+ process.exit(1);+}++mkdirSync(destDir, { recursive: true });+const staged = existsSync(destDir)+ ? readdirSync(destDir).filter((name) => /^stirling-pdf-.*\.jar$/.test(name))+ : [];+for (const name of staged) {+ rmSync(join(destDir, name), { force: true });+}+copyFileSync(source, join(destDir, jarName));+console.log(`Staged ${jarName} in ${destDir}`);diff --git a/frontend/editor/src-tauri/src/commands/backend.rs b/frontend/editor/src-tauri/src/commands/backend.rsindex 28c406dda5..5ccef61603 100644--- a/frontend/editor/src-tauri/src/commands/backend.rs+++ b/frontend/editor/src-tauri/src/commands/backend.rs@@ -125,11 +125,12 @@ fn find_stirling_jar(resource_dir: &PathBuf) -> Result<PathBuf, String> {return Err(error_msg);}- // Sort by filename to get the latest version (case-insensitive)+ // Sort by parsed version, newest first. A name sort would rank 3.9.0 above+ // 3.10.0, launching an older backend than the one that shipped.jar_files.sort_by(|a, b| {- let name_a = a.file_name().to_string_lossy().to_ascii_lowercase();- let name_b = b.file_name().to_string_lossy().to_ascii_lowercase();- name_b.cmp(&name_a) // Reverse order to get latest first+ let key_a = version_key(&a.file_name().to_string_lossy());+ let key_b = version_key(&b.file_name().to_string_lossy());+ key_b.cmp(&key_a)});let jar_path = jar_files[0].path();@@ -137,6 +138,96 @@ fn find_stirling_jar(resource_dir: &PathBuf) -> Result<PathBuf, String> {Ok(jar_path)}+/// One component of a prerelease suffix. Recognized stages sort by maturity+/// (snapshot < alpha < beta < milestone < rc) rather than alphabetically, so a+/// development `SNAPSHOT` cannot outrank a release candidate. Unrecognized words+/// stay text, and a bare stage sorts below the same stage with a number (`rc` <+/// `rc1`) because a shorter token list precedes its own extension.+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]+enum PrereleaseToken {+ Stage(u8),+ Numeric(u64),+ Text(String),+}++/// Maturity rank for a known prerelease stage, or `None` to keep the word as+/// text. Rankings ascend toward the release candidate so a validated build wins.+fn stage_rank(word: &str) -> Option<u8> {+ Some(match word {+ "snapshot" | "dev" => 0,+ "alpha" => 1,+ "beta" => 2,+ "milestone" => 3,+ "rc" => 4,+ _ => return None,+ })+}++/// Split a prerelease suffix into ordered tokens, dropping separators so+/// `rc.10` and `rc10` compare the same.+fn prerelease_tokens(suffix: &str) -> Vec<PrereleaseToken> {+ let mut tokens = Vec::new();+ let mut chars = suffix.chars().peekable();+ while let Some(¤t) = chars.peek() {+ if current.is_ascii_digit() {+ let mut value: u64 = 0;+ while let Some(&digit) = chars.peek() {+ match digit.to_digit(10) {+ Some(d) => {+ value = value.saturating_mul(10).saturating_add(u64::from(d));+ chars.next();+ }+ None => break,+ }+ }+ tokens.push(PrereleaseToken::Numeric(value));+ } else if current.is_ascii_alphabetic() {+ let mut text = String::new();+ while let Some(&letter) = chars.peek() {+ if letter.is_ascii_alphabetic() {+ text.push(letter.to_ascii_lowercase());+ chars.next();+ } else {+ break;+ }+ }+ match stage_rank(&text) {+ Some(rank) => tokens.push(PrereleaseToken::Stage(rank)),+ None => tokens.push(PrereleaseToken::Text(text)),+ }+ } else {+ chars.next();+ }+ }+ tokens+}++/// Ordering key for `stirling-pdf-<version>.jar`: the numeric release components,+/// whether the version is a final release (1 for final release, 0 for prerelease),+/// and the prerelease identifiers. Anything unparseable counts as zero so comparison never+/// panics, while final releases sort above prereleases, and prereleases order by stage+/// maturity (snapshot < alpha < beta < milestone < rc) then by stage number (rc2 < rc10).+fn version_key(name: &str) -> (Vec<u64>, u8, Vec<PrereleaseToken>) {+ let lower = name.to_ascii_lowercase();+ let version = lower+ .split_once("stirling-pdf-")+ .map(|(_, rest)| rest)+ .and_then(|rest| rest.strip_suffix(".jar"))+ .unwrap_or(&lower);+ let (release, suffix) = match version.split_once(['-', '_']) {+ Some((release, suffix)) => (release, suffix),+ None => (version, ""),+ };+ (+ release+ .split('.')+ .map(|part| part.parse::<u64>().unwrap_or(0))+ .collect(),+ if suffix.is_empty() { 1 } else { 0 },+ prerelease_tokens(suffix),+ )+}+// Normalize path to remove Windows UNC prefixfn normalize_path(path: &PathBuf) -> PathBuf {if cfg!(windows) {@@ -533,3 +624,147 @@ pub fn cleanup_backend() {let _ = child.kill();}}++#[cfg(test)]+mod tests {+ use super::{find_stirling_jar, version_key};++ #[test]+ fn version_key_orders_numerically_not_lexically() {+ let mut names = [+ "stirling-pdf-2.9.0.jar",+ "stirling-pdf-3.9.0.jar",+ "stirling-pdf-3.10.0.jar",+ "stirling-pdf-2.14.2.jar",+ ];+ names.sort_by_key(|name| std::cmp::Reverse(version_key(name)));+ assert_eq!(+ names,+ [+ "stirling-pdf-3.10.0.jar",+ "stirling-pdf-3.9.0.jar",+ "stirling-pdf-2.14.2.jar",+ "stirling-pdf-2.9.0.jar",+ ]+ );+ }++ #[test]+ fn version_key_ranks_prereleases_below_the_release() {+ assert!(+ version_key("stirling-pdf-3.0.0-SNAPSHOT.jar") < version_key("stirling-pdf-3.0.0.jar")+ );+ assert!(version_key("stirling-pdf-3.0.0-rc1.jar") < version_key("stirling-pdf-3.0.0.jar"));+ assert!(+ version_key("stirling-pdf-3.0.0-rc1.jar") < version_key("stirling-pdf-3.0.0-rc2.jar")+ );++ let mut names = [+ "stirling-pdf-3.0.0-rc1.jar",+ "stirling-pdf-3.0.0.jar",+ "stirling-pdf-3.0.0-rc2.jar",+ "stirling-pdf-2.14.3.jar",+ ];+ names.sort_by_key(|name| std::cmp::Reverse(version_key(name)));+ assert_eq!(+ names,+ [+ "stirling-pdf-3.0.0.jar",+ "stirling-pdf-3.0.0-rc2.jar",+ "stirling-pdf-3.0.0-rc1.jar",+ "stirling-pdf-2.14.3.jar",+ ]+ );+ }++ #[test]+ fn version_key_orders_prerelease_numbers_numerically() {+ assert!(+ version_key("stirling-pdf-3.0.0-rc2.jar") < version_key("stirling-pdf-3.0.0-rc10.jar")+ );++ let mut names = [+ "stirling-pdf-3.0.0-rc10.jar",+ "stirling-pdf-3.0.0-rc2.jar",+ "stirling-pdf-3.0.0-rc1.jar",+ ];+ names.sort_by_key(|name| std::cmp::Reverse(version_key(name)));+ assert_eq!(+ names,+ [+ "stirling-pdf-3.0.0-rc10.jar",+ "stirling-pdf-3.0.0-rc2.jar",+ "stirling-pdf-3.0.0-rc1.jar",+ ]+ );+ }++ #[test]+ fn version_key_tolerates_non_numeric_versions() {+ let key = version_key("not-a-version.jar");+ assert_eq!(key.0, vec![0]);+ assert_eq!(key.1, 0);+ assert_eq!(version_key("stirling-pdf-3.0.0.jar").1, 1);+ }++ #[test]+ fn version_key_parses_the_token_anywhere_in_the_name() {+ // find_stirling_jar accepts any name containing "stirling-pdf", so a+ // prefixed build must still yield a real version rather than 0.+ assert!(+ version_key("stirling-pdf-3.9.0.jar") < version_key("vendor-stirling-pdf-3.10.0.jar")+ );++ let mut names = ["vendor-stirling-pdf-3.10.0.jar", "stirling-pdf-3.9.0.jar"];+ names.sort_by_key(|name| std::cmp::Reverse(version_key(name)));+ assert_eq!(+ names,+ ["vendor-stirling-pdf-3.10.0.jar", "stirling-pdf-3.9.0.jar"]+ );+ }++ #[test]+ fn version_key_ranks_snapshot_below_release_candidates() {+ // A development SNAPSHOT must never outrank a validated release candidate.+ assert!(+ version_key("stirling-pdf-3.0.0-SNAPSHOT.jar")+ < version_key("stirling-pdf-3.0.0-rc1.jar")+ );+ assert!(+ version_key("stirling-pdf-3.0.0-alpha1.jar")+ < version_key("stirling-pdf-3.0.0-beta1.jar")+ );+ assert!(+ version_key("stirling-pdf-3.0.0-beta1.jar") < version_key("stirling-pdf-3.0.0-rc1.jar")+ );++ let mut names = [+ "stirling-pdf-3.0.0-SNAPSHOT.jar",+ "stirling-pdf-3.0.0-rc1.jar",+ "stirling-pdf-3.0.0.jar",+ ];+ names.sort_by_key(|name| std::cmp::Reverse(version_key(name)));+ assert_eq!(+ names,+ [+ "stirling-pdf-3.0.0.jar",+ "stirling-pdf-3.0.0-rc1.jar",+ "stirling-pdf-3.0.0-SNAPSHOT.jar",+ ]+ );+ }++ #[test]+ fn find_stirling_jar_prefers_release_candidate_over_snapshot() {+ let dir = std::env::temp_dir().join(format!("stirling-jar-select-{}", std::process::id()));+ let libs = dir.join("libs");+ std::fs::create_dir_all(&libs).unwrap();+ std::fs::write(libs.join("stirling-pdf-3.0.0-SNAPSHOT.jar"), b"").unwrap();+ std::fs::write(libs.join("stirling-pdf-3.0.0-rc1.jar"), b"").unwrap();++ let selected = find_stirling_jar(&dir).unwrap();++ assert_eq!(selected.file_name().unwrap(), "stirling-pdf-3.0.0-rc1.jar");+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/frontend/editor/src/core/components/layout/AppRoot.tsx b/frontend/editor/src/core/components/layout/AppRoot.tsxindex b8f1c1294e..c22db4cd11 100644--- a/frontend/editor/src/core/components/layout/AppRoot.tsx+++ b/frontend/editor/src/core/components/layout/AppRoot.tsx@@ -5,6 +5,7 @@ import { LoadingFallback } from "@app/components/shared/LoadingFallback";import { stripBasePath } from "@app/constants/app";import { DOCS_PATH, HAS_DOCS } from "@app/routes/docsRoute";import { StartupPrompts } from "@app/components/startup/StartupPrompts";+import { usePdfEngineWarmUp } from "@app/hooks/usePdfEngineWarmUp";// Their own chunks: the settings tree (admin sections, account, licence flows)// and the docs manifest are both large, and most sessions open neither.@@ -36,6 +37,7 @@ function AppContent() {/** The editor's authenticated or login-disabled routes, including catch-all entries. */export function AppRoot() {+ usePdfEngineWarmUp();return (<><StartupPrompts />diff --git a/frontend/editor/src/core/components/shared/LoginAgreementBody.tsx b/frontend/editor/src/core/components/shared/LoginAgreementBody.tsxnew file mode 100644index 0000000000..8b0869bacd--- /dev/null+++ b/frontend/editor/src/core/components/shared/LoginAgreementBody.tsx@@ -0,0 +1,20 @@+import Markdown, { type Components } from "react-markdown";+import remarkGfm from "remark-gfm";++// Separate module so the markdown renderer stays in its own chunk: the modal+// shell renders without it and only the disclaimer text needs it.++const markdownComponents: Components = {+ // Strip react-markdown's `node` prop so it isn't spread onto the DOM element.+ a({ node, ...props }) {+ return <a {...props} target="_blank" rel="noopener noreferrer" />;+ },+};++export default function LoginAgreementBody({ content }: { content: string }) {+ return (+ <Markdown remarkPlugins={[remarkGfm]} components={markdownComponents}>+ {content}+ </Markdown>+ );+}diff --git a/frontend/editor/src/core/components/shared/LoginAgreementModal.tsx b/frontend/editor/src/core/components/shared/LoginAgreementModal.tsxindex 9096aadbb9..b796997d47 100644--- a/frontend/editor/src/core/components/shared/LoginAgreementModal.tsx+++ b/frontend/editor/src/core/components/shared/LoginAgreementModal.tsx@@ -1,8 +1,18 @@-import { useEffect, useRef, useState, type ReactNode } from "react";+import {+ Component,+ Suspense,+ lazy,+ useEffect,+ useRef,+ useState,+ type ReactNode,+} from "react";import {Box,+ Center,Divider,Group,+ Loader,Modal,ScrollArea,Stack,@@ -10,14 +20,43 @@ import {} from "@mantine/core";import { Button } from "@app/ui/Button";import { useTranslation } from "react-i18next";-import Markdown, { type Components } from "react-markdown";-import remarkGfm from "remark-gfm";import apiClient from "@app/services/apiClient";import { useAppConfig } from "@app/contexts/AppConfigContext";import { useAuth } from "@app/auth/UseSession";import { withBasePath } from "@app/constants/app";import { Z_INDEX_SIGN_IN_MODAL } from "@app/styles/zIndex";+// The markdown renderer (react-markdown + remark-gfm + micromark, ~120 KB gz)+// is only needed when an administrator set a disclaimer, so the modal body+// loads it as its own chunk.+const LoginAgreementBody = lazy(+ () => import("@app/components/shared/LoginAgreementBody"),+);++/**+ * Catches a failed login-agreement chunk so the modal can offer a retry. Without+ * it the rejection surfaces at the nearest ancestor boundary, outside this+ * modal, leaving the mandatory agreement impossible to pass.+ */+class BodyBoundary extends Component<+ { children: ReactNode; onError: () => void },+ { failed: boolean }+> {+ state = { failed: false };++ static getDerivedStateFromError() {+ return { failed: true };+ }++ componentDidCatch() {+ this.props.onError();+ }++ render() {+ return this.state.failed ? null : this.props.children;+ }+}+const ACCEPTED_STORAGE_KEY = "loginAgreementAccepted";interface DisclaimerResponse {@@ -55,13 +94,6 @@ function getLoginNonce(loginEnabled: boolean, userId?: string): string {return "session";}-const markdownComponents: Components = {- // Strip react-markdown's `node` prop so it isn't spread onto the DOM element.- a({ node, ...props }) {- return <a {...props} target="_blank" rel="noopener noreferrer" />;- },-};-/*** Blocking login agreement / disclaimer shown once per login (and once per app session in* anonymous mode). Text is fetched live for the user's current language; admins manage it via@@ -79,12 +111,14 @@ export default function LoginAgreementModal({const [opened, setOpened] = useState(false);const [resolved, setResolved] = useState(false);const [content, setContent] = useState("");+ const [bodyError, setBodyError] = useState(false);const nonceRef = useRef("anon");useEffect(() => {if (!config) return;setResolved(false);setOpened(false);+ setBodyError(false);const loginEnabled = config.enableLogin !== false;let cancelled = false;@@ -174,33 +208,67 @@ export default function LoginAgreementModal({zIndex={Z_INDEX_SIGN_IN_MODAL}><Stack>- <ScrollArea.Autosize mah="50vh" type="auto">- <Box px="xs">- <Markdown- remarkPlugins={[remarkGfm]}- components={markdownComponents}+ {bodyError ? (+ <Stack align="center" gap="md">+ <Text size="sm" c="dimmed" ta="center">+ {t(+ "loginAgreementLoadFailed",+ "The login agreement could not be loaded.",+ )}+ </Text>+ <Group gap="sm">+ <Button variant="secondary" onClick={handleDecline}>+ {t("loginAgreementDecline", "Decline")}+ </Button>+ <Button+ variant="primary"+ onClick={() => window.location.reload()}+ >+ {t("loginAgreementRetry", "Retry")}+ </Button>+ </Group>+ </Stack>+ ) : (+ /* The controls share the boundary: acceptance must not be reachable+ before the agreement text itself has loaded. */+ <BodyBoundary onError={() => setBodyError(true)}>+ <Suspense+ fallback={+ <Center mih="8rem">+ <Loader size="sm" />+ </Center>+ }>- {content}- </Markdown>- </Box>- </ScrollArea.Autosize>- <Divider />- <Group justify="space-between" gap="sm" align="center" wrap="wrap">- <Text size="xs" c="dimmed" style={{ flex: 1, minWidth: 0 }}>- {t(- "loginAgreementProvider",- "This notice is provided by your administrator, not Stirling PDF Inc.",- )}- </Text>- <Group gap="sm" wrap="nowrap">- <Button variant="secondary" onClick={handleDecline}>- {t("loginAgreementDecline", "Decline")}- </Button>- <Button variant="primary" onClick={handleAccept}>- {t("loginAgreementAccept", "Accept")}- </Button>- </Group>- </Group>+ <ScrollArea.Autosize mah="50vh" type="auto">+ <Box px="xs">+ <LoginAgreementBody content={content} />+ </Box>+ </ScrollArea.Autosize>+ <Divider />+ <Group+ justify="space-between"+ gap="sm"+ align="center"+ wrap="wrap"+ >+ <Text size="xs" c="dimmed" style={{ flex: 1, minWidth: 0 }}>+ {t(+ "loginAgreementProvider",+ "This notice is provided by your administrator, not Stirling PDF Inc.",+ )}+ </Text>+ <Group gap="sm" wrap="nowrap">+ <Button variant="secondary" onClick={handleDecline}>+ {t("loginAgreementDecline", "Decline")}+ </Button>+ <Button variant="primary" onClick={handleAccept}>+ {t("loginAgreementAccept", "Accept")}+ </Button>+ </Group>+ </Group>+ </Suspense>+ </BodyBoundary>+ )}</Stack></Modal>);diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsxindex ddaf292100..4e29a21039 100644--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx@@ -10,7 +10,7 @@ import React, {import { createPluginRegistration, type PluginRegistry } from "@embedpdf/core";import type { InitialDocumentOptions } from "@embedpdf/plugin-document-manager";import { EmbedPDF, useDocumentState } from "@embedpdf/core/react";-import { usePdfiumEngine } from "@embedpdf/engines/react";+import { useLocalPdfiumEngine } from "@app/hooks/useLocalPdfiumEngine";import { PrivateContent } from "@app/components/shared/PrivateContent";import { useAppConfig } from "@app/contexts/AppConfigContext";import { useSignaturePreviewHistory } from "@app/hooks/signing/useSignaturePreviewHistory";@@ -116,7 +116,7 @@ import { RedactionAPIBridge } from "@app/components/viewer/RedactionAPIBridge";import { DocumentPermissionsAPIBridge } from "@app/components/viewer/DocumentPermissionsAPIBridge";import { DocumentReadyWrapper } from "@app/components/viewer/DocumentReadyWrapper";import ToolLoadingFallback from "@app/components/tools/ToolLoadingFallback";-import { getLocalFontFallbackConfig } from "@app/services/pdfiumFontFallback";+import { useFontFallbackConfig } from "@app/hooks/useFontFallbackConfig";import { pdfiumWasmUrl } from "@app/services/wasmPrecompiler";import { FormFieldOverlay } from "@app/tools/formFill/FormFieldOverlay";import { FormCreationInteractionLock } from "@app/tools/formFill/FormCreationInteractionLock";@@ -1229,9 +1229,9 @@ export function LocalEmbedPDF({];}, [initialDocument, urlPluginsSource, enableAnnotations]);- const fontFallbackConfig = useMemo(() => getLocalFontFallbackConfig(), []);+ const fontFallbackConfig = useFontFallbackConfig();- const { engine, isLoading, error } = usePdfiumEngine({+ const { engine, isLoading, error } = useLocalPdfiumEngine({wasmUrl: pdfiumWasmUrl,fontFallback: fontFallbackConfig,});@@ -1293,6 +1293,27 @@ export function LocalEmbedPDF({const hasInput = Boolean(file || url);const isInputReady = Boolean(initialDocument || (!file && pdfUrl));+ // Checked before the loading screen: a rejected engine import leaves `engine`+ // null, so the loader would otherwise hide the error forever.+ if (error) {+ return (+ <Center h="100%" w="100%">+ <Stack align="center" gap="md">+ <div style={{ fontSize: "24px" }}>⚠️</div>+ <Text c="red" size="sm">+ {t(+ "viewer.engineLoadError",+ "Failed to initialize PDF viewer engine",+ )}+ </Text>+ <Text c="dimmed" size="xs">+ {error.message}+ </Text>+ </Stack>+ </Center>+ );+ }+if (isLoading || !engine || (hasInput && !isInputReady)) {return (<Center h="100%" w="100%">@@ -1318,25 +1339,6 @@ export function LocalEmbedPDF({);}- if (error) {- return (- <Center h="100%" w="100%">- <Stack align="center" gap="md">- <div style={{ fontSize: "24px" }}>⚠️</div>- <Text c="red" size="sm">- {t(- "viewer.engineLoadError",- "Failed to initialize PDF viewer engine",- )}- </Text>- <Text c="dimmed" size="xs">- {error.message}- </Text>- </Stack>- </Center>- );- }-const handleInitialized = async (registry: PluginRegistry) => {// v2.0: Use registry.getPlugin() to access plugin APIsconst annotationPlugin = registry.getPlugin("annotation");diff --git a/frontend/editor/src/core/components/viewer/nonpdf/MarkdownRenderer.tsx b/frontend/editor/src/core/components/viewer/nonpdf/MarkdownRenderer.tsxindex fe820aa2db..42fec10d3c 100644--- a/frontend/editor/src/core/components/viewer/nonpdf/MarkdownRenderer.tsx+++ b/frontend/editor/src/core/components/viewer/nonpdf/MarkdownRenderer.tsx@@ -1,114 +1,81 @@-import React, { useState } from "react";-import ReactMarkdown from "react-markdown";-import type { Components } from "react-markdown";-import remarkGfm from "remark-gfm";+import React, { Component, Suspense, lazy, useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "@app/ui/Button";-function CopyButton({ text }: { text: string }) {+// react-markdown + remark-gfm + micromark are ~120 KB gz and only needed when a+// markdown document is open (viewer) or a chat message arrives, so the heavy+// module is its own chunk while callers keep the synchronous signature.+const loadMarkdownRendererImpl = () =>+ import("@app/components/viewer/nonpdf/MarkdownRendererImpl");++function rawMarkdown(content: string): React.ReactNode {+ return <div style={{ whiteSpace: "pre-wrap" }}>{content}</div>;+}++/** Keeps a failed chunk local: the raw text stays visible instead of the app+ * boundary replacing the whole view. */+class MarkdownBoundary extends Component<+ { children: React.ReactNode; onError: () => void },+ { failed: boolean }+> {+ state = { failed: false };++ static getDerivedStateFromError() {+ return { failed: true };+ }++ componentDidCatch() {+ this.props.onError();+ }++ render() {+ return this.state.failed ? null : this.props.children;+ }+}++function MarkdownBlock({ content }: { content: string }) {const { t } = useTranslation();- const [copied, setCopied] = useState(false);- return (- <Button- variant="tertiary"- onClick={() =>- navigator.clipboard.writeText(text).then(() => {- setCopied(true);- setTimeout(() => setCopied(false), 1500);- })- }- style={{- position: "absolute",- top: 8,- right: 8,- background: copied- ? "var(--mantine-color-green-0)"- : "var(--mantine-color-gray-0)",- border: "1px solid var(--mantine-color-gray-3)",- borderRadius: 3,- cursor: "pointer",- fontSize: "0.7em",- padding: "2px 8px",- color: copied- ? "var(--mantine-color-green-7)"- : "var(--mantine-color-gray-7)",- }}- >- {copied- ? `✓ ${t("viewer.nonPdf.copied", "Copied")}`- : t("common.copy", "Copy")}- </Button>+ // Held here, not in the rendered chunk: a component that suspends on its+ // first render loses its state, so a lazy built inside it would be recreated+ // on every retry and suspend forever. React also caches a lazy's rejected+ // import, so the retry below swaps in a fresh one.+ const [MarkdownRendererImpl, setMarkdownRendererImpl] = useState(() =>+ lazy(loadMarkdownRendererImpl),);-}+ const [attempt, setAttempt] = useState(0);+ const [failed, setFailed] = useState(false);-const components: Components = {- pre: ({ children }) => {- const codeText = React.isValidElement(children)- ? String((children.props as { children?: unknown }).children ?? "")- : String(children ?? "");+ if (failed) {return (- <div style={{ position: "relative", margin: "8px 0" }}>- <pre- style={{- background: "var(--mantine-color-gray-1)",- padding: "10px 52px 10px 14px",- borderRadius: 4,- overflowX: "auto",- fontSize: "0.85em",- margin: 0,- }}- >- {children}- </pre>- <CopyButton text={codeText} />+ <div style={{ whiteSpace: "pre-wrap" }}>+ {content}+ <div style={{ marginTop: "var(--mantine-spacing-sm)" }}>+ <Button+ variant="secondary"+ onClick={() => {+ setMarkdownRendererImpl(lazy(loadMarkdownRendererImpl));+ setFailed(false);+ setAttempt((n) => n + 1);+ }}+ >+ {t("errorBoundary.tryAgain", "Try Again")}+ </Button>+ </div></div>);- },- table: ({ children }) => (- <div style={{ overflowX: "auto", margin: "10px 0" }}>- <table- style={{- borderCollapse: "collapse",- width: "100%",- fontSize: "0.85em",- }}- >- {children}- </table>- </div>- ),- th: ({ children, style }) => (- <th- style={{- border: "1px solid var(--mantine-color-gray-3)",- padding: "6px 10px",- background: "var(--mantine-color-gray-1)",- textAlign: "left",- fontWeight: 600,- whiteSpace: "nowrap",- ...style,- }}- >- {children}- </th>- ),- td: ({ children, style }) => (- <td- style={{- border: "1px solid var(--mantine-color-gray-3)",- padding: "5px 10px",- ...style,- }}- >- {children}- </td>- ),-};+ }++ return (+ <MarkdownBoundary key={attempt} onError={() => setFailed(true)}>+ <Suspense fallback={rawMarkdown(content)}>+ <MarkdownRendererImpl content={content} />+ </Suspense>+ </MarkdownBoundary>+ );+}+/** Renders markdown; while the chunk loads the raw text shows, and if the chunk+ * fails the raw text stays with a retry control. */export function renderMarkdown(content: string): React.ReactNode[] {- return [- <ReactMarkdown key="md" remarkPlugins={[remarkGfm]} components={components}>- {content}- </ReactMarkdown>,- ];+ return [<MarkdownBlock key="md" content={content} />];}diff --git a/frontend/editor/src/core/components/viewer/nonpdf/MarkdownRendererImpl.tsx b/frontend/editor/src/core/components/viewer/nonpdf/MarkdownRendererImpl.tsxnew file mode 100644index 0000000000..b9ec6442e9--- /dev/null+++ b/frontend/editor/src/core/components/viewer/nonpdf/MarkdownRendererImpl.tsx@@ -0,0 +1,115 @@+import React, { useState } from "react";+import ReactMarkdown from "react-markdown";+import type { Components } from "react-markdown";+import remarkGfm from "remark-gfm";+import { useTranslation } from "react-i18next";+import { Button } from "@app/ui/Button";++function CopyButton({ text }: { text: string }) {+ const { t } = useTranslation();+ const [copied, setCopied] = useState(false);+ return (+ <Button+ variant="tertiary"+ onClick={() =>+ navigator.clipboard.writeText(text).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ })+ }+ style={{+ position: "absolute",+ top: 8,+ right: 8,+ background: copied+ ? "var(--mantine-color-green-0)"+ : "var(--mantine-color-gray-0)",+ border: "1px solid var(--mantine-color-gray-3)",+ borderRadius: 3,+ cursor: "pointer",+ fontSize: "0.7em",+ padding: "2px 8px",+ color: copied+ ? "var(--mantine-color-green-7)"+ : "var(--mantine-color-gray-7)",+ }}+ >+ {copied+ ? `✓ ${t("viewer.nonPdf.copied", "Copied")}`+ : t("common.copy", "Copy")}+ </Button>+ );+}++const components: Components = {+ pre: ({ children }) => {+ const codeText = React.isValidElement(children)+ ? String((children.props as { children?: unknown }).children ?? "")+ : String(children ?? "");+ return (+ <div style={{ position: "relative", margin: "8px 0" }}>+ <pre+ style={{+ background: "var(--mantine-color-gray-1)",+ padding: "10px 52px 10px 14px",+ borderRadius: 4,+ overflowX: "auto",+ fontSize: "0.85em",+ margin: 0,+ }}+ >+ {children}+ </pre>+ <CopyButton text={codeText} />+ </div>+ );+ },+ table: ({ children }) => (+ <div style={{ overflowX: "auto", margin: "10px 0" }}>+ <table+ style={{+ borderCollapse: "collapse",+ width: "100%",+ fontSize: "0.85em",+ }}+ >+ {children}+ </table>+ </div>+ ),+ th: ({ children, style }) => (+ <th+ style={{+ border: "1px solid var(--mantine-color-gray-3)",+ padding: "6px 10px",+ background: "var(--mantine-color-gray-1)",+ textAlign: "left",+ fontWeight: 600,+ whiteSpace: "nowrap",+ ...style,+ }}+ >+ {children}+ </th>+ ),+ td: ({ children, style }) => (+ <td+ style={{+ border: "1px solid var(--mantine-color-gray-3)",+ padding: "5px 10px",+ ...style,+ }}+ >+ {children}+ </td>+ ),+};++/** The actual react-markdown render; loaded on demand by MarkdownRenderer. */+export default function MarkdownRendererImpl({ content }: { content: string }) {+ return (+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>+ {content}+ </ReactMarkdown>+ );+}diff --git a/frontend/editor/src/core/contexts/ViewerContext.tsx b/frontend/editor/src/core/contexts/ViewerContext.tsxindex 86c42743be..a39cf14318 100644--- a/frontend/editor/src/core/contexts/ViewerContext.tsx+++ b/frontend/editor/src/core/contexts/ViewerContext.tsx@@ -47,11 +47,19 @@ import {DocumentPermissionsState,PdfPermissionFlag,} from "@app/contexts/viewer/viewerBridges";-import { SpreadMode } from "@embedpdf/plugin-spread/react";import {ViewerContext,type ViewerContextType,} from "@app/contexts/viewer/viewerContext";+import type { SpreadMode } from "@embedpdf/plugin-spread/react";++/**+ * SpreadMode.None as a literal. This context sits at the app root, and a runtime+ * import of any embedpdf module loads the whole viewer engine chunk, so+ * importing the enum would put all of it on the initial load. `satisfies` keeps+ * the literal checked against the library's own values.+ */+const SPREAD_NONE = "none" satisfies `${SpreadMode}` as SpreadMode;export { ViewerContext, useViewer } from "@app/contexts/viewer/viewerContext";export type { ViewerContextType } from "@app/contexts/viewer/viewerContext";@@ -197,7 +205,7 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {);const triggerImmediateSpreadUpdate = useCallback(- (mode: SpreadMode, isDualPage: boolean = mode !== SpreadMode.None) => {+ (mode: SpreadMode, isDualPage: boolean = mode !== SPREAD_NONE) => {triggerImmediateSpreadInternal(mode, isDualPage);},[triggerImmediateSpreadInternal],@@ -323,7 +331,7 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {const getSpreadState = useCallback((): SpreadState => {return (bridgeRefs.current.spread?.state || {- spreadMode: SpreadMode.None,+ spreadMode: SPREAD_NONE,isDualPage: false,});diff --git a/frontend/editor/src/core/hooks/useFontFallbackConfig.ts b/frontend/editor/src/core/hooks/useFontFallbackConfig.tsnew file mode 100644index 0000000000..7f7c4f58aa--- /dev/null+++ b/frontend/editor/src/core/hooks/useFontFallbackConfig.ts@@ -0,0 +1,20 @@+import { useEffect, useMemo, useState } from "react";+import { getLocalFontFallbackConfig } from "@app/services/pdfiumFontFallback";+import { subscribeToFontBaseUrl } from "@app/services/fontBaseUrl";++/**+ * PDFium fallback-font configuration, recomputed when the font base URL changes.+ * The desktop webview only learns the backend port after startup, so a config+ * memoized at mount would keep an empty base URL; `subscribeToFontBaseUrl` is a+ * no-op in the web build, where the base is known immediately.+ */+export function useFontFallbackConfig() {+ const [revision, setRevision] = useState(0);++ useEffect(+ () => subscribeToFontBaseUrl(() => setRevision((current) => current + 1)),+ [],+ );++ return useMemo(() => getLocalFontFallbackConfig(), [revision]);+}diff --git a/frontend/editor/src/core/hooks/useLocalPdfiumEngine.test.ts b/frontend/editor/src/core/hooks/useLocalPdfiumEngine.test.tsnew file mode 100644index 0000000000..be7770e947--- /dev/null+++ b/frontend/editor/src/core/hooks/useLocalPdfiumEngine.test.ts@@ -0,0 +1,226 @@+import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";++const mockCreatePdfiumEngine = vi.fn();++vi.mock("@embedpdf/engines/pdfium-worker-engine", () => ({+ createPdfiumEngine: (...args: unknown[]) => mockCreatePdfiumEngine(...args),+}));++const mockStartEagerWasmCompilation = vi.fn();++vi.mock("@app/services/wasmPrecompiler", () => ({+ startEagerWasmCompilation: () => mockStartEagerWasmCompilation(),+}));++const WASM_URL = "https://example.com/pdfium.wasm";++function engineWith(wait: (ok: () => void, fail: () => void) => void) {+ return {+ closeAllDocuments: () => ({ wait }),+ destroy: vi.fn(),+ };+}++describe("useLocalPdfiumEngine", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ test("creates the worker engine from the wasm url without gating on the precompiled module", async () => {+ const engine = engineWith((ok) => ok());+ mockCreatePdfiumEngine.mockReturnValue(engine);++ const { useLocalPdfiumEngine } =+ await import("@app/hooks/useLocalPdfiumEngine");++ const { result } = renderHook(() =>+ useLocalPdfiumEngine({ wasmUrl: WASM_URL }),+ );++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false);+ });++ expect(mockStartEagerWasmCompilation).toHaveBeenCalledTimes(1);+ expect(mockCreatePdfiumEngine).toHaveBeenCalledWith(+ WASM_URL,+ expect.not.objectContaining({ wasmModule: expect.anything() }),+ );+ expect(result.current.engine).toBe(engine);+ });++ test("destroys the engine when its documents close successfully", async () => {+ const engine = engineWith((ok) => ok());+ mockCreatePdfiumEngine.mockReturnValue(engine);++ const { useLocalPdfiumEngine } =+ await import("@app/hooks/useLocalPdfiumEngine");++ const { unmount } = renderHook(() =>+ useLocalPdfiumEngine({ wasmUrl: WASM_URL }),+ );+ await waitFor(() => {+ expect(mockCreatePdfiumEngine).toHaveBeenCalledTimes(1);+ });++ unmount();++ expect(engine.destroy).toHaveBeenCalledTimes(1);+ });++ test("still destroys the engine when closing its documents fails", async () => {+ // The engine's `wait` runs only one of its two callbacks, so destroy has to+ // be registered on the failure path too or the worker leaks.+ const engine = engineWith((_ok, fail) => fail());+ mockCreatePdfiumEngine.mockReturnValue(engine);++ const { useLocalPdfiumEngine } =+ await import("@app/hooks/useLocalPdfiumEngine");++ const { unmount } = renderHook(() =>+ useLocalPdfiumEngine({ wasmUrl: WASM_URL }),+ );+ await waitFor(() => {+ expect(mockCreatePdfiumEngine).toHaveBeenCalledTimes(1);+ });++ unmount();++ expect(engine.destroy).toHaveBeenCalledTimes(1);+ });++ test("destroys the engine when closeAllDocuments is absent or returns nothing", async () => {+ const absent = { destroy: vi.fn() };+ const noTask = { closeAllDocuments: () => undefined, destroy: vi.fn() };+ mockCreatePdfiumEngine+ .mockReturnValueOnce(absent)+ .mockReturnValueOnce(noTask);++ const { useLocalPdfiumEngine } =+ await import("@app/hooks/useLocalPdfiumEngine");++ const first = renderHook(() => useLocalPdfiumEngine({ wasmUrl: WASM_URL }));+ await waitFor(() => {+ expect(mockCreatePdfiumEngine).toHaveBeenCalledTimes(1);+ });+ first.unmount();+ expect(absent.destroy).toHaveBeenCalledTimes(1);++ const second = renderHook(() =>+ useLocalPdfiumEngine({ wasmUrl: WASM_URL }),+ );+ await waitFor(() => {+ expect(mockCreatePdfiumEngine).toHaveBeenCalledTimes(2);+ });+ second.unmount();+ expect(noTask.destroy).toHaveBeenCalledTimes(1);+ });++ test("destroys the engine when closing its documents throws", async () => {+ const engine = {+ closeAllDocuments: () => {+ throw new Error("close failed");+ },+ destroy: vi.fn(),+ };+ mockCreatePdfiumEngine.mockReturnValue(engine);++ const { useLocalPdfiumEngine } =+ await import("@app/hooks/useLocalPdfiumEngine");++ const { unmount } = renderHook(() =>+ useLocalPdfiumEngine({ wasmUrl: WASM_URL }),+ );+ await waitFor(() => {+ expect(mockCreatePdfiumEngine).toHaveBeenCalledTimes(1);+ });++ unmount();++ expect(engine.destroy).toHaveBeenCalledTimes(1);+ });++ test("destroys the engine exactly once when both close callbacks run", async () => {+ const engine = {+ closeAllDocuments: () => ({+ wait: (ok: () => void) => {+ ok();+ ok();+ },+ }),+ destroy: vi.fn(),+ };+ mockCreatePdfiumEngine.mockReturnValue(engine);++ const { useLocalPdfiumEngine } =+ await import("@app/hooks/useLocalPdfiumEngine");++ const { unmount } = renderHook(() =>+ useLocalPdfiumEngine({ wasmUrl: WASM_URL }),+ );+ await waitFor(() => {+ expect(mockCreatePdfiumEngine).toHaveBeenCalledTimes(1);+ });++ unmount();++ expect(engine.destroy).toHaveBeenCalledTimes(1);+ });++ test("destroys the previous engine when the wasm url changes", async () => {+ const first = engineWith((ok) => ok());+ const second = engineWith((ok) => ok());+ mockCreatePdfiumEngine+ .mockReturnValueOnce(first)+ .mockReturnValueOnce(second);++ const { useLocalPdfiumEngine } =+ await import("@app/hooks/useLocalPdfiumEngine");++ const { result, rerender } = renderHook(+ ({ url }: { url: string }) => useLocalPdfiumEngine({ wasmUrl: url }),+ { initialProps: { url: WASM_URL } },+ );+ await waitFor(() => {+ expect(result.current.engine).toBe(first);+ });++ rerender({ url: "https://example.com/other.wasm" });++ await waitFor(() => {+ expect(result.current.engine).toBe(second);+ });+ expect(first.destroy).toHaveBeenCalledTimes(1);+ });++ test("clears a prior error once a later attempt succeeds", async () => {+ mockCreatePdfiumEngine.mockImplementationOnce(() => {+ throw new Error("engine failed");+ });+ const recovered = engineWith((ok) => ok());+ mockCreatePdfiumEngine.mockReturnValueOnce(recovered);++ const { useLocalPdfiumEngine } =+ await import("@app/hooks/useLocalPdfiumEngine");++ const { result, rerender } = renderHook(+ ({ url }: { url: string }) => useLocalPdfiumEngine({ wasmUrl: url }),+ { initialProps: { url: WASM_URL } },+ );+ await waitFor(() => {+ expect(result.current.error).not.toBeNull();+ });++ rerender({ url: "https://example.com/other.wasm" });++ await waitFor(() => {+ expect(result.current.engine).toBe(recovered);+ });+ expect(result.current.error).toBeNull();+ });+});diff --git a/frontend/editor/src/core/hooks/useLocalPdfiumEngine.ts b/frontend/editor/src/core/hooks/useLocalPdfiumEngine.tsnew file mode 100644index 0000000000..c19d610ab8--- /dev/null+++ b/frontend/editor/src/core/hooks/useLocalPdfiumEngine.ts@@ -0,0 +1,101 @@+import { useEffect, useRef, useState } from "react";+import { type Logger, type PdfEngine } from "@embedpdf/models";+import type { FontFallbackConfig } from "@embedpdf/engines/pdfium-worker-engine";+import { startEagerWasmCompilation } from "@app/services/wasmPrecompiler";++interface LocalPdfiumEngineOptions {+ wasmUrl: string;+ logger?: Logger;+ encoderPoolSize?: number;+ fontFallback?: FontFallbackConfig | null;+}++/**+ * Destroy an engine once its documents are closed. Teardown has to be+ * unconditional: `closeAllDocuments` may be absent, return nothing, or throw,+ * and `wait` runs only one of its two callbacks, so a failed close would+ * otherwise leave the worker running for the lifetime of the app.+ */+function destroyEngine(engine: PdfEngine<Blob> | null): void {+ if (!engine) return;++ let destroyed = false;+ const destroy = () => {+ if (destroyed) return;+ destroyed = true;+ try {+ engine.destroy?.();+ } catch {+ // Nothing left to release once destroy itself fails.+ }+ };++ try {+ const closing = engine.closeAllDocuments?.();+ if (closing?.wait) {+ closing.wait(destroy, destroy);+ } else {+ destroy();+ }+ } catch {+ destroy();+ }+}++export function useLocalPdfiumEngine({+ wasmUrl,+ logger,+ encoderPoolSize,+ fontFallback,+}: LocalPdfiumEngineOptions) {+ const [engine, setEngine] = useState<PdfEngine<Blob> | null>(null);+ const [isLoading, setIsLoading] = useState(true);+ const [error, setError] = useState<Error | null>(null);+ const engineRef = useRef<PdfEngine<Blob> | null>(null);++ useEffect(() => {+ let cancelled = false;+ // Reset per attempt so the render tree never exposes the engine this run is+ // about to destroy, nor a stale error left over from an earlier failure.+ setEngine(null);+ setError(null);+ setIsLoading(true);++ (async () => {+ try {+ startEagerWasmCompilation();+ const { createPdfiumEngine } =+ await import("@embedpdf/engines/pdfium-worker-engine");+ // The worker engine resolves pdfium from wasmUrl itself, so the+ // precompiled module (a main-thread optimization) must not gate+ // creation; awaiting it here would only delay the engine.+ const pdfEngine = createPdfiumEngine(wasmUrl, {+ logger,+ encoderPoolSize,+ fontFallback,+ });+ if (cancelled) {+ destroyEngine(pdfEngine);+ return;+ }+ engineRef.current = pdfEngine;+ setEngine(pdfEngine);+ setIsLoading(false);+ } catch (cause) {+ if (!cancelled) {+ setError(cause instanceof Error ? cause : new Error(String(cause)));+ setIsLoading(false);+ }+ }+ })();++ return () => {+ cancelled = true;+ const current = engineRef.current;+ engineRef.current = null;+ destroyEngine(current);+ };+ }, [wasmUrl, logger, encoderPoolSize, fontFallback]);++ return { engine, isLoading, error };+}diff --git a/frontend/editor/src/core/hooks/usePdfEngineWarmUp.test.tsx b/frontend/editor/src/core/hooks/usePdfEngineWarmUp.test.tsxnew file mode 100644index 0000000000..64a952f977--- /dev/null+++ b/frontend/editor/src/core/hooks/usePdfEngineWarmUp.test.tsx@@ -0,0 +1,223 @@+import React from "react";+import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";+import { renderHook, act } from "@testing-library/react";+import {+ FileStoreContext,+ type FileStateStore,+} from "@app/contexts/file/contexts";+import type { FileContextState } from "@app/types/fileContext";+import type { FileId } from "@app/types/file";++const mockStartEagerWasmCompilation = vi.fn();++vi.mock("@app/services/wasmPrecompiler", () => ({+ startEagerWasmCompilation: () => mockStartEagerWasmCompilation(),+}));++interface MutableMockStore extends FileStateStore {+ setFiles: (ids: FileId[]) => void;+}++function createMockStore(initialFileIds: FileId[] = []): MutableMockStore {+ let state = {+ files: {+ ids: initialFileIds,+ byId: {},+ },+ } as unknown as FileContextState;+ const listeners = new Set<() => void>();++ return {+ getState: () => state,+ setFiles: (ids: FileId[]) => {+ state = {+ ...state,+ files: { ...state.files, ids },+ };+ listeners.forEach((l) => l());+ },+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ selectors: {} as FileStateStore["selectors"],+ };+}++describe("usePdfEngineWarmUp", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ test("warms up immediately when files already exist in store", async () => {+ const store = createMockStore(["file-1" as FileId]);+ const { usePdfEngineWarmUp } =+ await import("@app/hooks/usePdfEngineWarmUp");++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <FileStoreContext.Provider value={store}>+ {children}+ </FileStoreContext.Provider>+ );++ renderHook(() => usePdfEngineWarmUp(), { wrapper });++ expect(mockStartEagerWasmCompilation).toHaveBeenCalledTimes(1);+ });++ test("fetches nothing when the page is only visited", async () => {+ const store = createMockStore([]);+ const { usePdfEngineWarmUp } =+ await import("@app/hooks/usePdfEngineWarmUp");++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <FileStoreContext.Provider value={store}>+ {children}+ </FileStoreContext.Provider>+ );++ renderHook(() => usePdfEngineWarmUp(), { wrapper });++ act(() => {+ vi.advanceTimersByTime(60_000);+ });++ expect(mockStartEagerWasmCompilation).not.toHaveBeenCalled();+ });++ test("does not warm up for pointer input outside the file picker", async () => {+ const store = createMockStore([]);+ const { usePdfEngineWarmUp } =+ await import("@app/hooks/usePdfEngineWarmUp");++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <FileStoreContext.Provider value={store}>+ {children}+ </FileStoreContext.Provider>+ );++ renderHook(() => usePdfEngineWarmUp(), { wrapper });++ act(() => {+ window.dispatchEvent(new Event("pointerdown"));+ window.dispatchEvent(new Event("click"));+ });++ expect(mockStartEagerWasmCompilation).not.toHaveBeenCalled();+ });++ test("warms up when the file picker is opened", async () => {+ const store = createMockStore([]);+ const { usePdfEngineWarmUp } =+ await import("@app/hooks/usePdfEngineWarmUp");++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <FileStoreContext.Provider value={store}>+ {children}+ </FileStoreContext.Provider>+ );++ renderHook(() => usePdfEngineWarmUp(), { wrapper });++ const input = document.createElement("input");+ input.type = "file";+ input.style.display = "none";+ document.body.appendChild(input);++ act(() => {+ input.dispatchEvent(new Event("click", { bubbles: true }));+ });++ expect(mockStartEagerWasmCompilation).toHaveBeenCalledTimes(1);++ // A second open must not warm the engine again.+ act(() => {+ input.dispatchEvent(new Event("click", { bubbles: true }));+ });+ expect(mockStartEagerWasmCompilation).toHaveBeenCalledTimes(1);++ input.remove();+ });++ test("triggers early when file is added to store", async () => {+ const store = createMockStore([]);+ const { usePdfEngineWarmUp } =+ await import("@app/hooks/usePdfEngineWarmUp");++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <FileStoreContext.Provider value={store}>+ {children}+ </FileStoreContext.Provider>+ );++ renderHook(() => usePdfEngineWarmUp(), { wrapper });++ expect(mockStartEagerWasmCompilation).not.toHaveBeenCalled();++ act(() => {+ store.setFiles(["new-file" as FileId]);+ });++ expect(mockStartEagerWasmCompilation).toHaveBeenCalledTimes(1);+ });++ test("warms up only for an OS file drag, not an internal drag", async () => {+ const store = createMockStore([]);+ const { usePdfEngineWarmUp } =+ await import("@app/hooks/usePdfEngineWarmUp");++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <FileStoreContext.Provider value={store}>+ {children}+ </FileStoreContext.Provider>+ );++ renderHook(() => usePdfEngineWarmUp(), { wrapper });++ act(() => {+ window.dispatchEvent(new Event("dragenter"));+ });+ expect(mockStartEagerWasmCompilation).not.toHaveBeenCalled();++ act(() => {+ const fileDrag = new Event("dragenter") as Event & {+ dataTransfer?: { types: string[] };+ };+ fileDrag.dataTransfer = { types: ["Files"] };+ window.dispatchEvent(fileDrag);+ });+ expect(mockStartEagerWasmCompilation).toHaveBeenCalledTimes(1);+ });++ test("warms up when the file picker takes focus", async () => {+ const store = createMockStore([]);+ const { usePdfEngineWarmUp } =+ await import("@app/hooks/usePdfEngineWarmUp");++ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <FileStoreContext.Provider value={store}>+ {children}+ </FileStoreContext.Provider>+ );++ renderHook(() => usePdfEngineWarmUp(), { wrapper });++ const input = document.createElement("input");+ input.type = "file";+ document.body.appendChild(input);++ act(() => {+ input.dispatchEvent(new Event("focusin", { bubbles: true }));+ });++ expect(mockStartEagerWasmCompilation).toHaveBeenCalledTimes(1);++ input.remove();+ });+});diff --git a/frontend/editor/src/core/hooks/usePdfEngineWarmUp.ts b/frontend/editor/src/core/hooks/usePdfEngineWarmUp.tsnew file mode 100644index 0000000000..65c271dea2--- /dev/null+++ b/frontend/editor/src/core/hooks/usePdfEngineWarmUp.ts@@ -0,0 +1,66 @@+import { useContext, useEffect } from "react";+import { FileStoreContext } from "@app/contexts/file/contexts";+import { startEagerWasmCompilation } from "@app/services/wasmPrecompiler";++/**+ * Starts the PDFium WASM download and compile only once a document is actually+ * in play: documents already open, a document added, an OS file drag, or the+ * file picker opening. A page the user merely visits fetches nothing, so the+ * engine cost lands only on sessions that will open a PDF.+ */+export function usePdfEngineWarmUp(): void {+ const store = useContext(FileStoreContext);++ useEffect(() => {+ const warmUp = () => startEagerWasmCompilation();+ if (store && store.getState().files.ids.length > 0) {+ warmUp();+ return;+ }++ let warmed = false;+ const warmUpOnce = () => {+ if (warmed) {+ return;+ }+ warmed = true;+ warmUp();+ };++ const unsubscribe = store+ ? store.subscribe(() => {+ if (store.getState().files.ids.length > 0) {+ warmUpOnce();+ }+ })+ : undefined;++ const onDragEnter = (event: DragEvent) => {+ // Internal reorder/drop targets also emit dragenter; only an OS file drag+ // should pull the engine down.+ if (event.dataTransfer?.types.includes("Files")) {+ warmUpOnce();+ }+ };+ // The picker is a hidden input opened with a programmatic click, which no+ // longer focuses it, so match on click as well as keyboard focus. Both are+ // scoped to the file input: a pointerdown anywhere else must not warm.+ const onFilePickerIntent = (event: Event) => {+ const target = event.target as Element | null;+ if (target?.matches?.('input[type="file"]')) {+ warmUpOnce();+ }+ };++ window.addEventListener("dragenter", onDragEnter, { passive: true });+ window.addEventListener("click", onFilePickerIntent, { passive: true });+ window.addEventListener("focusin", onFilePickerIntent);++ return () => {+ unsubscribe?.();+ window.removeEventListener("dragenter", onDragEnter);+ window.removeEventListener("click", onFilePickerIntent);+ window.removeEventListener("focusin", onFilePickerIntent);+ };+ }, [store]);+}diff --git a/frontend/editor/src/core/hooks/usePosthogTracking.test.tsx b/frontend/editor/src/core/hooks/usePosthogTracking.test.tsxindex b2e88a0ddd..43d08ab486 100644--- a/frontend/editor/src/core/hooks/usePosthogTracking.test.tsx+++ b/frontend/editor/src/core/hooks/usePosthogTracking.test.tsx@@ -78,4 +78,46 @@ describe("usePosthogTracking", () => {expect(posthogMock.init).toHaveBeenCalledTimes(1);});});++ it("retries the import after a failed load instead of replaying it", async () => {+ vi.resetModules();+ let attempts = 0;+ vi.doMock("posthog-js", () => {+ attempts += 1;+ if (attempts === 1) throw new Error("chunk load failed");+ return { default: posthogMock };+ });++ const [+ { usePosthogTracking: useTracking },+ { AppConfigProvider: Provider },+ ] = await Promise.all([+ import("@app/hooks/usePosthogTracking"),+ import("@app/contexts/AppConfigContext"),+ ]);+ const wrapper = ({ children }: { children: ReactNode }) => (+ <TestQueryProvider>+ <Provider+ initialConfig={{ enableAnalytics: true }}+ bootstrapMode="non-blocking"+ autoFetch={false}+ >+ {children}+ </Provider>+ </TestQueryProvider>+ );++ const first = renderHook(() => useTracking(), { wrapper });+ await waitFor(() => {+ expect(attempts).toBe(1);+ });+ expect(posthogMock.init).not.toHaveBeenCalled();+ first.unmount();++ renderHook(() => useTracking(), { wrapper });+ await waitFor(() => {+ expect(posthogMock.init).toHaveBeenCalledTimes(1);+ });+ expect(attempts).toBe(2);+ });});diff --git a/frontend/editor/src/core/hooks/usePosthogTracking.ts b/frontend/editor/src/core/hooks/usePosthogTracking.tsindex a8037ec4a7..204d273afe 100644--- a/frontend/editor/src/core/hooks/usePosthogTracking.ts+++ b/frontend/editor/src/core/hooks/usePosthogTracking.ts@@ -1,8 +1,20 @@import { useEffect } from "react";-import posthog from "posthog-js";import { useAppConfig } from "@app/contexts/AppConfigContext";+import { setActivePosthog } from "@app/services/analytics";-function applyPosthogConsent(): void {+// posthog-js is ~230 KB and only needed when analytics is on. This hook owns the+// load and publishes the client to analytics.ts, so capture never loads it.+type Posthog = typeof import("posthog-js").default;++let posthogPromise: Promise<Posthog> | null = null;+let activePosthog: Posthog | null = null;++function loadPosthog(): Promise<Posthog> {+ posthogPromise ??= import("posthog-js").then((mod) => mod.default);+ return posthogPromise;+}++function applyPosthogConsent(posthog: Posthog): void {if (typeof window === "undefined" || !posthog.__loaded) {return;}@@ -20,31 +32,24 @@ function applyPosthogConsent(): void {posthog.set_config({ persistence: "memory" });}-function ensurePosthogInitialized(): boolean {- if (typeof window === "undefined") {- return false;- }-- const posthogKey = import.meta.env.VITE_PUBLIC_POSTHOG_KEY;- const posthogHost = import.meta.env.VITE_PUBLIC_POSTHOG_HOST;-- if (!posthogKey || !posthogHost) {- return false;- }-- if (!posthog.__loaded) {- posthog.init(posthogKey, {- api_host: posthogHost,- defaults: "2025-05-24",- capture_exceptions: true,- debug: false,- opt_out_capturing_by_default: true,- persistence: "memory",- cross_subdomain_cookie: false,- });- }+function posthogConfig(): { key: string; host: string } | null {+ const key = import.meta.env.VITE_PUBLIC_POSTHOG_KEY;+ const host = import.meta.env.VITE_PUBLIC_POSTHOG_HOST;+ if (!key || !host) return null;+ return { key, host };+}- return true;+function initializePosthog(posthog: Posthog, key: string, host: string): void {+ if (posthog.__loaded) return;+ posthog.init(key, {+ api_host: host,+ defaults: "2025-05-24",+ capture_exceptions: true,+ debug: false,+ opt_out_capturing_by_default: true,+ persistence: "memory",+ cross_subdomain_cookie: false,+ });}export function usePosthogTracking(): void {@@ -55,29 +60,53 @@ export function usePosthogTracking(): void {const posthogEnabled = analyticsEnabled && config?.enablePosthog !== false;if (!posthogEnabled) {- if (posthog.__loaded) {- posthog.opt_out_capturing();- posthog.set_config({ persistence: "memory" });+ // Nothing loaded means nothing to opt out of; loading the module to do+ // so would defeat the deferral. An already-loaded client is opted out so+ // its own autocapture stops too, not just our capture() calls.+ if (activePosthog) {+ activePosthog.opt_out_capturing();+ activePosthog.set_config({ persistence: "memory" });}+ setActivePosthog(null);return;}- if (!ensurePosthogInitialized()) {+ const credentials = posthogConfig();+ if (!credentials) {return;}- applyPosthogConsent();-- const handleConsentChange = () => {- applyPosthogConsent();- };-- window.addEventListener("cc:onConsent", handleConsentChange);- window.addEventListener("cc:onChange", handleConsentChange);+ let cancelled = false;+ let handleConsentChange: (() => void) | null = null;++ void (async () => {+ const load = loadPosthog();+ const posthog = await load.catch(() => {+ // A rejected import would otherwise be replayed to every later effect;+ // clearing the cache lets the next enabled effect retry.+ if (posthogPromise === load) posthogPromise = null;+ return null;+ });+ if (!posthog || cancelled) return;+ activePosthog = posthog;+ setActivePosthog(posthog);++ initializePosthog(posthog, credentials.key, credentials.host);+ applyPosthogConsent(posthog);++ handleConsentChange = () => {+ applyPosthogConsent(posthog);+ };+ window.addEventListener("cc:onConsent", handleConsentChange);+ window.addEventListener("cc:onChange", handleConsentChange);+ })();return () => {- window.removeEventListener("cc:onConsent", handleConsentChange);- window.removeEventListener("cc:onChange", handleConsentChange);+ cancelled = true;+ if (handleConsentChange) {+ window.removeEventListener("cc:onConsent", handleConsentChange);+ window.removeEventListener("cc:onChange", handleConsentChange);+ }};}, [config?.enableAnalytics, config?.enablePosthog]);}diff --git a/frontend/editor/src/core/services/analytics.test.ts b/frontend/editor/src/core/services/analytics.test.tsindex 3334066cb9..4db22b6292 100644--- a/frontend/editor/src/core/services/analytics.test.ts+++ b/frontend/editor/src/core/services/analytics.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach } from "vitest";+import posthog from "posthog-js";const capture = vi.fn();let optedIn = true;@@ -12,6 +13,7 @@ vi.mock("posthog-js", () => ({}));import {+ setActivePosthog,trackPdfUploaded,trackEditorOperation,} from "@app/services/analytics";@@ -24,6 +26,7 @@ describe("analytics", () => {beforeEach(() => {capture.mockClear();optedIn = true;+ setActivePosthog(posthog);});it("captures one event per uploaded PDF (no dedup)", () => {@@ -57,4 +60,11 @@ describe("analytics", () => {trackEditorOperation("compress", 1);expect(capture).not.toHaveBeenCalled();});++ it("does not capture until usePosthogTracking publishes a client", () => {+ setActivePosthog(null);+ trackPdfUploaded([pdf("a.pdf")]);+ trackEditorOperation("compress", 1);+ expect(capture).not.toHaveBeenCalled();+ });});diff --git a/frontend/editor/src/core/services/analytics.ts b/frontend/editor/src/core/services/analytics.tsindex f4ea317eab..35ecc19241 100644--- a/frontend/editor/src/core/services/analytics.ts+++ b/frontend/editor/src/core/services/analytics.ts@@ -1,8 +1,17 @@-import posthog from "posthog-js";-const DEV = process.env.NODE_ENV === "development";-function canCapture(): boolean {+// usePosthogTracking owns loading and configuring posthog-js; capture only uses+// the client that hook publishes, so nothing downloads while analytics is off.+type Posthog = typeof import("posthog-js").default;++let activePosthog: Posthog | null = null;++/** Publishes the configured client, or null while analytics is disabled. */+export function setActivePosthog(posthog: Posthog | null): void {+ activePosthog = posthog;+}++function canCapture(posthog: Posthog): boolean {if (typeof window === "undefined") return false;const ph = posthog as unknown as {__loaded?: boolean;@@ -15,26 +24,31 @@ function canCapture(): boolean {);}-export function trackPdfUploaded(files: File[]): void {+function capture(+ tool: string,+ event: string,+ props: Record<string, unknown>,+): void {+ const posthog = activePosthog;+ if (!posthog || !canCapture(posthog)) return;try {- if (!canCapture() || !files) return;- for (let i = 0; i < files.length; i++) {- posthog.capture("editor_pdf_uploaded", { source: "editor" });- }+ posthog.capture(event, props);} catch (error) {- if (DEV) console.warn("[analytics] trackPdfUploaded failed", error);+ if (DEV) console.warn(`[analytics] ${tool} failed`, error);}}-export function trackEditorOperation(toolId: string, fileCount: number): void {- try {- if (!canCapture()) return;- posthog.capture("editor_operation", {- source: "editor",- tool: toolId,- file_count: fileCount,- });- } catch (error) {- if (DEV) console.warn("[analytics] trackEditorOperation failed", error);+export function trackPdfUploaded(files: File[]): void {+ if (!files) return;+ for (let i = 0; i < files.length; i++) {+ capture("trackPdfUploaded", "editor_pdf_uploaded", { source: "editor" });}}++export function trackEditorOperation(toolId: string, fileCount: number): void {+ capture("trackEditorOperation", "editor_operation", {+ source: "editor",+ tool: toolId,+ file_count: fileCount,+ });+}diff --git a/frontend/editor/src/core/services/fontBaseUrl.test.ts b/frontend/editor/src/core/services/fontBaseUrl.test.tsnew file mode 100644index 0000000000..2e735a5661--- /dev/null+++ b/frontend/editor/src/core/services/fontBaseUrl.test.ts@@ -0,0 +1,43 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { getApiBaseUrl } from "@app/services/apiClientConfig";+import { getFontBaseUrl } from "@app/services/fontBaseUrl";+import { BASE_PATH } from "@app/constants/app";++vi.mock("@app/services/apiClientConfig", () => ({+ getApiBaseUrl: vi.fn(() => "/"),+}));++const mockedApiBase = vi.mocked(getApiBaseUrl);++describe("getFontBaseUrl", () => {+ afterEach(() => {+ mockedApiBase.mockReturnValue("/");+ });++ it("resolves fonts under the API root as an absolute URL", () => {+ expect(getFontBaseUrl()).toBe(`${window.location.origin}/fonts`);+ });++ it("keeps a context-path prefix", () => {+ mockedApiBase.mockReturnValue("/stirling/");+ expect(getFontBaseUrl()).toBe(`${window.location.origin}/stirling/fonts`);+ });++ it("keeps an absolute API origin", () => {+ mockedApiBase.mockReturnValue("http://127.0.0.1:49152");+ expect(getFontBaseUrl()).toBe("http://127.0.0.1:49152/fonts");+ });++ it("resolves a slashless API base under the origin", () => {+ mockedApiBase.mockReturnValue("api");+ expect(getFontBaseUrl()).toBe(`${window.location.origin}/api/fonts`);+ });++ it("falls back to the app root when the API base is unset", () => {+ // import.meta.env.VITE_API_BASE_URL is undefined in Storybook and bare builds.+ mockedApiBase.mockReturnValue(undefined as unknown as string);+ expect(getFontBaseUrl()).toBe(+ `${window.location.origin}${BASE_PATH}/fonts`,+ );+ });+});diff --git a/frontend/editor/src/core/services/fontBaseUrl.ts b/frontend/editor/src/core/services/fontBaseUrl.tsnew file mode 100644index 0000000000..e2344cae98--- /dev/null+++ b/frontend/editor/src/core/services/fontBaseUrl.ts@@ -0,0 +1,36 @@+import { getApiBaseUrl } from "@app/services/apiClientConfig";+import { BASE_PATH } from "@app/constants/app";++/**+ * Base URL for the PDFium fallback fonts. The backend serves the TrueType set+ * from the JAR at /fonts/**, so the frontend bundle carries no copy of it. The+ * API base already includes any context-path prefix.+ *+ * Must stay absolute: the engine resolves it inside a blob-based worker, where+ * a root-relative path would resolve against the blob URL and fail to load.+ */+export function getFontBaseUrl(): string {+ // Env-less contexts (Storybook, bare builds) leave the API base unset; the+ // web app serves fonts from its own root then.+ const apiBase = (getApiBaseUrl() || BASE_PATH).replace(/\/$/, "");+ if (/^https?:\/\//i.test(apiBase)) {+ return `${apiBase}/fonts`;+ }+ if (typeof window === "undefined") {+ // No origin to resolve against; a root-relative path is still usable.+ return `${apiBase.startsWith("/") ? apiBase : `/${apiBase}`}/fonts`;+ }+ // Resolve against the origin so a slashless base ("api") stays a path under+ // the host instead of gluing onto the hostname ("https://hostapi").+ const resolved = new URL(apiBase, `${window.location.origin}/`);+ return `${resolved.origin}${resolved.pathname.replace(/\/$/, "")}/fonts`;+}++/**+ * Subscribe to font-base-URL changes. The web app knows its base at module+ * load, so there is nothing to watch; the desktop shadow fires when the bundled+ * backend's port is discovered and the base stops being empty.+ */+export function subscribeToFontBaseUrl(_onChange: () => void): () => void {+ return () => {};+}diff --git a/frontend/editor/src/core/services/pdfWorkerManager.ts b/frontend/editor/src/core/services/pdfWorkerManager.tsindex 871a08e949..8f8069a32b 100644--- a/frontend/editor/src/core/services/pdfWorkerManager.ts+++ b/frontend/editor/src/core/services/pdfWorkerManager.ts@@ -3,13 +3,28 @@** Prevents infinite worker creation by managing PDF.js workers globally* and ensuring proper cleanup when operations complete.+ *+ * pdf.js is a 450 KB chunk most sessions never need, so it loads on first use+ * even though the editor's startup graph reaches this module (upload+ * classification, tool previews). The type-only import keeps the runtime edge+ * dynamic.*/-import {- GlobalWorkerOptions,- getDocument,- PDFDocumentProxy,-} from "pdfjs-dist/legacy/build/pdf.mjs";+import type { PDFDocumentProxy } from "pdfjs-dist/types/src/display/api";++type PdfJsModule = typeof import("pdfjs-dist/legacy/build/pdf.mjs");++let pdfJsPromise: Promise<PdfJsModule> | null = null;++function loadPdfJs(): Promise<PdfJsModule> {+ pdfJsPromise ??= import("pdfjs-dist/legacy/build/pdf.mjs").catch((cause) => {+ // Drop the rejected promise so a later caller retries the chunk load+ // instead of inheriting a cache that can never resolve.+ pdfJsPromise = null;+ throw cause;+ });+ return pdfJsPromise;+}/** A document did not open inside the caller's `openTimeoutMs`. */export class PdfOpenTimeout extends Error {@@ -25,11 +40,7 @@ class PDFWorkerManager {private destroyingDocuments = new WeakSet<PDFDocumentProxy>();private workerCount = 0;private maxWorkers = 10; // Limit concurrent workers- private isInitialized = false;-- private constructor() {- this.initializeWorker();- }+ private workerReady: Promise<void> | null = null;static getInstance(): PDFWorkerManager {if (!PDFWorkerManager.instance) {@@ -38,18 +49,21 @@ class PDFWorkerManager {return PDFWorkerManager.instance;}- /**- * Initialize PDF.js worker once globally- */- private initializeWorker(): void {- if (!this.isInitialized) {- GlobalWorkerOptions.workerSrc = new URL(- "pdfjs-dist/legacy/build/pdf.worker.min.mjs",- import.meta.url,- ).toString();- (GlobalWorkerOptions as { docBaseUrl?: string }).docBaseUrl = undefined;- this.isInitialized = true;- }+ private ensureWorker(): Promise<void> {+ this.workerReady ??= loadPdfJs()+ .then(({ GlobalWorkerOptions }) => {+ GlobalWorkerOptions.workerSrc = new URL(+ "pdfjs-dist/legacy/build/pdf.worker.min.mjs",+ import.meta.url,+ ).toString();+ (GlobalWorkerOptions as { docBaseUrl?: string }).docBaseUrl = undefined;+ })+ .catch((cause) => {+ // Same as loadPdfJs: a failed setup must be retryable on the next open.+ this.workerReady = null;+ throw cause;+ });+ return this.workerReady;}/**@@ -88,43 +102,62 @@ class PDFWorkerManager {pdfData = data; // Pass through as-is}- const loadingTask = getDocument(- typeof pdfData === "string"- ? {- url: pdfData,- disableAutoFetch: options.disableAutoFetch ?? true,- disableStream: options.disableStream ?? true,- stopAtErrors: options.stopAtErrors ?? false,- verbosity: options.verbosity ?? 0,- // Suppress warnings about unimplemented widget types and other non-critical issues- isEvalSupported: false,- }- : {- ...pdfData,- disableAutoFetch: options.disableAutoFetch ?? true,- disableStream: options.disableStream ?? true,- stopAtErrors: options.stopAtErrors ?? false,- verbosity: options.verbosity ?? 0,- // Suppress warnings about unimplemented widget types and other non-critical issues- isEvalSupported: false,- },- );-+ // The deadline covers the first-use pdf.js import as well as the open: a cold+ // module load that stalls must not leave the caller waiting past it. When it+ // fires during the import, no loading task is created.const openTimeoutMs = options.openTimeoutMs;let timer: ReturnType<typeof setTimeout> | null = null;+ let timedOut = false;+ const deadline =+ openTimeoutMs === undefined+ ? null+ : new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ timedOut = true;+ reject(new PdfOpenTimeout(openTimeoutMs));+ }, openTimeoutMs);+ });++ let loadingTask: ReturnType<PdfJsModule["getDocument"]> | null = null;try {+ const prepare = (async () => {+ const [{ getDocument }] = await Promise.all([+ loadPdfJs(),+ this.ensureWorker(),+ ]);+ if (timedOut && openTimeoutMs !== undefined) {+ throw new PdfOpenTimeout(openTimeoutMs);+ }+ return getDocument(+ typeof pdfData === "string"+ ? {+ url: pdfData,+ disableAutoFetch: options.disableAutoFetch ?? true,+ disableStream: options.disableStream ?? true,+ stopAtErrors: options.stopAtErrors ?? false,+ verbosity: options.verbosity ?? 0,+ // Suppress warnings about unimplemented widget types and other non-critical issues+ isEvalSupported: false,+ }+ : {+ ...pdfData,+ disableAutoFetch: options.disableAutoFetch ?? true,+ disableStream: options.disableStream ?? true,+ stopAtErrors: options.stopAtErrors ?? false,+ verbosity: options.verbosity ?? 0,+ // Suppress warnings about unimplemented widget types and other non-critical issues+ isEvalSupported: false,+ },+ );+ })();+ loadingTask = await (deadline+ ? Promise.race([prepare, deadline])+ : prepare);+const opened =- openTimeoutMs === undefined+ deadline === null? loadingTask.promise- : Promise.race([- loadingTask.promise,- new Promise<never>((_, reject) => {- timer = setTimeout(- () => reject(new PdfOpenTimeout(openTimeoutMs)),- openTimeoutMs,- );- }),- ]);+ : Promise.race([loadingTask.promise, deadline]);const pdf = await opened;this.activeDocuments.add(pdf);this.workerCount++;diff --git a/frontend/editor/src/core/services/pdfiumFontFallback.test.ts b/frontend/editor/src/core/services/pdfiumFontFallback.test.tsindex b488d9fe6b..5fcb02fa69 100644--- a/frontend/editor/src/core/services/pdfiumFontFallback.test.ts+++ b/frontend/editor/src/core/services/pdfiumFontFallback.test.ts@@ -29,4 +29,27 @@ describe("pdfiumFontFallback", () => {expect(String(fontVal)).not.toContain("jsdelivr");}});++ it("maps every charset with a face and leaves the rest to the default", () => {+ const config = getLocalFontFallbackConfig();++ // A numeric enum also exposes reverse mappings, so keep the names only.+ const charsets = Object.keys(FontCharset).filter((key) =>+ Number.isNaN(Number(key)),+ ) as (keyof typeof FontCharset)[];++ expect(config.baseUrl).toBeTruthy();+ expect(config.defaultFont).toBeTruthy();++ for (const name of charsets) {+ // Noto has no symbol face, so that charset must resolve via defaultFont.+ if (name === "SYMBOL") {+ expect(config.fonts[FontCharset[name]]).toBeUndefined();+ continue;+ }+ expect(String(config.fonts[FontCharset[name]])).toMatch(+ /^NotoSans[A-Za-z-]*\.ttf$/,+ );+ }+ });});diff --git a/frontend/editor/src/core/services/pdfiumFontFallback.ts b/frontend/editor/src/core/services/pdfiumFontFallback.tsindex f14a0e36f7..dbd7c13492 100644--- a/frontend/editor/src/core/services/pdfiumFontFallback.ts+++ b/frontend/editor/src/core/services/pdfiumFontFallback.ts@@ -1,13 +1,19 @@-import { BASE_PATH } from "@app/constants/app";+import { getFontBaseUrl } from "@app/services/fontBaseUrl";import type { FontFallbackConfig } from "@embedpdf/engines";import { FontCharset } from "@embedpdf/models";+/**+ * Fonts the engine substitutes for characters missing from a document.+ *+ * Must always return the object: the EmbedPDF engine selects its jsDelivr+ * defaults when `fontFallback` is omitted, and disables fallback entirely when+ * it is `null`. Keeping the files here and the base on our own `/fonts` route+ * is what keeps that CDN out of the render path. Charsets without a face+ * (SYMBOL) resolve to `defaultFont`.+ */export function getLocalFontFallbackConfig(): FontFallbackConfig {- const origin = typeof window !== "undefined" ? window.location.origin : "";- const baseUrl = `${origin}${BASE_PATH}/fonts`;-return {- baseUrl,+ baseUrl: getFontBaseUrl(),defaultFont: "NotoSans-Regular.ttf",fonts: {[FontCharset.ANSI]: "NotoSans-Regular.ttf",diff --git a/frontend/editor/src/core/services/pdfiumService.ts b/frontend/editor/src/core/services/pdfiumService.tsindex cf41fae3fb..aee632d269 100644--- a/frontend/editor/src/core/services/pdfiumService.ts+++ b/frontend/editor/src/core/services/pdfiumService.ts@@ -12,11 +12,7 @@* `getSignatures`, `saveAsCopy`, …) wrap the `PdfEngine` interface so callers* never have to deal with raw pointers or Tasks.*/-import {- init,- type WrappedPdfiumModule,- type PdfiumModule,-} from "@embedpdf/pdfium";+import type { WrappedPdfiumModule, PdfiumModule } from "@embedpdf/pdfium";import {pdfiumWasmModulePromise,startEagerWasmCompilation,@@ -90,7 +86,13 @@ async function initPdfiumModule(): Promise<WrappedPdfiumModule> {startEagerWasmCompilation();const overrides: PdfiumModuleOverrides = { locateFile: () => wasmUrl() };- const precompiled = await pdfiumWasmModulePromise;+ // The glue is imported here, not at the top: this service is reached from+ // app-root contexts, and a static import would put the whole embedpdf chunk on+ // the initial load. It downloads alongside the WASM rather than after it.+ const [precompiled, { init }] = await Promise.all([+ pdfiumWasmModulePromise,+ import("@embedpdf/pdfium"),+ ]);let reportFailure: (error: unknown) => void = () => {};const instantiateFailed = new Promise<never>((_, reject) => {diff --git a/frontend/editor/src/core/services/serverStorageBundle.ts b/frontend/editor/src/core/services/serverStorageBundle.tsindex e132200626..1a7617e263 100644--- a/frontend/editor/src/core/services/serverStorageBundle.ts+++ b/frontend/editor/src/core/services/serverStorageBundle.ts@@ -1,4 +1,4 @@-import JSZip from "jszip";+import type JSZipClass from "jszip";import { fileStorage } from "@app/services/fileStorage";import type { FileId, ToolOperation } from "@app/types/file";@@ -32,6 +32,20 @@ function sanitizeFilename(name: string): string {return trimmed.replace(/[\\/:*?"<>|]/g, "_");}+// JSZip is ~140 KB and only needed to build or read a share bundle.+let jsZipPromise: Promise<typeof JSZipClass> | null = null;++function loadJSZip(): Promise<typeof JSZipClass> {+ jsZipPromise ??= import("jszip")+ .then((mod) => mod.default)+ .catch((cause) => {+ // Reset so a later caller can retry a failed load.+ jsZipPromise = null;+ throw cause;+ });+ return jsZipPromise;+}+export async function buildHistoryBundle(originalFileIds: FileId[] | FileId,): Promise<{@@ -55,6 +69,7 @@ export async function buildHistoryBundle(allStubs.push({ rootId, stubs });}+ const JSZip = await loadJSZip();const zip = new JSZip();const entries: ShareBundleEntry[] = [];@@ -120,6 +135,7 @@ export async function buildSharePackage(stubs: StirlingFileStub[]): Promise<{throw new Error("No files provided for sharing.");}+ const JSZip = await loadJSZip();const zip = new JSZip();const entries: ShareBundleEntry[] = [];diff --git a/frontend/editor/src/core/services/shareBundleUtils.ts b/frontend/editor/src/core/services/shareBundleUtils.tsindex a5cd301dcd..ed9f29231f 100644--- a/frontend/editor/src/core/services/shareBundleUtils.ts+++ b/frontend/editor/src/core/services/shareBundleUtils.ts@@ -1,4 +1,4 @@-import JSZip from "jszip";+import type JSZipClass from "jszip";import type { ShareBundleManifest } from "@app/services/serverStorageBundle";@@ -94,12 +94,27 @@ export function resolveShareBundleOrder(manifest: ShareBundleManifest): {return { rootOrder, sortedEntries };}+// JSZip is ~140 KB and only needed to build or read a share bundle.+let jsZipPromise: Promise<typeof JSZipClass> | null = null;++function loadJSZip(): Promise<typeof JSZipClass> {+ jsZipPromise ??= import("jszip")+ .then((mod) => mod.default)+ .catch((cause) => {+ // Reset so a later caller can retry a failed load.+ jsZipPromise = null;+ throw cause;+ });+ return jsZipPromise;+}+export async function loadShareBundleEntries(blob: Blob): Promise<{manifest: ShareBundleManifest;rootOrder: string[];sortedEntries: ShareBundleManifest["entries"];files: File[];} | null> {+ const JSZip = await loadJSZip();const zip = await JSZip.loadAsync(blob);const manifestEntry = zip.file(MANIFEST_FILENAME);if (!manifestEntry) {diff --git a/frontend/editor/src/core/services/wasmPrecompiler.ts b/frontend/editor/src/core/services/wasmPrecompiler.tsindex 085c9a952e..683591cdac 100644--- a/frontend/editor/src/core/services/wasmPrecompiler.ts+++ b/frontend/editor/src/core/services/wasmPrecompiler.ts@@ -1,16 +1,8 @@-import { BASE_PATH } from "@app/constants/app";import pdfiumWasmAssetUrl from "@embedpdf/pdfium/pdfium.wasm?url";+// Resolved against the document: the raw URL is relative in dev, and workers+// need an absolute URL too.const getWasmUrl = (): string => {- // In dev, Vite serves the statically-copied asset from the dev server root.- if (import.meta.env.DEV) {- const origin = typeof window !== "undefined" ? window.location.origin : "";- return `${origin}${BASE_PATH}/pdfium/pdfium.wasm`;- }-- // Vite has already produced a base-aware asset URL (absolute under a relative- // base, root-relative under an absolute base). Resolve it against the document- // to get a fetchable absolute URL that is also safe to pass to Web Workers.if (typeof window !== "undefined") {return new URL(pdfiumWasmAssetUrl, window.location.href).href;}@@ -37,6 +29,11 @@ export function startEagerWasmCompilation(): void {return;}+ // The JS glue that runs this WASM is a lazy chunk. Fetch it in the same idle+ // slot so the first thumbnail or form read waits for neither. A failure here+ // is left to pdfiumService, whose own import retries it and reports it.+ import("@embedpdf/pdfium").catch(() => {});+const compileWithFallback = async (): Promise<WebAssembly.Module | null> => {try {if (typeof WebAssembly.compileStreaming === "function") {diff --git a/frontend/editor/src/core/services/zipFileService.ts b/frontend/editor/src/core/services/zipFileService.tsindex 3e57237cfc..e1427afc9c 100644--- a/frontend/editor/src/core/services/zipFileService.ts+++ b/frontend/editor/src/core/services/zipFileService.ts@@ -1,4 +1,5 @@-import JSZip, { JSZipObject } from "jszip";+import type JSZipClass from "jszip";+import type { JSZipObject } from "jszip";import { StirlingFileStub, createStirlingFile } from "@app/types/fileContext";import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";import { fileStorage } from "@app/services/fileStorage";@@ -16,6 +17,20 @@ const getData = (zipEntry: JSZipObject): CompressedObject | undefined => {return (zipEntry as JSZipObject & { _data: CompressedObject })._data;};+// JSZip is ~140 KB and only needed when the user opens a zip.+let jsZipPromise: Promise<typeof JSZipClass> | null = null;++function loadJSZip(): Promise<typeof JSZipClass> {+ jsZipPromise ??= import("jszip")+ .then((mod) => mod.default)+ .catch((cause) => {+ // Reset so a later caller can retry a failed load.+ jsZipPromise = null;+ throw cause;+ });+ return jsZipPromise;+}+export interface ZipExtractionResult {success: boolean;extractedFiles: File[];@@ -85,6 +100,7 @@ export class ZipFileService {}// Load and validate ZIP contents+ const JSZip = await loadJSZip();const zip = new JSZip();const zipContents = await zip.loadAsync(file);@@ -151,6 +167,7 @@ export class ZipFileService {zipFilename: string,): Promise<{ zipFile: File; size: number }> {try {+ const JSZip = await loadJSZip();const zip = new JSZip();// Add each file to the ZIP@@ -206,6 +223,7 @@ export class ZipFileService {}// Load ZIP contents+ const JSZip = await loadJSZip();const zip = new JSZip();const zipContents = await zip.loadAsync(file);@@ -359,6 +377,7 @@ export class ZipFileService {*/async containsHtmlFiles(file: Blob | File): Promise<boolean> {try {+ const JSZip = await loadJSZip();const zip = new JSZip();const zipContents = await zip.loadAsync(file);@@ -443,6 +462,7 @@ export class ZipFileService {try {// Automation always extracts - but still need to count files for warningif (skipAutoUnzip) {+ const JSZip = await loadJSZip();const zip = new JSZip();const zipContents = await zip.loadAsync(zipBlob);const fileCount = Object.values(zipContents.files).filter(@@ -457,6 +477,7 @@ export class ZipFileService {}// Load ZIP and count files (single parse)+ const JSZip = await loadJSZip();const zip = new JSZip();const zipContents = await zip.loadAsync(zipBlob);@@ -571,6 +592,7 @@ export class ZipFileService {try {// Load ZIP contents+ const JSZip = await loadJSZip();const zip = new JSZip();const zipContents = await zip.loadAsync(file);diff --git a/frontend/editor/src/core/ui/Logo.tsx b/frontend/editor/src/core/ui/Logo.tsxindex acbd9bdd18..99ab25f8de 100644--- a/frontend/editor/src/core/ui/Logo.tsx+++ b/frontend/editor/src/core/ui/Logo.tsx@@ -75,12 +75,16 @@ export function Logo({className="sui-logo__wordmark sui-logo__wordmark--light"src={wordmarkLightUrl}alt={alt}+ width={58}+ height={21}style={{ height: textHeight }}/><imgclassName="sui-logo__wordmark sui-logo__wordmark--dark"src={wordmarkDarkUrl}alt={alt}+ width={58}+ height={21}style={{ height: textHeight }}/></>diff --git a/frontend/editor/src/core/utils/patchRequestIdleCallback.test.ts b/frontend/editor/src/core/utils/patchRequestIdleCallback.test.tsindex dcd0dc722e..aba8a0633f 100644--- a/frontend/editor/src/core/utils/patchRequestIdleCallback.test.ts+++ b/frontend/editor/src/core/utils/patchRequestIdleCallback.test.ts@@ -58,8 +58,8 @@ describe("patchRequestIdleCallback", () => {expect(task).toHaveBeenCalledTimes(1);});- // `src/index.tsx` asks for 2000ms so the pdfium WASM compile doesn't land on- // top of the app's first renders.+ // `src/proprietary/utils/scheduleIdle.ts` asks for 2000ms so the policy+ // passes yield to the app's first renders.it("does not run background work earlier than the caller allowed for", () => {delete globals.requestIdleCallback;patchRequestIdleCallback();diff --git a/frontend/editor/src/desktop/components/AccountLinkNotice.test.tsx b/frontend/editor/src/desktop/components/AccountLinkNotice.test.tsxindex fca4d9bf3b..29d879fa8f 100644--- a/frontend/editor/src/desktop/components/AccountLinkNotice.test.tsx+++ b/frontend/editor/src/desktop/components/AccountLinkNotice.test.tsx@@ -8,6 +8,10 @@ import { handleHttpError } from "@app/services/httpErrorHandler";import { clearAccountLinkBlock } from "@app/services/accountLinkBlock";import type { ConnectionConfig } from "@app/services/connectionModeService";+// The notice renders the linking modal through React.lazy; warming it here+// keeps the first assertion from racing the chunk import.+await import("@app/components/account-link/EditorLinkModal");+const {auth,alert,diff --git a/frontend/editor/src/desktop/services/billing.ts b/frontend/editor/src/desktop/services/billing.tsindex 954273b930..7b91988a2a 100644--- a/frontend/editor/src/desktop/services/billing.ts+++ b/frontend/editor/src/desktop/services/billing.ts@@ -12,7 +12,6 @@* server / tauri:// origin Stripe can't return to. We pass the app's deep-link* scheme (stirlingpdf://) so Stripe can bring the user back into the app.*/-import { supabase } from "@app/auth/supabase";import { authService } from "@app/services/authService";import type {CheckoutParams,@@ -28,6 +27,10 @@ export type {PortalSession,} from "@cloud/services/billing";+// Avoid a static import: it would pull the Supabase SDK onto the startup path+// even for users who never open a billing flow.+const loadSupabase = async () => (await import("@app/auth/supabase")).supabase;+/*** Deep-link the SaaS billing backend uses as Stripe's success/cancel/return* URL on desktop. The OS routes it back to the running app, which the deep-link@@ -55,6 +58,7 @@ export async function createCheckoutSession(params: CheckoutParams,): Promise<CheckoutSession> {const token = await requireToken();+ const supabase = await loadSupabase();const { data, error } = await supabase.functions.invoke<{client_secret?: string;@@ -98,6 +102,7 @@ export async function createPortalSession(params: PortalParams,): Promise<PortalSession> {const token = await requireToken();+ const supabase = await loadSupabase();const { data, error } = await supabase.functions.invoke<{url?: string;diff --git a/frontend/editor/src/desktop/services/fontBaseUrl.ts b/frontend/editor/src/desktop/services/fontBaseUrl.tsnew file mode 100644index 0000000000..892e46595f--- /dev/null+++ b/frontend/editor/src/desktop/services/fontBaseUrl.ts@@ -0,0 +1,28 @@+import { tauriBackendService } from "@app/services/tauriBackendService";++/**+ * Desktop shadow: the webview has no /fonts of its own, but the bundled backend+ * runs in every connection mode and serves the font set from the JAR. Empty+ * while the backend port is still unknown; the engine then falls back to+ * same-origin URLs, which fail gracefully.+ */+export function getFontBaseUrl(): string {+ const base = tauriBackendService.getBackendUrl();+ return base ? `${base.replace(/\/$/, "")}/fonts` : "";+}++/**+ * The webview learns the backend port after startup, so the base URL moves from+ * empty to a real origin. Consumers memoize the font config; this lets them+ * recompute it, but only when the resolved URL actually changes so an unrelated+ * health flap does not churn the engine.+ */+export function subscribeToFontBaseUrl(onChange: () => void): () => void {+ let previous = getFontBaseUrl();+ return tauriBackendService.subscribeToStatus(() => {+ const next = getFontBaseUrl();+ if (next === previous) return;+ previous = next;+ onChange();+ });+}diff --git a/frontend/editor/src/index.tsx b/frontend/editor/src/index.tsxindex 1d05928f60..87b789d657 100644--- a/frontend/editor/src/index.tsx+++ b/frontend/editor/src/index.tsx@@ -19,21 +19,8 @@ import "@app/i18n"; // Initialize i18nextimport { BASE_PATH } from "@app/constants/app";import { applyDevWorktreeLabel } from "@app/utils/applyDevWorktreeLabel";-import { startEagerWasmCompilation } from "@app/services/wasmPrecompiler";-applyDevWorktreeLabel();-if (typeof window !== "undefined") {- const scheduleCompilation = () =>- requestIdleCallback(() => startEagerWasmCompilation(), { timeout: 2000 });-- if (document.readyState === "complete") {- scheduleCompilation();- } else {- window.addEventListener("load", scheduleCompilation);- }-}-const container = document.getElementById("root");if (!container) {throw new Error("Root container missing in index.html");diff --git a/frontend/editor/src/proprietary/auth/session.ts b/frontend/editor/src/proprietary/auth/session.tsindex 0cc4894eb9..0d40e50879 100644--- a/frontend/editor/src/proprietary/auth/session.ts+++ b/frontend/editor/src/proprietary/auth/session.ts@@ -1,6 +1,8 @@-import { getPortalSaasToken } from "@app/portal/auth/portalSaasSession";-/** Checkout uses the account session installed by the validated owner connection flow. */export async function getAccessToken(): Promise<string | null> {+ // Dynamic import: the portal session module registers Supabase auth listeners+ // and would otherwise sit on the startup path of every build.+ const { getPortalSaasToken } =+ await import("@app/portal/auth/portalSaasSession");return getPortalSaasToken();}diff --git a/frontend/editor/src/proprietary/auth/spring/springAuthClient.ts b/frontend/editor/src/proprietary/auth/spring/springAuthClient.tsindex 227e412820..a2342a67e3 100644--- a/frontend/editor/src/proprietary/auth/spring/springAuthClient.ts+++ b/frontend/editor/src/proprietary/auth/spring/springAuthClient.ts@@ -19,7 +19,6 @@ import { JWT_STORAGE_KEY } from "@app/auth/httpClient";import { type OAuthProvider } from "@app/auth/spring/oauthTypes";import { resetOAuthState } from "@app/auth/spring/oauthStorage";import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";-import { clearSupabaseSession } from "@app/auth/supabase/supabaseClient";import type {AuthUser as User,AuthSession as Session,@@ -508,7 +507,16 @@ class SpringAuthClient {*/async signOut(): Promise<{ error: AuthError | null }> {try {- clearSupabaseSession();+ // Avoid a static import: it would put the Supabase SDK on the startup path+ // even for installs that never use it. The inner catch keeps a failed load+ // from skipping the local cleanup below.+ try {+ const { clearSupabaseSession } =+ await import("@app/auth/supabase/supabaseClient");+ clearSupabaseSession();+ } catch {+ // Nothing loaded means nothing to clear.+ }localStorage.removeItem("stirling.portalSaasOwner");sessionStorage.removeItem("stirling.portalConnect");Array.from({ length: localStorage.length }, (_, i) => localStorage.key(i))diff --git a/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsx b/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsxindex 355f06c948..bc8e2508eb 100644--- a/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsx+++ b/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsx@@ -18,6 +18,10 @@ import {useAccountLinkBlock,} from "@app/services/accountLinkBlock";+// The notice renders the linking modal through React.lazy; warming it here+// keeps the first assertion from racing the chunk import.+await import("@app/components/account-link/EditorLinkModal");+const { alert, begin, auth, get } = vi.hoisted(() => ({alert: vi.fn(),begin: vi.fn(),@@ -101,7 +105,9 @@ describe("editor shared account-link modal", () => {mount("/editor");await act(async () => reportFreeTierExhausted());expect(- screen.getByRole("dialog", { name: "Keep your workflows running" }),+ await screen.findByRole("dialog", {+ name: "Keep your workflows running",+ }),).toBeTruthy();expect(screen.getByText("Add more users with a paid Team plan"),@@ -122,6 +128,7 @@ describe("editor shared account-link modal", () => {reportFreeTierExhausted();reportFreeTierExhausted();});+ await screen.findByRole("dialog");expect(screen.getAllByRole("dialog")).toHaveLength(1);expect(alert).not.toHaveBeenCalled();});@@ -138,7 +145,7 @@ describe("editor shared account-link modal", () => {}),);expect(screen.queryByText(/report\.pdf/)).toBeNull();- fireEvent.click(screen.getByText("Active pipelines"));+ fireEvent.click(await screen.findByText("Active pipelines"));await screen.findByRole("button", { name: "Open pipeline settings" });fireEvent.click(screen.getByRole("button", { name: "Open pipeline settings" }),@@ -161,7 +168,9 @@ describe("editor shared account-link modal", () => {}),);expect(- screen.getByText(/Pipeline “Quarterly rotation” stopped after upload/),+ await screen.findByText(+ /Pipeline “Quarterly rotation” stopped after upload/,+ ),).toBeTruthy();expect(screen.getByRole("dialog", { name: "Ask your server administrator" }),@@ -173,7 +182,7 @@ describe("editor shared account-link modal", () => {it("does not replace a dismissed modal with a toast or reopen it on subsequent failures", async () => {const view = mount("/editor");await act(async () => reportFreeTierExhausted());- fireEvent.click(screen.getByRole("button", { name: "Not now" }));+ fireEvent.click(await screen.findByRole("button", { name: "Not now" }));await act(async () => {reportFreeTierExhausted();reportFreeTierExhausted();@@ -188,7 +197,9 @@ describe("editor shared account-link modal", () => {mount("/editor");await act(async () => reportFreeTierExhausted());expect(- screen.getByRole("dialog", { name: "Ask your server administrator" }),+ await screen.findByRole("dialog", {+ name: "Ask your server administrator",+ }),).toBeTruthy();expect(screen.getByRole("button", { name: "Copy message for administrator" }),diff --git a/frontend/editor/src/proprietary/components/AccountLinkNotice.tsx b/frontend/editor/src/proprietary/components/AccountLinkNotice.tsxindex a357bbeabb..1b7c647761 100644--- a/frontend/editor/src/proprietary/components/AccountLinkNotice.tsx+++ b/frontend/editor/src/proprietary/components/AccountLinkNotice.tsx@@ -1,19 +1,58 @@-import { useEffect, useState } from "react";+import {+ Component,+ lazy,+ Suspense,+ useEffect,+ useState,+ type ReactNode,+} from "react";+import { useTranslation } from "react-i18next";+import { Stack, Text } from "@mantine/core";import { useLocation } from "react-router-dom";import { useQuery } from "@tanstack/react-query";import { useAuth } from "@app/auth";import apiClient from "@app/services/apiClient";+import { Button } from "@app/ui/Button";import { PORTAL_BASENAME } from "@app/routes/portalBasename";-import { EditorLinkModal } from "@app/components/account-link/EditorLinkModal";import { FreeTierBalanceSummary } from "@app/components/account-link/FreeTierBalanceSummary";import type { FreeTierBalance } from "@app/components/account-link/FreeTierBalanceSummary";-import {acknowledgeAccountLinkPrompt,clearBlockIfAllowanceRemains,useAccountLinkBlock,} from "@app/services/accountLinkBlock";+// Lazy: the linking UI drags in the account-link context tree and the Supabase+// SDK, neither of which the notice needs until a prompt actually opens.+const loadEditorLinkModal = () =>+ import("@app/components/account-link/EditorLinkModal").then((module) => ({+ default: module.EditorLinkModal,+ }));++/**+ * Keeps a failed modal import local. The app-level boundary would otherwise+ * remount everything with the prompt already acknowledged, stranding the user+ * with no way back to linking in this tab.+ */+class LinkModalBoundary extends Component<+ { children: ReactNode; onError: () => void },+ { failed: boolean }+> {+ state = { failed: false };++ static getDerivedStateFromError() {+ return { failed: true };+ }++ componentDidCatch() {+ this.props.onError();+ }++ render() {+ return this.state.failed ? null : this.props.children;+ }+}+interface Props {/** Hosts without a Processor route open the connected server's billing page externally. */onShowOptions?: () => void;@@ -28,10 +67,20 @@ export function AccountLinkNotice({onManagePipeline,balance,}: Props = {}) {+ const { t } = useTranslation();const { isAdmin, loading } = useAuth();const { pathname } = useLocation();const { exhausted, promptPending, context } = useAccountLinkBlock();const [open, setOpen] = useState(false);+ // Held here, not in a rendered child: a component that suspends on its first+ // render loses its state, so a lazy built inside it would be recreated on+ // every retry and suspend forever. React also caches a lazy's rejected+ // import, so a retry must swap in a fresh one.+ const [EditorLinkModal, setEditorLinkModal] = useState(() =>+ lazy(loadEditorLinkModal),+ );+ const [linkAttempt, setLinkAttempt] = useState(0);+ const [linkFailed, setLinkFailed] = useState(false);const hasLinkDialog =!onShowOptions &&(pathname === PORTAL_BASENAME ||@@ -70,20 +119,52 @@ export function AccountLinkNotice({}, [hasLinkDialog, loading, promptPending]);if (!open || !exhausted || hasLinkDialog) return null;++ if (linkFailed) {+ return (+ <Stack align="center" gap="sm" p="md">+ <Text size="sm" c="dimmed">+ {t(+ "portal.accountLink.notice.loadFailed",+ "The account linking dialog could not be loaded.",+ )}+ </Text>+ <Button+ variant="secondary"+ onClick={() => {+ setEditorLinkModal(lazy(loadEditorLinkModal));+ setLinkFailed(false);+ setLinkAttempt((n) => n + 1);+ }}+ >+ {t("errorBoundary.tryAgain", "Try Again")}+ </Button>+ </Stack>+ );+ }+return (- <EditorLinkModal- open- failureContext={context}- onClose={() => setOpen(false)}- onStart={onShowOptions}- onManagePipeline={onManagePipeline}- summary={- <FreeTierBalanceSummary- balance={- onShowOptions ? balance : ledger.isSuccess ? ledger.data : undefined+ <LinkModalBoundary key={linkAttempt} onError={() => setLinkFailed(true)}>+ <Suspense fallback={null}>+ <EditorLinkModal+ open+ failureContext={context}+ onClose={() => setOpen(false)}+ onStart={onShowOptions}+ onManagePipeline={onManagePipeline}+ summary={+ <FreeTierBalanceSummary+ balance={+ onShowOptions+ ? balance+ : ledger.isSuccess+ ? ledger.data+ : undefined+ }+ />}/>- }- />+ </Suspense>+ </LinkModalBoundary>);}diff --git a/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsx b/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsxindex f1c6ffed5f..456d3788d1 100644--- a/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsx+++ b/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsx@@ -82,6 +82,7 @@ it("opens on the first click using asynchronously fetched plans", async () => {);fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));+ // The click loads the Supabase client before fetching plans.await waitFor(() => expect(mocks.getPlans).toHaveBeenCalledTimes(1));resolvePlans({ plans: [{ id: "server-monthly" }] });expect(await screen.findByRole("dialog")).toBeInTheDocument();diff --git a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsxindex ce0362dedb..f69605b83c 100644--- a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx+++ b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx@@ -31,7 +31,6 @@ import {pollTeamCheckout,} from "@app/utils/licenseCheckoutUtils";import { useLicense } from "@app/contexts/LicenseContext";-import { isSupabaseConfigured } from "@app/services/supabaseClient";import { getPreferredCurrency } from "@app/utils/currencyDetection";import {usePlanFeatures,@@ -352,7 +351,10 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({try {setIsLoading(true);- // Check if Supabase is configured+ // Avoid a static import: it would pull the Supabase SDK onto the startup+ // path of every build, including installs that never reach checkout.+ const { isSupabaseConfigured } =+ await import("@app/services/supabaseClient");if (!isSupabaseConfigured) {throw new Error("Checkout is not available. Supabase is not configured.",diff --git a/frontend/editor/src/proprietary/services/licenseService.ts b/frontend/editor/src/proprietary/services/licenseService.tsindex fc1aaeee9b..228d37baa6 100644--- a/frontend/editor/src/proprietary/services/licenseService.ts+++ b/frontend/editor/src/proprietary/services/licenseService.ts@@ -1,12 +1,15 @@import apiClient from "@app/services/apiClient";import { stripeAmountToMajor } from "@app/utils/stripeCurrency";-import { supabase, isSupabaseConfigured } from "@app/services/supabaseClient";import type {PlanFeaturesMap,PlanHighlightsMap,} from "@app/constants/planConstants";import type { LicenseInfo, PlanFeature } from "@app/types/license";+// Avoid a static import: it would pull the Supabase SDK onto the startup path of+// every build, including installs that never reach billing.+const loadSupabaseClient = () => import("@app/services/supabaseClient");+export interface PlanTier {id: string;name: string;@@ -103,7 +106,7 @@ const licenseService = {tier?: "server" | "enterprise",): Promise<PlansResponse> {try {- // Check if Supabase is configured+ const { supabase, isSupabaseConfigured } = await loadSupabaseClient();if (!isSupabaseConfigured || !supabase) {throw new Error("Supabase is not configured. Please use static plans instead.",@@ -338,7 +341,7 @@ const licenseService = {returnUrl: string,licenseKey: string,): Promise<BillingPortalResponse> {- // Check if Supabase is configured+ const { supabase, isSupabaseConfigured } = await loadSupabaseClient();if (!isSupabaseConfigured || !supabase) {throw new Error("Supabase is not configured. Billing portal is not available.",@@ -381,7 +384,7 @@ const licenseService = {* Check if license key is ready for the given installation ID*/async checkLicenseKey(installationId: string): Promise<LicenseKeyResponse> {- // Check if Supabase is configured+ const { supabase, isSupabaseConfigured } = await loadSupabaseClient();if (!isSupabaseConfigured || !supabase) {throw new Error("Supabase is not configured. License key lookup is not available.",@@ -479,7 +482,7 @@ const licenseService = {newSeatCount: number,licenseKey: string,): Promise<string> {- // Check if Supabase is configured+ const { supabase, isSupabaseConfigured } = await loadSupabaseClient();if (!isSupabaseConfigured || !supabase) {throw new Error("Supabase is not configured. Seat updates are not available.",diff --git a/frontend/editor/src/proprietary/services/serverPlanCheckout.ts b/frontend/editor/src/proprietary/services/serverPlanCheckout.tsindex 623d5979b1..121821591e 100644--- a/frontend/editor/src/proprietary/services/serverPlanCheckout.ts+++ b/frontend/editor/src/proprietary/services/serverPlanCheckout.ts@@ -1,7 +1,10 @@/** Account-owned Team checkout and the separate installed Enterprise licence checkout. */-import { supabase, isSupabaseConfigured } from "@app/services/supabaseClient";import { getAccessToken } from "@app/auth/session";+// Avoid a static import: it would pull the Supabase SDK onto the startup path of+// every build, including installs that never reach checkout.+const loadSupabaseClient = () => import("@app/services/supabaseClient");+/*** A Team-plan checkout, sized in user blocks rather than seats.*@@ -47,6 +50,7 @@ interface CheckoutResponse {export async function createServerPlanCheckoutSession(request: ServerPlanCheckoutRequest,): Promise<ServerPlanCheckoutSession> {+ const { supabase, isSupabaseConfigured } = await loadSupabaseClient();if (!isSupabaseConfigured || !supabase) {throw new Error("Supabase is not configured. Checkout is not available.");}@@ -122,6 +126,7 @@ export async function teamSubscriptionChange(pending: PendingTeamChange | null;unsupportedSchedule?: boolean;}> {+ const { supabase } = await loadSupabaseClient();if (!supabase) throw new Error("Checkout is not configured");const token = await getAccessToken();if (!token) throw new Error("Sign in to manage your Team plan");@@ -141,6 +146,7 @@ export async function verifyTeamCheckout(sessionId: string,quantity: number,): Promise<number | PendingTeamChange | null> {+ const { supabase } = await loadSupabaseClient();if (!supabase) throw new Error("Checkout is not configured");const token = await getAccessToken();if (!token) throw new Error("Sign in to verify the Team purchase");diff --git a/frontend/editor/vite.config.ts b/frontend/editor/vite.config.tsindex 1e67a42cf4..e2a6c9e56d 100644--- a/frontend/editor/vite.config.ts+++ b/frontend/editor/vite.config.ts@@ -1,12 +1,14 @@import react from "@vitejs/plugin-react-swc";import { compression, defineAlgorithm } from "vite-plugin-compression2";+import { randomUUID } from "node:crypto";import fs from "node:fs/promises";import path, { resolve } from "node:path";import { constants, brotliCompress, gzip } from "node:zlib";import { fileURLToPath } from "node:url";import { promisify } from "node:util";import { defineConfig, loadEnv } from "vite";-import type { Connect, PluginOption } from "vite";+import type { Connect, PluginOption, Rollup } from "vite";+import type { PreRenderedAsset } from "rollup";import tsconfigPaths from "vite-tsconfig-paths";// oxlint-disable-next-line no-restricted-imports -- config runs in node, before the aliases existimport { iconSvgr } from "./scripts/icons/svgrOptions.mts";@@ -16,62 +18,275 @@ const gzipPromise = promisify(gzip);const brotliPromise = promisify(brotliCompress);const __dirname = path.dirname(fileURLToPath(import.meta.url));+// UV_THREADPOOL_SIZE is set by the build entrypoints (the Taskfiles and the+// frontend Dockerfile): loading this config already touches the pool, so it+// cannot be set here.++// One list so the plugin's regex and the walk cannot drift.+const COMPRESSION_EXCLUDED_EXTENSIONS = [+ ".gz",+ ".br",+ ".png",+ ".jpg",+ ".jpeg",+ ".gif",+ ".webp",+ ".avif",+ ".ico",+ ".woff",+ ".woff2",+];+const COMPRESSION_EXCLUDE_REGEX = new RegExp(+ `\\.(${COMPRESSION_EXCLUDED_EXTENSIONS.map((e) => e.slice(1)).join("|")})$`,+);+const EXCLUDED_EXTENSION_SET = new Set(COMPRESSION_EXCLUDED_EXTENSIONS);++// Cloudflare's extension-based cache list omits .mjs, so pdf.js's hashed worker+// assets would bypass its edge cache. Renaming at emission also lets Rollup+// rewrite the `new URL(..., import.meta.url)` references; worker sub-builds need+// the same option because they do not inherit the main build's output options.+const mjsToJsAssetFileNames = (assetInfo: PreRenderedAsset) =>+ assetInfo.names.some((name) => name.endsWith(".mjs"))+ ? "assets/[name]-[hash].js"+ : "assets/[name]-[hash][extname]";++// A variant only earns its place when it is meaningfully smaller than the source+// it shadows; the encoders happily emit a sidecar larger than a small or already+// compressed file. The bundler pass drops non-shrinking variants too+// (skipIfLargerOrEqual) and this walk treats its output as fresh, so the two+// passes agree in practice.+const MIN_COMPRESSION_RATIO = 0.98;++/** True when `sibling` exists and is at least as new as the source. */+async function isFresh(+ sibling: string,+ sourceMtimeMs: number,+): Promise<boolean> {+ try {+ return (await fs.stat(sibling)).mtimeMs >= sourceMtimeMs;+ } catch {+ return false;+ }+}++/** Writes through a same-directory temp file so a reader never sees a partial sidecar. */+async function writeVariant(target: string, bytes: Uint8Array): Promise<void> {+ const temp = `${target}.${process.pid}.${randomUUID()}.tmp`;+ await fs.writeFile(temp, bytes);+ await fs.rename(temp, target);+}++async function writeVariantIfSmaller(+ target: string,+ encoded: Uint8Array,+ sourceLength: number,+): Promise<void> {+ if (encoded.length < sourceLength * MIN_COMPRESSION_RATIO) {+ await writeVariant(target, encoded);+ } else {+ // Never leave a variant that shadows the source without a real saving.+ await fs.rm(target, { force: true });+ }+}++/** Compresses one file under `distDir`; paths outside it are ignored. */+async function compressFile(file: string, distDir: string): Promise<void> {+ const resolved = path.resolve(file);+ if (!resolved.startsWith(`${path.resolve(distDir)}${path.sep}`)) return;++ const ext = path.extname(resolved).toLowerCase();+ if (EXCLUDED_EXTENSION_SET.has(ext)) return;++ const gzPath = `${resolved}.gz`;+ const brPath = `${resolved}.br`;++ // The bundler pass wrote some siblings; the walk runs over an existing dist,+ // so a stale one has to be replaced rather than trusted. Each encoding is+ // checked independently: a fresh .br next to a stale .gz is not a pair.+ const source = await fs.stat(resolved);+ const [gzFresh, brFresh] = await Promise.all([+ isFresh(gzPath, source.mtimeMs),+ isFresh(brPath, source.mtimeMs),+ ]);+ if (gzFresh && brFresh) return;++ // A source that shrank below the threshold must not keep serving the variants+ // left over from when it was larger.+ if (source.size < 1024) {+ await Promise.all([+ fs.rm(gzPath, { force: true }),+ fs.rm(brPath, { force: true }),+ ]);+ return;+ }++ const content = await fs.readFile(resolved);+ const [gzipped, brotlied] = await Promise.all([+ gzipPromise(content, { level: 9 }),+ brotliPromise(content, {+ params: {+ [constants.BROTLI_PARAM_QUALITY]: 11,+ },+ }),+ ]);+ await Promise.all([+ writeVariantIfSmaller(gzPath, gzipped, content.length),+ writeVariantIfSmaller(brPath, brotlied, content.length),+ ]);+}++// Batching bounds the zlib queue: 16 files with both encoders in flight is up+// to 32 jobs against the 16-thread libuv pool set by the build entrypoints.+const COMPRESSION_BATCH_FILES = 16;++async function compressFiles(files: string[], distDir: string): Promise<void> {+ for (let i = 0; i < files.length; i += COMPRESSION_BATCH_FILES) {+ await Promise.all(+ files+ .slice(i, i + COMPRESSION_BATCH_FILES)+ .map((f) => compressFile(f, distDir)),+ );+ }+}++type ManualChunkMeta = Parameters<Rollup.GetManualChunk>[1];++const startupModulesByOutput = new WeakMap<ManualChunkMeta, Set<string>>();++/**+ * The modules the entry imports statically: these load before first render, so+ * a chunk every page loads should hold only them. Memoized per output because+ * Rollup hands manualChunks the module graph once per output.+ */+function startupModules(meta: ManualChunkMeta): Set<string> {+ let modules = startupModulesByOutput.get(meta);+ if (modules) return modules;+ modules = new Set();+ const queue = [...meta.getModuleIds()].filter(+ (id) => meta.getModuleInfo(id)?.isEntry,+ );+ for (const id of queue) {+ if (modules.has(id)) continue;+ modules.add(id);+ queue.push(...(meta.getModuleInfo(id)?.importedIds ?? []));+ }+ startupModulesByOutput.set(meta, modules);+ return modules;+}++/**+ * The npm package a normalized module id belongs to, or null for app code. Ids+ * are absolute paths, often through a pnpm store, so the package is the segment+ * after the last node_modules. Matching on that segment, rather than a raw path+ * substring, keeps a directory that merely looks like a package from steering+ * the split.+ */+function packageNameOf(id: string): string | null {+ const marker = "node_modules/";+ const index = id.lastIndexOf(marker);+ // Reject a match inside a longer directory name such as "my-node_modules".+ if (index === -1 || (index > 0 && id[index - 1] !== "/")) return null;+ const [first, second] = id.slice(index + marker.length).split("/");+ if (!first) return null;+ return first.startsWith("@") ? `${first}/${second ?? ""}` : first;+}++function inScope(pkg: string, scope: string): boolean {+ return pkg === scope || pkg.startsWith(`${scope}/`);+}++// react-markdown and its remark/micromark/mdast/hast closure is heavy and only+// needed when a disclaimer, document or chat message renders. Matching on the+// package name keeps an app file named like one of these out of the chunk.+const MARKDOWN_PACKAGE_PREFIXES = [+ "remark-",+ "rehype-",+ "micromark",+ "mdast-",+ "hast-",+ "unist-",+ "estree-util-",+ "style-to-",+ "character-entities",+ "vfile",+] as const;+const MARKDOWN_PACKAGES = new Set([+ "react-markdown",+ "unified",+ "parse-entities",+ "decode-named-character-reference",+ "markdown-table",+ "devlop",+ "longest-streak",+ "ccount",+ "zwitch",+ "trough",+ "bail",+ "is-plain-obj",+ "property-information",+ "space-separated-tokens",+ "comma-separated-tokens",+ "trim-lines",+ "html-url-attributes",+ "@ungap/structured-clone",+]);++function isMarkdownPackage(pkg: string): boolean {+ return (+ MARKDOWN_PACKAGES.has(pkg) ||+ MARKDOWN_PACKAGE_PREFIXES.some((prefix) => pkg.startsWith(prefix))+ );+}+function compressStaticCopyPlugin(): PluginOption {return {name: "compress-static-copy",apply: "build" as const,async closeBundle() {const distDir = path.resolve(__dirname, "dist");- const targets = ["pdfium", "vendor", "pdfjs"];-- const excludedExtensions = [- ".gz",- ".br",- ".png",- ".jpg",- ".jpeg",- ".gif",- ".webp",- ".woff",- ".woff2",- ];-- async function walkAndCompress(dirOrFile: string) {- let stat;++ // The plugin's include list skips .wasm and viteStaticCopy output never+ // reaches it, so the walk has to cover the rest of dist. HTML, sitemap.xml+ // and robots.txt stay with the prerender hook, which rewrites them in a+ // concurrent closeBundle.+ const files: string[] = [];+ const walk = async (dir: string) => {+ let entries;try {- stat = await fs.stat(dirOrFile);+ entries = await fs.readdir(dir, { withFileTypes: true });} catch {return;}-- if (stat.isFile()) {- const ext = path.extname(dirOrFile).toLowerCase();- if (stat.size >= 1024 && !excludedExtensions.includes(ext)) {- const content = await fs.readFile(dirOrFile);-- // Gzip (level 9)- const gzipped = await gzipPromise(content, { level: 9 });- await fs.writeFile(`${dirOrFile}.gz`, gzipped);-- // Brotli (quality 11)- const brotlied = await brotliPromise(content, {- params: {- [constants.BROTLI_PARAM_QUALITY]: 11,- },- });- await fs.writeFile(`${dirOrFile}.br`, brotlied);- }- } else if (stat.isDirectory()) {- const files = await fs.readdir(dirOrFile);- for (const file of files) {- await walkAndCompress(path.join(dirOrFile, file));- }+ for (const entry of entries) {+ const p = path.join(dir, entry.name);+ if (entry.isDirectory()) await walk(p);+ else if (+ !entry.name.endsWith(".html") &&+ entry.name !== "sitemap.xml" &&+ entry.name !== "robots.txt"+ )+ files.push(p);}- }+ };- for (const target of targets) {- await walkAndCompress(path.join(distDir, target));- }+ await walk(distDir);++ await compressFiles(files, distDir);++ // The TTFs are only ever requested through the backend, which serves the+ // .br/.gz siblings and falls back to its own classpath copy of the raw+ // file. Shipping the raw set in dist would duplicate ~100 MB for nothing.+ // NotoSans-Regular.ttf stays: the text editor's Unicode fallback fetches+ // it directly, and static hosts have no classpath to fall back to.+ const fontsDir = path.join(distDir, "fonts");+ const fontEntries = await fs.readdir(fontsDir).catch(() => []);+ await Promise.all(+ fontEntries+ .filter(+ (name) => name.endsWith(".ttf") && name !== "NotoSans-Regular.ttf",+ )+ .map((name) => fs.rm(path.join(fontsDir, name), { force: true })),+ );},};}@@ -91,7 +306,11 @@ function compressStaticCopyPlugin(): PluginOption {// origin serves the page (correct for self-hosted Docker). Indexing signals// (canonical, JSON-LD, sitemap) need VITE_OG_BASE_URL specifically - see below.// Logic lives in scripts/og-prerender.mjs so it can be unit-tested without a full build.-function prerenderOgPlugin(isSaas: boolean): PluginOption {+function prerenderOgPlugin(options: {+ isSaas: boolean;+ precompress: boolean;+}): PluginOption {+ const { isSaas, precompress } = options;// SaaS (stirling.com) prerenders the marketing cards from a dedicated// manifest; every other flavour uses the tool-registry manifest.const manifestFile = isSaas@@ -153,12 +372,26 @@ function prerenderOgPlugin(isSaas: boolean): PluginOption {: " (root-relative URLs, no landing body)"),);+ // prerenderOg rewrote index.html, so the bundler's siblings for the+ // original shell are stale.+ await Promise.all(+ ["index.html.br", "index.html.gz"].map((name) =>+ fs.rm(path.join(distDir, name), { force: true }),+ ),+ );++ const lateFiles: string[] = [path.join(distDir, "index.html")];+// Sitemaps are an indexing instruction, so they need the canonical origin,// not just any absolute one. Self-hosted and preview builds skip it.const sitemap = buildSitemap(manifest, { canonicalBase });if (sitemap) {- await fs.writeFile(path.join(distDir, "sitemap.xml"), sitemap);+ const sitemapPath = path.join(distDir, "sitemap.xml");+ await fs.writeFile(sitemapPath, sitemap);+ lateFiles.push(sitemapPath);// Point robots.txt at the sitemap (best-effort; robots.txt may be absent).+ // Static hosts only: packaged builds exclude dist/robots.txt and serve it+ // from RobotsController, gated on system.googlevisibility.const robotsPath = path.join(distDir, "robots.txt");try {let robots = await fs.readFile(robotsPath, "utf8");@@ -173,6 +406,38 @@ function prerenderOgPlugin(isSaas: boolean): PluginOption {}console.log(`[prerender-og] wrote sitemap.xml (base=${canonicalBase})`);}+ // Rewritten above when the sitemap points at it.+ const robotsPath = path.join(distDir, "robots.txt");+ try {+ await fs.access(robotsPath);+ lateFiles.push(robotsPath);+ } catch {+ // absent+ }+ // These are written here, and closeBundle hooks run concurrently, so the+ // walk in the other plugin cannot compress them reliably.+ const walkHtml = async (dir: string) => {+ let entries;+ try {+ entries = await fs.readdir(dir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ const p = path.join(dir, entry.name);+ if (entry.isDirectory()) await walkHtml(p);+ else if (entry.name.endsWith(".html") && entry.name !== "index.html")+ lateFiles.push(p);+ }+ };+ await walkHtml(distDir);+ // The HTML, sitemap and robots.txt written above skip the other plugin's+ // walk, so they are compressed here (desktop is embedded and compressed by+ // Tauri). The siblings only serve static hosts: Jetty gzips the Spring+ // responses in memory, so it never reads them.+ if (precompress) {+ await compressFiles(lateFiles, distDir);+ }},};}@@ -282,7 +547,9 @@ export default defineConfig(async ({ mode, command }) => {};// Shared between `vite` (dev) and `vite preview` (production-build serve, used- // in CI/E2E) so the live test suite still resolves /api → :8080.+ // in CI/E2E) so the live test suite still resolves /api → :8080. /fonts is+ // deliberately absent: the stubbed suite runs backend-free and proxying font+ // requests would turn a static 404 into a connection error.const backendProxyConfig =effectiveMode === "desktop"? undefined@@ -321,25 +588,33 @@ export default defineConfig(async ({ mode, command }) => {tsconfigPaths({projects: [tsconfigProject],}),- compression({- threshold: 1024,- exclude: [/\.(png|jpg|jpeg|gif|webp|woff|woff2)$/],- algorithms: [- defineAlgorithm("gzip", { level: 9 }),- defineAlgorithm("brotliCompress", {- params: {- [constants.BROTLI_PARAM_QUALITY]: 11,- },- }),- ],- }),- // Set ANALYZE=true to emit dist/stats.html (treemap) alongside the- // build; rollup-plugin-visualizer is ESM-only so we import dynamically.+ // Desktop/mobile output is embedded in the Tauri binary, which brotli-+ // compresses every asset itself and never negotiates encodings, so the+ // .br/.gz siblings would only add their full size (tens of MB) to the+ // bundle. Web flavours keep both encodings for the HTTP server.+ ...(effectiveMode === "desktop"+ ? []+ : [+ compression({+ threshold: 1024,+ exclude: [COMPRESSION_EXCLUDE_REGEX],+ algorithms: [+ defineAlgorithm("gzip", { level: 9 }),+ defineAlgorithm("brotliCompress", {+ params: {+ [constants.BROTLI_PARAM_QUALITY]: 11,+ },+ }),+ ],+ }),+ ]),+ // ANALYZE=true emits dist/stats.json; the visualizer is ESM-only, hence+ // the dynamic import....(process.env.ANALYZE === "true"? [(await import("rollup-plugin-visualizer")).visualizer({- filename: "dist/stats.html",- template: "treemap",+ filename: "dist/stats.json",+ template: "raw-data",gzipSize: true,brotliSize: true,emitFile: false,@@ -348,12 +623,6 @@ export default defineConfig(async ({ mode, command }) => {: []),viteStaticCopy({targets: [- {- // node_modules is hoisted to the workspace root (frontend/), so- // these paths walk up one level from editor/.- src: "../node_modules/@embedpdf/pdfium/dist/pdfium.wasm",- dest: "pdfium",- },{// Copy jscanify vendor files to distsrc: "public/vendor/jscanify/*",@@ -379,20 +648,37 @@ export default defineConfig(async ({ mode, command }) => {src: "src/core/assets/brand/modern-logo/*",dest: "modern-logo",},- {- // Fallback TrueType fonts for PDFium (Noto Sans, CJK, Arabic, etc.)- src: "../../app/core/src/main/resources/static/fonts/*.ttf",- dest: "fonts",- },+ // The compression pass writes the .br/.gz siblings the backend JAR+ // serves from classpath:/static/fonts/; desktop is embedded and gets+ // them from the bundled backend instead.+ ...(effectiveMode === "desktop"+ ? []+ : [+ {+ src: "../../app/core/src/main/resources/static/fonts/*.ttf",+ dest: "fonts",+ },+ ]),],}),- compressStaticCopyPlugin(),- prerenderOgPlugin(effectiveMode === "saas"),+ ...(effectiveMode === "desktop" ? [] : [compressStaticCopyPlugin()]),+ prerenderOgPlugin({+ isSaas: effectiveMode === "saas",+ precompress: effectiveMode !== "desktop",+ }),],// Worker bundles are a separate Rollup pass and do NOT inherit `plugins`,// so without this `@app/*` resolves in the app and fails in a worker.worker: {plugins: () => [tsconfigPaths({ projects: [tsconfigProject] })],+ // Worker sub-builds do not inherit the main build's output options, so+ // without this a worker asset referenced from inside a worker is emitted+ // as .mjs again (see mjsToJsAssetFileNames above).+ rollupOptions: {+ output: {+ assetFileNames: mjsToJsAssetFileNames,+ },+ },},server: {host: true,@@ -422,30 +708,80 @@ export default defineConfig(async ({ mode, command }) => {resolveDependencies: (filename, deps, { hostType }) =>hostType === "html" ? [filename, ...deps] : deps,},+ // The real precompression runs below, so Vite's gzip measurement is+ // wasted CI time.+ reportCompressedSize: false,+ // Minifies better than esbuild for this esnext target.+ cssMinify: "lightningcss" as const,rollupOptions: {output: {- manualChunks(id: string) {- if (id.includes("node_modules")) {- if (id.includes("pdfjs-dist")) return "vendor-pdfjs";- if (id.includes("@embedpdf")) return "vendor-embedpdf";- if (id.includes("react") || id.includes("@mantine")) {- return "vendor-ui";- }- if (id.includes("@supabase")) return "vendor-supabase";- if (id.includes("posthog-js") || id.includes("@posthog"))- return "vendor-posthog";- if (id.includes("@cantoo/pdf-lib") || id.includes("pdf-lib"))- return "vendor-pdflib";- if (- id.includes("recharts") ||- id.includes("d3") ||- id.includes("decimal.js")- )- return "vendor-charts";- if (id.includes("jszip") || id.includes("pako"))- return "vendor-zip";- if (id.includes("i18next")) return "vendor-i18n";+ assetFileNames: mjsToJsAssetFileNames,+ manualChunks(id: string, meta: ManualChunkMeta) {+ if (id.includes("material-symbols-icons.json"))+ return "vendor-iconset";+ // An asset URL import compiles to a single string. Filed by package+ // name it joins that package's vendor chunk, and its importer then+ // loads the whole chunk: the startup WASM warm-up imports pdfium's+ // URL, which would pull all of embedpdf into the initial load.+ if (id.includes("?url")) return undefined;+ // Left to Rollup, this lands in the first dynamic-importing vendor+ // chunk and the entry then statically imports that whole chunk.+ if (id.includes("vite/preload-helper")) return "vendor-preload";++ const pkg = packageNameOf(id);+ if (!pkg) return undefined;++ if (pkg === "pdfjs-dist") return "vendor-pdfjs";+ // Only the lazily opened viewer needs the engine and the plugins;+ // the startup graph needs just the pdfium glue and the shared+ // enums, so they get their own chunks.+ if (pkg === "@embedpdf/engines") return "vendor-embedpdf";+ if (pkg === "@embedpdf/pdfium") return "vendor-pdfium";+ if (+ pkg === "@embedpdf/core" ||+ pkg === "@embedpdf/models" ||+ pkg === "@embedpdf/utils" ||+ pkg === "@embedpdf/plugin-spread"+ ) {+ return "vendor-embedpdf-core";+ }+ if (inScope(pkg, "@embedpdf")) return "vendor-embedpdf";+ // Without its own chunk the portal's static import drags the+ // markdown pipeline into vendor-ui, which the editor preloads.+ if (isMarkdownPackage(pkg)) return "vendor-markdown";+ // Splitting these out keeps icon changes from invalidating all of+ // vendor-ui.+ if (pkg === "@mui/icons-material") return "vendor-mui-icons";+ if (pkg === "@iconify/react") return "vendor-iconify";+ // These packages are mutually circular: splitting them breaks+ // module init order at runtime. Only startup modules land in+ // vendor-ui; libraries only some screens use (the markdown+ // renderer, the date pickers) go with the screens that import them.+ if (+ pkg.includes("react") ||+ pkg === "scheduler" ||+ inScope(pkg, "@mantine") ||+ inScope(pkg, "@mui") ||+ inScope(pkg, "@emotion") ||+ inScope(pkg, "@iconify")+ ) {+ return startupModules(meta).has(id) ? "vendor-ui" : undefined;+ }+ if (inScope(pkg, "@supabase")) return "vendor-supabase";+ if (pkg === "posthog-js" || inScope(pkg, "@posthog"))+ return "vendor-posthog";+ if (pkg === "@cantoo/pdf-lib" || pkg === "pdf-lib")+ return "vendor-pdflib";+ if (+ pkg === "recharts" ||+ pkg === "d3" ||+ pkg.startsWith("d3-") ||+ pkg === "decimal.js"+ ) {+ return "vendor-charts";}+ if (pkg === "jszip" || pkg === "pako") return "vendor-zip";+ if (pkg.includes("i18next")) return "vendor-i18n";},},},diff --git a/scripts/subset_cjk_fallback_fonts.py b/scripts/subset_cjk_fallback_fonts.pynew file mode 100644index 0000000000..347e3ad56d--- /dev/null+++ b/scripts/subset_cjk_fallback_fonts.py@@ -0,0 +1,145 @@+#!/usr/bin/env python3+"""+Subset the four Noto CJK fallback fonts to their codepage coverage.++The fonts under app/core/src/main/resources/static/fonts are the single source+for the backend classpath and for the frontend build copy. NotoSansSC,+NotoSansTC, NotoSansJP and NotoSansKR are the large faces, about 40 MB raw and+about 19 MB brotli together; the rest of the set is small enough to ship whole.++Each face is reduced to the characters its codepage can encode, so documents in+that language keep rendering while the files that never get downloaded travel+much smaller. The codepages are the Windows ones (cp936, big5hkscs, cp932,+cp949) rather than the stricter GB2312, Big5, Shift_JIS and EUC-KR sets, because+the Windows sets also cover the characters these languages use in practice.++Run it with the engine environment, which carries fontTools:++ uv run --project engine --locked python scripts/subset_cjk_fallback_fonts.py++The full faces stay in git history if a wider coverage is ever needed.+"""++from __future__ import annotations++import argparse+import sys+import unicodedata+from pathlib import Path++from fontTools import subset+from fontTools.ttLib import TTFont++FONT_DIR = Path(__file__).resolve().parent.parent / "app/core/src/main/resources/static/fonts"++CJK_COVERAGE: dict[str, str] = {+ "NotoSansSC-Regular.ttf": "cp936",+ "NotoSansTC-Regular.ttf": "big5hkscs",+ "NotoSansJP-Regular.ttf": "cp932",+ "NotoSansKR-Regular.ttf": "cp949",+}++CODEPOINT_RANGE = range(0x20, 0x10000)+++def codepoints_for(codec: str) -> str:+ """Return the printable characters of the Basic Multilingual Plane that codec can encode."""+ chars: list[str] = []+ for codepoint in CODEPOINT_RANGE:+ char = chr(codepoint)+ # Control, format, surrogate and private use characters are not text a+ # font needs a glyph for.+ if unicodedata.category(char)[0] == "C":+ continue+ try:+ char.encode(codec)+ except UnicodeEncodeError:+ continue+ chars.append(char)+ return "".join(chars)+++def font_codepoints(path: Path) -> set[int]:+ """Return the codepoints the font has a glyph for."""+ with TTFont(path, fontNumber=0, lazy=True) as font:+ return set(font.getBestCmap())+++def subset_font(path: Path, text: str) -> None:+ """Rewrite the font in place, keeping the glyphs the text needs."""+ options = subset.Options()+ options.layout_features = ["*"]+ options.name_IDs = ["*"]+ options.name_legacy = True+ options.name_languages = ["*"]+ options.glyph_names = True+ options.notdef_outline = True+ options.recommended_glyphs = True+ options.recalc_bounds = True++ font = subset.load_font(str(path), options)+ try:+ subsetter = subset.Subsetter(options=options)+ subsetter.populate(text=text)+ subsetter.subset(font)+ subset.save_font(font, str(path), options)+ finally:+ font.close()+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[1])+ parser.add_argument("--font-dir", type=Path, default=FONT_DIR)+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="report the result without rewriting the fonts",+ )+ args = parser.parse_args()++ if not args.font_dir.is_dir():+ parser.error(f"font directory not found: {args.font_dir}")++ total_before = 0+ total_after = 0+ for name, codec in sorted(CJK_COVERAGE.items()):+ path = args.font_dir / name+ if not path.is_file():+ parser.error(f"missing font: {path}")++ text = codepoints_for(codec)+ wanted = {ord(char) for char in text}+ present = font_codepoints(path)+ if not present:+ parser.error(f"{name} has no cmap and cannot be subset")++ # Keep what the font actually has; a few codepoints of a codepage are+ # control characters the face has no glyph for.+ target = wanted & present+ gaps = len(wanted - present)+ if gaps:+ print(f"{name}: no glyph for {gaps} of {len(wanted)} {codec} characters, keeping the rest")++ before = path.stat().st_size+ total_before += before+ if args.dry_run:+ print(f"{name}: {codec} covers {len(wanted)} characters, subsetting to {len(target)}")+ continue++ subset_font(path, "".join(chr(codepoint) for codepoint in sorted(target)))++ after = path.stat().st_size+ total_after += after+ lost = target - font_codepoints(path)+ if lost:+ parser.error(f"{name} lost {len(lost)} characters after subsetting")+ print(f"{name}: {len(target)} characters, {before // 1024} KB to {after // 1024} KB")++ if not args.dry_run:+ saved = total_before - total_after+ print(f"total: {total_before // 1024} KB to {total_after // 1024} KB, saved {saved // 1024} KB")+ return 0+++if __name__ == "__main__":+ sys.exit(main())