From 56553fb46415002253d81768f99e4e822c35ad28 Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Tue, 24 Nov 2026 17:04:55 +0200 Subject: [PATCH 1/2] feat: add a Vite plugin that emits the PDF.js data next to the bundled viewer Vite emits the viewer's runtime files under hashed names and leaves the PDF.js data folders behind, so a bundled app answers 404 for wasm/jbig2.wasm and scanned pages lose their image. The plugin, exported as @missing-elements/pdfjs-viewer/vite, finds the emitted viewer.mjs and pdf.mjs by content and writes the data next to them, where the element already looks for it. Tests build a fixture app from dist with and without the plugin and open both in Firefox. CI runs them through pnpm test:plugin, which builds the package first. Part of #83 Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yml | 3 +- CONTRIBUTING.md | 7 + README.md | 17 ++- package.json | 6 + plugins/vite.d.ts | 7 + plugins/vite.js | 52 ++++++++ scripts/copy-worker.mjs | 2 +- src/pdfjs-viewer-element.ts | 3 +- tests/fixtures/bundled-app/index.html | 11 ++ tests/fixtures/bundled-app/main.js | 2 + tests/fixtures/ccitt-g4.pdf | Bin 0 -> 1226 bytes tests/plugin/vite.test.ts | 176 ++++++++++++++++++++++++++ vite.config.ts | 4 +- vitest.plugin.config.ts | 12 ++ 14 files changed, 297 insertions(+), 5 deletions(-) create mode 100644 plugins/vite.d.ts create mode 100644 plugins/vite.js create mode 100644 tests/fixtures/bundled-app/index.html create mode 100644 tests/fixtures/bundled-app/main.js create mode 100644 tests/fixtures/ccitt-g4.pdf create mode 100644 tests/plugin/vite.test.ts create mode 100644 vitest.plugin.config.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a92a79d..e43a122 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,4 +27,5 @@ jobs: - run: pnpm install --frozen-lockfile - run: pnpm exec playwright install --with-deps firefox - run: pnpm test -- --run - - run: pnpm build + # Builds the package, then tests the Vite plugin on an app bundled from that build. + - run: pnpm test:plugin diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0b005bb..6eff7cb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,6 +39,13 @@ Build the package: pnpm build ``` +Test the Vite plugin. This builds the package, bundles a small app from it and opens the app in +Firefox: + +```bash +pnpm test:plugin +``` + The test and build scripts synchronize the PDF.js runtime assets before running. The PDF.js release archive is required because the viewer assets are not published in this repository. Do not commit generated `dist` or `public` diff --git a/README.md b/README.md index 5104bb2..1b4d145 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,22 @@ npm install @missing-elements/pdfjs-viewer import '@missing-elements/pdfjs-viewer' ``` -Vite, webpack 5 and Next.js bundle the viewer with no configuration. They don't copy the PDF.js data folders, though, because PDF.js loads those files by name. Without them, scanned pages compressed with JBIG2, CCITT or JPEG 2000 render blank or black, CJK text in fonts the PDF doesn't embed goes missing, and JavaScript in PDFs doesn't run. To support every PDF, copy the package's `dist` folder into your public files, for example in a `postinstall` script, and point [`assets-base`](https://missing-elements.github.io/pdfjs-viewer/#hosting) at it: +Vite, webpack 5 and Next.js bundle the viewer with no configuration. They don't copy the PDF.js data folders, though, because PDF.js loads those files by name. Without them, scanned pages compressed with JBIG2, CCITT or JPEG 2000 render blank or black, CJK text in fonts the PDF doesn't embed goes missing, and JavaScript in PDFs doesn't run. + +With Vite, add the plugin that ships with the package. It writes the data into the build output, next to the viewer files: about 3.4 MB, which a browser downloads only for a document that needs it. + +```js +// vite.config.js +import { pdfjsViewerData } from '@missing-elements/pdfjs-viewer/vite' + +export default { + plugins: [pdfjsViewerData()] +} +``` + +The data files keep the names PDF.js asks for, with no hash in them. If your server caches the whole `assets` folder as `immutable`, leave them out of that rule, or browsers keep the old files after you upgrade. + +With webpack, Next.js or another bundler, copy the package's `dist` folder into your public files, for example in a `postinstall` script, and point [`assets-base`](https://missing-elements.github.io/pdfjs-viewer/#hosting) at it: ```html diff --git a/package.json b/package.json index 34ce6fa..463a7e4 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,10 @@ "types": "./types/pdfjs-viewer-element.d.ts", "default": "./dist/pdfjs-viewer-element.js" }, + "./vite": { + "types": "./plugins/vite.d.ts", + "default": "./plugins/vite.js" + }, "./dist/*": "./dist/*", "./package.json": "./package.json" }, @@ -45,6 +49,7 @@ }, "files": [ "dist", + "plugins", "types" ], "publishConfig": { @@ -55,6 +60,7 @@ "dev": "vite", "build": "pnpm sync:pdfjs && tsc && vite build && node scripts/copy-worker.mjs", "test": "pnpm sync:pdfjs && vitest", + "test:plugin": "pnpm build && vitest run --config vitest.plugin.config.ts", "coverage": "pnpm sync:pdfjs && vitest run --coverage", "release": "node scripts/release.mjs", "release:dry": "node scripts/release.mjs --dry-run" diff --git a/plugins/vite.d.ts b/plugins/vite.d.ts new file mode 100644 index 0000000..3f347f0 --- /dev/null +++ b/plugins/vite.d.ts @@ -0,0 +1,7 @@ +/** + * A Vite plugin. It writes the PDF.js data the viewer loads on demand (`wasm/`, `cmaps/`, + * `standard_fonts/`, `iccs/`, `images/` and `pdf.sandbox.mjs`) into the build output, next to the + * viewer files Vite emits. The element finds the data there, with no `assets-base` or resource + * attribute. + */ +export declare function pdfjsViewerData(): { name: string } diff --git a/plugins/vite.js b/plugins/vite.js new file mode 100644 index 0000000..901dbeb --- /dev/null +++ b/plugins/vite.js @@ -0,0 +1,52 @@ +import { readdirSync, readFileSync, statSync } from 'node:fs' +import { join, posix } from 'node:path' +import { fileURLToPath } from 'node:url' + +// A bundler emits the viewer's runtime files under hashed names and leaves the PDF.js data behind: +// PDF.js asks for those files by name from a folder URL, so nothing references them one by one. +// The element looks for the data next to two of the runtime files (`RESOURCE_OPTIONS` in +// src/pdfjs-viewer-element.ts). This plugin finds those two files in the build output and writes +// the data next to them, under the names PDF.js expects. +const distDirectory = fileURLToPath(new URL('../dist', import.meta.url)) + +const dataByAnchor = { + 'viewer.mjs': ['cmaps', 'iccs', 'images', 'standard_fonts', 'wasm'], + 'pdf.mjs': ['pdf.sandbox.mjs'] +} + +const readFile = (file) => readFileSync(join(distDirectory, file)) + +const listFiles = (entry) => { + const path = join(distDirectory, entry) + if (!statSync(path).isDirectory()) return [entry] + return readdirSync(path).map((name) => posix.join(entry, name)) +} + +// The bundler copies a runtime file byte for byte and only renames it, so an emitted asset is +// recognised by its content. That follows any `assetFileNames` setting, and it works in Vite and +// Rollup versions that don't record which source file an asset came from. +const isSameFile = (source, file) => + Buffer.byteLength(source) === file.length && file.equals(Buffer.from(source)) + +export const pdfjsViewerData = () => ({ + name: 'pdfjs-viewer-data', + generateBundle(_options, bundle) { + const anchors = Object.entries(dataByAnchor).map(([name, entries]) => ({ file: readFile(name), entries })) + + Object.values(bundle) + .filter((output) => output.type === 'asset') + .forEach((asset) => { + const anchor = anchors.find(({ file }) => isSameFile(asset.source, file)) + if (!anchor) return + + const outputDirectory = posix.dirname(asset.fileName) + anchor.entries.flatMap(listFiles).forEach((file) => { + this.emitFile({ + type: 'asset', + fileName: posix.join(outputDirectory, file), + source: readFile(file) + }) + }) + }) + } +}) diff --git a/scripts/copy-worker.mjs b/scripts/copy-worker.mjs index e4f3d0e..a853d8e 100644 --- a/scripts/copy-worker.mjs +++ b/scripts/copy-worker.mjs @@ -17,7 +17,7 @@ const targetFile = resolve(distDir, 'pdf.worker.min.mjs') const targetRendererFile = resolve(distDir, 'pdf.renderer.min.mjs') const targetSandboxFile = resolve(distDir, 'pdf.sandbox.mjs') // Resources PDF.js loads only for documents that need them. The element defaults their URLs to -// these folders next to viewer.mjs. +// these folders next to viewer.mjs, and plugins/vite.js copies the same folders into a bundled app. const resourceDirs = ['cmaps', 'iccs', 'standard_fonts', 'wasm'] const targetPdfFile = resolve(distDir, 'pdf.mjs') const targetViewerFile = resolve(distDir, 'viewer.mjs') diff --git a/src/pdfjs-viewer-element.ts b/src/pdfjs-viewer-element.ts index 4c2c92b..71bb345 100644 --- a/src/pdfjs-viewer-element.ts +++ b/src/pdfjs-viewer-element.ts @@ -62,7 +62,8 @@ const DEFAULTS = { // Resources PDF.js loads only for documents that need them. They ship in the package `dist` // folder, and each defaults to `fileName` resolved against the runtime file named by `base`, so // `assets-base` and the individual runtime URLs carry them along. Bundlers emit the runtime files -// but not these folders, so bundled apps set `assets-base` or the attributes. +// but not these folders, so bundled apps add the build plugin (plugins/vite.js), which writes the +// folders next to the emitted files, or set `assets-base` or the attributes. // PDF.js fetches most of them from its worker, which runs from a `blob:` URL where relative paths // don't resolve, so attribute values are made absolute, and folder URLs get the trailing slash // PDF.js requires. diff --git a/tests/fixtures/bundled-app/index.html b/tests/fixtures/bundled-app/index.html new file mode 100644 index 0000000..8b6dde3 --- /dev/null +++ b/tests/fixtures/bundled-app/index.html @@ -0,0 +1,11 @@ + + + + + Bundled app + + + + + + diff --git a/tests/fixtures/bundled-app/main.js b/tests/fixtures/bundled-app/main.js new file mode 100644 index 0000000..a4d9463 --- /dev/null +++ b/tests/fixtures/bundled-app/main.js @@ -0,0 +1,2 @@ +// The built package, as an installed app imports it. +import '../../../dist/pdfjs-viewer-element.js' diff --git a/tests/fixtures/ccitt-g4.pdf b/tests/fixtures/ccitt-g4.pdf new file mode 100644 index 0000000000000000000000000000000000000000..6044c904a1da25e2ce69cb7409db7ae1cc44971f GIT binary patch literal 1226 zcmZWp?{C^L5dEIN;(bBdBuWy>uT>RN3!`J*)UKdzQne2bIlwfrnQaR6uix2$wOtL7 zo%7whchBe4Zil0jw9$%cxWHO02yM`Jx3R%4;=DNtqfL%*ztyGH!rcARcBo|K9 zkxA!kF7fRusWjr)W-8zMMalC89~q9h1gNywx`rk^N)5vx><UP3A)Nrd(4D**=t7&xTCj%kke*n}D$I;g6^0E2>_0QIB`fKx_t=oHN u>n87QpE|GboDs4h6Iyp7pNYQ~tdsU#cW7C@`o;yGY0_#&wc6*KQS=u#&022& literal 0 HcmV?d00001 diff --git a/tests/plugin/vite.test.ts b/tests/plugin/vite.test.ts new file mode 100644 index 0000000..5172335 --- /dev/null +++ b/tests/plugin/vite.test.ts @@ -0,0 +1,176 @@ +import { copyFileSync, createReadStream, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs' +import { createServer, type Server } from 'node:http' +import { createRequire } from 'node:module' +import type { AddressInfo } from 'node:net' +import { tmpdir } from 'node:os' +import { dirname, extname, join, relative, resolve, sep } from 'node:path' +import { firefox, type Browser } from 'playwright' +import { build, type PluginOption } from 'vite' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { pdfjsViewerData } from '../../plugins/vite.js' + +const rootDirectory = resolve(import.meta.dirname, '../..') +const distDirectory = join(rootDirectory, 'dist') +const appDirectory = join(rootDirectory, 'tests/fixtures/bundled-app') +const samplePdf = join(rootDirectory, 'tests/fixtures/ccitt-g4.pdf') + +const outputDirectories: string[] = [] + +const listFiles = (directory: string): string[] => + readdirSync(directory, { withFileTypes: true, recursive: true }) + .filter((entry) => entry.isFile()) + .map((entry) => relative(directory, join(entry.parentPath, entry.name)).split(sep).join('/')) + .sort() + +// Builds the fixture app, which imports the built package the way an installed app does. +const buildApp = async (plugins: PluginOption[], output = {}) => { + const outDir = mkdtempSync(join(tmpdir(), 'pdfjs-viewer-bundled-app-')) + outputDirectories.push(outDir) + await build({ + root: appDirectory, + configFile: false, + logLevel: 'error', + plugins, + build: { outDir, emptyOutDir: true, rolldownOptions: { output } } + }) + copyFileSync(samplePdf, join(outDir, 'ccitt-g4.pdf')) + return outDir +} + +const findFile = (files: string[], pattern: RegExp) => { + const file = files.find((name) => pattern.test(name)) + expect(file, `${pattern} in the build output`).toBeDefined() + return file! +} + +const contentTypes: Record = { + '.html': 'text/html', + '.js': 'text/javascript', + '.mjs': 'text/javascript', + '.pdf': 'application/pdf', + '.wasm': 'application/wasm' +} + +// A dev or preview server answers a missing file with the app's HTML page and a 200. A static host +// answers 404, which is what breaks the viewer in production, so the build output is served that way. +const serve = (directory: string) => new Promise((done) => { + const server = createServer((request, response) => { + const { pathname } = new URL(request.url ?? '/', 'http://localhost') + const file = join(directory, pathname === '/' ? 'index.html' : decodeURIComponent(pathname)) + if (!file.startsWith(directory) || !statSync(file, { throwIfNoEntry: false })?.isFile()) { + response.writeHead(404).end() + return + } + response.writeHead(200, { 'content-type': contentTypes[extname(file)] ?? 'application/octet-stream' }) + createReadStream(file).pipe(response) + }) + server.listen(0, '127.0.0.1', () => done(server)) +}) + +describe('Vite plugin', () => { + let browser: Browser + let plainOutput: string + let pluginOutput: string + + beforeAll(async () => { + browser = await firefox.launch() + plainOutput = await buildApp([]) + pluginOutput = await buildApp([pdfjsViewerData()]) + }) + + afterAll(async () => { + await browser?.close() + outputDirectories.forEach((directory) => rmSync(directory, { recursive: true, force: true })) + }) + + // Opens the built app and reads the first page: the sample PDF fills it with an image that is + // black on the left and white on the right, which PDF.js decodes with `wasm/jbig2.wasm`. + const openApp = async (directory: string) => { + const server = await serve(directory) + const page = await browser.newPage() + const missing: string[] = [] + page.on('response', (response) => { + if (response.status() === 404) missing.push(new URL(response.url()).pathname) + }) + + try { + await page.goto(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`) + // PDF.js finishes the page with or without the image: a failed image is only a warning. + await page.waitForFunction(() => { + const viewer = document.querySelector('pdfjs-viewer-element') as any + return viewer?.iframe?.contentWindow?.PDFViewerApplication?.pdfViewer?.getPageView(0)?.renderingState === 3 + }) + const colors = await page.evaluate(() => { + const viewer = document.querySelector('pdfjs-viewer-element') as any + const canvas = viewer.iframe.contentDocument.querySelector('.page canvas') as HTMLCanvasElement + const readRed = (x: number) => + canvas.getContext('2d')!.getImageData(Math.floor(canvas.width * x), Math.floor(canvas.height / 2), 1, 1).data[0] + return { left: readRed(0.25), right: readRed(0.75) } + }) + return { ...colors, missing } + } finally { + await page.close() + // The browser keeps its connections open, and `close` alone waits for them to end. + server.closeAllConnections() + await new Promise((done) => server.close(done)) + } + } + + it('leaves a scanned image blank in a build without the plugin', async () => { + const files = listFiles(plainOutput) + expect(files.filter((file) => file.includes('wasm/'))).toEqual([]) + + const { left, right, missing } = await openApp(plainOutput) + expect(missing).toContain('/assets/wasm/jbig2.wasm') + expect(left, 'the black half stays blank').toBeGreaterThan(192) + expect(right).toBeGreaterThan(192) + }) + + it('draws the scanned image in a build with the plugin', async () => { + const { left, right, missing } = await openApp(pluginOutput) + expect(missing.filter((path) => path.startsWith('/assets/'))).toEqual([]) + expect(left, 'the black half').toBeLessThan(64) + expect(right, 'the white half').toBeGreaterThan(192) + }) + + it('emits every data file under its own name next to the runtime file the element resolves it from', () => { + const files = listFiles(pluginOutput) + const viewerDirectory = dirname(findFile(files, /\/viewer-[\w-]+\.mjs$/)) + const libDirectory = dirname(findFile(files, /\/pdf-[\w-]+\.mjs$/)) + + // Every folder in `dist` holds data the element resolves against viewer.mjs, so a folder that + // scripts/copy-worker.mjs starts to ship has to reach the plugin's list too. + const dataFiles = listFiles(distDirectory).filter((file) => file.includes('/')) + expect(dataFiles.length).toBeGreaterThan(200) + for (const file of dataFiles) { + const emitted = join(pluginOutput, viewerDirectory, file) + expect(statSync(emitted, { throwIfNoEntry: false })?.size, file).eq(statSync(join(distDirectory, file)).size) + } + + const sandbox = join(pluginOutput, libDirectory, 'pdf.sandbox.mjs') + expect(readFileSync(sandbox).equals(readFileSync(join(distDirectory, 'pdf.sandbox.mjs')))).eq(true) + expect(files.length).eq(listFiles(plainOutput).length + dataFiles.length + 1) + }) + + it('follows the runtime files when the app renames and moves them', async () => { + const assetFileNames = ({ names }: { names: string[] }) => { + if (names.includes('viewer.mjs')) return 'static/viewer/v.[hash][extname]' + if (names.includes('pdf.mjs')) return 'static/lib/p.[hash][extname]' + return 'static/[name]-[hash][extname]' + } + const files = listFiles(await buildApp([pdfjsViewerData()], { assetFileNames })) + + expect(files).toContain('static/viewer/wasm/jbig2.wasm') + expect(files).toContain('static/viewer/cmaps/Adobe-Japan1-UCS2.bcmap') + expect(files).toContain('static/lib/pdf.sandbox.mjs') + expect(files.filter((file) => file.endsWith('pdf.sandbox.mjs'))).toEqual(['static/lib/pdf.sandbox.mjs']) + expect(files.filter((file) => file.endsWith('jbig2.wasm'))).toEqual(['static/viewer/wasm/jbig2.wasm']) + }) + + it('is exported from the package as ./vite, with types', () => { + const packageJson = JSON.parse(readFileSync(join(rootDirectory, 'package.json'), 'utf8')) + const require = createRequire(import.meta.url) + expect(require.resolve(`${packageJson.name}/vite`)).eq(join(rootDirectory, 'plugins/vite.js')) + expect(statSync(join(rootDirectory, packageJson.exports['./vite'].types)).isFile()).eq(true) + }) +}) diff --git a/vite.config.ts b/vite.config.ts index f0418a7..5f70636 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,7 +1,7 @@ /// import { readFile } from 'node:fs/promises' import { resolve } from 'node:path' -import { defineConfig } from 'vitest/config' +import { configDefaults, defineConfig } from 'vitest/config' import terser from '@rollup/plugin-terser' import { playwright } from '@vitest/browser-playwright' import { minify as minifyHtml } from 'html-minifier-terser' @@ -96,6 +96,8 @@ export default defineConfig({ copyPublicDir: false }, test: { + // The plugin tests run in Node, against the built package (vitest.plugin.config.ts). + exclude: [...configDefaults.exclude, 'tests/plugin/**'], browser: { // Vitest provider overloads can conflict when multiple provider typings exist in the graph. provider: playwright(), diff --git a/vitest.plugin.config.ts b/vitest.plugin.config.ts new file mode 100644 index 0000000..a23a37b --- /dev/null +++ b/vitest.plugin.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'vitest/config' + +// The plugin tests build a fixture app from the package's `dist` folder and open it in a browser +// they start themselves, so they run in Node, after the package is built. The element's own tests +// run in the browser (vite.config.ts). +export default defineConfig({ + test: { + include: ['tests/plugin/**/*.test.ts'], + testTimeout: 60_000, + hookTimeout: 60_000 + } +}) From 22eeef17a9dcaa13ba6d76eb75ae874ccc795a50 Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Tue, 24 Nov 2026 17:10:14 +0200 Subject: [PATCH 2/2] test: compare the emitted data with dist byte for byte The check compared file sizes only, so wrong content of the right length passed. Co-Authored-By: Claude Fable 5.2 --- tests/plugin/vite.test.ts | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/tests/plugin/vite.test.ts b/tests/plugin/vite.test.ts index 5172335..67b725c 100644 --- a/tests/plugin/vite.test.ts +++ b/tests/plugin/vite.test.ts @@ -142,14 +142,16 @@ describe('Vite plugin', () => { // scripts/copy-worker.mjs starts to ship has to reach the plugin's list too. const dataFiles = listFiles(distDirectory).filter((file) => file.includes('/')) expect(dataFiles.length).toBeGreaterThan(200) - for (const file of dataFiles) { - const emitted = join(pluginOutput, viewerDirectory, file) - expect(statSync(emitted, { throwIfNoEntry: false })?.size, file).eq(statSync(join(distDirectory, file)).size) + const expected = [ + ...dataFiles.map((file) => [`${viewerDirectory}/${file}`, file]), + [`${libDirectory}/pdf.sandbox.mjs`, 'pdf.sandbox.mjs'] + ] + for (const [emitted, source] of expected) { + expect(files, source).toContain(emitted) + const sameBytes = readFileSync(join(pluginOutput, emitted)).equals(readFileSync(join(distDirectory, source))) + expect(sameBytes, `${source} is copied byte for byte`).eq(true) } - - const sandbox = join(pluginOutput, libDirectory, 'pdf.sandbox.mjs') - expect(readFileSync(sandbox).equals(readFileSync(join(distDirectory, 'pdf.sandbox.mjs')))).eq(true) - expect(files.length).eq(listFiles(plainOutput).length + dataFiles.length + 1) + expect(files.length).eq(listFiles(plainOutput).length + expected.length) }) it('follows the runtime files when the app renames and moves them', async () => {