Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(files): keep the PDF.js stub out of the server bundle (#1818)

Sidedfc7334882a
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 873dd16d4c..0b1cc896f9 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2878,3 +2878,14 @@ tag until proven otherwise.
**Rule:** A "return to where you were" target is `pathname + search`, never `pathname`. When it is passed on inside another URL, encode it (`encodeURIComponent` / `URLSearchParams`), or its own `&` splits it. Test the round trip with a URL that has a query string. Drop React Router's `_routes` param from it, and only when present: middleware sees that param (loaders do not), a page URL that carries it limits which loaders later data requests run, and `searchParams.delete` re-encodes the whole query even when it removes nothing. Whatever sends the target on must be matched by something that reads it: three of the four callbacks ignored the `redirectTo` their login page sent.
**Applies to:** `packages/auth/src/utils/http.ts` (`getCurrentPath`, `makeRedirectToFromHere`), `requireAuthSession` / `refreshAuthSession`, every app's `login.tsx` callback URL and the `callback.tsx` that consumes it.
+
+
+## A `resolve.alias` stub reaches the server bundle too
+
+**Context:** Both apps aliased `unpdf/pdfjs` to a throwing stub to keep unpdf's 1.5 MB engine out of the browser bundle, where react-pdf's `pdfjs-dist` is used instead.
+
+**Problem:** A top-level `resolve.alias` applies to every Vite environment. On the server `unpdf/pdfjs` is the only PDF engine, so every deployed document extraction (purchase invoice, sales RFQ) failed with "Serverless PDF.js bundle could not be resolved". Dev and vitest passed: dev leaves `unpdf` external, so Node resolves the real module and the alias never applies.
+
+**Rule:** A stub that exists to shrink the client bundle goes through `clientOnlyAlias` (`@carbon/dev/vite`), never `resolve.alias`. Verify a server-side dependency change against a bundle built with `ssr.noExternal: true`, not against the dev server.
+
+**Applies to:** `apps/{erp,mes}/vite.config.ts`, `app/ssr-shims/`, `packages/dev/vite.js`.
diff --git a/apps/erp/app/ssr-shims/unpdf-pdfjs-stub.mjs b/apps/erp/app/ssr-shims/unpdf-pdfjs-stub.mjs
index 9096915228..a225047c9a 100644
--- a/apps/erp/app/ssr-shims/unpdf-pdfjs-stub.mjs
+++ b/apps/erp/app/ssr-shims/unpdf-pdfjs-stub.mjs
@@ -8,8 +8,10 @@
* `@carbon/files/pdf` points unpdf at react-pdf's `pdfjs-dist` in the browser
* (`definePDFJSModule`), so this app runs exactly ONE PDF.js engine. unpdf still
* carries `import("unpdf/pdfjs")` as a never-reached fallback, and Vite emits
- * that as a lazy chunk in every deploy. Alias it away; the throw is only
- * reachable if the resolver above were ever removed.
+ * that as a lazy chunk in every deploy. Alias it away in the client build
+ * only (`clientOnlyAlias` in vite.config.ts): the server has no other engine,
+ * so there `unpdf/pdfjs` must stay real. The throw is only reachable if the
+ * resolver above were ever removed.
*/
throw new Error(
"unpdf/pdfjs is stubbed in the app bundle — @carbon/files/pdf must resolve PDF.js via react-pdf's pdfjs-dist"
diff --git a/apps/erp/vite.config.ts b/apps/erp/vite.config.ts
index c9c0a4d9af..373065b59c 100644
--- a/apps/erp/vite.config.ts
+++ b/apps/erp/vite.config.ts
@@ -2,7 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { applyDotenvToProcessEnv } from "@carbon/dev/vite";
+import { applyDotenvToProcessEnv, clientOnlyAlias } from "@carbon/dev/vite";
import { lingui } from "@lingui/vite-plugin";
import { reactRouter } from "@react-router/dev/vite";
import tailwindcss from "@tailwindcss/vite";
@@ -124,6 +124,13 @@ export default defineConfig(({ command, isSsrBuild, mode }) => {
babelMacros(),
lingui(),
reactRouter(),
+ // unpdf's bundled PDF.js engine is a dead lazy chunk in the browser, which
+ // runs react-pdf's pdfjs-dist (see @carbon/files/pdf). Keep it out there
+ // only: on the server it is the one engine PDF reading has.
+ clientOnlyAlias(
+ "unpdf/pdfjs",
+ path.resolve(__dirname, "app/ssr-shims/unpdf-pdfjs-stub.mjs")
+ ),
] as PluginOption[],
resolve: {
tsconfigPaths: true,
@@ -142,12 +149,6 @@ export default defineConfig(({ command, isSsrBuild, mode }) => {
* like `canvas` above.
*/
ws: path.resolve(__dirname, "app/ssr-shims/ws-stub.cjs"),
- // unpdf's bundled PDF.js engine is a dead lazy chunk here — the browser
- // runs react-pdf's pdfjs-dist (see @carbon/files/pdf). Keep it out.
- "unpdf/pdfjs": path.resolve(
- __dirname,
- "app/ssr-shims/unpdf-pdfjs-stub.mjs"
- ),
// Directory (not index.ts) so subpath imports like
// `@carbon/utils/favicon` resolve to `src/favicon.ts`.
"@carbon/utils": path.resolve(__dirname, "../../packages/utils/src"),
diff --git a/apps/mes/app/ssr-shims/unpdf-pdfjs-stub.mjs b/apps/mes/app/ssr-shims/unpdf-pdfjs-stub.mjs
index 9096915228..a225047c9a 100644
--- a/apps/mes/app/ssr-shims/unpdf-pdfjs-stub.mjs
+++ b/apps/mes/app/ssr-shims/unpdf-pdfjs-stub.mjs
@@ -8,8 +8,10 @@
* `@carbon/files/pdf` points unpdf at react-pdf's `pdfjs-dist` in the browser
* (`definePDFJSModule`), so this app runs exactly ONE PDF.js engine. unpdf still
* carries `import("unpdf/pdfjs")` as a never-reached fallback, and Vite emits
- * that as a lazy chunk in every deploy. Alias it away; the throw is only
- * reachable if the resolver above were ever removed.
+ * that as a lazy chunk in every deploy. Alias it away in the client build
+ * only (`clientOnlyAlias` in vite.config.ts): the server has no other engine,
+ * so there `unpdf/pdfjs` must stay real. The throw is only reachable if the
+ * resolver above were ever removed.
*/
throw new Error(
"unpdf/pdfjs is stubbed in the app bundle — @carbon/files/pdf must resolve PDF.js via react-pdf's pdfjs-dist"
diff --git a/apps/mes/vite.config.ts b/apps/mes/vite.config.ts
index 6e089b3273..c0df732f10 100644
--- a/apps/mes/vite.config.ts
+++ b/apps/mes/vite.config.ts
@@ -2,7 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { applyDotenvToProcessEnv } from "@carbon/dev/vite";
+import { applyDotenvToProcessEnv, clientOnlyAlias } from "@carbon/dev/vite";
import { reactRouter } from "@react-router/dev/vite";
import { lingui } from "@lingui/vite-plugin";
import tailwindcss from "@tailwindcss/vite";
@@ -95,6 +95,13 @@ export default defineConfig(({ command, mode, isSsrBuild }) => {
babelMacros(),
lingui(),
reactRouter(),
+ // unpdf's bundled PDF.js engine is a dead lazy chunk in the browser, which
+ // runs react-pdf's pdfjs-dist (see @carbon/files/pdf). Keep it out there
+ // only: on the server it is the one engine PDF reading has.
+ clientOnlyAlias(
+ "unpdf/pdfjs",
+ path.resolve(__dirname, "app/ssr-shims/unpdf-pdfjs-stub.mjs")
+ ),
] as PluginOption[],
resolve: {
tsconfigPaths: true,
@@ -113,12 +120,6 @@ export default defineConfig(({ command, mode, isSsrBuild }) => {
* not. Nothing here uses `ws` — stub it like `canvas` above.
*/
ws: path.resolve(__dirname, "app/ssr-shims/ws-stub.cjs"),
- // unpdf's bundled PDF.js engine is a dead lazy chunk here — the browser
- // runs react-pdf's pdfjs-dist (see @carbon/files/pdf). Keep it out.
- "unpdf/pdfjs": path.resolve(
- __dirname,
- "app/ssr-shims/unpdf-pdfjs-stub.mjs"
- ),
// Directory (not index.ts) so subpath imports like
// `@carbon/utils/favicon` resolve to `src/favicon.ts`.
"@carbon/utils": path.resolve(__dirname, "../../packages/utils/src"),
diff --git a/packages/dev/src/vite.test.ts b/packages/dev/src/vite.test.ts
new file mode 100644
index 0000000000..65e7c4045c
--- /dev/null
+++ b/packages/dev/src/vite.test.ts
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { clientOnlyAlias } from "../vite.js";
+
+describe("clientOnlyAlias", () => {
+ const plugin = clientOnlyAlias("unpdf/pdfjs", "/stub.mjs") as unknown as {
+ applyToEnvironment: (environment: { name: string }) => boolean;
+ resolveId: (source: string) => string | undefined;
+ };
+
+ it("applies to the client environment only", () => {
+ expect(plugin.applyToEnvironment({ name: "client" })).toBe(true);
+ expect(plugin.applyToEnvironment({ name: "ssr" })).toBe(false);
+ expect(plugin.applyToEnvironment({ name: "ssr_bundle_x" })).toBe(false);
+ });
+
+ it("resolves the exact specifier and nothing else", () => {
+ expect(plugin.resolveId("unpdf/pdfjs")).toBe("/stub.mjs");
+ expect(plugin.resolveId("unpdf")).toBeUndefined();
+ });
+});
diff --git a/packages/dev/vite.d.ts b/packages/dev/vite.d.ts
new file mode 100644
index 0000000000..e1a3a37362
--- /dev/null
+++ b/packages/dev/vite.d.ts
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { Plugin } from "vite";
+
+export function applyDotenvToProcessEnv(mode: string, appDir: string): void;
+export function clientOnlyAlias(specifier: string, file: string): Plugin;
diff --git a/packages/dev/vite.js b/packages/dev/vite.js
index 2661d91253..30f601a0f9 100644
--- a/packages/dev/vite.js
+++ b/packages/dev/vite.js
@@ -32,3 +32,23 @@ export function applyDotenvToProcessEnv(mode, appDir) {
}
}
}
+
+/**
+ * Resolve `specifier` to `file` in the browser build only. A top-level
+ * `resolve.alias` applies to every environment, so a stub meant to keep a
+ * chunk out of the client bundle also replaces the module on the server.
+ *
+ * @param {string} specifier
+ * @param {string} file
+ * @returns {import("vite").Plugin}
+ */
+export function clientOnlyAlias(specifier, file) {
+ return {
+ name: `carbon:client-only-alias:${specifier}`,
+ enforce: "pre",
+ applyToEnvironment: (environment) => environment.name === "client",
+ resolveId(source) {
+ if (source === specifier) return file;
+ },
+ };
+}
diff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.md
index 587a5a1c65..8a1a26a9e2 100644
--- a/packages/files/AGENTS.md
+++ b/packages/files/AGENTS.md
@@ -96,10 +96,17 @@ and ~2 MB of duplicate code, so `./pdf` resolves the engine per runtime:
| Node / edge / jobs | unpdf's inlined serverless build | built in — no worker file, no `@ts-ignore` legacy imports (the old `extract-document` hack) |
unpdf still carries `import("unpdf/pdfjs")` as a never-reached fallback, which
-Vite emitted as a 1.5 MB lazy chunk in every deploy. Both apps alias
-`unpdf/pdfjs` to `app/ssr-shims/unpdf-pdfjs-stub.mjs` to keep it out; the ERP
-client build was verified to contain exactly ONE engine chunk (388 KB). Any new
-app that consumes `./pdf` in the browser needs the same alias.
+Vite emitted as a 1.5 MB lazy chunk in every deploy. Both apps resolve
+`unpdf/pdfjs` to `app/ssr-shims/unpdf-pdfjs-stub.mjs` **in the client build
+only**, with `clientOnlyAlias` from `@carbon/dev/vite`; the ERP client build was
+verified to contain exactly ONE engine chunk (388 KB). Any new app that consumes
+`./pdf` in the browser needs the same plugin.
+
+Never put that stub in `resolve.alias`: a top-level alias applies to every
+environment, and on the server `unpdf/pdfjs` IS the engine (the table above). It
+was there once, and every deployed document extraction failed with "Serverless
+PDF.js bundle could not be resolved" while dev worked, because dev leaves
+`unpdf` external and Node resolves the real module.
- Classify with `getDocumentType`; narrow to preview-capable with
`isPreviewableDocumentType` (a `@ts-expect-error` on a `DocumentPreview` `type`
prop means a missing narrow, not a type bug).