Skip to content

Commit 573aedc

Browse files
fix: stub DOMMatrix before custom PDF.js resolver import (closes #48)
1 parent 63b2f5f commit 573aedc

File tree

3 files changed

+21
-4
lines changed

3 files changed

+21
-4
lines changed

src/_internal/canvas.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,15 +104,15 @@ export async function resolveCanvasModule(canvasImport: () => Promise<typeof imp
104104
* Node.js environments that do not support these constructors natively.
105105
*
106106
* @remarks
107-
* If a constructor is already defined in the global scope,
108-
* it will not be overridden.
107+
* `DOMMatrix` is always set because {@link stubBrowserGlobals} may have
108+
* installed a minimal stub to allow PDF.js to import – the real
109+
* `@napi-rs/canvas` implementation must take precedence for rendering.
109110
*/
110111
export function injectCanvasConstructors() {
111112
if (!resolvedCanvasModule)
112113
return
113114

114-
if (typeof globalThis.DOMMatrix === 'undefined')
115-
globalThis.DOMMatrix = resolvedCanvasModule.DOMMatrix as unknown as typeof DOMMatrix
115+
globalThis.DOMMatrix = resolvedCanvasModule.DOMMatrix as unknown as typeof DOMMatrix
116116

117117
if (typeof globalThis.ImageData === 'undefined')
118118
globalThis.ImageData = resolvedCanvasModule.ImageData as unknown as typeof ImageData

src/_internal/env.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* Stubs browser globals that PDF.js expects at the module level
3+
* in non-browser environments.
4+
*
5+
* @remarks
6+
* Must be called before importing any PDF.js module, since PDF.js
7+
* accesses these globals at parse time (top-level constants).
8+
*/
9+
export function stubBrowserGlobals(): void {
10+
if (typeof globalThis.DOMMatrix === 'undefined') {
11+
// @ts-expect-error: Minimal stub
12+
globalThis.DOMMatrix = class DOMMatrix {}
13+
}
14+
}

src/utils.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { DocumentInitParameters, PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api'
22
import type * as PDFJS from 'pdfjs-dist/types/src/pdf'
3+
import { stubBrowserGlobals } from './_internal/env'
34

45
let resolvedModule: typeof PDFJS | undefined
56

@@ -46,6 +47,8 @@ export async function resolvePDFJSImport(
4647
return
4748
}
4849

50+
stubBrowserGlobals()
51+
4952
if (pdfjsResolver) {
5053
try {
5154
resolvedModule = await interopDefault(pdfjsResolver())

0 commit comments

Comments
 (0)