From 50681d71c8f629c5785590fd853c1a74a1ce5e2d Mon Sep 17 00:00:00 2001
From: Jonas Jenwald <jonas.jenwald@gmail.com>
Date: Wed, 10 Mar 2021 23:13:55 +0100
Subject: [PATCH] Ensure that `getDocument` handles Node.js `Buffer`s more
 gracefully (issue 13075)

While the JSDocs have never advertised `getDocument` as supporting Node.js `Buffer`s, that apparently doesn't stop users from passing such data structures to `getDocument`.
In theory the existing `instanceof Uint8Array` check ought to have caught Node.js `Buffer`s, however for reasons that I don't even pretend to understand that check actually passes. Hence this patch which, *only* in Node.js environments, will special-case `Buffer`s to hopefully provide a slightly better out-of-the-box behaviour in Node.js environments[1].

---
[1] Although I'm not sure that we necessarily want to advertise this in the JSDocs, given the specialized use-case.
---
 src/display/api.js | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/src/display/api.js b/src/display/api.js
index 2aa097521..690193ade 100644
--- a/src/display/api.js
+++ b/src/display/api.js
@@ -243,10 +243,21 @@ function getDocument(src) {
     } else if (key === "worker") {
       worker = source[key];
       continue;
-    } else if (key === "data" && !(source[key] instanceof Uint8Array)) {
+    } else if (key === "data") {
       // Converting string or array-like data to Uint8Array.
       const pdfBytes = source[key];
-      if (typeof pdfBytes === "string") {
+      if (
+        typeof PDFJSDev !== "undefined" &&
+        PDFJSDev.test("GENERIC") &&
+        isNodeJS &&
+        typeof Buffer !== "undefined" && // eslint-disable-line no-undef
+        pdfBytes instanceof Buffer // eslint-disable-line no-undef
+      ) {
+        params[key] = new Uint8Array(pdfBytes);
+      } else if (pdfBytes instanceof Uint8Array) {
+        // Use the data as-is when it's already a Uint8Array.
+        params[key] = pdfBytes;
+      } else if (typeof pdfBytes === "string") {
         params[key] = stringToBytes(pdfBytes);
       } else if (
         typeof pdfBytes === "object" &&
@@ -259,8 +270,7 @@ function getDocument(src) {
       } else {
         throw new Error(
           "Invalid PDF binary data: either typed array, " +
-            "string or array-like object is expected in the " +
-            "data property."
+            "string, or array-like object is expected in the data property."
         );
       }
       continue;