Skip to content

About

A shared PDF.js 3.11.174 legacy-runtime compatibility boundary for old Android WebViews

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@0k/pdfjs-legacy-runtime

A shared PDF.js compatibility boundary for applications that must run on old Android WebViews: the exact pin, the legacy/ import, worker resolution, retry-on-rejected-load and single-owner teardown, stated once.

What this is

Not a utility — a policy. Five rules that every consuming application must obey identically, because they may render different documents for different readers but do it on the same engine on the same device:

  1. pdfjs-dist is EXACTLY 3.11.174;
  2. the legacy/ build is loaded, never the default one;
  3. the worker is resolved as a build-emitted asset URL;
  4. a REJECTED load is not memoised, so a retry can succeed;
  5. teardown has exactly ONE owner.

Copied into each application instead, these rules diverge: a copy that memoises a rejected load unconditionally makes a transient import failure permanent for the life of the page. Nothing fails, because nothing checks.

It also forces isEvalSupported: false on every document it loads (see Security).

⚠ Why the pin is not negotiable

Android System WebView 91 (the SM-N910C test device) runs a V8 that cannot parse two constructs later PDF.js emits even in its =legacy/= bundle: ES2022 class static-init blocks (static { … }) and ES2024 Promise.withResolvers(). On device a v6 legacy worker fails with Setting up fake worker failed: Unexpected token '{'.

The reader is then shown a blank rectangle where the document should be — the failure is silent in the worst possible way.

Two checks hold the pin:

  • pdfjs-dist is an EXACT dependency of this package, so the copy it imports is 3.11.174 whatever else the application installs. test/compat.test.ts checks the declaration stays exact.
  • The same test scans the installed bundles for both constructs — a version number is a label, the bytes are the fact.

Install

npm install @0k/pdfjs-legacy-runtime

pdfjs-dist 3.11.174 comes with it. The application’s bundler must handle new URL("<package path>", import.meta.url) by resolving the package path as a module and emitting the file as an asset (Vite and webpack 5 do); under plain URL rules that string resolves next to the importing chunk instead.

Usage

import { loadPdfRuntime, type PdfLoadingTask } from '@0k/pdfjs-legacy-runtime';

const runtime = await loadPdfRuntime();   // imports PDF.js on first call
const task: PdfLoadingTask = runtime.getDocument({
  url: 'document.pdf',
  disableAutoFetch: true,                 // with disableStream: fetch
  disableStream: true,                    // only what the page needs
});
const doc = await task.promise;
const page = await doc.getPage(1);
const viewport = page.getViewport({ scale: 1.5 });

const canvas = document.createElement('canvas');
canvas.width = viewport.width;
canvas.height = viewport.height;
const render = page.render({ canvasContext: canvas.getContext('2d')!, viewport });
await render.promise;                     // render.cancel() aborts it

page.cleanup();
await task.destroy();                     // the ONLY teardown: network + worker
  • Keep the loading task for the life of the document: its destroy() is the only way to release the worker. PdfDocument has no destroy(), on purpose.
  • If loadPdfRuntime() rejects (a chunk that did not arrive), call it again: a failed import is not cached.
  • For large files, serve the URL with Range support and pass disableAutoFetch and disableStream as above: PDF.js then fetches the cross-reference table and the pages shown, not the whole body.

Each document gets its own dedicated worker from GlobalWorkerOptions.workerSrc; GlobalWorkerOptions.workerPort is not used. The returned loading task is a wrapper exposing only the typed promise and destroy(). Untyped PDF.js members reached through casts, such as onProgress, onPassword and docId, are not available.

The loading task’s destroy() resolves only once the worker thread has stopped, including when cancelled during startup. Consumers that await it before loading another document do not overlap workers. If transport teardown fails, the worker is still destroyed and awaited before destroy() rejects with the original error. A worker script that never loads nor errors keeps destroy() pending.

If PDF.js rejects the document parameters (for example, an empty or invalid URL), getDocument() does not throw synchronously: it returns a loading task whose promise rejects with PDF.js’s error message. An invalid URL starts no worker, and the task’s destroy() resolves immediately. For other synchronous PDF.js failures, the worker is destroyed immediately; await destroy() until its startup has settled and its thread has stopped. Repeated destroy() calls are safe. Leaving this failed task’s promise unread does not produce an unhandled rejection; awaiting it still rejects normally.

API

ExportWhat it is
loadPdfRuntime()Promise<PdfRuntime>; imports the legacy build once, wires the worker
PdfRuntime.getDocument(p)starts a load; forwards p with isEvalSupported: false added
PdfGetDocumentParamsurl, disableAutoFetch, disableStream, disableRange
PdfLoadingTaskpromise (the document), destroy() (network + worker)
PdfDocumentnumPages, getPage(n)
PdfPagegetViewport({scale}), render(params), cleanup()
PdfRenderParamscanvasContext, viewport, optional transform (device-pixel-ratio)
PdfRenderTaskpromise, cancel()
__setPdfRuntimeForTest(r)for the application’s tests: inject a runtime or a promise of one, or reset the memo with null

Security

pdfjs-dist 3.11.174 is affected by CVE-2024-4367 (GHSA-wgrm-67xf-hhpq): with isEvalSupported at its default true, a crafted font in a PDF runs JavaScript in the page’s origin. The fix (4.2.67) is out of reach of the pin, so this package applies the advisory’s workaround itself: getDocument always passes isEvalSupported: false, after the caller’s options. Glyph outlines are then interpreted instead of compiled: slower, same output.

A Content-Security-Policy without 'unsafe-eval' is a useful second layer. Expect npm audit in an application to keep reporting this advisory, and advisories against tar, pulled in by pdfjs-dist’s optional canvas dependency: tar only runs at install time (canvas builds a Node.js renderer) and never reaches the browser bundle.

Development

npm run check            # tsc --noEmit, build dist/, vitest run

Releases are published to npm from a git tag. To try an unreleased change in an application, link this checkout there (npm link) rather than bumping the version. The application imports dist/, so run npm run build here after each change.

Layout

PathHolds
src/index.tsthe whole boundary; built by tsc into dist/
test/compat.test.tsthe pin + a syntax scan of the installed bundles
test/runtime.test.tsthe real loader (import mocked) and the test seam
test/dist.test.tsdist/index.js keeps the import and the worker URL as is
test/teardown-ownership.test-d.tsrule 5, as a compile error

About

A shared PDF.js 3.11.174 legacy-runtime compatibility boundary for old Android WebViews

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages