Avoid bundling DOM-related code in the built pdf.worker.mjs file

Currently the `isCanvasFilterSupported`/`isAlphaColorInputSupported` getters, on the `FeatureTest` class, contains code that cannot run in the worker-thread since it relies on the DOM being available.
To avoid that a new DEFINE is added, in `gulpfile.mjs`, to allow skipping this sort of dead code in the built `pdf.worker.mjs` file.
This commit is contained in:
Jonas Jenwald 2026-05-14 12:21:36 +02:00
parent bf9ae7622f
commit 204f9203bd
2 changed files with 24 additions and 15 deletions

View File

@ -113,6 +113,7 @@ const BABEL_PRESET_ENV_OPTS = Object.freeze({
const DEFINES = Object.freeze({
SKIP_BABEL: true,
WORKER_THREAD: false,
TESTING: undefined,
COVERAGE: undefined,
// The main build targets:
@ -536,8 +537,12 @@ function createSandboxBundle(defines, extraOptions = undefined) {
}
function createWorkerBundle(defines) {
const workerFileConfig = createWebpackConfig(defines, {
filename: defines.MINIFIED ? "pdf.worker.min.mjs" : "pdf.worker.mjs",
const workerDefines = {
...defines,
WORKER_THREAD: true,
};
const workerFileConfig = createWebpackConfig(workerDefines, {
filename: workerDefines.MINIFIED ? "pdf.worker.min.mjs" : "pdf.worker.mjs",
library: {
type: "module",
},

View File

@ -661,7 +661,10 @@ class FeatureTest {
let ctx;
if (this.isOffscreenCanvasSupported) {
ctx = new OffscreenCanvas(1, 1).getContext("2d");
} else if (typeof document !== "undefined") {
} else if (
(typeof PDFJSDev === "undefined" || !PDFJSDev.test("WORKER_THREAD")) &&
typeof document !== "undefined"
) {
ctx = document.createElement("canvas").getContext("2d");
}
// Spec-compliant Canvas2D defaults `ctx.filter` to "none". On
@ -673,21 +676,22 @@ class FeatureTest {
}
static get isAlphaColorInputSupported() {
if (
(typeof PDFJSDev !== "undefined" && PDFJSDev.test("WORKER_THREAD")) ||
typeof document === "undefined"
) {
return shadow(this, "isAlphaColorInputSupported", false);
}
const input = document.createElement("input");
input.type = "color";
input.setAttribute("alpha", "");
input.value = "#ff000080";
// If alpha is supported the color picker retains the alpha channel, so
// the value won't be a plain opaque color (7-char #rrggbb).
return shadow(
this,
"isAlphaColorInputSupported",
(() => {
if (typeof document === "undefined") {
return false;
}
const input = document.createElement("input");
input.type = "color";
input.setAttribute("alpha", "");
input.value = "#ff000080";
// If alpha is supported the color picker retains the alpha channel, so
// the value won't be a plain opaque color (7-char #rrggbb).
return input.value !== "#ff0000";
})()
input.value !== "#ff0000"
);
}
}